@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.
Files changed (49) hide show
  1. package/README.md +35 -8
  2. package/dashboard-dist/{api-reference-C2_JX174.js → api-reference-ZQs4Z4Yd.js} +71 -71
  3. package/dashboard-dist/app.css +1 -1
  4. package/dashboard-dist/app.js +12 -12
  5. package/dashboard-dist/{client-DsITZplk.js → client-CFM1S4Xv.js} +1 -1
  6. package/dashboard-dist/{core-sW89OSz5.js → core-VNHGFYB7.js} +1 -1
  7. package/dashboard-dist/{docs-D3U7gUWq.js → docs-CM2krp6H.js} +2 -2
  8. package/dashboard-dist/kit.js +1 -1
  9. package/dashboard-dist/popover-CVY1eRNY.js +1 -0
  10. package/dashboard-dist/theme.css +48 -39
  11. package/dist/bin.js +3 -2
  12. package/dist/bin.js.map +1 -1
  13. package/dist/build.js +6 -1
  14. package/dist/build.js.map +1 -1
  15. package/dist/dashboard-host.js +2594 -889
  16. package/dist/dashboard-host.js.map +1 -1
  17. package/dist/dashboard-protocol.js +10 -6
  18. package/dist/dashboard-protocol.js.map +1 -1
  19. package/dist/dashboard.d.ts +3 -3
  20. package/dist/dev-inspector.js +111 -0
  21. package/dist/dev-inspector.js.map +1 -0
  22. package/dist/dev-worker.js +1 -102
  23. package/dist/dev-worker.js.map +1 -1
  24. package/dist/package.js +5 -0
  25. package/dist/package.js.map +1 -0
  26. package/dist/production-dashboard.js +27 -2
  27. package/dist/production-dashboard.js.map +1 -1
  28. package/dist/production-dashboard2.d.ts +5 -0
  29. package/dist/project.js +2 -3
  30. package/dist/project.js.map +1 -1
  31. package/dist/vite.js +2 -1
  32. package/dist/vite.js.map +1 -1
  33. package/inspector-dist/NOTICE +3 -1
  34. package/inspector-dist/client/assets/{app-Wfnqu2Ic.css → app-PJHZvcxl.css} +49 -40
  35. package/inspector-dist/client/assets/{manifest-cfc09adc.js → manifest-274ef876.js} +1 -1
  36. package/inspector-dist/client/assets/{root-CVescmwt.css → root-CPvk93Fe.css} +49 -40
  37. package/inspector-dist/server/assets/{app-w0nTXgJd.js → app-DdYuYhBk.js} +89 -17
  38. package/inspector-dist/server/assets/{functions-B9XwHSzK.js → functions-BebJWj30.js} +2 -2
  39. package/inspector-dist/server/assets/{serialization-DsMds3lJ.js → serialization-Cgu5b7aC.js} +1 -1
  40. package/inspector-dist/server/assets/{token-CvvD8Y5H.js → token-3-nUtxO2.js} +1 -1
  41. package/inspector-dist/server/assets/{token-CxjWFNNq.js → token-DH652a7D.js} +1 -1
  42. package/inspector-dist/server/assets/token-util-wQgchIHA.js +3 -0
  43. package/inspector-dist/server/assets/{ws-transport-CamzQ5O8.js → ws-transport-7nLI4Gq9.js} +1 -1
  44. package/inspector-dist/server/index.js +1 -1
  45. package/package.json +2 -2
  46. package/dashboard-dist/PopoverPopup-CiI2avT_.js +0 -1
  47. package/dashboard-dist/popover-Bb2Q3jiK.js +0 -1
  48. package/inspector-dist/server/assets/token-util-D9IsWeEs.js +0 -3
  49. /package/inspector-dist/client/assets/{root-CVhM1JOR.js → root-2KbsWt-J.js} +0 -0
@@ -4,8 +4,7 @@ const GET = ["GET"];
4
4
  /**
5
5
  * Every route the dashboard serves. The server dispatches from this table and
6
6
  * the page builds its URLs from it. Production serves only what is marked
7
- * `production`: the shell, live state and stored history. Nothing that
8
- * changes the app or reaches into it, and nothing from the project's source.
7
+ * `production`.
9
8
  */
