@brickkit/cli 0.12.0 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/dashboard-dist/{api-reference-B-bZRtNV.js → api-reference-mT9VNcPb.js} +69 -69
  2. package/dashboard-dist/app.css +1 -1
  3. package/dashboard-dist/app.js +12 -13
  4. package/dashboard-dist/{client-BJJtVSVr.js → client-CwATkLJa.js} +1 -1
  5. package/dashboard-dist/{core-Z7NJFk0K.js → core-BEUWp6B5.js} +1 -1
  6. package/dashboard-dist/docs-BRrtyxDB.js +4 -0
  7. package/dashboard-dist/kit.js +1 -1
  8. package/dashboard-dist/popover-Bj9x-88h.js +1 -0
  9. package/dist/bin.js +154 -217
  10. package/dist/bin.js.map +1 -1
  11. package/dist/build.js +463 -0
  12. package/dist/build.js.map +1 -0
  13. package/dist/client-contract-file.js +356 -1
  14. package/dist/client-contract-file.js.map +1 -0
  15. package/dist/compiler.d.ts +12 -2
  16. package/dist/compiler2.js +12 -5
  17. package/dist/compiler2.js.map +1 -1
  18. package/dist/config.d.ts +3 -0
  19. package/dist/config.js +1 -250
  20. package/dist/config2.d.ts +122 -0
  21. package/dist/config2.js +207 -0
  22. package/dist/config2.js.map +1 -0
  23. package/dist/dashboard-extension.d.ts +3 -0
  24. package/dist/{dev-telemetry-store.js → dashboard-host.js} +1533 -1574
  25. package/dist/dashboard-host.js.map +1 -0
  26. package/dist/dashboard-protocol.js +189 -0
  27. package/dist/dashboard-protocol.js.map +1 -0
  28. package/dist/dashboard.d.ts +4 -1
  29. package/dist/definitions.js +33 -0
  30. package/dist/definitions.js.map +1 -0
  31. package/dist/dev-application.js +34 -0
  32. package/dist/dev-application.js.map +1 -0
  33. package/dist/dev-protocol.js +21 -0
  34. package/dist/dev-protocol.js.map +1 -0
  35. package/dist/dev-reporter.js +2 -1
  36. package/dist/dev-reporter.js.map +1 -1
  37. package/dist/dev-telemetry.js +5 -20
  38. package/dist/dev-telemetry.js.map +1 -1
  39. package/dist/dev-worker.js +79 -19
  40. package/dist/dev-worker.js.map +1 -1
  41. package/dist/index.d.ts +15 -74
  42. package/dist/index.js +12 -5
  43. package/dist/index.js.map +1 -0
  44. package/dist/lint/oxlint.js +5 -3
  45. package/dist/lint/oxlint.js.map +1 -1
  46. package/dist/own-module.js +7 -0
  47. package/dist/own-module.js.map +1 -0
  48. package/dist/plugin.d.ts +6 -5
  49. package/dist/plugin.js +5 -39
  50. package/dist/plugin.js.map +1 -1
  51. package/dist/production-dashboard.d.ts +2 -0
  52. package/dist/production-dashboard.js +51 -0
  53. package/dist/production-dashboard.js.map +1 -0
  54. package/dist/production-dashboard2.d.ts +34 -0
  55. package/dist/{presets.js → project.js} +104 -106
  56. package/dist/project.js.map +1 -0
  57. package/dist/serve.d.ts +24 -0
  58. package/dist/serve.js +1 -0
  59. package/dist/serve2.js +49 -0
  60. package/dist/serve2.js.map +1 -0
  61. package/dist/vite.js +26 -47
  62. package/dist/vite.js.map +1 -1
  63. package/dist/workflows.d.ts +2 -2
  64. package/dist/workflows2.js +59 -37
  65. package/dist/workflows2.js.map +1 -1
  66. package/inspector-dist/client/assets/app-CeSwVsRm.css +2 -0
  67. package/inspector-dist/client/assets/{highlighted-body-B3W2YXNL-DYVdwGy2.js → highlighted-body-B3W2YXNL-CfRnuITN.js} +1 -1
  68. package/inspector-dist/client/assets/{home-CyjkvtII.js → home-hwPlkNhv.js} +1529 -378
  69. package/inspector-dist/client/assets/manifest-0e76e9ac.js +1 -0
  70. package/inspector-dist/client/assets/mermaid-3ZIDBTTL-ZDR2PNY_.js +1 -0
  71. package/inspector-dist/client/assets/root-ChBNTZd2.css +2 -0
  72. package/inspector-dist/client/assets/{root-DX9wtogx.js → root-SLeEf-sT.js} +17 -29
  73. package/inspector-dist/client/assets/{run-detail-C69EJGql.js → run-detail-DYbVkIFH.js} +398 -76
  74. package/inspector-dist/client/assets/{tabs-B6B88IjT.js → tabs-CaJisoyb.js} +189 -2130
  75. package/inspector-dist/client/assets/{zstd-browser-decoder-ByUgcY9H.js → zstd-browser-decoder-D94wmfAU.js} +1 -1
  76. package/inspector-dist/server/assets/{app-WoDoT62X.js → app-DGlfWVUI.js} +69783 -70608
  77. package/inspector-dist/server/assets/{chunk-RLXIAIE6-CbvDIAEa.js → chunk-RLXIAIE6-F0SJZlei.js} +4 -6
  78. package/inspector-dist/server/assets/{dist-qR-969AD.js → dist-BCbwm6jl.js} +2 -4
  79. package/inspector-dist/server/assets/{dist-CQnQcIJg.js → dist-CG2aVufI.js} +0 -2
  80. package/inspector-dist/server/assets/{dist-BRxZSWUN.js → dist-Ce0I2PUv.js} +2 -5
  81. package/inspector-dist/server/assets/{dist-DqRd9pyS.js → dist-DY0UlahA.js} +0 -2
  82. package/inspector-dist/server/assets/{encryption-_PuklZNX.js → encryption-DdQgC8Rk.js} +2 -4
  83. package/inspector-dist/server/assets/{event-metadata-BVakQJ_y.js → event-metadata-n7E4zEmT.js} +0 -2
  84. package/inspector-dist/server/assets/{functions-CImcpqNl.js → functions-CNVQtbgg.js} +2 -4
  85. package/inspector-dist/server/assets/{global-singleton-CPirHxFh.js → global-singleton-D8sIN5du.js} +0 -2
  86. package/inspector-dist/server/assets/{highlighted-body-B3W2YXNL-fPMB_t7F.js → highlighted-body-B3W2YXNL-CWRzMxYD.js} +2 -4
  87. package/inspector-dist/server/assets/mermaid-3ZIDBTTL-D0v0ngVr.js +1 -0
  88. package/inspector-dist/server/assets/{parse-D9Vvgzt9.js → parse-Begau9cA.js} +0 -2
  89. package/inspector-dist/server/assets/{rolldown-runtime-CLg409Sh.js → rolldown-runtime-C1I3wEg2.js} +1 -2
  90. package/inspector-dist/server/assets/{serialization-format-DDtsVTU1.js → serialization-format-BbuGfHog.js} +6 -8
  91. package/inspector-dist/server/assets/{token-BW4GdQZh.js → token-BgMmJNP5.js} +2 -4
  92. package/inspector-dist/server/assets/{token-D6FXdkJT.js → token-BrUX0bxz.js} +2 -4
  93. package/inspector-dist/server/assets/{token-util-BoNmi-wE.js → token-util-DZN32qmT.js} +1 -3
  94. package/inspector-dist/server/assets/{wrapper-wiqsGXcE.js → wrapper-CIC3w0oC.js} +1 -3
  95. package/inspector-dist/server/assets/{ws-transport-DV7oG4mL.js → ws-transport-CxTYB11n.js} +24094 -24096
  96. package/inspector-dist/server/assets/{zstd-browser-decoder-Cswf0KO6.js → zstd-browser-decoder-D7bCXbGg.js} +2 -4
  97. package/inspector-dist/server/index.js +1 -3
  98. package/package.json +12 -2
  99. package/dashboard-dist/docs-Dpfc0wJb.js +0 -4
  100. package/dashboard-dist/popover-BzejBolB.js +0 -1
  101. package/dist/app-entry.js +0 -1
  102. package/dist/app-entry2.js +0 -18
  103. package/dist/app-entry2.js.map +0 -1
  104. package/dist/client-contract-file2.js +0 -33
  105. package/dist/client-contract-file2.js.map +0 -1
  106. package/dist/client-contract.js +0 -1
  107. package/dist/client-contract2.js +0 -296
  108. package/dist/client-contract2.js.map +0 -1
  109. package/dist/config.js.map +0 -1
  110. package/dist/dev-telemetry-store.js.map +0 -1
  111. package/dist/emit.d.ts +0 -5
  112. package/dist/presets.js.map +0 -1
  113. package/dist/runner.js +0 -519
  114. package/dist/runner.js.map +0 -1
  115. package/inspector-dist/client/assets/app-CCzpuUz_.css +0 -2
  116. package/inspector-dist/client/assets/manifest-ba30b52d.js +0 -1
  117. package/inspector-dist/client/assets/mermaid-3ZIDBTTL-Dy6IVqPy.js +0 -1
  118. package/inspector-dist/client/assets/root-8BMab1lL.css +0 -2
  119. package/inspector-dist/client/assets/world-config-context-C3BqXPIv.js +0 -30
  120. package/inspector-dist/server/assets/mermaid-3ZIDBTTL-bADXySE3.js +0 -3
