@brickkit/cli 0.16.0-beta.1 → 0.16.0-beta.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +35 -8
- package/dashboard-dist/{api-reference-C2_JX174.js → api-reference-ZQs4Z4Yd.js} +71 -71
- package/dashboard-dist/app.css +1 -1
- package/dashboard-dist/app.js +12 -12
- package/dashboard-dist/{client-DsITZplk.js → client-CFM1S4Xv.js} +1 -1
- package/dashboard-dist/{core-sW89OSz5.js → core-VNHGFYB7.js} +1 -1
- package/dashboard-dist/{docs-D3U7gUWq.js → docs-CM2krp6H.js} +2 -2
- package/dashboard-dist/kit.js +1 -1
- package/dashboard-dist/popover-CVY1eRNY.js +1 -0
- package/dashboard-dist/theme.css +48 -39
- package/dist/bin.js +3 -2
- package/dist/bin.js.map +1 -1
- package/dist/build.js +6 -1
- package/dist/build.js.map +1 -1
- package/dist/dashboard-host.js +2594 -889
- package/dist/dashboard-host.js.map +1 -1
- package/dist/dashboard-protocol.js +10 -6
- package/dist/dashboard-protocol.js.map +1 -1
- package/dist/dashboard.d.ts +3 -3
- package/dist/dev-inspector.js +111 -0
- package/dist/dev-inspector.js.map +1 -0
- package/dist/dev-worker.js +1 -102
- package/dist/dev-worker.js.map +1 -1
- package/dist/package.js +5 -0
- package/dist/package.js.map +1 -0
- package/dist/production-dashboard.js +27 -2
- package/dist/production-dashboard.js.map +1 -1
- package/dist/production-dashboard2.d.ts +5 -0
- package/dist/project.js +2 -3
- package/dist/project.js.map +1 -1
- package/dist/vite.js +2 -1
- package/dist/vite.js.map +1 -1
- package/inspector-dist/NOTICE +3 -1
- package/inspector-dist/client/assets/{app-Wfnqu2Ic.css → app-PJHZvcxl.css} +49 -40
- package/inspector-dist/client/assets/{manifest-cfc09adc.js → manifest-274ef876.js} +1 -1
- package/inspector-dist/client/assets/{root-CVescmwt.css → root-CPvk93Fe.css} +49 -40
- package/inspector-dist/server/assets/{app-w0nTXgJd.js → app-DdYuYhBk.js} +89 -17
- package/inspector-dist/server/assets/{functions-B9XwHSzK.js → functions-BebJWj30.js} +2 -2
- package/inspector-dist/server/assets/{serialization-DsMds3lJ.js → serialization-Cgu5b7aC.js} +1 -1
- package/inspector-dist/server/assets/{token-CvvD8Y5H.js → token-3-nUtxO2.js} +1 -1
- package/inspector-dist/server/assets/{token-CxjWFNNq.js → token-DH652a7D.js} +1 -1
- package/inspector-dist/server/assets/token-util-wQgchIHA.js +3 -0
- package/inspector-dist/server/assets/{ws-transport-CamzQ5O8.js → ws-transport-7nLI4Gq9.js} +1 -1
- package/inspector-dist/server/index.js +1 -1
- package/package.json +2 -2
- package/dashboard-dist/PopoverPopup-CiI2avT_.js +0 -1
- package/dashboard-dist/popover-Bb2Q3jiK.js +0 -1
- package/inspector-dist/server/assets/token-util-D9IsWeEs.js +0 -3
- /package/inspector-dist/client/assets/{root-CVhM1JOR.js → root-2KbsWt-J.js} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dashboard-host.js","names":[],"sources":["../src/dashboard-extension.ts","../src/dev-docs.ts","../src/dashboard-query.ts","../src/dev-dashboard-shell.ts","../src/dashboard-access.ts","../src/dev-dashboard.ts","../src/dev-history.ts","../src/dev-telemetry-store.ts","../src/dashboard-host.ts"],"sourcesContent":["import { existsSync, watch, type FSWatcher } from \"node:fs\";\nimport { mkdir, readdir, readFile, writeFile } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport { ConfigError } from \"./config\";\nimport {\n ASSETS,\n SHARED_MODULES,\n type ExtensionPart,\n} from \"./dashboard-protocol\";\n\n/*\n * The dashboard's extension: one module of the project's own, built with the\n * dashboard's React and UI kit left external (the page's import map hands it\n * the dashboard's copies), and its Tailwind classes compiled against the\n * dashboard's theme.css. Plus the theme, which needs no code at all.\n */\n\n/** Token values for the dashboard's light and dark themes, its radius and fonts. */\nexport interface DashboardTheme {\n /** Colour tokens in light mode, by name: `{ primary: \"oklch(0.55 0.2 260)\" }`. */\n light?: Record<string, string>;\n /** Colour tokens in dark mode. */\n dark?: Record<string, string>;\n /** The base corner radius, such as `\"0.5rem\"`. */\n radius?: string;\n /** CSS font stacks. The page must be able to load the font. */\n fonts?: { sans?: string; mono?: string };\n}\n\n/** What `dashboard` accepts wherever the dashboard starts or is built. */\nexport interface DashboardExtensionOptions {\n /**\n * A module whose default export is `defineDashboard({ ... })`, or the\n * `dashboard` folder `brick build` wrote it to.\n */\n extension?: string;\n theme?: DashboardTheme;\n}\n\n/** The colour tokens of `dashboard/theme.css`; a test keeps the two in step. */\nexport const THEME_TOKENS = [\n \"background\",\n \"foreground\",\n \"card\",\n \"card-foreground\",\n \"popover\",\n \"popover-foreground\",\n \"primary\",\n \"primary-foreground\",\n \"secondary\",\n \"secondary-foreground\",\n \"muted\",\n \"muted-foreground\",\n \"accent\",\n \"accent-foreground\",\n \"destructive\",\n \"destructive-foreground\",\n \"positive\",\n \"border\",\n \"input\",\n \"ring\",\n \"chart-1\",\n \"chart-2\",\n \"chart-3\",\n \"chart-4\",\n \"chart-5\",\n \"span-request\",\n \"span-action\",\n \"span-rpc\",\n \"span-sql\",\n \"span-event\",\n \"span-other\",\n] as const;\n\nconst THEME_KEYS = new Set([\"light\", \"dark\", \"radius\", \"fonts\"]);\nconst FONT_KEYS = new Set([\"sans\", \"mono\"]);\nconst TOKENS = new Set<string>(THEME_TOKENS);\n\n/** A value that cannot close the rule it sits in. */\nfunction cssValue(where: string, value: unknown): string {\n if (typeof value !== \"string\" || !value.trim() || /[;{}<>\\\\]/.test(value))\n throw new ConfigError(\n `Brick: dashboard.theme.${where} must be a CSS value without ; { } < > or \\\\.`,\n );\n return value.trim();\n}\n\n/**\n * The stylesheet for a theme, loaded after the dashboard's own; empty when the\n * theme sets nothing. Throws on a token name theme.css does not have.\n */\nexport function themeCss(theme: DashboardTheme | undefined): string {\n if (!theme) return \"\";\n for (const key of Object.keys(theme))\n if (!THEME_KEYS.has(key))\n throw new ConfigError(\n `Brick: dashboard.theme has no \"${key}\". It takes light, dark, radius and fonts.`,\n );\n const rules: string[] = [];\n const root: string[] = [];\n if (theme.radius !== undefined)\n root.push(`--radius: ${cssValue(\"radius\", theme.radius)};`);\n for (const [name, value] of Object.entries(theme.fonts ?? {})) {\n if (!FONT_KEYS.has(name))\n throw new ConfigError(\n `Brick: dashboard.theme.fonts has no \"${name}\". It takes sans and mono.`,\n );\n root.push(`--font-${name}: ${cssValue(`fonts.${name}`, value)};`);\n }\n if (root.length) rules.push(`:root {\\n ${root.join(\"\\n \")}\\n}`);\n // theme.css sets light on :root and dark on .dark, both on <html>; these\n // selectors win over both, and each applies only in its own mode.\n for (const [mode, selector] of [\n [\"light\", \":root:not(.dark)\"],\n [\"dark\", \":root.dark\"],\n ] as const) {\n const tokens = theme[mode];\n if (!tokens) continue;\n const lines = Object.entries(tokens).map(([name, value]) => {\n if (!TOKENS.has(name))\n throw new ConfigError(\n `Brick: dashboard.theme.${mode} has no token \"${name}\". Tokens: ${THEME_TOKENS.join(\", \")}.`,\n );\n return `--${name}: ${cssValue(`${mode}.${name}`, value)};`;\n });\n if (lines.length) rules.push(`${selector} {\\n ${lines.join(\"\\n \")}\\n}`);\n }\n return rules.length ? `${rules.join(\"\\n\")}\\n` : \"\";\n}\n\nconst SHARED = SHARED_MODULES.map((module) => module.specifier);\n\n/** Bundle a module of React components for the dashboard to import (an extension, or the docs' components), with its shared modules left to the page. */\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 // Report what went wrong, not only that something did.\n throw: false,\n });\n if (!result.success)\n throw new Error(result.logs.map((log) => log.message).join(\"\\n\"));\n // A CSS import adds a stylesheet output; the module is the entry point.\n const output =\n result.outputs.find((item) => item.kind === \"entry-point\") ??\n result.outputs[0]!;\n return output.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 dashboard module produced no output.\");\n}\n\n/** The built React app, next to `src/` in the repo and next to `dist/` when published. */\nexport function 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\nexport interface BuiltExtension {\n js: string;\n /** The extension's own Tailwind classes; empty when it uses none. */\n css: string;\n /** The `extension-N.js` files `js` lists, by name. */\n parts?: Record<string, string>;\n}\n\n/** The `warn` functions already told that tailwindcss is missing: once each, not once per rebuild. */\nconst warnedTailwind = new WeakSet<(message: string) => void>();\n\n/**\n * Tailwind for the classes in the extension's bundle, compiled against the\n * dashboard's theme.css so `bg-primary` and the rest match. Only utilities are\n * emitted: the dashboard's stylesheet already has the base styles and tokens.\n * Tailwind is an optional peer, found from the project first.\n */\nasync function extensionCss(\n entry: string,\n js: string,\n warn: (message: string) => void,\n): Promise<string> {\n let tailwind: string | undefined;\n let main: string | undefined;\n for (const from of [entry, fileURLToPath(import.meta.url)]) {\n try {\n const require = createRequire(from);\n tailwind = require.resolve(\"tailwindcss/package.json\");\n main = require.resolve(\"tailwindcss\");\n break;\n } catch {}\n }\n const assets = assetsDirectory();\n const themeFile = assets\n ? join(assets, \"theme.css\")\n : fileURLToPath(new URL(\"../dashboard/theme.css\", import.meta.url));\n if (!tailwind || !main) {\n if (!warnedTailwind.has(warn))\n warn(\n \"[Brick-TS] tailwindcss is not installed, so the dashboard extension's own Tailwind classes are not compiled. The UI kit is styled either way.\",\n );\n warnedTailwind.add(warn);\n return \"\";\n }\n const root = dirname(tailwind);\n const { compile } = (await import(\n pathToFileURL(main).href\n )) as typeof import(\"tailwindcss\");\n const compiler = await compile(\n `@layer theme, base, components, utilities;\n@import \"tailwindcss/theme.css\" theme(reference inline);\n@import \"tailwindcss/utilities.css\" layer(utilities);\n@reference \"brick/theme.css\";\n`,\n {\n base: root,\n async loadStylesheet(id) {\n const path =\n id === \"brick/theme.css\"\n ? themeFile\n : join(root, id.replace(/^tailwindcss\\//, \"\"));\n return {\n path,\n base: dirname(path),\n content: await readFile(path, \"utf8\"),\n };\n },\n },\n );\n // Every word in the bundle is a candidate; Tailwind ignores what is not a class.\n const candidates = new Set(js.split(/[\\s\"'`]+/).filter(Boolean));\n const css = compiler.build([...candidates]);\n return /\\{/.test(css) ? css : \"\";\n}\n\n/** Bundle the extension and its styles for the dashboard page. */\nexport async function buildDashboardExtension(\n entry: string,\n options: { warn?: (message: string) => void } = {},\n): Promise<BuiltExtension> {\n const js = await bundleComponents(entry);\n return {\n js,\n css: await extensionCss(\n entry,\n js,\n options.warn ?? ((message) => console.warn(message)),\n ),\n };\n}\n\n/**\n * Write the app's extension and its plugins' into `outdir`, where `brick start`\n * can serve them: the app's alone as it is, or with plugins each part apart\n * and `extension.js` loading them, as `brick dev` serves them. Returns false\n * when there is none to write. A plugin's that fails to build throws.\n */\nexport async function writeDashboardExtension(\n entry: string | undefined,\n plugins: readonly PluginDashboard[],\n outdir: string,\n): Promise<boolean> {\n const parts = [\n ...(entry ? [{ name: \"app\", path: entry, plugin: false }] : []),\n ...[...pluginDashboards(plugins)].map(([path, name]) => ({\n name,\n path,\n plugin: true,\n })),\n ];\n if (!parts.length) return false;\n const warn = (message: string) => console.warn(message);\n const built = await Promise.all(\n parts.map((part) =>\n buildDashboardExtension(part.path, { warn }).catch((error: unknown) => {\n if (!part.plugin) throw error;\n throw new Error(\n `Brick compiler: the dashboard extension of plugin ${part.name} failed to build: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }),\n ),\n );\n await writeBuiltFolder(\n outdir,\n layoutParts(\n parts.map((part, index) => ({ ...part, built: built[index] })),\n )!,\n );\n return true;\n}\n\n/** Whether `path` is a folder `brick build` wrote, which is served as it is. */\nconst isBuiltFolder = (path: string): boolean =>\n existsSync(join(path, ASSETS.extension));\n\n/** Write the extensions as `layoutParts` lays them out; `readBuiltFolder` reads them back. */\nasync function writeBuiltFolder(\n outdir: string,\n layout: BuiltExtension,\n): Promise<void> {\n await mkdir(outdir, { recursive: true });\n await writeFile(join(outdir, ASSETS.extension), layout.js);\n await writeFile(join(outdir, ASSETS.extensionCss), layout.css);\n for (const [name, js] of Object.entries(layout.parts ?? {}))\n await writeFile(join(outdir, name), js);\n}\n\nasync function readBuiltFolder(path: string): Promise<BuiltExtension> {\n const css = join(path, ASSETS.extensionCss);\n const parts: Record<string, string> = {};\n for (const name of await readdir(path))\n if (/^extension-\\d+\\.js$/.test(name))\n parts[name] = await readFile(join(path, name), \"utf8\");\n return {\n js: await readFile(join(path, ASSETS.extension), \"utf8\"),\n css: existsSync(css) ? await readFile(css, \"utf8\") : \"\",\n parts,\n };\n}\n\n/**\n * How the extensions are served, by `brick dev` and from a `brick build`\n * folder alike. The app's alone is served as it is. Otherwise each that built\n * is `extension-<index>.js`, `extension.js` lists them for the page to load\n * and merge, and their styles are served together. `version` is added to each\n * part's address, so a rebuilt one is fetched again.\n */\nfunction layoutParts(\n parts: readonly {\n name: string;\n plugin: boolean;\n built: BuiltExtension | undefined;\n }[],\n version = \"\",\n): BuiltExtension | undefined {\n if (parts.length === 1 && !parts[0]!.plugin) return parts[0]!.built;\n const built = parts.flatMap((part, index) =>\n part.built\n ? [{ ...part, built: part.built, file: `extension-${index}.js` }]\n : [],\n );\n if (!built.length) return undefined;\n return {\n js: extensionManifest(\n built.map((part) => ({\n name: part.name,\n src: `./${part.file}${version}`,\n plugin: part.plugin,\n })),\n ),\n css: built.map((part) => part.built.css).join(\"\"),\n parts: Object.fromEntries(built.map((part) => [part.file, part.built.js])),\n };\n}\n\n/**\n * The extension as the dashboard serves it. From source it is built here, and\n * rebuilt as its folder changes when watching; from a `brick build` folder it\n * is read as it is. A failed build keeps the error to show on the page.\n */\nexport class DashboardExtensionHost {\n readonly #path: string;\n readonly #warn: (message: string) => void;\n readonly #listeners = new Set<() => void>();\n #watcher: FSWatcher | undefined;\n #timer: ReturnType<typeof setTimeout> | undefined;\n #pending: Promise<void> = Promise.resolve();\n revision = 0;\n built: BuiltExtension | undefined;\n error: string | undefined;\n\n constructor(path: string, warn: (message: string) => void) {\n this.#path = resolve(path);\n this.#warn = warn;\n }\n\n load(): Promise<void> {\n this.#pending = this.#pending.then(async () => {\n const before = JSON.stringify([this.built, this.error]);\n try {\n if (isBuiltFolder(this.#path)) {\n this.built = await readBuiltFolder(this.#path);\n } else {\n if (!existsSync(this.#path))\n throw new Error(\n `Brick: the dashboard extension ${this.#path} does not exist.`,\n );\n this.built = await buildDashboardExtension(this.#path, {\n warn: this.#warn,\n });\n }\n this.error = undefined;\n } catch (error) {\n this.built = undefined;\n this.error = error instanceof Error ? error.message : String(error);\n this.#warn(`[Brick-TS] Dashboard extension: ${this.error}`);\n }\n // The folder may hold the app too; its changes leave the bundle as it was.\n if (JSON.stringify([this.built, this.error]) === before) return;\n this.revision++;\n for (const listener of this.#listeners) listener();\n });\n return this.#pending;\n }\n\n watch(): void {\n try {\n this.#watcher = watch(\n dirname(this.#path),\n { recursive: true },\n (_event, file) => {\n if (file && /(^|[\\\\/])(node_modules|\\.)/.test(file)) return;\n clearTimeout(this.#timer);\n this.#timer = setTimeout(() => void this.load(), 100);\n },\n );\n } catch {\n // A folder that cannot be watched still works; it needs a restart.\n }\n }\n\n onChange(listener: () => void): () => void {\n this.#listeners.add(listener);\n return () => {\n this.#listeners.delete(listener);\n };\n }\n\n close(): void {\n clearTimeout(this.#timer);\n this.#watcher?.close();\n this.#listeners.clear();\n }\n}\n\n/** A plugin's dashboard extension, as `app.definition.plugins` lists it. */\nexport interface PluginDashboard {\n name: string;\n dashboard?: string;\n}\n\n/** The plugins' extensions by path, each once, in install order. */\nfunction pluginDashboards(\n plugins: readonly PluginDashboard[],\n): Map<string, string> {\n const wanted = new Map<string, string>();\n for (const plugin of plugins)\n if (plugin.dashboard && !wanted.has(resolve(plugin.dashboard)))\n wanted.set(resolve(plugin.dashboard), plugin.name);\n return wanted;\n}\n\n/**\n * The module the page loads when several extensions take part: it lists them,\n * and the page imports each apart and merges them (`mergeExtensions` there).\n */\nexport function extensionManifest(parts: readonly ExtensionPart[]): string {\n return `export const parts = ${JSON.stringify(parts)};\\n`;\n}\n\n/**\n * The app's extension and those of its plugins, served as one. With only the\n * app's, it is served as it is; with plugins, each is built apart (a failed\n * build leaves the others) and `extension.js` loads them all.\n */\nexport class DashboardExtensions {\n readonly #warn: (message: string) => void;\n readonly #listeners = new Set<() => void>();\n /** The app's own first, when it has one, then its plugins'. */\n readonly #parts: {\n name: string;\n path: string;\n plugin: boolean;\n host: DashboardExtensionHost;\n }[] = [];\n revision = 0;\n\n constructor(path: string | undefined, warn: (message: string) => void) {\n this.#warn = warn;\n if (path) this.#add(\"app\", path, false);\n }\n\n #add(name: string, path: string, plugin: boolean) {\n const host = new DashboardExtensionHost(path, this.#warn);\n host.onChange(() => this.#changed());\n this.#parts.push({ name, path: resolve(path), plugin, host });\n return host;\n }\n\n get #own() {\n return this.#parts.find((part) => !part.plugin);\n }\n\n #changed() {\n this.revision++;\n for (const listener of this.#listeners) listener();\n }\n\n get active(): boolean {\n return this.#parts.length > 0;\n }\n\n get built(): BuiltExtension | undefined {\n return layoutParts(\n this.#parts.map((part) => ({\n name: part.name,\n plugin: part.plugin,\n built: part.host.built,\n })),\n `?v=${this.revision}`,\n );\n }\n\n get error(): string | undefined {\n const errors = this.#parts.flatMap((part) =>\n part.host.error\n ? [\n this.#parts.length === 1 && !part.plugin\n ? part.host.error\n : `${part.name}: ${part.host.error}`,\n ]\n : [],\n );\n return errors.length ? errors.join(\"\\n\") : undefined;\n }\n\n /** A file under `/assets/` this serves, or undefined. */\n asset(name: string): string | undefined {\n if (name === ASSETS.extension) return this.built?.js;\n if (name === ASSETS.extensionCss) return this.built?.css;\n // From the layout, or the `brick build` folder the app's names.\n return this.built?.parts?.[name];\n }\n\n /** Follow the app's plugins: build the extensions they ship, drop the rest. */\n async setPlugins(plugins: readonly PluginDashboard[]): Promise<void> {\n // A `brick build` folder already holds its plugins' extensions.\n const own = this.#own;\n if (own && isBuiltFolder(own.path)) return;\n const wanted = pluginDashboards(plugins);\n const current = this.#parts.filter((part) => part.plugin);\n if (\n current.length === wanted.size &&\n current.every((part) => wanted.get(part.path) === part.name)\n )\n return;\n for (const part of current) part.host.close();\n this.#parts.splice(own ? 1 : 0);\n const loads = [...wanted].map(([path, name]) =>\n this.#add(name, path, true).load(),\n );\n await Promise.all(loads);\n this.#changed();\n }\n\n load(): Promise<void> {\n return Promise.all(this.#parts.map((part) => part.host.load())).then(\n () => undefined,\n );\n }\n\n /** Rebuild the app's own as its folder changes; plugins' are packages. */\n watch(): void {\n this.#own?.host.watch();\n }\n\n onChange(listener: () => void): () => void {\n this.#listeners.add(listener);\n return () => {\n this.#listeners.delete(listener);\n };\n }\n\n close(): void {\n for (const part of this.#parts) part.host.close();\n this.#listeners.clear();\n }\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 { bundleComponents } from \"./dashboard-extension\";\nimport {\n decode,\n docsFileUrl,\n docsHref,\n isExternalHref,\n type DocsInfo,\n type DocsNode,\n type DocsPage,\n type DocsSearchHit,\n type DocsSnapshot,\n type DocsTree,\n} from \"./dashboard-protocol\";\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\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;\n/** What the docs are called when their folder does not name them. */\nconst DEFAULT_TITLE = \"Docs\";\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 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 (isExternalHref(href) || href.startsWith(\"#\")) 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 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 = DEFAULT_TITLE;\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 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 : DEFAULT_TITLE;\n this.revision++;\n for (const listener of this.#listeners) listener();\n }\n\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 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 = docsFileUrl(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 = docsFileUrl(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 anchor = hashAt >= 0 ? decode(href.slice(hashAt + 1)) : undefined;\n const target =\n (hashAt >= 0 ? href.slice(0, hashAt) : href).split(\"?\")[0] ?? \"\";\n const route = (slug: string) =>\n docsHref(slug ? slug.split(\"/\") : [], anchor);\n if (isExternalHref(href) || !target) 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/** 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) || DEFAULT_TITLE,\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 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 #publish: (docs: DocsSnapshot | null) => void;\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(\n publish: (docs: DocsSnapshot | null) => void,\n warn: (message: string) => void,\n ) {\n this.#publish = publish;\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.#publish(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.#publish(\n opened.status === \"missing\"\n ? { status: \"missing\", packages: opened.packages, message }\n : { status: \"error\", message },\n );\n return;\n }\n this.#docs = opened.docs;\n this.#stopListening = opened.docs.onChange(() =>\n this.#publish(opened.docs.snapshot()),\n );\n this.#publish(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 {\n SPAN,\n type FacetValue,\n type HistoryFacets,\n type HistorySummary,\n type HistoryTrace,\n type Outcome,\n type TraceSummary,\n type SpanEventRecord,\n type VolumeBucket,\n} from \"./dashboard-protocol\";\n\n/*\n * The request log's rules, as plain functions over rows: what a request's\n * outcome is, which rows a filter keeps, and the counts the log shows. The\n * page runs them over live requests; stored history runs the same rules in SQL\n * (dev-history.ts), and a test keeps the two in step.\n */\n\n/** A response status at or above this is a server error; below it and at or above `CLIENT_ERROR`, a client error. */\nexport const SERVER_ERROR = 500;\nexport const CLIENT_ERROR = 400;\n\nexport function outcomeOf(\n row: Pick<TraceSummary, \"status\" | \"httpStatus\">,\n): Outcome {\n const http = row.httpStatus ?? 0;\n if (row.status === \"error\" || http >= SERVER_ERROR) return \"server\";\n if (http >= CLIENT_ERROR) return \"client\";\n return \"ok\";\n}\n\nexport function endpointOf(\n trace: Pick<TraceSummary, \"method\" | \"route\" | \"name\">,\n): string {\n return trace.method && trace.route\n ? `${trace.method} ${trace.route}`\n : trace.name;\n}\n\n/** A live request as a log row; the same shape the history API returns. */\nexport function toRow(trace: TraceSummary): HistoryTrace {\n const { spans: _spans, ...row } = trace;\n return { ...row, endpoint: endpointOf(trace) };\n}\n\nexport const OUTCOMES: readonly Outcome[] = [\"ok\", \"client\", \"server\"];\n\n/** The filters of the request log, over a window, a page at a time. */\nexport interface HistoryQuery extends RowFilters {\n from: number;\n to: number;\n limit?: number;\n offset?: number;\n}\n\n/** A history query as the query string the history API takes. */\nexport function encodeHistoryQuery(query: HistoryQuery): URLSearchParams {\n const params = new URLSearchParams({\n from: String(query.from),\n to: String(query.to),\n });\n for (const endpoint of query.endpoints ?? [])\n params.append(\"endpoint\", endpoint);\n for (const method of query.methods ?? []) params.append(\"method\", method);\n for (const service of query.services ?? []) params.append(\"service\", service);\n for (const outcome of query.outcomes ?? []) params.append(\"outcome\", outcome);\n if (query.minMs !== undefined) params.set(\"minMs\", String(query.minMs));\n if (query.query) params.set(\"q\", query.query);\n if (query.sort && query.sort !== \"recent\") params.set(\"sort\", query.sort);\n if (query.limit !== undefined) params.set(\"limit\", String(query.limit));\n if (query.offset !== undefined) params.set(\"offset\", String(query.offset));\n return params;\n}\n\n/** The history query in a query string, parsed defensively: what `encodeHistoryQuery` wrote. */\nexport function decodeHistoryQuery(\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) ? Math.trunc(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 // A week back by default.\n from: integer(\"from\") ?? to - 7 * 86_400_000,\n endpoints: all(\"endpoint\"),\n methods: all(\"method\"),\n services: all(\"service\"),\n outcomes: all(\"outcome\")?.filter((value): value is Outcome =>\n OUTCOMES.includes(value as Outcome),\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/** A filter groups its values with OR; separate filters combine with AND. */\nexport interface RowFilters {\n endpoints?: string[];\n methods?: string[];\n services?: string[];\n outcomes?: Outcome[];\n /** Only requests at least this slow, in milliseconds. */\n minMs?: number;\n /** Matches the endpoint, path, span name, action or failure message. */\n query?: string;\n sort?: \"recent\" | \"slowest\";\n}\n\nexport type Facet = keyof HistoryFacets;\n\n/** The fields the search box looks in. */\nexport const SEARCHED: readonly (keyof HistoryTrace)[] = [\n \"endpoint\",\n \"path\",\n \"name\",\n \"action\",\n \"message\",\n];\n\n/** Whether `row` passes the filters, leaving out `skip` when counting its facet. */\nexport function matches(\n row: HistoryTrace,\n filters: RowFilters,\n skip?: Facet,\n): boolean {\n const anyOf = (facet: Facet, values: string[] | undefined, value?: string) =>\n skip === facet ||\n !values?.length ||\n (value !== undefined && values.includes(value));\n if (!anyOf(\"endpoint\", filters.endpoints, row.endpoint)) return false;\n if (!anyOf(\"method\", filters.methods, row.method)) return false;\n if (!anyOf(\"service\", filters.services, row.service)) return false;\n if (!anyOf(\"outcome\", filters.outcomes, outcomeOf(row))) return false;\n if (\n filters.minMs !== undefined &&\n filters.minMs > 0 &&\n (row.durationMs ?? 0) < filters.minMs\n )\n return false;\n const needle = filters.query?.trim().toLowerCase();\n if (needle)\n return SEARCHED.some((field) =>\n String(row[field] ?? \"\")\n .toLowerCase()\n .includes(needle),\n );\n return true;\n}\n\n/** Newest first, or slowest first and then newest. */\nexport function compareRows(\n sort: RowFilters[\"sort\"],\n): (a: HistoryTrace, b: HistoryTrace) => number {\n return sort === \"slowest\"\n ? (a, b) =>\n (b.durationMs ?? 0) - (a.durationMs ?? 0) || b.startMs - a.startMs\n : (a, b) => b.startMs - a.startMs;\n}\n\nexport function applyFilters(\n rows: HistoryTrace[],\n filters: RowFilters,\n): HistoryTrace[] {\n return rows\n .filter((row) => matches(row, filters))\n .sort(compareRows(filters.sort));\n}\n\n/** The most values a facet lists. */\nexport const MAX_FACET_VALUES = 30;\n\nconst FACET_VALUE: Record<Facet, (row: HistoryTrace) => string | undefined> = {\n outcome: outcomeOf,\n method: (row) => row.method,\n service: (row) => row.service,\n endpoint: (row) => row.endpoint,\n};\n\n/** Counts for each filter, as if that filter were not applied. */\nexport function computeFacets(\n rows: HistoryTrace[],\n filters: RowFilters,\n): HistoryFacets {\n const count = (facet: Facet): FacetValue[] => {\n const counts = new Map<string, number>();\n for (const row of rows) {\n if (!matches(row, filters, facet)) continue;\n const value = FACET_VALUE[facet](row);\n if (value !== undefined) counts.set(value, (counts.get(value) ?? 0) + 1);\n }\n return [...counts.entries()]\n .map(([value, total]) => ({ value, count: total }))\n .sort(\n (a, b) =>\n b.count - a.count ||\n (a.value < b.value ? -1 : a.value > b.value ? 1 : 0),\n )\n .slice(0, MAX_FACET_VALUES);\n };\n return {\n outcome: count(\"outcome\"),\n method: count(\"method\"),\n service: count(\"service\"),\n endpoint: count(\"endpoint\"),\n };\n}\n\n/** The width of each of `count` buckets across [from, to]: whole milliseconds, at least one. */\nexport const bucketSize = (from: number, to: number, count: number): number =>\n Math.max(Math.ceil((to - from) / count), 1);\n\n/** Count rows into `count` equal time buckets across [from, to], by outcome. */\nexport function bucketRows(\n rows: HistoryTrace[],\n from: number,\n to: number,\n count: number,\n): VolumeBucket[] {\n const size = bucketSize(from, to, count);\n const buckets: VolumeBucket[] = Array.from({ length: count }, (_, index) => ({\n start: from + index * size,\n ok: 0,\n client: 0,\n server: 0,\n }));\n for (const row of rows) {\n if (row.startMs < from || row.startMs > to) continue;\n const index = Math.floor((row.startMs - from) / size);\n buckets[Math.min(index, count - 1)]![outcomeOf(row)] += 1;\n }\n return buckets;\n}\n\n/** Linear-interpolated percentile of an ascending list; 0 for an empty list. */\nexport function 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 (\n sorted[lower]! + (sorted[upper]! - sorted[lower]!) * (position - lower)\n );\n}\n\n/** The numbers for the cards at the top of the log, for these requests. */\nexport function summarizeRows(rows: HistoryTrace[]): HistorySummary {\n let clientErrors = 0;\n let serverErrors = 0;\n const durations: number[] = [];\n for (const row of rows) {\n const outcome = outcomeOf(row);\n if (outcome === \"client\") clientErrors += 1;\n if (outcome === \"server\") serverErrors += 1;\n if (row.durationMs !== undefined) durations.push(row.durationMs);\n }\n durations.sort((a, b) => a - b);\n return {\n total: rows.length,\n clientErrors,\n serverErrors,\n medianMs: percentile(durations, 0.5),\n p95Ms: percentile(durations, 0.95),\n };\n}\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 [\n new Date(trace.startMs).toISOString(),\n trace.method,\n trace.route,\n trace.path,\n trace.httpStatus ?? trace.status,\n outcomeOf(trace),\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\n/** A string attribute, or undefined when it is missing or of another type. */\nexport function 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\n/** The attributes of the exception a span recorded, if it recorded one. */\nexport function findException(\n events: SpanEventRecord[],\n): Attributes | undefined {\n return events.find((event) => event.name === SPAN.exceptionEvent)?.attributes;\n}\n\n/** The span that ran the request's action, when it ran one. */\nexport function actionSpan<T extends { name: string }>(\n spans: readonly T[],\n): T | undefined {\n return spans.find((span) => span.name.startsWith(SPAN.actionPrefix));\n}\n","import {\n ASSETS,\n assetUrl,\n SHARED_MODULES,\n THEME_STORAGE_KEY,\n} from \"./dashboard-protocol\";\n\nconst IMPORT_MAP = JSON.stringify({\n imports: Object.fromEntries(\n SHARED_MODULES.map((module) => [module.specifier, assetUrl(module.file)]),\n ),\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 hands the project's own modules (its docs components and its\n * dashboard extension), bundled apart from the dashboard, the dashboard's copy\n * of React and its UI kit, so there is one of each on the page.\n *\n * `extension` describes the project's extension: `revision` changes with every\n * rebuild (the page reloads when it does), `js` and `css` say what it built.\n * `theme` is whether `/assets/brick-theme.css` has token values to apply.\n */\nexport function dashboardShell(\n options: {\n extension?: { revision: number; js: boolean; css: boolean };\n theme?: boolean;\n mode?: \"dev\" | \"production\";\n } = {},\n): string {\n const { extension, theme, mode } = options;\n const version = extension ? `?v=${extension.revision}` : \"\";\n return `<!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>${mode === \"production\" ? \"Brick\" : \"Brick dev\"}</title>\n<link rel=\"icon\" href=\"data:,\">\n<script>\n(function () {\n try {\n var theme = localStorage.getItem(${JSON.stringify(THEME_STORAGE_KEY)});\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=\"${assetUrl(ASSETS.appCss)}\">\n${extension?.css ? `<link rel=\"stylesheet\" href=\"${assetUrl(ASSETS.extensionCss)}${version}\">\\n` : \"\"}${theme ? `<link rel=\"stylesheet\" href=\"${assetUrl(ASSETS.theme)}\" data-brick-theme>\\n` : \"\"}${extension ? `<meta name=\"brick-extension\" data-revision=\"${extension.revision}\"${extension.js ? ` data-src=\"${assetUrl(ASSETS.extension)}${version}\"` : \"\"}>\\n` : \"\"}<script type=\"importmap\">\n${IMPORT_MAP}\n</script>\n</head>\n<body>\n<div id=\"root\"></div>\n<script type=\"module\" src=\"${assetUrl(ASSETS.app)}\"></script>\n</body>\n</html>\n`;\n}\n","import { createHash, timingSafeEqual } from \"node:crypto\";\nimport type { IncomingMessage } from \"node:http\";\nimport type { DashboardAuth, DashboardIdentity } from \"@brickkit/core\";\n\nexport type Access =\n | { allowed: true; identity: DashboardIdentity }\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. */\nconst AUTHORIZE_TIMEOUT_MS = 5000;\n\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 protocol the client used: https when a proxy in front terminated TLS and says so. */\nexport function requestProtocol(request: IncomingMessage): \"http\" | \"https\" {\n const forwarded = request.headers[\"x-forwarded-proto\"];\n return (Array.isArray(forwarded) ? forwarded[0] : forwarded)\n ?.split(\",\")[0]\n ?.trim() === \"https\"\n ? \"https\"\n : \"http\";\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 protocol = requestProtocol(request);\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 isIdentity = (value: unknown): value is Required<DashboardIdentity> =>\n typeof value === \"object\" &&\n value !== null &&\n !(value instanceof Response) &&\n typeof (value as DashboardIdentity).user?.id === \"string\";\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` or an identity (`{ user }`). 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, identity: {} };\n if (!auth.authorize) return refusal(401, \"Unauthorized\", prompt);\n\n let decision: boolean | Response | DashboardIdentity;\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, identity: {} };\n if (isIdentity(decision))\n return {\n allowed: true,\n identity: {\n user: {\n id: decision.user.id,\n ...(typeof decision.user.name === \"string\"\n ? { name: decision.user.name }\n : {}),\n },\n },\n };\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 { 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 { Readable } from \"node:stream\";\nimport { pipeline } from \"node:stream/promises\";\nimport { ConfigError } from \"./config\";\nimport type { DevDocs } from \"./dev-docs\";\nimport type { DevHistory } from \"./dev-history\";\nimport { decodeHistoryQuery, type HistoryQuery } from \"./dashboard-query\";\nimport type { DevTelemetryStore } from \"./dev-telemetry-store\";\nimport { dashboardShell } from \"./dev-dashboard-shell\";\nimport {\n DASHBOARD_IDENTITY_HEADER,\n signDashboardIdentity,\n type DashboardAuth,\n type DashboardIdentity,\n} from \"@brickkit/core\";\nimport {\n createAccess,\n isLoopbackHost,\n requestProtocol,\n} from \"./dashboard-access\";\nimport {\n ASSETS,\n CSRF_HEADER,\n CSRF_VALUE,\n DOCS_PATHS,\n INSPECTOR_TOKEN_HEADER,\n matchRoute,\n ROUTES,\n type DashboardEvents,\n type DashboardSnapshot,\n type HistoryResponses,\n type IngestPayload,\n type RouteName,\n} from \"./dashboard-protocol\";\nimport {\n assetsDirectory,\n DashboardExtensions,\n type PluginDashboard,\n themeCss,\n type DashboardExtensionOptions,\n} from \"./dashboard-extension\";\n\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\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 the routes marked `production`, 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 * The project's extension and theme. In dev mode the extension is rebuilt as\n * its folder changes, and the page reloads; production serves it as built.\n */\n dashboard?: DashboardExtensionOptions;\n /**\n * The app's plugins, whose extensions are built and served before the\n * dashboard listens. Dev learns them later, with `setPluginExtensions`.\n */\n plugins?: readonly PluginDashboard[];\n /** Where `/app/*` goes; the app the store's API documents name otherwise. */\n appUrl?: string;\n /** How the host's user picks another port, added when the port is taken. */\n portHint?: string;\n}\n\nexport interface DevDashboard {\n readonly port: number;\n /** Build and serve the dashboard extensions the app's plugins ship. */\n setPluginExtensions(plugins: readonly PluginDashboard[]): Promise<void>;\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 ConfigError(\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 let theme: string;\n try {\n theme = themeCss(options.dashboard?.theme);\n } catch (error) {\n return Promise.reject(error);\n }\n // In dev, plugins' extensions can join later (`setPluginExtensions`).\n const extension =\n options.dashboard?.extension ||\n !production ||\n options.plugins?.some((plugin) => plugin.dashboard)\n ? new DashboardExtensions(options.dashboard?.extension, (message) =>\n console.warn(message),\n )\n : undefined;\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 route = matchRoute(request.method, url.pathname);\n if (route === \"health\") {\n await health(response);\n return;\n }\n let identity: DashboardIdentity = {};\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 identity = decision.identity;\n }\n if (!route || (production && !servedInProduction(route))) {\n send(response, 404, \"Not found\");\n return;\n }\n if (\n \"csrf\" in ROUTES[route] &&\n request.headers[CSRF_HEADER] !== CSRF_VALUE\n ) {\n send(response, 403, \"Forbidden\");\n return;\n }\n await handlers[route](request, response, url, identity);\n }\n\n function servedInProduction(route: RouteName): boolean {\n const served: boolean | \"extension\" = ROUTES[route].production;\n return served === \"extension\" ? Boolean(extension?.active) : served;\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 type Handler = (\n request: IncomingMessage,\n response: ServerResponse,\n url: URL,\n identity: DashboardIdentity,\n ) => void | Promise<void>;\n\n const handlers: Record<Exclude<RouteName, \"health\">, Handler> = {\n shell: (_request, response) =>\n send(\n response,\n 200,\n dashboardShell({\n extension: extension?.active\n ? {\n revision: extension.revision,\n js: Boolean(extension.built),\n css: Boolean(extension.built?.css),\n }\n : undefined,\n theme: theme !== \"\",\n mode: production ? \"production\" : \"dev\",\n }),\n {\n \"content-type\": \"text/html; charset=utf-8\",\n \"cache-control\": \"no-store\",\n },\n ),\n assets(_request, response, url) {\n const name = url.pathname.slice(ROUTES.assets.path.length + 1);\n // The project's own files, kept in memory beside the dashboard's.\n const own = name === ASSETS.theme ? theme : extension?.asset(name);\n if (own !== undefined)\n send(response, 200, own, {\n \"content-type\": assetType(name),\n \"cache-control\": \"no-store\",\n });\n else serveAsset(response, name);\n },\n app,\n state: (_request, response) => json(response, snapshot()),\n events: eventStream,\n history(_request, response, url) {\n if (options.history)\n history(options.history, url.pathname, url.searchParams, response);\n else send(response, 404, \"Not found\");\n },\n docs: (_request, response, url) =>\n docsRoute(response, url.pathname, url.searchParams),\n openapi: (_request, response) =>\n json(response, options.store.apiDocuments()),\n proxy,\n workflows(request, response, url) {\n // Only the dashboard may frame it: framed by another site, a click could\n // land on Cancel or Replay. The rest of the dashboard may be embedded.\n frameOnlyHere(response);\n return inspector(request, response, url);\n },\n schedules: (request, response, url) => inspector(request, response, url),\n ingest,\n restart(request, response) {\n if (!options.restart) {\n send(response, 404, \"Not found\");\n return;\n }\n options.restart();\n send(response, 202, \"\");\n },\n };\n\n function snapshot(): DashboardSnapshot {\n return {\n ...options.store.snapshot(),\n canRestart: Boolean(options.restart),\n historyDays: options.history?.days ?? 0,\n mode: production ? \"production\" : \"dev\",\n extension: extension?.active\n ? { revision: extension.revision, error: extension.error }\n : null,\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 async function ingest(\n request: IncomingMessage,\n response: ServerResponse,\n ): Promise<void> {\n const body = await readBytes(request, MAX_INGEST_BYTES);\n if (!body) {\n tooLarge(response);\n return;\n }\n let payload: IngestPayload | null;\n try {\n payload = JSON.parse(Buffer.from(body).toString(\"utf8\")) as IngestPayload;\n } catch {\n payload = null;\n }\n if (payload === null || typeof payload !== \"object\") {\n send(response, 400, \"Bad request\");\n return;\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 }\n\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 try {\n if (pathname === DOCS_PATHS.info) return json(response, docs.info());\n if (pathname === DOCS_PATHS.search)\n return json(response, await docs.search(params.get(\"q\") ?? \"\"));\n if (pathname === DOCS_PATHS.components) {\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 = DOCS_PATHS.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\n ? json(response, page)\n : send(response, 404, \"No such page.\");\n }\n const filePrefix = `${DOCS_PATHS.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 * Pass a request to the workflow inspector, which the app serves on a port of\n * its own, and stream its answer back (it follows a run's output as it\n * grows). Anyone who can open the dashboard may look, but a change must come\n * from the dashboard's own page: the inspector can cancel runs and resume\n * hooks, and a page on another site could otherwise post to it.\n */\n async function inspector(\n request: IncomingMessage,\n response: ServerResponse,\n url: URL,\n ): Promise<void> {\n const target = options.store.inspectorTarget();\n if (!target) {\n send(\n response,\n 503,\n \"The workflow inspector and schedules are not being served. The app may be restarting, or it may have neither workflows nor schedules.\",\n { \"content-type\": \"text/plain; charset=utf-8\" },\n );\n return;\n }\n if (!isBodyless(request) && !fromOwnPage(request)) {\n send(response, 403, \"Forbidden\");\n return;\n }\n await forward(\n request,\n response,\n `http://127.0.0.1:${target.port}${url.pathname}${url.search}`,\n (headers) => headers.set(INSPECTOR_TOKEN_HEADER, target.token),\n \"Could not reach the workflow inspector.\",\n );\n }\n\n /**\n * Pass `/app/*` to the app, so the extension's pages read it from the\n * dashboard's own origin. Only the dashboard's page may use it, as with the\n * API proxy. A credential for the dashboard itself is not passed on; who the\n * dashboard let in is, signed, for `ctx.dashboard` and `dashboardUser()`.\n */\n async function app(\n request: IncomingMessage,\n response: ServerResponse,\n url: URL,\n identity: DashboardIdentity,\n ): Promise<void> {\n if (!fromOwnPage(request)) {\n send(response, 403, \"Forbidden\");\n return;\n }\n const appUrl = options.appUrl ?? options.store.apiSnapshot()?.appUrl;\n if (!appUrl) {\n send(response, 503, \"The app is not running yet.\");\n return;\n }\n // Framed by an extension's iframe page, and by nothing else.\n frameOnlyHere(response);\n await forward(\n request,\n response,\n `${new URL(appUrl).origin}${url.pathname.slice(ROUTES.app.path.length) || \"/\"}${url.search}`,\n (headers) => {\n if (access) headers.delete(\"authorization\");\n headers.set(DASHBOARD_IDENTITY_HEADER, signDashboardIdentity(identity));\n },\n \"Could not reach the app.\",\n );\n }\n\n /**\n * Send the request on to `target` and stream its answer back. `body`: the\n * request's body when the caller already read it; else it is streamed.\n */\n async function forward(\n request: IncomingMessage,\n response: ServerResponse,\n target: string,\n adjust: (headers: Headers) => void,\n unreachable: string,\n body?: Uint8Array,\n ): Promise<void> {\n const headers = forwardedHeaders(request);\n adjust(headers);\n const abort = new AbortController();\n response.on(\"close\", () => abort.abort());\n try {\n const upstream = await fetch(target, {\n method: request.method,\n headers,\n redirect: \"manual\",\n signal: abort.signal,\n ...(isBodyless(request)\n ? {}\n : body\n ? { body: body as BodyInit }\n : {\n body: Readable.toWeb(request) as unknown as BodyInit,\n duplex: \"half\",\n }),\n } as RequestInit);\n response.writeHead(upstream.status, returnedHeaders(upstream));\n if (!upstream.body || request.method === \"HEAD\") {\n response.end();\n return;\n }\n await pipeline(Readable.fromWeb(upstream.body as never), response);\n } catch {\n if (response.headersSent) response.destroy();\n else send(response, 502, unreachable);\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 if (!fromOwnPage(request)) {\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 tooLarge(response);\n return;\n }\n const cookie = url.searchParams.get(\"cookie\");\n await forward(\n request,\n response,\n target.href,\n (headers) => {\n if (cookie) headers.set(\"cookie\", cookie);\n },\n \"Could not reach the app.\",\n body,\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 const emit = <K extends keyof DashboardEvents>(\n name: K,\n data: DashboardEvents[K],\n ) => write(`event: ${name}\\ndata: ${JSON.stringify(data)}\\n\\n`);\n emit(\"snapshot\", snapshot());\n const unsubscribe = options.store.subscribe((event) =>\n emit(event.type, event),\n );\n const unwatch = extension?.onChange(() =>\n emit(\"extension\", snapshot().extension),\n );\n const keepalive = setInterval(() => write(\": keepalive\\n\\n\"), KEEPALIVE_MS);\n request.on(\"close\", () => {\n clearInterval(keepalive);\n unsubscribe();\n unwatch?.();\n });\n }\n\n // The first build finishes before the page can be asked for; a failed one\n // is shown on the page, and does not stop the dashboard.\n const ready = extension\n ? Promise.all([\n extension.load(),\n options.plugins && extension.setPlugins(options.plugins),\n ])\n : Promise.resolve();\n return ready.then(() => listen());\n\n function listen(): Promise<DevDashboard> {\n return new Promise((resolve, reject) => {\n server.once(\"error\", (error) => {\n extension?.close();\n reject(\n new Error(\n `Brick: dashboard port ${options.port} is unavailable.${options.portHint ? ` ${options.portHint}` : \"\"}`,\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 if (!production) extension?.watch();\n resolve({\n port,\n setPluginExtensions: (plugins) =>\n extension?.setPlugins(plugins) ?? Promise.resolve(),\n stop() {\n extension?.close();\n server.close();\n server.closeAllConnections();\n },\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 // Stop buffering; tooLarge() answers and closes the connection.\n request.removeAllListeners(\"data\");\n request.resume();\n resolve(undefined);\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 queries: {\n [K in keyof HistoryResponses]: (query: HistoryQuery) => HistoryResponses[K];\n } = {\n summary: (query) => store.summary(query),\n traces: (query) => store.traces(query),\n facets: (query) => store.facets(query),\n volume: (query) => store.volume(query),\n };\n try {\n const endpoint = pathname.slice(ROUTES.history.path.length + 1);\n if (endpoint === \"\") return json(response, store.info());\n if (endpoint === \"export\") {\n return send(response, 200, store.exportCsv(decodeHistoryQuery(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 if (Object.hasOwn(queries, endpoint))\n return json(\n response,\n queries[endpoint as keyof typeof queries](decodeHistoryQuery(params)),\n );\n const prefix = \"traces/\";\n if (endpoint.startsWith(prefix)) {\n const trace = store.trace(\n decodeURIComponent(endpoint.slice(prefix.length)),\n );\n if (trace) return json(response, trace);\n }\n send(response, 404, \"Not found\");\n } catch (error) {\n // A malformed `%` in the trace id is the caller's mistake.\n if (error instanceof URIError) return send(response, 400, error.message);\n console.error(\"[Brick-TS] A dashboard history query failed:\", error);\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\nconst assetType = (name: string): string =>\n ASSET_TYPES[extname(name)] ?? \"application/octet-stream\";\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\": assetType(name),\n \"cache-control\": \"no-store\",\n }),\n () => send(response, 404, \"Not found\"),\n );\n}\n\nfunction tooLarge(response: ServerResponse): void {\n // Closing after the 413 stops the rest of the upload being read.\n send(response, 413, \"Payload too large\", {\n \"content-type\": \"text/plain; charset=utf-8\",\n connection: \"close\",\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\nfunction json(response: ServerResponse, body: unknown): void {\n send(response, 200, JSON.stringify(body), {\n \"content-type\": \"application/json\",\n \"cache-control\": \"no-store\",\n });\n}\n\nconst isBodyless = (request: IncomingMessage) =>\n request.method === \"GET\" || request.method === \"HEAD\";\n\n/**\n * Whether a request comes from the dashboard's own page, as far as the browser\n * says: the same site, and the same origin as the address it was sent to.\n * Behind a proxy that terminates TLS that address is https.\n */\nfunction fromOwnPage(request: IncomingMessage): boolean {\n const site = request.headers[\"sec-fetch-site\"];\n const origin = request.headers.origin;\n return (\n (site === undefined || site === \"same-origin\") &&\n (origin === undefined ||\n origin === `${requestProtocol(request)}://${request.headers.host}`)\n );\n}\n\nfunction frameOnlyHere(response: ServerResponse): void {\n response.setHeader(\"content-security-policy\", \"frame-ancestors 'self'\");\n response.setHeader(\"x-frame-options\", \"SAMEORIGIN\");\n}\n\n/** The request's headers to send on, without those of this hop or this page. */\nfunction forwardedHeaders(request: IncomingMessage): Headers {\n const headers = new Headers();\n for (const [name, value] of Object.entries(request.headers)) {\n if (\n value === undefined ||\n NOT_FORWARDED.has(name) ||\n name === DASHBOARD_IDENTITY_HEADER\n )\n continue;\n if (name.startsWith(\"sec-\")) continue;\n headers.set(name, Array.isArray(value) ? value.join(\", \") : value);\n }\n return headers;\n}\n\nfunction returnedHeaders(upstream: Response): Record<string, string> {\n const returned: Record<string, string> = {};\n upstream.headers.forEach((value, name) => {\n if (!NOT_RETURNED.has(name)) returned[name] = value;\n });\n return returned;\n}\n","import { existsSync, mkdirSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport {\n HISTORY_PAGE_SIZE,\n type FacetValue,\n type HistoryFacets,\n type HistoryInfo,\n type HistorySummary,\n type HistoryTrace,\n type Outcome,\n type SpanOutcome,\n type TraceSummary,\n type VolumeBucket,\n} from \"./dashboard-protocol\";\nimport {\n bucketSize,\n CLIENT_ERROR,\n endpointOf,\n MAX_FACET_VALUES,\n percentile,\n SEARCHED,\n SERVER_ERROR,\n tracesToCsv,\n type Facet,\n type HistoryQuery,\n} from \"./dashboard-query\";\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 MAX_LIMIT = 500;\nconst MAX_EXPORT_ROWS = 100_000;\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, options.warn);\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\n/** Each row's outcome, by the rules of `outcomeOf`. */\nconst OUTCOME_CASE = `CASE\n WHEN status = 'error' OR http_status >= ${SERVER_ERROR} THEN 'server'\n WHEN http_status >= ${CLIENT_ERROR} THEN 'client'\n ELSE 'ok' END`;\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\") anyOf(OUTCOME_CASE, query.outcomes);\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 `(${SEARCHED.map((column) => `${column} LIKE ? ESCAPE '\\\\'`).join(\" OR \")})`,\n );\n params.push(...SEARCHED.map(() => pattern));\n }\n return { sql: clauses.join(\" AND \"), params };\n}\n\nconst orderSql = (sort: HistoryQuery[\"sort\"]) =>\n sort === \"slowest\" ? \"duration_ms DESC, start_ms DESC\" : \"start_ms DESC\";\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 readonly #warn?: (message: string) => void;\n /** Failure kinds already reported: one warning each, not one per batch. */\n readonly #warned = new Set<string>();\n\n constructor(\n database: Database,\n days: number,\n warn?: (message: string) => void,\n ) {\n this.#database = database;\n this.days = days;\n this.#warn = warn;\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 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 endpointOf(trace),\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 (error) {\n // A failed write loses a batch of history; it must not break the app.\n this.#warnOnce(\"save requests to\", error);\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 (error) {\n // Pruning is housekeeping; try again next time.\n this.#warnOnce(\"prune\", error);\n }\n }\n\n #warnOnce(action: string, error: unknown): void {\n if (this.#warned.has(action)) return;\n this.#warned.add(action);\n const reason = error instanceof Error ? error.message : String(error);\n this.#warn?.(\n `[Brick-TS] Could not ${action} the request history (${reason}).`,\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 ?? HISTORY_PAGE_SIZE, 1),\n MAX_LIMIT,\n );\n const offset = Math.max(query.offset ?? 0, 0);\n const rows = this.#database\n .prepare(\n `SELECT ${LIST_COLUMNS}\n FROM traces WHERE ${sql} ORDER BY ${orderSql(query.sort)} 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 = bucketSize(query.from, query.to, buckets);\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 rows = this.#database\n .prepare(\n `SELECT ${LIST_COLUMNS}\n FROM traces WHERE ${sql} ORDER BY ${orderSql(query.sort)} LIMIT ?`,\n )\n .all(...params, MAX_EXPORT_ROWS);\n return tracesToCsv(rows.map(toHistoryTrace));\n }\n\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","import type { Attributes } from \"@opentelemetry/api\";\nimport type { ApiDocument, ArchitectureSchema } from \"@brickkit/core\";\nimport {\n ATTR,\n LIVE_LIMITS,\n type ApiSnapshot,\n type ArchitectureSnapshot,\n type DevTelemetryEvent,\n type DevTelemetrySnapshot,\n type DocsSnapshot,\n type FailureSummary,\n type ReloadSummary,\n type SerializedError,\n type SpanEndRecord,\n type SpanOutcome,\n type SpanStartRecord,\n type TelemetryRecord,\n type TraceSpan,\n type TraceSummary,\n type WorkerErrorPhase,\n} from \"./dashboard-protocol\";\nimport {\n actionSpan,\n CLIENT_ERROR,\n findException,\n outcomeOf,\n stringAttribute,\n} from \"./dashboard-query\";\n\nconst LIMITS = { ...LIVE_LIMITS, spansPerTrace: 500 };\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: { saveTrace(trace: TraceSummary): void } | undefined;\n #architecture: ArchitectureSnapshot | null = null;\n #api: ApiSnapshot | null = null;\n #docs: DocsSnapshot | null = null;\n #inspector: { port: number; token: string; workflows: boolean } | undefined;\n #apiDocuments: ApiDocument[] = [];\n #sequence = 0;\n #generation = 0;\n\n /** Finished requests are also kept in `history`, when given. */\n constructor(\n options: { history?: { saveTrace(trace: TraceSummary): void } } = {},\n ) {\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 /**\n * Set where the app serves its workflow inspector and schedules, or\n * `undefined` when it stops. The address stays here: the snapshot says only\n * whether there is a workflow inspector.\n */\n setInspector(\n target: { port: number; token: string; workflows: boolean } | undefined,\n ): void {\n this.#inspector = target;\n this.#emit({ type: \"inspector\", inspector: Boolean(target?.workflows) });\n }\n\n /** Where the dashboard proxies the workflow inspector and schedules, when the app serves them. */\n inspectorTarget(): { port: number; token: string } | undefined {\n return this.#inspector;\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 inspector: Boolean(this.#inspector?.workflows),\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, ATTR.httpMethod);\n entry.route = stringAttribute(record.attributes, ATTR.httpRoute);\n entry.path = stringAttribute(record.attributes, ATTR.urlPath);\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, ATTR.errorCode);\n if (code !== undefined) {\n const exception = findException(record.events);\n this.#pushFailure({\n phase: \"request\",\n code,\n message:\n stringAttribute(exception, ATTR.exceptionMessage) ??\n stringAttribute(record.attributes, ATTR.errorMessage) ??\n code,\n status: numberAttribute(record.attributes, ATTR.errorStatus),\n stack: stringAttribute(exception, ATTR.exceptionStack),\n traceId: entry.traceId,\n route: entry.route,\n service: stringAttribute(record.attributes, ATTR.service),\n action: stringAttribute(record.attributes, ATTR.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(record.attributes, ATTR.httpStatus);\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 outcome = outcomeOf({\n status: record.status === \"error\" ? \"error\" : \"ok\",\n httpStatus: entry.httpStatus,\n });\n entry.status = outcome === \"server\" ? \"error\" : \"ok\";\n if (outcome !== \"ok\" && !entry.failureRecorded) {\n const exception = findException(record.events);\n this.#pushFailure({\n phase: \"request\",\n code: status >= CLIENT_ERROR ? `HTTP_${status}` : \"UNHANDLED_ERROR\",\n message:\n stringAttribute(exception, ATTR.exceptionMessage) ??\n record.statusMessage ??\n describeResponse(entry, status),\n status: entry.httpStatus,\n stack: stringAttribute(exception, ATTR.exceptionStack),\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 (error) {\n this.#listeners.delete(listener);\n console.warn(\n \"[Brick-TS] A dashboard client stopped receiving updates:\",\n error,\n );\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 action = actionSpan(spans);\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(action?.attributes, ATTR.service),\n action: stringAttribute(action?.attributes, ATTR.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 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","import {\n ConfigError,\n DEFAULT_DASHBOARD_PORT,\n DEFAULT_HISTORY_DAYS,\n} from \"./config\";\nimport { DocsHost } from \"./dev-docs\";\nimport {\n startDevDashboard,\n type DevDashboard,\n type DevDashboardOptions,\n} from \"./dev-dashboard\";\nimport { openHistory } from \"./dev-history\";\nimport { DevTelemetryStore } from \"./dev-telemetry-store\";\n\nexport interface DashboardHost extends DevDashboard {\n /** Where the host records what the app reports. */\n readonly store: DevTelemetryStore;\n /** The app's developer documentation, when `docs` was asked for. */\n readonly docs?: DocsHost;\n}\n\n/**\n * Open the dashboard with its history, store and docs, for `brick dev`, the\n * Vite plugin and the production dashboard alike. When it cannot start, what\n * it opened is closed, `warn` says why, and the host runs on without it. A\n * configuration mistake (a bad theme, a public host without auth) throws.\n */\nexport async function openDashboard(\n options: Omit<DevDashboardOptions, \"store\" | \"history\" | \"docs\" | \"port\"> & {\n /** Default 9400. */\n port?: number;\n /** The project folder; history is kept in `.brick/` inside it. */\n directory: string;\n /** Days of requests to keep on disk; zero for none. Default 90. */\n historyDays?: number;\n warn: (message: string) => void;\n /** Serve the app's developer documentation (the Docs tab). */\n docs?: boolean;\n },\n): Promise<DashboardHost | undefined> {\n const {\n port = DEFAULT_DASHBOARD_PORT,\n directory,\n historyDays = DEFAULT_HISTORY_DAYS,\n warn,\n docs: withDocs,\n ...rest\n } = options;\n const history = await openHistory({ directory, days: historyDays, warn });\n const store = new DevTelemetryStore({ history });\n const docs = withDocs\n ? new DocsHost((docs) => store.setDocs(docs), warn)\n : undefined;\n let server: DevDashboard;\n try {\n server = await startDevDashboard({\n ...rest,\n port,\n store,\n history,\n docs: docs && (() => docs.current),\n });\n } catch (error) {\n docs?.close();\n history?.close();\n if (error instanceof ConfigError) throw error;\n const reason = error instanceof Error ? error.message : String(error);\n warn(`[Brick-TS] ${reason} Continuing without the dashboard.`);\n return undefined;\n }\n return {\n port: server.port,\n store,\n docs,\n setPluginExtensions: (plugins) => server.setPluginExtensions(plugins),\n stop() {\n server.stop();\n docs?.close();\n history?.close();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AA0CA,MAAa,eAAe;CAC1B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAM,6BAAa,IAAI,IAAI;CAAC;CAAS;CAAQ;CAAU;AAAO,CAAC;AAC/D,MAAM,4BAAY,IAAI,IAAI,CAAC,QAAQ,MAAM,CAAC;AAC1C,MAAM,SAAS,IAAI,IAAY,YAAY;;AAG3C,SAAS,SAAS,OAAe,OAAwB;CACvD,IAAI,OAAO,UAAU,YAAY,CAAC,MAAM,KAAK,KAAK,YAAY,KAAK,KAAK,GACtE,MAAM,IAAI,YACR,0BAA0B,MAAM,8CAClC;CACF,OAAO,MAAM,KAAK;AACpB;;;;;AAMA,SAAgB,SAAS,OAA2C;CAClE,IAAI,CAAC,OAAO,OAAO;CACnB,KAAK,MAAM,OAAO,OAAO,KAAK,KAAK,GACjC,IAAI,CAAC,WAAW,IAAI,GAAG,GACrB,MAAM,IAAI,YACR,kCAAkC,IAAI,2CACxC;CACJ,MAAM,QAAkB,CAAC;CACzB,MAAM,OAAiB,CAAC;CACxB,I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WoC;CACpC,MAAM,EACJ,OAAO,wBACP,WACA,cAAA,IACA,MACA,MAAM,UACN,GAAG,SACD;CACJ,MAAM,UAAU,MAAM,YAAY;EAAE;EAAW,MAAM;EAAa;CAAK,CAAC;CACxE,MAAM,QAAQ,IAAI,kBAAkB,EAAE,QAAQ,CAAC;CAC/C,MAAM,OAAO,WACT,IAAI,UAAU,SAAS,MAAM,QAAQ,IAAI,GAAG,IAAI,IAChD,KAAA;CACJ,IAAI;CACJ,IAAI;EACF,SAAS,MAAM,kBAAkB;GAC/B,GAAG;GACH;GACA;GACA;GACA,MAAM,eAAe,KAAK;EAC5B,CAAC;CACH,SAAS,OAAO;EACd,MAAM,MAAM;EACZ,SAAS,MAAM;EACf,IAAI,iBAAiB,aAAa,MAAM;EAExC,KAAK,cADU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAC1C,mCAAmC;EAC7D;CACF;CACA,OAAO;EACL,MAAM,OAAO;EACb;EACA;EACA,sBAAsB,YAAY,OAAO,oBAAoB,OAAO;EACpE,OAAO;GACL,OAAO,KAAK;GACZ,MAAM,MAAM;GACZ,SAAS,MAAM;EACjB;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"dashboard-host.js","names":["text","text","text","text","text","cliPkg.version"],"sources":["../src/dashboard-extension.ts","../src/dev-docs.ts","../src/dashboard-query.ts","../src/dev-dashboard-shell.ts","../src/dashboard-mcp-args.ts","../src/dashboard-mcp-docs.ts","../src/dev-history.ts","../src/dashboard-mcp-logs.ts","../src/dashboard-mcp-workflows.ts","../src/dashboard-mcp.ts","../src/dashboard-access.ts","../src/dev-dashboard.ts","../src/dev-telemetry-store.ts","../src/dashboard-host.ts"],"sourcesContent":["import { existsSync, watch, type FSWatcher } from \"node:fs\";\nimport { mkdir, readdir, readFile, writeFile } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport { ConfigError } from \"./config\";\nimport {\n ASSETS,\n SHARED_MODULES,\n type ExtensionPart,\n} from \"./dashboard-protocol\";\n\n/*\n * The dashboard's extension: one module of the project's own, built with the\n * dashboard's React and UI kit left external (the page's import map hands it\n * the dashboard's copies), and its Tailwind classes compiled against the\n * dashboard's theme.css. Plus the theme, which needs no code at all.\n */\n\n/** Token values for the dashboard's light and dark themes, its radius and fonts. */\nexport interface DashboardTheme {\n /** Colour tokens in light mode, by name: `{ primary: \"oklch(0.55 0.2 260)\" }`. */\n light?: Record<string, string>;\n /** Colour tokens in dark mode. */\n dark?: Record<string, string>;\n /** The base corner radius, such as `\"0.5rem\"`. */\n radius?: string;\n /** CSS font stacks. The page must be able to load the font. */\n fonts?: { sans?: string; mono?: string };\n}\n\n/** What `dashboard` accepts wherever the dashboard starts or is built. */\nexport interface DashboardExtensionOptions {\n /**\n * A module whose default export is `defineDashboard({ ... })`, or the\n * `dashboard` folder `brick build` wrote it to.\n */\n extension?: string;\n theme?: DashboardTheme;\n}\n\n/** The colour tokens of `dashboard/theme.css`; a test keeps the two in step. */\nexport const THEME_TOKENS = [\n \"background\",\n \"foreground\",\n \"card\",\n \"card-foreground\",\n \"popover\",\n \"popover-foreground\",\n \"primary\",\n \"primary-foreground\",\n \"secondary\",\n \"secondary-foreground\",\n \"muted\",\n \"muted-foreground\",\n \"accent\",\n \"accent-foreground\",\n \"destructive\",\n \"destructive-foreground\",\n \"positive\",\n \"border\",\n \"input\",\n \"ring\",\n \"chart-1\",\n \"chart-2\",\n \"chart-3\",\n \"chart-4\",\n \"chart-5\",\n \"span-request\",\n \"span-action\",\n \"span-rpc\",\n \"span-sql\",\n \"span-event\",\n \"span-other\",\n] as const;\n\nconst THEME_KEYS = new Set([\"light\", \"dark\", \"radius\", \"fonts\"]);\nconst FONT_KEYS = new Set([\"sans\", \"mono\"]);\nconst TOKENS = new Set<string>(THEME_TOKENS);\n\n/** A value that cannot close the rule it sits in. */\nfunction cssValue(where: string, value: unknown): string {\n if (typeof value !== \"string\" || !value.trim() || /[;{}<>\\\\]/.test(value))\n throw new ConfigError(\n `Brick: dashboard.theme.${where} must be a CSS value without ; { } < > or \\\\.`,\n );\n return value.trim();\n}\n\n/**\n * The stylesheet for a theme, loaded after the dashboard's own; empty when the\n * theme sets nothing. Throws on a token name theme.css does not have.\n */\nexport function themeCss(theme: DashboardTheme | undefined): string {\n if (!theme) return \"\";\n for (const key of Object.keys(theme))\n if (!THEME_KEYS.has(key))\n throw new ConfigError(\n `Brick: dashboard.theme has no \"${key}\". It takes light, dark, radius and fonts.`,\n );\n const rules: string[] = [];\n const root: string[] = [];\n if (theme.radius !== undefined)\n root.push(`--radius: ${cssValue(\"radius\", theme.radius)};`);\n for (const [name, value] of Object.entries(theme.fonts ?? {})) {\n if (!FONT_KEYS.has(name))\n throw new ConfigError(\n `Brick: dashboard.theme.fonts has no \"${name}\". It takes sans and mono.`,\n );\n root.push(`--font-${name}: ${cssValue(`fonts.${name}`, value)};`);\n }\n if (root.length) rules.push(`:root {\\n ${root.join(\"\\n \")}\\n}`);\n // theme.css sets light on :root and dark on .dark, both on <html>; these\n // selectors win over both, and each applies only in its own mode.\n for (const [mode, selector] of [\n [\"light\", \":root:not(.dark)\"],\n [\"dark\", \":root.dark\"],\n ] as const) {\n const tokens = theme[mode];\n if (!tokens) continue;\n const lines = Object.entries(tokens).map(([name, value]) => {\n if (!TOKENS.has(name))\n throw new ConfigError(\n `Brick: dashboard.theme.${mode} has no token \"${name}\". Tokens: ${THEME_TOKENS.join(\", \")}.`,\n );\n return `--${name}: ${cssValue(`${mode}.${name}`, value)};`;\n });\n if (lines.length) rules.push(`${selector} {\\n ${lines.join(\"\\n \")}\\n}`);\n }\n return rules.length ? `${rules.join(\"\\n\")}\\n` : \"\";\n}\n\nconst SHARED = SHARED_MODULES.map((module) => module.specifier);\n\n/** Bundle a module of React components for the dashboard to import (an extension, or the docs' components), with its shared modules left to the page. */\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 // Report what went wrong, not only that something did.\n throw: false,\n });\n if (!result.success)\n throw new Error(result.logs.map((log) => log.message).join(\"\\n\"));\n // A CSS import adds a stylesheet output; the module is the entry point.\n const output =\n result.outputs.find((item) => item.kind === \"entry-point\") ??\n result.outputs[0]!;\n return output.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 dashboard module produced no output.\");\n}\n\n/** The built React app, next to `src/` in the repo and next to `dist/` when published. */\nexport function 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\nexport interface BuiltExtension {\n js: string;\n /** The extension's own Tailwind classes; empty when it uses none. */\n css: string;\n /** The `extension-N.js` files `js` lists, by name. */\n parts?: Record<string, string>;\n}\n\n/** The `warn` functions already told that tailwindcss is missing: once each, not once per rebuild. */\nconst warnedTailwind = new WeakSet<(message: string) => void>();\n\n/**\n * Tailwind for the classes in the extension's bundle, compiled against the\n * dashboard's theme.css so `bg-primary` and the rest match. Only utilities are\n * emitted: the dashboard's stylesheet already has the base styles and tokens.\n * Tailwind is an optional peer, found from the project first.\n */\nasync function extensionCss(\n entry: string,\n js: string,\n warn: (message: string) => void,\n): Promise<string> {\n let tailwind: string | undefined;\n let main: string | undefined;\n for (const from of [entry, fileURLToPath(import.meta.url)]) {\n try {\n const require = createRequire(from);\n tailwind = require.resolve(\"tailwindcss/package.json\");\n main = require.resolve(\"tailwindcss\");\n break;\n } catch {}\n }\n const assets = assetsDirectory();\n const themeFile = assets\n ? join(assets, \"theme.css\")\n : fileURLToPath(new URL(\"../dashboard/theme.css\", import.meta.url));\n if (!tailwind || !main) {\n if (!warnedTailwind.has(warn))\n warn(\n \"[Brick-TS] tailwindcss is not installed, so the dashboard extension's own Tailwind classes are not compiled. The UI kit is styled either way.\",\n );\n warnedTailwind.add(warn);\n return \"\";\n }\n const root = dirname(tailwind);\n const { compile } = (await import(\n pathToFileURL(main).href\n )) as typeof import(\"tailwindcss\");\n const compiler = await compile(\n `@layer theme, base, components, utilities;\n@import \"tailwindcss/theme.css\" theme(reference inline);\n@import \"tailwindcss/utilities.css\" layer(utilities);\n@reference \"brick/theme.css\";\n`,\n {\n base: root,\n async loadStylesheet(id) {\n const path =\n id === \"brick/theme.css\"\n ? themeFile\n : join(root, id.replace(/^tailwindcss\\//, \"\"));\n return {\n path,\n base: dirname(path),\n content: await readFile(path, \"utf8\"),\n };\n },\n },\n );\n // Every word in the bundle is a candidate; Tailwind ignores what is not a class.\n const candidates = new Set(js.split(/[\\s\"'`]+/).filter(Boolean));\n const css = compiler.build([...candidates]);\n return /\\{/.test(css) ? css : \"\";\n}\n\n/** Bundle the extension and its styles for the dashboard page. */\nexport async function buildDashboardExtension(\n entry: string,\n options: { warn?: (message: string) => void } = {},\n): Promise<BuiltExtension> {\n const js = await bundleComponents(entry);\n return {\n js,\n css: await extensionCss(\n entry,\n js,\n options.warn ?? ((message) => console.warn(message)),\n ),\n };\n}\n\n/**\n * Write the app's extension and its plugins' into `outdir`, where `brick start`\n * can serve them: the app's alone as it is, or with plugins each part apart\n * and `extension.js` loading them, as `brick dev` serves them. Returns false\n * when there is none to write. A plugin's that fails to build throws.\n */\nexport async function writeDashboardExtension(\n entry: string | undefined,\n plugins: readonly PluginDashboard[],\n outdir: string,\n): Promise<boolean> {\n const parts = [\n ...(entry ? [{ name: \"app\", path: entry, plugin: false }] : []),\n ...[...pluginDashboards(plugins)].map(([path, name]) => ({\n name,\n path,\n plugin: true,\n })),\n ];\n if (!parts.length) return false;\n const warn = (message: string) => console.warn(message);\n const built = await Promise.all(\n parts.map((part) =>\n buildDashboardExtension(part.path, { warn }).catch((error: unknown) => {\n if (!part.plugin) throw error;\n throw new Error(\n `Brick compiler: the dashboard extension of plugin ${part.name} failed to build: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }),\n ),\n );\n await writeBuiltFolder(\n outdir,\n layoutParts(\n parts.map((part, index) => ({ ...part, built: built[index] })),\n )!,\n );\n return true;\n}\n\n/** Whether `path` is a folder `brick build` wrote, which is served as it is. */\nconst isBuiltFolder = (path: string): boolean =>\n existsSync(join(path, ASSETS.extension));\n\n/** Write the extensions as `layoutParts` lays them out; `readBuiltFolder` reads them back. */\nasync function writeBuiltFolder(\n outdir: string,\n layout: BuiltExtension,\n): Promise<void> {\n await mkdir(outdir, { recursive: true });\n await writeFile(join(outdir, ASSETS.extension), layout.js);\n await writeFile(join(outdir, ASSETS.extensionCss), layout.css);\n for (const [name, js] of Object.entries(layout.parts ?? {}))\n await writeFile(join(outdir, name), js);\n}\n\nasync function readBuiltFolder(path: string): Promise<BuiltExtension> {\n const css = join(path, ASSETS.extensionCss);\n const parts: Record<string, string> = {};\n for (const name of await readdir(path))\n if (/^extension-\\d+\\.js$/.test(name))\n parts[name] = await readFile(join(path, name), \"utf8\");\n return {\n js: await readFile(join(path, ASSETS.extension), \"utf8\"),\n css: existsSync(css) ? await readFile(css, \"utf8\") : \"\",\n parts,\n };\n}\n\n/**\n * How the extensions are served, by `brick dev` and from a `brick build`\n * folder alike. The app's alone is served as it is. Otherwise each that built\n * is `extension-<index>.js`, `extension.js` lists them for the page to load\n * and merge, and their styles are served together. `version` is added to each\n * part's address, so a rebuilt one is fetched again.\n */\nfunction layoutParts(\n parts: readonly {\n name: string;\n plugin: boolean;\n built: BuiltExtension | undefined;\n }[],\n version = \"\",\n): BuiltExtension | undefined {\n if (parts.length === 1 && !parts[0]!.plugin) return parts[0]!.built;\n const built = parts.flatMap((part, index) =>\n part.built\n ? [{ ...part, built: part.built, file: `extension-${index}.js` }]\n : [],\n );\n if (!built.length) return undefined;\n return {\n js: extensionManifest(\n built.map((part) => ({\n name: part.name,\n src: `./${part.file}${version}`,\n plugin: part.plugin,\n })),\n ),\n css: built.map((part) => part.built.css).join(\"\"),\n parts: Object.fromEntries(built.map((part) => [part.file, part.built.js])),\n };\n}\n\n/**\n * The extension as the dashboard serves it. From source it is built here, and\n * rebuilt as its folder changes when watching; from a `brick build` folder it\n * is read as it is. A failed build keeps the error to show on the page.\n */\nexport class DashboardExtensionHost {\n readonly #path: string;\n readonly #warn: (message: string) => void;\n readonly #listeners = new Set<() => void>();\n #watcher: FSWatcher | undefined;\n #timer: ReturnType<typeof setTimeout> | undefined;\n #pending: Promise<void> = Promise.resolve();\n revision = 0;\n built: BuiltExtension | undefined;\n error: string | undefined;\n\n constructor(path: string, warn: (message: string) => void) {\n this.#path = resolve(path);\n this.#warn = warn;\n }\n\n load(): Promise<void> {\n this.#pending = this.#pending.then(async () => {\n const before = JSON.stringify([this.built, this.error]);\n try {\n if (isBuiltFolder(this.#path)) {\n this.built = await readBuiltFolder(this.#path);\n } else {\n if (!existsSync(this.#path))\n throw new Error(\n `Brick: the dashboard extension ${this.#path} does not exist.`,\n );\n this.built = await buildDashboardExtension(this.#path, {\n warn: this.#warn,\n });\n }\n this.error = undefined;\n } catch (error) {\n this.built = undefined;\n this.error = error instanceof Error ? error.message : String(error);\n this.#warn(`[Brick-TS] Dashboard extension: ${this.error}`);\n }\n // The folder may hold the app too; its changes leave the bundle as it was.\n if (JSON.stringify([this.built, this.error]) === before) return;\n this.revision++;\n for (const listener of this.#listeners) listener();\n });\n return this.#pending;\n }\n\n watch(): void {\n try {\n this.#watcher = watch(\n dirname(this.#path),\n { recursive: true },\n (_event, file) => {\n if (file && /(^|[\\\\/])(node_modules|\\.)/.test(file)) return;\n clearTimeout(this.#timer);\n this.#timer = setTimeout(() => void this.load(), 100);\n },\n );\n } catch {\n // A folder that cannot be watched still works; it needs a restart.\n }\n }\n\n onChange(listener: () => void): () => void {\n this.#listeners.add(listener);\n return () => {\n this.#listeners.delete(listener);\n };\n }\n\n close(): void {\n clearTimeout(this.#timer);\n this.#watcher?.close();\n this.#listeners.clear();\n }\n}\n\n/** A plugin's dashboard extension, as `app.definition.plugins` lists it. */\nexport interface PluginDashboard {\n name: string;\n dashboard?: string;\n}\n\n/** The plugins' extensions by path, each once, in install order. */\nfunction pluginDashboards(\n plugins: readonly PluginDashboard[],\n): Map<string, string> {\n const wanted = new Map<string, string>();\n for (const plugin of plugins)\n if (plugin.dashboard && !wanted.has(resolve(plugin.dashboard)))\n wanted.set(resolve(plugin.dashboard), plugin.name);\n return wanted;\n}\n\n/**\n * The module the page loads when several extensions take part: it lists them,\n * and the page imports each apart and merges them (`mergeExtensions` there).\n */\nexport function extensionManifest(parts: readonly ExtensionPart[]): string {\n return `export const parts = ${JSON.stringify(parts)};\\n`;\n}\n\n/**\n * The app's extension and those of its plugins, served as one. With only the\n * app's, it is served as it is; with plugins, each is built apart (a failed\n * build leaves the others) and `extension.js` loads them all.\n */\nexport class DashboardExtensions {\n readonly #warn: (message: string) => void;\n readonly #listeners = new Set<() => void>();\n /** The app's own first, when it has one, then its plugins'. */\n readonly #parts: {\n name: string;\n path: string;\n plugin: boolean;\n host: DashboardExtensionHost;\n }[] = [];\n revision = 0;\n\n constructor(path: string | undefined, warn: (message: string) => void) {\n this.#warn = warn;\n if (path) this.#add(\"app\", path, false);\n }\n\n #add(name: string, path: string, plugin: boolean) {\n const host = new DashboardExtensionHost(path, this.#warn);\n host.onChange(() => this.#changed());\n this.#parts.push({ name, path: resolve(path), plugin, host });\n return host;\n }\n\n get #own() {\n return this.#parts.find((part) => !part.plugin);\n }\n\n #changed() {\n this.revision++;\n for (const listener of this.#listeners) listener();\n }\n\n get active(): boolean {\n return this.#parts.length > 0;\n }\n\n get built(): BuiltExtension | undefined {\n return layoutParts(\n this.#parts.map((part) => ({\n name: part.name,\n plugin: part.plugin,\n built: part.host.built,\n })),\n `?v=${this.revision}`,\n );\n }\n\n get error(): string | undefined {\n const errors = this.#parts.flatMap((part) =>\n part.host.error\n ? [\n this.#parts.length === 1 && !part.plugin\n ? part.host.error\n : `${part.name}: ${part.host.error}`,\n ]\n : [],\n );\n return errors.length ? errors.join(\"\\n\") : undefined;\n }\n\n /** A file under `/assets/` this serves, or undefined. */\n asset(name: string): string | undefined {\n if (name === ASSETS.extension) return this.built?.js;\n if (name === ASSETS.extensionCss) return this.built?.css;\n // From the layout, or the `brick build` folder the app's names.\n return this.built?.parts?.[name];\n }\n\n /** Follow the app's plugins: build the extensions they ship, drop the rest. */\n async setPlugins(plugins: readonly PluginDashboard[]): Promise<void> {\n // A `brick build` folder already holds its plugins' extensions.\n const own = this.#own;\n if (own && isBuiltFolder(own.path)) return;\n const wanted = pluginDashboards(plugins);\n const current = this.#parts.filter((part) => part.plugin);\n if (\n current.length === wanted.size &&\n current.every((part) => wanted.get(part.path) === part.name)\n )\n return;\n for (const part of current) part.host.close();\n this.#parts.splice(own ? 1 : 0);\n const loads = [...wanted].map(([path, name]) =>\n this.#add(name, path, true).load(),\n );\n await Promise.all(loads);\n this.#changed();\n }\n\n load(): Promise<void> {\n return Promise.all(this.#parts.map((part) => part.host.load())).then(\n () => undefined,\n );\n }\n\n /** Rebuild the app's own as its folder changes; plugins' are packages. */\n watch(): void {\n this.#own?.host.watch();\n }\n\n onChange(listener: () => void): () => void {\n this.#listeners.add(listener);\n return () => {\n this.#listeners.delete(listener);\n };\n }\n\n close(): void {\n for (const part of this.#parts) part.host.close();\n this.#listeners.clear();\n }\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 { bundleComponents } from \"./dashboard-extension\";\nimport {\n decode,\n docsFileUrl,\n docsHref,\n isExternalHref,\n type DocsInfo,\n type DocsNode,\n type DocsPage,\n type DocsSearchHit,\n type DocsSnapshot,\n type DocsTree,\n} from \"./dashboard-protocol\";\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\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;\n/** What the docs are called when their folder does not name them. */\nconst DEFAULT_TITLE = \"Docs\";\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 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 (isExternalHref(href) || href.startsWith(\"#\")) 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 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 = DEFAULT_TITLE;\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 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 : DEFAULT_TITLE;\n this.revision++;\n for (const listener of this.#listeners) listener();\n }\n\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 /** A page as written, without its frontmatter, for a reader that is not the dashboard's page. */\n source(\n slugs: string[],\n ):\n | { title: string; description?: string; path: string; content: string }\n | undefined {\n const file = this.#pages.get(slugs.join(\"/\"));\n return (\n file && {\n title: file.title,\n description: file.description,\n path: file.path,\n content: file.content,\n }\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 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 = docsFileUrl(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 = docsFileUrl(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 anchor = hashAt >= 0 ? decode(href.slice(hashAt + 1)) : undefined;\n const target =\n (hashAt >= 0 ? href.slice(0, hashAt) : href).split(\"?\")[0] ?? \"\";\n const route = (slug: string) =>\n docsHref(slug ? slug.split(\"/\") : [], anchor);\n if (isExternalHref(href) || !target) 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/** 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) || DEFAULT_TITLE,\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 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 #publish: (docs: DocsSnapshot | null) => void;\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(\n publish: (docs: DocsSnapshot | null) => void,\n warn: (message: string) => void,\n ) {\n this.#publish = publish;\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.#publish(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.#publish(\n opened.status === \"missing\"\n ? { status: \"missing\", packages: opened.packages, message }\n : { status: \"error\", message },\n );\n return;\n }\n this.#docs = opened.docs;\n this.#stopListening = opened.docs.onChange(() =>\n this.#publish(opened.docs.snapshot()),\n );\n this.#publish(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 {\n ATTR,\n SPAN,\n type FacetValue,\n type HistoryFacets,\n type HistorySummary,\n type HistoryTrace,\n type Outcome,\n type TraceSummary,\n type SpanEventRecord,\n type VolumeBucket,\n} from \"./dashboard-protocol\";\n\n/*\n * The request log's rules, as plain functions over rows: what a request's\n * outcome is, which rows a filter keeps, and the counts the log shows. The\n * page runs them over live requests; stored history runs the same rules in SQL\n * (dev-history.ts), and a test keeps the two in step.\n */\n\n/** A response status at or above this is a server error; below it and at or above `CLIENT_ERROR`, a client error. */\nexport const SERVER_ERROR = 500;\nexport const CLIENT_ERROR = 400;\n\nexport function outcomeOf(\n row: Pick<TraceSummary, \"status\" | \"httpStatus\">,\n): Outcome {\n const http = row.httpStatus ?? 0;\n if (row.status === \"error\" || http >= SERVER_ERROR) return \"server\";\n if (http >= CLIENT_ERROR) return \"client\";\n return \"ok\";\n}\n\nexport function endpointOf(\n trace: Pick<TraceSummary, \"method\" | \"route\" | \"name\">,\n): string {\n return trace.method && trace.route\n ? `${trace.method} ${trace.route}`\n : trace.name;\n}\n\n/** A live request as a log row; the same shape the history API returns. */\nexport function toRow(trace: TraceSummary): HistoryTrace {\n const { spans: _spans, ...row } = trace;\n return { ...row, endpoint: endpointOf(trace) };\n}\n\nexport const OUTCOMES: readonly Outcome[] = [\"ok\", \"client\", \"server\"];\n\n/** The filters of the request log, over a window, a page at a time. */\nexport interface HistoryQuery extends RowFilters {\n from: number;\n to: number;\n limit?: number;\n offset?: number;\n}\n\n/** A history query as the query string the history API takes. */\nexport function encodeHistoryQuery(query: HistoryQuery): URLSearchParams {\n const params = new URLSearchParams({\n from: String(query.from),\n to: String(query.to),\n });\n for (const endpoint of query.endpoints ?? [])\n params.append(\"endpoint\", endpoint);\n for (const method of query.methods ?? []) params.append(\"method\", method);\n for (const service of query.services ?? []) params.append(\"service\", service);\n for (const outcome of query.outcomes ?? []) params.append(\"outcome\", outcome);\n if (query.minMs !== undefined) params.set(\"minMs\", String(query.minMs));\n if (query.query) params.set(\"q\", query.query);\n if (query.sort && query.sort !== \"recent\") params.set(\"sort\", query.sort);\n if (query.limit !== undefined) params.set(\"limit\", String(query.limit));\n if (query.offset !== undefined) params.set(\"offset\", String(query.offset));\n return params;\n}\n\n/** The history query in a query string, parsed defensively: what `encodeHistoryQuery` wrote. */\nexport function decodeHistoryQuery(\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) ? Math.trunc(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 // A week back by default.\n from: integer(\"from\") ?? to - 7 * 86_400_000,\n endpoints: all(\"endpoint\"),\n methods: all(\"method\"),\n services: all(\"service\"),\n outcomes: all(\"outcome\")?.filter((value): value is Outcome =>\n OUTCOMES.includes(value as Outcome),\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/** A filter groups its values with OR; separate filters combine with AND. */\nexport interface RowFilters {\n endpoints?: string[];\n methods?: string[];\n services?: string[];\n outcomes?: Outcome[];\n /** Only requests at least this slow, in milliseconds. */\n minMs?: number;\n /** Matches the endpoint, path, span name, action or failure message. */\n query?: string;\n sort?: \"recent\" | \"slowest\";\n}\n\nexport type Facet = keyof HistoryFacets;\n\n/** The fields the search box looks in. */\nexport const SEARCHED: readonly (keyof HistoryTrace)[] = [\n \"endpoint\",\n \"path\",\n \"name\",\n \"action\",\n \"message\",\n];\n\n/** Whether `row` passes the filters, leaving out `skip` when counting its facet. */\nexport function matches(\n row: HistoryTrace,\n filters: RowFilters,\n skip?: Facet,\n): boolean {\n const anyOf = (facet: Facet, values: string[] | undefined, value?: string) =>\n skip === facet ||\n !values?.length ||\n (value !== undefined && values.includes(value));\n if (!anyOf(\"endpoint\", filters.endpoints, row.endpoint)) return false;\n if (!anyOf(\"method\", filters.methods, row.method)) return false;\n if (!anyOf(\"service\", filters.services, row.service)) return false;\n if (!anyOf(\"outcome\", filters.outcomes, outcomeOf(row))) return false;\n if (\n filters.minMs !== undefined &&\n filters.minMs > 0 &&\n (row.durationMs ?? 0) < filters.minMs\n )\n return false;\n const needle = filters.query?.trim().toLowerCase();\n if (needle)\n return SEARCHED.some((field) =>\n String(row[field] ?? \"\")\n .toLowerCase()\n .includes(needle),\n );\n return true;\n}\n\n/** Newest first, or slowest first and then newest. */\nexport function compareRows(\n sort: RowFilters[\"sort\"],\n): (a: HistoryTrace, b: HistoryTrace) => number {\n return sort === \"slowest\"\n ? (a, b) =>\n (b.durationMs ?? 0) - (a.durationMs ?? 0) || b.startMs - a.startMs\n : (a, b) => b.startMs - a.startMs;\n}\n\nexport function applyFilters(\n rows: HistoryTrace[],\n filters: RowFilters,\n): HistoryTrace[] {\n return rows\n .filter((row) => matches(row, filters))\n .sort(compareRows(filters.sort));\n}\n\n/** The most values a facet lists. */\nexport const MAX_FACET_VALUES = 30;\n\nconst FACET_VALUE: Record<Facet, (row: HistoryTrace) => string | undefined> = {\n outcome: outcomeOf,\n method: (row) => row.method,\n service: (row) => row.service,\n endpoint: (row) => row.endpoint,\n};\n\n/** Counts for each filter, as if that filter were not applied. */\nexport function computeFacets(\n rows: HistoryTrace[],\n filters: RowFilters,\n): HistoryFacets {\n const count = (facet: Facet): FacetValue[] => {\n const counts = new Map<string, number>();\n for (const row of rows) {\n if (!matches(row, filters, facet)) continue;\n const value = FACET_VALUE[facet](row);\n if (value !== undefined) counts.set(value, (counts.get(value) ?? 0) + 1);\n }\n return [...counts.entries()]\n .map(([value, total]) => ({ value, count: total }))\n .sort(\n (a, b) =>\n b.count - a.count ||\n (a.value < b.value ? -1 : a.value > b.value ? 1 : 0),\n )\n .slice(0, MAX_FACET_VALUES);\n };\n return {\n outcome: count(\"outcome\"),\n method: count(\"method\"),\n service: count(\"service\"),\n endpoint: count(\"endpoint\"),\n };\n}\n\n/** The width of each of `count` buckets across [from, to]: whole milliseconds, at least one. */\nexport const bucketSize = (from: number, to: number, count: number): number =>\n Math.max(Math.ceil((to - from) / count), 1);\n\n/** Count rows into `count` equal time buckets across [from, to], by outcome. */\nexport function bucketRows(\n rows: HistoryTrace[],\n from: number,\n to: number,\n count: number,\n): VolumeBucket[] {\n const size = bucketSize(from, to, count);\n const buckets: VolumeBucket[] = Array.from({ length: count }, (_, index) => ({\n start: from + index * size,\n ok: 0,\n client: 0,\n server: 0,\n }));\n for (const row of rows) {\n if (row.startMs < from || row.startMs > to) continue;\n const index = Math.floor((row.startMs - from) / size);\n buckets[Math.min(index, count - 1)]![outcomeOf(row)] += 1;\n }\n return buckets;\n}\n\n/** Linear-interpolated percentile of an ascending list; 0 for an empty list. */\nexport function 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 (\n sorted[lower]! + (sorted[upper]! - sorted[lower]!) * (position - lower)\n );\n}\n\nexport const LOG_LEVELS = [\"debug\", \"info\", \"warn\", \"error\"] as const;\nexport type LogLevel = (typeof LOG_LEVELS)[number];\n\n/** A line with no level, or one this does not know, is `info`, as the Logs view reads it. */\nconst levelOf = (value: unknown): LogLevel =>\n LOG_LEVELS.find((level) => level === value) ?? \"info\";\n\n/** The line of a log search: which requests, and which of their lines. */\nexport interface LogSearch {\n /** The window is on when the request started. */\n from: number;\n to: number;\n /** Case-insensitive substring of the message. */\n query?: string;\n level?: LogLevel;\n service?: string;\n endpoint?: string;\n}\n\n/** One log line, with the request it belongs to. */\nexport interface LogLine {\n timeMs: number;\n level: LogLevel;\n message: string;\n traceId: string;\n endpoint: string;\n span: string;\n /** Where the line sits in its request, to order lines of the same millisecond. */\n spanIndex: number;\n eventIndex: number;\n}\n\n/** Newest first, then by request and position, so a page never repeats or skips a line. */\nexport function compareLogLines(a: LogLine, b: LogLine): number {\n return (\n b.timeMs - a.timeMs ||\n (a.traceId < b.traceId ? -1 : a.traceId > b.traceId ? 1 : 0) ||\n a.spanIndex - b.spanIndex ||\n a.eventIndex - b.eventIndex\n );\n}\n\n/** The matching log lines of these requests, newest first. */\nexport function searchLogLines(\n traces: TraceSummary[],\n search: LogSearch,\n): LogLine[] {\n const needle = search.query?.toLowerCase();\n const lines: LogLine[] = [];\n for (const trace of traces) {\n const endpoint = endpointOf(trace);\n if (\n trace.startMs < search.from ||\n trace.startMs > search.to ||\n (search.service !== undefined && trace.service !== search.service) ||\n (search.endpoint !== undefined && endpoint !== search.endpoint)\n )\n continue;\n for (const [spanIndex, span] of trace.spans.entries())\n for (const [eventIndex, event] of span.events.entries()) {\n if (event.name !== SPAN.logEvent) continue;\n const level = levelOf(event.attributes[ATTR.logLevel]);\n const message = String(event.attributes[ATTR.logMessage] ?? \"\");\n if (\n (search.level !== undefined && level !== search.level) ||\n (needle !== undefined && !message.toLowerCase().includes(needle))\n )\n continue;\n lines.push({\n timeMs: event.timeMs,\n level,\n message,\n traceId: trace.traceId,\n endpoint,\n span: span.name,\n spanIndex,\n eventIndex,\n });\n }\n }\n return lines.sort(compareLogLines);\n}\n\nexport interface EndpointStats {\n endpoint: string;\n requests: number;\n serverErrors: number;\n avgMs: number;\n maxMs: number;\n}\n\nexport function slowestEndpoints(\n rows: HistoryTrace[],\n limit: number,\n): EndpointStats[] {\n const byEndpoint = new Map<\n string,\n { requests: number; serverErrors: number; totalMs: number; maxMs: number }\n >();\n for (const row of rows) {\n if (row.durationMs === undefined) continue;\n const stats = byEndpoint.get(row.endpoint) ?? {\n requests: 0,\n serverErrors: 0,\n totalMs: 0,\n maxMs: 0,\n };\n stats.requests += 1;\n if (outcomeOf(row) === \"server\") stats.serverErrors += 1;\n stats.totalMs += row.durationMs;\n stats.maxMs = Math.max(stats.maxMs, row.durationMs);\n byEndpoint.set(row.endpoint, stats);\n }\n return [...byEndpoint.entries()]\n .map(([endpoint, { totalMs, ...stats }]) => ({\n endpoint,\n ...stats,\n avgMs: totalMs / stats.requests,\n }))\n .sort((a, b) => b.avgMs - a.avgMs || b.requests - a.requests)\n .slice(0, limit);\n}\n\n/** The numbers for the cards at the top of the log, for these requests. */\nexport function summarizeRows(rows: HistoryTrace[]): HistorySummary {\n let clientErrors = 0;\n let serverErrors = 0;\n const durations: number[] = [];\n for (const row of rows) {\n const outcome = outcomeOf(row);\n if (outcome === \"client\") clientErrors += 1;\n if (outcome === \"server\") serverErrors += 1;\n if (row.durationMs !== undefined) durations.push(row.durationMs);\n }\n durations.sort((a, b) => a - b);\n return {\n total: rows.length,\n clientErrors,\n serverErrors,\n medianMs: percentile(durations, 0.5),\n p95Ms: percentile(durations, 0.95),\n };\n}\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 [\n new Date(trace.startMs).toISOString(),\n trace.method,\n trace.route,\n trace.path,\n trace.httpStatus ?? trace.status,\n outcomeOf(trace),\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\n/** A string attribute, or undefined when it is missing or of another type. */\nexport function 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\n/** The attributes of the exception a span recorded, if it recorded one. */\nexport function findException(\n events: SpanEventRecord[],\n): Attributes | undefined {\n return events.find((event) => event.name === SPAN.exceptionEvent)?.attributes;\n}\n\n/** The span that ran the request's action, when it ran one. */\nexport function actionSpan<T extends { name: string }>(\n spans: readonly T[],\n): T | undefined {\n return spans.find((span) => span.name.startsWith(SPAN.actionPrefix));\n}\n","import {\n ASSETS,\n assetUrl,\n SHARED_MODULES,\n THEME_STORAGE_KEY,\n} from \"./dashboard-protocol\";\n\nconst IMPORT_MAP = JSON.stringify({\n imports: Object.fromEntries(\n SHARED_MODULES.map((module) => [module.specifier, assetUrl(module.file)]),\n ),\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 hands the project's own modules (its docs components and its\n * dashboard extension), bundled apart from the dashboard, the dashboard's copy\n * of React and its UI kit, so there is one of each on the page.\n *\n * `extension` describes the project's extension: `revision` changes with every\n * rebuild (the page reloads when it does), `js` and `css` say what it built.\n * `theme` is whether `/assets/brick-theme.css` has token values to apply.\n */\nexport function dashboardShell(\n options: {\n extension?: { revision: number; js: boolean; css: boolean };\n theme?: boolean;\n mode?: \"dev\" | \"production\";\n } = {},\n): string {\n const { extension, theme, mode } = options;\n const version = extension ? `?v=${extension.revision}` : \"\";\n return `<!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>${mode === \"production\" ? \"Brick\" : \"Brick dev\"}</title>\n<link rel=\"icon\" href=\"data:,\">\n<script>\n(function () {\n try {\n var theme = localStorage.getItem(${JSON.stringify(THEME_STORAGE_KEY)});\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=\"${assetUrl(ASSETS.appCss)}\">\n${extension?.css ? `<link rel=\"stylesheet\" href=\"${assetUrl(ASSETS.extensionCss)}${version}\">\\n` : \"\"}${theme ? `<link rel=\"stylesheet\" href=\"${assetUrl(ASSETS.theme)}\" data-brick-theme>\\n` : \"\"}${extension ? `<meta name=\"brick-extension\" data-revision=\"${extension.revision}\"${extension.js ? ` data-src=\"${assetUrl(ASSETS.extension)}${version}\"` : \"\"}>\\n` : \"\"}<script type=\"importmap\">\n${IMPORT_MAP}\n</script>\n</head>\n<body>\n<div id=\"root\"></div>\n<script type=\"module\" src=\"${assetUrl(ASSETS.app)}\"></script>\n</body>\n</html>\n`;\n}\n","import type { McpToolDefinition } from \"@brickkit/core\";\nimport type { DevDocs } from \"./dev-docs\";\nimport type { DevHistory } from \"./dev-history\";\nimport type { DevTelemetryStore } from \"./dev-telemetry-store\";\n\n/*\n * What the dashboard's MCP tools share: how they read their arguments, how\n * they shorten what they return, and what data they may read.\n */\n\nexport type Args = Record<string, unknown>;\n\n/** Where the tools read, as the dashboard has them. */\nexport interface McpSources {\n store: DevTelemetryStore;\n /** Stored requests; absent when history is off. */\n history?: DevHistory;\n mode: \"dev\" | \"production\";\n /** Whether this dashboard serves the workflow inspector and schedules: always in dev, in production with `dashboard.inspector`. */\n inspector: boolean;\n /** The app's developer documentation, when it has any, as of this call. */\n docs?: () => DevDocs | undefined;\n}\n\n/** A tool the dashboard offers, listed only while the data it reads exists. */\nexport interface BuiltInTool {\n definition: McpToolDefinition;\n run(args: Args): string | Promise<string>;\n available?(): boolean;\n}\n\nexport const MINUTE = 60_000;\nconst UNITS = { s: 1000, m: MINUTE, h: 60 * MINUTE, d: 24 * 60 * MINUTE };\nexport const DAY = UNITS.d;\nexport const DEFAULT_LIST_LIMIT = 20;\nexport const MAX_LIST_LIMIT = 100;\nconst EPOCH_MS_MIN_DIGITS = 10;\nconst EPOCH_MS = new RegExp(`^\\\\d{${EPOCH_MS_MIN_DIGITS},}$`);\n\nexport const TIME_HELP =\n 'An ISO 8601 time, epoch milliseconds, or a time ago such as \"30m\", \"2h\" or \"7d\".';\n\nexport const READ_ONLY = { readOnlyHint: true } as const;\n\nexport function time(\n value: unknown,\n name: string,\n now: number,\n): number | undefined {\n if (value === undefined) return undefined;\n if (typeof value === \"number\" && Number.isFinite(value)) return value;\n if (typeof value === \"string\") {\n if (EPOCH_MS.test(value.trim())) return Number(value.trim());\n const ago = /^(\\d+)\\s*([smhd])$/.exec(value.trim());\n if (ago) return now - Number(ago[1]) * UNITS[ago[2] as keyof typeof UNITS];\n const parsed = Date.parse(value);\n if (!Number.isNaN(parsed)) return parsed;\n }\n throw new Error(\n `${name} must be an ISO 8601 time, epoch milliseconds, or a time ago such as \"30m\", \"2h\" or \"7d\".`,\n );\n}\n\nexport function window(args: Args, defaultSpanMs: number) {\n const now = Date.now();\n const to = time(args.to, \"to\", now) ?? now;\n const from = time(args.from, \"from\", now) ?? to - defaultSpanMs;\n if (from > to) throw new Error(\"from must not be after to.\");\n return { from, to };\n}\n\nexport function integer(\n args: Args,\n name: string,\n min: number,\n max: number,\n fallback?: number,\n): number | undefined {\n const value = args[name];\n if (value === undefined) return fallback;\n if (typeof value !== \"number\" || !Number.isInteger(value))\n throw new Error(`${name} must be a whole number.`);\n return Math.min(Math.max(value, min), max);\n}\n\nexport function text(args: Args, name: string): string | undefined {\n const value = args[name];\n if (value === undefined) return undefined;\n if (typeof value !== \"string\") throw new Error(`${name} must be a string.`);\n return value.trim() || undefined;\n}\n\nexport const iso = (ms: number) => new Date(ms).toISOString();\nexport const round = (ms: number | undefined) =>\n ms === undefined ? undefined : Math.round(ms * 10) / 10;\nexport const cut = (value: string | undefined, limit: number) =>\n value !== undefined && value.length > limit\n ? `${value.slice(0, limit)}… [${value.length - limit} more characters]`\n : value;\nexport const compactJson = (value: unknown) => JSON.stringify(value);\n","import type { ApiDocument } from \"@brickkit/core\";\nimport {\n compactJson,\n cut,\n READ_ONLY,\n text,\n type Args,\n type BuiltInTool,\n type McpSources,\n} from \"./dashboard-mcp-args\";\nimport type { DocsNode } from \"./dashboard-protocol\";\n\n/*\n * The APIs and Docs views, for a coding agent: the app's OpenAPI documents and\n * its developer documentation. The dashboard serves neither in production.\n */\n\n/** An answer about the OpenAPI document or a docs page is cut to about this many characters. */\nexport const MAX_DOCS_CHARS = 50_000;\nconst MAX_OPERATIONS_LISTED = 300;\nconst MAX_REFERENCED_SCHEMAS = 100;\n/** The last resort for an operation too large to show: how much of it to try, each time half as much. */\nconst PREVIEW_CHARS_MOST_FIRST = [25_000, 10_000, 2_000] as const;\nconst MAX_NAMED_SCHEMAS = 20;\nconst MAX_NAME_CHARS = 200;\nconst HTTP_METHODS = [\n \"get\",\n \"put\",\n \"post\",\n \"delete\",\n \"options\",\n \"head\",\n \"patch\",\n \"trace\",\n] as const;\n\ntype Json = Record<string, any>;\n\nconst sameName = (a: string, b: string) => a.toLowerCase() === b.toLowerCase();\n\nfunction pickDocument(documents: ApiDocument[], name: string | undefined) {\n const found = name\n ? documents.find((item) => sameName(item.title, name))\n : documents[0];\n if (!found)\n throw new Error(\n `No OpenAPI document called ${name}. The app has: ${documents.map((item) => item.title).join(\", \")}.`,\n );\n return found;\n}\n\n/** Each operation of a document: its method and path, and the operation object. */\nfunction operationsOf(document: Json) {\n const found: { method: string; path: string; operation: Json }[] = [];\n for (const [path, item] of Object.entries<Json>(document.paths ?? {}))\n for (const method of HTTP_METHODS)\n if (item?.[method]) found.push({ method, path, operation: item[method] });\n return found;\n}\n\n/** `GET /api/pages/:id` and `get /api/pages/{id}` are the same operation. */\nconst normalizePath = (path: string) => path.replace(/:(\\w+)/g, \"{$1}\");\n\nfunction findOperation(document: Json, wanted: string) {\n const operations = operationsOf(document);\n const spaced = /^(\\w+)\\s+(\\S+)$/.exec(wanted.trim());\n const found = spaced\n ? operations.find(\n (item) =>\n sameName(item.method, spaced[1]!) &&\n item.path === normalizePath(spaced[2]!),\n )\n : operations.find((item) => item.operation.operationId === wanted.trim());\n if (!found)\n throw new Error(\n `No operation ${wanted} in that document. Call get_openapi without operation to list them.`,\n );\n return found;\n}\n\n/** The schemas an operation points to with `$ref`, and those they point to in turn. */\nfunction referencedSchemas(document: Json, operation: Json) {\n const schemas: Record<string, unknown> = {};\n const pending: unknown[] = [operation];\n while (\n pending.length &&\n Object.keys(schemas).length < MAX_REFERENCED_SCHEMAS\n ) {\n const value = pending.pop();\n if (Array.isArray(value)) pending.push(...value);\n else if (value && typeof value === \"object\")\n for (const [key, entry] of Object.entries(value)) {\n if (key === \"$ref\" && typeof entry === \"string\") {\n const target = entry.startsWith(\"#/\")\n ? entry\n .slice(2)\n .split(\"/\")\n .reduce<any>((at, part) => at?.[part], document)\n : undefined;\n if (target !== undefined && !(entry in schemas)) {\n schemas[entry] = target;\n pending.push(target);\n }\n } else pending.push(entry);\n }\n }\n return schemas;\n}\n\nfunction getOpenapi(documents: ApiDocument[], args: Args) {\n const { title, document } = pickDocument(documents, text(args, \"document\"));\n const wanted = text(args, \"operation\");\n if (!wanted) {\n const operations = operationsOf(document);\n const listed = operations.slice(0, MAX_OPERATIONS_LISTED);\n return compactJson({\n documents: documents.map((item) => item.title),\n document: title,\n info: document.info,\n servers: document.servers,\n operations: listed.map(({ method, path, operation }) => ({\n method: method.toUpperCase(),\n path,\n operationId: operation.operationId,\n summary: operation.summary,\n tags: operation.tags,\n })),\n ...(listed.length < operations.length\n ? {\n note: `${operations.length - listed.length} more operations are left out. Ask for one by operation.`,\n }\n : {}),\n });\n }\n const { method, path, operation } = findOperation(document, wanted);\n const schemas = referencedSchemas(document, operation);\n const answer = (\n parts: { schemas: unknown; operation: unknown },\n note?: string,\n ) =>\n compactJson({\n document: cut(title, MAX_NAME_CHARS),\n method: method.toUpperCase(),\n path: cut(path, MAX_NAME_CHARS),\n operation: parts.operation,\n referenced: parts.schemas,\n ...(note ? { note } : {}),\n });\n let result = answer({ operation, schemas });\n if (result.length <= MAX_DOCS_CHARS) return result;\n // Too big: keep the operation, and name the schemas it points to instead of showing them.\n result = answer(\n { operation, schemas: Object.keys(schemas) },\n \"Cut to fit about 50 KB: the schemas the operation refers to are named, not shown.\",\n );\n if (result.length <= MAX_DOCS_CHARS) return result;\n // Still too big: show only its start, as little as it takes to fit (escaping\n // can double a preview), and in the end none of it.\n const names = Object.keys(schemas)\n .slice(0, MAX_NAMED_SCHEMAS)\n .map((name) => cut(name, MAX_NAME_CHARS));\n const json = JSON.stringify(operation);\n for (const chars of PREVIEW_CHARS_MOST_FIRST) {\n result = answer(\n { operation: { preview: cut(json, chars) }, schemas: names },\n \"Cut to fit about 50 KB: the operation itself is too large, so only its start is shown.\",\n );\n if (result.length <= MAX_DOCS_CHARS) return result;\n }\n return answer(\n { operation: \"left out\", schemas: names },\n `The operation is ${json.length} characters long, too large to show even cut down. Read it in the dashboard's APIs view.`,\n );\n}\n\ninterface DocsEntry {\n path: string;\n title: string;\n description?: string;\n section?: string;\n}\n\n/** The pages of the docs tree in order, each with the folders it sits in. */\nfunction pagesOf(nodes: DocsNode[], section?: string): DocsEntry[] {\n return nodes.flatMap((node): DocsEntry[] => {\n if (node.type === \"page\")\n return [\n {\n path: node.url.replace(/^\\//, \"\"),\n title: node.name,\n description: node.description,\n section,\n },\n ];\n if (node.type !== \"folder\") return [];\n return [\n ...(node.index\n ? [\n {\n path: node.index.url.replace(/^\\//, \"\"),\n title: node.index.name,\n section: node.name,\n },\n ]\n : []),\n ...pagesOf(node.children, node.name),\n ];\n });\n}\n\n/** What the APIs view and the Docs view show, while the dashboard serves them. */\nexport function docsTools(sources: McpSources): BuiltInTool[] {\n const dev = sources.mode === \"dev\";\n const documents = () => sources.store.apiDocuments();\n const docs = () => (dev ? sources.docs?.() : undefined);\n return [\n {\n definition: {\n name: \"get_openapi\",\n description:\n 'The app\\'s OpenAPI documents, as the APIs view renders them. Without operation it lists the operations of one document (method, path, operation id, summary, tags) with its info and servers. With operation (\"POST /api/orders/order\" or an operation id) it returns that operation in full, with the schemas it refers to. Output is cut to about 50 KB and says what was left out. Only under `brick dev`.',\n inputSchema: {\n type: \"object\",\n properties: {\n document: {\n type: \"string\",\n description:\n \"The document's title. Default: the first, which is the app's own.\",\n },\n operation: {\n type: \"string\",\n description:\n 'One operation: \"METHOD /path\" (the path as in the document, `{id}` or `:id`), or its operationId.',\n },\n },\n additionalProperties: false,\n },\n annotations: READ_ONLY,\n },\n available: () => dev && documents().length > 0,\n run: (args) => getOpenapi(documents(), args),\n },\n {\n definition: {\n name: \"list_docs\",\n description:\n \"The app's developer documentation, as the Docs view lists it: each page's path, title and description, in order, with the section it sits in. Open one with read_doc. Only under `brick dev`, and only for an app that sets `documentation`.\",\n inputSchema: {\n type: \"object\",\n properties: {},\n additionalProperties: false,\n },\n annotations: READ_ONLY,\n },\n available: () => docs() !== undefined,\n run: () => {\n const { tree } = docs()!.info();\n return compactJson({ title: tree.name, pages: pagesOf(tree.children) });\n },\n },\n {\n definition: {\n name: \"read_doc\",\n description: `One page of the app's developer documentation, by path: its title, description and source (Markdown or MDX, without the frontmatter), cut to about ${MAX_DOCS_CHARS / 1000} KB with a note when it is longer. Only under \\`brick dev\\`, and only for an app that sets \\`documentation\\`.`,\n inputSchema: {\n type: \"object\",\n properties: {\n path: {\n type: \"string\",\n description:\n 'From list_docs, such as \"guide/setup\". The home page is \"\" or \"/\".',\n },\n },\n required: [\"path\"],\n additionalProperties: false,\n },\n annotations: READ_ONLY,\n },\n available: () => docs() !== undefined,\n run: (args) => {\n const path = args.path;\n if (typeof path !== \"string\") throw new Error(\"path is required.\");\n const page = docs()!.source(path.split(\"/\").filter(Boolean));\n if (!page)\n throw new Error(\n `No docs page at ${JSON.stringify(path)}. Call list_docs for the paths.`,\n );\n return compactJson({\n title: page.title,\n description: page.description,\n file: page.path,\n content: cut(page.content, MAX_DOCS_CHARS),\n ...(page.content.length > MAX_DOCS_CHARS\n ? {\n note: `The page is ${page.content.length} characters long and was cut to ${MAX_DOCS_CHARS}.`,\n }\n : {}),\n });\n },\n },\n ];\n}\n\nexport const DOCS_TOOL_NAMES = [\n \"get_openapi\",\n \"list_docs\",\n \"read_doc\",\n] as const;\n","import { existsSync, mkdirSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport {\n ATTR,\n HISTORY_PAGE_SIZE,\n SPAN,\n type FacetValue,\n type HistoryFacets,\n type HistoryInfo,\n type HistorySummary,\n type HistoryTrace,\n type Outcome,\n type SpanOutcome,\n type TraceSummary,\n type VolumeBucket,\n} from \"./dashboard-protocol\";\nimport {\n bucketSize,\n CLIENT_ERROR,\n endpointOf,\n LOG_LEVELS,\n MAX_FACET_VALUES,\n percentile,\n SEARCHED,\n SERVER_ERROR,\n tracesToCsv,\n type EndpointStats,\n type Facet,\n type HistoryQuery,\n type LogLevel,\n type LogLine,\n type LogSearch,\n} from \"./dashboard-query\";\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 MAX_LIMIT = 500;\nconst MAX_EXPORT_ROWS = 100_000;\n/** A log search reads the spans of this many requests, the newest of its window. */\nexport const MAX_SCANNED_REQUESTS = 20_000;\n/** A text search reads at most this many log lines, newest first, of those requests. */\nexport const MAX_SCANNED_LOG_LINES = 100_000;\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, options.warn);\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\nconst LOG_LEVEL_SQL = `CASE WHEN json_extract(event.value, '$.attributes.\"${ATTR.logLevel}\"') IN (${LOG_LEVELS.map((level) => `'${level}'`).join(\", \")})\n THEN json_extract(event.value, '$.attributes.\"${ATTR.logLevel}\"') ELSE 'info' END`;\nconst LOG_MESSAGE_SQL = `COALESCE(json_extract(event.value, '$.attributes.\"${ATTR.logMessage}\"'), '')`;\n\n/** Each row's outcome, by the rules of `outcomeOf`. */\nconst OUTCOME_CASE = `CASE\n WHEN status = 'error' OR http_status >= ${SERVER_ERROR} THEN 'server'\n WHEN http_status >= ${CLIENT_ERROR} THEN 'client'\n ELSE 'ok' END`;\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\") anyOf(OUTCOME_CASE, query.outcomes);\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 `(${SEARCHED.map((column) => `${column} LIKE ? ESCAPE '\\\\'`).join(\" OR \")})`,\n );\n params.push(...SEARCHED.map(() => pattern));\n }\n return { sql: clauses.join(\" AND \"), params };\n}\n\nconst orderSql = (sort: HistoryQuery[\"sort\"]) =>\n sort === \"slowest\" ? \"duration_ms DESC, start_ms DESC\" : \"start_ms DESC\";\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 readonly #warn?: (message: string) => void;\n /** Failure kinds already reported: one warning each, not one per batch. */\n readonly #warned = new Set<string>();\n\n constructor(\n database: Database,\n days: number,\n warn?: (message: string) => void,\n ) {\n this.#database = database;\n this.days = days;\n this.#warn = warn;\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 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 endpointOf(trace),\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 (error) {\n // A failed write loses a batch of history; it must not break the app.\n this.#warnOnce(\"save requests to\", error);\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 (error) {\n // Pruning is housekeeping; try again next time.\n this.#warnOnce(\"prune\", error);\n }\n }\n\n #warnOnce(action: string, error: unknown): void {\n if (this.#warned.has(action)) return;\n this.#warned.add(action);\n const reason = error instanceof Error ? error.message : String(error);\n this.#warn?.(\n `[Brick-TS] Could not ${action} the request history (${reason}).`,\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 ?? HISTORY_PAGE_SIZE, 1),\n MAX_LIMIT,\n );\n const offset = Math.max(query.offset ?? 0, 0);\n const rows = this.#database\n .prepare(\n `SELECT ${LIST_COLUMNS}\n FROM traces WHERE ${sql} ORDER BY ${orderSql(query.sort)} 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 = bucketSize(query.from, query.to, buckets);\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 rows = this.#database\n .prepare(\n `SELECT ${LIST_COLUMNS}\n FROM traces WHERE ${sql} ORDER BY ${orderSql(query.sort)} LIMIT ?`,\n )\n .all(...params, MAX_EXPORT_ROWS);\n return tracesToCsv(rows.map(toHistoryTrace));\n }\n\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 /**\n * Log lines (span events named `log`) of the requests in a window, newest\n * first, found with SQLite's JSON functions over each request's stored spans.\n * Only the newest `MAX_SCANNED_REQUESTS` requests of the window are searched;\n * `requestsInWindow` says how many it held. SQLite's `LIKE` folds only\n * ASCII, so text is matched here, as the in-memory search does, over at most\n * `MAX_SCANNED_LOG_LINES` lines; `linesCapped` says it stopped there.\n */\n searchLogLines(\n search: LogSearch,\n page: { limit: number; offset: number },\n ): { lines: LogLine[]; requestsInWindow: number; linesCapped: boolean } {\n this.flush();\n const { sql, params } = filterSql({\n from: search.from,\n to: search.to,\n endpoints: search.endpoint ? [search.endpoint] : undefined,\n services: search.service ? [search.service] : undefined,\n });\n const requestsInWindow = Number(\n this.#database\n .prepare(`SELECT COUNT(*) AS n FROM traces WHERE ${sql}`)\n .get(...params)?.n ?? 0,\n );\n const clauses = [\n `json_extract(event.value, '$.name') = '${SPAN.logEvent}'`,\n ];\n const filters: unknown[] = [];\n if (search.level) {\n clauses.push(`${LOG_LEVEL_SQL} = ?`);\n filters.push(search.level);\n }\n const needle = search.query?.toLowerCase();\n const rows = this.#database\n .prepare(\n `WITH newest AS (\n SELECT trace_id, endpoint, spans FROM traces WHERE ${sql}\n ORDER BY start_ms DESC LIMIT ?)\n SELECT newest.trace_id, newest.endpoint,\n json_extract(span.value, '$.name') AS span_name,\n json_extract(event.value, '$.timeMs') AS time_ms,\n ${LOG_LEVEL_SQL} AS level, ${LOG_MESSAGE_SQL} AS message,\n span.key AS span_index, event.key AS event_index\n FROM newest, json_each(newest.spans) AS span,\n json_each(span.value, '$.events') AS event\n WHERE ${clauses.join(\" AND \")}\n ORDER BY time_ms DESC, newest.trace_id ASC, span_index ASC, event_index ASC\n LIMIT ? OFFSET ?`,\n )\n .all(\n ...params,\n MAX_SCANNED_REQUESTS,\n ...filters,\n needle === undefined ? page.limit : MAX_SCANNED_LOG_LINES,\n needle === undefined ? page.offset : 0,\n );\n const lines = rows\n .map((row) => ({\n timeMs: Number(row.time_ms),\n level: String(row.level) as LogLevel,\n message: String(row.message),\n traceId: String(row.trace_id),\n endpoint: String(row.endpoint),\n span: String(row.span_name),\n spanIndex: Number(row.span_index),\n eventIndex: Number(row.event_index),\n }))\n .filter(\n (line) =>\n needle === undefined || line.message.toLowerCase().includes(needle),\n );\n return {\n requestsInWindow,\n lines:\n needle === undefined\n ? lines\n : lines.slice(page.offset, page.offset + page.limit),\n linesCapped:\n needle !== undefined && rows.length === MAX_SCANNED_LOG_LINES,\n };\n }\n\n slowestEndpoints(query: HistoryQuery, limit: number): EndpointStats[] {\n this.flush();\n const { sql, params } = filterSql(query);\n return this.#database\n .prepare(\n `SELECT endpoint, COUNT(*) AS n,\n SUM(CASE WHEN ${OUTCOME_CASE} = 'server' THEN 1 ELSE 0 END) AS errors,\n AVG(duration_ms) AS avg_ms, MAX(duration_ms) AS max_ms\n FROM traces WHERE ${sql} AND duration_ms IS NOT NULL\n GROUP BY endpoint ORDER BY avg_ms DESC, n DESC LIMIT ?`,\n )\n .all(...params, limit)\n .map((row) => ({\n endpoint: String(row.endpoint),\n requests: Number(row.n),\n serverErrors: Number(row.errors),\n avgMs: Number(row.avg_ms),\n maxMs: Number(row.max_ms),\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","import {\n compactJson,\n cut,\n DAY,\n DEFAULT_LIST_LIMIT,\n integer,\n iso,\n MAX_LIST_LIMIT,\n READ_ONLY,\n text,\n time,\n TIME_HELP,\n window,\n type BuiltInTool,\n type McpSources,\n} from \"./dashboard-mcp-args\";\nimport {\n LOG_LEVELS,\n searchLogLines,\n type LogLevel,\n type LogLine,\n type LogSearch,\n} from \"./dashboard-query\";\nimport { MAX_SCANNED_LOG_LINES, MAX_SCANNED_REQUESTS } from \"./dev-history\";\n\nconst DEFAULT_LOG_LIMIT = 50;\nconst MAX_LOG_LIMIT = 200;\nconst MAX_MESSAGE_CHARS = 500;\n\nfunction hit(line: LogLine) {\n return {\n time: iso(line.timeMs),\n level: line.level,\n message: cut(line.message, MAX_MESSAGE_CHARS),\n traceId: line.traceId,\n endpoint: line.endpoint,\n span: line.span,\n };\n}\n\nfunction searchLogs(sources: McpSources, args: Record<string, unknown>) {\n const { from, to } = window(args, DAY);\n const level = text(args, \"level\");\n if (level && !LOG_LEVELS.includes(level as LogLevel))\n throw new Error(`level must be one of: ${LOG_LEVELS.join(\", \")}.`);\n const search: LogSearch = {\n from,\n to,\n query: text(args, \"query\"),\n level: level as LogLevel | undefined,\n service: text(args, \"service\"),\n endpoint: text(args, \"endpoint\"),\n };\n const limit = integer(args, \"limit\", 1, MAX_LOG_LIMIT, DEFAULT_LOG_LIMIT)!;\n const offset = integer(args, \"offset\", 0, Number.MAX_SAFE_INTEGER, 0)!;\n // One line more than asked for tells whether there is a next page.\n const { history, store } = sources;\n let found: LogLine[];\n let note: string | undefined;\n if (history) {\n const stored = history.searchLogLines(search, {\n limit: limit + 1,\n offset,\n });\n found = stored.lines;\n if (stored.requestsInWindow > MAX_SCANNED_REQUESTS)\n note = `The window holds ${stored.requestsInWindow} requests and only the newest ${MAX_SCANNED_REQUESTS} were searched. Narrow from and to to search older ones.`;\n if (stored.linesCapped)\n note = `${note ? `${note} ` : \"\"}The text was looked for in the newest ${MAX_SCANNED_LOG_LINES} log lines only. Narrow from and to, or add level, service or endpoint, to search older ones.`;\n } else {\n found = searchLogLines(store.snapshot().traces, search).slice(\n offset,\n offset + limit + 1,\n );\n }\n const lines = found.slice(0, limit);\n return compactJson({\n window: { from: iso(from), to: iso(to) },\n source: history ? \"history\" : \"memory\",\n offset,\n ...(found.length > limit ? { nextOffset: offset + limit } : {}),\n ...(note ? { note } : {}),\n lines: lines.map(hit),\n });\n}\n\nconst MAX_STACK_CHARS = 1500;\nconst MAX_CRASH_MESSAGE_CHARS = 500;\n\nfunction listReloads(sources: McpSources, args: Record<string, unknown>) {\n const since = time(args.from, \"from\", Date.now());\n const limit = integer(args, \"limit\", 1, MAX_LIST_LIMIT, DEFAULT_LIST_LIMIT)!;\n const { reloads, failures } = sources.store.snapshot();\n const recent = <T extends { at: number }>(items: T[]) =>\n items.filter((item) => since === undefined || item.at >= since);\n return compactJson({\n mode: sources.mode,\n reloads: recent(reloads)\n .slice(0, limit)\n .map((reload) => ({\n time: iso(reload.at),\n kind: reload.kind,\n generation: reload.generation,\n detail: reload.detail,\n })),\n // A request's failure is in list_errors; these are the process's own.\n crashes: recent(failures.filter((failure) => failure.phase !== \"request\"))\n .slice(0, limit)\n .map((crash) => ({\n time: iso(crash.at),\n kind: crash.phase,\n code: crash.code,\n message: cut(crash.message, MAX_CRASH_MESSAGE_CHARS),\n stack: cut(crash.stack, MAX_STACK_CHARS),\n generation: crash.generation,\n })),\n });\n}\n\n/** What the Logs view and the Reloads view list. */\nexport function logTools(sources: McpSources): BuiltInTool[] {\n return [\n {\n definition: {\n name: \"search_logs\",\n description: `Log lines written with ctx.logger or console during requests, newest first: time, level, message, trace id, endpoint and the span that wrote it. Search by text and level, then open a trace id with get_trace for the whole request. The window is on when the request started (default: the last 24 hours). Text matching ignores case, for any letters. With history it searches the newest ${MAX_SCANNED_REQUESTS} requests of the window, and for text the newest ${MAX_SCANNED_LOG_LINES} lines of them, and says when it left some out.`,\n inputSchema: {\n type: \"object\",\n properties: {\n query: {\n type: \"string\",\n description: \"Text the message contains, in any case.\",\n },\n level: {\n type: \"string\",\n enum: [...LOG_LEVELS],\n description: \"Only lines of this level.\",\n },\n service: {\n type: \"string\",\n description: \"Only requests handled by this service.\",\n },\n endpoint: {\n type: \"string\",\n description:\n 'Only this endpoint, as list_requests shows it: \"GET /api/pages/:id\".',\n },\n from: {\n type: \"string\",\n description: `Window start. ${TIME_HELP} Default: a day before \\`to\\`.`,\n },\n to: {\n type: \"string\",\n description: `Window end. ${TIME_HELP} Default: now.`,\n },\n limit: {\n type: \"integer\",\n minimum: 1,\n maximum: MAX_LOG_LIMIT,\n description: `Default ${DEFAULT_LOG_LIMIT}.`,\n },\n offset: {\n type: \"integer\",\n minimum: 0,\n description: \"Lines to skip, to page through.\",\n },\n },\n additionalProperties: false,\n },\n annotations: READ_ONLY,\n },\n run: (args) => searchLogs(sources, args),\n },\n {\n definition: {\n name: \"list_reloads\",\n description:\n 'What the Reloads view shows, newest first: each time the app started, restarted or exited (kind \"started\", \"restarting\", \"exited\" or \"contract-ready\"), why, and which generation of the process it was, and the crashes of the process itself with their error and stack: a failed startup, an uncaught exception, an unhandled rejection. Check it when the app seems to restart or does not come up. Under `brick start` the dashboard sees only the process it runs in, so it lists the one start of that process and no crashes.',\n inputSchema: {\n type: \"object\",\n properties: {\n from: {\n type: \"string\",\n description: `Only events after this. ${TIME_HELP}`,\n },\n limit: {\n type: \"integer\",\n minimum: 1,\n maximum: MAX_LIST_LIMIT,\n description: `Of each list. Default ${DEFAULT_LIST_LIMIT}.`,\n },\n },\n additionalProperties: false,\n },\n annotations: READ_ONLY,\n },\n run: (args) => listReloads(sources, args),\n },\n ];\n}\n\nexport const LOG_TOOL_NAMES = [\"search_logs\", \"list_reloads\"] as const;\n","import {\n compactJson,\n cut,\n DEFAULT_LIST_LIMIT,\n integer,\n MAX_LIST_LIMIT,\n READ_ONLY,\n text,\n TIME_HELP,\n time,\n type Args,\n type BuiltInTool,\n type McpSources,\n} from \"./dashboard-mcp-args\";\nimport {\n describeSchedule,\n INSPECTOR_READ_ONLY_HEADER,\n INSPECTOR_TOKEN_HEADER,\n ROUTES,\n} from \"./dashboard-protocol\";\n\n/*\n * The workflow runs and schedules the dashboard's Workflows and Schedules views\n * show, read from the workflow inspector the dashboard proxies. Every call is\n * marked read-only, so the inspector refuses whatever would change a run, and\n * only the reads below can be asked for.\n */\n\n/** The inspector's RPC methods these tools may call. All of them read. */\nconst READ_RPC = [\"fetchRuns\", \"fetchRun\", \"fetchEvents\"] as const;\ntype ReadRpc = (typeof READ_RPC)[number];\n\nconst RPC_PATH = `${ROUTES.workflows.path}/api/rpc`;\nconst INSPECTOR_TIMEOUT_MS = 10_000;\nconst RUN_STATUSES = [\n \"pending\",\n \"running\",\n \"completed\",\n \"failed\",\n \"cancelled\",\n] as const;\nconst RUNS_PER_PAGE = 100;\n/** A run list reads at most this many pages of runs to fill its limit. */\nconst MAX_RUN_PAGES = 10;\nconst EVENTS_PER_PAGE = 1000;\nconst MAX_EVENT_PAGES = 5;\nconst LAST_SCHEDULE_RUNS = 5;\nconst MAX_ERROR_CHARS = 500;\nconst MAX_ID_CHARS = 200;\n/** A `get_run` answer is cut to about this many characters of JSON. */\nexport const MAX_RUN_CHARS = 50_000;\n/** From mildest to harshest: the first that fits the cap is the answer. */\nconst RUN_LEVELS_MILDEST_FIRST = [\n { value: 2000, steps: 200, hooks: 200 },\n { value: 500, steps: 100, hooks: 100 },\n { value: 100, steps: 50, hooks: 50 },\n { value: 0, steps: 20, hooks: 20 },\n] as const;\n\ninterface InspectorTarget {\n port: number;\n token: string;\n}\n\nasync function askInspector(\n target: InspectorTarget,\n path: string,\n init: RequestInit = {},\n): Promise<Response> {\n return fetch(`http://127.0.0.1:${target.port}${path}`, {\n ...init,\n headers: {\n ...init.headers,\n [INSPECTOR_TOKEN_HEADER]: target.token,\n // The inspector refuses every call that changes something from this caller.\n [INSPECTOR_READ_ONLY_HEADER]: \"1\",\n },\n signal: AbortSignal.timeout(INSPECTOR_TIMEOUT_MS),\n });\n}\n\n/**\n * A hook's token resumes it from outside the dashboard, and only a signed-in\n * user may have it. The inspector sends none to a read-only caller; this takes\n * out any that is left, wherever it sits.\n */\nexport function withoutHookTokens<T>(value: T): T {\n if (Array.isArray(value)) return value.map(withoutHookTokens) as T;\n if (value === null || typeof value !== \"object\") return value;\n const row = value as Record<string, unknown>;\n const isHook =\n \"hookId\" in row || String(row.eventType ?? \"\").startsWith(\"hook_\");\n const kept: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(row)) {\n if (isHook && key === \"token\") continue;\n kept[key] =\n isHook && key === \"eventData\" && entry && typeof entry === \"object\"\n ? withoutHookTokens(\n Object.fromEntries(\n Object.entries(entry).filter(([name]) => name !== \"token\"),\n ),\n )\n : withoutHookTokens(entry);\n }\n return kept as T;\n}\n\n/** One read of the inspector's RPC: its `data`, or the error it answered. */\nexport async function inspectorRpc(\n target: InspectorTarget,\n method: ReadRpc,\n params: Record<string, unknown>,\n): Promise<any> {\n if (!READ_RPC.includes(method))\n throw new Error(`The dashboard's MCP does not call ${method}.`);\n const response = await askInspector(target, RPC_PATH, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n accept: \"application/json\",\n },\n body: JSON.stringify({ method, params }),\n });\n const answer = (await response.json().catch(() => undefined)) as\n | { success: boolean; data?: unknown; error?: { message?: string } }\n | undefined;\n if (!response.ok || !answer?.success)\n throw new Error(\n answer?.error?.message ??\n `The workflow inspector answered ${response.status}.`,\n );\n return withoutHookTokens(answer.data);\n}\n\n/** The last part of a workflow's machine name, `workflow//./src/orders//ship`: `ship`. */\nconst shortName = (workflowName: string) =>\n workflowName.split(\"//\").pop() || workflowName;\n\nconst dateOf = (value: unknown): number | undefined => {\n const parsed = typeof value === \"string\" ? Date.parse(value) : NaN;\n return Number.isNaN(parsed) ? undefined : parsed;\n};\n\nconst durationMs = (from: unknown, to: unknown) => {\n const start = dateOf(from);\n const end = dateOf(to);\n return start === undefined || end === undefined ? undefined : end - start;\n};\n\nfunction runRow(run: any) {\n return {\n runId: run.runId,\n workflow: shortName(String(run.workflowName)),\n status: run.status,\n createdAt: run.createdAt,\n startedAt: run.startedAt,\n completedAt: run.completedAt,\n durationMs: durationMs(run.startedAt ?? run.createdAt, run.completedAt),\n error: run.error?.message ? cut(String(run.error.message), 300) : undefined,\n };\n}\n\nasync function listRuns(target: InspectorTarget, args: Args) {\n const status = text(args, \"status\");\n if (status && !RUN_STATUSES.includes(status as never))\n throw new Error(`status must be one of: ${RUN_STATUSES.join(\", \")}.`);\n const workflow = text(args, \"workflow\");\n const now = Date.now();\n const from = time(args.from, \"from\", now);\n const to = time(args.to, \"to\", now) ?? now;\n if (from !== undefined && from > to)\n throw new Error(\"from must not be after to.\");\n const limit = integer(args, \"limit\", 1, MAX_LIST_LIMIT, DEFAULT_LIST_LIMIT)!;\n const found: any[] = [];\n let cursor: string | undefined;\n let more = false;\n let scanned = 0;\n // Newest first: stop at a run older than the window, or when there is enough.\n for (let page = 0; page < MAX_RUN_PAGES && found.length <= limit; page++) {\n const answer = await inspectorRpc(target, \"fetchRuns\", {\n limit: RUNS_PER_PAGE,\n sortOrder: \"desc\",\n cursor,\n ...(status ? { status } : {}),\n });\n let passedWindow = false;\n scanned += (answer.data as any[]).length;\n for (const run of answer.data as any[]) {\n const created = dateOf(run.createdAt) ?? 0;\n if (from !== undefined && created < from) {\n passedWindow = true;\n break;\n }\n if (created > to) continue;\n if (\n workflow &&\n run.workflowName !== workflow &&\n shortName(String(run.workflowName)) !== workflow\n )\n continue;\n found.push(run);\n }\n more = Boolean(answer.hasMore) && !passedWindow;\n cursor = answer.cursor ?? undefined;\n if (!more || !cursor) break;\n }\n // The page budget ran out with runs left to read and too few found.\n const cutShort = more && found.length <= limit;\n return compactJson({\n runs: found.slice(0, limit).map(runRow),\n ...(found.length > limit ? { hasMore: true } : {}),\n ...(cutShort\n ? {\n truncated: true,\n note: `Only the newest ${scanned} runs were looked through, and older ones may match. Narrow it with from, status or workflow.`,\n }\n : {}),\n });\n}\n\ninterface Level {\n value: number;\n steps: number;\n hooks: number;\n}\n\n/** A value as it is, or a preview of its JSON when that is longer than `limit`. */\nfunction bounded(value: unknown, limit: number): unknown {\n if (value === undefined) return undefined;\n const json = JSON.stringify(value) ?? \"\";\n if (json.length <= limit) return value;\n return limit === 0\n ? { left: \"out\", chars: json.length }\n : { preview: cut(json, limit), chars: json.length };\n}\n\n/** A run's steps, from the events that record them: a step's events share a correlation id. */\nfunction stepsOf(events: any[]) {\n const steps = new Map<string, any>();\n for (const event of events) {\n if (!String(event.eventType).startsWith(\"step_\") || !event.correlationId)\n continue;\n const step = steps.get(event.correlationId) ?? {\n stepId: event.correlationId,\n status: \"pending\",\n attempts: 0,\n retries: [] as unknown[],\n };\n steps.set(event.correlationId, step);\n const data = event.eventData ?? {};\n step.name ??= data.stepName;\n step.createdAt ??= event.createdAt;\n switch (event.eventType) {\n case \"step_started\":\n step.status = \"running\";\n step.attempts += 1;\n step.startedAt ??= event.createdAt;\n step.completedAt = undefined;\n if (data.input !== undefined) step.input ??= data.input;\n break;\n case \"step_created\":\n if (data.input !== undefined) step.input ??= data.input;\n break;\n case \"step_retrying\":\n step.status = \"pending\";\n step.retries.push({\n attempt: data.attempt,\n error: data.error,\n retryAfter: data.retryAfter,\n });\n break;\n case \"step_completed\":\n step.status = \"completed\";\n step.completedAt = event.createdAt;\n step.output = data.result;\n break;\n case \"step_failed\":\n step.status = \"failed\";\n step.completedAt = event.createdAt;\n step.error = data.error;\n break;\n }\n }\n return [...steps.values()];\n}\n\nfunction hooksOf(events: any[]) {\n const hooks = new Map<string, any>();\n for (const event of events) {\n if (!String(event.eventType).startsWith(\"hook_\") || !event.correlationId)\n continue;\n const hook = hooks.get(event.correlationId) ?? {\n hookId: event.correlationId,\n received: 0,\n disposed: false,\n };\n hooks.set(event.correlationId, hook);\n if (event.eventType === \"hook_created\") hook.createdAt = event.createdAt;\n if (event.eventType === \"hook_received\") hook.received += 1;\n if (event.eventType === \"hook_disposed\") hook.disposed = true;\n }\n return [...hooks.values()];\n}\n\nfunction runAnswer(\n run: any,\n steps: any[],\n hooks: any[],\n eventsRead: number,\n moreEvents: boolean,\n level: Level,\n) {\n const shown = steps.slice(0, level.steps);\n const shownHooks = hooks.slice(0, level.hooks);\n return {\n runId: run.runId,\n workflow: shortName(String(run.workflowName)),\n workflowName: run.workflowName,\n status: run.status,\n createdAt: run.createdAt,\n startedAt: run.startedAt,\n completedAt: run.completedAt,\n durationMs: durationMs(run.startedAt ?? run.createdAt, run.completedAt),\n input: bounded(run.input, level.value),\n output: bounded(run.output, level.value),\n error: run.error && {\n message: cut(String(run.error.message ?? \"\"), MAX_ERROR_CHARS),\n stack: cut(run.error.stack, Math.max(level.value, 0)),\n },\n steps: shown.map((step) => ({\n stepId: step.stepId,\n name: step.name,\n status: step.status,\n attempts: step.attempts,\n createdAt: step.createdAt,\n startedAt: step.startedAt,\n completedAt: step.completedAt,\n durationMs: durationMs(step.startedAt, step.completedAt),\n input: bounded(step.input, level.value),\n output: bounded(step.output, level.value),\n error: bounded(step.error, level.value),\n retries: bounded(\n step.retries.length ? step.retries : undefined,\n level.value,\n ),\n })),\n hooks: shownHooks,\n note:\n shown.length < steps.length ||\n shownHooks.length < hooks.length ||\n moreEvents ||\n level !== RUN_LEVELS_MILDEST_FIRST[0]\n ? `Cut to fit about ${MAX_RUN_CHARS / 1000} KB.${shown.length < steps.length ? ` ${steps.length - shown.length} steps are left out.` : \"\"}${shownHooks.length < hooks.length ? ` ${hooks.length - shownHooks.length} hooks are left out.` : \"\"}${level !== RUN_LEVELS_MILDEST_FIRST[0] ? \" Long inputs, outputs and errors are shortened or left out.\" : \"\"}${moreEvents ? ` Only the first ${eventsRead} events were read, so later steps may be missing.` : \"\"}`\n : undefined,\n };\n}\n\nasync function getRun(target: InspectorTarget, args: Args) {\n const runId = text(args, \"run_id\");\n if (!runId) throw new Error(\"run_id is required.\");\n const run = await inspectorRpc(target, \"fetchRun\", { runId });\n const events: any[] = [];\n let cursor: string | undefined;\n let moreEvents = false;\n for (let page = 0; page < MAX_EVENT_PAGES; page++) {\n const answer = await inspectorRpc(target, \"fetchEvents\", {\n runId,\n withData: true,\n sortOrder: \"asc\",\n limit: EVENTS_PER_PAGE,\n cursor,\n });\n events.push(...answer.data);\n cursor = answer.cursor ?? undefined;\n moreEvents = Boolean(answer.hasMore);\n if (!moreEvents || !cursor) break;\n }\n const steps = stepsOf(events);\n const hooks = hooksOf(events);\n for (const level of RUN_LEVELS_MILDEST_FIRST) {\n const answer = compactJson(\n runAnswer(run, steps, hooks, events.length, moreEvents, level),\n );\n if (answer.length <= MAX_RUN_CHARS) return answer;\n }\n // Even the harshest cut is too big: the run's own facts, and how much there is.\n return compactJson({\n runId: cut(String(run.runId), MAX_ID_CHARS),\n workflow: cut(shortName(String(run.workflowName)), MAX_ID_CHARS),\n status: run.status,\n createdAt: run.createdAt,\n completedAt: run.completedAt,\n steps: steps.length,\n hooks: hooks.length,\n note: `This run is too large to send even cut down, so its details are left out: ${steps.length} steps, ${hooks.length} hooks. Open it in the dashboard's Workflows view.`,\n });\n}\n\nasync function listSchedules(target: InspectorTarget) {\n const response = await askInspector(target, ROUTES.schedules.path);\n if (!response.ok)\n throw new Error(`The schedules answered ${response.status}.`);\n const schedules = withoutHookTokens(await response.json()) as any[];\n return compactJson({\n schedules: schedules.map((schedule) => ({\n name: schedule.name,\n kind: schedule.kind,\n schedule: describeSchedule(schedule),\n enabled: schedule.enabled,\n running: schedule.running,\n nextRunAt: schedule.nextRunAt,\n attempts: schedule.attempts,\n lastSuccessAt: schedule.lastSuccessAt,\n lastRuns: (schedule.runs ?? [])\n .slice(0, LAST_SCHEDULE_RUNS)\n .map((run: any) => ({\n slot: run.slot,\n trigger: run.trigger,\n attempt: run.attempt,\n startedAt: run.startedAt,\n finishedAt: run.finishedAt,\n outcome: run.outcome,\n error: cut(run.error, MAX_ERROR_CHARS),\n })),\n })),\n });\n}\n\n/** The Schedules and Workflows views, while the dashboard serves the inspector. */\nexport function workflowTools(sources: McpSources): BuiltInTool[] {\n const { store } = sources;\n const served = () =>\n sources.inspector ? store.inspectorTarget() : undefined;\n const hasSchedules = () =>\n Boolean(served() && store.architecture()?.schema.events?.schedules?.length);\n const hasWorkflows = () => Boolean(served() && store.servesWorkflows());\n const target = () => {\n const found = served();\n if (!found) throw new Error(\"The workflow inspector is not being served.\");\n return found;\n };\n return [\n {\n definition: {\n name: \"list_schedules\",\n description:\n \"The app's schedules, as the Schedules view shows them: each one's name, kind (handler or workflow), cron or interval, whether it is enabled and running, when it is next due, when it last succeeded, and its last five runs with their outcome (succeeded, failed or skipped) and error. Look here when something that should run on a timer did not.\",\n inputSchema: {\n type: \"object\",\n properties: {},\n additionalProperties: false,\n },\n annotations: READ_ONLY,\n },\n available: hasSchedules,\n run: () => listSchedules(target()),\n },\n {\n definition: {\n name: \"list_runs\",\n description: `Workflow runs, newest first, as the Workflows view lists them: run id, workflow, status, when it was created and finished, how long it took, and its error. Filter by status (pending, running, completed, failed or cancelled), workflow name and time window. Start with status \"failed\", then open one with get_run. It reads up to ${MAX_RUN_PAGES * RUNS_PER_PAGE} runs to fill the limit.`,\n inputSchema: {\n type: \"object\",\n properties: {\n status: {\n type: \"string\",\n enum: [...RUN_STATUSES],\n description: \"Only runs in this state.\",\n },\n workflow: {\n type: \"string\",\n description:\n \"Only runs of this workflow, by the name list_runs shows.\",\n },\n from: {\n type: \"string\",\n description: `Only runs created after this. ${TIME_HELP}`,\n },\n to: {\n type: \"string\",\n description: `Only runs created before this. ${TIME_HELP} Default: now.`,\n },\n limit: {\n type: \"integer\",\n minimum: 1,\n maximum: MAX_LIST_LIMIT,\n description: `Default ${DEFAULT_LIST_LIMIT}.`,\n },\n },\n additionalProperties: false,\n },\n annotations: READ_ONLY,\n },\n available: hasWorkflows,\n run: (args) => listRuns(target(), args),\n },\n {\n definition: {\n name: \"get_run\",\n description: `One workflow run in full, by run id: its input, output and error, and each step with its status, attempts, timing, input, output, error and retries, and its hooks (by id, never their tokens). Long values are shortened and the answer is cut to about ${MAX_RUN_CHARS / 1000} KB, and says what was left out.`,\n inputSchema: {\n type: \"object\",\n properties: {\n run_id: { type: \"string\", description: \"From list_runs.\" },\n },\n required: [\"run_id\"],\n additionalProperties: false,\n },\n annotations: READ_ONLY,\n },\n available: hasWorkflows,\n run: (args) => getRun(target(), args),\n },\n ];\n}\n\nexport const WORKFLOW_TOOL_NAMES = [\n \"list_schedules\",\n \"list_runs\",\n \"get_run\",\n] as const;\n","import {\n createMcpHandler,\n DASHBOARD_IDENTITY_HEADER,\n DASHBOARD_MCP_ROUTE,\n signDashboardMcp,\n UnknownToolError,\n WRAP_RESULT,\n type DashboardIdentity,\n type DashboardMcpCaller,\n type McpRegistry,\n type McpToolDefinition,\n} from \"@brickkit/core\";\nimport cliPkg from \"../package.json\";\nimport {\n ATTR,\n SPAN,\n type HistoryFacets,\n type HistorySummary,\n type HistoryTrace,\n type Outcome,\n type TraceSpan,\n type TraceSummary,\n} from \"./dashboard-protocol\";\nimport {\n applyFilters,\n computeFacets,\n slowestEndpoints,\n type EndpointStats,\n findException,\n OUTCOMES,\n outcomeOf,\n SERVER_ERROR,\n stringAttribute,\n summarizeRows,\n toRow,\n type HistoryQuery,\n} from \"./dashboard-query\";\nimport { DOCS_TOOL_NAMES, docsTools } from \"./dashboard-mcp-docs\";\nimport { LOG_TOOL_NAMES, logTools } from \"./dashboard-mcp-logs\";\nimport { WORKFLOW_TOOL_NAMES, workflowTools } from \"./dashboard-mcp-workflows\";\nimport {\n compactJson,\n cut,\n DAY,\n DEFAULT_LIST_LIMIT,\n integer,\n iso,\n MAX_LIST_LIMIT,\n MINUTE,\n READ_ONLY,\n round,\n text,\n time,\n TIME_HELP,\n window,\n type Args,\n type BuiltInTool,\n type McpSources,\n} from \"./dashboard-mcp-args\";\nimport type { DevHistory } from \"./dev-history\";\nimport type { DevTelemetryStore } from \"./dev-telemetry-store\";\n\n/*\n * The five built-in tools only read, for every caller, a signed-in user\n * included: log lines carry what end users typed, and an agent that reads them\n * must not be able to act on them.\n */\n\nconst SLOWEST_ENDPOINTS = 5;\nexport const MAX_TRACE_CHARS = 50_000;\nconst TRACE_LEVELS_MILDEST_FIRST = [\n { text: 2000, attributes: 40, events: 50, spans: 300 },\n { text: 500, attributes: 20, events: 20, spans: 150 },\n { text: 200, attributes: 10, events: 5, spans: 60 },\n { text: 100, attributes: 5, events: 2, spans: 30 },\n] as const;\n\ninterface Source {\n name: \"history\" | \"memory\";\n summary(query: HistoryQuery): HistorySummary;\n slowestEndpoints(query: HistoryQuery, limit: number): EndpointStats[];\n traces(query: HistoryQuery): { total: number; traces: HistoryTrace[] };\n facets(query: HistoryQuery): HistoryFacets;\n trace(traceId: string): TraceSummary | undefined;\n}\n\nfunction memorySource(store: DevTelemetryStore): Source {\n const rows = (query: HistoryQuery) =>\n store\n .snapshot()\n .traces.map(toRow)\n .filter((row) => row.startMs >= query.from && row.startMs <= query.to);\n return {\n name: \"memory\",\n summary: (query) => summarizeRows(applyFilters(rows(query), query)),\n slowestEndpoints: (query, limit) => slowestEndpoints(rows(query), limit),\n traces(query) {\n const found = applyFilters(rows(query), query);\n const offset = query.offset ?? 0;\n return {\n total: found.length,\n traces: found.slice(offset, offset + (query.limit ?? found.length)),\n };\n },\n facets: (query) => computeFacets(rows(query), query),\n trace: (traceId) =>\n store.snapshot().traces.find((trace) => trace.traceId === traceId),\n };\n}\n\nfunction sourceOf(store: DevTelemetryStore, history?: DevHistory): Source {\n if (!history) return memorySource(store);\n const unfinished = memorySource(store).trace;\n return {\n name: \"history\",\n summary: (query) => history.summary(query),\n slowestEndpoints: (query, limit) => history.slowestEndpoints(query, limit),\n traces: (query) => history.traces(query),\n facets: (query) => history.facets(query),\n trace: (traceId) => history.trace(traceId) ?? unfinished(traceId),\n };\n}\n\nfunction row(trace: HistoryTrace) {\n return {\n traceId: trace.traceId,\n time: iso(trace.startMs),\n endpoint: trace.endpoint,\n path: trace.path,\n status: trace.httpStatus,\n outcome: outcomeOf(trace),\n state: trace.status,\n durationMs: round(trace.durationMs),\n service: trace.service,\n action: trace.action,\n message: cut(trace.message, 300),\n };\n}\n\ninterface Cuts {\n text: number;\n attributes: number;\n events: number;\n spans: number;\n}\n\nfunction traceTree(\n trace: TraceSummary,\n limits: (typeof TRACE_LEVELS_MILDEST_FIRST)[number],\n) {\n const cuts: Cuts = { text: 0, attributes: 0, events: 0, spans: 0 };\n const shorten = (value: string | undefined) => {\n const short = cut(value, limits.text);\n if (short !== value) cuts.text += 1;\n return short;\n };\n const attributes = (source: TraceSpan[\"attributes\"]) => {\n const entries = Object.entries(source).filter(([, v]) => v !== undefined);\n cuts.attributes += Math.max(entries.length - limits.attributes, 0);\n return Object.fromEntries(\n entries\n .slice(0, limits.attributes)\n .map(([key, value]) => [\n key,\n typeof value === \"string\"\n ? shorten(value)\n : Array.isArray(value)\n ? shorten(JSON.stringify(value))\n : value,\n ]),\n );\n };\n const spans = [...trace.spans].sort((a, b) => a.startMs - b.startMs);\n cuts.spans += Math.max(spans.length - limits.spans, 0);\n const nodes = new Map<\n string,\n Record<string, unknown> & { children: any[] }\n >();\n const roots: unknown[] = [];\n for (const span of spans.slice(0, limits.spans)) {\n const exception = findException(span.events);\n const shown = span.events.filter(\n (event) => event.name !== SPAN.exceptionEvent,\n );\n cuts.events += Math.max(shown.length - limits.events, 0);\n const node = {\n spanId: span.spanId,\n name: span.name,\n startMs: Math.round(span.startMs - trace.startMs),\n durationMs:\n span.endMs === undefined ? undefined : round(span.endMs - span.startMs),\n status: span.status,\n statusMessage: shorten(span.statusMessage),\n error: exception && {\n type: stringAttribute(exception, \"exception.type\"),\n message: shorten(stringAttribute(exception, ATTR.exceptionMessage)),\n stack: shorten(stringAttribute(exception, ATTR.exceptionStack)),\n },\n attributes: attributes(span.attributes),\n events: shown.slice(0, limits.events).map((event) =>\n event.name === SPAN.logEvent\n ? {\n atMs: Math.round(event.timeMs - trace.startMs),\n name: event.name,\n level: stringAttribute(event.attributes, ATTR.logLevel),\n message: shorten(\n stringAttribute(event.attributes, ATTR.logMessage),\n ),\n }\n : {\n atMs: Math.round(event.timeMs - trace.startMs),\n name: event.name,\n attributes: attributes(event.attributes),\n },\n ),\n children: [] as unknown[],\n };\n nodes.set(span.spanId, node);\n const parent = span.parentSpanId && nodes.get(span.parentSpanId);\n (parent ? parent.children : roots).push(node);\n }\n return { roots, cuts };\n}\n\nfunction withoutSpans(answer: string, trace: TraceSummary): string {\n const {\n spans: _spans,\n truncated: _truncated,\n ...request\n } = JSON.parse(answer) as Record<string, unknown>;\n return compactJson({\n ...request,\n message: cut(trace.message, 500),\n spans: [],\n truncated: {\n note: `This trace is too large to send even cut down, so its spans are left out. It is about ${Math.round(answer.length / 1000)} KB; open it in the dashboard instead.`,\n },\n });\n}\n\nfunction traceAnswer(trace: TraceSummary): string {\n let answer = \"\";\n for (const limits of TRACE_LEVELS_MILDEST_FIRST) {\n const { roots, cuts } = traceTree(trace, limits);\n const row = toRow(trace);\n const cutAny = () => Object.values(cuts).some((count) => count > 0);\n const body = {\n traceId: trace.traceId,\n endpoint: row.endpoint,\n path: trace.path,\n status: trace.httpStatus,\n outcome: outcomeOf(trace),\n state: trace.status,\n time: iso(trace.startMs),\n durationMs: round(trace.durationMs),\n service: trace.service,\n action: trace.action,\n message: cut(trace.message, limits.text),\n spans: roots,\n truncated: undefined as unknown,\n };\n if (trace.truncated || cutAny())\n body.truncated = {\n note: `Cut to fit about ${MAX_TRACE_CHARS / 1000} KB. Left out: ${cuts.spans} spans, ${cuts.events} events, ${cuts.attributes} attributes; shortened ${cuts.text} long strings.${trace.truncated ? \" The app itself also stopped recording spans of this request, which was very large.\" : \"\"}`,\n ...cuts,\n };\n answer = compactJson(body);\n if (answer.length <= MAX_TRACE_CHARS) return answer;\n }\n return withoutSpans(answer, trace);\n}\n\nconst TOOLS: McpToolDefinition[] = [\n {\n name: \"summary\",\n description:\n \"How the app is doing over a time window: request count, how many failed (client errors 4xx, server errors 5xx or thrown), the share that failed on the server, median and p95 duration, and the five endpoints with the highest average duration (with their request counts, server errors and slowest request). Start here to see whether something is wrong. Default window: the last hour.\",\n inputSchema: {\n type: \"object\",\n properties: {\n from: {\n type: \"string\",\n description: `Window start. ${TIME_HELP} Default: an hour before \\`to\\`.`,\n },\n to: {\n type: \"string\",\n description: `Window end. ${TIME_HELP} Default: now.`,\n },\n },\n additionalProperties: false,\n },\n annotations: READ_ONLY,\n },\n {\n name: \"list_requests\",\n description:\n \"Requests the app served, newest first (or slowest first), one row each: trace id, time, endpoint, path, HTTP status, outcome (ok, client error, server error), duration, service and action, and the failure message. Rows only; call get_trace with a trace id for the spans and log lines. Default window: the last 24 hours.\",\n inputSchema: {\n type: \"object\",\n properties: {\n outcome: {\n type: \"string\",\n enum: [...OUTCOMES],\n description:\n \"ok (below 400), client (4xx), or server (5xx or thrown).\",\n },\n endpoint: {\n type: \"string\",\n description:\n 'Exactly as the rows show it, such as \"GET /api/pages/:id\".',\n },\n method: {\n type: \"string\",\n description: 'An HTTP method, such as \"POST\".',\n },\n service: { type: \"string\", description: \"A service name.\" },\n query: {\n type: \"string\",\n description:\n \"Text to look for in the endpoint, path, span name, action or failure message.\",\n },\n min_ms: {\n type: \"integer\",\n minimum: 1,\n description: \"Only requests at least this slow.\",\n },\n sort: {\n type: \"string\",\n enum: [\"recent\", \"slowest\"],\n description: \"Default: recent.\",\n },\n from: {\n type: \"string\",\n description: `Window start. ${TIME_HELP} Default: a day before \\`to\\`.`,\n },\n to: {\n type: \"string\",\n description: `Window end. ${TIME_HELP} Default: now.`,\n },\n limit: {\n type: \"integer\",\n minimum: 1,\n maximum: MAX_LIST_LIMIT,\n description: `Rows to return. Default ${DEFAULT_LIST_LIMIT}.`,\n },\n offset: {\n type: \"integer\",\n minimum: 0,\n description: \"Rows to skip, to page through.\",\n },\n },\n additionalProperties: false,\n },\n annotations: READ_ONLY,\n },\n {\n name: \"get_trace\",\n description:\n 'One request in full, by trace id: the tree of spans with each one\\'s name, timing (milliseconds from the start of the request), status, attributes (such as SQL text), events and any error with its stack. Log lines are events named \"log\" with a level and message. The answer is cut to about 50 KB, and says what was left out.',\n inputSchema: {\n type: \"object\",\n properties: {\n trace_id: {\n type: \"string\",\n description: \"From list_requests or list_errors.\",\n },\n },\n required: [\"trace_id\"],\n additionalProperties: false,\n },\n annotations: READ_ONLY,\n },\n {\n name: \"list_errors\",\n description:\n 'Recent failures, newest first: failed requests (server errors, 5xx or thrown) and crashes of the app process, with the message, the route, the service and action, a stack when there is one, and the trace id to open with get_trace. Covers what the dashboard has seen since it started (the last 200). For older server errors use list_requests with outcome \"server\".',\n inputSchema: {\n type: \"object\",\n properties: {\n from: {\n type: \"string\",\n description: `Only failures after this. ${TIME_HELP}`,\n },\n limit: {\n type: \"integer\",\n minimum: 1,\n maximum: MAX_LIST_LIMIT,\n description: `Default ${DEFAULT_LIST_LIMIT}.`,\n },\n },\n additionalProperties: false,\n },\n annotations: READ_ONLY,\n },\n {\n name: \"app_overview\",\n description:\n \"How the app is built, not what it is doing: its services with their actions (and the HTTP route of each), MCP tools, sockets, events and database tables; the event listeners and schedules, with the workflows among them; and the installed plugins.\",\n inputSchema: {\n type: \"object\",\n properties: {},\n additionalProperties: false,\n },\n annotations: READ_ONLY,\n },\n];\n\n/** The tools of the dashboard's other views, by name, whether or not their data exists now. */\nconst VIEW_TOOL_NAMES: readonly string[] = [\n ...LOG_TOOL_NAMES,\n ...WORKFLOW_TOOL_NAMES,\n ...DOCS_TOOL_NAMES,\n];\n\n/** Every tool the dashboard has of its own, listed or not. */\nexport const DASHBOARD_TOOL_NAMES: readonly string[] = [\n ...TOOLS.map((tool) => tool.name),\n ...VIEW_TOOL_NAMES,\n];\n\nexport function createDashboardMcpRegistry(options: McpSources): McpRegistry {\n const { store, history } = options;\n const viewTools: BuiltInTool[] = [\n ...logTools(options),\n ...workflowTools(options),\n ...docsTools(options),\n ];\n const calls: Record<string, (args: Args) => string> = {\n summary(args) {\n const { from, to } = window(args, 60 * MINUTE);\n const source = sourceOf(store, history);\n const query: HistoryQuery = { from, to };\n const total = source.summary(query);\n const slowest = source.slowestEndpoints(query, SLOWEST_ENDPOINTS);\n return compactJson({\n window: { from: iso(from), to: iso(to) },\n source: source.name,\n requests: total.total,\n clientErrors: total.clientErrors,\n serverErrors: total.serverErrors,\n errorRate: total.total\n ? Math.round((total.serverErrors / total.total) * 10_000) / 10_000\n : 0,\n medianMs: round(total.medianMs),\n p95Ms: round(total.p95Ms),\n slowestEndpoints: slowest.map((endpoint) => ({\n ...endpoint,\n avgMs: round(endpoint.avgMs),\n maxMs: round(endpoint.maxMs),\n })),\n });\n },\n list_requests(args) {\n const { from, to } = window(args, DAY);\n const outcome = text(args, \"outcome\");\n if (outcome && !OUTCOMES.includes(outcome as Outcome))\n throw new Error(`outcome must be one of: ${OUTCOMES.join(\", \")}.`);\n const sort = text(args, \"sort\");\n if (sort && sort !== \"recent\" && sort !== \"slowest\")\n throw new Error(\"sort must be recent or slowest.\");\n const one = (name: string) => {\n const value = text(args, name);\n return value ? [value] : undefined;\n };\n const limit = integer(\n args,\n \"limit\",\n 1,\n MAX_LIST_LIMIT,\n DEFAULT_LIST_LIMIT,\n )!;\n const offset = integer(args, \"offset\", 0, Number.MAX_SAFE_INTEGER, 0)!;\n const source = sourceOf(store, history);\n const found = source.traces({\n from,\n to,\n endpoints: one(\"endpoint\"),\n methods: one(\"method\")?.map((method) => method.toUpperCase()),\n services: one(\"service\"),\n outcomes: outcome ? [outcome as Outcome] : undefined,\n minMs: integer(args, \"min_ms\", 1, Number.MAX_SAFE_INTEGER),\n query: text(args, \"query\"),\n sort: sort === \"slowest\" ? \"slowest\" : \"recent\",\n limit,\n offset,\n });\n return compactJson({\n window: { from: iso(from), to: iso(to) },\n source: source.name,\n total: found.total,\n offset,\n ...(offset + found.traces.length < found.total\n ? { nextOffset: offset + found.traces.length }\n : {}),\n requests: found.traces.map(row),\n });\n },\n get_trace(args) {\n const id = text(args, \"trace_id\");\n if (!id) throw new Error(\"trace_id is required.\");\n const trace = sourceOf(store, history).trace(id);\n if (!trace)\n throw new Error(\n `No request with trace id ${id}. The dashboard keeps ${history ? `${history.days} days of requests` : \"only the last 200 requests, and history is off\"}.`,\n );\n return traceAnswer(trace);\n },\n list_errors(args) {\n const since = time(args.from, \"from\", Date.now());\n const limit = integer(\n args,\n \"limit\",\n 1,\n MAX_LIST_LIMIT,\n DEFAULT_LIST_LIMIT,\n )!;\n const failures = store\n .snapshot()\n .failures.filter(\n (failure) =>\n (since === undefined || failure.at >= since) &&\n (failure.status ?? SERVER_ERROR) >= SERVER_ERROR,\n );\n return compactJson({\n total: failures.length,\n errors: failures.slice(0, limit).map((failure) => ({\n time: iso(failure.at),\n code: failure.code,\n kind: failure.phase,\n message: cut(failure.message, 500),\n status: failure.status,\n route: failure.route,\n service: failure.service,\n action: failure.action,\n traceId: failure.traceId,\n stack: cut(failure.stack, 1500),\n })),\n });\n },\n app_overview() {\n const { architecture } = store.snapshot();\n if (!architecture)\n return compactJson({\n note: \"The app has not reported its architecture yet. It may still be starting.\",\n });\n const { schema } = architecture;\n const events = schema.events;\n const workflows = [\n ...(events?.listeners ?? []).filter((item) => item.kind === \"workflow\"),\n ...(events?.schedules ?? []).filter((item) => item.kind === \"workflow\"),\n ].map((item) => item.name);\n return compactJson({\n mode: options.mode,\n historyDays: history?.days ?? 0,\n version: schema.version,\n services: schema.services.map((service) => ({\n name: service.name,\n database: service.databaseConfig,\n actions: service.actions.map((action) => ({\n name: action.name,\n route:\n action.method && action.path\n ? `${action.method} ${action.path}`\n : undefined,\n description: cut(action.description, 200),\n access: action.accessPolicy,\n emits: action.emits,\n })),\n tools: service.tools?.map((tool) => tool.name),\n sockets: service.sockets?.map((socket) => socket.name),\n events: service.events?.map((event) => event.name),\n resources: service.resources?.map((resource) => resource.name),\n })),\n listeners: events?.listeners,\n schedules: events?.schedules,\n workflows,\n plugins: schema.plugins?.map((plugin) => plugin.name),\n });\n },\n };\n const listed = () => viewTools.filter((tool) => tool.available?.() ?? true);\n return {\n listTools: () => [...TOOLS, ...listed().map((tool) => tool.definition)],\n async callTool(name, args = {}) {\n const call = Object.hasOwn(calls, name) ? calls[name] : undefined;\n if (call) return call(args);\n const view = listed().find((tool) => tool.definition.name === name);\n if (!view) throw new UnknownToolError(name);\n return view.run(args);\n },\n };\n}\n\nconst LIST_TIMEOUT_MS = 5000;\nconst CALL_TIMEOUT_MS = 30_000;\nconst BUILT_IN = new Set(DASHBOARD_TOOL_NAMES);\n\n/** MCP defaults `readOnlyHint` to false, so a tool is a write tool unless it says otherwise. */\nconst writes = (tool: McpToolDefinition) =>\n tool.annotations?.readOnlyHint !== true;\n\ninterface AppTools {\n tools: McpToolDefinition[];\n failed?: string;\n}\n\n/** Signed with the MCP scope, which `/app` never signs: neither signature works on the other's route. */\nasync function askApp(\n appUrl: string,\n caller: DashboardMcpCaller,\n method: string,\n params: unknown,\n timeoutMs: number,\n) {\n const answer = await fetch(\n `${new URL(appUrl).origin}${DASHBOARD_MCP_ROUTE}`,\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n [DASHBOARD_IDENTITY_HEADER]: signDashboardMcp(caller),\n },\n body: JSON.stringify({ jsonrpc: \"2.0\", id: 1, method, params }),\n signal: AbortSignal.timeout(timeoutMs),\n },\n );\n if (!answer.ok) throw new Error(`HTTP ${answer.status}`);\n return (await answer.json()) as {\n result?: {\n content?: { text?: string }[];\n structuredContent?: unknown;\n isError?: boolean;\n tools?: McpToolDefinition[];\n };\n error?: { code?: number; message: string };\n };\n}\n\nfunction withAppTools(\n base: McpRegistry,\n app: AppTools | undefined,\n caller: {\n identity: DashboardIdentity;\n appUrl: string | undefined;\n mayChange: boolean;\n },\n): McpRegistry {\n const own = (app?.tools ?? []).filter((tool) => !BUILT_IN.has(tool.name));\n return {\n listTools: () => [\n ...base.listTools(),\n ...own\n .filter((tool) => !writes(tool) || caller.mayChange)\n .map((tool) =>\n writes(tool)\n ? {\n ...tool,\n annotations: {\n ...tool.annotations,\n destructiveHint: tool.annotations?.destructiveHint ?? true,\n },\n }\n : tool,\n ),\n ],\n async callTool(name, args) {\n if (BUILT_IN.has(name)) return base.callTool(name, args);\n if (app?.failed)\n throw new Error(\n `The app did not answer (${app.failed}), so its tools are unavailable. It may be restarting.`,\n );\n if (!caller.appUrl) throw new UnknownToolError(name);\n const listed = own.find((item) => item.name === name);\n const answer = await askApp(\n caller.appUrl,\n { ...caller.identity, write: caller.mayChange },\n \"tools/call\",\n { name, arguments: args ?? {} },\n CALL_TIMEOUT_MS,\n );\n const text = answer.result?.content?.map((part) => part.text).join(\"\\n\");\n if (answer.error?.code === -32602) throw new UnknownToolError(name);\n if (answer.error || answer.result?.isError)\n throw new Error(answer.error?.message ?? text);\n const structured = answer.result?.structuredContent;\n if (structured === undefined) return text ?? \"\";\n return (listed?.outputSchema as Record<string, unknown> | undefined)?.[\n WRAP_RESULT\n ]\n ? (structured as { result: unknown }).result\n : structured;\n },\n };\n}\n\nexport function createDashboardMcp(\n options: Parameters<typeof createDashboardMcpRegistry>[0] & {\n appUrl: () => string | undefined;\n mayChange: (identity: DashboardIdentity) => boolean;\n },\n): (request: Request, identity: DashboardIdentity) => Promise<Response> {\n const base = createDashboardMcpRegistry(options);\n return async (request, identity) => {\n const rpc = (await request\n .clone()\n .json()\n .catch(() => undefined)) as\n | { method?: unknown; params?: { name?: unknown } }\n | undefined;\n const appUrl = options.appUrl();\n let app: AppTools | undefined;\n if (\n appUrl &&\n (rpc?.method === \"tools/list\" ||\n (rpc?.method === \"tools/call\" &&\n typeof rpc.params?.name === \"string\" &&\n !BUILT_IN.has(rpc.params.name)))\n ) {\n try {\n const answer = await askApp(\n appUrl,\n { ...identity, write: options.mayChange(identity) },\n \"tools/list\",\n undefined,\n LIST_TIMEOUT_MS,\n );\n app = { tools: answer.result?.tools ?? [] };\n } catch (error) {\n app = {\n tools: [],\n failed: error instanceof Error ? error.message : String(error),\n };\n }\n }\n return createMcpHandler({\n registry: withAppTools(base, app, {\n identity,\n appUrl,\n mayChange: options.mayChange(identity),\n }),\n serverInfo: {\n name: \"brick-dashboard\",\n title: \"Brick dashboard\",\n version: cliPkg.version,\n },\n })(request);\n };\n}\n","import { createHash, timingSafeEqual } from \"node:crypto\";\nimport type { IncomingMessage } from \"node:http\";\nimport type { DashboardAuth, DashboardIdentity } from \"@brickkit/core\";\n\nexport type Access =\n | { allowed: true; identity: DashboardIdentity }\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. */\nconst AUTHORIZE_TIMEOUT_MS = 5000;\n\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 MAX_DECODE_ROUNDS = 4;\n\n/**\n * Whether a path, as the app will route it, is under `/_brick/`: Brick's own\n * routes, such as the one that answers the dashboard's MCP, which the `/app`\n * proxy must never reach. It decodes percent-encoding until nothing changes\n * (`%2F`, `%5F`, `%252F`), reads `\\` as `/`, drops empty and `.` segments,\n * resolves `..`, and compares without regard to case. A path it cannot decode\n * is refused too. `/_brick/files`, local file storage's signed links, passes.\n */\nexport function isInternalAppPath(path: string): boolean {\n let current = path;\n for (let round = 0; ; round++) {\n let decoded: string;\n try {\n decoded = decodeURIComponent(current);\n } catch {\n return true;\n }\n if (decoded === current) break;\n if (round === MAX_DECODE_ROUNDS) return true;\n current = decoded;\n }\n const resolved: string[] = [];\n for (const segment of current.replace(/\\\\/g, \"/\").split(\"/\")) {\n if (segment === \"\" || segment === \".\") continue;\n if (segment === \"..\") resolved.pop();\n else resolved.push(segment);\n }\n // Local file storage's links are signed with their own token, so an\n // extension may open them.\n if (resolved.join(\"/\") === \"_brick/files\") return false;\n return resolved[0]?.toLowerCase() === \"_brick\";\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 protocol the client used: https when a proxy in front terminated TLS and says so. */\nexport function requestProtocol(request: IncomingMessage): \"http\" | \"https\" {\n const forwarded = request.headers[\"x-forwarded-proto\"];\n return (Array.isArray(forwarded) ? forwarded[0] : forwarded)\n ?.split(\",\")[0]\n ?.trim() === \"https\"\n ? \"https\"\n : \"http\";\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 protocol = requestProtocol(request);\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 isIdentity = (value: unknown): value is Required<DashboardIdentity> =>\n typeof value === \"object\" &&\n value !== null &&\n !(value instanceof Response) &&\n typeof (value as DashboardIdentity).user?.id === \"string\";\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` or an identity (`{ user }`). 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, identity: {} };\n if (!auth.authorize) return refusal(401, \"Unauthorized\", prompt);\n\n let decision: boolean | Response | DashboardIdentity;\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, identity: {} };\n if (isIdentity(decision))\n return {\n allowed: true,\n identity: {\n user: {\n id: decision.user.id,\n ...(typeof decision.user.name === \"string\"\n ? { name: decision.user.name }\n : {}),\n },\n },\n };\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 { 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 { Readable } from \"node:stream\";\nimport { pipeline } from \"node:stream/promises\";\nimport { ConfigError } from \"./config\";\nimport type { DevDocs } from \"./dev-docs\";\nimport type { DevHistory } from \"./dev-history\";\nimport { decodeHistoryQuery, type HistoryQuery } from \"./dashboard-query\";\nimport type { DevTelemetryStore } from \"./dev-telemetry-store\";\nimport { dashboardShell } from \"./dev-dashboard-shell\";\nimport { createDashboardMcp } from \"./dashboard-mcp\";\nimport {\n DASHBOARD_IDENTITY_HEADER,\n signDashboardIdentity,\n type DashboardAuth,\n type DashboardIdentity,\n} from \"@brickkit/core\";\nimport {\n createAccess,\n isInternalAppPath,\n isLoopbackHost,\n requestProtocol,\n} from \"./dashboard-access\";\nimport {\n ASSETS,\n CSRF_HEADER,\n CSRF_VALUE,\n DOCS_PATHS,\n INSPECTOR_READ_ONLY_HEADER,\n INSPECTOR_TOKEN_HEADER,\n matchRoute,\n ROUTES,\n viewsWithout,\n type DashboardEvents,\n type DashboardSnapshot,\n type HistoryResponses,\n type IngestPayload,\n type RouteName,\n} from \"./dashboard-protocol\";\nimport {\n assetsDirectory,\n DashboardExtensions,\n type PluginDashboard,\n themeCss,\n type DashboardExtensionOptions,\n} from \"./dashboard-extension\";\n\nconst KEEPALIVE_MS = 15_000;\nconst MAX_INGEST_BYTES = 5 * 1024 * 1024;\nconst MAX_PROXY_BYTES = 10 * 1024 * 1024;\nconst MAX_MCP_BYTES = 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\nconst PRODUCTION_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'\";\n\n// 'wasm-unsafe-eval': the inspector decodes zstd-compressed payloads with WebAssembly.\nconst INSPECTOR_POLICY = `${PRODUCTION_POLICY.replace(\n \"script-src 'self' 'unsafe-inline'\",\n \"script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval'\",\n)}; frame-ancestors 'self'`;\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\": `${PRODUCTION_POLICY}; 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 monitoring dashboard of `brick start`: it\n * serves only the routes marked `production`, 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 inspector?: boolean;\n mcp?: boolean;\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 * The project's extension and theme. In dev mode the extension is rebuilt as\n * its folder changes, and the page reloads; production serves it as built.\n */\n dashboard?: DashboardExtensionOptions;\n /**\n * The app's plugins, whose extensions are built and served before the\n * dashboard listens. Dev learns them later, with `setPluginExtensions`.\n */\n plugins?: readonly PluginDashboard[];\n /** Where `/app/*` goes; the app the store's API documents name otherwise. */\n appUrl?: string;\n /** How the host's user picks another port, added when the port is taken. */\n portHint?: string;\n}\n\nexport interface DevDashboard {\n readonly port: number;\n /** Build and serve the dashboard extensions the app's plugins ship. */\n setPluginExtensions(plugins: readonly PluginDashboard[]): Promise<void>;\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 ConfigError(\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 let theme: string;\n try {\n theme = themeCss(options.dashboard?.theme);\n } catch (error) {\n return Promise.reject(error);\n }\n // In dev, plugins' extensions can join later (`setPluginExtensions`).\n const extension =\n options.dashboard?.extension ||\n !production ||\n options.plugins?.some((plugin) => plugin.dashboard)\n ? new DashboardExtensions(options.dashboard?.extension, (message) =>\n console.warn(message),\n )\n : undefined;\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 route = matchRoute(request.method, url.pathname);\n if (route === \"health\") {\n await health(response);\n return;\n }\n let identity: DashboardIdentity = {};\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 identity = decision.identity;\n }\n if (!route || (production && !servedInProduction(route))) {\n send(response, 404, \"Not found\");\n return;\n }\n if (\n \"csrf\" in ROUTES[route] &&\n request.headers[CSRF_HEADER] !== CSRF_VALUE\n ) {\n send(response, 403, \"Forbidden\");\n return;\n }\n await handlers[route](request, response, url, identity);\n }\n\n function servedInProduction(route: RouteName): boolean {\n const served: boolean | \"extension\" | \"inspector\" | \"mcp\" =\n ROUTES[route].production;\n if (served === \"extension\") return Boolean(extension?.active);\n if (served === \"mcp\") return Boolean(options.mcp);\n return served === \"inspector\"\n ? Boolean(options.inspector && options.store.inspectorTarget())\n : served;\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 type Handler = (\n request: IncomingMessage,\n response: ServerResponse,\n url: URL,\n identity: DashboardIdentity,\n ) => void | Promise<void>;\n\n const handlers: Record<Exclude<RouteName, \"health\">, Handler> = {\n shell: (_request, response) =>\n send(\n response,\n 200,\n dashboardShell({\n extension: extension?.active\n ? {\n revision: extension.revision,\n js: Boolean(extension.built),\n css: Boolean(extension.built?.css),\n }\n : undefined,\n theme: theme !== \"\",\n mode: production ? \"production\" : \"dev\",\n }),\n {\n \"content-type\": \"text/html; charset=utf-8\",\n \"cache-control\": \"no-store\",\n },\n ),\n assets(_request, response, url) {\n const name = url.pathname.slice(ROUTES.assets.path.length + 1);\n // The project's own files, kept in memory beside the dashboard's.\n const own = name === ASSETS.theme ? theme : extension?.asset(name);\n if (own !== undefined)\n send(response, 200, own, {\n \"content-type\": assetType(name),\n \"cache-control\": \"no-store\",\n });\n else serveAsset(response, name);\n },\n app,\n state: (_request, response) => json(response, snapshot()),\n events: eventStream,\n history(_request, response, url) {\n if (options.history)\n history(options.history, url.pathname, url.searchParams, response);\n else send(response, 404, \"Not found\");\n },\n docs: (_request, response, url) =>\n docsRoute(response, url.pathname, url.searchParams),\n openapi: (_request, response) =>\n json(response, options.store.apiDocuments()),\n proxy,\n workflows(request, response, url, identity) {\n // Only the dashboard may frame it: framed by another site, a click could\n // land on Cancel or Replay. The rest of the dashboard may be embedded.\n frameOnlyHere(response);\n if (production)\n response.setHeader(\"content-security-policy\", INSPECTOR_POLICY);\n return inspector(request, response, url, identity);\n },\n schedules: inspector,\n mcp: mcpRoute,\n ingest,\n restart(request, response) {\n if (!options.restart) {\n send(response, 404, \"Not found\");\n return;\n }\n options.restart();\n send(response, 202, \"\");\n },\n };\n\n const mayChange = (identity: DashboardIdentity) =>\n !production || Boolean(identity.user);\n\n const mcp = createDashboardMcp({\n store: options.store,\n history: options.history,\n mode: production ? \"production\" : \"dev\",\n inspector: !production || Boolean(options.inspector),\n docs: options.docs,\n appUrl: () => options.appUrl ?? options.store.apiSnapshot()?.appUrl,\n mayChange,\n });\n\n /**\n * The MCP endpoint. Browsers have no use for it, so a request from another\n * origin is refused (`fromOwnPage` accepts an `Origin` that matches the\n * `Host`, so it does not stop DNS rebinding: the `allowedHosts` check in\n * `respond` does, on loopback).\n */\n async function mcpRoute(\n request: IncomingMessage,\n response: ServerResponse,\n url: URL,\n identity: DashboardIdentity,\n ): Promise<void> {\n if (!fromOwnPage(request)) {\n send(response, 403, \"Forbidden\");\n return;\n }\n const body = isBodyless(request)\n ? undefined\n : await readBytes(request, MAX_MCP_BYTES);\n if (!isBodyless(request) && !body) {\n tooLarge(response);\n return;\n }\n const headers = forwardedHeaders(request);\n const answer = await mcp(\n new Request(`http://127.0.0.1${url.pathname}`, {\n method: request.method,\n headers,\n ...(body ? { body: body as BodyInit } : {}),\n }),\n identity,\n );\n const returned: Record<string, string> = { \"cache-control\": \"no-store\" };\n answer.headers.forEach((value, name) => {\n returned[name] = value;\n });\n send(response, answer.status, await answer.text(), returned);\n }\n\n function snapshot(): DashboardSnapshot {\n return {\n ...options.store.snapshot(),\n canRestart: Boolean(options.restart),\n historyDays: options.history?.days ?? 0,\n mode: production ? \"production\" : \"dev\",\n hiddenViews: production ? viewsWithout(servedInProduction) : [],\n extension: extension?.active\n ? { revision: extension.revision, error: extension.error }\n : null,\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 async function ingest(\n request: IncomingMessage,\n response: ServerResponse,\n ): Promise<void> {\n const body = await readBytes(request, MAX_INGEST_BYTES);\n if (!body) {\n tooLarge(response);\n return;\n }\n let payload: IngestPayload | null;\n try {\n payload = JSON.parse(Buffer.from(body).toString(\"utf8\")) as IngestPayload;\n } catch {\n payload = null;\n }\n if (payload === null || typeof payload !== \"object\") {\n send(response, 400, \"Bad request\");\n return;\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 }\n\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 try {\n if (pathname === DOCS_PATHS.info) return json(response, docs.info());\n if (pathname === DOCS_PATHS.search)\n return json(response, await docs.search(params.get(\"q\") ?? \"\"));\n if (pathname === DOCS_PATHS.components) {\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 = DOCS_PATHS.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\n ? json(response, page)\n : send(response, 404, \"No such page.\");\n }\n const filePrefix = `${DOCS_PATHS.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 * Pass a request to the workflow inspector, which the app serves on a port of\n * its own, and stream its answer back (it follows a run's output as it\n * grows). Anyone who can open the dashboard may look, but a change must come\n * from the dashboard's own page: the inspector can cancel runs and resume\n * hooks, and a page on another site could otherwise post to it.\n */\n async function inspector(\n request: IncomingMessage,\n response: ServerResponse,\n url: URL,\n identity: DashboardIdentity,\n ): Promise<void> {\n const target = options.store.inspectorTarget();\n if (!target) {\n send(\n response,\n 503,\n \"The workflow inspector and schedules are not being served. The app may be restarting, or it may have neither workflows nor schedules.\",\n { \"content-type\": \"text/plain; charset=utf-8\" },\n );\n return;\n }\n if (!isBodyless(request) && !fromOwnPage(request)) {\n send(response, 403, \"Forbidden\");\n return;\n }\n await forward(\n request,\n response,\n `http://127.0.0.1:${target.port}${url.pathname}${url.search}`,\n (headers) => {\n headers.set(INSPECTOR_TOKEN_HEADER, target.token);\n if (!mayChange(identity)) headers.set(INSPECTOR_READ_ONLY_HEADER, \"1\");\n else headers.delete(INSPECTOR_READ_ONLY_HEADER);\n },\n \"Could not reach the workflow inspector.\",\n );\n }\n\n /**\n * Pass `/app/*` to the app, so the extension's pages read it from the\n * dashboard's own origin. Only the dashboard's page may use it, as with the\n * API proxy. A credential for the dashboard itself is not passed on; who the\n * dashboard let in is, signed, for `ctx.dashboard` and `dashboardUser()`.\n */\n async function app(\n request: IncomingMessage,\n response: ServerResponse,\n url: URL,\n identity: DashboardIdentity,\n ): Promise<void> {\n if (!fromOwnPage(request)) {\n send(response, 403, \"Forbidden\");\n return;\n }\n // Brick's own routes (`/_brick/...`) are not for pages: the one that\n // answers MCP for the dashboard must be reached only by its `/mcp`.\n if (isInternalAppPath(url.pathname.slice(ROUTES.app.path.length))) {\n send(response, 404, \"Not found\");\n return;\n }\n const appUrl = options.appUrl ?? options.store.apiSnapshot()?.appUrl;\n if (!appUrl) {\n send(response, 503, \"The app is not running yet.\");\n return;\n }\n // Framed by an extension's iframe page, and by nothing else.\n frameOnlyHere(response);\n await forward(\n request,\n response,\n `${new URL(appUrl).origin}${url.pathname.slice(ROUTES.app.path.length) || \"/\"}${url.search}`,\n (headers) => {\n if (access) headers.delete(\"authorization\");\n headers.set(DASHBOARD_IDENTITY_HEADER, signDashboardIdentity(identity));\n },\n \"Could not reach the app.\",\n );\n }\n\n /**\n * Send the request on to `target` and stream its answer back. `body`: the\n * request's body when the caller already read it; else it is streamed.\n */\n async function forward(\n request: IncomingMessage,\n response: ServerResponse,\n target: string,\n adjust: (headers: Headers) => void,\n unreachable: string,\n body?: Uint8Array,\n ): Promise<void> {\n const headers = forwardedHeaders(request);\n adjust(headers);\n const abort = new AbortController();\n response.on(\"close\", () => abort.abort());\n try {\n const upstream = await fetch(target, {\n method: request.method,\n headers,\n redirect: \"manual\",\n signal: abort.signal,\n ...(isBodyless(request)\n ? {}\n : body\n ? { body: body as BodyInit }\n : {\n body: Readable.toWeb(request) as unknown as BodyInit,\n duplex: \"half\",\n }),\n } as RequestInit);\n response.writeHead(upstream.status, returnedHeaders(upstream));\n if (!upstream.body || request.method === \"HEAD\") {\n response.end();\n return;\n }\n await pipeline(Readable.fromWeb(upstream.body as never), response);\n } catch {\n if (response.headersSent) response.destroy();\n else send(response, 502, unreachable);\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 if (!fromOwnPage(request)) {\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 tooLarge(response);\n return;\n }\n const cookie = url.searchParams.get(\"cookie\");\n await forward(\n request,\n response,\n target.href,\n (headers) => {\n if (cookie) headers.set(\"cookie\", cookie);\n },\n \"Could not reach the app.\",\n body,\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 const emit = <K extends keyof DashboardEvents>(\n name: K,\n data: DashboardEvents[K],\n ) => write(`event: ${name}\\ndata: ${JSON.stringify(data)}\\n\\n`);\n emit(\"snapshot\", snapshot());\n const unsubscribe = options.store.subscribe((event) =>\n emit(event.type, event),\n );\n const unwatch = extension?.onChange(() =>\n emit(\"extension\", snapshot().extension),\n );\n const keepalive = setInterval(() => write(\": keepalive\\n\\n\"), KEEPALIVE_MS);\n request.on(\"close\", () => {\n clearInterval(keepalive);\n unsubscribe();\n unwatch?.();\n });\n }\n\n // The first build finishes before the page can be asked for; a failed one\n // is shown on the page, and does not stop the dashboard.\n const ready = extension\n ? Promise.all([\n extension.load(),\n options.plugins && extension.setPlugins(options.plugins),\n ])\n : Promise.resolve();\n return ready.then(() => listen());\n\n function listen(): Promise<DevDashboard> {\n return new Promise((resolve, reject) => {\n server.once(\"error\", (error) => {\n extension?.close();\n reject(\n new Error(\n `Brick: dashboard port ${options.port} is unavailable.${options.portHint ? ` ${options.portHint}` : \"\"}`,\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 if (!production) extension?.watch();\n resolve({\n port,\n setPluginExtensions: (plugins) =>\n extension?.setPlugins(plugins) ?? Promise.resolve(),\n stop() {\n extension?.close();\n server.close();\n server.closeAllConnections();\n },\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 // Stop buffering; tooLarge() answers and closes the connection.\n request.removeAllListeners(\"data\");\n request.resume();\n resolve(undefined);\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 queries: {\n [K in keyof HistoryResponses]: (query: HistoryQuery) => HistoryResponses[K];\n } = {\n summary: (query) => store.summary(query),\n traces: (query) => store.traces(query),\n facets: (query) => store.facets(query),\n volume: (query) => store.volume(query),\n };\n try {\n const endpoint = pathname.slice(ROUTES.history.path.length + 1);\n if (endpoint === \"\") return json(response, store.info());\n if (endpoint === \"export\") {\n return send(response, 200, store.exportCsv(decodeHistoryQuery(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 if (Object.hasOwn(queries, endpoint))\n return json(\n response,\n queries[endpoint as keyof typeof queries](decodeHistoryQuery(params)),\n );\n const prefix = \"traces/\";\n if (endpoint.startsWith(prefix)) {\n const trace = store.trace(\n decodeURIComponent(endpoint.slice(prefix.length)),\n );\n if (trace) return json(response, trace);\n }\n send(response, 404, \"Not found\");\n } catch (error) {\n // A malformed `%` in the trace id is the caller's mistake.\n if (error instanceof URIError) return send(response, 400, error.message);\n console.error(\"[Brick-TS] A dashboard history query failed:\", error);\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\nconst assetType = (name: string): string =>\n ASSET_TYPES[extname(name)] ?? \"application/octet-stream\";\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\": assetType(name),\n \"cache-control\": \"no-store\",\n }),\n () => send(response, 404, \"Not found\"),\n );\n}\n\nfunction tooLarge(response: ServerResponse): void {\n // Closing after the 413 stops the rest of the upload being read.\n send(response, 413, \"Payload too large\", {\n \"content-type\": \"text/plain; charset=utf-8\",\n connection: \"close\",\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\nfunction json(response: ServerResponse, body: unknown): void {\n send(response, 200, JSON.stringify(body), {\n \"content-type\": \"application/json\",\n \"cache-control\": \"no-store\",\n });\n}\n\nconst isBodyless = (request: IncomingMessage) =>\n request.method === \"GET\" || request.method === \"HEAD\";\n\n/**\n * Whether a request comes from the dashboard's own page, as far as the browser\n * says: the same site, and the same origin as the address it was sent to.\n * Behind a proxy that terminates TLS that address is https.\n */\nfunction fromOwnPage(request: IncomingMessage): boolean {\n const site = request.headers[\"sec-fetch-site\"];\n const origin = request.headers.origin;\n return (\n (site === undefined || site === \"same-origin\") &&\n (origin === undefined ||\n origin === `${requestProtocol(request)}://${request.headers.host}`)\n );\n}\n\nfunction frameOnlyHere(response: ServerResponse): void {\n response.setHeader(\"content-security-policy\", \"frame-ancestors 'self'\");\n response.setHeader(\"x-frame-options\", \"SAMEORIGIN\");\n}\n\n/** The request's headers to send on, without those of this hop or this page. */\nfunction forwardedHeaders(request: IncomingMessage): Headers {\n const headers = new Headers();\n for (const [name, value] of Object.entries(request.headers)) {\n if (\n value === undefined ||\n NOT_FORWARDED.has(name) ||\n name === DASHBOARD_IDENTITY_HEADER\n )\n continue;\n if (name.startsWith(\"sec-\")) continue;\n headers.set(name, Array.isArray(value) ? value.join(\", \") : value);\n }\n return headers;\n}\n\nfunction returnedHeaders(upstream: Response): Record<string, string> {\n const returned: Record<string, string> = {};\n upstream.headers.forEach((value, name) => {\n if (!NOT_RETURNED.has(name)) returned[name] = value;\n });\n return returned;\n}\n","import type { Attributes } from \"@opentelemetry/api\";\nimport type { ApiDocument, ArchitectureSchema } from \"@brickkit/core\";\nimport {\n ATTR,\n LIVE_LIMITS,\n type ApiSnapshot,\n type ArchitectureSnapshot,\n type DevTelemetryEvent,\n type DevTelemetrySnapshot,\n type DocsSnapshot,\n type FailureSummary,\n type ReloadSummary,\n type SerializedError,\n type SpanEndRecord,\n type SpanOutcome,\n type SpanStartRecord,\n type TelemetryRecord,\n type TraceSpan,\n type TraceSummary,\n type WorkerErrorPhase,\n} from \"./dashboard-protocol\";\nimport {\n actionSpan,\n CLIENT_ERROR,\n findException,\n outcomeOf,\n stringAttribute,\n} from \"./dashboard-query\";\n\nconst LIMITS = { ...LIVE_LIMITS, spansPerTrace: 500 };\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: { saveTrace(trace: TraceSummary): void } | undefined;\n #architecture: ArchitectureSnapshot | null = null;\n #api: ApiSnapshot | null = null;\n #docs: DocsSnapshot | null = null;\n #inspector: { port: number; token: string; workflows: boolean } | undefined;\n #apiDocuments: ApiDocument[] = [];\n #sequence = 0;\n #generation = 0;\n\n /** Finished requests are also kept in `history`, when given. */\n constructor(\n options: { history?: { saveTrace(trace: TraceSummary): void } } = {},\n ) {\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 /**\n * Set where the app serves its workflow inspector and schedules, or\n * `undefined` when it stops. The address stays here: the snapshot says only\n * whether there is a workflow inspector.\n */\n setInspector(\n target: { port: number; token: string; workflows: boolean } | undefined,\n ): void {\n this.#inspector = target;\n this.#emit({ type: \"inspector\", inspector: Boolean(target?.workflows) });\n }\n\n /** The architecture as the app last reported it, without building the whole snapshot. */\n architecture(): ArchitectureSnapshot | null {\n return this.#architecture;\n }\n\n /** Whether the app serves the workflow inspector, not only the schedules. */\n servesWorkflows(): boolean {\n return Boolean(this.#inspector?.workflows);\n }\n\n /** Where the dashboard proxies the workflow inspector and schedules, when the app serves them. */\n inspectorTarget(): { port: number; token: string } | undefined {\n return this.#inspector;\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 inspector: Boolean(this.#inspector?.workflows),\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, ATTR.httpMethod);\n entry.route = stringAttribute(record.attributes, ATTR.httpRoute);\n entry.path = stringAttribute(record.attributes, ATTR.urlPath);\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, ATTR.errorCode);\n if (code !== undefined) {\n const exception = findException(record.events);\n this.#pushFailure({\n phase: \"request\",\n code,\n message:\n stringAttribute(exception, ATTR.exceptionMessage) ??\n stringAttribute(record.attributes, ATTR.errorMessage) ??\n code,\n status: numberAttribute(record.attributes, ATTR.errorStatus),\n stack: stringAttribute(exception, ATTR.exceptionStack),\n traceId: entry.traceId,\n route: entry.route,\n service: stringAttribute(record.attributes, ATTR.service),\n action: stringAttribute(record.attributes, ATTR.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(record.attributes, ATTR.httpStatus);\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 outcome = outcomeOf({\n status: record.status === \"error\" ? \"error\" : \"ok\",\n httpStatus: entry.httpStatus,\n });\n entry.status = outcome === \"server\" ? \"error\" : \"ok\";\n if (outcome !== \"ok\" && !entry.failureRecorded) {\n const exception = findException(record.events);\n this.#pushFailure({\n phase: \"request\",\n code: status >= CLIENT_ERROR ? `HTTP_${status}` : \"UNHANDLED_ERROR\",\n message:\n stringAttribute(exception, ATTR.exceptionMessage) ??\n record.statusMessage ??\n describeResponse(entry, status),\n status: entry.httpStatus,\n stack: stringAttribute(exception, ATTR.exceptionStack),\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 (error) {\n this.#listeners.delete(listener);\n console.warn(\n \"[Brick-TS] A dashboard client stopped receiving updates:\",\n error,\n );\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 action = actionSpan(spans);\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(action?.attributes, ATTR.service),\n action: stringAttribute(action?.attributes, ATTR.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 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","import {\n ConfigError,\n DEFAULT_DASHBOARD_PORT,\n DEFAULT_HISTORY_DAYS,\n} from \"./config\";\nimport { DocsHost } from \"./dev-docs\";\nimport {\n startDevDashboard,\n type DevDashboard,\n type DevDashboardOptions,\n} from \"./dev-dashboard\";\nimport { openHistory } from \"./dev-history\";\nimport { DevTelemetryStore } from \"./dev-telemetry-store\";\n\nexport interface DashboardHost extends DevDashboard {\n /** Where the host records what the app reports. */\n readonly store: DevTelemetryStore;\n /** The app's developer documentation, when `docs` was asked for. */\n readonly docs?: DocsHost;\n}\n\n/**\n * Open the dashboard with its history, store and docs, for `brick dev`, the\n * Vite plugin and the production dashboard alike. When it cannot start, what\n * it opened is closed, `warn` says why, and the host runs on without it. A\n * configuration mistake (a bad theme, a public host without auth) throws.\n */\nexport async function openDashboard(\n options: Omit<DevDashboardOptions, \"store\" | \"history\" | \"docs\" | \"port\"> & {\n /** Default 9400. */\n port?: number;\n /** The project folder; history is kept in `.brick/` inside it. */\n directory: string;\n /** Days of requests to keep on disk; zero for none. Default 90. */\n historyDays?: number;\n warn: (message: string) => void;\n /** Serve the app's developer documentation (the Docs tab). */\n docs?: boolean;\n },\n): Promise<DashboardHost | undefined> {\n const {\n port = DEFAULT_DASHBOARD_PORT,\n directory,\n historyDays = DEFAULT_HISTORY_DAYS,\n warn,\n docs: withDocs,\n ...rest\n } = options;\n const history = await openHistory({ directory, days: historyDays, warn });\n const store = new DevTelemetryStore({ history });\n const docs = withDocs\n ? new DocsHost((docs) => store.setDocs(docs), warn)\n : undefined;\n let server: DevDashboard;\n try {\n server = await startDevDashboard({\n ...rest,\n port,\n store,\n history,\n docs: docs && (() => docs.current),\n });\n } catch (error) {\n docs?.close();\n history?.close();\n if (error instanceof ConfigError) throw error;\n const reason = error instanceof Error ? error.message : String(error);\n warn(`[Brick-TS] ${reason} Continuing without the dashboard.`);\n return undefined;\n }\n return {\n port: server.port,\n store,\n docs,\n setPluginExtensions: (plugins) => server.setPluginExtensions(plugins),\n stop() {\n server.stop();\n docs?.close();\n history?.close();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;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