10
9
  const ROUTES = {
11
10
  /** Open to everyone: uptime monitors cannot sign in. */
@@ -70,7 +69,7 @@ const ROUTES = {
70
69
  workflows: {
71
70
  path: "/workflows",
72
71
  prefix: true,
73
- production: false,
72
+ production: "inspector",
74
73
  view: "workflows"
75
74
  },
76
75
  /** The app's schedules, served beside the workflow inspector: list them, run one now. */
@@ -78,9 +77,13 @@ const ROUTES = {
78
77
  path: "/api/schedules",
79
78
  prefix: true,
80
79
  methods: ["GET", "POST"],
81
- production: false,
80
+ production: "inspector",
82
81
  view: "schedules"
83
82
  },
83
+ mcp: {
84
+ path: "/mcp",
85
+ production: "mcp"
86
+ },
84
87
  ingest: {
85
88
  path: "/api/ingest",
86
89
  methods: ["POST"],
@@ -98,7 +101,7 @@ const ROUTES = {
98
101
  function matchRoute(method, pathname) {
99
102
  for (const [name, route] of Object.entries(ROUTES)) if ((pathname === route.path || route.prefix === true && pathname.startsWith(`${route.path}/`)) && (!route.methods || route.methods.includes(method ?? ""))) return name;
100
103
  }
101
- new Set(Object.values(ROUTES).flatMap((route) => route.view && route.production === false ? [route.view] : []));
104
+ const viewsWithout = (served) => [...new Set(Object.entries(ROUTES).flatMap(([name, route]) => route.view && !served(name) ? [route.view] : []))];
102
105
  /** The Docs tab's data: tree, search, compiled pages, files, components. */
103
106
  const DOCS_PATHS = {
104
107
  info: ROUTES.docs.path,
@@ -135,6 +138,7 @@ const isExternalHref = (href) => /^[a-z][a-z\d+.-]*:/i.test(href);
135
138
  const CSRF_HEADER = "x-brick-dashboard";
136
139
  /** The header that proves a request to the workflow inspector comes from the dashboard. */
137
140
  const INSPECTOR_TOKEN_HEADER = "x-brick-inspector";
141
+ const INSPECTOR_READ_ONLY_HEADER = "x-brick-inspector-read-only";
138
142
  /** The files the shell loads from `ROUTES.assets.path`. `app.*` come from the dashboard's build. */
139
143
  const ASSETS = {
140
144
  app: "app.js",
@@ -204,6 +208,6 @@ function describeSchedule(schedule) {
204
208
  ]) if (ms % size === 0) return `every ${ms / size}${unit}`;
205
209
  return `every ${ms}ms`;
206
210
  }
207
- export { matchRoute as _, INSPECTOR_TOKEN_HEADER as a, SHARED_MODULES as c, assetUrl as d, decode as f, isExternalHref as g, docsHref as h, DOCS_PATHS as i, SPAN as l, docsFileUrl as m, ATTR as n, LIVE_LIMITS as o, describeSchedule as p, CSRF_HEADER as r, ROUTES as s, ASSETS as t, THEME_STORAGE_KEY as u };
211
+ export { isExternalHref as _, INSPECTOR_READ_ONLY_HEADER as a, ROUTES as c, THEME_STORAGE_KEY as d, assetUrl as f, docsHref as g, docsFileUrl as h, DOCS_PATHS as i, SHARED_MODULES as l, describeSchedule as m, ATTR as n, INSPECTOR_TOKEN_HEADER as o, decode as p, CSRF_HEADER as r, LIVE_LIMITS as s, ASSETS as t, SPAN as u, matchRoute as v, viewsWithout as y };
208
212
 
209
213
  //# sourceMappingURL=dashboard-protocol.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"dashboard-protocol.js","names":[],"sources":["../src/dashboard-protocol.ts"],"sourcesContent":["import type { Attributes } from \"@opentelemetry/api\";\nimport type { ArchitectureSchema } from \"@brickkit/core\";\n\n/*\n * What the dashboard server and its page agree on: the routes, headers, event\n * names and the data they carry. Types and constants only, so the page can\n * import it without the server's code.\n */\n\n// ---------------------------------------------------------------------------\n// Span records: what the app's tracer reports, over IPC or `/api/ingest`\n\nexport interface SpanEventRecord {\n name: string;\n timeMs: number;\n attributes: Attributes;\n}\n\nexport interface SpanStartRecord {\n phase: \"start\";\n traceId: string;\n spanId: string;\n parentSpanId?: string;\n name: string;\n startMs: number;\n attributes: Attributes;\n}\n\nexport interface SpanEndRecord {\n phase: \"end\";\n traceId: string;\n spanId: string;\n name: string;\n endMs: number;\n status: \"unset\" | \"ok\" | \"error\";\n statusMessage?: string;\n attributes: Attributes;\n events: SpanEventRecord[];\n}\n\nexport type TelemetryRecord = SpanStartRecord | SpanEndRecord;\n\nexport type WorkerErrorPhase = \"startup\" | \"uncaught\" | \"unhandled-rejection\";\n\nexport interface SerializedError {\n name: string;\n message: string;\n stack?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Routes\n\n/** The dashboard's built-in views; `#/<view>/…` opens one. */\nexport const VIEW_NAMES = [\n \"requests\",\n \"logs\",\n \"overview\",\n \"apis\",\n \"docs\",\n \"workflows\",\n \"schedules\",\n \"errors\",\n \"reloads\",\n] as const;\nexport type ViewName = (typeof VIEW_NAMES)[number];\n\ninterface RouteSpec {\n path: string;\n /** Also answers every path below `path`. */\n prefix?: boolean;\n /** The methods it answers; any when absent. */\n methods?: readonly string[];\n /** Served by the production dashboard; `\"extension\"`: only when it has one. */\n production: boolean | \"extension\";\n /** The page's view that needs it; a view whose routes production lacks is hidden there. */\n view?: ViewName;\n /** It changes something, so the request must carry `CSRF_HEADER`. */\n csrf?: true;\n}\n\nconst GET = [\"GET\"] as const;\n\n/**\n * Every route the dashboard serves. The server dispatches from this table and\n * the page builds its URLs from it. Production serves only what is marked\n * `production`: the shell, live state and stored history. Nothing that\n * changes the app or reaches into it, and nothing from the project's source.\n */\nexport const ROUTES = {\n /** Open to everyone: uptime monitors cannot sign in. */\n health: { path: \"/_health\", methods: [\"GET\", \"HEAD\"], production: true },\n shell: { path: \"/\", methods: GET, production: true },\n assets: { path: \"/assets\", prefix: true, methods: GET, production: true },\n /** The app itself, for an extension's `appFetch`. */\n app: { path: \"/app\", prefix: true, production: \"extension\" },\n state: { path: \"/api/state\", methods: GET, production: true },\n events: { path: \"/api/events\", methods: GET, production: true },\n history: {\n path: \"/api/history\",\n prefix: true,\n methods: GET,\n production: true,\n },\n docs: {\n path: \"/api/docs\",\n prefix: true,\n methods: GET,\n production: false,\n view: \"docs\",\n },\n openapi: {\n path: \"/api/openapi\",\n methods: GET,\n production: false,\n view: \"apis\",\n },\n /** Try it in the APIs view; the app is another origin. */\n proxy: { path: \"/api/proxy\", production: false, view: \"apis\" },\n /** The workflow inspector the app serves on a port of its own. */\n workflows: {\n path: \"/workflows\",\n prefix: true,\n production: false,\n view: \"workflows\",\n },\n /** The app's schedules, served beside the workflow inspector: list them, run one now. */\n schedules: {\n path: \"/api/schedules\",\n prefix: true,\n methods: [\"GET\", \"POST\"],\n production: false,\n view: \"schedules\",\n },\n ingest: {\n path: \"/api/ingest\",\n methods: [\"POST\"],\n production: false,\n csrf: true,\n },\n restart: {\n path: \"/api/restart\",\n methods: [\"POST\"],\n production: false,\n csrf: true,\n },\n} as const satisfies Record<string, RouteSpec>;\n\nexport type RouteName = keyof typeof ROUTES;\n\n/** The route a request is for, or undefined when none answers it. */\nexport function matchRoute(\n method: string | undefined,\n pathname: string,\n): RouteName | undefined {\n for (const [name, route] of Object.entries(ROUTES) as [\n RouteName,\n RouteSpec,\n ][]) {\n const at =\n pathname === route.path ||\n (route.prefix === true && pathname.startsWith(`${route.path}/`));\n if (at && (!route.methods || route.methods.includes(method ?? \"\")))\n return name;\n }\n return undefined;\n}\n\n/** Views the production dashboard hides: they need a route it does not serve. */\nexport const PRODUCTION_HIDDEN_VIEWS: ReadonlySet<string> = new Set<ViewName>(\n Object.values(ROUTES as Record<RouteName, RouteSpec>).flatMap((route) =>\n route.view && route.production === false ? [route.view] : [],\n ),\n);\n\n/** What each history query endpoint answers, as JSON. */\nexport interface HistoryResponses {\n summary: HistorySummary;\n traces: { total: number; traces: HistoryTrace[] };\n facets: HistoryFacets;\n volume: VolumeBucket[];\n}\n\n/** The history endpoints: the JSON queries, and `export` (CSV). */\nexport type HistoryEndpoint = keyof HistoryResponses | \"export\";\n\n/** A history query's address; with no endpoint, what the history holds. */\nexport const historyUrl = (\n endpoint?: HistoryEndpoint,\n params?: URLSearchParams,\n): string =>\n `${ROUTES.history.path}${endpoint ? `/${endpoint}` : \"\"}${params ? `?${params}` : \"\"}`;\n\nexport const historyTraceUrl = (traceId: string): string =>\n `${historyUrl(\"traces\")}/${encodeURIComponent(traceId)}`;\n\n/** The Docs tab's data: tree, search, compiled pages, files, components. */\nexport const DOCS_PATHS = {\n info: ROUTES.docs.path,\n search: `${ROUTES.docs.path}/search`,\n components: `${ROUTES.docs.path}/components.js`,\n page: `${ROUTES.docs.path}/page`,\n files: `${ROUTES.docs.path}/files`,\n} as const;\n\n/** A path segment as written, when it is not valid percent-encoding. */\nexport function decode(value: string): string {\n try {\n return decodeURIComponent(value);\n } catch {\n return value;\n }\n}\n\n/**\n * A page address, `#/<segments>#<anchor>`, each part encoded. Every view's\n * links are built with it, and the page's `parseRoute` reads them back.\n */\nexport const hashHref = (segments: string[], anchor?: string): string =>\n `#/${encodePath(segments)}${anchor ? `#${encodeURIComponent(anchor)}` : \"\"}`;\n\n/** The page's address of a docs page, optionally at one of its headings. */\nexport const docsHref = (path: string[], anchor?: string): string =>\n hashHref([\"docs\", ...path], anchor);\n\nconst encodePath = (path: string[]): string =>\n path.map(encodeURIComponent).join(\"/\");\n\n/** Where a file in the docs folder is served, by its path inside it. */\nexport const docsFileUrl = (path: string): string =>\n `${DOCS_PATHS.files}/${encodePath(path.split(\"/\"))}`;\n\n/** Where a compiled docs page is served, by its slugs. */\nexport const docsPageUrl = (path: string[]): string =>\n `${DOCS_PATHS.page}/${encodePath(path)}`;\n\n/** Where the docs search answers `query`. */\nexport const docsSearchUrl = (query: string): string =>\n `${DOCS_PATHS.search}?q=${encodeURIComponent(query)}`;\n\n/** Whether a link names a scheme (`https:`, `mailto:`) and so leaves the dashboard. */\nexport const isExternalHref = (href: string): boolean =>\n /^[a-z][a-z\\d+.-]*:/i.test(href);\n\n/**\n * Sent with every request that changes something (restart, ingest). A page on\n * another site cannot send it without a preflight, which the server never\n * answers.\n */\nexport const CSRF_HEADER = \"x-brick-dashboard\";\nexport const CSRF_VALUE = \"1\";\n\n/** The header that proves a request to the workflow inspector comes from the dashboard. */\nexport const INSPECTOR_TOKEN_HEADER = \"x-brick-inspector\";\n\n/** What a process that cannot share memory with the dashboard posts to `/api/ingest`. */\nexport interface IngestPayload {\n /** Span records, of the newest generation. */\n records?: TelemetryRecord[];\n /** A notice that the app loaded: a new generation begins. */\n worker?: string;\n}\n\n// ---------------------------------------------------------------------------\n// The shell and its assets\n\n/** The files the shell loads from `ROUTES.assets.path`. `app.*` come from the dashboard's build. */\nexport const ASSETS = {\n app: \"app.js\",\n appCss: \"app.css\",\n /** The project's extension, or the list of parts when plugins have one too. */\n extension: \"extension.js\",\n extensionCss: \"extension.css\",\n /** The project's theme tokens; see `themeCss`. */\n theme: \"brick-theme.css\",\n} as const;\n\n/** Where an asset is served. */\nexport const assetUrl = (file: string): string =>\n `${ROUTES.assets.path}/${file}`;\n\n/**\n * What the shell tells the page in its markup: a `<meta name=\"brick-extension\"\n * data-revision data-src>` for the extension, and the theme's `<link>`.\n */\nexport const SHELL = {\n extensionMeta: 'meta[name=\"brick-extension\"]',\n themeLink: \"link[data-brick-theme]\",\n} as const;\n\n// ---------------------------------------------------------------------------\n// Modules the page shares with the project's own\n\n/**\n * What the dashboard supplies to the project's docs components and dashboard\n * extension, so there is one copy of React and of the UI kit on the page: the\n * bundler leaves `specifier` external, the shell's import map points it at\n * `/assets/<file>`, and `file` hands over the page's `globalThis.__brickDashboard[global]`.\n */\nexport const SHARED_MODULES = [\n { specifier: \"react\", file: \"react.js\", global: \"React\" },\n {\n specifier: \"react/jsx-runtime\",\n file: \"react-jsx-runtime.js\",\n global: \"jsxRuntime\",\n },\n {\n specifier: \"react/jsx-dev-runtime\",\n file: \"react-jsx-runtime.js\",\n global: \"jsxRuntime\",\n },\n { specifier: \"react-dom\", file: \"react-dom.js\", global: \"ReactDOM\" },\n {\n specifier: \"react-dom/client\",\n file: \"react-dom-client.js\",\n global: \"ReactDOMClient\",\n },\n // The UI kit is a module of the dashboard's own build.\n { specifier: \"@brickkit/cli/dashboard\", file: \"kit.js\" },\n] as const;\n\nexport type SharedGlobal = Extract<\n (typeof SHARED_MODULES)[number],\n { global: string }\n>[\"global\"];\n\n/**\n * One of several dashboard extensions (the app's and its plugins'), as\n * `/assets/extension.js` lists them in `export const parts`.\n */\nexport interface ExtensionPart {\n name: string;\n /** Relative to `extension.js`. */\n src: string;\n /** A plugin's: its pages without a place go under a section named after it. */\n plugin: boolean;\n}\n\n/** Where the page keeps the chosen theme; the shell applies it before first paint. */\nexport const THEME_STORAGE_KEY = \"brick-dashboard-theme\";\n\n// ---------------------------------------------------------------------------\n// Span names and attribute keys core sets, read here and on the page\n\nexport { SPAN, ATTR } from \"@brickkit/core/client\";\n\n// ---------------------------------------------------------------------------\n// Live data\n\n/** How many of each the live state keeps, on the server and on the page. */\nexport const LIVE_LIMITS = { traces: 200, failures: 200, reloads: 100 };\n\nexport type SpanOutcome = \"running\" | \"ok\" | \"error\" | \"interrupted\";\n\nexport interface TraceSpan {\n spanId: string;\n parentSpanId?: string;\n name: string;\n startMs: number;\n endMs?: number;\n status: SpanOutcome;\n statusMessage?: string;\n attributes: Attributes;\n events: SpanEventRecord[];\n}\n\nexport interface TraceSummary {\n traceId: string;\n name: string;\n method?: string;\n route?: string;\n /** The request's actual path, which differs from a wildcard route template. */\n path?: string;\n httpStatus?: number;\n generation: number;\n startMs: number;\n endMs?: number;\n durationMs?: number;\n status: SpanOutcome;\n truncated: boolean;\n /** The service and action that handled the request, when it ran one. */\n service?: string;\n action?: string;\n /** Why it failed, when it did. */\n message?: string;\n spans: TraceSpan[];\n}\n\nexport interface FailureSummary {\n id: number;\n at: number;\n phase: \"request\" | WorkerErrorPhase;\n code: string;\n message: string;\n status?: number;\n stack?: string;\n traceId?: string;\n route?: string;\n service?: string;\n action?: string;\n generation: number;\n}\n\nexport type ReloadKind = \"started\" | \"restarting\" | \"exited\" | \"contract-ready\";\n\nexport interface ReloadSummary {\n id: number;\n at: number;\n kind: ReloadKind;\n generation: number;\n detail?: string;\n}\n\n/** Services, actions, and routes of the application as last started. */\nexport interface ArchitectureSnapshot {\n generation: number;\n schema: ArchitectureSchema;\n}\n\n/** The OpenAPI documents the app offers, for the dashboard's APIs view. */\nexport interface ApiSnapshot {\n /** Changes each time the documents are replaced, so views know to reload. */\n revision: number;\n /** Where the app listens; Try it in the APIs view sends requests here. */\n appUrl?: string;\n /** Names of the documents, in order. */\n titles: string[];\n}\n\n/** What the dashboard knows about the app's developer documentation. */\nexport type DocsSnapshot =\n | {\n status: \"ready\";\n /** Changes whenever the pages change, so the Docs tab reloads. */\n revision: number;\n title: string;\n /** Whether the project supplied components of its own. */\n components: boolean;\n }\n /** The packages the docs need are not installed. */\n | { status: \"missing\"; packages: string[]; message: string }\n /** Why the docs cannot be shown. */\n | { status: \"error\"; message: string };\n\n/** The project's dashboard extension as last built. */\nexport interface ExtensionBuild {\n revision: number;\n /** Why the last build failed. */\n error?: string;\n}\n\nexport type DevTelemetryEvent =\n | { type: \"trace\"; trace: TraceSummary }\n | { type: \"failure\"; failure: FailureSummary }\n | { type: \"reload\"; reload: ReloadSummary }\n | { type: \"architecture\"; architecture: ArchitectureSnapshot }\n | { type: \"api\"; api: ApiSnapshot }\n | { type: \"docs\"; docs: DocsSnapshot | null }\n | { type: \"inspector\"; inspector: boolean };\n\nexport interface DevTelemetrySnapshot {\n traces: TraceSummary[];\n failures: FailureSummary[];\n reloads: ReloadSummary[];\n architecture: ArchitectureSnapshot | null;\n api: ApiSnapshot | null;\n /** Null when the app has no `documentation`. */\n docs: DocsSnapshot | null;\n /** Whether the app serves the workflow inspector the dashboard can show. */\n inspector: boolean;\n}\n\n/** `/api/state`, and the first event of `/api/events`: the store's snapshot and the server's own fields. */\nexport interface DashboardSnapshot extends DevTelemetrySnapshot {\n /** Whether the host can restart the app; the page shows the button. */\n canRestart: boolean;\n /** Days of requests kept on disk; zero when history is off. */\n historyDays: number;\n /** `production` is the read-only monitoring dashboard of `brick start`. */\n mode: \"dev\" | \"production\";\n /** The project's extension; null when it has none. */\n extension: ExtensionBuild | null;\n}\n\n/** The server-sent events of `/api/events`, by name, with the data each carries. */\nexport type DashboardEvents = {\n snapshot: DashboardSnapshot;\n /** A rebuilt extension: the page reloads to run it. */\n extension: ExtensionBuild | null;\n} & { [E in DevTelemetryEvent as E[\"type\"]]: E };\n\n/** The store's event names; each event is sent under its `type`. */\nexport const TELEMETRY_EVENTS = Object.keys({\n trace: true,\n failure: true,\n reload: true,\n architecture: true,\n api: true,\n docs: true,\n inspector: true,\n} satisfies Record<\n DevTelemetryEvent[\"type\"],\n true\n>) as DevTelemetryEvent[\"type\"][];\n\n// ---------------------------------------------------------------------------\n// Stored history\n\n/** A finished request without its spans; fetch the full trace by id. */\nexport type HistoryTrace = Omit<TraceSummary, \"spans\"> & {\n /** \"GET /api/page/:id\" when the method and route are known, else the span name. */\n endpoint: string;\n};\n\n/** How a request ended: a 5xx or crash, a 4xx, or neither. */\nexport type Outcome = \"ok\" | \"client\" | \"server\";\n\n/** Rows in one page of `/api/history/traces`, unless the query asks for another number. */\nexport const HISTORY_PAGE_SIZE = 100;\n\nexport interface VolumeBucket {\n start: number;\n ok: number;\n client: number;\n server: number;\n}\n\n/** The numbers behind the cards at the top of the log, for what matches. */\nexport interface HistorySummary {\n total: number;\n clientErrors: number;\n serverErrors: number;\n medianMs: number;\n p95Ms: number;\n}\n\nexport interface FacetValue {\n value: string;\n count: number;\n}\n\n/** What is in the range, counted for each filter as if it were not applied. */\nexport interface HistoryFacets {\n outcome: FacetValue[];\n method: FacetValue[];\n service: FacetValue[];\n endpoint: FacetValue[];\n}\n\nexport interface HistoryInfo {\n days: number;\n count: number;\n oldestMs?: number;\n}\n\n// ---------------------------------------------------------------------------\n// Docs\n\n/** One entry of the docs sidebar. */\nexport type DocsNode =\n | { type: \"page\"; name: string; url: string; description?: string }\n | {\n type: \"folder\";\n name: string;\n index?: { name: string; url: string };\n children: DocsNode[];\n defaultOpen?: boolean;\n }\n | { type: \"separator\"; name?: string };\n\nexport interface DocsTree {\n name: string;\n children: DocsNode[];\n}\n\nexport interface DocsHeading {\n title: string;\n url: string;\n depth: number;\n}\n\n/** A page ready to run in the browser. */\nexport interface DocsPage {\n title: string;\n description?: string;\n /** The file, relative to the docs folder. */\n path: string;\n slugs: string[];\n toc: DocsHeading[];\n /** MDX compiled to a function body; see `runMdx` in the dashboard. */\n code: string;\n /** Set instead of `code` when the page does not compile. */\n error?: string;\n}\n\nexport interface DocsSearchHit {\n id: string;\n type: \"page\" | \"heading\" | \"text\";\n content: string;\n /** Route within the docs, with a `#heading` when the hit is inside a page. */\n url: string;\n}\n\nexport interface DocsInfo {\n tree: DocsTree;\n /** Whether the project supplied components of its own. */\n components: boolean;\n revision: number;\n}\n\n/** How a schedule fires: its cron expression and time zone, or its interval (`every 6h`). */\nexport function describeSchedule(schedule: {\n cron?: string;\n timeZone?: string;\n every?: number;\n}): string {\n if (schedule.cron)\n return schedule.timeZone && schedule.timeZone !== \"UTC\"\n ? `${schedule.cron} (${schedule.timeZone})`\n : schedule.cron;\n const ms = schedule.every ?? 0;\n for (const [unit, size] of [\n [\"d\", 86_400_000],\n [\"h\", 3_600_000],\n [\"m\", 60_000],\n [\"s\", 1000],\n ] as const)\n if (ms % size === 0) return `every ${ms / size}${unit}`;\n return `every ${ms}ms`;\n}\n"],"mappings":";;AAiFA,MAAM,MAAM,CAAC,KAAK;;;;;;;AAQlB,MAAa,SAAS;;CAEpB,QAAQ;EAAE,MAAM;EAAY,SAAS,CAAC,OAAO,MAAM;EAAG,YAAY;CAAK;CACvE,OAAO;EAAE,MAAM;EAAK,SAAS;EAAK,YAAY;CAAK;CACnD,QAAQ;EAAE,MAAM;EAAW,QAAQ;EAAM,SAAS;EAAK,YAAY;CAAK;;CAExE,KAAK;EAAE,MAAM;EAAQ,QAAQ;EAAM,YAAY;CAAY;CAC3D,OAAO;EAAE,MAAM;EAAc,SAAS;EAAK,YAAY;CAAK;CAC5D,QAAQ;EAAE,MAAM;EAAe,SAAS;EAAK,YAAY;CAAK;CAC9D,SAAS;EACP,MAAM;EACN,QAAQ;EACR,SAAS;EACT,YAAY;CACd;CACA,MAAM;EACJ,MAAM;EACN,QAAQ;EACR,SAAS;EACT,YAAY;EACZ,MAAM;CACR;CACA,SAAS;EACP,MAAM;EACN,SAAS;EACT,YAAY;EACZ,MAAM;CACR;;CAEA,OAAO;EAAE,MAAM;EAAc,YAAY;EAAO,MAAM;CAAO;;CAE7D,WAAW;EACT,MAAM;EACN,QAAQ;EACR,YAAY;EACZ,MAAM;CACR;;CAEA,WAAW;EACT,MAAM;EACN,QAAQ;EACR,SAAS,CAAC,OAAO,MAAM;EACvB,YAAY;EACZ,MAAM;CACR;CACA,QAAQ;EACN,MAAM;EACN,SAAS,CAAC,MAAM;EAChB,YAAY;EACZ,MAAM;CACR;CACA,SAAS;EACP,MAAM;EACN,SAAS,CAA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;;AAGA,MAAa,YAAY,SACvB,GAAG,OAAO,OAAO,KAAK,GAAG;;;;;;;AAoB3B,MAAa,iBAAiB;CAC5B;EAAE,WAAW;EAAS,MAAM;EAAY,QAAQ;CAAQ;CACxD;EACE,WAAW;EACX,MAAM;EACN,QAAQ;CACV;CACA;EACE,WAAW;EACX,MAAM;EACN,QAAQ;CACV;CACA;EAAE,WAAW;EAAa,MAAM;EAAgB,QAAQ;CAAW;CACnE;EACE,WAAW;EACX,MAAM;EACN,QAAQ;CACV;CAEA;EAAE,WAAW;EAA2B,MAAM;CAAS;AACzD;;AAoBA,MAAa,oBAAoB;;AAWjC,MAAa,cAAc;CAAE,QAAQ;CAAK,UAAU;CAAK,SAAS;AAAI;;AAqQtE,SAAgB,iBAAiB,UAItB;CACT,IAAI,SAAS,MACX,OAAO,SAAS,YAAY,SAAS,aAAa,QAC9C,GAAG,SAAS,KAAK,IAAI,SAAS,SAAS,KACvC,SAAS;CACf,MAAM,KAAK,SAAS,SAAS;CAC7B,KAAK,MAAM,CAAC,MAAM,SAAS;EACzB,CAAC,KAAK,KAAU;EAChB,CAAC,KAAK,IAAS;EACf,CAAC,KAAK,GAAM;EACZ,CAAC,KAAK,GAAI;CACZ,GACE,IAAI,KAAK,SAAS,GAAG,OAAO,SAAS,KAAK,OAAO;CACnD,OAAO,SAAS,GAAG;AACrB"}
1
+ {"version":3,"file":"dashboard-protocol.js","names":[],"sources":["../src/dashboard-protocol.ts"],"sourcesContent":["import type { Attributes } from \"@opentelemetry/api\";\nimport type { ArchitectureSchema } from \"@brickkit/core\";\n\n/*\n * What the dashboard server and its page agree on: the routes, headers, event\n * names and the data they carry. Types and constants only, so the page can\n * import it without the server's code.\n */\n\n// ---------------------------------------------------------------------------\n// Span records: what the app's tracer reports, over IPC or `/api/ingest`\n\nexport interface SpanEventRecord {\n name: string;\n timeMs: number;\n attributes: Attributes;\n}\n\nexport interface SpanStartRecord {\n phase: \"start\";\n traceId: string;\n spanId: string;\n parentSpanId?: string;\n name: string;\n startMs: number;\n attributes: Attributes;\n}\n\nexport interface SpanEndRecord {\n phase: \"end\";\n traceId: string;\n spanId: string;\n name: string;\n endMs: number;\n status: \"unset\" | \"ok\" | \"error\";\n statusMessage?: string;\n attributes: Attributes;\n events: SpanEventRecord[];\n}\n\nexport type TelemetryRecord = SpanStartRecord | SpanEndRecord;\n\nexport type WorkerErrorPhase = \"startup\" | \"uncaught\" | \"unhandled-rejection\";\n\nexport interface SerializedError {\n name: string;\n message: string;\n stack?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Routes\n\n/** The dashboard's built-in views; `#/<view>/…` opens one. */\nexport const VIEW_NAMES = [\n \"requests\",\n \"logs\",\n \"overview\",\n \"apis\",\n \"docs\",\n \"workflows\",\n \"schedules\",\n \"errors\",\n \"reloads\",\n] as const;\nexport type ViewName = (typeof VIEW_NAMES)[number];\n\ninterface RouteSpec {\n path: string;\n /** Also answers every path below `path`. */\n prefix?: boolean;\n /** The methods it answers; any when absent. */\n methods?: readonly string[];\n /**\n * Served by the production dashboard; `\"extension\"`: only when it has one;\n * `\"inspector\"`: only with `dashboard.inspector` and a running inspector.\n */\n production: boolean | \"extension\" | \"inspector\" | \"mcp\";\n /** The page's view that needs it; a view whose routes production lacks is hidden there. */\n view?: ViewName;\n /** It changes something, so the request must carry `CSRF_HEADER`. */\n csrf?: true;\n}\n\nconst GET = [\"GET\"] as const;\n\n/**\n * Every route the dashboard serves. The server dispatches from this table and\n * the page builds its URLs from it. Production serves only what is marked\n * `production`.\n */\nexport const ROUTES = {\n /** Open to everyone: uptime monitors cannot sign in. */\n health: { path: \"/_health\", methods: [\"GET\", \"HEAD\"], production: true },\n shell: { path: \"/\", methods: GET, production: true },\n assets: { path: \"/assets\", prefix: true, methods: GET, production: true },\n /** The app itself, for an extension's `appFetch`. */\n app: { path: \"/app\", prefix: true, production: \"extension\" },\n state: { path: \"/api/state\", methods: GET, production: true },\n events: { path: \"/api/events\", methods: GET, production: true },\n history: {\n path: \"/api/history\",\n prefix: true,\n methods: GET,\n production: true,\n },\n docs: {\n path: \"/api/docs\",\n prefix: true,\n methods: GET,\n production: false,\n view: \"docs\",\n },\n openapi: {\n path: \"/api/openapi\",\n methods: GET,\n production: false,\n view: \"apis\",\n },\n /** Try it in the APIs view; the app is another origin. */\n proxy: { path: \"/api/proxy\", production: false, view: \"apis\" },\n /** The workflow inspector the app serves on a port of its own. */\n workflows: {\n path: \"/workflows\",\n prefix: true,\n production: \"inspector\",\n view: \"workflows\",\n },\n /** The app's schedules, served beside the workflow inspector: list them, run one now. */\n schedules: {\n path: \"/api/schedules\",\n prefix: true,\n methods: [\"GET\", \"POST\"],\n production: \"inspector\",\n view: \"schedules\",\n },\n mcp: { path: \"/mcp\", production: \"mcp\" },\n ingest: {\n path: \"/api/ingest\",\n methods: [\"POST\"],\n production: false,\n csrf: true,\n },\n restart: {\n path: \"/api/restart\",\n methods: [\"POST\"],\n production: false,\n csrf: true,\n },\n} as const satisfies Record<string, RouteSpec>;\n\nexport type RouteName = keyof typeof ROUTES;\n\n/** The route a request is for, or undefined when none answers it. */\nexport function matchRoute(\n method: string | undefined,\n pathname: string,\n): RouteName | undefined {\n for (const [name, route] of Object.entries(ROUTES) as [\n RouteName,\n RouteSpec,\n ][]) {\n const at =\n pathname === route.path ||\n (route.prefix === true && pathname.startsWith(`${route.path}/`));\n if (at && (!route.methods || route.methods.includes(method ?? \"\")))\n return name;\n }\n return undefined;\n}\n\nexport const viewsWithout = (\n served: (route: RouteName) => boolean,\n): ViewName[] => [\n ...new Set(\n (Object.entries(ROUTES) as [RouteName, RouteSpec][]).flatMap(\n ([name, route]) => (route.view && !served(name) ? [route.view] : []),\n ),\n ),\n];\n\n/** What each history query endpoint answers, as JSON. */\nexport interface HistoryResponses {\n summary: HistorySummary;\n traces: { total: number; traces: HistoryTrace[] };\n facets: HistoryFacets;\n volume: VolumeBucket[];\n}\n\n/** The history endpoints: the JSON queries, and `export` (CSV). */\nexport type HistoryEndpoint = keyof HistoryResponses | \"export\";\n\n/** A history query's address; with no endpoint, what the history holds. */\nexport const historyUrl = (\n endpoint?: HistoryEndpoint,\n params?: URLSearchParams,\n): string =>\n `${ROUTES.history.path}${endpoint ? `/${endpoint}` : \"\"}${params ? `?${params}` : \"\"}`;\n\nexport const historyTraceUrl = (traceId: string): string =>\n `${historyUrl(\"traces\")}/${encodeURIComponent(traceId)}`;\n\n/** The Docs tab's data: tree, search, compiled pages, files, components. */\nexport const DOCS_PATHS = {\n info: ROUTES.docs.path,\n search: `${ROUTES.docs.path}/search`,\n components: `${ROUTES.docs.path}/components.js`,\n page: `${ROUTES.docs.path}/page`,\n files: `${ROUTES.docs.path}/files`,\n} as const;\n\n/** A path segment as written, when it is not valid percent-encoding. */\nexport function decode(value: string): string {\n try {\n return decodeURIComponent(value);\n } catch {\n return value;\n }\n}\n\n/**\n * A page address, `#/<segments>#<anchor>`, each part encoded. Every view's\n * links are built with it, and the page's `parseRoute` reads them back.\n */\nexport const hashHref = (segments: string[], anchor?: string): string =>\n `#/${encodePath(segments)}${anchor ? `#${encodeURIComponent(anchor)}` : \"\"}`;\n\n/** The page's address of a docs page, optionally at one of its headings. */\nexport const docsHref = (path: string[], anchor?: string): string =>\n hashHref([\"docs\", ...path], anchor);\n\nconst encodePath = (path: string[]): string =>\n path.map(encodeURIComponent).join(\"/\");\n\n/** Where a file in the docs folder is served, by its path inside it. */\nexport const docsFileUrl = (path: string): string =>\n `${DOCS_PATHS.files}/${encodePath(path.split(\"/\"))}`;\n\n/** Where a compiled docs page is served, by its slugs. */\nexport const docsPageUrl = (path: string[]): string =>\n `${DOCS_PATHS.page}/${encodePath(path)}`;\n\n/** Where the docs search answers `query`. */\nexport const docsSearchUrl = (query: string): string =>\n `${DOCS_PATHS.search}?q=${encodeURIComponent(query)}`;\n\n/** Whether a link names a scheme (`https:`, `mailto:`) and so leaves the dashboard. */\nexport const isExternalHref = (href: string): boolean =>\n /^[a-z][a-z\\d+.-]*:/i.test(href);\n\n/**\n * Sent with every request that changes something (restart, ingest). A page on\n * another site cannot send it without a preflight, which the server never\n * answers.\n */\nexport const CSRF_HEADER = \"x-brick-dashboard\";\nexport const CSRF_VALUE = \"1\";\n\n/** The header that proves a request to the workflow inspector comes from the dashboard. */\nexport const INSPECTOR_TOKEN_HEADER = \"x-brick-inspector\";\n\nexport const INSPECTOR_READ_ONLY_HEADER = \"x-brick-inspector-read-only\";\n\n/** What a process that cannot share memory with the dashboard posts to `/api/ingest`. */\nexport interface IngestPayload {\n /** Span records, of the newest generation. */\n records?: TelemetryRecord[];\n /** A notice that the app loaded: a new generation begins. */\n worker?: string;\n}\n\n// ---------------------------------------------------------------------------\n// The shell and its assets\n\n/** The files the shell loads from `ROUTES.assets.path`. `app.*` come from the dashboard's build. */\nexport const ASSETS = {\n app: \"app.js\",\n appCss: \"app.css\",\n /** The project's extension, or the list of parts when plugins have one too. */\n extension: \"extension.js\",\n extensionCss: \"extension.css\",\n /** The project's theme tokens; see `themeCss`. */\n theme: \"brick-theme.css\",\n} as const;\n\n/** Where an asset is served. */\nexport const assetUrl = (file: string): string =>\n `${ROUTES.assets.path}/${file}`;\n\n/**\n * What the shell tells the page in its markup: a `<meta name=\"brick-extension\"\n * data-revision data-src>` for the extension, and the theme's `<link>`.\n */\nexport const SHELL = {\n extensionMeta: 'meta[name=\"brick-extension\"]',\n themeLink: \"link[data-brick-theme]\",\n} as const;\n\n// ---------------------------------------------------------------------------\n// Modules the page shares with the project's own\n\n/**\n * What the dashboard supplies to the project's docs components and dashboard\n * extension, so there is one copy of React and of the UI kit on the page: the\n * bundler leaves `specifier` external, the shell's import map points it at\n * `/assets/<file>`, and `file` hands over the page's `globalThis.__brickDashboard[global]`.\n */\nexport const SHARED_MODULES = [\n { specifier: \"react\", file: \"react.js\", global: \"React\" },\n {\n specifier: \"react/jsx-runtime\",\n file: \"react-jsx-runtime.js\",\n global: \"jsxRuntime\",\n },\n {\n specifier: \"react/jsx-dev-runtime\",\n file: \"react-jsx-runtime.js\",\n global: \"jsxRuntime\",\n },\n { specifier: \"react-dom\", file: \"react-dom.js\", global: \"ReactDOM\" },\n {\n specifier: \"react-dom/client\",\n file: \"react-dom-client.js\",\n global: \"ReactDOMClient\",\n },\n // The UI kit is a module of the dashboard's own build.\n { specifier: \"@brickkit/cli/dashboard\", file: \"kit.js\" },\n] as const;\n\nexport type SharedGlobal = Extract<\n (typeof SHARED_MODULES)[number],\n { global: string }\n>[\"global\"];\n\n/**\n * One of several dashboard extensions (the app's and its plugins'), as\n * `/assets/extension.js` lists them in `export const parts`.\n */\nexport interface ExtensionPart {\n name: string;\n /** Relative to `extension.js`. */\n src: string;\n /** A plugin's: its pages without a place go under a section named after it. */\n plugin: boolean;\n}\n\n/** Where the page keeps the chosen theme; the shell applies it before first paint. */\nexport const THEME_STORAGE_KEY = \"brick-dashboard-theme\";\n\n// ---------------------------------------------------------------------------\n// Span names and attribute keys core sets, read here and on the page\n\nexport { SPAN, ATTR } from \"@brickkit/core/client\";\n\n// ---------------------------------------------------------------------------\n// Live data\n\n/** How many of each the live state keeps, on the server and on the page. */\nexport const LIVE_LIMITS = { traces: 200, failures: 200, reloads: 100 };\n\nexport type SpanOutcome = \"running\" | \"ok\" | \"error\" | \"interrupted\";\n\nexport interface TraceSpan {\n spanId: string;\n parentSpanId?: string;\n name: string;\n startMs: number;\n endMs?: number;\n status: SpanOutcome;\n statusMessage?: string;\n attributes: Attributes;\n events: SpanEventRecord[];\n}\n\nexport interface TraceSummary {\n traceId: string;\n name: string;\n method?: string;\n route?: string;\n /** The request's actual path, which differs from a wildcard route template. */\n path?: string;\n httpStatus?: number;\n generation: number;\n startMs: number;\n endMs?: number;\n durationMs?: number;\n status: SpanOutcome;\n truncated: boolean;\n /** The service and action that handled the request, when it ran one. */\n service?: string;\n action?: string;\n /** Why it failed, when it did. */\n message?: string;\n spans: TraceSpan[];\n}\n\nexport interface FailureSummary {\n id: number;\n at: number;\n phase: \"request\" | WorkerErrorPhase;\n code: string;\n message: string;\n status?: number;\n stack?: string;\n traceId?: string;\n route?: string;\n service?: string;\n action?: string;\n generation: number;\n}\n\nexport type ReloadKind = \"started\" | \"restarting\" | \"exited\" | \"contract-ready\";\n\nexport interface ReloadSummary {\n id: number;\n at: number;\n kind: ReloadKind;\n generation: number;\n detail?: string;\n}\n\n/** Services, actions, and routes of the application as last started. */\nexport interface ArchitectureSnapshot {\n generation: number;\n schema: ArchitectureSchema;\n}\n\n/** The OpenAPI documents the app offers, for the dashboard's APIs view. */\nexport interface ApiSnapshot {\n /** Changes each time the documents are replaced, so views know to reload. */\n revision: number;\n /** Where the app listens; Try it in the APIs view sends requests here. */\n appUrl?: string;\n /** Names of the documents, in order. */\n titles: string[];\n}\n\n/** What the dashboard knows about the app's developer documentation. */\nexport type DocsSnapshot =\n | {\n status: \"ready\";\n /** Changes whenever the pages change, so the Docs tab reloads. */\n revision: number;\n title: string;\n /** Whether the project supplied components of its own. */\n components: boolean;\n }\n /** The packages the docs need are not installed. */\n | { status: \"missing\"; packages: string[]; message: string }\n /** Why the docs cannot be shown. */\n | { status: \"error\"; message: string };\n\n/** The project's dashboard extension as last built. */\nexport interface ExtensionBuild {\n revision: number;\n /** Why the last build failed. */\n error?: string;\n}\n\nexport type DevTelemetryEvent =\n | { type: \"trace\"; trace: TraceSummary }\n | { type: \"failure\"; failure: FailureSummary }\n | { type: \"reload\"; reload: ReloadSummary }\n | { type: \"architecture\"; architecture: ArchitectureSnapshot }\n | { type: \"api\"; api: ApiSnapshot }\n | { type: \"docs\"; docs: DocsSnapshot | null }\n | { type: \"inspector\"; inspector: boolean };\n\nexport interface DevTelemetrySnapshot {\n traces: TraceSummary[];\n failures: FailureSummary[];\n reloads: ReloadSummary[];\n architecture: ArchitectureSnapshot | null;\n api: ApiSnapshot | null;\n /** Null when the app has no `documentation`. */\n docs: DocsSnapshot | null;\n /** Whether the app serves the workflow inspector the dashboard can show. */\n inspector: boolean;\n}\n\n/** `/api/state`, and the first event of `/api/events`: the store's snapshot and the server's own fields. */\nexport interface DashboardSnapshot extends DevTelemetrySnapshot {\n /** Whether the host can restart the app; the page shows the button. */\n canRestart: boolean;\n /** Days of requests kept on disk; zero when history is off. */\n historyDays: number;\n /** `production` is the monitoring dashboard of `brick start`. */\n mode: \"dev\" | \"production\";\n hiddenViews: ViewName[];\n /** The project's extension; null when it has none. */\n extension: ExtensionBuild | null;\n}\n\n/** The server-sent events of `/api/events`, by name, with the data each carries. */\nexport type DashboardEvents = {\n snapshot: DashboardSnapshot;\n /** A rebuilt extension: the page reloads to run it. */\n extension: ExtensionBuild | null;\n} & { [E in DevTelemetryEvent as E[\"type\"]]: E };\n\n/** The store's event names; each event is sent under its `type`. */\nexport const TELEMETRY_EVENTS = Object.keys({\n trace: true,\n failure: true,\n reload: true,\n architecture: true,\n api: true,\n docs: true,\n inspector: true,\n} satisfies Record<\n DevTelemetryEvent[\"type\"],\n true\n>) as DevTelemetryEvent[\"type\"][];\n\n// ---------------------------------------------------------------------------\n// Stored history\n\n/** A finished request without its spans; fetch the full trace by id. */\nexport type HistoryTrace = Omit<TraceSummary, \"spans\"> & {\n /** \"GET /api/page/:id\" when the method and route are known, else the span name. */\n endpoint: string;\n};\n\n/** How a request ended: a 5xx or crash, a 4xx, or neither. */\nexport type Outcome = \"ok\" | \"client\" | \"server\";\n\n/** Rows in one page of `/api/history/traces`, unless the query asks for another number. */\nexport const HISTORY_PAGE_SIZE = 100;\n\nexport interface VolumeBucket {\n start: number;\n ok: number;\n client: number;\n server: number;\n}\n\n/** The numbers behind the cards at the top of the log, for what matches. */\nexport interface HistorySummary {\n total: number;\n clientErrors: number;\n serverErrors: number;\n medianMs: number;\n p95Ms: number;\n}\n\nexport interface FacetValue {\n value: string;\n count: number;\n}\n\n/** What is in the range, counted for each filter as if it were not applied. */\nexport interface HistoryFacets {\n outcome: FacetValue[];\n method: FacetValue[];\n service: FacetValue[];\n endpoint: FacetValue[];\n}\n\nexport interface HistoryInfo {\n days: number;\n count: number;\n oldestMs?: number;\n}\n\n// ---------------------------------------------------------------------------\n// Docs\n\n/** One entry of the docs sidebar. */\nexport type DocsNode =\n | { type: \"page\"; name: string; url: string; description?: string }\n | {\n type: \"folder\";\n name: string;\n index?: { name: string; url: string };\n children: DocsNode[];\n defaultOpen?: boolean;\n }\n | { type: \"separator\"; name?: string };\n\nexport interface DocsTree {\n name: string;\n children: DocsNode[];\n}\n\nexport interface DocsHeading {\n title: string;\n url: string;\n depth: number;\n}\n\n/** A page ready to run in the browser. */\nexport interface DocsPage {\n title: string;\n description?: string;\n /** The file, relative to the docs folder. */\n path: string;\n slugs: string[];\n toc: DocsHeading[];\n /** MDX compiled to a function body; see `runMdx` in the dashboard. */\n code: string;\n /** Set instead of `code` when the page does not compile. */\n error?: string;\n}\n\nexport interface DocsSearchHit {\n id: string;\n type: \"page\" | \"heading\" | \"text\";\n content: string;\n /** Route within the docs, with a `#heading` when the hit is inside a page. */\n url: string;\n}\n\nexport interface DocsInfo {\n tree: DocsTree;\n /** Whether the project supplied components of its own. */\n components: boolean;\n revision: number;\n}\n\n/** How a schedule fires: its cron expression and time zone, or its interval (`every 6h`). */\nexport function describeSchedule(schedule: {\n cron?: string;\n timeZone?: string;\n every?: number;\n}): string {\n if (schedule.cron)\n return schedule.timeZone && schedule.timeZone !== \"UTC\"\n ? `${schedule.cron} (${schedule.timeZone})`\n : schedule.cron;\n const ms = schedule.every ?? 0;\n for (const [unit, size] of [\n [\"d\", 86_400_000],\n [\"h\", 3_600_000],\n [\"m\", 60_000],\n [\"s\", 1000],\n ] as const)\n if (ms % size === 0) return `every ${ms / size}${unit}`;\n return `every ${ms}ms`;\n}\n"],"mappings":";;AAoFA,MAAM,MAAM,CAAC,KAAK;;;;;;AAOlB,MAAa,SAAS;;CAEpB,QAAQ;EAAE,MAAM;EAAY,SAAS,CAAC,OAAO,MAAM;EAAG,YAAY;CAAK;CACvE,OAAO;EAAE,MAAM;EAAK,SAAS;EAAK,YAAY;CAAK;CACnD,QAAQ;EAAE,MAAM;EAAW,QAAQ;EAAM,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c;CAAE,QAAQ;CAAK,UAAU;CAAK,SAAS;AAAI;;AAsQtE,SAAgB,iBAAiB,UAItB;CACT,IAAI,SAAS,MACX,OAAO,SAAS,YAAY,SAAS,aAAa,QAC9C,GAAG,SAAS,KAAK,IAAI,SAAS,SAAS,KACvC,SAAS;CACf,MAAM,KAAK,SAAS,SAAS;CAC7B,KAAK,MAAM,CAAC,MAAM,SAAS;EACzB,CAAC,KAAK,KAAU;EAChB,CAAC,KAAK,IAAS;EACf,CAAC,KAAK,GAAM;EACZ,CAAC,KAAK,GAAI;CACZ,GACE,IAAI,KAAK,SAAS,GAAG,OAAO,SAAS,KAAK,OAAO;CACnD,OAAO,SAAS,GAAG;AACrB"}
@@ -175,9 +175,9 @@ export declare function useAppQuery<T>(query: ((signal: AbortSignal) => Promise<
175
175
  */
176
176
  export declare function useAppFetch<T = unknown>(path: string | null, init?: RequestInit): AppFetchResult<T>;
177
177
  /**
178
- * Efferd's card: a square, 1px-bordered surface with a plus mark on each
179
- * corner, built on the shadcn Card with its radius and ring removed. A `title`
180
- * is a heading row across the top.
178
+ * The landing page's card: a square, 1px-bordered surface on the card color,
179
+ * built on the shadcn Card with its radius and ring removed. A `title` is a
180
+ * heading row across the top.
181
181
  */
182
182
  export declare function Panel({ className, children, title, ...props }: Omit<ComponentProps<"div">, "title"> & {
183
183
  title?: ReactNode;
@@ -0,0 +1,111 @@
1
+ import { a as INSPECTOR_READ_ONLY_HEADER, c as ROUTES } from "./dashboard-protocol.js";
2
+ import { existsSync, statSync } from "node:fs";
3
+ import { join, resolve, sep } from "node:path";
4
+ import { fileURLToPath, pathToFileURL } from "node:url";
5
+ import { randomBytes } from "node:crypto";
6
+ // src/dev-inspector.ts
7
+ const INSPECTOR_PATH = ROUTES.workflows.path;
8
+ const READ_ONLY = "This sign-in can look but not change anything. To run a schedule or change a run, sign in as a user: dashboard.auth.authorize must return { user }.";
9
+ /** The built inspector, next to `src/` in the repo and next to `dist/` when published. */
10
+ const INSPECTOR_DIRECTORY = fileURLToPath(new URL("../inspector-dist/", import.meta.url));
11
+ /** Whether a path is a regular file; any failure to find out (not a directory, name too long) says no. */
12
+ function isFile(path) {
13
+ try {
14
+ return statSync(path).isFile();
15
+ } catch {
16
+ return false;
17
+ }
18
+ }
19
+ /**
20
+ * A file of the inspector's browser build. Its names carry a hash of their
21
+ * content, so a browser may keep them for good. Anything else under `assets/`
22
+ * is a plain 404: the page would answer with HTML. `undefined` for requests
23
+ * outside `assets/`, which are the page's to answer.
24
+ */
25
+ function browserAsset(request, client) {
26
+ if (request.method !== "GET" && request.method !== "HEAD") return void 0;
27
+ const { pathname } = new URL(request.url);
28
+ if (!pathname.startsWith(`${INSPECTOR_PATH}/assets/`)) return void 0;
29
+ const file = resolve(client, pathname.slice(INSPECTOR_PATH.length + 1));
30
+ if (!file.startsWith(client + sep) || !isFile(file)) return new Response("Not found", { status: 404 });
31
+ return new Response(Bun.file(file), { headers: { "cache-control": "public, max-age=31536000, immutable" } });
32
+ }
33
+ /**
34
+ * The app's schedules, for the dashboard's Schedules view: `GET` lists them,
35
+ * `POST <path>/<name>` runs one now.
36
+ */
37
+ async function schedulesRoute(schedules, names, request, pathname, readOnly) {
38
+ let name;
39
+ try {
40
+ name = decodeURIComponent(pathname.slice(ROUTES.schedules.path.length + 1));
41
+ } catch (error) {
42
+ return new Response(error.message, { status: 400 });
43
+ }
44
+ if (request.method === "GET" && !name) return Response.json(await schedules.list());
45
+ if (request.method !== "POST" || !name) return new Response("Not found", { status: 404 });
46
+ if (!names.has(name)) return new Response(`No schedule named '${name}'`, { status: 404 });
47
+ if (readOnly) return new Response(READ_ONLY, { status: 403 });
48
+ try {
49
+ return Response.json({ started: await schedules.trigger(name) });
50
+ } catch (error) {
51
+ return new Response(error.message, { status: 500 });
52
+ }
53
+ }
54
+ /**
55
+ * Serve the Workflow inspector (the Workflow SDK's observability UI, built into
56
+ * this package) for the app's world, and the app's schedules, on a loopback
57
+ * port of its own. The dashboard proxies them at `/workflows` and
58
+ * `/api/schedules`; it is the only caller that knows the token. The UI can
59
+ * cancel runs and resume hooks, and a schedule can be run from it, so nothing
60
+ * else may reach it.
61
+ *
62
+ * @param app - The loaded app, running in this process.
63
+ * @param directory - The inspector's build; this package's own by default.
64
+ * @returns The inspector, or `undefined` when the app runs no workflows and has no schedules.
65
+ * @throws When the inspector's build is missing.
66
+ */
67
+ async function startInspector(app, directory = INSPECTOR_DIRECTORY) {
68
+ const target = app.events?.workflows;
69
+ const schedules = app.events?.schedules;
70
+ if (!target && !schedules) return void 0;
71
+ const workflows = target && await workflowsPage(target, directory).catch((error) => {
72
+ if (!schedules) throw error;
73
+ console.warn(`[Brick-TS] ${error.message}`);
74
+ });
75
+ const names = new Set(schedules ? app.events.describe().schedules?.map((schedule) => schedule.name) : []);
76
+ const token = randomBytes(16).toString("hex");
77
+ const server = Bun.serve({
78
+ hostname: "127.0.0.1",
79
+ port: 0,
80
+ idleTimeout: 0,
81
+ fetch: (request) => {
82
+ if (request.headers.get("x-brick-inspector") !== token) return new Response("Forbidden", { status: 403 });
83
+ const { pathname } = new URL(request.url);
84
+ const readOnly = request.headers.has(INSPECTOR_READ_ONLY_HEADER);
85
+ if (schedules && pathname.startsWith(ROUTES.schedules.path)) return schedulesRoute(schedules, names, request, pathname, readOnly);
86
+ if (!workflows) return new Response("Not found", { status: 404 });
87
+ return browserAsset(request, workflows.client) ?? workflows.page(request, {
88
+ readOnly,
89
+ refusal: READ_ONLY
90
+ });
91
+ }
92
+ });
93
+ return {
94
+ port: server.port,
95
+ workflows: Boolean(workflows),
96
+ token,
97
+ stop: () => void server.stop(true)
98
+ };
99
+ }
100
+ async function workflowsPage(target, directory) {
101
+ const entry = join(directory, "server", "index.js");
102
+ if (!existsSync(entry)) throw new Error("The workflow inspector is not built. Build it with: bun run --filter @brickkit/cli build");
103
+ const { createFetchHandler } = await import(pathToFileURL(entry).href);
104
+ return {
105
+ page: createFetchHandler(INSPECTOR_PATH, { world: target.world }),
106
+ client: join(directory, "client")
107
+ };
108
+ }
109
+ export { startInspector as t };
110
+
111
+ //# sourceMappingURL=dev-inspector.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dev-inspector.js","names":[],"sources":["../src/dev-inspector.ts"],"sourcesContent":["import { randomBytes } from \"node:crypto\";\nimport { existsSync, statSync } from \"node:fs\";\nimport { join, resolve, sep } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport type { BrickApp, ScheduleControl } from \"@brickkit/core\";\nimport type { CreateFetchHandler } from \"../../workflow-inspector/server/handler\";\nimport {\n INSPECTOR_READ_ONLY_HEADER,\n INSPECTOR_TOKEN_HEADER,\n ROUTES,\n} from \"./dashboard-protocol\";\n\nconst INSPECTOR_PATH = ROUTES.workflows.path;\n\nconst READ_ONLY =\n \"This sign-in can look but not change anything. To run a schedule or change a run, sign in as a user: dashboard.auth.authorize must return { user }.\";\n\nexport interface Inspector {\n readonly port: number;\n /** Whether it serves the workflow inspector; it may serve only the schedules. */\n readonly workflows: boolean;\n /** Every request must carry it in `INSPECTOR_TOKEN_HEADER`. */\n readonly token: string;\n stop(): void;\n}\n\n/** The built inspector, next to `src/` in the repo and next to `dist/` when published. */\nconst INSPECTOR_DIRECTORY = fileURLToPath(\n new URL(\"../inspector-dist/\", import.meta.url),\n);\n\n/** Whether a path is a regular file; any failure to find out (not a directory, name too long) says no. */\nfunction isFile(path: string): boolean {\n try {\n return statSync(path).isFile();\n } catch {\n return false;\n }\n}\n\n/**\n * A file of the inspector's browser build. Its names carry a hash of their\n * content, so a browser may keep them for good. Anything else under `assets/`\n * is a plain 404: the page would answer with HTML. `undefined` for requests\n * outside `assets/`, which are the page's to answer.\n */\nfunction browserAsset(request: Request, client: string): Response | undefined {\n if (request.method !== \"GET\" && request.method !== \"HEAD\") return undefined;\n const { pathname } = new URL(request.url);\n if (!pathname.startsWith(`${INSPECTOR_PATH}/assets/`)) return undefined;\n const file = resolve(client, pathname.slice(INSPECTOR_PATH.length + 1));\n if (!file.startsWith(client + sep) || !isFile(file))\n return new Response(\"Not found\", { status: 404 });\n return new Response(Bun.file(file), {\n headers: { \"cache-control\": \"public, max-age=31536000, immutable\" },\n });\n}\n\n/**\n * The app's schedules, for the dashboard's Schedules view: `GET` lists them,\n * `POST <path>/<name>` runs one now.\n */\nasync function schedulesRoute(\n schedules: ScheduleControl,\n names: ReadonlySet<string>,\n request: Request,\n pathname: string,\n readOnly: boolean,\n): Promise<Response> {\n let name: string;\n try {\n name = decodeURIComponent(pathname.slice(ROUTES.schedules.path.length + 1));\n } catch (error) {\n return new Response((error as Error).message, { status: 400 });\n }\n if (request.method === \"GET\" && !name)\n return Response.json(await schedules.list());\n if (request.method !== \"POST\" || !name)\n return new Response(\"Not found\", { status: 404 });\n if (!names.has(name))\n return new Response(`No schedule named '${name}'`, { status: 404 });\n if (readOnly) return new Response(READ_ONLY, { status: 403 });\n try {\n return Response.json({ started: await schedules.trigger(name) });\n } catch (error) {\n return new Response((error as Error).message, { status: 500 });\n }\n}\n\n/**\n * Serve the Workflow inspector (the Workflow SDK's observability UI, built into\n * this package) for the app's world, and the app's schedules, on a loopback\n * port of its own. The dashboard proxies them at `/workflows` and\n * `/api/schedules`; it is the only caller that knows the token. The UI can\n * cancel runs and resume hooks, and a schedule can be run from it, so nothing\n * else may reach it.\n *\n * @param app - The loaded app, running in this process.\n * @param directory - The inspector's build; this package's own by default.\n * @returns The inspector, or `undefined` when the app runs no workflows and has no schedules.\n * @throws When the inspector's build is missing.\n */\nexport async function startInspector(\n app: BrickApp,\n directory = INSPECTOR_DIRECTORY,\n): Promise<Inspector | undefined> {\n const target = app.events?.workflows;\n const schedules = app.events?.schedules;\n if (!target && !schedules) return undefined;\n // An unbuilt inspector costs the Workflows view, not the schedules.\n const workflows =\n target &&\n (await workflowsPage(target, directory).catch((error: unknown) => {\n if (!schedules) throw error;\n console.warn(`[Brick-TS] ${(error as Error).message}`);\n return undefined;\n }));\n const names = new Set(\n schedules\n ? app.events!.describe().schedules?.map((schedule) => schedule.name)\n : [],\n );\n const token = randomBytes(16).toString(\"hex\");\n const server = Bun.serve({\n hostname: \"127.0.0.1\",\n port: 0,\n // The UI streams a run's output and holds the connection open.\n idleTimeout: 0,\n fetch: (request) => {\n if (request.headers.get(INSPECTOR_TOKEN_HEADER) !== token)\n return new Response(\"Forbidden\", { status: 403 });\n const { pathname } = new URL(request.url);\n const readOnly = request.headers.has(INSPECTOR_READ_ONLY_HEADER);\n if (schedules && pathname.startsWith(ROUTES.schedules.path))\n return schedulesRoute(schedules, names, request, pathname, readOnly);\n if (!workflows) return new Response(\"Not found\", { status: 404 });\n return (\n browserAsset(request, workflows.client) ??\n workflows.page(request, { readOnly, refusal: READ_ONLY })\n );\n },\n });\n return {\n port: server.port!,\n workflows: Boolean(workflows),\n token,\n stop: () => void server.stop(true),\n };\n}\n\nasync function workflowsPage(\n target: NonNullable<NonNullable<BrickApp[\"events\"]>[\"workflows\"]>,\n directory: string,\n) {\n const entry = join(directory, \"server\", \"index.js\");\n if (!existsSync(entry))\n throw new Error(\n \"The workflow inspector is not built. Build it with: bun run --filter @brickkit/cli build\",\n );\n const { createFetchHandler } = (await import(pathToFileURL(entry).href)) as {\n createFetchHandler: CreateFetchHandler;\n };\n const page = createFetchHandler(INSPECTOR_PATH, {\n // Core types only the parts of the world it calls; the world is a whole Workflow SDK World.\n world: target.world as Parameters<CreateFetchHandler>[1][\"world\"],\n });\n return { page, client: join(directory, \"client\") };\n}\n"],"mappings":";;;;;;AAYA,MAAM,iBAAiB,OAAO,UAAU;AAExC,MAAM,YACJ;;AAYF,MAAM,sBAAsB,cAC1B,IAAI,IAAI,sBAAsB,YAAY,GAAG,CAC/C;;AAGA,SAAS,OAAO,MAAuB;CACrC,IAAI;EACF,OAAO,SAAS,IAAI,CAAC,CAAC,OAAO;CAC/B,QAAQ;EACN,OAAO;CACT;AACF;;;;;;;AAQA,SAAS,aAAa,SAAkB,QAAsC;CAC5E,IAAI,QAAQ,WAAW,SAAS,QAAQ,WAAW,QAAQ,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AM,EAAE,uBAAwB,MAAM,OAAO,cAAc,KAAK,CAAC,CAAC;CAOlE,OAAO;EAAE,MAJI,mBAAmB,gBAAgB,EAE9C,OAAO,OAAO,MAChB,CACY;EAAG,QAAQ,KAAK,WAAW,QAAQ;CAAE;AACnD"}
@@ -1,109 +1,8 @@
1
- import { s as ROUTES } from "./dashboard-protocol.js";
1
+ import { t as startInspector } from "./dev-inspector.js";
2
2
  import { t as startDevApplication } from "./dev-application.js";
3
3
  import { t as sendToSupervisor } from "./dev-protocol.js";
4
4
  import { n as installWorkerTelemetry, r as reportWorkerError } from "./dev-telemetry.js";
5
- import { existsSync, statSync } from "node:fs";
6
- import { join, resolve, sep } from "node:path";
7
5
  import { getGlobalRegistry, stopAllEvents } from "@brickkit/core";
8
- import { fileURLToPath, pathToFileURL } from "node:url";
9
- import { randomBytes } from "node:crypto";
10
- // src/dev-inspector.ts
11
- const INSPECTOR_PATH = ROUTES.workflows.path;
12
- /** The built inspector, next to `src/` in the repo and next to `dist/` when published. */
13
- const INSPECTOR_DIRECTORY = fileURLToPath(new URL("../inspector-dist/", import.meta.url));
14
- /** Whether a path is a regular file; any failure to find out (not a directory, name too long) says no. */
15
- function isFile(path) {
16
- try {
17
- return statSync(path).isFile();
18
- } catch {
19
- return false;
20
- }
21
- }
22
- /**
23
- * A file of the inspector's browser build. Its names carry a hash of their
24
- * content, so a browser may keep them for good. Anything else under `assets/`
25
- * is a plain 404: the page would answer with HTML. `undefined` for requests
26
- * outside `assets/`, which are the page's to answer.
27
- */
28
- function browserAsset(request, client) {
29
- if (request.method !== "GET" && request.method !== "HEAD") return void 0;
30
- const { pathname } = new URL(request.url);
31
- if (!pathname.startsWith(`${INSPECTOR_PATH}/assets/`)) return void 0;
32
- const file = resolve(client, pathname.slice(INSPECTOR_PATH.length + 1));
33
- if (!file.startsWith(client + sep) || !isFile(file)) return new Response("Not found", { status: 404 });
34
- return new Response(Bun.file(file), { headers: { "cache-control": "public, max-age=31536000, immutable" } });
35
- }
36
- /**
37
- * The app's schedules, for the dashboard's Schedules view: `GET` lists them,
38
- * `POST <path>/<name>` runs one now.
39
- */
40
- async function schedulesRoute(schedules, names, request, pathname) {
41
- let name;
42
- try {
43
- name = decodeURIComponent(pathname.slice(ROUTES.schedules.path.length + 1));
44
- } catch (error) {
45
- return new Response(error.message, { status: 400 });
46
- }
47
- if (request.method === "GET" && !name) return Response.json(await schedules.list());
48
- if (request.method !== "POST" || !name) return new Response("Not found", { status: 404 });
49
- if (!names.has(name)) return new Response(`No schedule named '${name}'`, { status: 404 });
50
- try {
51
- return Response.json({ started: await schedules.trigger(name) });
52
- } catch (error) {
53
- return new Response(error.message, { status: 500 });
54
- }
55
- }
56
- /**
57
- * Serve the Workflow inspector (the Workflow SDK's observability UI, built into
58
- * this package) for the app's world, and the app's schedules, on a loopback
59
- * port of its own. The dashboard proxies them at `/workflows` and
60
- * `/api/schedules`; it is the only caller that knows the token. The UI can
61
- * cancel runs and resume hooks, and a schedule can be run from it, so nothing
62
- * else may reach it, and it exists only under `brick dev`.
63
- *
64
- * @param app - The loaded app, running in this process.
65
- * @param directory - The inspector's build; this package's own by default.
66
- * @returns The inspector, or `undefined` when the app runs no workflows and has no schedules.
67
- * @throws When the inspector's build is missing.
68
- */
69
- async function startInspector(app, directory = INSPECTOR_DIRECTORY) {
70
- const target = app.events?.workflows;
71
- const schedules = app.events?.schedules;
72
- if (!target && !schedules) return void 0;
73
- const workflows = target && await workflowsPage(target, directory).catch((error) => {
74
- if (!schedules) throw error;
75
- console.warn(`[Brick-TS] ${error.message}`);
76
- });
77
- const names = new Set(schedules ? app.events.describe().schedules?.map((schedule) => schedule.name) : []);
78
- const token = randomBytes(16).toString("hex");
79
- const server = Bun.serve({
80
- hostname: "127.0.0.1",
81
- port: 0,
82
- idleTimeout: 0,
83
- fetch: (request) => {
84
- if (request.headers.get("x-brick-inspector") !== token) return new Response("Forbidden", { status: 403 });
85
- const { pathname } = new URL(request.url);
86
- if (schedules && pathname.startsWith(ROUTES.schedules.path)) return schedulesRoute(schedules, names, request, pathname);
87
- if (!workflows) return new Response("Not found", { status: 404 });
88
- return browserAsset(request, workflows.client) ?? workflows.page(request);
89
- }
90
- });
91
- return {
92
- port: server.port,
93
- workflows: Boolean(workflows),
94
- token,
95
- stop: () => void server.stop(true)
96
- };
97
- }
98
- async function workflowsPage(target, directory) {
99
- const entry = join(directory, "server", "index.js");
100
- if (!existsSync(entry)) throw new Error("The workflow inspector is not built. Build it with: bun run --filter @brickkit/cli build");
101
- const { createFetchHandler } = await import(pathToFileURL(entry).href);
102
- return {
103
- page: createFetchHandler(INSPECTOR_PATH, { world: target.world }),
104
- client: join(directory, "client")
105
- };
106
- }
107
6
  // src/dev-worker.ts
108
7
  let stopping = false;
109
8
  const stop = () => {
@@ -1 +1 @@
1
- {"version":3,"file":"dev-worker.js","names":[],"sources":["../src/dev-inspector.ts","../src/dev-worker.ts"],"sourcesContent":["import { randomBytes } from \"node:crypto\";\nimport { existsSync, statSync } from \"node:fs\";\nimport { join, resolve, sep } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport type { BrickApp, ScheduleControl } from \"@brickkit/core\";\nimport type { CreateFetchHandler } from \"../../workflow-inspector/server/handler\";\nimport { INSPECTOR_TOKEN_HEADER, ROUTES } from \"./dashboard-protocol\";\n\nconst INSPECTOR_PATH = ROUTES.workflows.path;\n\nexport interface Inspector {\n readonly port: number;\n /** Whether it serves the workflow inspector; it may serve only the schedules. */\n readonly workflows: boolean;\n /** Every request must carry it in `INSPECTOR_TOKEN_HEADER`. */\n readonly token: string;\n stop(): void;\n}\n\n/** The built inspector, next to `src/` in the repo and next to `dist/` when published. */\nconst INSPECTOR_DIRECTORY = fileURLToPath(\n new URL(\"../inspector-dist/\", import.meta.url),\n);\n\n/** Whether a path is a regular file; any failure to find out (not a directory, name too long) says no. */\nfunction isFile(path: string): boolean {\n try {\n return statSync(path).isFile();\n } catch {\n return false;\n }\n}\n\n/**\n * A file of the inspector's browser build. Its names carry a hash of their\n * content, so a browser may keep them for good. Anything else under `assets/`\n * is a plain 404: the page would answer with HTML. `undefined` for requests\n * outside `assets/`, which are the page's to answer.\n */\nfunction browserAsset(request: Request, client: string): Response | undefined {\n if (request.method !== \"GET\" && request.method !== \"HEAD\") return undefined;\n const { pathname } = new URL(request.url);\n if (!pathname.startsWith(`${INSPECTOR_PATH}/assets/`)) return undefined;\n const file = resolve(client, pathname.slice(INSPECTOR_PATH.length + 1));\n if (!file.startsWith(client + sep) || !isFile(file))\n return new Response(\"Not found\", { status: 404 });\n return new Response(Bun.file(file), {\n headers: { \"cache-control\": \"public, max-age=31536000, immutable\" },\n });\n}\n\n/**\n * The app's schedules, for the dashboard's Schedules view: `GET` lists them,\n * `POST <path>/<name>` runs one now.\n */\nasync function schedulesRoute(\n schedules: ScheduleControl,\n names: ReadonlySet<string>,\n request: Request,\n pathname: string,\n): Promise<Response> {\n let name: string;\n try {\n name = decodeURIComponent(pathname.slice(ROUTES.schedules.path.length + 1));\n } catch (error) {\n return new Response((error as Error).message, { status: 400 });\n }\n if (request.method === \"GET\" && !name)\n return Response.json(await schedules.list());\n if (request.method !== \"POST\" || !name)\n return new Response(\"Not found\", { status: 404 });\n if (!names.has(name))\n return new Response(`No schedule named '${name}'`, { status: 404 });\n try {\n return Response.json({ started: await schedules.trigger(name) });\n } catch (error) {\n return new Response((error as Error).message, { status: 500 });\n }\n}\n\n/**\n * Serve the Workflow inspector (the Workflow SDK's observability UI, built into\n * this package) for the app's world, and the app's schedules, on a loopback\n * port of its own. The dashboard proxies them at `/workflows` and\n * `/api/schedules`; it is the only caller that knows the token. The UI can\n * cancel runs and resume hooks, and a schedule can be run from it, so nothing\n * else may reach it, and it exists only under `brick dev`.\n *\n * @param app - The loaded app, running in this process.\n * @param directory - The inspector's build; this package's own by default.\n * @returns The inspector, or `undefined` when the app runs no workflows and has no schedules.\n * @throws When the inspector's build is missing.\n */\nexport async function startInspector(\n app: BrickApp,\n directory = INSPECTOR_DIRECTORY,\n): Promise<Inspector | undefined> {\n const target = app.events?.workflows;\n const schedules = app.events?.schedules;\n if (!target && !schedules) return undefined;\n // An unbuilt inspector costs the Workflows view, not the schedules.\n const workflows =\n target &&\n (await workflowsPage(target, directory).catch((error: unknown) => {\n if (!schedules) throw error;\n console.warn(`[Brick-TS] ${(error as Error).message}`);\n return undefined;\n }));\n const names = new Set(\n schedules\n ? app.events!.describe().schedules?.map((schedule) => schedule.name)\n : [],\n );\n const token = randomBytes(16).toString(\"hex\");\n const server = Bun.serve({\n hostname: \"127.0.0.1\",\n port: 0,\n // The UI streams a run's output and holds the connection open.\n idleTimeout: 0,\n fetch: (request) => {\n if (request.headers.get(INSPECTOR_TOKEN_HEADER) !== token)\n return new Response(\"Forbidden\", { status: 403 });\n const { pathname } = new URL(request.url);\n if (schedules && pathname.startsWith(ROUTES.schedules.path))\n return schedulesRoute(schedules, names, request, pathname);\n if (!workflows) return new Response(\"Not found\", { status: 404 });\n return browserAsset(request, workflows.client) ?? workflows.page(request);\n },\n });\n return {\n port: server.port!,\n workflows: Boolean(workflows),\n token,\n stop: () => void server.stop(true),\n };\n}\n\nasync function workflowsPage(\n target: NonNullable<NonNullable<BrickApp[\"events\"]>[\"workflows\"]>,\n directory: string,\n) {\n const entry = join(directory, \"server\", \"index.js\");\n if (!existsSync(entry))\n throw new Error(\n \"The workflow inspector is not built. Build it with: bun run --filter @brickkit/cli build\",\n );\n const { createFetchHandler } = (await import(pathToFileURL(entry).href)) as {\n createFetchHandler: CreateFetchHandler;\n };\n const page = createFetchHandler(INSPECTOR_PATH, {\n // Core types only the parts of the world it calls; the world is a whole Workflow SDK World.\n world: target.world as Parameters<CreateFetchHandler>[1][\"world\"],\n });\n return { page, client: join(directory, \"client\") };\n}\n","import { getGlobalRegistry, stopAllEvents } from \"@brickkit/core\";\nimport { startInspector } from \"./dev-inspector\";\nimport { startDevApplication } from \"./dev-application\";\nimport type { WorkerErrorPhase } from \"./dashboard-protocol\";\nimport { sendToSupervisor, type WorkerOptions } from \"./dev-protocol\";\nimport { installWorkerTelemetry, reportWorkerError } from \"./dev-telemetry\";\n\nlet stopping = false;\n// A reload stops this process. Deliveries cut off would stay claimed, and wait\n// a minute (claimTimeoutMs) before the next process takes them. Stop every\n// started hub: an event emitted while the entry still loads starts one.\nconst stop = () => {\n if (stopping) return;\n stopping = true;\n void Promise.race([stopAllEvents(), Bun.sleep(3000)])\n .catch((error: unknown) =>\n console.error(\n `[Brick-TS] Could not stop the events: ${error instanceof Error ? error.message : String(error)}`,\n ),\n )\n .finally(() => process.exit(0));\n};\nprocess.on(\"SIGTERM\", stop);\nif (process.connected && typeof process.send === \"function\") {\n // The terminal also signals the supervisor, which sends SIGTERM and waits for us.\n process.on(\"SIGINT\", () => {});\n process.on(\"disconnect\", stop);\n} else {\n process.on(\"SIGINT\", stop);\n}\n\nconst options: WorkerOptions = JSON.parse(process.argv[2]!);\nconst { telemetry } = options;\nlet startupComplete = false;\nlet reported = false;\n\nasync function reportOnce(phase: WorkerErrorPhase, error: unknown) {\n if (!telemetry || reported) return;\n reported = true;\n await reportWorkerError(phase, error);\n}\n\nasync function exitAfterFailure(phase: WorkerErrorPhase, error: unknown) {\n await reportOnce(phase, error);\n console.error(error);\n process.exit(1);\n}\n\nif (telemetry) {\n installWorkerTelemetry();\n // Failures before the app is listening are startup failures, not crashes.\n const phaseOf = (): WorkerErrorPhase =>\n startupComplete ? \"uncaught\" : \"startup\";\n process.on(\"uncaughtException\", (error) => {\n void exitAfterFailure(phaseOf(), error);\n });\n process.on(\"unhandledRejection\", (reason) => {\n void exitAfterFailure(\n startupComplete ? \"unhandled-rejection\" : \"startup\",\n reason,\n );\n });\n}\n\n// Scan local imports so dependencies outside the app directory are watched too.\n{\n const files = new Set<string>();\n try {\n await Bun.build({\n entrypoints: [options.entry],\n target: \"bun\",\n packages: \"external\",\n plugins: [\n {\n name: \"brick:dependencies\",\n setup(build) {\n build.onLoad({ filter: /./ }, (args) => {\n files.add(args.path);\n return undefined;\n });\n },\n },\n ],\n });\n } finally {\n // Awaited: a build error ends this process, and the list must arrive first.\n await sendToSupervisor({ type: \"brick:dependencies\", files: [...files] });\n }\n}\n\ntry {\n const app = await startDevApplication(options);\n startupComplete = true;\n if (telemetry) {\n void sendToSupervisor({\n type: \"brick:architecture\",\n architecture: getGlobalRegistry().exportArchitecture(app.definition),\n });\n void sendToSupervisor({\n type: \"brick:documentation\",\n documentation: app.definition.documentation,\n });\n void app.referenceDocuments().then(\n (documents) =>\n sendToSupervisor({ type: \"brick:api-documents\", documents }),\n (error: unknown) =>\n console.warn(\n `[Brick-TS] Could not load the API documents: ${error instanceof Error ? error.message : String(error)}`,\n ),\n );\n void startInspector(app).then(\n (inspector) =>\n inspector &&\n sendToSupervisor({\n type: \"brick:inspector\",\n port: inspector.port,\n workflows: inspector.workflows,\n token: inspector.token,\n }),\n (error: unknown) =>\n console.warn(\n `[Brick-TS] Could not start the workflow inspector: ${error instanceof Error ? error.message : String(error)}`,\n ),\n );\n if (!app.definition.telemetry)\n console.warn(\n \"[Brick-TS] The dashboard shows no requests: pass { telemetry: true } to brick() in your app entry.\",\n );\n }\n} catch (error) {\n await reportOnce(\"startup\", error);\n throw error;\n}\n"],"mappings":";;;;;;;;;;AAQA,MAAM,iBAAiB,OAAO,UAAU;;AAYxC,MAAM,sBAAsB,cAC1B,IAAI,IAAI,sBAAsB,YAAY,GAAG,CAC/C;;AAGA,SAAS,OAAO,MAAuB;CACrC,IAAI;EACF,OAAO,SAAS,IAAI,CAAC,CAAC,OAAO;CAC/B,QAAQ;EACN,OAAO;CACT;AACF;;;;;;;AAQA,SAAS,aAAa,SAAkB,QAAsC;CAC5E,IAAI,QAAQ,WAAW,SAAS,QAAQ,WAAW,QAAQ,OAAO,KAAA;CAClE,MAAM,EAAE,aAAa,IAAI,IAAI,QAAQ,GAAG;CACxC,IAAI,CAAC,SAAS,WAAW,GAAG,eAAe,SAAS,GAAG,OAAO,KAAA;CAC9D,MAAM,OAAO,QAAQ,QAAQ,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MAAM;GAAsB,OAAO,CAAC,GAAG,KAAK;EAAE,CAAC;CAC1E;AACF;AAEA,IAAI;CACF,MAAM,MAAM,MAAM,oBAAoB,OAAO;CAC7C,kBAAkB;CAClB,IAAI,WAAW;EACR,iBAAiB;GACpB,MAAM;GACN,cAAc,kBAAkB,CAAC,CAAC,mBAAmB,IAAI,UAAU;EACrE,CAAC;EACI,iBAAiB;GACpB,MAAM;GACN,eAAe,IAAI,WAAW;EAChC,CAAC;EACI,IAAI,mBAAmB,CAAC,CAAC,MAC3B,cACC,iBAAiB;GAAE,MAAM;GAAuB;EAAU,CAAC,IAC5D,UACC,QAAQ,KACN,gDAAgD,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GACvG,CACJ;EACK,eAAe,GAAG,CAAC,CAAC,MACtB,cACC,aACA,iBAAiB;GACf,MAAM;GACN,MAAM,UAAU;GAChB,WAAW,UAAU;GACrB,OAAO,UAAU;EACnB,CAAC,IACF,UACC,QAAQ,KACN,sDAAsD,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAC7G,CACJ;EACA,IAAI,CAAC,IAAI,WAAW,WAClB,QAAQ,KACN,oGACF;CACJ;AACF,SAAS,OAAO;CACd,MAAM,WAAW,WAAW,KAAK;CACjC,MAAM;AACR"}
1
+ {"version":3,"file":"dev-worker.js","names":[],"sources":["../src/dev-worker.ts"],"sourcesContent":["import { getGlobalRegistry, stopAllEvents } from \"@brickkit/core\";\nimport { startInspector } from \"./dev-inspector\";\nimport { startDevApplication } from \"./dev-application\";\nimport type { WorkerErrorPhase } from \"./dashboard-protocol\";\nimport { sendToSupervisor, type WorkerOptions } from \"./dev-protocol\";\nimport { installWorkerTelemetry, reportWorkerError } from \"./dev-telemetry\";\n\nlet stopping = false;\n// A reload stops this process. Deliveries cut off would stay claimed, and wait\n// a minute (claimTimeoutMs) before the next process takes them. Stop every\n// started hub: an event emitted while the entry still loads starts one.\nconst stop = () => {\n if (stopping) return;\n stopping = true;\n void Promise.race([stopAllEvents(), Bun.sleep(3000)])\n .catch((error: unknown) =>\n console.error(\n `[Brick-TS] Could not stop the events: ${error instanceof Error ? error.message : String(error)}`,\n ),\n )\n .finally(() => process.exit(0));\n};\nprocess.on(\"SIGTERM\", stop);\nif (process.connected && typeof process.send === \"function\") {\n // The terminal also signals the supervisor, which sends SIGTERM and waits for us.\n process.on(\"SIGINT\", () => {});\n process.on(\"disconnect\", stop);\n} else {\n process.on(\"SIGINT\", stop);\n}\n\nconst options: WorkerOptions = JSON.parse(process.argv[2]!);\nconst { telemetry } = options;\nlet startupComplete = false;\nlet reported = false;\n\nasync function reportOnce(phase: WorkerErrorPhase, error: unknown) {\n if (!telemetry || reported) return;\n reported = true;\n await reportWorkerError(phase, error);\n}\n\nasync function exitAfterFailure(phase: WorkerErrorPhase, error: unknown) {\n await reportOnce(phase, error);\n console.error(error);\n process.exit(1);\n}\n\nif (telemetry) {\n installWorkerTelemetry();\n // Failures before the app is listening are startup failures, not crashes.\n const phaseOf = (): WorkerErrorPhase =>\n startupComplete ? \"uncaught\" : \"startup\";\n process.on(\"uncaughtException\", (error) => {\n void exitAfterFailure(phaseOf(), error);\n });\n process.on(\"unhandledRejection\", (reason) => {\n void exitAfterFailure(\n startupComplete ? \"unhandled-rejection\" : \"startup\",\n reason,\n );\n });\n}\n\n// Scan local imports so dependencies outside the app directory are watched too.\n{\n const files = new Set<string>();\n try {\n await Bun.build({\n entrypoints: [options.entry],\n target: \"bun\",\n packages: \"external\",\n plugins: [\n {\n name: \"brick:dependencies\",\n setup(build) {\n build.onLoad({ filter: /./ }, (args) => {\n files.add(args.path);\n return undefined;\n });\n },\n },\n ],\n });\n } finally {\n // Awaited: a build error ends this process, and the list must arrive first.\n await sendToSupervisor({ type: \"brick:dependencies\", files: [...files] });\n }\n}\n\ntry {\n const app = await startDevApplication(options);\n startupComplete = true;\n if (telemetry) {\n void sendToSupervisor({\n type: \"brick:architecture\",\n architecture: getGlobalRegistry().exportArchitecture(app.definition),\n });\n void sendToSupervisor({\n type: \"brick:documentation\",\n documentation: app.definition.documentation,\n });\n void app.referenceDocuments().then(\n (documents) =>\n sendToSupervisor({ type: \"brick:api-documents\", documents }),\n (error: unknown) =>\n console.warn(\n `[Brick-TS] Could not load the API documents: ${error instanceof Error ? error.message : String(error)}`,\n ),\n );\n void startInspector(app).then(\n (inspector) =>\n inspector &&\n sendToSupervisor({\n type: \"brick:inspector\",\n port: inspector.port,\n workflows: inspector.workflows,\n token: inspector.token,\n }),\n (error: unknown) =>\n console.warn(\n `[Brick-TS] Could not start the workflow inspector: ${error instanceof Error ? error.message : String(error)}`,\n ),\n );\n if (!app.definition.telemetry)\n console.warn(\n \"[Brick-TS] The dashboard shows no requests: pass { telemetry: true } to brick() in your app entry.\",\n );\n }\n} catch (error) {\n await reportOnce(\"startup\", error);\n throw error;\n}\n"],"mappings":";;;;;;AAOA,IAAI,WAAW;AAIf,MAAM,aAAa;CACjB,IAAI,UAAU;CACd,WAAW;CACN,QAAQ,KAAK,CAAC,cAAc,GAAG,IAAI,MAAM,GAAI,CAAC,CAAC,CAAC,CAClD,OAAO,UACN,QAAQ,MACN,yCAAyC,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAChG,CACF,CAAC,CACA,cAAc,QAAQ,KAAK,CAAC,CAAC;AAClC;AACA,QAAQ,GAAG,WAAW,IAAI;AAC1B,IAAI,QAAQ,aAAa,OAAO,QAAQ,SAAS,YAAY;CAE3D,QAAQ,GAAG,gBAAgB,CAAC,CAAC;CAC7B,QAAQ,GAAG,cAAc,IAAI;AAC/B,OACE,QAAQ,GAAG,UAAU,IAAI;AAG3B,MAAM,UAAyB,KAAK,MAAM,QAAQ,KAAK,EAAG;AAC1D,MAAM,EAAE,cAAc;AACtB,IAAI,kBAAkB;AACtB,IAAI,WAAW;AAEf,eAAe,WAAW,OAAyB,OAAgB;CACjE,IAAI,CAAC,aAAa,UAAU;CAC5B,WAAW;CACX,MAAM,kBAAkB,OAAO,KAAK;AACtC;AAEA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AU;GACrB,OAAO,UAAU;EACnB,CAAC,IACF,UACC,QAAQ,KACN,sDAAsD,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAC7G,CACJ;EACA,IAAI,CAAC,IAAI,WAAW,WAClB,QAAQ,KACN,oGACF;CACJ;AACF,SAAS,OAAO;CACd,MAAM,WAAW,WAAW,KAAK;CACjC,MAAM;AACR"}
@@ -0,0 +1,5 @@
1
+ // package.json
2
+ var version = "0.16.0-beta.3";
3
+ export { version as t };
4
+
5
+ //# sourceMappingURL=package.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"package.js","names":[],"sources":["../package.json"],"sourcesContent":[""],"mappings":""}
@@ -1,4 +1,5 @@
1
1
  import { t as openDashboard } from "./dashboard-host.js";
2
+ import { t as startInspector } from "./dev-inspector.js";
2
3
  import { t as installTracing } from "./dev-telemetry.js";
3
4
  import { getGlobalRegistry } from "@brickkit/core";
4
5
  // src/production-dashboard.ts
@@ -9,6 +10,11 @@ import { getGlobalRegistry } from "@brickkit/core";
9
10
  * uptime monitor whether the app does. From here on `ctx.logger` and `console`
10
11
  * lines written during a request go to the dashboard, not the console.
11
12
  *
13
+ * With `dashboard.inspector` it also serves the workflow inspector and the
14
+ * schedules, on a loopback port only the dashboard knows, for the Workflows
15
+ * and Schedules views. An app with neither, or an inspector that cannot start,
16
+ * costs those views and a warning, nothing else.
17
+ *
12
18
  * Call it before the app starts listening. Returns undefined when the app
13
19
  * asks for no dashboard, or when it cannot start (the app runs on without it,
14
20
  * and says so). A configuration that would leave the dashboard open to others
@@ -19,6 +25,13 @@ async function startProductionDashboard(app, options) {
19
25
  if (!config) return void 0;
20
26
  const warn = options.warn ?? ((message) => console.warn(message));
21
27
  const host = config.host ?? "127.0.0.1";
28
+ let inspector;
29
+ if (config.inspector) try {
30
+ inspector = await startInspector(app);
31
+ if (!inspector) warn("[Brick-TS] dashboard.inspector is on, but the app has no workflows and no schedules, so there is nothing for it to show.");
32
+ } catch (error) {
33
+ warn(`[Brick-TS] Could not start the workflow inspector, so the dashboard has no Schedules and Workflows views: ${error instanceof Error ? error.message : String(error)}`);
34
+ }
22
35
  const started = await openDashboard({
23
36
  directory: options.directory ?? process.cwd(),
24
37
  historyDays: config.historyDays ?? 0,
@@ -28,22 +41,34 @@ async function startProductionDashboard(app, options) {
28
41
  mode: "production",
29
42
  portHint: "Set dashboard.port in brick() to another.",
30
43
  auth: config.auth,
44
+ inspector: config.inspector,
45
+ mcp: config.mcp,
31
46
  dashboard: options.dashboard,
32
47
  plugins: app.definition.plugins,
33
48
  appUrl: `http://127.0.0.1:${options.appPort}`,
34
49
  probe: async () => {
35
50
  return (await fetch(`http://127.0.0.1:${options.appPort}/_health`, { signal: AbortSignal.timeout(2e3) })).ok;
36
51
  }
52
+ }).catch((error) => {
53
+ inspector?.stop();
54
+ throw error;
37
55
  });
38
- if (!started) return void 0;
56
+ if (!started) {
57
+ inspector?.stop();
58
+ return;
59
+ }
39
60
  const { store } = started;
61
+ if (inspector) store.setInspector(inspector);
40
62
  if (!installTracing((records) => store.ingest(records, store.latestGeneration))) warn("[Brick-TS] Another tracer provider is already registered, so the dashboard will show no requests or logs.");
41
63
  const generation = store.startGeneration("application started");
42
64
  store.setArchitecture(getGlobalRegistry().exportArchitecture(app.definition), generation);
43
65
  return {
44
66
  host,
45
67
  port: started.port,
46
- stop: () => started.stop()
68
+ stop() {
69
+ inspector?.stop();
70
+ started.stop();
71
+ }
47
72
  };
48
73
  }
49
74
  export { startProductionDashboard };
@@ -1 +1 @@
1
- {"version":3,"file":"production-dashboard.js","names":[],"sources":["../src/production-dashboard.ts"],"sourcesContent":["import { getGlobalRegistry, type BrickApp } from \"@brickkit/core\";\nimport type { DashboardExtensionOptions } from \"./dashboard-extension\";\nimport { openDashboard } from \"./dashboard-host\";\nimport { installTracing } from \"./dev-telemetry\";\n\nexport interface ProductionDashboard {\n readonly host: string;\n readonly port: number;\n stop(): void;\n}\n\n/**\n * Serve the monitoring dashboard an app asks for with `brick({ dashboard })`,\n * in the process that serves the app. It listens on a port of its own, so it\n * stays up when the app's routes do not answer, and its `/_health` tells an\n * uptime monitor whether the app does. From here on `ctx.logger` and `console`\n * lines written during a request go to the dashboard, not the console.\n *\n * Call it before the app starts listening. Returns undefined when the app\n * asks for no dashboard, or when it cannot start (the app runs on without it,\n * and says so). A configuration that would leave the dashboard open to others\n * throws instead: the app must not start unprotected.\n */\nexport async function startProductionDashboard(\n app: BrickApp,\n options: {\n /** The port the app listens on, for the health probe. */\n appPort: number;\n /** Where `.brick/` history is kept; the working folder by default. */\n directory?: string;\n warn?: (message: string) => void;\n /**\n * The project's extension (source, or the folder `brick build` wrote) and\n * theme. The app's plugins' extensions join it, from source or as the\n * folder holds them. Only pages marked `production: true` are shown.\n */\n dashboard?: DashboardExtensionOptions;\n },\n): Promise<ProductionDashboard | undefined> {\n const config = app.definition.dashboard;\n if (!config) return undefined;\n const warn = options.warn ?? ((message) => console.warn(message));\n const host = config.host ?? \"127.0.0.1\";\n const started = await openDashboard({\n directory: options.directory ?? process.cwd(),\n historyDays: config.historyDays ?? 0,\n warn,\n port: config.port,\n host,\n mode: \"production\",\n portHint: \"Set dashboard.port in brick() to another.\",\n auth: config.auth,\n dashboard: options.dashboard,\n plugins: app.definition.plugins,\n appUrl: `http://127.0.0.1:${options.appPort}`,\n probe: async () => {\n const response = await fetch(\n `http://127.0.0.1:${options.appPort}/_health`,\n { signal: AbortSignal.timeout(2000) },\n );\n return response.ok;\n },\n });\n if (!started) return undefined;\n const { store } = started;\n\n const registered = installTracing((records) =>\n store.ingest(records, store.latestGeneration),\n );\n if (!registered) {\n warn(\n \"[Brick-TS] Another tracer provider is already registered, so the dashboard will show no requests or logs.\",\n );\n }\n const generation = store.startGeneration(\"application started\");\n store.setArchitecture(\n getGlobalRegistry().exportArchitecture(app.definition),\n generation,\n );\n return { host, port: started.port, stop: () => started.stop() };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAuBA,eAAsB,yBACpB,KACA,SAa0C;CAC1C,MAAM,SAAS,IAAI,WAAW;CAC9B,IAAI,CAAC,QAAQ,OAAO,KAAA;CACpB,MAAM,OAAO,QAAQ,UAAU,YAAY,QAAQ,KAAK,OAAO;CAC/D,MAAM,OAAO,OAAO,QAAQ;CAC5B,MAAM,UAAU,MAAM,cAAc;EAClC,WAAW,QAAQ,aAAa,QAAQ,IAAI;EAC5C,aAAa,OAAO,eAAe;EACnC;EACA,MAAM,OAAO;EACb;EACA,MAAM;EACN,UAAU;EACV,MAAM,OAAO;EACb,WAAW,QAAQ;EACnB,SAAS,IAAI,WAAW;EACxB,QAAQ,oBAAoB,QAAQ;EACpC,OAAO,YAAY;GAKjB,QAAO,MAJgB,MACrB,oBAAoB,QAAQ,QAAQ,WACpC,EAAE,QAAQ,YAAY,QAAQ,GAAI,EAAE,CACtC,EAAA,CACgB;EAClB;CACF,CAAC;CACD,IAAI,CAAC,SAAS,OAAO,KAAA;CACrB,MAAM,EAAE,UAAU;CAKlB,IAAI,CAHe,gBAAgB,YACjC,MAAM,OAAO,SAAS,MAAM,gBAAgB,CAEhC,GACZ,KACE,2GACF;CAEF,MAAM,aAAa,MAAM,gBAAgB,qBAAqB;CAC9D,MAAM,gBACJ,kBAAkB,CAAC,CAAC,mBAAmB,IAAI,UAAU,GACrD,UACF;CACA,OAAO;EAAE;EAAM,MAAM,QAAQ;EAAM,YAAY,QAAQ,KAAK;CAAE;AAChE"}
1
+ {"version":3,"file":"production-dashboard.js","names":[],"sources":["../src/production-dashboard.ts"],"sourcesContent":["import { getGlobalRegistry, type BrickApp } from \"@brickkit/core\";\nimport type { DashboardExtensionOptions } from \"./dashboard-extension\";\nimport { openDashboard } from \"./dashboard-host\";\nimport { startInspector, type Inspector } from \"./dev-inspector\";\nimport { installTracing } from \"./dev-telemetry\";\n\nexport interface ProductionDashboard {\n readonly host: string;\n readonly port: number;\n stop(): void;\n}\n\n/**\n * Serve the monitoring dashboard an app asks for with `brick({ dashboard })`,\n * in the process that serves the app. It listens on a port of its own, so it\n * stays up when the app's routes do not answer, and its `/_health` tells an\n * uptime monitor whether the app does. From here on `ctx.logger` and `console`\n * lines written during a request go to the dashboard, not the console.\n *\n * With `dashboard.inspector` it also serves the workflow inspector and the\n * schedules, on a loopback port only the dashboard knows, for the Workflows\n * and Schedules views. An app with neither, or an inspector that cannot start,\n * costs those views and a warning, nothing else.\n *\n * Call it before the app starts listening. Returns undefined when the app\n * asks for no dashboard, or when it cannot start (the app runs on without it,\n * and says so). A configuration that would leave the dashboard open to others\n * throws instead: the app must not start unprotected.\n */\nexport async function startProductionDashboard(\n app: BrickApp,\n options: {\n /** The port the app listens on, for the health probe. */\n appPort: number;\n /** Where `.brick/` history is kept; the working folder by default. */\n directory?: string;\n warn?: (message: string) => void;\n /**\n * The project's extension (source, or the folder `brick build` wrote) and\n * theme. The app's plugins' extensions join it, from source or as the\n * folder holds them. Only pages marked `production: true` are shown.\n */\n dashboard?: DashboardExtensionOptions;\n },\n): Promise<ProductionDashboard | undefined> {\n const config = app.definition.dashboard;\n if (!config) return undefined;\n const warn = options.warn ?? ((message) => console.warn(message));\n const host = config.host ?? \"127.0.0.1\";\n let inspector: Inspector | undefined;\n if (config.inspector) {\n try {\n inspector = await startInspector(app);\n if (!inspector)\n warn(\n \"[Brick-TS] dashboard.inspector is on, but the app has no workflows and no schedules, so there is nothing for it to show.\",\n );\n } catch (error) {\n warn(\n `[Brick-TS] Could not start the workflow inspector, so the dashboard has no Schedules and Workflows views: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n const started = await openDashboard({\n directory: options.directory ?? process.cwd(),\n historyDays: config.historyDays ?? 0,\n warn,\n port: config.port,\n host,\n mode: \"production\",\n portHint: \"Set dashboard.port in brick() to another.\",\n auth: config.auth,\n inspector: config.inspector,\n mcp: config.mcp,\n dashboard: options.dashboard,\n plugins: app.definition.plugins,\n appUrl: `http://127.0.0.1:${options.appPort}`,\n probe: async () => {\n const response = await fetch(\n `http://127.0.0.1:${options.appPort}/_health`,\n { signal: AbortSignal.timeout(2000) },\n );\n return response.ok;\n },\n }).catch((error: unknown) => {\n inspector?.stop();\n throw error;\n });\n if (!started) {\n inspector?.stop();\n return undefined;\n }\n const { store } = started;\n if (inspector) store.setInspector(inspector);\n\n const registered = installTracing((records) =>\n store.ingest(records, store.latestGeneration),\n );\n if (!registered) {\n warn(\n \"[Brick-TS] Another tracer provider is already registered, so the dashboard will show no requests or logs.\",\n );\n }\n const generation = store.startGeneration(\"application started\");\n store.setArchitecture(\n getGlobalRegistry().exportArchitecture(app.definition),\n generation,\n );\n return {\n host,\n port: started.port,\n stop() {\n inspector?.stop();\n started.stop();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA6BA,eAAsB,yBACpB,KACA,SAa0C;CAC1C,MAAM,SAAS,IAAI,WAAW;CAC9B,IAAI,CAAC,QAAQ,OAAO,KAAA;CACpB,MAAM,OAAO,QAAQ,UAAU,YAAY,QAAQ,KAAK,OAAO;CAC/D,MAAM,OAAO,OAAO,QAAQ;CAC5B,IAAI;CACJ,IAAI,OAAO,WACT,IAAI;EACF,YAAY,MAAM,eAAe,GAAG;EACpC,IAAI,CAAC,WACH,KACE,0HACF;CACJ,SAAS,OAAO;EACd,KACE,6GAA6G,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GACpK;CACF;CAEF,MAAM,UAAU,MAAM,cAAc;EAClC,WAAW,QAAQ,aAAa,QAAQ,IAAI;EAC5C,aAAa,OAAO,eAAe;EACnC;EACA,MAAM,OAAO;EACb;EACA,MAAM;EACN,UAAU;EACV,MAAM,OAAO;EACb,WAAW,OAAO;EAClB,KAAK,OAAO;EACZ,WAAW,QAAQ;EACnB,SAAS,IAAI,WAAW;EACxB,QAAQ,oBAAoB,QAAQ;EACpC,OAAO,YAAY;GAKjB,QAAO,MAJgB,MACrB,oBAAoB,QAAQ,QAAQ,WACpC,EAAE,QAAQ,YAAY,QAAQ,GAAI,EAAE,CACtC,EAAA,CACgB;EAClB;CACF,CAAC,CAAC,CAAC,OAAO,UAAmB;EAC3B,WAAW,KAAK;EAChB,MAAM;CACR,CAAC;CACD,IAAI,CAAC,SAAS;EACZ,WAAW,KAAK;EAChB;CACF;CACA,MAAM,EAAE,UAAU;CAClB,IAAI,WAAW,MAAM,aAAa,SAAS;CAK3C,IAAI,CAHe,gBAAgB,YACjC,MAAM,OAAO,SAAS,MAAM,gBAAgB,CAEhC,GACZ,KACE,2GACF;CAEF,MAAM,aAAa,MAAM,gBAAgB,qBAAqB;CAC9D,MAAM,gBACJ,kBAAkB,CAAC,CAAC,mBAAmB,IAAI,UAAU,GACrD,UACF;CACA,OAAO;EACL;EACA,MAAM,QAAQ;EACd,OAAO;GACL,WAAW,KAAK;GAChB,QAAQ,KAAK;EACf;CACF;AACF"}
@@ -12,6 +12,11 @@ interface ProductionDashboard {
12
12
  * uptime monitor whether the app does. From here on `ctx.logger` and `console`
13
13
  * lines written during a request go to the dashboard, not the console.
14
14
  *
15
+ * With `dashboard.inspector` it also serves the workflow inspector and the
16
+ * schedules, on a loopback port only the dashboard knows, for the Workflows
17
+ * and Schedules views. An app with neither, or an inspector that cannot start,
18
+ * costs those views and a warning, nothing else.
19
+ *
15
20
  * Call it before the app starts listening. Returns undefined when the app
16
21
  * asks for no dashboard, or when it cannot start (the app runs on without it,
17
22
  * and says so). A configuration that would leave the dashboard open to others