@@ -0,0 +1,189 @@
1
+ import { ATTR, SPAN } from "@brickkit/core/client";
2
+ // src/dashboard-protocol.ts
3
+ const GET = ["GET"];
4
+ /**
5
+ * Every route the dashboard serves. The server dispatches from this table and
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.
9
+ */
10
+ const ROUTES = {
11
+ /** Open to everyone: uptime monitors cannot sign in. */
12
+ health: {
13
+ path: "/_health",
14
+ methods: ["GET", "HEAD"],
15
+ production: true
16
+ },
17
+ shell: {
18
+ path: "/",
19
+ methods: GET,
20
+ production: true
21
+ },
22
+ assets: {
23
+ path: "/assets",
24
+ prefix: true,
25
+ methods: GET,
26
+ production: true
27
+ },
28
+ /** The app itself, for an extension's `appFetch`. */
29
+ app: {
30
+ path: "/app",
31
+ prefix: true,
32
+ production: "extension"
33
+ },
34
+ state: {
35
+ path: "/api/state",
36
+ methods: GET,
37
+ production: true
38
+ },
39
+ events: {
40
+ path: "/api/events",
41
+ methods: GET,
42
+ production: true
43
+ },
44
+ history: {
45
+ path: "/api/history",
46
+ prefix: true,
47
+ methods: GET,
48
+ production: true
49
+ },
50
+ docs: {
51
+ path: "/api/docs",
52
+ prefix: true,
53
+ methods: GET,
54
+ production: false,
55
+ view: "docs"
56
+ },
57
+ openapi: {
58
+ path: "/api/openapi",
59
+ methods: GET,
60
+ production: false,
61
+ view: "apis"
62
+ },
63
+ /** Try it in the APIs view; the app is another origin. */
64
+ proxy: {
65
+ path: "/api/proxy",
66
+ production: false,
67
+ view: "apis"
68
+ },
69
+ /** The workflow inspector the app serves on a port of its own. */
70
+ workflows: {
71
+ path: "/workflows",
72
+ prefix: true,
73
+ production: false,
74
+ view: "workflows"
75
+ },
76
+ ingest: {
77
+ path: "/api/ingest",
78
+ methods: ["POST"],
79
+ production: false,
80
+ csrf: true
81
+ },
82
+ restart: {
83
+ path: "/api/restart",
84
+ methods: ["POST"],
85
+ production: false,
86
+ csrf: true
87
+ }
88
+ };
89
+ /** The route a request is for, or undefined when none answers it. */
90
+ function matchRoute(method, pathname) {
91
+ 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;
92
+ }
93
+ new Set(Object.values(ROUTES).flatMap((route) => route.view && route.production === false ? [route.view] : []));
94
+ /** The Docs tab's data: tree, search, compiled pages, files, components. */
95
+ const DOCS_PATHS = {
96
+ info: ROUTES.docs.path,
97
+ search: `${ROUTES.docs.path}/search`,
98
+ components: `${ROUTES.docs.path}/components.js`,
99
+ page: `${ROUTES.docs.path}/page`,
100
+ files: `${ROUTES.docs.path}/files`
101
+ };
102
+ /** A path segment as written, when it is not valid percent-encoding. */
103
+ function decode(value) {
104
+ try {
105
+ return decodeURIComponent(value);
106
+ } catch {
107
+ return value;
108
+ }
109
+ }
110
+ /**
111
+ * A page address, `#/<segments>#<anchor>`, each part encoded. Every view's
112
+ * links are built with it, and the page's `parseRoute` reads them back.
113
+ */
114
+ const hashHref = (segments, anchor) => `#/${encodePath(segments)}${anchor ? `#${encodeURIComponent(anchor)}` : ""}`;
115
+ /** The page's address of a docs page, optionally at one of its headings. */
116
+ const docsHref = (path, anchor) => hashHref(["docs", ...path], anchor);
117
+ const encodePath = (path) => path.map(encodeURIComponent).join("/");
118
+ /** Where a file in the docs folder is served, by its path inside it. */
119
+ const docsFileUrl = (path) => `${DOCS_PATHS.files}/${encodePath(path.split("/"))}`;
120
+ /** Whether a link names a scheme (`https:`, `mailto:`) and so leaves the dashboard. */
121
+ const isExternalHref = (href) => /^[a-z][a-z\d+.-]*:/i.test(href);
122
+ /**
123
+ * Sent with every request that changes something (restart, ingest). A page on
124
+ * another site cannot send it without a preflight, which the server never
125
+ * answers.
126
+ */
127
+ const CSRF_HEADER = "x-brick-dashboard";
128
+ /** The header that proves a request to the workflow inspector comes from the dashboard. */
129
+ const INSPECTOR_TOKEN_HEADER = "x-brick-inspector";
130
+ /** The files the shell loads from `ROUTES.assets.path`. `app.*` come from the dashboard's build. */
131
+ const ASSETS = {
132
+ app: "app.js",
133
+ appCss: "app.css",
134
+ /** The project's extension, or the list of parts when plugins have one too. */
135
+ extension: "extension.js",
136
+ extensionCss: "extension.css",
137
+ /** The project's theme tokens; see `themeCss`. */
138
+ theme: "brick-theme.css"
139
+ };
140
+ /** Where an asset is served. */
141
+ const assetUrl = (file) => `${ROUTES.assets.path}/${file}`;
142
+ /**
143
+ * What the dashboard supplies to the project's docs components and dashboard
144
+ * extension, so there is one copy of React and of the UI kit on the page: the
145
+ * bundler leaves `specifier` external, the shell's import map points it at
146
+ * `/assets/<file>`, and `file` hands over the page's `globalThis.__brickDashboard[global]`.
147
+ */
148
+ const SHARED_MODULES = [
149
+ {
150
+ specifier: "react",
151
+ file: "react.js",
152
+ global: "React"
153
+ },
154
+ {
155
+ specifier: "react/jsx-runtime",
156
+ file: "react-jsx-runtime.js",
157
+ global: "jsxRuntime"
158
+ },
159
+ {
160
+ specifier: "react/jsx-dev-runtime",
161
+ file: "react-jsx-runtime.js",
162
+ global: "jsxRuntime"
163
+ },
164
+ {
165
+ specifier: "react-dom",
166
+ file: "react-dom.js",
167
+ global: "ReactDOM"
168
+ },
169
+ {
170
+ specifier: "react-dom/client",
171
+ file: "react-dom-client.js",
172
+ global: "ReactDOMClient"
173
+ },
174
+ {
175
+ specifier: "@brickkit/cli/dashboard",
176
+ file: "kit.js"
177
+ }
178
+ ];
179
+ /** Where the page keeps the chosen theme; the shell applies it before first paint. */
180
+ const THEME_STORAGE_KEY = "brick-dashboard-theme";
181
+ /** How many of each the live state keeps, on the server and on the page. */
182
+ const LIVE_LIMITS = {
183
+ traces: 200,
184
+ failures: 200,
185
+ reloads: 100
186
+ };
187
+ export { INSPECTOR_TOKEN_HEADER as a, SHARED_MODULES as c, assetUrl as d, decode as f, matchRoute as g, isExternalHref as h, DOCS_PATHS as i, SPAN as l, docsHref as m, ATTR as n, LIVE_LIMITS as o, docsFileUrl as p, CSRF_HEADER as r, ROUTES as s, ASSETS as t, THEME_STORAGE_KEY as u };
188
+
189
+ //# sourceMappingURL=dashboard-protocol.js.map
@@ -0,0 +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 \"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 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"],"mappings":";;AAgFA,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;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AG,IAAI,GAAG,MAAM;AAEpC,MAAM,cAAc,SAClB,KAAK,IAAI,kBAAkB,CAAC,CAAC,KAAK,GAAG;;AAGvC,MAAa,eAAe,SAC1B,GAAG,WAAW,MAAM,GAAG,WAAW,KAAK,MAAM,GAAG,CAAC;;AAWnD,MAAa,kBAAkB,SAC7B,sBAAsB,KAAK,IAAI;;;;;;AAOjC,MAAa,cAAc;;AAI3B,MAAa,yBAAyB;;AActC,MAAa,SAAS;CACpB,KAAK;CACL,QAAQ;;CAER,WAAW;CACX,cAAc;;CAEd,OAAO;AACT;;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"}
@@ -9,6 +9,9 @@ interface SpanEventRecord {
9
9
  timeMs: number;
10
10
  attributes: Attributes;
11
11
  }
12
+ /** The dashboard's built-in views; `#/<view>/…` opens one. */
13
+ declare const VIEW_NAMES: readonly ["requests", "logs", "overview", "apis", "docs", "workflows", "errors", "reloads"];
14
+ type ViewName = (typeof VIEW_NAMES)[number];
12
15
  type SpanOutcome = "running" | "ok" | "error" | "interrupted";
13
16
  interface TraceSpan {
14
17
  spanId: string;
@@ -42,7 +45,7 @@ interface TraceSummary {
42
45
  message?: string;
43
46
  spans: TraceSpan[];
44
47
  }
45
- type View = "requests" | "logs" | "overview" | "apis" | "docs" | "workflows" | "errors" | "reloads" |
48
+ type View = ViewName |
46
49
  /** An extension's page, at `#/x/<id>/…`, so it never clashes with a built-in one. */
47
50
  "x";
48
51
  interface Route {
@@ -0,0 +1,33 @@
1
+ // src/definitions.ts
2
+ /** Definition file kinds: `<name>.<kind>.ts`. */
3
+ const DEFINITION_KINDS = [
4
+ "service",
5
+ "events",
6
+ "resource",
7
+ "table",
8
+ "action",
9
+ "command",
10
+ "tool",
11
+ "socket",
12
+ "listener",
13
+ "workflow",
14
+ "step"
15
+ ];
16
+ /** The extensions a definition file may have. */
17
+ const DEFINITION_EXTENSIONS = [
18
+ "ts",
19
+ "tsx",
20
+ "mts",
21
+ "js",
22
+ "jsx",
23
+ "mjs"
24
+ ];
25
+ /** A definition file name: the name, then the kind, then the extension. */
26
+ const DEFINITION_FILE = new RegExp(`^(.*)\\.(${DEFINITION_KINDS.join("|")})\\.(${DEFINITION_EXTENSIONS.join("|")})$`);
27
+ /** A test file name: `*.test.ts`, `*.spec.mjs` and the like. */
28
+ const TEST_FILE = /\.(test|spec)\.[cm]?[jt]sx?$/;
29
+ /** The generated file that imports every definition file. */
30
+ const MANIFEST_FILE = "services.gen.ts";
31
+ export { TEST_FILE as a, MANIFEST_FILE as i, DEFINITION_FILE as n, DEFINITION_KINDS as r, DEFINITION_EXTENSIONS as t };
32
+
33
+ //# sourceMappingURL=definitions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"definitions.js","names":[],"sources":["../src/definitions.ts"],"sourcesContent":["// The project structure's file names, shared by the manifest and the lint.\n// A leaf: the lint plugin bundles it to run under Node.\n\n/** Definition file kinds: `<name>.<kind>.ts`. */\nexport const DEFINITION_KINDS = [\n \"service\",\n \"events\",\n \"resource\",\n \"table\",\n \"action\",\n \"command\",\n \"tool\",\n \"socket\",\n \"listener\",\n \"workflow\",\n \"step\",\n] as const;\nexport type DefinitionKind = (typeof DEFINITION_KINDS)[number];\n\n/** The extensions a definition file may have. */\nexport const DEFINITION_EXTENSIONS = [\"ts\", \"tsx\", \"mts\", \"js\", \"jsx\", \"mjs\"];\n\n/** A definition file name: the name, then the kind, then the extension. */\nexport const DEFINITION_FILE = new RegExp(\n `^(.*)\\\\.(${DEFINITION_KINDS.join(\"|\")})\\\\.(${DEFINITION_EXTENSIONS.join(\"|\")})$`,\n);\n\n/** A test file name: `*.test.ts`, `*.spec.mjs` and the like. */\nexport const TEST_FILE = /\\.(test|spec)\\.[cm]?[jt]sx?$/;\n\n/** The generated file that imports every definition file. */\nexport const MANIFEST_FILE = \"services.gen.ts\";\n"],"mappings":";;AAIA,MAAa,mBAAmB;CAC9B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAIA,MAAa,wBAAwB;CAAC;CAAM;CAAO;CAAO;CAAM;CAAO;AAAK;;AAG5E,MAAa,kBAAkB,IAAI,OACjC,YAAY,iBAAiB,KAAK,GAAG,EAAE,OAAO,sBAAsB,KAAK,GAAG,EAAE,GAChF;;AAGA,MAAa,YAAY;;AAGzB,MAAa,gBAAgB"}
@@ -0,0 +1,34 @@
1
+ import { n as writeAppContract, o as importEntry } from "./client-contract-file.js";
2
+ import { t as sendToSupervisor } from "./dev-protocol.js";
3
+ import { n as serveApp, t as printBanner } from "./serve2.js";
4
+ import { t as buildAppWorkflows } from "./workflows2.js";
5
+ import { brick, isBrickApp } from "@brickkit/core";
6
+ // src/dev-application.ts
7
+ /**
8
+ * Start the app `brick dev` runs: the entry's default-exported app, else one
9
+ * with the registered services. Its own dashboard option is ignored: `brick
10
+ * dev` serves the dev dashboard.
11
+ */
12
+ async function startDevApplication(options) {
13
+ const exported = options.entry ? await importEntry(options.entry, { run: true }) : void 0;
14
+ if (isBrickApp(exported) && options.prefix !== void 0) console.warn(`[Brick-TS] Ignoring prefix ${options.prefix}: exported BrickApp prefix ${exported.definition.prefix} takes precedence.`);
15
+ if (options.clientOutput) {
16
+ if (!isBrickApp(exported) || !options.entry) throw new Error("Brick: client generation requires a default-exported BrickApp.");
17
+ await writeAppContract(exported, options.entry, options.clientOutput);
18
+ sendToSupervisor({ type: "brick:contract-ready" });
19
+ }
20
+ const app = isBrickApp(exported) ? exported : brick({ prefix: options.prefix });
21
+ await buildAppWorkflows(app, { reuse: true });
22
+ await serveApp(app, {
23
+ port: options.port,
24
+ dashboard: false
25
+ });
26
+ printBanner(app, {
27
+ label: "Development",
28
+ port: options.port
29
+ });
30
+ return app;
31
+ }
32
+ export { startDevApplication as t };
33
+
34
+ //# sourceMappingURL=dev-application.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dev-application.js","names":[],"sources":["../src/dev-application.ts"],"sourcesContent":["import { brick, isBrickApp } from \"@brickkit/core\";\nimport { importEntry } from \"./app-entry\";\nimport { writeAppContract } from \"./client-contract-file\";\nimport { sendToSupervisor, type WorkerOptions } from \"./dev-protocol\";\nimport { printBanner, serveApp } from \"./serve\";\nimport { buildAppWorkflows } from \"./workflows\";\n\n/**\n * Start the app `brick dev` runs: the entry's default-exported app, else one\n * with the registered services. Its own dashboard option is ignored: `brick\n * dev` serves the dev dashboard.\n */\nexport async function startDevApplication(\n options: Omit<WorkerOptions, \"entry\" | \"telemetry\"> & { entry?: string },\n) {\n const exported = options.entry\n ? await importEntry(options.entry, { run: true })\n : undefined;\n if (isBrickApp(exported) && options.prefix !== undefined) {\n console.warn(\n `[Brick-TS] Ignoring prefix ${options.prefix}: exported BrickApp prefix ${exported.definition.prefix} takes precedence.`,\n );\n }\n if (options.clientOutput) {\n if (!isBrickApp(exported) || !options.entry)\n throw new Error(\n \"Brick: client generation requires a default-exported BrickApp.\",\n );\n await writeAppContract(exported, options.entry, options.clientOutput);\n void sendToSupervisor({ type: \"brick:contract-ready\" });\n }\n const app = isBrickApp(exported)\n ? exported\n : brick({ prefix: options.prefix });\n await buildAppWorkflows(app, { reuse: true });\n await serveApp(app, { port: options.port, dashboard: false });\n printBanner(app, { label: \"Development\", port: options.port });\n return app;\n}\n"],"mappings":";;;;;;;;;;;AAYA,eAAsB,oBACpB,SACA;CACA,MAAM,WAAW,QAAQ,QACrB,MAAM,YAAY,QAAQ,OAAO,EAAE,KAAK,KAAK,CAAC,IAC9C,KAAA;CACJ,IAAI,WAAW,QAAQ,KAAK,QAAQ,WAAW,KAAA,GAC7C,QAAQ,KACN,8BAA8B,QAAQ,OAAO,6BAA6B,SAAS,WAAW,OAAO,mBACvG;CAEF,IAAI,QAAQ,cAAc;EACxB,IAAI,CAAC,WAAW,QAAQ,KAAK,CAAC,QAAQ,OACpC,MAAM,IAAI,MACR,gEACF;EACF,MAAM,iBAAiB,UAAU,QAAQ,OAAO,QAAQ,YAAY;EACpE,iBAAsB,EAAE,MAAM,uBAAuB,CAAC;CACxD;CACA,MAAM,MAAM,WAAW,QAAQ,IAC3B,WACA,MAAM,EAAE,QAAQ,QAAQ,OAAO,CAAC;CACpC,MAAM,kBAAkB,KAAK,EAAE,OAAO,KAAK,CAAC;CAC5C,MAAM,SAAS,KAAK;EAAE,MAAM,QAAQ;EAAM,WAAW;CAAM,CAAC;CAC5D,YAAY,KAAK;EAAE,OAAO;EAAe,MAAM,QAAQ;CAAK,CAAC;CAC7D,OAAO;AACT"}
@@ -0,0 +1,21 @@
1
+ // src/dev-protocol.ts
2
+ const SEND_TIMEOUT_MS = 1e3;
3
+ /** Resolves once the message is written, or after a short timeout if the channel is gone. */
4
+ function sendToSupervisor(message) {
5
+ if (!process.send) return Promise.resolve();
6
+ return new Promise((resolve) => {
7
+ const timer = setTimeout(resolve, SEND_TIMEOUT_MS);
8
+ try {
9
+ process.send(message, () => {
10
+ clearTimeout(timer);
11
+ resolve();
12
+ });
13
+ } catch {
14
+ clearTimeout(timer);
15
+ resolve();
16
+ }
17
+ });
18
+ }
19
+ export { sendToSupervisor as t };
20
+
21
+ //# sourceMappingURL=dev-protocol.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dev-protocol.js","names":[],"sources":["../src/dev-protocol.ts"],"sourcesContent":["import type {\n ApiDocument,\n ArchitectureSchema,\n DocumentationOptions,\n} from \"@brickkit/core\";\nimport type {\n SerializedError,\n TelemetryRecord,\n WorkerErrorPhase,\n} from \"./dashboard-protocol\";\n\nconst SEND_TIMEOUT_MS = 1000;\n\n/*\n * What `brick dev`'s supervisor and its worker process agree on: the options\n * the worker starts with, and the messages it sends back over IPC.\n */\n\n/** The worker's one argument, as JSON. */\nexport interface WorkerOptions {\n /** Absolute path of the app entry. */\n entry: string;\n port: number;\n prefix?: string;\n /** Absolute path of the browser contract to write before serving. */\n clientOutput?: string;\n /** The supervisor serves the dashboard, so the worker reports its spans. */\n telemetry: boolean;\n}\n\n/** Messages the dev worker sends to the supervisor over the IPC channel. */\nexport type WorkerMessage =\n | { type: \"brick:telemetry\"; records: TelemetryRecord[] }\n | { type: \"brick:error\"; phase: WorkerErrorPhase; error: SerializedError }\n | { type: \"brick:architecture\"; architecture: ArchitectureSchema }\n | { type: \"brick:api-documents\"; documents: ApiDocument[] }\n | {\n type: \"brick:inspector\";\n /** The loopback port the workflow inspector listens on. */\n port: number;\n /** What the dashboard sends with each request to prove who it is. */\n token: string;\n }\n | {\n type: \"brick:documentation\";\n /** The app's `documentation` option; absent when it has none. */\n documentation?: DocumentationOptions;\n }\n /** The local files the entry imports, for the supervisor to watch. */\n | { type: \"brick:dependencies\"; files: string[] }\n /** The browser contract is written; the frontend may start. */\n | { type: \"brick:contract-ready\" };\n\n/** Resolves once the message is written, or after a short timeout if the channel is gone. */\nexport function sendToSupervisor(message: WorkerMessage): Promise<void> {\n if (!process.send) return Promise.resolve();\n return new Promise((resolve) => {\n const timer = setTimeout(resolve, SEND_TIMEOUT_MS);\n try {\n process.send!(message, () => {\n clearTimeout(timer);\n resolve();\n });\n } catch {\n clearTimeout(timer);\n resolve();\n }\n });\n}\n"],"mappings":";AAWA,MAAM,kBAAkB;;AA2CxB,SAAgB,iBAAiB,SAAuC;CACtE,IAAI,CAAC,QAAQ,MAAM,OAAO,QAAQ,QAAQ;CAC1C,OAAO,IAAI,SAAS,YAAY;EAC9B,MAAM,QAAQ,WAAW,SAAS,eAAe;EACjD,IAAI;GACF,QAAQ,KAAM,eAAe;IAC3B,aAAa,KAAK;IAClB,QAAQ;GACV,CAAC;EACH,QAAQ;GACN,aAAa,KAAK;GAClB,QAAQ;EACV;CACF,CAAC;AACH"}
@@ -1,3 +1,4 @@
1
+ import { r as CSRF_HEADER } from "./dashboard-protocol.js";
1
2
  import { t as installTracing } from "./dev-telemetry.js";
2
3
  // src/dev-reporter.ts
3
4
  /**
@@ -13,7 +14,7 @@ function installDevReporter(options) {
13
14
  method: "POST",
14
15
  headers: {
15
16
  "content-type": "application/json",
16
- "x-brick-dashboard": "1"
17
+ [CSRF_HEADER]: "1"
17
18
  },
18
19
  body: JSON.stringify(body)
19
20
  }).catch(() => {});
@@ -1 +1 @@
1
- {"version":3,"file":"dev-reporter.js","names":[],"sources":["../src/dev-reporter.ts"],"sourcesContent":["import { installTracing, type TelemetryRecord } from \"./dev-telemetry\";\n\nexport interface DevReporterOptions {\n /** The dashboard's ingest endpoint, for example http://127.0.0.1:9400/api/ingest. */\n url: string;\n}\n\n/**\n * Report this process's spans to a running dashboard. Dev servers that evaluate\n * the app in a worker (Vite with Nitro or TanStack Start) cannot share memory\n * with the dashboard, so the worker posts its spans over loopback HTTP. Call\n * before the app is constructed. Reporting is best effort: a dashboard that is\n * not running never affects the app.\n */\nexport function installDevReporter(options: DevReporterOptions): boolean {\n const post = (body: { records?: TelemetryRecord[]; worker?: string }) => {\n void fetch(options.url, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n \"x-brick-dashboard\": \"1\",\n },\n body: JSON.stringify(body),\n }).catch(() => {});\n };\n const registered = installTracing((records) => post({ records }));\n post({ worker: \"application loaded\" });\n return registered;\n}\n"],"mappings":";;;;;;;;;AAcA,SAAgB,mBAAmB,SAAsC;CACvE,MAAM,QAAQ,SAA2D;EACvE,MAAW,QAAQ,KAAK;GACtB,QAAQ;GACR,SAAS;IACP,gBAAgB;IAChB,qBAAqB;GACvB;GACA,MAAM,KAAK,UAAU,IAAI;EAC3B,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC;CACnB;CACA,MAAM,aAAa,gBAAgB,YAAY,KAAK,EAAE,QAAQ,CAAC,CAAC;CAChE,KAAK,EAAE,QAAQ,qBAAqB,CAAC;CACrC,OAAO;AACT"}
1
+ {"version":3,"file":"dev-reporter.js","names":[],"sources":["../src/dev-reporter.ts"],"sourcesContent":["import {\n CSRF_HEADER,\n CSRF_VALUE,\n type IngestPayload,\n} from \"./dashboard-protocol\";\nimport { installTracing } from \"./dev-telemetry\";\n\nexport interface DevReporterOptions {\n /** The dashboard's ingest endpoint, for example http://127.0.0.1:9400/api/ingest. */\n url: string;\n}\n\n/**\n * Report this process's spans to a running dashboard. Dev servers that evaluate\n * the app in a worker (Vite with Nitro or TanStack Start) cannot share memory\n * with the dashboard, so the worker posts its spans over loopback HTTP. Call\n * before the app is constructed. Reporting is best effort: a dashboard that is\n * not running never affects the app.\n */\nexport function installDevReporter(options: DevReporterOptions): boolean {\n const post = (body: IngestPayload) => {\n void fetch(options.url, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n [CSRF_HEADER]: CSRF_VALUE,\n },\n body: JSON.stringify(body),\n }).catch(() => {});\n };\n const registered = installTracing((records) => post({ records }));\n post({ worker: \"application loaded\" });\n return registered;\n}\n"],"mappings":";;;;;;;;;;AAmBA,SAAgB,mBAAmB,SAAsC;CACvE,MAAM,QAAQ,SAAwB;EACpC,MAAW,QAAQ,KAAK;GACtB,QAAQ;GACR,SAAS;IACP,gBAAgB;KACf,cAAA;GACH;GACA,MAAM,KAAK,UAAU,IAAI;EAC3B,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC;CACnB;CACA,MAAM,aAAa,gBAAgB,YAAY,KAAK,EAAE,QAAQ,CAAC,CAAC;CAChE,KAAK,EAAE,QAAQ,qBAAqB,CAAC;CACrC,OAAO;AACT"}
@@ -1,12 +1,14 @@
1
+ import { t as sendToSupervisor } from "./dev-protocol.js";
2
+ import { GLOBAL_SYMBOL } from "@brickkit/core";
1
3
  import { SpanStatusCode, context, propagation, trace } from "@opentelemetry/api";
2
4
  import { AsyncLocalStorageContextManager } from "@opentelemetry/context-async-hooks";
3
5
  import { W3CTraceContextPropagator } from "@opentelemetry/core";
4
6
  import { TracerProvider } from "@opentelemetry/sdk-trace";
5
7
  // src/dev-telemetry.ts
6
8
  /** Read by @brickkit/core's logger; see `createLogger` there. */
7
- const LOG_CAPTURE = Symbol.for("brickkit.logs.capture");
9
+ const LOG_CAPTURE = Symbol.for(GLOBAL_SYMBOL.logsCapture);
8
10
  /** Core's function that records a line on the running span; see `recordActive` there. */
9
- const LOG_RECORD = Symbol.for("brickkit.logs.record");
11
+ const LOG_RECORD = Symbol.for(GLOBAL_SYMBOL.logsRecord);
10
12
  const CONSOLE_CAPTURED = Symbol.for("brickkit.console.captured");
11
13
  const CONSOLE_LEVELS = {
12
14
  log: "info",
@@ -19,7 +21,6 @@ const MAX_TEXT_LENGTH = 500;
19
21
  const MAX_STACK_LENGTH = 4e3;
20
22
  const FLUSH_DELAY_MS = 20;
21
23
  const MAX_BATCH_SIZE = 200;
22
- const SEND_TIMEOUT_MS = 1e3;
23
24
  /**
24
25
  * Register the tracer provider, context manager, and W3C trace context
25
26
  * propagator. Span records are batched and passed to `onRecords`. Returns false
@@ -80,22 +81,6 @@ function installWorkerTelemetry() {
80
81
  });
81
82
  });
82
83
  }
83
- /** Resolves once the message is written, or after a short timeout if the channel is gone. */
84
- function sendToSupervisor(message) {
85
- if (!process.send) return Promise.resolve();
86
- return new Promise((resolve) => {
87
- const timer = setTimeout(resolve, SEND_TIMEOUT_MS);
88
- try {
89
- process.send(message, () => {
90
- clearTimeout(timer);
91
- resolve();
92
- });
93
- } catch {
94
- clearTimeout(timer);
95
- resolve();
96
- }
97
- });
98
- }
99
84
  function reportWorkerError(phase, error) {
100
85
  return sendToSupervisor({
101
86
  type: "brick:error",
@@ -193,6 +178,6 @@ var SupervisorSpanProcessor = class {
193
178
  this.#batcher.flush();
194
179
  }
195
180
  };
196
- export { sendToSupervisor as i, installWorkerTelemetry as n, reportWorkerError as r, installTracing as t };
181
+ export { installWorkerTelemetry as n, reportWorkerError as r, installTracing as t };
197
182
 
198
183
  //# sourceMappingURL=dev-telemetry.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"dev-telemetry.js","names":[],"sources":["../src/dev-telemetry.ts"],"sourcesContent":["import {\n context,\n propagation,\n SpanStatusCode,\n trace,\n type Attributes,\n type HrTime,\n} from \"@opentelemetry/api\";\nimport { AsyncLocalStorageContextManager } from \"@opentelemetry/context-async-hooks\";\nimport { W3CTraceContextPropagator } from \"@opentelemetry/core\";\nimport {\n TracerProvider,\n type ReadableSpan,\n type Span,\n type SpanProcessor,\n} from \"@opentelemetry/sdk-trace\";\nimport type {\n ApiDocument,\n ArchitectureSchema,\n DocumentationOptions,\n} from \"@brickkit/core\";\n\n/** Read by @brickkit/core's logger; see `createLogger` there. */\nconst LOG_CAPTURE = Symbol.for(\"brickkit.logs.capture\");\n/** Core's function that records a line on the running span; see `recordActive` there. */\nconst LOG_RECORD = Symbol.for(\"brickkit.logs.record\");\nconst CONSOLE_CAPTURED = Symbol.for(\"brickkit.console.captured\");\n\nconst CONSOLE_LEVELS = {\n log: \"info\",\n info: \"info\",\n warn: \"warn\",\n error: \"error\",\n debug: \"debug\",\n} as const;\n\nconst MAX_TEXT_LENGTH = 500;\nconst MAX_STACK_LENGTH = 4000;\nconst FLUSH_DELAY_MS = 20;\nconst MAX_BATCH_SIZE = 200;\nconst SEND_TIMEOUT_MS = 1000;\n\nexport interface SpanEventRecord {\n name: string;\n timeMs: number;\n attributes: Attributes;\n}\n\nexport interface SpanStartRecord {\n phase: \"start\";\n traceId: string;\n spanId: string;\n parentSpanId?: string;\n name: string;\n startMs: number;\n attributes: Attributes;\n}\n\nexport interface SpanEndRecord {\n phase: \"end\";\n traceId: string;\n spanId: string;\n name: string;\n endMs: number;\n status: \"unset\" | \"ok\" | \"error\";\n statusMessage?: string;\n attributes: Attributes;\n events: SpanEventRecord[];\n}\n\nexport type TelemetryRecord = SpanStartRecord | SpanEndRecord;\n\nexport type WorkerErrorPhase = \"startup\" | \"uncaught\" | \"unhandled-rejection\";\n\nexport interface SerializedError {\n name: string;\n message: string;\n stack?: string;\n}\n\n/** Messages the dev worker sends to the supervisor over the IPC channel. */\nexport type WorkerMessage =\n | { type: \"brick:telemetry\"; records: TelemetryRecord[] }\n | { type: \"brick:error\"; phase: WorkerErrorPhase; error: SerializedError }\n | { type: \"brick:architecture\"; architecture: ArchitectureSchema }\n | { type: \"brick:api-documents\"; documents: ApiDocument[] }\n | {\n type: \"brick:inspector\";\n /** The loopback port the workflow inspector listens on. */\n port: number;\n /** What the dashboard sends with each request to prove who it is. */\n token: string;\n }\n | {\n type: \"brick:documentation\";\n /** The app's `documentation` option; absent when it has none. */\n documentation?: DocumentationOptions;\n };\n\n/**\n * Register the tracer provider, context manager, and W3C trace context\n * propagator. Span records are batched and passed to `onRecords`. Returns false\n * when another tracer provider was already registered, in which case\n * `onRecords` never runs.\n */\nexport function installTracing(\n onRecords: (records: TelemetryRecord[]) => void,\n): boolean {\n const batcher = new RecordBatcher(onRecords);\n const registered = trace.setGlobalTracerProvider(\n new TracerProvider({\n spanProcessors: [new SupervisorSpanProcessor(batcher)],\n }),\n );\n context.setGlobalContextManager(\n new AsyncLocalStorageContextManager().enable(),\n );\n propagation.setGlobalPropagator(new W3CTraceContextPropagator());\n // From here the dashboard shows what actions and tools log, as span events,\n // so @brickkit/core stops printing it. The key is shared by name because the\n // app and the dev server may each hold their own copy of core.\n if (registered) {\n (globalThis as Record<symbol, unknown>)[LOG_CAPTURE] = true;\n captureConsole();\n }\n return registered;\n}\n\ntype Restore = () => void;\n\n/**\n * Send `console.log`, `info`, `warn`, `error`, and `debug` to the dashboard\n * while a traced request is running, as `ctx.logger` does, so code that logs\n * with `console` needs no change. Lines logged outside a request print as\n * usual. Only a dashboard turns this on, `brick dev`'s or the monitoring one\n * of `brick start`: with neither, the console is left alone. Calling it again\n * does nothing; the returned function puts the console back.\n */\nexport function captureConsole(): Restore {\n const target = console as unknown as Record<string | symbol, unknown>;\n const existing = target[CONSOLE_CAPTURED];\n if (typeof existing === \"function\") return existing as Restore;\n\n const globals = globalThis as Record<symbol, unknown>;\n const originals = new Map<string, (...args: unknown[]) => void>();\n for (const [method, level] of Object.entries(CONSOLE_LEVELS)) {\n const original = target[method] as (...args: unknown[]) => void;\n originals.set(method, original);\n target[method] = function (this: unknown, ...args: unknown[]) {\n const record = globals[LOG_RECORD];\n if (\n globals[LOG_CAPTURE] === true &&\n typeof record === \"function\" &&\n record(level, args) === true\n )\n return;\n original.apply(this, args);\n };\n }\n const restore: Restore = () => {\n for (const [method, original] of originals) target[method] = original;\n delete target[CONSOLE_CAPTURED];\n };\n target[CONSOLE_CAPTURED] = restore;\n return restore;\n}\n\n/**\n * Install tracing in the dev worker, so spans from apps built with\n * `brick({ telemetry: true })` reach the supervisor and join callers' traces.\n * Call before the app entry is imported.\n */\nexport function installWorkerTelemetry(): void {\n installTracing((records) => {\n void sendToSupervisor({ type: \"brick:telemetry\", records });\n });\n}\n\n/** Resolves once the message is written, or after a short timeout if the channel is gone. */\nexport function sendToSupervisor(message: WorkerMessage): Promise<void> {\n if (!process.send) return Promise.resolve();\n return new Promise((resolve) => {\n const timer = setTimeout(resolve, SEND_TIMEOUT_MS);\n try {\n process.send!(message, () => {\n clearTimeout(timer);\n resolve();\n });\n } catch {\n clearTimeout(timer);\n resolve();\n }\n });\n}\n\nexport function reportWorkerError(\n phase: WorkerErrorPhase,\n error: unknown,\n): Promise<void> {\n return sendToSupervisor({\n type: \"brick:error\",\n phase,\n error: serializeError(error),\n });\n}\n\nexport function serializeError(error: unknown): SerializedError {\n if (error instanceof Error) {\n return {\n name: error.name,\n message: truncate(error.message),\n stack:\n error.stack === undefined\n ? undefined\n : truncate(error.stack, MAX_STACK_LENGTH),\n };\n }\n return { name: \"Error\", message: truncate(String(error)) };\n}\n\nfunction truncate(text: string, limit = MAX_TEXT_LENGTH): string {\n return text.length > limit ? `${text.slice(0, limit)}…` : text;\n}\n\nfunction toMs(time: HrTime): number {\n return time[0] * 1000 + time[1] / 1e6;\n}\n\nfunction statusName(code: SpanStatusCode): \"unset\" | \"ok\" | \"error\" {\n if (code === SpanStatusCode.ERROR) return \"error\";\n if (code === SpanStatusCode.OK) return \"ok\";\n return \"unset\";\n}\n\nfunction boundAttributes(attributes: Attributes | undefined): Attributes {\n const bounded: Attributes = {};\n for (const [key, value] of Object.entries(attributes ?? {})) {\n bounded[key] =\n typeof value === \"string\" ? truncate(value, MAX_STACK_LENGTH) : value;\n }\n return bounded;\n}\n\nclass RecordBatcher {\n #records: TelemetryRecord[] = [];\n #timer: ReturnType<typeof setTimeout> | undefined;\n readonly #send: (records: TelemetryRecord[]) => void;\n\n constructor(send: (records: TelemetryRecord[]) => void) {\n this.#send = send;\n }\n\n push(record: TelemetryRecord): void {\n this.#records.push(record);\n if (this.#records.length >= MAX_BATCH_SIZE) this.flush();\n else this.#timer ??= setTimeout(() => this.flush(), FLUSH_DELAY_MS);\n }\n\n flush(): void {\n clearTimeout(this.#timer);\n this.#timer = undefined;\n if (this.#records.length === 0) return;\n const records = this.#records;\n this.#records = [];\n this.#send(records);\n }\n}\n\nclass SupervisorSpanProcessor implements SpanProcessor {\n readonly #batcher: RecordBatcher;\n\n constructor(batcher: RecordBatcher) {\n this.#batcher = batcher;\n }\n\n onStart(span: Span): void {\n const { traceId, spanId } = span.spanContext();\n this.#batcher.push({\n phase: \"start\",\n traceId,\n spanId,\n parentSpanId: span.parentSpanContext?.spanId,\n name: span.name,\n startMs: toMs(span.startTime),\n attributes: boundAttributes(span.attributes),\n });\n }\n\n onEnd(span: ReadableSpan): void {\n const { traceId, spanId } = span.spanContext();\n this.#batcher.push({\n phase: \"end\",\n traceId,\n spanId,\n name: span.name,\n endMs: toMs(span.endTime),\n status: statusName(span.status.code),\n statusMessage: span.status.message,\n attributes: boundAttributes(span.attributes),\n events: span.events.map((event) => ({\n name: event.name,\n timeMs: toMs(event.time),\n attributes: boundAttributes(event.attributes),\n })),\n });\n }\n\n async forceFlush(): Promise<void> {\n this.#batcher.flush();\n }\n\n async shutdown(): Promise<void> {\n this.#batcher.flush();\n }\n}\n"],"mappings":";;;;;;AAuBA,MAAM,cAAc,OAAO,IAAI,uBAAuB;;AAEtD,MAAM,aAAa,OAAO,IAAI,sBAAsB;AACpD,MAAM,mBAAmB,OAAO,IAAI,2BAA2B;AAE/D,MAAM,iBAAiB;CACrB,KAAK;CACL,MAAM;CACN,MAAM;CACN,OAAO;CACP,OAAO;AACT;AAEA,MAAM,kBAAkB;AACxB,MAAM,mBAAmB;AACzB,MAAM,iBAAiB;AACvB,MAAM,iBAAiB;AACvB,MAAM,kBAAkB;;;;;;;AAiExB,SAAgB,eACd,WACS;CACT,MAAM,UAAU,IAAI,cAAc,SAAS;CAC3C,MAAM,aAAa,MAAM,wBACvB,IAAI,eAAe,EACjB,gBAAgB,CAAC,IAAI,wBAAwB,OAAO,CAAC,EACvD,CAAC,CACH;CACA,QAAQ,wBACN,IAAI,gCAAgC,CAAC,CAAC,OAAO,CAC/C;CACA,YAAY,oBAAoB,IAAI,0BAA0B,CAAC;CAI/D,IAAI,YAAY;EACd,WAAwC,eAAe;EACvD,eAAe;CACjB;CACA,OAAO;AACT;;;;;;;;;AAYA,SAAgB,iBAA0B;CACxC,MAAM,SAAS;CACf,MAAM,WAAW,OAAO;CACxB,IAAI,OAAO,aAAa,YAAY,OAAO;CAE3C,MAAM,UAAU;CAChB,MAAM,4BAAY,IAAI,IAA0C;CAChE,KAAK,MAAM,CAAC,QAAQ,UAAU,OAAO,QAAQ,cAAc,GAAG;EAC5D,MAAM,WAAW,OAAO;EACxB,UAAU,IAAI,QAAQ,QAAQ;EAC9B,OAAO,UAAU,SAAyB,GAAG,MAAiB;GAC5D,MAAM,SAAS,QAAQ;GACvB,IACE,QAAQ,iBAAiB,QACzB,OAAO,WAAW,cA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AC3B,YAAY,gBAAgB,KAAK,UAAU;GAC3C,QAAQ,KAAK,OAAO,KAAK,WAAW;IAClC,MAAM,MAAM;IACZ,QAAQ,KAAK,MAAM,IAAI;IACvB,YAAY,gBAAgB,MAAM,UAAU;GAC9C,EAAE;EACJ,CAAC;CACH;CAEA,MAAM,aAA4B;EAChC,KAAK,SAAS,MAAM;CACtB;CAEA,MAAM,WAA0B;EAC9B,KAAK,SAAS,MAAM;CACtB;AACF"}
1
+ {"version":3,"file":"dev-telemetry.js","names":[],"sources":["../src/dev-telemetry.ts"],"sourcesContent":["import {\n context,\n propagation,\n SpanStatusCode,\n trace,\n type Attributes,\n type HrTime,\n} from \"@opentelemetry/api\";\nimport { AsyncLocalStorageContextManager } from \"@opentelemetry/context-async-hooks\";\nimport { W3CTraceContextPropagator } from \"@opentelemetry/core\";\nimport {\n TracerProvider,\n type ReadableSpan,\n type Span,\n type SpanProcessor,\n} from \"@opentelemetry/sdk-trace\";\nimport { GLOBAL_SYMBOL } from \"@brickkit/core\";\nimport type {\n SerializedError,\n TelemetryRecord,\n WorkerErrorPhase,\n} from \"./dashboard-protocol\";\nimport { sendToSupervisor } from \"./dev-protocol\";\n\n/** Read by @brickkit/core's logger; see `createLogger` there. */\nconst LOG_CAPTURE = Symbol.for(GLOBAL_SYMBOL.logsCapture);\n/** Core's function that records a line on the running span; see `recordActive` there. */\nconst LOG_RECORD = Symbol.for(GLOBAL_SYMBOL.logsRecord);\nconst CONSOLE_CAPTURED = Symbol.for(\"brickkit.console.captured\");\n\nconst CONSOLE_LEVELS = {\n log: \"info\",\n info: \"info\",\n warn: \"warn\",\n error: \"error\",\n debug: \"debug\",\n} as const;\n\nconst MAX_TEXT_LENGTH = 500;\nconst MAX_STACK_LENGTH = 4000;\nconst FLUSH_DELAY_MS = 20;\nconst MAX_BATCH_SIZE = 200;\n\n/**\n * Register the tracer provider, context manager, and W3C trace context\n * propagator. Span records are batched and passed to `onRecords`. Returns false\n * when another tracer provider was already registered, in which case\n * `onRecords` never runs.\n */\nexport function installTracing(\n onRecords: (records: TelemetryRecord[]) => void,\n): boolean {\n const batcher = new RecordBatcher(onRecords);\n const registered = trace.setGlobalTracerProvider(\n new TracerProvider({\n spanProcessors: [new SupervisorSpanProcessor(batcher)],\n }),\n );\n context.setGlobalContextManager(\n new AsyncLocalStorageContextManager().enable(),\n );\n propagation.setGlobalPropagator(new W3CTraceContextPropagator());\n // From here the dashboard shows what actions and tools log, as span events,\n // so @brickkit/core stops printing it. The key is shared by name because the\n // app and the dev server may each hold their own copy of core.\n if (registered) {\n (globalThis as Record<symbol, unknown>)[LOG_CAPTURE] = true;\n captureConsole();\n }\n return registered;\n}\n\ntype Restore = () => void;\n\n/**\n * Send `console.log`, `info`, `warn`, `error`, and `debug` to the dashboard\n * while a traced request is running, as `ctx.logger` does, so code that logs\n * with `console` needs no change. Lines logged outside a request print as\n * usual. Only a dashboard turns this on, `brick dev`'s or the monitoring one\n * of `brick start`: with neither, the console is left alone. Calling it again\n * does nothing; the returned function puts the console back.\n */\nexport function captureConsole(): Restore {\n const target = console as unknown as Record<string | symbol, unknown>;\n const existing = target[CONSOLE_CAPTURED];\n if (typeof existing === \"function\") return existing as Restore;\n\n const globals = globalThis as Record<symbol, unknown>;\n const originals = new Map<string, (...args: unknown[]) => void>();\n for (const [method, level] of Object.entries(CONSOLE_LEVELS)) {\n const original = target[method] as (...args: unknown[]) => void;\n originals.set(method, original);\n target[method] = function (this: unknown, ...args: unknown[]) {\n const record = globals[LOG_RECORD];\n if (\n globals[LOG_CAPTURE] === true &&\n typeof record === \"function\" &&\n record(level, args) === true\n )\n return;\n original.apply(this, args);\n };\n }\n const restore: Restore = () => {\n for (const [method, original] of originals) target[method] = original;\n delete target[CONSOLE_CAPTURED];\n };\n target[CONSOLE_CAPTURED] = restore;\n return restore;\n}\n\n/**\n * Install tracing in the dev worker, so spans from apps built with\n * `brick({ telemetry: true })` reach the supervisor and join callers' traces.\n * Call before the app entry is imported.\n */\nexport function installWorkerTelemetry(): void {\n installTracing((records) => {\n void sendToSupervisor({ type: \"brick:telemetry\", records });\n });\n}\n\nexport function reportWorkerError(\n phase: WorkerErrorPhase,\n error: unknown,\n): Promise<void> {\n return sendToSupervisor({\n type: \"brick:error\",\n phase,\n error: serializeError(error),\n });\n}\n\nfunction serializeError(error: unknown): SerializedError {\n if (error instanceof Error) {\n return {\n name: error.name,\n message: truncate(error.message),\n stack:\n error.stack === undefined\n ? undefined\n : truncate(error.stack, MAX_STACK_LENGTH),\n };\n }\n return { name: \"Error\", message: truncate(String(error)) };\n}\n\nfunction truncate(text: string, limit = MAX_TEXT_LENGTH): string {\n return text.length > limit ? `${text.slice(0, limit)}…` : text;\n}\n\nfunction toMs(time: HrTime): number {\n return time[0] * 1000 + time[1] / 1e6;\n}\n\nfunction statusName(code: SpanStatusCode): \"unset\" | \"ok\" | \"error\" {\n if (code === SpanStatusCode.ERROR) return \"error\";\n if (code === SpanStatusCode.OK) return \"ok\";\n return \"unset\";\n}\n\nfunction boundAttributes(attributes: Attributes | undefined): Attributes {\n const bounded: Attributes = {};\n for (const [key, value] of Object.entries(attributes ?? {})) {\n bounded[key] =\n typeof value === \"string\" ? truncate(value, MAX_STACK_LENGTH) : value;\n }\n return bounded;\n}\n\nclass RecordBatcher {\n #records: TelemetryRecord[] = [];\n #timer: ReturnType<typeof setTimeout> | undefined;\n readonly #send: (records: TelemetryRecord[]) => void;\n\n constructor(send: (records: TelemetryRecord[]) => void) {\n this.#send = send;\n }\n\n push(record: TelemetryRecord): void {\n this.#records.push(record);\n if (this.#records.length >= MAX_BATCH_SIZE) this.flush();\n else this.#timer ??= setTimeout(() => this.flush(), FLUSH_DELAY_MS);\n }\n\n flush(): void {\n clearTimeout(this.#timer);\n this.#timer = undefined;\n if (this.#records.length === 0) return;\n const records = this.#records;\n this.#records = [];\n this.#send(records);\n }\n}\n\nclass SupervisorSpanProcessor implements SpanProcessor {\n readonly #batcher: RecordBatcher;\n\n constructor(batcher: RecordBatcher) {\n this.#batcher = batcher;\n }\n\n onStart(span: Span): void {\n const { traceId, spanId } = span.spanContext();\n this.#batcher.push({\n phase: \"start\",\n traceId,\n spanId,\n parentSpanId: span.parentSpanContext?.spanId,\n name: span.name,\n startMs: toMs(span.startTime),\n attributes: boundAttributes(span.attributes),\n });\n }\n\n onEnd(span: ReadableSpan): void {\n const { traceId, spanId } = span.spanContext();\n this.#batcher.push({\n phase: \"end\",\n traceId,\n spanId,\n name: span.name,\n endMs: toMs(span.endTime),\n status: statusName(span.status.code),\n statusMessage: span.status.message,\n attributes: boundAttributes(span.attributes),\n events: span.events.map((event) => ({\n name: event.name,\n timeMs: toMs(event.time),\n attributes: boundAttributes(event.attributes),\n })),\n });\n }\n\n async forceFlush(): Promise<void> {\n this.#batcher.flush();\n }\n\n async shutdown(): Promise<void> {\n this.#batcher.flush();\n }\n}\n"],"mappings":";;;;;;;;AAyBA,MAAM,cAAc,OAAO,IAAI,cAAc,WAAW;;AAExD,MAAM,aAAa,OAAO,IAAI,cAAc,UAAU;AACtD,MAAM,mBAAmB,OAAO,IAAI,2BAA2B;AAE/D,MAAM,iBAAiB;CACrB,KAAK;CACL,MAAM;CACN,MAAM;CACN,OAAO;CACP,OAAO;AACT;AAEA,MAAM,kBAAkB;AACxB,MAAM,mBAAmB;AACzB,MAAM,iBAAiB;AACvB,MAAM,iBAAiB;;;;;;;AAQvB,SAAgB,eACd,WACS;CACT,MAAM,UAAU,IAAI,cAAc,SAAS;CAC3C,MAAM,aAAa,MAAM,wBACvB,IAAI,eAAe,EACjB,gBAAgB,CAAC,IAAI,wBAAwB,OAAO,CAAC,EACvD,CAAC,CACH;CACA,QAAQ,wBACN,IAAI,gCAAgC,CAAC,CAAC,OAAO,CAC/C;CACA,YAAY,oBAAoB,IAAI,0BAA0B,CAAC;CAI/D,IAAI,YAAY;EACd,WAAwC,eAAe;EACvD,eAAe;CACjB;CACA,OAAO;AACT;;;;;;;;;AAYA,SAAgB,iBAA0B;CACxC,MAAM,SAAS;CACf,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