@brickkit/cli 0.10.0 → 0.12.0

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 (147) hide show
  1. package/README.md +1 -1
  2. package/dashboard-dist/CollapsiblePanel-CbUysOp5.js +2 -0
  3. package/dashboard-dist/CompositeRoot-D4sRkYq3.js +1 -0
  4. package/dashboard-dist/Geist-Variable.woff2 +0 -0
  5. package/dashboard-dist/GeistMono-Variable.woff2 +0 -0
  6. package/dashboard-dist/PopoverPopup-CiI2avT_.js +1 -0
  7. package/dashboard-dist/api-reference-B-bZRtNV.js +265 -0
  8. package/dashboard-dist/app.css +2 -2
  9. package/dashboard-dist/app.js +13 -13
  10. package/dashboard-dist/ccount-CcG1m-Yh.js +1 -0
  11. package/dashboard-dist/client-BJJtVSVr.js +1 -0
  12. package/dashboard-dist/core-Z7NJFk0K.js +1 -0
  13. package/dashboard-dist/docs-Dpfc0wJb.js +4 -0
  14. package/dashboard-dist/docs.css +1 -1
  15. package/dashboard-dist/kit.js +1 -0
  16. package/dashboard-dist/popover-BzejBolB.js +1 -0
  17. package/dashboard-dist/react-dom-client.js +3 -0
  18. package/dashboard-dist/react-dom.js +3 -0
  19. package/dashboard-dist/react-jsx-runtime.js +1 -1
  20. package/dashboard-dist/react.js +3 -3
  21. package/dashboard-dist/theme.css +123 -0
  22. package/dist/app-entry2.js +2 -3
  23. package/dist/bin.d.ts +0 -2
  24. package/dist/bin.js +606 -49
  25. package/dist/bin.js.map +1 -1
  26. package/dist/client-contract-file2.js +2 -3
  27. package/dist/client-contract2.js +18 -10
  28. package/dist/client-contract2.js.map +1 -1
  29. package/dist/compiler.d.ts +1 -2
  30. package/dist/compiler.js +1 -1
  31. package/dist/compiler2.js +3 -4
  32. package/dist/config.js +250 -0
  33. package/dist/config.js.map +1 -0
  34. package/dist/dashboard-extension.d.ts +25 -0
  35. package/dist/dashboard.d.ts +2997 -0
  36. package/dist/dev-reporter.d.ts +0 -2
  37. package/dist/dev-reporter.js +1 -2
  38. package/dist/dev-telemetry-store.js +1411 -966
  39. package/dist/dev-telemetry-store.js.map +1 -1
  40. package/dist/dev-telemetry.js +3 -4
  41. package/dist/dev-telemetry.js.map +1 -1
  42. package/dist/dev-worker.js +3 -4
  43. package/dist/emit.d.ts +0 -2
  44. package/dist/index.d.ts +96 -17
  45. package/dist/index.js +4 -5
  46. package/dist/lint/eslint.d.ts +2 -0
  47. package/dist/lint/eslint.js +1 -0
  48. package/dist/lint/oxlint.d.ts +17 -0
  49. package/dist/lint/oxlint.js +18 -0
  50. package/dist/lint/oxlint.js.map +1 -0
  51. package/dist/plugin.d.ts +70 -0
  52. package/dist/plugin.js +64 -0
  53. package/dist/plugin.js.map +1 -0
  54. package/dist/presets.js +1066 -0
  55. package/dist/presets.js.map +1 -0
  56. package/dist/runner.js +114 -32
  57. package/dist/runner.js.map +1 -1
  58. package/dist/vite.d.ts +6 -5
  59. package/dist/vite.js +13 -9
  60. package/dist/vite.js.map +1 -1
  61. package/dist/workflows.d.ts +0 -2
  62. package/dist/workflows2.js +3 -4
  63. package/inspector-dist/client/assets/api.rpc-BvRk9kiK.js +0 -0
  64. package/inspector-dist/client/assets/api.stream._streamId-BvRk9kiK.js +0 -0
  65. package/inspector-dist/client/assets/app-CCzpuUz_.css +2 -0
  66. package/inspector-dist/client/assets/dist-BK8w6xOr.js +3930 -0
  67. package/inspector-dist/client/assets/dist-CG2aVufI.js +197 -0
  68. package/inspector-dist/client/assets/entry.client-D9jbgmTR.js +9391 -0
  69. package/inspector-dist/client/assets/highlighted-body-B3W2YXNL-DYVdwGy2.js +34 -0
  70. package/inspector-dist/client/assets/home-CyjkvtII.js +2883 -0
  71. package/inspector-dist/client/assets/jsx-runtime-CPEah4WQ.js +7084 -0
  72. package/inspector-dist/client/assets/manifest-ba30b52d.js +1 -0
  73. package/inspector-dist/client/assets/mermaid-3ZIDBTTL-Dy6IVqPy.js +1 -0
  74. package/inspector-dist/client/assets/root-8BMab1lL.css +2 -0
  75. package/inspector-dist/client/assets/root-DX9wtogx.js +332 -0
  76. package/inspector-dist/client/assets/run-detail-C69EJGql.js +1549 -0
  77. package/inspector-dist/client/assets/tabs-B6B88IjT.js +75692 -0
  78. package/inspector-dist/client/assets/tabs-L5XKzOpP.css +1 -0
  79. package/inspector-dist/client/assets/world-config-context-C3BqXPIv.js +30 -0
  80. package/inspector-dist/client/assets/zstd-browser-decoder-ByUgcY9H.js +41 -0
  81. package/inspector-dist/server/assets/app-WoDoT62X.js +100155 -0
  82. package/inspector-dist/server/assets/chunk-RLXIAIE6-CbvDIAEa.js +42977 -0
  83. package/inspector-dist/server/assets/dist-BRxZSWUN.js +1140 -0
  84. package/inspector-dist/server/assets/dist-CQnQcIJg.js +199 -0
  85. package/inspector-dist/server/assets/dist-DqRd9pyS.js +1644 -0
  86. package/inspector-dist/server/assets/dist-qR-969AD.js +10327 -0
  87. package/inspector-dist/server/assets/encryption-_PuklZNX.js +888 -0
  88. package/inspector-dist/server/assets/event-metadata-BVakQJ_y.js +147 -0
  89. package/inspector-dist/server/assets/functions-CImcpqNl.js +1172 -0
  90. package/inspector-dist/server/assets/global-singleton-CPirHxFh.js +82 -0
  91. package/inspector-dist/server/assets/highlighted-body-B3W2YXNL-fPMB_t7F.js +36 -0
  92. package/inspector-dist/server/assets/mermaid-3ZIDBTTL-bADXySE3.js +3 -0
  93. package/inspector-dist/server/assets/parse-D9Vvgzt9.js +471 -0
  94. package/inspector-dist/server/assets/rolldown-runtime-CLg409Sh.js +44 -0
  95. package/inspector-dist/server/assets/serialization-format-DDtsVTU1.js +478 -0
  96. package/inspector-dist/server/assets/token-BW4GdQZh.js +62 -0
  97. package/inspector-dist/server/assets/token-D6FXdkJT.js +57 -0
  98. package/inspector-dist/server/assets/token-util-BoNmi-wE.js +457 -0
  99. package/inspector-dist/server/assets/wrapper-wiqsGXcE.js +3626 -0
  100. package/inspector-dist/server/assets/ws-transport-DV7oG4mL.js +29478 -0
  101. package/inspector-dist/server/assets/zstd-browser-decoder-Cswf0KO6.js +40 -0
  102. package/inspector-dist/server/index.js +2 -57
  103. package/package.json +57 -32
  104. package/vite-client.d.ts +1 -1
  105. package/dashboard-dist/CollapsiblePanel-a54TwMKb.js +0 -2
  106. package/dashboard-dist/PopoverPopup-BLzjTqsi.js +0 -1
  107. package/dashboard-dist/api-reference-r893F8zi.js +0 -260
  108. package/dashboard-dist/core-BWAwhSFf.js +0 -1
  109. package/dashboard-dist/docs-CkMy3Y5i.js +0 -4
  110. package/dashboard-dist/preload-helper-CjQDFR0M.js +0 -1
  111. package/dist/bin.d.ts.map +0 -1
  112. package/dist/build.js +0 -119
  113. package/dist/build.js.map +0 -1
  114. package/dist/dev-reporter.d.ts.map +0 -1
  115. package/dist/emit.d.ts.map +0 -1
  116. package/dist/index.d.ts.map +0 -1
  117. package/dist/vite.d.ts.map +0 -1
  118. package/dist/workflows.d.ts.map +0 -1
  119. package/inspector-dist/client/assets/api.rpc-l0sNRNKZ.js +0 -1
  120. package/inspector-dist/client/assets/api.stream._streamId-l0sNRNKZ.js +0 -1
  121. package/inspector-dist/client/assets/app-CY7CQBRo.css +0 -1
  122. package/inspector-dist/client/assets/entry.client-BJ6G3n5t.js +0 -11697
  123. package/inspector-dist/client/assets/highlighted-body-B3W2YXNL-C-3wZnxf.js +0 -19
  124. package/inspector-dist/client/assets/home-CSKAS4P2.js +0 -4979
  125. package/inspector-dist/client/assets/index-DECCyMR0.js +0 -4482
  126. package/inspector-dist/client/assets/index-Dot7CgrA.js +0 -9837
  127. package/inspector-dist/client/assets/index-HqNj_XIX.js +0 -200
  128. package/inspector-dist/client/assets/manifest-4baa7c6f.js +0 -1
  129. package/inspector-dist/client/assets/mermaid-3ZIDBTTL-DC0K8uTy.js +0 -58626
  130. package/inspector-dist/client/assets/mermaid-3ZIDBTTL-F88p7PFX.css +0 -1
  131. package/inspector-dist/client/assets/root-Bmn5n3jF.js +0 -305
  132. package/inspector-dist/client/assets/root-CfCr265_.css +0 -1
  133. package/inspector-dist/client/assets/run-detail-CWoGxu_0.css +0 -1
  134. package/inspector-dist/client/assets/run-detail-Cc7tSGNq.js +0 -6237
  135. package/inspector-dist/client/assets/world-config-context-BAD1QCrR.js +0 -26
  136. package/inspector-dist/client/assets/zstd-browser-decoder-BQoRpP7L.js +0 -28
  137. package/inspector-dist/server/assets/app-C-ZVJtic.js +0 -174880
  138. package/inspector-dist/server/assets/highlighted-body-B3W2YXNL-C8sq8F_D.js +0 -71
  139. package/inspector-dist/server/assets/index-BfLBLRRi.js +0 -204
  140. package/inspector-dist/server/assets/index-BzrGWk7J.js +0 -1164
  141. package/inspector-dist/server/assets/index-CWJr34WJ.js +0 -1296
  142. package/inspector-dist/server/assets/index-CYlmUaKx.js +0 -191
  143. package/inspector-dist/server/assets/mermaid-3ZIDBTTL-Dv5rjfMN.js +0 -58
  144. package/inspector-dist/server/assets/token-DnLp3wBO.js +0 -95
  145. package/inspector-dist/server/assets/token-util-Bpfp-B0w.js +0 -33
  146. package/inspector-dist/server/assets/wrapper-D5LIcZ_u.js +0 -67
  147. package/inspector-dist/server/assets/zstd-browser-decoder-BM8GpVB8.js +0 -77
@@ -1,12 +1,13 @@
1
+ import { createRequire } from "node:module";
1
2
  import { fileURLToPath, pathToFileURL } from "node:url";
2
- import { existsSync, mkdirSync, statSync, watch, writeFileSync } from "node:fs";
3
- import { readFile, readdir, stat } from "node:fs/promises";
3
+ import { mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
4
4
  import { createServer } from "node:http";
5
5
  import { basename, dirname, extname, join, posix, relative, resolve, sep } from "node:path";
6
6
  import { Readable } from "node:stream";
7
7
  import { pipeline } from "node:stream/promises";
8
8
  import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
9
- //#region src/dev-inspector.ts
9
+ import { existsSync, mkdirSync, statSync, watch, writeFileSync } from "node:fs";
10
+ // src/dev-inspector.ts
10
11
  /** Where the dashboard serves the inspector. */
11
12
  const INSPECTOR_PATH = "/workflows";
12
13
  /** The header that proves a request comes from the dashboard. */
@@ -68,8 +69,7 @@ async function startInspector(app, directory = INSPECTOR_DIRECTORY) {
68
69
  stop: () => void server.stop(true)
69
70
  };
70
71
  }
71
- //#endregion
72
- //#region src/dev-history-csv.ts
72
+ // src/dev-history-csv.ts
73
73
  const CSV_COLUMNS = [
74
74
  "time",
75
75
  "method",
@@ -110,8 +110,7 @@ function tracesToCsv(traces) {
110
110
  });
111
111
  return [CSV_COLUMNS.join(","), ...lines].join("\n") + "\n";
112
112
  }
113
- //#endregion
114
- //#region src/dev-history.ts
113
+ // src/dev-history.ts
115
114
  const DAY_MS = 864e5;
116
115
  const MAX_TRACES = 1e5;
117
116
  const FLUSH_MS = 250;
@@ -488,15 +487,22 @@ function parseHistoryQuery(params, now = Date.now()) {
488
487
  offset: integer("offset")
489
488
  };
490
489
  }
491
- //#endregion
492
- //#region src/dev-dashboard-shell.ts
490
+ // src/dev-dashboard-shell.ts
493
491
  /**
494
492
  * The page the dashboard serves at `/`. The React app and its styles load from
495
493
  * `/assets/`; the inline script applies the saved theme before first paint. The
496
- * import map lets the project's own docs components, bundled apart from the
497
- * dashboard, share its copy of React.
494
+ * import map hands the project's own modules (its docs components and its
495
+ * dashboard extension), bundled apart from the dashboard, the dashboard's copy
496
+ * of React and its UI kit, so there is one of each on the page.
497
+ *
498
+ * `extension` describes the project's extension: `revision` changes with every
499
+ * rebuild (the page reloads when it does), `js` and `css` say what it built.
500
+ * `theme` is whether `/assets/brick-theme.css` has token values to apply.
498
501
  */
499
- const DEV_DASHBOARD_SHELL = `<!doctype html>
502
+ function dashboardShell(options = {}) {
503
+ const { extension, theme } = options;
504
+ const version = extension ? `?v=${extension.revision}` : "";
505
+ return `<!doctype html>
500
506
  <html lang="en">
501
507
  <head>
502
508
  <meta charset="utf-8">
@@ -513,8 +519,8 @@ const DEV_DASHBOARD_SHELL = `<!doctype html>
513
519
  })();
514
520
  <\/script>
515
521
  <link rel="stylesheet" href="/assets/app.css">
516
- <script type="importmap">
517
- {"imports":{"react":"/assets/react.js","react/jsx-runtime":"/assets/react-jsx-runtime.js","react/jsx-dev-runtime":"/assets/react-jsx-runtime.js"}}
522
+ ${extension?.css ? `<link rel="stylesheet" href="/assets/extension.css${version}">\n` : ""}${theme ? `<link rel="stylesheet" href="/assets/brick-theme.css" data-brick-theme>\n` : ""}${extension ? `<meta name="brick-extension" data-revision="${extension.revision}"${extension.js ? ` data-src="/assets/extension.js${version}"` : ""}>\n` : ""}<script type="importmap">
523
+ {"imports":{"react":"/assets/react.js","react/jsx-runtime":"/assets/react-jsx-runtime.js","react/jsx-dev-runtime":"/assets/react-jsx-runtime.js","react-dom":"/assets/react-dom.js","react-dom/client":"/assets/react-dom-client.js","@brickkit/cli/dashboard":"/assets/kit.js"}}
518
524
  <\/script>
519
525
  </head>
520
526
  <body>
@@ -523,8 +529,8 @@ const DEV_DASHBOARD_SHELL = `<!doctype html>
523
529
  </body>
524
530
  </html>
525
531
  `;
526
- //#endregion
527
- //#region src/dashboard-access.ts
532
+ }
533
+ // src/dashboard-access.ts
528
534
  /** How long the app's `authorize` may take before the request is refused. */
529
535
  const AUTHORIZE_TIMEOUT_MS = 5e3;
530
536
  /** Whether `host` can only be reached from the machine it runs on. */
@@ -640,457 +646,656 @@ function createAccess(auth, onError = () => {}, timeoutMs = AUTHORIZE_TIMEOUT_MS
640
646
  return refusal(401, "Unauthorized", prompt);
641
647
  };
642
648
  }
643
- //#endregion
644
- //#region src/dev-dashboard.ts
645
- const DEFAULT_DASHBOARD_PORT = 9400;
646
- const KEEPALIVE_MS = 15e3;
647
- const MAX_INGEST_BYTES = 5242880;
648
- const MAX_PROXY_BYTES = 10485760;
649
- const NOT_FORWARDED = /* @__PURE__ */ new Set([
650
- "host",
651
- "connection",
652
- "keep-alive",
653
- "proxy-connection",
654
- "transfer-encoding",
655
- "te",
656
- "trailer",
657
- "upgrade",
658
- "content-length",
659
- "accept-encoding",
660
- "origin",
661
- "referer",
662
- "cookie"
663
- ]);
664
- const NOT_RETURNED = /* @__PURE__ */ new Set([
665
- "connection",
666
- "keep-alive",
667
- "transfer-encoding",
668
- "content-length",
669
- "content-encoding",
670
- "set-cookie"
671
- ]);
672
- /**
673
- * What a production dashboard may show: the shell and its assets, the live
674
- * state and its event stream, and stored history. Nothing that changes the app
675
- * or reaches into it (restart, the API proxy, ingest) and nothing from the
676
- * project's source (documentation, OpenAPI documents).
677
- */
678
- const isMonitoringRoute = (method, pathname) => method === "GET" && (pathname === "/" || pathname.startsWith("/assets/") || pathname === "/api/state" || pathname === "/api/events" || pathname.startsWith("/api/history"));
679
- const PRODUCTION_HEADERS = {
680
- "x-content-type-options": "nosniff",
681
- "x-frame-options": "DENY",
682
- "referrer-policy": "no-referrer",
683
- "cross-origin-opener-policy": "same-origin",
684
- "cross-origin-resource-policy": "same-origin",
685
- "cache-control": "no-store",
686
- "content-security-policy": "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'"
649
+ // src/dev-docs.ts
650
+ const PACKAGES = ["fumadocs-core", "@mdx-js/mdx"];
651
+ const PAGE_EXTENSIONS = /* @__PURE__ */ new Set([".md", ".mdx"]);
652
+ const IMAGE_TYPES = {
653
+ ".png": "image/png",
654
+ ".jpg": "image/jpeg",
655
+ ".jpeg": "image/jpeg",
656
+ ".gif": "image/gif",
657
+ ".webp": "image/webp",
658
+ ".avif": "image/avif",
659
+ ".svg": "image/svg+xml",
660
+ ".ico": "image/x-icon"
687
661
  };
688
- /** How long `/_health` waits for the app before calling it down. */
689
- const PROBE_TIMEOUT_MS = 3e3;
662
+ const REFRESH_DELAY_MS = 100;
663
+ async function loadFumadocs() {
664
+ try {
665
+ const [source, matter, plugins, search, mdx] = await Promise.all([
666
+ import("fumadocs-core/source"),
667
+ import("fumadocs-core/content/md/frontmatter"),
668
+ import("fumadocs-core/mdx-plugins"),
669
+ import("fumadocs-core/search/server"),
670
+ import("@mdx-js/mdx")
671
+ ]);
672
+ return {
673
+ loader: source.loader,
674
+ frontmatter: matter.frontmatter,
675
+ plugins,
676
+ createSearchAPI: search.createSearchAPI,
677
+ compile: mdx.compile
678
+ };
679
+ } catch (error) {
680
+ if (error.code === "ERR_MODULE_NOT_FOUND" || /Cannot find (module|package)/.test(String(error?.message))) return [...PACKAGES];
681
+ throw error;
682
+ }
683
+ }
684
+ const humanize = (name) => {
685
+ const spaced = name.replace(/[-_]+/g, " ").trim();
686
+ return spaced.charAt(0).toUpperCase() + spaced.slice(1);
687
+ };
688
+ const H1 = /^#\s+(.+?)\s*#*\s*$/;
690
689
  /**
691
- * Serve the dashboard, on loopback unless told otherwise. On loopback requests
692
- * must name a local host (blocks DNS rebinding), and restart requires a header
693
- * that cross-origin pages cannot send without a preflight. Elsewhere `auth` is
694
- * required and decides who gets in. Uses node:http, so it runs under Bun and
695
- * under Node (Vite's dev server runs under Node).
690
+ * The first `# Heading` outside code fences: its text, and the content without
691
+ * it. The page shows its title above the content, so a heading that only
692
+ * repeats the title would appear twice.
696
693
  */
697
- function startDevDashboard(options) {
698
- const host = options.host ?? "127.0.0.1";
699
- const loopback = isLoopbackHost(host);
700
- const production = options.mode === "production";
701
- if (!loopback && !options.auth) return Promise.reject(/* @__PURE__ */ new Error(`Brick: the dashboard would listen on ${host}, where others can reach it, so it needs access control. Set dashboard.auth with a token or an authorize function.`));
702
- const access = options.auth ? createAccess(options.auth, (error) => console.error("[Brick-TS] The dashboard sign-in check failed:", error)) : void 0;
703
- let allowedHosts = /* @__PURE__ */ new Set();
704
- const server = createServer((request, response) => {
705
- respond(request, response).catch((error) => {
706
- console.error("[Brick-TS] The dashboard failed to answer:", error);
707
- if (response.headersSent) response.end();
708
- else send(response, 500, "Server error");
709
- });
710
- });
711
- async function respond(request, response) {
712
- if (production) for (const [name, value] of Object.entries(PRODUCTION_HEADERS)) response.setHeader(name, value);
713
- if (loopback && !allowedHosts.has(request.headers.host ?? "")) {
714
- send(response, 403, "Forbidden");
715
- return;
716
- }
717
- const url = new URL(request.url ?? "/", "http://127.0.0.1");
718
- const { pathname } = url;
719
- if (pathname === "/_health" && (request.method === "GET" || request.method === "HEAD")) {
720
- await health(response);
721
- return;
722
- }
723
- if (access) {
724
- const decision = await access(request);
725
- if (!decision.allowed) {
726
- send(response, decision.status, decision.body, decision.headers);
727
- return;
728
- }
729
- }
730
- if (production && !isMonitoringRoute(request.method, pathname)) {
731
- send(response, 404, "Not found");
732
- return;
694
+ function firstHeading(content) {
695
+ const lines = content.split("\n");
696
+ let fenced = false;
697
+ let seenText = false;
698
+ for (const [index, line] of lines.entries()) if (/^\s*(```|~~~)/.test(line)) {
699
+ fenced = !fenced;
700
+ seenText = true;
701
+ } else if (!fenced) {
702
+ const match = H1.exec(line);
703
+ if (match) {
704
+ const rest = [...lines.slice(0, index), ...lines.slice(index + 1)];
705
+ if (rest[index]?.trim() === "") rest.splice(index, 1);
706
+ return {
707
+ text: match[1],
708
+ rest: rest.join("\n"),
709
+ leading: !seenText
710
+ };
733
711
  }
734
- handle(request, response, url);
712
+ if (line.trim() !== "") seenText = true;
735
713
  }
736
- /** 200 while the app answers its own health check, 503 when it does not. */
737
- async function health(response) {
738
- const probe = options.probe;
739
- let up = true;
740
- if (probe) {
741
- let timer;
742
- up = await Promise.race([probe().catch(() => false), new Promise((resolve) => {
743
- timer = setTimeout(() => resolve(false), PROBE_TIMEOUT_MS);
744
- })]);
745
- clearTimeout(timer);
714
+ }
715
+ async function scan(root, fumadocs, warn) {
716
+ const pages = [];
717
+ const metas = [];
718
+ async function visit(directory) {
719
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
720
+ if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
721
+ const absolute = join(directory, entry.name);
722
+ const path = relative(root, absolute).split(sep).join("/");
723
+ if (entry.isDirectory()) await visit(absolute);
724
+ else if (entry.name === "meta.json") try {
725
+ const data = JSON.parse(await readFile(absolute, "utf8"));
726
+ if (data && typeof data === "object") metas.push({
727
+ path,
728
+ data
729
+ });
730
+ } catch (error) {
731
+ warn(`[Brick-TS] Skipping docs ${path}: ${errorMessage(error)}`);
732
+ }
733
+ else if (PAGE_EXTENSIONS.has(extname(entry.name))) {
734
+ const text = await readFile(absolute, "utf8");
735
+ let data = {};
736
+ let content = text;
737
+ try {
738
+ const parsed = fumadocs.frontmatter(text);
739
+ data = parsed.data;
740
+ content = parsed.content;
741
+ } catch (error) {
742
+ warn(`[Brick-TS] Ignoring the frontmatter of docs ${path}: ${errorMessage(error)}`);
743
+ }
744
+ const name = basename(entry.name, extname(entry.name));
745
+ const heading = firstHeading(content);
746
+ const given = typeof data.title === "string" && data.title ? data.title : void 0;
747
+ const title = given ?? heading?.text ?? humanize(name === "index" ? basename(dirname(path)) || "Home" : name);
748
+ if (heading && (!given || heading.leading && heading.text === given)) content = heading.rest;
749
+ pages.push({
750
+ path,
751
+ absolute,
752
+ title,
753
+ description: typeof data.description === "string" ? data.description : void 0,
754
+ content,
755
+ data
756
+ });
757
+ }
746
758
  }
747
- send(response, up ? 200 : 503, JSON.stringify({
748
- status: up ? "ok" : "degraded",
749
- ...probe ? { app: up ? "up" : "down" } : {}
750
- }), {
751
- "content-type": "application/json",
752
- "cache-control": "no-store"
753
- });
754
759
  }
755
- function handle(request, response, url) {
756
- const { pathname } = url;
757
- if (request.method === "GET" && pathname === "/") {
758
- send(response, 200, DEV_DASHBOARD_SHELL, {
759
- "content-type": "text/html; charset=utf-8",
760
- "cache-control": "no-store"
761
- });
762
- return;
763
- }
764
- if (request.method === "GET" && pathname.startsWith("/assets/")) {
765
- serveAsset(response, pathname.slice(8));
766
- return;
767
- }
768
- if (request.method === "GET" && pathname === "/api/state") {
769
- send(response, 200, JSON.stringify(snapshot()), { "content-type": "application/json" });
770
- return;
771
- }
772
- if (request.method === "GET" && pathname === "/api/events") {
773
- eventStream(request, response);
774
- return;
775
- }
776
- if (request.method === "GET" && pathname.startsWith("/api/history") && options.history) {
777
- history(options.history, pathname, url.searchParams, response);
778
- return;
779
- }
780
- if (request.method === "GET" && pathname.startsWith("/api/docs")) {
781
- docsRoute(response, pathname, url.searchParams);
782
- return;
783
- }
784
- if (request.method === "GET" && pathname === "/api/openapi") {
785
- send(response, 200, JSON.stringify(options.store.apiDocuments()), {
786
- "content-type": "application/json",
787
- "cache-control": "no-store"
788
- });
789
- return;
790
- }
791
- if (pathname === "/api/proxy") {
792
- proxy(request, response, url);
793
- return;
794
- }
795
- if (pathname === "/workflows" || pathname.startsWith(`/workflows/`)) {
796
- response.setHeader("content-security-policy", "frame-ancestors 'self'");
797
- response.setHeader("x-frame-options", "SAMEORIGIN");
798
- inspector(request, response, url);
799
- return;
800
- }
801
- if (request.method === "POST" && pathname === "/api/ingest") {
802
- ingest(request, response);
803
- return;
804
- }
805
- if (request.method === "POST" && pathname === "/api/restart" && options.restart) {
806
- if (request.headers["x-brick-dashboard"] !== "1") {
807
- send(response, 403, "Forbidden");
808
- return;
809
- }
810
- options.restart();
811
- send(response, 202, "");
812
- return;
760
+ await visit(root);
761
+ return {
762
+ pages,
763
+ metas
764
+ };
765
+ }
766
+ function errorMessage(error) {
767
+ return error instanceof Error ? error.message : String(error);
768
+ }
769
+ function walk(node, visit) {
770
+ visit(node);
771
+ for (const child of node.children ?? []) walk(child, visit);
772
+ }
773
+ /** Ways a link inside a page can point at another page or a local image. */
774
+ function resolveInside(from, href) {
775
+ if (/^[a-z][a-z\d+.-]*:/i.test(href) || href.startsWith("#")) return void 0;
776
+ if (href.startsWith("/")) return void 0;
777
+ const [target] = href.split(/[?#]/);
778
+ if (!target) return void 0;
779
+ const resolved = posix.normalize(posix.join(posix.dirname(from), target));
780
+ return resolved.startsWith("../") ? void 0 : resolved;
781
+ }
782
+ /**
783
+ * The page tree and compiled pages of one docs folder. It watches the folder,
784
+ * so edits show in the dashboard as they are saved.
785
+ */
786
+ var DevDocs = class {
787
+ #root;
788
+ #documentation;
789
+ /** Relative paths in `documentation` start here: the app entry's folder. */
790
+ #base;
791
+ #fumadocs;
792
+ #warn;
793
+ #listeners = /* @__PURE__ */ new Set();
794
+ #watchers = [];
795
+ #loader;
796
+ #pages = /* @__PURE__ */ new Map();
797
+ #byPath = /* @__PURE__ */ new Map();
798
+ #compiled = /* @__PURE__ */ new Map();
799
+ #search;
800
+ #timer;
801
+ #refreshing = Promise.resolve();
802
+ #closed = false;
803
+ #title = "Docs";
804
+ revision = 0;
805
+ constructor(base, documentation, fumadocs, warn) {
806
+ this.#base = base;
807
+ this.#documentation = documentation;
808
+ this.#root = resolve(base, documentation.dir);
809
+ this.#fumadocs = fumadocs;
810
+ this.#warn = warn;
811
+ }
812
+ /** Read the folder again and tell listeners. */
813
+ async refresh() {
814
+ this.#refreshing = this.#refreshing.then(() => this.#scan());
815
+ await this.#refreshing;
816
+ }
817
+ async #scan() {
818
+ const { pages, metas } = await scan(this.#root, this.#fumadocs, this.#warn);
819
+ if (this.#closed) return;
820
+ const source = this.#fumadocs.loader({
821
+ baseUrl: "/",
822
+ source: { files: [...pages.map((page) => ({
823
+ type: "page",
824
+ path: page.path,
825
+ data: {
826
+ ...page.data,
827
+ title: page.title,
828
+ description: page.description
829
+ }
830
+ })), ...metas.map((meta) => ({
831
+ type: "meta",
832
+ path: meta.path,
833
+ data: meta.data
834
+ }))] }
835
+ });
836
+ this.#loader = source;
837
+ this.#pages = /* @__PURE__ */ new Map();
838
+ this.#byPath = /* @__PURE__ */ new Map();
839
+ for (const page of this.#loader.getPages()) {
840
+ const slug = page.slugs.join("/");
841
+ const file = pages.find((candidate) => candidate.path === page.path);
842
+ if (!file) continue;
843
+ this.#pages.set(slug, file);
844
+ this.#byPath.set(file.path, slug);
813
845
  }
814
- send(response, 404, "Not found");
846
+ this.#compiled.clear();
847
+ this.#search = void 0;
848
+ const tree = this.#loader.getPageTree();
849
+ this.#title = typeof tree.name === "string" ? tree.name : "Docs";
850
+ this.revision++;
851
+ for (const listener of this.#listeners) listener();
815
852
  }
816
- function snapshot() {
853
+ /** Start watching the folder, and the project's components module. */
854
+ watch() {
855
+ const changed = () => {
856
+ clearTimeout(this.#timer);
857
+ this.#timer = setTimeout(() => {
858
+ this.refresh().catch((error) => this.#warn(`[Brick-TS] Docs: ${errorMessage(error)}`));
859
+ }, REFRESH_DELAY_MS);
860
+ };
861
+ const folders = [this.#root];
862
+ if (this.#documentation.components) folders.push(dirname(this.#componentsPath()));
863
+ for (const [index, folder] of folders.entries()) try {
864
+ this.#watchers.push(watch(folder, { recursive: index === 0 }, () => changed()));
865
+ } catch {
866
+ try {
867
+ this.#watchers.push(watch(folder, () => changed()));
868
+ } catch {}
869
+ }
870
+ }
871
+ onChange(listener) {
872
+ this.#listeners.add(listener);
873
+ return () => {
874
+ this.#listeners.delete(listener);
875
+ };
876
+ }
877
+ snapshot() {
817
878
  return {
818
- ...options.store.snapshot(),
819
- canRestart: Boolean(options.restart),
820
- historyDays: options.history?.days ?? 0,
821
- mode: production ? "production" : "dev"
879
+ revision: this.revision,
880
+ status: "ready",
881
+ title: this.#title,
882
+ components: Boolean(this.#documentation.components)
883
+ };
884
+ }
885
+ info() {
886
+ return {
887
+ tree: simplify(this.#loader?.getPageTree()),
888
+ components: Boolean(this.#documentation.components),
889
+ revision: this.revision
890
+ };
891
+ }
892
+ /** Compile one page; undefined when there is no such page. */
893
+ async page(slugs) {
894
+ const key = slugs.join("/");
895
+ const file = this.#pages.get(key);
896
+ if (!file) return void 0;
897
+ const cached = this.#compiled.get(key);
898
+ if (cached) return cached;
899
+ const page = await this.#compile(file, slugs);
900
+ if (this.#pages.get(key) === file) this.#compiled.set(key, page);
901
+ return page;
902
+ }
903
+ async #compile(file, slugs) {
904
+ const { plugins, compile } = this.#fumadocs;
905
+ const base = {
906
+ title: file.title,
907
+ description: file.description,
908
+ path: file.path,
909
+ slugs
822
910
  };
911
+ try {
912
+ const result = await compile({
913
+ path: file.absolute,
914
+ value: file.content
915
+ }, {
916
+ outputFormat: "function-body",
917
+ development: false,
918
+ remarkPlugins: [
919
+ plugins.remarkGfm,
920
+ plugins.remarkHeading,
921
+ plugins.remarkCodeTab,
922
+ plugins.remarkNpm,
923
+ plugins.remarkAdmonition,
924
+ () => (tree) => this.#rewriteLinks(tree, file.path)
925
+ ],
926
+ rehypePlugins: [plugins.rehypeCode]
927
+ });
928
+ const toc = result.data.toc ?? [];
929
+ return {
930
+ ...base,
931
+ toc: toc.map((item) => ({
932
+ title: plainText(item.title),
933
+ url: item.url,
934
+ depth: item.depth
935
+ })),
936
+ code: String(result)
937
+ };
938
+ } catch (error) {
939
+ return {
940
+ ...base,
941
+ toc: [],
942
+ code: "",
943
+ error: errorMessage(error)
944
+ };
945
+ }
823
946
  }
824
947
  /**
825
- * Accept telemetry from an application process that cannot share memory with
826
- * the dashboard, such as a dev server worker: span batches, and a notice when
827
- * the app loads.
948
+ * Links to other pages become dashboard routes, and local images are served
949
+ * from the docs folder, so a folder reads the same here as on a docs site.
950
+ * This covers markdown links and the `href` of components such as `<Card>`.
828
951
  */
829
- function ingest(request, response) {
830
- if (request.headers["x-brick-dashboard"] !== "1") {
831
- send(response, 403, "Forbidden");
832
- return;
833
- }
834
- let body = "";
835
- let rejected = false;
836
- request.setEncoding("utf8");
837
- request.on("data", (chunk) => {
838
- if (rejected) return;
839
- body += chunk;
840
- if (body.length > MAX_INGEST_BYTES) {
841
- rejected = true;
842
- send(response, 413, "Payload too large");
843
- request.destroy();
844
- }
845
- });
846
- request.on("end", () => {
847
- if (rejected) return;
848
- try {
849
- const payload = JSON.parse(body);
850
- if (Array.isArray(payload.records)) options.store.ingest(payload.records, options.store.latestGeneration);
851
- if (typeof payload.worker === "string") options.store.startGeneration(payload.worker);
852
- send(response, 204, "");
853
- } catch {
854
- send(response, 400, "Bad request");
952
+ #rewriteLinks(tree, from) {
953
+ const file = (resolved) => `/api/docs/files/${resolved.split("/").map(encodeURIComponent).join("/")}`;
954
+ walk(tree, (node) => {
955
+ if (node.type === "link" && node.url !== void 0) node.url = this.#route(from, node.url) ?? node.url;
956
+ else if (node.type === "image" && node.url !== void 0) {
957
+ const resolved = resolveInside(from, node.url);
958
+ if (resolved !== void 0) node.url = file(resolved);
959
+ } else if (node.type === "mdxJsxFlowElement" || node.type === "mdxJsxTextElement") for (const attribute of node.attributes ?? []) {
960
+ if (attribute.type !== "mdxJsxAttribute") continue;
961
+ if (typeof attribute.value !== "string") continue;
962
+ if (attribute.name === "href") attribute.value = this.#route(from, attribute.value) ?? attribute.value;
963
+ else if (attribute.name === "src" && node.name === "img") {
964
+ const resolved = resolveInside(from, attribute.value);
965
+ if (resolved !== void 0) attribute.value = file(resolved);
966
+ }
855
967
  }
856
968
  });
857
969
  }
858
- /** The Docs tab's data: tree, compiled pages, search, images, components. */
859
- async function docsRoute(response, pathname, params) {
860
- const docs = options.docs?.();
861
- if (!docs) {
862
- send(response, 404, "The app has no documentation.");
863
- return;
864
- }
865
- const json = (body) => send(response, 200, JSON.stringify(body), {
866
- "content-type": "application/json",
867
- "cache-control": "no-store"
868
- });
869
- try {
870
- if (pathname === "/api/docs") return json(docs.info());
871
- if (pathname === "/api/docs/search") return json(await docs.search(params.get("q") ?? ""));
872
- if (pathname === "/api/docs/components.js") {
873
- const code = await docs.components();
874
- if (code === void 0) return send(response, 404, "No components.");
875
- return send(response, 200, code, {
876
- "content-type": "text/javascript; charset=utf-8",
877
- "cache-control": "no-store"
878
- });
879
- }
880
- const pagePrefix = "/api/docs/page";
881
- if (pathname === pagePrefix || pathname.startsWith(`${pagePrefix}/`)) {
882
- const slugs = pathname.slice(14).split("/").filter(Boolean).map(decodeURIComponent);
883
- const page = await docs.page(slugs);
884
- return page ? json(page) : send(response, 404, "No such page.");
885
- }
886
- if (pathname.startsWith("/api/docs/files/")) {
887
- const file = await docs.file(pathname.slice(16).split("/").map(decodeURIComponent).join("/"));
888
- if (!file) return send(response, 404, "No such file.");
889
- return send(response, 200, file.body, {
890
- "content-type": file.type,
891
- "cache-control": "no-store",
892
- "content-security-policy": "sandbox"
893
- });
894
- }
895
- send(response, 404, "Not found");
896
- } catch (error) {
897
- send(response, error instanceof URIError ? 400 : 500, error instanceof Error ? error.message : String(error));
898
- }
899
- }
900
- /**
901
- * Send a request on to the app for the APIs view, which cannot call the app
902
- * directly: it is another origin. Only the dashboard's own page may use this,
903
- * and only to reach the app being shown. The address to call is `?url=`; a
904
- * `?cookie=` is the cookie parameters the reader typed into Try it, and the
905
- * only cookie the app is sent (the dashboard's own are never forwarded).
906
- */
907
970
  /**
908
- * Pass a request to the workflow inspector, which the app serves on a port of
909
- * its own, and stream its answer back (it follows a run's output as it
910
- * grows). Anyone who can open the dashboard may look, but a change must come
911
- * from the dashboard's own page: the inspector can cancel runs and resume
912
- * hooks, and a page on another site could otherwise post to it.
971
+ * The dashboard route for a link to a page of these docs, or undefined for
972
+ * anything else (other sites, in-page anchors, files). A link to a page that
973
+ * does not exist still becomes a route, so it says "No such page" here
974
+ * instead of leaving the dashboard.
913
975
  */
914
- async function inspector(request, response, url) {
915
- const target = options.store.inspectorTarget();
916
- if (!target) {
917
- send(response, 503, "The workflow inspector is not running. The app may be restarting, or it may run no workflows.", { "content-type": "text/plain; charset=utf-8" });
918
- return;
919
- }
920
- const bodyless = request.method === "GET" || request.method === "HEAD";
921
- const site = request.headers["sec-fetch-site"];
922
- const origin = request.headers.origin;
923
- if (!bodyless && (site !== void 0 && site !== "same-origin" || origin !== void 0 && origin !== `http://${request.headers.host}`)) {
924
- send(response, 403, "Forbidden");
925
- return;
926
- }
927
- const headers = new Headers();
928
- for (const [name, value] of Object.entries(request.headers)) {
929
- if (value === void 0 || NOT_FORWARDED.has(name)) continue;
930
- if (name.startsWith("sec-")) continue;
931
- headers.set(name, Array.isArray(value) ? value.join(", ") : value);
932
- }
933
- headers.set(INSPECTOR_TOKEN_HEADER, target.token);
934
- const abort = new AbortController();
935
- response.on("close", () => abort.abort());
936
- try {
937
- const upstream = await fetch(`http://127.0.0.1:${target.port}${url.pathname}${url.search}`, {
938
- method: request.method,
939
- headers,
940
- redirect: "manual",
941
- signal: abort.signal,
942
- ...bodyless ? {} : {
943
- body: Readable.toWeb(request),
944
- duplex: "half"
945
- }
946
- });
947
- const returned = {};
948
- upstream.headers.forEach((value, name) => {
949
- if (!NOT_RETURNED.has(name)) returned[name] = value;
950
- });
951
- response.writeHead(upstream.status, returned);
952
- if (!upstream.body || request.method === "HEAD") {
953
- response.end();
954
- return;
955
- }
956
- await pipeline(Readable.fromWeb(upstream.body), response);
957
- } catch {
958
- if (response.headersSent) response.destroy();
959
- else send(response, 502, "Could not reach the workflow inspector.");
976
+ #route(from, href) {
977
+ const hashAt = href.indexOf("#");
978
+ const hash = hashAt >= 0 ? href.slice(hashAt) : "";
979
+ const target = (hashAt >= 0 ? href.slice(0, hashAt) : href).split("?")[0] ?? "";
980
+ const route = (slug) => `#/docs${slug ? `/${slug}` : ""}${hash}`;
981
+ if (/^[a-z][a-z\d+.-]*:/i.test(href) || href.startsWith("#") || !target) return void 0;
982
+ if (target.startsWith("/")) {
983
+ const slug = target.replace(/^\/+|\/+$/g, "");
984
+ return this.#pages.has(slug) ? route(slug) : void 0;
960
985
  }
986
+ const resolved = resolveInside(from, target);
987
+ if (resolved === void 0) return void 0;
988
+ const known = this.#byPath.get(resolved);
989
+ if (known !== void 0) return route(known);
990
+ if (!PAGE_EXTENSIONS.has(extname(resolved))) return void 0;
991
+ return route(resolved.slice(0, -extname(resolved).length).replace(/(^|\/)index$/, ""));
961
992
  }
962
- async function proxy(request, response, url) {
963
- const site = request.headers["sec-fetch-site"];
964
- const origin = request.headers.origin;
965
- if (site !== void 0 && site !== "same-origin" || origin !== void 0 && origin !== `http://${request.headers.host}`) {
966
- send(response, 403, "Forbidden");
967
- return;
968
- }
969
- let target;
970
- try {
971
- target = new URL(url.searchParams.get("url") ?? "");
972
- } catch {}
973
- const appUrl = options.store.apiSnapshot()?.appUrl;
974
- if (!target || !appUrl || target.origin !== new URL(appUrl).origin) {
975
- send(response, 403, "Only the app shown in the dashboard can be reached.");
976
- return;
977
- }
978
- const body = await readBytes(request, MAX_PROXY_BYTES);
979
- if (!body) {
980
- send(response, 413, "Payload too large");
981
- return;
982
- }
983
- const headers = new Headers();
984
- for (const [name, value] of Object.entries(request.headers)) {
985
- if (value === void 0 || NOT_FORWARDED.has(name)) continue;
986
- if (name.startsWith("sec-")) continue;
987
- headers.set(name, Array.isArray(value) ? value.join(", ") : value);
988
- }
989
- const cookie = url.searchParams.get("cookie");
990
- if (cookie) headers.set("cookie", cookie);
991
- const bodyless = request.method === "GET" || request.method === "HEAD";
993
+ async search(query) {
994
+ if (!query.trim()) return [];
995
+ this.#search ??= this.#buildSearch();
996
+ return (await this.#search).search(query);
997
+ }
998
+ async #buildSearch() {
999
+ const { plugins, createSearchAPI } = this.#fumadocs;
1000
+ const api = createSearchAPI("advanced", { indexes: [...this.#pages.entries()].map(([slug, file]) => ({
1001
+ id: file.path,
1002
+ title: file.title,
1003
+ description: file.description,
1004
+ url: `/${slug}`,
1005
+ structuredData: plugins.structure(file.content)
1006
+ })) });
1007
+ return { async search(query) {
1008
+ return await api.search(query);
1009
+ } };
1010
+ }
1011
+ /** A file from the docs folder that a page can show, such as an image. */
1012
+ async file(relativePath) {
1013
+ const type = IMAGE_TYPES[extname(relativePath).toLowerCase()];
1014
+ if (!type) return void 0;
1015
+ const absolute = resolve(this.#root, relativePath);
1016
+ if (absolute !== this.#root && !absolute.startsWith(this.#root + sep)) return void 0;
992
1017
  try {
993
- const upstream = await fetch(target, {
994
- method: request.method,
995
- headers,
996
- body: bodyless ? void 0 : body,
997
- redirect: "manual"
998
- });
999
- const returned = {};
1000
- upstream.headers.forEach((value, name) => {
1001
- if (!NOT_RETURNED.has(name)) returned[name] = value;
1002
- });
1003
- send(response, upstream.status, new Uint8Array(await upstream.arrayBuffer()), returned);
1018
+ if (!(await stat(absolute)).isFile()) return void 0;
1019
+ return {
1020
+ body: new Uint8Array(await readFile(absolute)),
1021
+ type
1022
+ };
1004
1023
  } catch {
1005
- send(response, 502, "Could not reach the app.");
1024
+ return;
1006
1025
  }
1007
1026
  }
1008
- function eventStream(request, response) {
1009
- response.writeHead(200, {
1010
- "content-type": "text/event-stream",
1011
- "cache-control": "no-cache",
1012
- connection: "keep-alive",
1013
- "x-accel-buffering": "no"
1014
- });
1015
- const write = (chunk) => {
1016
- if (response.writableEnded || response.destroyed) return;
1017
- response.write(chunk);
1018
- };
1019
- write(`event: snapshot\ndata: ${JSON.stringify(snapshot())}\n\n`);
1020
- const unsubscribe = options.store.subscribe((event) => write(`event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`));
1021
- const keepalive = setInterval(() => write(": keepalive\n\n"), KEEPALIVE_MS);
1022
- request.on("close", () => {
1023
- clearInterval(keepalive);
1024
- unsubscribe();
1025
- });
1027
+ #componentsPath() {
1028
+ const { components } = this.#documentation;
1029
+ return components ? resolve(this.#base, components) : void 0;
1026
1030
  }
1027
- return new Promise((resolve, reject) => {
1028
- server.once("error", (error) => {
1029
- reject(new Error(production ? `Brick: dashboard port ${options.port} is unavailable. Set dashboard.port in brick() to another.` : `Brick: dashboard port ${options.port} is unavailable. Use --dashboard-port <number> or --no-dashboard.`, { cause: error }));
1030
- });
1031
- server.listen(options.port, host, () => {
1032
- const address = server.address();
1033
- const port = typeof address === "object" && address !== null ? address.port : options.port;
1034
- allowedHosts = /* @__PURE__ */ new Set([
1035
- `127.0.0.1:${port}`,
1036
- `localhost:${port}`,
1037
- `[::1]:${port}`
1038
- ]);
1039
- resolve({
1040
- port,
1041
- stop() {
1042
- server.close();
1043
- server.closeAllConnections();
1044
- }
1045
- });
1031
+ /** The project's components as one browser module; undefined when it has none. */
1032
+ async components() {
1033
+ const entry = this.#componentsPath();
1034
+ return entry ? bundleComponents(entry) : void 0;
1035
+ }
1036
+ close() {
1037
+ this.#closed = true;
1038
+ clearTimeout(this.#timer);
1039
+ for (const watcher of this.#watchers) watcher.close();
1040
+ this.#watchers.length = 0;
1041
+ this.#listeners.clear();
1042
+ }
1043
+ };
1044
+ const SHARED = [
1045
+ "react",
1046
+ "react/jsx-runtime",
1047
+ "react/jsx-dev-runtime",
1048
+ "react-dom",
1049
+ "react-dom/client",
1050
+ "@brickkit/cli/dashboard"
1051
+ ];
1052
+ /** Bundle a module of React components for the dashboard to import. */
1053
+ async function bundleComponents(entry) {
1054
+ if (typeof Bun !== "undefined") {
1055
+ const result = await Bun.build({
1056
+ entrypoints: [entry],
1057
+ target: "browser",
1058
+ format: "esm",
1059
+ external: SHARED,
1060
+ minify: false,
1061
+ throw: false
1046
1062
  });
1063
+ if (!result.success) throw new Error(result.logs.map((log) => log.message).join("\n"));
1064
+ return (result.outputs.find((item) => item.kind === "entry-point") ?? result.outputs[0]).text();
1065
+ }
1066
+ const { build } = await import("vite");
1067
+ const output = await build({
1068
+ configFile: false,
1069
+ logLevel: "silent",
1070
+ root: dirname(entry),
1071
+ oxc: { jsx: { runtime: "automatic" } },
1072
+ esbuild: { jsx: "automatic" },
1073
+ define: { "process.env.NODE_ENV": "\"development\"" },
1074
+ build: {
1075
+ write: false,
1076
+ minify: false,
1077
+ lib: {
1078
+ entry,
1079
+ formats: ["es"],
1080
+ fileName: "components"
1081
+ },
1082
+ rollupOptions: { external: SHARED }
1083
+ }
1047
1084
  });
1085
+ const bundles = Array.isArray(output) ? output : [output];
1086
+ for (const bundle of bundles) {
1087
+ const chunk = ("output" in bundle ? bundle.output : []).find((item) => item.type === "chunk" && item.isEntry);
1088
+ if (chunk && "code" in chunk) return chunk.code;
1089
+ }
1090
+ throw new Error("Brick: the docs components module produced no output.");
1048
1091
  }
1049
- /** The whole request body, or undefined when it is larger than `limit`. */
1050
- function readBytes(request, limit) {
1051
- return new Promise((resolve) => {
1052
- const chunks = [];
1053
- let size = 0;
1054
- request.on("data", (chunk) => {
1055
- size += chunk.length;
1056
- if (size > limit) {
1057
- resolve(void 0);
1058
- request.destroy();
1059
- return;
1060
- }
1061
- chunks.push(chunk);
1062
- });
1063
- request.on("end", () => resolve(new Uint8Array(Buffer.concat(chunks))));
1064
- request.on("error", () => resolve(void 0));
1065
- });
1092
+ /** Flatten what MDX gives for a heading to text. */
1093
+ function plainText(value) {
1094
+ if (typeof value === "string") return value;
1095
+ if (Array.isArray(value)) return value.map(plainText).join("");
1096
+ if (value && typeof value === "object") {
1097
+ const node = value;
1098
+ if (typeof node.value === "string") return node.value;
1099
+ return plainText(node.props?.children ?? node.children);
1100
+ }
1101
+ return "";
1066
1102
  }
1067
- function history(store, pathname, params, response) {
1068
- const json = (body) => send(response, 200, JSON.stringify(body), { "content-type": "application/json" });
1103
+ /** The page tree as plain data for the dashboard; icons and links are left out. */
1104
+ function simplify(tree) {
1105
+ const text = (value) => typeof value === "string" ? value : plainText(value);
1106
+ const convert = (node) => {
1107
+ if (node.type === "page" && node.url !== void 0) return {
1108
+ type: "page",
1109
+ name: text(node.name),
1110
+ url: node.url,
1111
+ ...typeof node.description === "string" ? { description: node.description } : {}
1112
+ };
1113
+ if (node.type === "separator") return {
1114
+ type: "separator",
1115
+ ...node.name ? { name: text(node.name) } : {}
1116
+ };
1117
+ if (node.type === "folder") return {
1118
+ type: "folder",
1119
+ name: text(node.name),
1120
+ ...node.index?.url !== void 0 ? { index: {
1121
+ name: text(node.index.name),
1122
+ url: node.index.url
1123
+ } } : {},
1124
+ children: (node.children ?? []).flatMap((child) => convert(child) ?? []),
1125
+ ...node.defaultOpen ? { defaultOpen: true } : {}
1126
+ };
1127
+ };
1128
+ return {
1129
+ name: text(tree?.name) || "Docs",
1130
+ children: (tree?.children ?? []).flatMap((child) => convert(child) ?? [])
1131
+ };
1132
+ }
1133
+ /** Open a docs folder; says what is missing when it cannot be shown. */
1134
+ async function openDocs(options) {
1135
+ const fumadocs = await loadFumadocs();
1136
+ if (Array.isArray(fumadocs)) return {
1137
+ status: "missing",
1138
+ packages: fumadocs
1139
+ };
1140
+ const docs = new DevDocs(options.base, options.documentation, fumadocs, options.warn);
1069
1141
  try {
1070
- if (pathname === "/api/history") return json(store.info());
1071
- if (pathname === "/api/history/summary") return json(store.summary(parseHistoryQuery(params)));
1072
- if (pathname === "/api/history/traces") return json(store.traces(parseHistoryQuery(params)));
1073
- if (pathname === "/api/history/facets") return json(store.facets(parseHistoryQuery(params)));
1074
- if (pathname === "/api/history/volume") return json(store.volume(parseHistoryQuery(params)));
1075
- if (pathname === "/api/history/export") return send(response, 200, store.exportCsv(parseHistoryQuery(params)), {
1076
- "content-type": "text/csv; charset=utf-8",
1077
- "content-disposition": "attachment; filename=\"brick-requests.csv\"",
1078
- "cache-control": "no-store"
1142
+ await docs.refresh();
1143
+ } catch (error) {
1144
+ docs.close();
1145
+ const root = resolve(options.base, options.documentation.dir);
1146
+ return {
1147
+ status: "error",
1148
+ message: error.code === "ENOENT" ? `The docs folder ${root} does not exist.` : errorMessage(error)
1149
+ };
1150
+ }
1151
+ docs.watch();
1152
+ return {
1153
+ status: "ready",
1154
+ docs
1155
+ };
1156
+ }
1157
+ /**
1158
+ * The docs of whichever app is running: opened when the app says where they
1159
+ * are, replaced when that changes, and closed when it stops asking for them.
1160
+ */
1161
+ var DocsHost = class {
1162
+ #store;
1163
+ #warn;
1164
+ #docs;
1165
+ #stopListening;
1166
+ #key;
1167
+ #pending = Promise.resolve();
1168
+ constructor(store, warn) {
1169
+ this.#store = store;
1170
+ this.#warn = warn;
1171
+ }
1172
+ get current() {
1173
+ return this.#docs;
1174
+ }
1175
+ /**
1176
+ * Follow the app's `documentation`. Relative paths in it start at `base`, the
1177
+ * folder of the app entry, as they read in the file that sets them.
1178
+ */
1179
+ configure(base, documentation) {
1180
+ this.#pending = this.#pending.then(() => this.#configure(base, documentation));
1181
+ return this.#pending;
1182
+ }
1183
+ async #configure(base, documentation) {
1184
+ const key = JSON.stringify([base, documentation ?? null]);
1185
+ if (key === this.#key) return;
1186
+ this.#key = key;
1187
+ this.#release();
1188
+ if (!documentation) {
1189
+ this.#store.setDocs(null);
1190
+ return;
1191
+ }
1192
+ const opened = await openDocs({
1193
+ base,
1194
+ documentation,
1195
+ warn: this.#warn
1079
1196
  });
1080
- if (pathname.startsWith("/api/history/traces/")) {
1081
- const trace = store.trace(decodeURIComponent(pathname.slice(20)));
1082
- if (trace) return json(trace);
1197
+ if (opened.status !== "ready") {
1198
+ const message = opened.status === "missing" ? `The docs need ${opened.packages.join(" and ")}. Install with: bun add -d ${opened.packages.join(" ")}` : opened.message;
1199
+ this.#warn(`[Brick-TS] Docs are off. ${message}`);
1200
+ this.#store.setDocs({
1201
+ revision: 1,
1202
+ status: opened.status,
1203
+ title: "Docs",
1204
+ components: false,
1205
+ message,
1206
+ ...opened.status === "missing" ? { packages: opened.packages } : {}
1207
+ });
1208
+ return;
1083
1209
  }
1084
- send(response, 404, "Not found");
1085
- } catch {
1086
- send(response, 500, "History query failed");
1210
+ this.#docs = opened.docs;
1211
+ this.#stopListening = opened.docs.onChange(() => this.#store.setDocs(opened.docs.snapshot()));
1212
+ this.#store.setDocs(opened.docs.snapshot());
1213
+ }
1214
+ #release() {
1215
+ this.#stopListening?.();
1216
+ this.#stopListening = void 0;
1217
+ this.#docs?.close();
1218
+ this.#docs = void 0;
1219
+ }
1220
+ close() {
1221
+ this.#key = void 0;
1222
+ this.#release();
1087
1223
  }
1088
- }
1089
- const ASSET_TYPES = {
1090
- ".js": "text/javascript; charset=utf-8",
1091
- ".css": "text/css; charset=utf-8",
1092
- ".woff2": "font/woff2"
1093
1224
  };
1225
+ // src/dashboard-extension.ts
1226
+ /** The colour tokens of `dashboard/theme.css`; a test keeps the two in step. */
1227
+ const THEME_TOKENS = [
1228
+ "background",
1229
+ "foreground",
1230
+ "card",
1231
+ "card-foreground",
1232
+ "popover",
1233
+ "popover-foreground",
1234
+ "primary",
1235
+ "primary-foreground",
1236
+ "secondary",
1237
+ "secondary-foreground",
1238
+ "muted",
1239
+ "muted-foreground",
1240
+ "accent",
1241
+ "accent-foreground",
1242
+ "destructive",
1243
+ "destructive-foreground",
1244
+ "positive",
1245
+ "border",
1246
+ "input",
1247
+ "ring",
1248
+ "chart-1",
1249
+ "chart-2",
1250
+ "chart-3",
1251
+ "chart-4",
1252
+ "chart-5",
1253
+ "span-request",
1254
+ "span-action",
1255
+ "span-rpc",
1256
+ "span-sql",
1257
+ "span-event",
1258
+ "span-other"
1259
+ ];
1260
+ const THEME_KEYS = /* @__PURE__ */ new Set([
1261
+ "light",
1262
+ "dark",
1263
+ "radius",
1264
+ "fonts"
1265
+ ]);
1266
+ const FONT_KEYS = /* @__PURE__ */ new Set(["sans", "mono"]);
1267
+ const TOKENS = new Set(THEME_TOKENS);
1268
+ /** A value that cannot close the rule it sits in. */
1269
+ function cssValue(where, value) {
1270
+ if (typeof value !== "string" || !value.trim() || /[;{}<>\\]/.test(value)) throw new Error(`Brick: dashboard.theme.${where} must be a CSS value without ; { } < > or \\.`);
1271
+ return value.trim();
1272
+ }
1273
+ /**
1274
+ * The stylesheet for a theme, loaded after the dashboard's own; empty when the
1275
+ * theme sets nothing. Throws on a token name theme.css does not have.
1276
+ */
1277
+ function themeCss(theme) {
1278
+ if (!theme) return "";
1279
+ for (const key of Object.keys(theme)) if (!THEME_KEYS.has(key)) throw new Error(`Brick: dashboard.theme has no "${key}". It takes light, dark, radius and fonts.`);
1280
+ const rules = [];
1281
+ const root = [];
1282
+ if (theme.radius !== void 0) root.push(`--radius: ${cssValue("radius", theme.radius)};`);
1283
+ for (const [name, value] of Object.entries(theme.fonts ?? {})) {
1284
+ if (!FONT_KEYS.has(name)) throw new Error(`Brick: dashboard.theme.fonts has no "${name}". It takes sans and mono.`);
1285
+ root.push(`--font-${name}: ${cssValue(`fonts.${name}`, value)};`);
1286
+ }
1287
+ if (root.length) rules.push(`:root {\n ${root.join("\n ")}\n}`);
1288
+ for (const [mode, selector] of [["light", ":root:not(.dark)"], ["dark", ":root.dark"]]) {
1289
+ const tokens = theme[mode];
1290
+ if (!tokens) continue;
1291
+ const lines = Object.entries(tokens).map(([name, value]) => {
1292
+ if (!TOKENS.has(name)) throw new Error(`Brick: dashboard.theme.${mode} has no token "${name}". Tokens: ${THEME_TOKENS.join(", ")}.`);
1293
+ return `--${name}: ${cssValue(`${mode}.${name}`, value)};`;
1294
+ });
1295
+ if (lines.length) rules.push(`${selector} {\n ${lines.join("\n ")}\n}`);
1296
+ }
1297
+ return rules.length ? `${rules.join("\n")}\n` : "";
1298
+ }
1094
1299
  /** The built React app, next to `src/` in the repo and next to `dist/` when published. */
1095
1300
  function assetsDirectory() {
1096
1301
  for (const relative of ["../dashboard-dist/", "../../dashboard-dist/"]) {
@@ -1098,247 +1303,152 @@ function assetsDirectory() {
1098
1303
  if (existsSync(join(directory, "app.js"))) return directory;
1099
1304
  }
1100
1305
  }
1101
- function serveAsset(response, name) {
1102
- if (!/^[\w.-]+$/.test(name) || name.startsWith(".")) {
1103
- send(response, 404, "Not found");
1104
- return;
1105
- }
1106
- const directory = assetsDirectory();
1107
- if (!directory) {
1108
- send(response, 503, "Dashboard assets are missing. Build them with: bun run --filter @brickkit/cli build");
1109
- return;
1110
- }
1111
- readFile(join(directory, name)).then((body) => send(response, 200, body, {
1112
- "content-type": ASSET_TYPES[extname(name)] ?? "application/octet-stream",
1113
- "cache-control": "no-store"
1114
- }), () => send(response, 404, "Not found"));
1115
- }
1116
- function send(response, status, body, headers = { "content-type": "text/plain; charset=utf-8" }) {
1117
- response.writeHead(status, headers);
1118
- response.end(body);
1119
- }
1120
- //#endregion
1121
- //#region src/dev-docs.ts
1122
- const PACKAGES = ["fumadocs-core", "@mdx-js/mdx"];
1123
- const PAGE_EXTENSIONS = /* @__PURE__ */ new Set([".md", ".mdx"]);
1124
- const IMAGE_TYPES = {
1125
- ".png": "image/png",
1126
- ".jpg": "image/jpeg",
1127
- ".jpeg": "image/jpeg",
1128
- ".gif": "image/gif",
1129
- ".webp": "image/webp",
1130
- ".avif": "image/avif",
1131
- ".svg": "image/svg+xml",
1132
- ".ico": "image/x-icon"
1133
- };
1134
- const REFRESH_DELAY_MS = 100;
1135
- async function loadFumadocs() {
1136
- try {
1137
- const [source, matter, plugins, search, mdx] = await Promise.all([
1138
- import("fumadocs-core/source"),
1139
- import("fumadocs-core/content/md/frontmatter"),
1140
- import("fumadocs-core/mdx-plugins"),
1141
- import("fumadocs-core/search/server"),
1142
- import("@mdx-js/mdx")
1143
- ]);
1144
- return {
1145
- loader: source.loader,
1146
- frontmatter: matter.frontmatter,
1147
- plugins,
1148
- createSearchAPI: search.createSearchAPI,
1149
- compile: mdx.compile
1150
- };
1151
- } catch (error) {
1152
- if (error.code === "ERR_MODULE_NOT_FOUND" || /Cannot find (module|package)/.test(String(error?.message))) return [...PACKAGES];
1153
- throw error;
1154
- }
1155
- }
1156
- const humanize = (name) => {
1157
- const spaced = name.replace(/[-_]+/g, " ").trim();
1158
- return spaced.charAt(0).toUpperCase() + spaced.slice(1);
1159
- };
1160
- const H1 = /^#\s+(.+?)\s*#*\s*$/;
1306
+ let warnedTailwind = false;
1161
1307
  /**
1162
- * The first `# Heading` outside code fences: its text, and the content without
1163
- * it. The page shows its title above the content, so a heading that only
1164
- * repeats the title would appear twice.
1308
+ * Tailwind for the classes in the extension's bundle, compiled against the
1309
+ * dashboard's theme.css so `bg-primary` and the rest match. Only utilities are
1310
+ * emitted: the dashboard's stylesheet already has the base styles and tokens.
1311
+ * Tailwind is an optional peer, found from the project first.
1165
1312
  */
1166
- function firstHeading(content) {
1167
- const lines = content.split("\n");
1168
- let fenced = false;
1169
- let seenText = false;
1170
- for (const [index, line] of lines.entries()) if (/^\s*(```|~~~)/.test(line)) {
1171
- fenced = !fenced;
1172
- seenText = true;
1173
- } else if (!fenced) {
1174
- const match = H1.exec(line);
1175
- if (match) {
1176
- const rest = [...lines.slice(0, index), ...lines.slice(index + 1)];
1177
- if (rest[index]?.trim() === "") rest.splice(index, 1);
1313
+ async function extensionCss(entry, js, warn) {
1314
+ let tailwind;
1315
+ let main;
1316
+ for (const from of [entry, fileURLToPath(import.meta.url)]) try {
1317
+ const require = createRequire(from);
1318
+ tailwind = require.resolve("tailwindcss/package.json");
1319
+ main = require.resolve("tailwindcss");
1320
+ break;
1321
+ } catch {}
1322
+ const assets = assetsDirectory();
1323
+ const themeFile = assets ? join(assets, "theme.css") : fileURLToPath(new URL("../dashboard/theme.css", import.meta.url));
1324
+ if (!tailwind || !main) {
1325
+ if (!warnedTailwind) warn("[Brick-TS] tailwindcss is not installed, so the dashboard extension's own Tailwind classes are not compiled. The UI kit is styled either way.");
1326
+ warnedTailwind = true;
1327
+ return "";
1328
+ }
1329
+ const root = dirname(tailwind);
1330
+ const { compile } = await import(pathToFileURL(main).href);
1331
+ const compiler = await compile(`@layer theme, base, components, utilities;
1332
+ @import "tailwindcss/theme.css" theme(reference inline);
1333
+ @import "tailwindcss/utilities.css" layer(utilities);
1334
+ @reference "brick/theme.css";
1335
+ `, {
1336
+ base: root,
1337
+ async loadStylesheet(id) {
1338
+ const path = id === "brick/theme.css" ? themeFile : join(root, id.replace(/^tailwindcss\//, ""));
1178
1339
  return {
1179
- text: match[1],
1180
- rest: rest.join("\n"),
1181
- leading: !seenText
1340
+ path,
1341
+ base: dirname(path),
1342
+ content: await readFile(path, "utf8")
1182
1343
  };
1183
1344
  }
1184
- if (line.trim() !== "") seenText = true;
1185
- }
1345
+ });
1346
+ const candidates = new Set(js.split(/[\s"'`]+/).filter(Boolean));
1347
+ const css = compiler.build([...candidates]);
1348
+ return /\{/.test(css) ? css : "";
1186
1349
  }
1187
- async function scan(root, fumadocs, warn) {
1188
- const pages = [];
1189
- const metas = [];
1190
- async function visit(directory) {
1191
- for (const entry of await readdir(directory, { withFileTypes: true })) {
1192
- if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
1193
- const absolute = join(directory, entry.name);
1194
- const path = relative(root, absolute).split(sep).join("/");
1195
- if (entry.isDirectory()) await visit(absolute);
1196
- else if (entry.name === "meta.json") try {
1197
- const data = JSON.parse(await readFile(absolute, "utf8"));
1198
- if (data && typeof data === "object") metas.push({
1199
- path,
1200
- data
1201
- });
1202
- } catch (error) {
1203
- warn(`[Brick-TS] Skipping docs ${path}: ${errorMessage(error)}`);
1204
- }
1205
- else if (PAGE_EXTENSIONS.has(extname(entry.name))) {
1206
- const text = await readFile(absolute, "utf8");
1207
- let data = {};
1208
- let content = text;
1209
- try {
1210
- const parsed = fumadocs.frontmatter(text);
1211
- data = parsed.data;
1212
- content = parsed.content;
1213
- } catch (error) {
1214
- warn(`[Brick-TS] Ignoring the frontmatter of docs ${path}: ${errorMessage(error)}`);
1215
- }
1216
- const name = basename(entry.name, extname(entry.name));
1217
- const heading = firstHeading(content);
1218
- const given = typeof data.title === "string" && data.title ? data.title : void 0;
1219
- const title = given ?? heading?.text ?? humanize(name === "index" ? basename(dirname(path)) || "Home" : name);
1220
- if (heading && (!given || heading.leading && heading.text === given)) content = heading.rest;
1221
- pages.push({
1222
- path,
1223
- absolute,
1224
- title,
1225
- description: typeof data.description === "string" ? data.description : void 0,
1226
- content,
1227
- data
1228
- });
1229
- }
1230
- }
1231
- }
1232
- await visit(root);
1350
+ /** Bundle the extension and its styles for the dashboard page. */
1351
+ async function buildDashboardExtension(entry, options = {}) {
1352
+ const js = await bundleComponents(entry);
1233
1353
  return {
1234
- pages,
1235
- metas
1354
+ js,
1355
+ css: await extensionCss(entry, js, options.warn ?? ((message) => console.warn(message)))
1236
1356
  };
1237
1357
  }
1238
- function errorMessage(error) {
1239
- return error instanceof Error ? error.message : String(error);
1240
- }
1241
- function walk(node, visit) {
1242
- visit(node);
1243
- for (const child of node.children ?? []) walk(child, visit);
1244
- }
1245
- /** Ways a link inside a page can point at another page or a local image. */
1246
- function resolveInside(from, href) {
1247
- if (/^[a-z][a-z\d+.-]*:/i.test(href) || href.startsWith("#")) return void 0;
1248
- if (href.startsWith("/")) return void 0;
1249
- const [target] = href.split(/[?#]/);
1250
- if (!target) return void 0;
1251
- const resolved = posix.normalize(posix.join(posix.dirname(from), target));
1252
- return resolved.startsWith("../") ? void 0 : resolved;
1358
+ /**
1359
+ * Write the app's extension and its plugins' into `outdir`, where `brick start`
1360
+ * can serve them: the app's alone as it is, or with plugins each part apart
1361
+ * and `extension.js` loading them, as `brick dev` serves them. Returns false
1362
+ * when there is none to write. A plugin's that fails to build throws.
1363
+ */
1364
+ async function writeDashboardExtension(entry, plugins, outdir) {
1365
+ const parts = [...entry ? [{
1366
+ name: "app",
1367
+ path: entry,
1368
+ plugin: false
1369
+ }] : [], ...[...pluginDashboards(plugins)].map(([path, name]) => ({
1370
+ name,
1371
+ path,
1372
+ plugin: true
1373
+ }))];
1374
+ if (!parts.length) return false;
1375
+ const built = await Promise.all(parts.map((part) => buildDashboardExtension(part.path).catch((error) => {
1376
+ if (!part.plugin) throw error;
1377
+ throw new Error(`Brick compiler: the dashboard extension of plugin ${part.name} failed to build: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
1378
+ })));
1379
+ await mkdir(outdir, { recursive: true });
1380
+ if (parts.length === 1 && entry) {
1381
+ await writeFile(join(outdir, "extension.js"), built[0].js);
1382
+ await writeFile(join(outdir, "extension.css"), built[0].css);
1383
+ return true;
1384
+ }
1385
+ for (const [index, part] of built.entries()) await writeFile(join(outdir, `extension-${index}.js`), part.js);
1386
+ await writeFile(join(outdir, "extension.js"), extensionLoader(parts.map((part, index) => ({
1387
+ name: part.name,
1388
+ src: `./extension-${index}.js`,
1389
+ plugin: part.plugin
1390
+ }))));
1391
+ await writeFile(join(outdir, "extension.css"), built.map((part) => part.css).join(""));
1392
+ return true;
1253
1393
  }
1254
1394
  /**
1255
- * The page tree and compiled pages of one docs folder. It watches the folder,
1256
- * so edits show in the dashboard as they are saved.
1395
+ * The extension as the dashboard serves it. From source it is built here, and
1396
+ * rebuilt as its folder changes when watching; from a `brick build` folder it
1397
+ * is read as it is. A failed build keeps the error to show on the page.
1257
1398
  */
1258
- var DevDocs = class {
1259
- #root;
1260
- #documentation;
1261
- /** Relative paths in `documentation` start here: the app entry's folder. */
1262
- #base;
1263
- #fumadocs;
1399
+ var DashboardExtensionHost = class {
1400
+ #path;
1264
1401
  #warn;
1265
1402
  #listeners = /* @__PURE__ */ new Set();
1266
- #watchers = [];
1267
- #loader;
1268
- #pages = /* @__PURE__ */ new Map();
1269
- #byPath = /* @__PURE__ */ new Map();
1270
- #compiled = /* @__PURE__ */ new Map();
1271
- #search;
1403
+ #watcher;
1272
1404
  #timer;
1273
- #refreshing = Promise.resolve();
1274
- #closed = false;
1275
- #title = "Docs";
1405
+ #pending = Promise.resolve();
1276
1406
  revision = 0;
1277
- constructor(base, documentation, fumadocs, warn) {
1278
- this.#base = base;
1279
- this.#documentation = documentation;
1280
- this.#root = resolve(base, documentation.dir);
1281
- this.#fumadocs = fumadocs;
1407
+ built;
1408
+ error;
1409
+ constructor(path, warn) {
1410
+ this.#path = resolve(path);
1282
1411
  this.#warn = warn;
1283
1412
  }
1284
- /** Read the folder again and tell listeners. */
1285
- async refresh() {
1286
- this.#refreshing = this.#refreshing.then(() => this.#scan());
1287
- await this.#refreshing;
1288
- }
1289
- async #scan() {
1290
- const { pages, metas } = await scan(this.#root, this.#fumadocs, this.#warn);
1291
- if (this.#closed) return;
1292
- const source = this.#fumadocs.loader({
1293
- baseUrl: "/",
1294
- source: { files: [...pages.map((page) => ({
1295
- type: "page",
1296
- path: page.path,
1297
- data: {
1298
- ...page.data,
1299
- title: page.title,
1300
- description: page.description
1413
+ load() {
1414
+ this.#pending = this.#pending.then(async () => {
1415
+ const before = JSON.stringify([this.built, this.error]);
1416
+ try {
1417
+ const prebuilt = join(this.#path, "extension.js");
1418
+ if (existsSync(prebuilt)) {
1419
+ const css = join(this.#path, "extension.css");
1420
+ const parts = {};
1421
+ for (const name of await readdir(this.#path)) if (/^extension-\d+\.js$/.test(name)) parts[name] = await readFile(join(this.#path, name), "utf8");
1422
+ this.built = {
1423
+ js: await readFile(prebuilt, "utf8"),
1424
+ css: existsSync(css) ? await readFile(css, "utf8") : "",
1425
+ parts
1426
+ };
1427
+ } else {
1428
+ if (!existsSync(this.#path)) throw new Error(`Brick: the dashboard extension ${this.#path} does not exist.`);
1429
+ this.built = await buildDashboardExtension(this.#path, { warn: this.#warn });
1301
1430
  }
1302
- })), ...metas.map((meta) => ({
1303
- type: "meta",
1304
- path: meta.path,
1305
- data: meta.data
1306
- }))] }
1431
+ this.error = void 0;
1432
+ } catch (error) {
1433
+ this.built = void 0;
1434
+ this.error = error instanceof Error ? error.message : String(error);
1435
+ this.#warn(`[Brick-TS] Dashboard extension: ${this.error}`);
1436
+ }
1437
+ if (JSON.stringify([this.built, this.error]) === before) return;
1438
+ this.revision++;
1439
+ for (const listener of this.#listeners) listener();
1307
1440
  });
1308
- this.#loader = source;
1309
- this.#pages = /* @__PURE__ */ new Map();
1310
- this.#byPath = /* @__PURE__ */ new Map();
1311
- for (const page of this.#loader.getPages()) {
1312
- const slug = page.slugs.join("/");
1313
- const file = pages.find((candidate) => candidate.path === page.path);
1314
- if (!file) continue;
1315
- this.#pages.set(slug, file);
1316
- this.#byPath.set(file.path, slug);
1317
- }
1318
- this.#compiled.clear();
1319
- this.#search = void 0;
1320
- const tree = this.#loader.getPageTree();
1321
- this.#title = typeof tree.name === "string" ? tree.name : "Docs";
1322
- this.revision++;
1323
- for (const listener of this.#listeners) listener();
1441
+ return this.#pending;
1324
1442
  }
1325
- /** Start watching the folder, and the project's components module. */
1443
+ /** Rebuild when a file in the extension's folder changes. */
1326
1444
  watch() {
1327
- const changed = () => {
1328
- clearTimeout(this.#timer);
1329
- this.#timer = setTimeout(() => {
1330
- this.refresh().catch((error) => this.#warn(`[Brick-TS] Docs: ${errorMessage(error)}`));
1331
- }, REFRESH_DELAY_MS);
1332
- };
1333
- const folders = [this.#root];
1334
- if (this.#documentation.components) folders.push(dirname(this.#componentsPath()));
1335
- for (const [index, folder] of folders.entries()) try {
1336
- this.#watchers.push(watch(folder, { recursive: index === 0 }, () => changed()));
1337
- } catch {
1338
- try {
1339
- this.#watchers.push(watch(folder, () => changed()));
1340
- } catch {}
1341
- }
1445
+ try {
1446
+ this.#watcher = watch(dirname(this.#path), { recursive: true }, (_event, file) => {
1447
+ if (file && /(^|[\\/])(node_modules|\.)/.test(file)) return;
1448
+ clearTimeout(this.#timer);
1449
+ this.#timer = setTimeout(() => void this.load(), 100);
1450
+ });
1451
+ } catch {}
1342
1452
  }
1343
1453
  onChange(listener) {
1344
1454
  this.#listeners.add(listener);
@@ -1346,352 +1456,688 @@ var DevDocs = class {
1346
1456
  this.#listeners.delete(listener);
1347
1457
  };
1348
1458
  }
1349
- snapshot() {
1350
- return {
1351
- revision: this.revision,
1352
- status: "ready",
1353
- title: this.#title,
1354
- components: Boolean(this.#documentation.components)
1355
- };
1459
+ close() {
1460
+ clearTimeout(this.#timer);
1461
+ this.#watcher?.close();
1462
+ this.#listeners.clear();
1356
1463
  }
1357
- info() {
1464
+ };
1465
+ /** The plugins' extensions by path, each once, in install order. */
1466
+ function pluginDashboards(plugins) {
1467
+ const wanted = /* @__PURE__ */ new Map();
1468
+ for (const plugin of plugins) if (plugin.dashboard && !wanted.has(resolve(plugin.dashboard))) wanted.set(resolve(plugin.dashboard), plugin.name);
1469
+ return wanted;
1470
+ }
1471
+ /**
1472
+ * The module the page loads when several extensions take part: it imports
1473
+ * each one apart, so one that throws leaves the others, and merges them. The
1474
+ * app's own comes first and keeps its slots; pages whose id is taken are
1475
+ * skipped; roots nest in order; a plugin's pages without a place go under a
1476
+ * section named after it.
1477
+ */
1478
+ function extensionLoader(parts) {
1479
+ return `const parts = ${JSON.stringify(parts)};
1480
+ const loaded = await Promise.allSettled(parts.map((part) => import(part.src)));
1481
+ const merged = { pages: [], sidebar: [], slots: {} };
1482
+ const roots = [];
1483
+ loaded.forEach((result, index) => {
1484
+ const { name, plugin } = parts[index];
1485
+ const extension = result.status === "fulfilled" ? result.value.default : undefined;
1486
+ if (!extension || typeof extension !== "object") {
1487
+ console.error("[Brick dashboard] Extension " + name + " failed to load:", result.status === "rejected" ? result.reason : "it must default-export defineDashboard({ ... })");
1488
+ return;
1489
+ }
1490
+ for (const page of extension.pages ?? []) {
1491
+ if (merged.pages.some((item) => item.id === page.id)) {
1492
+ console.error("[Brick dashboard] Extension " + name + ": page id " + page.id + " is taken; skipped.");
1493
+ continue;
1494
+ }
1495
+ merged.pages.push(plugin && !page.after && !page.section ? { ...page, section: name } : page);
1496
+ }
1497
+ merged.sidebar.push(...(extension.sidebar ?? []));
1498
+ for (const [slot, value] of Object.entries(extension.slots ?? {})) {
1499
+ if (slot === "request.drawer.tabs") merged.slots[slot] = [...(merged.slots[slot] ?? []), ...value];
1500
+ else if (!(slot in merged.slots)) merged.slots[slot] = value;
1501
+ }
1502
+ if (extension.root) roots.push(extension.root);
1503
+ });
1504
+ if (roots.length) {
1505
+ const { createElement } = await import("react");
1506
+ merged.root = ({ children }) => roots.reduceRight((inner, Root) => createElement(Root, null, inner), children);
1507
+ }
1508
+ export default merged;
1509
+ `;
1510
+ }
1511
+ /**
1512
+ * The app's extension and those of its plugins, served as one. With only the
1513
+ * app's, it is served as it is; with plugins, each is built apart (a failed
1514
+ * build leaves the others) and `extension.js` loads them all.
1515
+ */
1516
+ var DashboardExtensions = class {
1517
+ #warn;
1518
+ #listeners = /* @__PURE__ */ new Set();
1519
+ #parts = [];
1520
+ #own;
1521
+ revision = 0;
1522
+ constructor(path, warn) {
1523
+ this.#warn = warn;
1524
+ this.#own = path !== void 0;
1525
+ if (path) this.#add("app", path);
1526
+ }
1527
+ #add(name, path) {
1528
+ const host = new DashboardExtensionHost(path, this.#warn);
1529
+ host.onChange(() => this.#changed());
1530
+ this.#parts.push({
1531
+ name,
1532
+ path: resolve(path),
1533
+ host
1534
+ });
1535
+ return host;
1536
+ }
1537
+ #changed() {
1538
+ this.revision++;
1539
+ for (const listener of this.#listeners) listener();
1540
+ }
1541
+ /** Whether any extension takes part. */
1542
+ get active() {
1543
+ return this.#parts.length > 0;
1544
+ }
1545
+ get built() {
1546
+ const built = this.#parts.filter((part) => part.host.built);
1547
+ if (!built.length) return void 0;
1548
+ if (this.#own && this.#parts.length === 1) return built[0].host.built;
1358
1549
  return {
1359
- tree: simplify(this.#loader?.getPageTree()),
1360
- components: Boolean(this.#documentation.components),
1361
- revision: this.revision
1550
+ js: extensionLoader(this.#parts.flatMap((part, index) => part.host.built ? [{
1551
+ name: part.name,
1552
+ src: `./extension-${index}.js?v=${this.revision}`,
1553
+ plugin: !(this.#own && index === 0)
1554
+ }] : [])),
1555
+ css: built.map((part) => part.host.built.css).join("")
1362
1556
  };
1363
1557
  }
1364
- /** Compile one page; undefined when there is no such page. */
1365
- async page(slugs) {
1366
- const key = slugs.join("/");
1367
- const file = this.#pages.get(key);
1368
- if (!file) return void 0;
1369
- const cached = this.#compiled.get(key);
1370
- if (cached) return cached;
1371
- const page = await this.#compile(file, slugs);
1372
- if (this.#pages.get(key) === file) this.#compiled.set(key, page);
1373
- return page;
1558
+ get error() {
1559
+ const errors = this.#parts.flatMap((part) => part.host.error ? [this.#own && this.#parts.length === 1 ? part.host.error : `${part.name}: ${part.host.error}`] : []);
1560
+ return errors.length ? errors.join("\n") : void 0;
1561
+ }
1562
+ /** A file under `/assets/` this serves, or undefined. */
1563
+ asset(name) {
1564
+ if (name === "extension.js") return this.built?.js;
1565
+ if (name === "extension.css") return this.built?.css;
1566
+ const match = /^extension-(\d+)\.js$/.exec(name);
1567
+ if (!match) return void 0;
1568
+ if (this.#own && this.#parts.length === 1) return this.#parts[0].host.built?.parts?.[name];
1569
+ return this.#parts[Number(match[1])]?.host.built?.js;
1570
+ }
1571
+ /** Follow the app's plugins: build the extensions they ship, drop the rest. */
1572
+ async setPlugins(plugins) {
1573
+ if (this.#own && existsSync(join(this.#parts[0].path, "extension.js"))) return;
1574
+ const wanted = pluginDashboards(plugins);
1575
+ const start = this.#own ? 1 : 0;
1576
+ const current = this.#parts.slice(start);
1577
+ if (current.length === wanted.size && current.every((part) => wanted.get(part.path) === part.name)) return;
1578
+ for (const part of current) part.host.close();
1579
+ this.#parts.splice(start);
1580
+ const loads = [...wanted].map(([path, name]) => this.#add(name, path).load());
1581
+ await Promise.all(loads);
1582
+ this.#changed();
1583
+ }
1584
+ load() {
1585
+ return Promise.all(this.#parts.map((part) => part.host.load())).then(() => void 0);
1586
+ }
1587
+ /** Rebuild the app's own as its folder changes; plugins' are packages. */
1588
+ watch() {
1589
+ if (this.#own) this.#parts[0].host.watch();
1374
1590
  }
1375
- async #compile(file, slugs) {
1376
- const { plugins, compile } = this.#fumadocs;
1377
- const base = {
1378
- title: file.title,
1379
- description: file.description,
1380
- path: file.path,
1381
- slugs
1591
+ onChange(listener) {
1592
+ this.#listeners.add(listener);
1593
+ return () => {
1594
+ this.#listeners.delete(listener);
1382
1595
  };
1383
- try {
1384
- const result = await compile({
1385
- path: file.absolute,
1386
- value: file.content
1387
- }, {
1388
- outputFormat: "function-body",
1389
- development: false,
1390
- remarkPlugins: [
1391
- plugins.remarkGfm,
1392
- plugins.remarkHeading,
1393
- plugins.remarkCodeTab,
1394
- plugins.remarkNpm,
1395
- plugins.remarkAdmonition,
1396
- () => (tree) => this.#rewriteLinks(tree, file.path)
1397
- ],
1398
- rehypePlugins: [plugins.rehypeCode]
1399
- });
1400
- const toc = result.data.toc ?? [];
1401
- return {
1402
- ...base,
1403
- toc: toc.map((item) => ({
1404
- title: plainText(item.title),
1405
- url: item.url,
1406
- depth: item.depth
1407
- })),
1408
- code: String(result)
1409
- };
1410
- } catch (error) {
1411
- return {
1412
- ...base,
1413
- toc: [],
1414
- code: "",
1415
- error: errorMessage(error)
1416
- };
1417
- }
1418
1596
  }
1419
- /**
1420
- * Links to other pages become dashboard routes, and local images are served
1421
- * from the docs folder, so a folder reads the same here as on a docs site.
1422
- * This covers markdown links and the `href` of components such as `<Card>`.
1423
- */
1424
- #rewriteLinks(tree, from) {
1425
- const file = (resolved) => `/api/docs/files/${resolved.split("/").map(encodeURIComponent).join("/")}`;
1426
- walk(tree, (node) => {
1427
- if (node.type === "link" && node.url !== void 0) node.url = this.#route(from, node.url) ?? node.url;
1428
- else if (node.type === "image" && node.url !== void 0) {
1429
- const resolved = resolveInside(from, node.url);
1430
- if (resolved !== void 0) node.url = file(resolved);
1431
- } else if (node.type === "mdxJsxFlowElement" || node.type === "mdxJsxTextElement") for (const attribute of node.attributes ?? []) {
1432
- if (attribute.type !== "mdxJsxAttribute") continue;
1433
- if (typeof attribute.value !== "string") continue;
1434
- if (attribute.name === "href") attribute.value = this.#route(from, attribute.value) ?? attribute.value;
1435
- else if (attribute.name === "src" && node.name === "img") {
1436
- const resolved = resolveInside(from, attribute.value);
1437
- if (resolved !== void 0) attribute.value = file(resolved);
1438
- }
1439
- }
1440
- });
1597
+ close() {
1598
+ for (const part of this.#parts) part.host.close();
1599
+ this.#listeners.clear();
1441
1600
  }
1442
- /**
1443
- * The dashboard route for a link to a page of these docs, or undefined for
1444
- * anything else (other sites, in-page anchors, files). A link to a page that
1445
- * does not exist still becomes a route, so it says "No such page" here
1446
- * instead of leaving the dashboard.
1447
- */
1448
- #route(from, href) {
1449
- const hashAt = href.indexOf("#");
1450
- const hash = hashAt >= 0 ? href.slice(hashAt) : "";
1451
- const target = (hashAt >= 0 ? href.slice(0, hashAt) : href).split("?")[0] ?? "";
1452
- const route = (slug) => `#/docs${slug ? `/${slug}` : ""}${hash}`;
1453
- if (/^[a-z][a-z\d+.-]*:/i.test(href) || href.startsWith("#") || !target) return void 0;
1454
- if (target.startsWith("/")) {
1455
- const slug = target.replace(/^\/+|\/+$/g, "");
1456
- return this.#pages.has(slug) ? route(slug) : void 0;
1457
- }
1458
- const resolved = resolveInside(from, target);
1459
- if (resolved === void 0) return void 0;
1460
- const known = this.#byPath.get(resolved);
1461
- if (known !== void 0) return route(known);
1462
- if (!PAGE_EXTENSIONS.has(extname(resolved))) return void 0;
1463
- return route(resolved.slice(0, -extname(resolved).length).replace(/(^|\/)index$/, ""));
1464
- }
1465
- async search(query) {
1466
- if (!query.trim()) return [];
1467
- this.#search ??= this.#buildSearch();
1468
- return (await this.#search).search(query);
1469
- }
1470
- async #buildSearch() {
1471
- const { plugins, createSearchAPI } = this.#fumadocs;
1472
- const api = createSearchAPI("advanced", { indexes: [...this.#pages.entries()].map(([slug, file]) => ({
1473
- id: file.path,
1474
- title: file.title,
1475
- description: file.description,
1476
- url: `/${slug}`,
1477
- structuredData: plugins.structure(file.content)
1478
- })) });
1479
- return { async search(query) {
1480
- return await api.search(query);
1481
- } };
1601
+ };
1602
+ // src/dev-dashboard.ts
1603
+ const DEFAULT_DASHBOARD_PORT = 9400;
1604
+ const KEEPALIVE_MS = 15e3;
1605
+ const MAX_INGEST_BYTES = 5242880;
1606
+ const MAX_PROXY_BYTES = 10485760;
1607
+ const NOT_FORWARDED = /* @__PURE__ */ new Set([
1608
+ "host",
1609
+ "connection",
1610
+ "keep-alive",
1611
+ "proxy-connection",
1612
+ "transfer-encoding",
1613
+ "te",
1614
+ "trailer",
1615
+ "upgrade",
1616
+ "content-length",
1617
+ "accept-encoding",
1618
+ "origin",
1619
+ "referer",
1620
+ "cookie"
1621
+ ]);
1622
+ const NOT_RETURNED = /* @__PURE__ */ new Set([
1623
+ "connection",
1624
+ "keep-alive",
1625
+ "transfer-encoding",
1626
+ "content-length",
1627
+ "content-encoding",
1628
+ "set-cookie"
1629
+ ]);
1630
+ /**
1631
+ * What a production dashboard may show: the shell and its assets, the live
1632
+ * state and its event stream, and stored history. Nothing that changes the app
1633
+ * or reaches into it (restart, the API proxy, ingest) and nothing from the
1634
+ * project's source (documentation, OpenAPI documents). With an extension, the
1635
+ * `/app` proxy its pages read the app through.
1636
+ */
1637
+ const isMonitoringRoute = (method, pathname, extension) => extension && isAppRoute(pathname) || method === "GET" && (pathname === "/" || pathname.startsWith("/assets/") || pathname === "/api/state" || pathname === "/api/events" || pathname.startsWith("/api/history"));
1638
+ /** `/app/*` reaches the app itself, for the extension's `useAppFetch`. */
1639
+ const APP_PATH = "/app";
1640
+ const isAppRoute = (pathname) => pathname === APP_PATH || pathname.startsWith(`${APP_PATH}/`);
1641
+ const PRODUCTION_HEADERS = {
1642
+ "x-content-type-options": "nosniff",
1643
+ "x-frame-options": "DENY",
1644
+ "referrer-policy": "no-referrer",
1645
+ "cross-origin-opener-policy": "same-origin",
1646
+ "cross-origin-resource-policy": "same-origin",
1647
+ "cache-control": "no-store",
1648
+ "content-security-policy": "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'"
1649
+ };
1650
+ /** How long `/_health` waits for the app before calling it down. */
1651
+ const PROBE_TIMEOUT_MS = 3e3;
1652
+ /**
1653
+ * Serve the dashboard, on loopback unless told otherwise. On loopback requests
1654
+ * must name a local host (blocks DNS rebinding), and restart requires a header
1655
+ * that cross-origin pages cannot send without a preflight. Elsewhere `auth` is
1656
+ * required and decides who gets in. Uses node:http, so it runs under Bun and
1657
+ * under Node (Vite's dev server runs under Node).
1658
+ */
1659
+ function startDevDashboard(options) {
1660
+ const host = options.host ?? "127.0.0.1";
1661
+ const loopback = isLoopbackHost(host);
1662
+ const production = options.mode === "production";
1663
+ if (!loopback && !options.auth) return Promise.reject(/* @__PURE__ */ new Error(`Brick: the dashboard would listen on ${host}, where others can reach it, so it needs access control. Set dashboard.auth with a token or an authorize function.`));
1664
+ let theme;
1665
+ try {
1666
+ theme = themeCss(options.dashboard?.theme);
1667
+ } catch (error) {
1668
+ return Promise.reject(error);
1482
1669
  }
1483
- /** A file from the docs folder that a page can show, such as an image. */
1484
- async file(relativePath) {
1485
- const type = IMAGE_TYPES[extname(relativePath).toLowerCase()];
1486
- if (!type) return void 0;
1487
- const absolute = resolve(this.#root, relativePath);
1488
- if (absolute !== this.#root && !absolute.startsWith(this.#root + sep)) return void 0;
1489
- try {
1490
- if (!(await stat(absolute)).isFile()) return void 0;
1491
- return {
1492
- body: new Uint8Array(await readFile(absolute)),
1493
- type
1494
- };
1495
- } catch {
1670
+ const extension = options.dashboard?.extension || !production || options.plugins?.some((plugin) => plugin.dashboard) ? new DashboardExtensions(options.dashboard?.extension, (message) => console.warn(message)) : void 0;
1671
+ const access = options.auth ? createAccess(options.auth, (error) => console.error("[Brick-TS] The dashboard sign-in check failed:", error)) : void 0;
1672
+ let allowedHosts = /* @__PURE__ */ new Set();
1673
+ const server = createServer((request, response) => {
1674
+ respond(request, response).catch((error) => {
1675
+ console.error("[Brick-TS] The dashboard failed to answer:", error);
1676
+ if (response.headersSent) response.end();
1677
+ else send(response, 500, "Server error");
1678
+ });
1679
+ });
1680
+ async function respond(request, response) {
1681
+ if (production) for (const [name, value] of Object.entries(PRODUCTION_HEADERS)) response.setHeader(name, value);
1682
+ if (loopback && !allowedHosts.has(request.headers.host ?? "")) {
1683
+ send(response, 403, "Forbidden");
1496
1684
  return;
1497
1685
  }
1686
+ const url = new URL(request.url ?? "/", "http://127.0.0.1");
1687
+ const { pathname } = url;
1688
+ if (pathname === "/_health" && (request.method === "GET" || request.method === "HEAD")) {
1689
+ await health(response);
1690
+ return;
1691
+ }
1692
+ if (access) {
1693
+ const decision = await access(request);
1694
+ if (!decision.allowed) {
1695
+ send(response, decision.status, decision.body, decision.headers);
1696
+ return;
1697
+ }
1698
+ }
1699
+ if (production && !isMonitoringRoute(request.method, pathname, Boolean(extension?.active))) {
1700
+ send(response, 404, "Not found");
1701
+ return;
1702
+ }
1703
+ handle(request, response, url);
1498
1704
  }
1499
- #componentsPath() {
1500
- const { components } = this.#documentation;
1501
- return components ? resolve(this.#base, components) : void 0;
1502
- }
1503
- /** The project's components as one browser module; undefined when it has none. */
1504
- async components() {
1505
- const entry = this.#componentsPath();
1506
- return entry ? bundleComponents(entry) : void 0;
1507
- }
1508
- close() {
1509
- this.#closed = true;
1510
- clearTimeout(this.#timer);
1511
- for (const watcher of this.#watchers) watcher.close();
1512
- this.#watchers.length = 0;
1513
- this.#listeners.clear();
1514
- }
1515
- };
1516
- const SHARED = [
1517
- "react",
1518
- "react/jsx-runtime",
1519
- "react/jsx-dev-runtime"
1520
- ];
1521
- /** Bundle a module of React components for the dashboard to import. */
1522
- async function bundleComponents(entry) {
1523
- if (typeof Bun !== "undefined") {
1524
- const result = await Bun.build({
1525
- entrypoints: [entry],
1526
- target: "browser",
1527
- format: "esm",
1528
- external: SHARED,
1529
- minify: false
1705
+ /** 200 while the app answers its own health check, 503 when it does not. */
1706
+ async function health(response) {
1707
+ const probe = options.probe;
1708
+ let up = true;
1709
+ if (probe) {
1710
+ let timer;
1711
+ up = await Promise.race([probe().catch(() => false), new Promise((resolve) => {
1712
+ timer = setTimeout(() => resolve(false), PROBE_TIMEOUT_MS);
1713
+ })]);
1714
+ clearTimeout(timer);
1715
+ }
1716
+ send(response, up ? 200 : 503, JSON.stringify({
1717
+ status: up ? "ok" : "degraded",
1718
+ ...probe ? { app: up ? "up" : "down" } : {}
1719
+ }), {
1720
+ "content-type": "application/json",
1721
+ "cache-control": "no-store"
1530
1722
  });
1531
- if (!result.success) throw new Error(result.logs.map((log) => log.message).join("\n"));
1532
- return result.outputs[0].text();
1533
1723
  }
1534
- const { build } = await import("vite");
1535
- const output = await build({
1536
- configFile: false,
1537
- logLevel: "silent",
1538
- root: dirname(entry),
1539
- oxc: { jsx: { runtime: "automatic" } },
1540
- esbuild: { jsx: "automatic" },
1541
- define: { "process.env.NODE_ENV": "\"development\"" },
1542
- build: {
1543
- write: false,
1544
- minify: false,
1545
- lib: {
1546
- entry,
1547
- formats: ["es"],
1548
- fileName: "components"
1549
- },
1550
- rollupOptions: { external: SHARED }
1724
+ function handle(request, response, url) {
1725
+ const { pathname } = url;
1726
+ if (request.method === "GET" && pathname === "/") {
1727
+ send(response, 200, dashboardShell({
1728
+ extension: extension?.active ? {
1729
+ revision: extension.revision,
1730
+ js: Boolean(extension.built),
1731
+ css: Boolean(extension.built?.css)
1732
+ } : void 0,
1733
+ theme: theme !== ""
1734
+ }), {
1735
+ "content-type": "text/html; charset=utf-8",
1736
+ "cache-control": "no-store"
1737
+ });
1738
+ return;
1551
1739
  }
1552
- });
1553
- const bundles = Array.isArray(output) ? output : [output];
1554
- for (const bundle of bundles) {
1555
- const chunk = ("output" in bundle ? bundle.output : []).find((item) => item.type === "chunk" && item.isEntry);
1556
- if (chunk && "code" in chunk) return chunk.code;
1557
- }
1558
- throw new Error("Brick: the docs components module produced no output.");
1559
- }
1560
- /** Flatten what MDX gives for a heading to text. */
1561
- function plainText(value) {
1562
- if (typeof value === "string") return value;
1563
- if (Array.isArray(value)) return value.map(plainText).join("");
1564
- if (value && typeof value === "object") {
1565
- const node = value;
1566
- if (typeof node.value === "string") return node.value;
1567
- return plainText(node.props?.children ?? node.children);
1740
+ if (request.method === "GET" && pathname.startsWith("/assets/")) {
1741
+ const name = pathname.slice(8);
1742
+ const own = name === "brick-theme.css" ? theme : extension?.asset(name);
1743
+ if (own !== void 0) send(response, 200, own, {
1744
+ "content-type": ASSET_TYPES[extname(name)],
1745
+ "cache-control": "no-store"
1746
+ });
1747
+ else serveAsset(response, name);
1748
+ return;
1749
+ }
1750
+ if (isAppRoute(pathname)) {
1751
+ app(request, response, url);
1752
+ return;
1753
+ }
1754
+ if (request.method === "GET" && pathname === "/api/state") {
1755
+ send(response, 200, JSON.stringify(snapshot()), { "content-type": "application/json" });
1756
+ return;
1757
+ }
1758
+ if (request.method === "GET" && pathname === "/api/events") {
1759
+ eventStream(request, response);
1760
+ return;
1761
+ }
1762
+ if (request.method === "GET" && pathname.startsWith("/api/history") && options.history) {
1763
+ history(options.history, pathname, url.searchParams, response);
1764
+ return;
1765
+ }
1766
+ if (request.method === "GET" && pathname.startsWith("/api/docs")) {
1767
+ docsRoute(response, pathname, url.searchParams);
1768
+ return;
1769
+ }
1770
+ if (request.method === "GET" && pathname === "/api/openapi") {
1771
+ send(response, 200, JSON.stringify(options.store.apiDocuments()), {
1772
+ "content-type": "application/json",
1773
+ "cache-control": "no-store"
1774
+ });
1775
+ return;
1776
+ }
1777
+ if (pathname === "/api/proxy") {
1778
+ proxy(request, response, url);
1779
+ return;
1780
+ }
1781
+ if (pathname === "/workflows" || pathname.startsWith(`/workflows/`)) {
1782
+ response.setHeader("content-security-policy", "frame-ancestors 'self'");
1783
+ response.setHeader("x-frame-options", "SAMEORIGIN");
1784
+ inspector(request, response, url);
1785
+ return;
1786
+ }
1787
+ if (request.method === "POST" && pathname === "/api/ingest") {
1788
+ ingest(request, response);
1789
+ return;
1790
+ }
1791
+ if (request.method === "POST" && pathname === "/api/restart" && options.restart) {
1792
+ if (request.headers["x-brick-dashboard"] !== "1") {
1793
+ send(response, 403, "Forbidden");
1794
+ return;
1795
+ }
1796
+ options.restart();
1797
+ send(response, 202, "");
1798
+ return;
1799
+ }
1800
+ send(response, 404, "Not found");
1568
1801
  }
1569
- return "";
1570
- }
1571
- /** The page tree as plain data for the dashboard; icons and links are left out. */
1572
- function simplify(tree) {
1573
- const text = (value) => typeof value === "string" ? value : plainText(value);
1574
- const convert = (node) => {
1575
- if (node.type === "page" && node.url !== void 0) return {
1576
- type: "page",
1577
- name: text(node.name),
1578
- url: node.url,
1579
- ...typeof node.description === "string" ? { description: node.description } : {}
1580
- };
1581
- if (node.type === "separator") return {
1582
- type: "separator",
1583
- ...node.name ? { name: text(node.name) } : {}
1584
- };
1585
- if (node.type === "folder") return {
1586
- type: "folder",
1587
- name: text(node.name),
1588
- ...node.index?.url !== void 0 ? { index: {
1589
- name: text(node.index.name),
1590
- url: node.index.url
1591
- } } : {},
1592
- children: (node.children ?? []).flatMap((child) => convert(child) ?? []),
1593
- ...node.defaultOpen ? { defaultOpen: true } : {}
1594
- };
1595
- };
1596
- return {
1597
- name: text(tree?.name) || "Docs",
1598
- children: (tree?.children ?? []).flatMap((child) => convert(child) ?? [])
1599
- };
1600
- }
1601
- /** Open a docs folder; says what is missing when it cannot be shown. */
1602
- async function openDocs(options) {
1603
- const fumadocs = await loadFumadocs();
1604
- if (Array.isArray(fumadocs)) return {
1605
- status: "missing",
1606
- packages: fumadocs
1607
- };
1608
- const docs = new DevDocs(options.base, options.documentation, fumadocs, options.warn);
1609
- try {
1610
- await docs.refresh();
1611
- } catch (error) {
1612
- docs.close();
1613
- const root = resolve(options.base, options.documentation.dir);
1802
+ function snapshot() {
1614
1803
  return {
1615
- status: "error",
1616
- message: error.code === "ENOENT" ? `The docs folder ${root} does not exist.` : errorMessage(error)
1804
+ ...options.store.snapshot(),
1805
+ canRestart: Boolean(options.restart),
1806
+ historyDays: options.history?.days ?? 0,
1807
+ mode: production ? "production" : "dev",
1808
+ extension: extension?.active ? {
1809
+ revision: extension.revision,
1810
+ error: extension.error
1811
+ } : null
1617
1812
  };
1618
1813
  }
1619
- docs.watch();
1620
- return {
1621
- status: "ready",
1622
- docs
1623
- };
1624
- }
1625
- /**
1626
- * The docs of whichever app is running: opened when the app says where they
1627
- * are, replaced when that changes, and closed when it stops asking for them.
1628
- */
1629
- var DocsHost = class {
1630
- #store;
1631
- #warn;
1632
- #docs;
1633
- #stopListening;
1634
- #key;
1635
- #pending = Promise.resolve();
1636
- constructor(store, warn) {
1637
- this.#store = store;
1638
- this.#warn = warn;
1814
+ /**
1815
+ * Accept telemetry from an application process that cannot share memory with
1816
+ * the dashboard, such as a dev server worker: span batches, and a notice when
1817
+ * the app loads.
1818
+ */
1819
+ function ingest(request, response) {
1820
+ if (request.headers["x-brick-dashboard"] !== "1") {
1821
+ send(response, 403, "Forbidden");
1822
+ return;
1823
+ }
1824
+ let body = "";
1825
+ let rejected = false;
1826
+ request.setEncoding("utf8");
1827
+ request.on("data", (chunk) => {
1828
+ if (rejected) return;
1829
+ body += chunk;
1830
+ if (body.length > MAX_INGEST_BYTES) {
1831
+ rejected = true;
1832
+ send(response, 413, "Payload too large");
1833
+ request.destroy();
1834
+ }
1835
+ });
1836
+ request.on("end", () => {
1837
+ if (rejected) return;
1838
+ try {
1839
+ const payload = JSON.parse(body);
1840
+ if (Array.isArray(payload.records)) options.store.ingest(payload.records, options.store.latestGeneration);
1841
+ if (typeof payload.worker === "string") options.store.startGeneration(payload.worker);
1842
+ send(response, 204, "");
1843
+ } catch {
1844
+ send(response, 400, "Bad request");
1845
+ }
1846
+ });
1639
1847
  }
1640
- get current() {
1641
- return this.#docs;
1848
+ /** The Docs tab's data: tree, compiled pages, search, images, components. */
1849
+ async function docsRoute(response, pathname, params) {
1850
+ const docs = options.docs?.();
1851
+ if (!docs) {
1852
+ send(response, 404, "The app has no documentation.");
1853
+ return;
1854
+ }
1855
+ const json = (body) => send(response, 200, JSON.stringify(body), {
1856
+ "content-type": "application/json",
1857
+ "cache-control": "no-store"
1858
+ });
1859
+ try {
1860
+ if (pathname === "/api/docs") return json(docs.info());
1861
+ if (pathname === "/api/docs/search") return json(await docs.search(params.get("q") ?? ""));
1862
+ if (pathname === "/api/docs/components.js") {
1863
+ const code = await docs.components();
1864
+ if (code === void 0) return send(response, 404, "No components.");
1865
+ return send(response, 200, code, {
1866
+ "content-type": "text/javascript; charset=utf-8",
1867
+ "cache-control": "no-store"
1868
+ });
1869
+ }
1870
+ const pagePrefix = "/api/docs/page";
1871
+ if (pathname === pagePrefix || pathname.startsWith(`${pagePrefix}/`)) {
1872
+ const slugs = pathname.slice(14).split("/").filter(Boolean).map(decodeURIComponent);
1873
+ const page = await docs.page(slugs);
1874
+ return page ? json(page) : send(response, 404, "No such page.");
1875
+ }
1876
+ if (pathname.startsWith("/api/docs/files/")) {
1877
+ const file = await docs.file(pathname.slice(16).split("/").map(decodeURIComponent).join("/"));
1878
+ if (!file) return send(response, 404, "No such file.");
1879
+ return send(response, 200, file.body, {
1880
+ "content-type": file.type,
1881
+ "cache-control": "no-store",
1882
+ "content-security-policy": "sandbox"
1883
+ });
1884
+ }
1885
+ send(response, 404, "Not found");
1886
+ } catch (error) {
1887
+ send(response, error instanceof URIError ? 400 : 500, error instanceof Error ? error.message : String(error));
1888
+ }
1642
1889
  }
1643
1890
  /**
1644
- * Follow the app's `documentation`. Relative paths in it start at `base`, the
1645
- * folder of the app entry, as they read in the file that sets them.
1891
+ * Send a request on to the app for the APIs view, which cannot call the app
1892
+ * directly: it is another origin. Only the dashboard's own page may use this,
1893
+ * and only to reach the app being shown. The address to call is `?url=`; a
1894
+ * `?cookie=` is the cookie parameters the reader typed into Try it, and the
1895
+ * only cookie the app is sent (the dashboard's own are never forwarded).
1646
1896
  */
1647
- configure(base, documentation) {
1648
- this.#pending = this.#pending.then(() => this.#configure(base, documentation));
1649
- return this.#pending;
1897
+ /**
1898
+ * Pass a request to the workflow inspector, which the app serves on a port of
1899
+ * its own, and stream its answer back (it follows a run's output as it
1900
+ * grows). Anyone who can open the dashboard may look, but a change must come
1901
+ * from the dashboard's own page: the inspector can cancel runs and resume
1902
+ * hooks, and a page on another site could otherwise post to it.
1903
+ */
1904
+ async function inspector(request, response, url) {
1905
+ const target = options.store.inspectorTarget();
1906
+ if (!target) {
1907
+ send(response, 503, "The workflow inspector is not running. The app may be restarting, or it may run no workflows.", { "content-type": "text/plain; charset=utf-8" });
1908
+ return;
1909
+ }
1910
+ const bodyless = request.method === "GET" || request.method === "HEAD";
1911
+ const site = request.headers["sec-fetch-site"];
1912
+ const origin = request.headers.origin;
1913
+ if (!bodyless && (site !== void 0 && site !== "same-origin" || origin !== void 0 && origin !== `http://${request.headers.host}`)) {
1914
+ send(response, 403, "Forbidden");
1915
+ return;
1916
+ }
1917
+ await forward(request, response, `http://127.0.0.1:${target.port}${url.pathname}${url.search}`, (headers) => headers.set(INSPECTOR_TOKEN_HEADER, target.token), "Could not reach the workflow inspector.");
1650
1918
  }
1651
- async #configure(base, documentation) {
1652
- const key = JSON.stringify([base, documentation ?? null]);
1653
- if (key === this.#key) return;
1654
- this.#key = key;
1655
- this.#release();
1656
- if (!documentation) {
1657
- this.#store.setDocs(null);
1919
+ /**
1920
+ * Pass `/app/*` to the app, so the extension's pages read it from the
1921
+ * dashboard's own origin. Only the dashboard's page may use it, as with the
1922
+ * API proxy. A credential for the dashboard itself is not passed on.
1923
+ */
1924
+ async function app(request, response, url) {
1925
+ const site = request.headers["sec-fetch-site"];
1926
+ const origin = request.headers.origin;
1927
+ if (site !== void 0 && site !== "same-origin" || origin !== void 0 && origin !== `http://${request.headers.host}`) {
1928
+ send(response, 403, "Forbidden");
1658
1929
  return;
1659
1930
  }
1660
- const opened = await openDocs({
1661
- base,
1662
- documentation,
1663
- warn: this.#warn
1664
- });
1665
- if (opened.status !== "ready") {
1666
- const message = opened.status === "missing" ? `The docs need ${opened.packages.join(" and ")}. Install with: bun add -d ${opened.packages.join(" ")}` : opened.message;
1667
- this.#warn(`[Brick-TS] Docs are off. ${message}`);
1668
- this.#store.setDocs({
1669
- revision: 1,
1670
- status: opened.status,
1671
- title: "Docs",
1672
- components: false,
1673
- message,
1674
- ...opened.status === "missing" ? { packages: opened.packages } : {}
1931
+ const appUrl = options.appUrl ?? options.store.apiSnapshot()?.appUrl;
1932
+ if (!appUrl) {
1933
+ send(response, 503, "The app is not running yet.");
1934
+ return;
1935
+ }
1936
+ response.setHeader("content-security-policy", "frame-ancestors 'self'");
1937
+ response.setHeader("x-frame-options", "SAMEORIGIN");
1938
+ await forward(request, response, `${new URL(appUrl).origin}${url.pathname.slice(4) || "/"}${url.search}`, (headers) => {
1939
+ if (access) headers.delete("authorization");
1940
+ }, "Could not reach the app.");
1941
+ }
1942
+ /** Send the request on to `target` and stream its answer back. */
1943
+ async function forward(request, response, target, adjust, unreachable) {
1944
+ const bodyless = request.method === "GET" || request.method === "HEAD";
1945
+ const headers = new Headers();
1946
+ for (const [name, value] of Object.entries(request.headers)) {
1947
+ if (value === void 0 || NOT_FORWARDED.has(name)) continue;
1948
+ if (name.startsWith("sec-")) continue;
1949
+ headers.set(name, Array.isArray(value) ? value.join(", ") : value);
1950
+ }
1951
+ adjust(headers);
1952
+ const abort = new AbortController();
1953
+ response.on("close", () => abort.abort());
1954
+ try {
1955
+ const upstream = await fetch(target, {
1956
+ method: request.method,
1957
+ headers,
1958
+ redirect: "manual",
1959
+ signal: abort.signal,
1960
+ ...bodyless ? {} : {
1961
+ body: Readable.toWeb(request),
1962
+ duplex: "half"
1963
+ }
1964
+ });
1965
+ const returned = {};
1966
+ upstream.headers.forEach((value, name) => {
1967
+ if (!NOT_RETURNED.has(name)) returned[name] = value;
1675
1968
  });
1969
+ response.writeHead(upstream.status, returned);
1970
+ if (!upstream.body || request.method === "HEAD") {
1971
+ response.end();
1972
+ return;
1973
+ }
1974
+ await pipeline(Readable.fromWeb(upstream.body), response);
1975
+ } catch {
1976
+ if (response.headersSent) response.destroy();
1977
+ else send(response, 502, unreachable);
1978
+ }
1979
+ }
1980
+ async function proxy(request, response, url) {
1981
+ const site = request.headers["sec-fetch-site"];
1982
+ const origin = request.headers.origin;
1983
+ if (site !== void 0 && site !== "same-origin" || origin !== void 0 && origin !== `http://${request.headers.host}`) {
1984
+ send(response, 403, "Forbidden");
1676
1985
  return;
1677
1986
  }
1678
- this.#docs = opened.docs;
1679
- this.#stopListening = opened.docs.onChange(() => this.#store.setDocs(opened.docs.snapshot()));
1680
- this.#store.setDocs(opened.docs.snapshot());
1987
+ let target;
1988
+ try {
1989
+ target = new URL(url.searchParams.get("url") ?? "");
1990
+ } catch {}
1991
+ const appUrl = options.store.apiSnapshot()?.appUrl;
1992
+ if (!target || !appUrl || target.origin !== new URL(appUrl).origin) {
1993
+ send(response, 403, "Only the app shown in the dashboard can be reached.");
1994
+ return;
1995
+ }
1996
+ const body = await readBytes(request, MAX_PROXY_BYTES);
1997
+ if (!body) {
1998
+ send(response, 413, "Payload too large");
1999
+ return;
2000
+ }
2001
+ const headers = new Headers();
2002
+ for (const [name, value] of Object.entries(request.headers)) {
2003
+ if (value === void 0 || NOT_FORWARDED.has(name)) continue;
2004
+ if (name.startsWith("sec-")) continue;
2005
+ headers.set(name, Array.isArray(value) ? value.join(", ") : value);
2006
+ }
2007
+ const cookie = url.searchParams.get("cookie");
2008
+ if (cookie) headers.set("cookie", cookie);
2009
+ const bodyless = request.method === "GET" || request.method === "HEAD";
2010
+ try {
2011
+ const upstream = await fetch(target, {
2012
+ method: request.method,
2013
+ headers,
2014
+ body: bodyless ? void 0 : body,
2015
+ redirect: "manual"
2016
+ });
2017
+ const returned = {};
2018
+ upstream.headers.forEach((value, name) => {
2019
+ if (!NOT_RETURNED.has(name)) returned[name] = value;
2020
+ });
2021
+ send(response, upstream.status, new Uint8Array(await upstream.arrayBuffer()), returned);
2022
+ } catch {
2023
+ send(response, 502, "Could not reach the app.");
2024
+ }
1681
2025
  }
1682
- #release() {
1683
- this.#stopListening?.();
1684
- this.#stopListening = void 0;
1685
- this.#docs?.close();
1686
- this.#docs = void 0;
2026
+ function eventStream(request, response) {
2027
+ response.writeHead(200, {
2028
+ "content-type": "text/event-stream",
2029
+ "cache-control": "no-cache",
2030
+ connection: "keep-alive",
2031
+ "x-accel-buffering": "no"
2032
+ });
2033
+ const write = (chunk) => {
2034
+ if (response.writableEnded || response.destroyed) return;
2035
+ response.write(chunk);
2036
+ };
2037
+ write(`event: snapshot\ndata: ${JSON.stringify(snapshot())}\n\n`);
2038
+ const unsubscribe = options.store.subscribe((event) => write(`event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`));
2039
+ const unwatch = extension?.onChange(() => write(`event: extension\ndata: ${JSON.stringify(snapshot().extension)}\n\n`));
2040
+ const keepalive = setInterval(() => write(": keepalive\n\n"), KEEPALIVE_MS);
2041
+ request.on("close", () => {
2042
+ clearInterval(keepalive);
2043
+ unsubscribe();
2044
+ unwatch?.();
2045
+ });
1687
2046
  }
1688
- close() {
1689
- this.#key = void 0;
1690
- this.#release();
2047
+ return (extension ? Promise.all([extension.load(), options.plugins && extension.setPlugins(options.plugins)]) : Promise.resolve()).then(() => listen());
2048
+ function listen() {
2049
+ return new Promise((resolve, reject) => {
2050
+ server.once("error", (error) => {
2051
+ extension?.close();
2052
+ reject(new Error(production ? `Brick: dashboard port ${options.port} is unavailable. Set dashboard.port in brick() to another.` : `Brick: dashboard port ${options.port} is unavailable. Use --dashboard-port <number> or --no-dashboard.`, { cause: error }));
2053
+ });
2054
+ server.listen(options.port, host, () => {
2055
+ const address = server.address();
2056
+ const port = typeof address === "object" && address !== null ? address.port : options.port;
2057
+ allowedHosts = /* @__PURE__ */ new Set([
2058
+ `127.0.0.1:${port}`,
2059
+ `localhost:${port}`,
2060
+ `[::1]:${port}`
2061
+ ]);
2062
+ if (!production) extension?.watch();
2063
+ resolve({
2064
+ port,
2065
+ setPluginExtensions: (plugins) => extension?.setPlugins(plugins) ?? Promise.resolve(),
2066
+ stop() {
2067
+ extension?.close();
2068
+ server.close();
2069
+ server.closeAllConnections();
2070
+ }
2071
+ });
2072
+ });
2073
+ });
1691
2074
  }
2075
+ }
2076
+ /** The whole request body, or undefined when it is larger than `limit`. */
2077
+ function readBytes(request, limit) {
2078
+ return new Promise((resolve) => {
2079
+ const chunks = [];
2080
+ let size = 0;
2081
+ request.on("data", (chunk) => {
2082
+ size += chunk.length;
2083
+ if (size > limit) {
2084
+ resolve(void 0);
2085
+ request.destroy();
2086
+ return;
2087
+ }
2088
+ chunks.push(chunk);
2089
+ });
2090
+ request.on("end", () => resolve(new Uint8Array(Buffer.concat(chunks))));
2091
+ request.on("error", () => resolve(void 0));
2092
+ });
2093
+ }
2094
+ function history(store, pathname, params, response) {
2095
+ const json = (body) => send(response, 200, JSON.stringify(body), { "content-type": "application/json" });
2096
+ try {
2097
+ if (pathname === "/api/history") return json(store.info());
2098
+ if (pathname === "/api/history/summary") return json(store.summary(parseHistoryQuery(params)));
2099
+ if (pathname === "/api/history/traces") return json(store.traces(parseHistoryQuery(params)));
2100
+ if (pathname === "/api/history/facets") return json(store.facets(parseHistoryQuery(params)));
2101
+ if (pathname === "/api/history/volume") return json(store.volume(parseHistoryQuery(params)));
2102
+ if (pathname === "/api/history/export") return send(response, 200, store.exportCsv(parseHistoryQuery(params)), {
2103
+ "content-type": "text/csv; charset=utf-8",
2104
+ "content-disposition": "attachment; filename=\"brick-requests.csv\"",
2105
+ "cache-control": "no-store"
2106
+ });
2107
+ if (pathname.startsWith("/api/history/traces/")) {
2108
+ const trace = store.trace(decodeURIComponent(pathname.slice(20)));
2109
+ if (trace) return json(trace);
2110
+ }
2111
+ send(response, 404, "Not found");
2112
+ } catch {
2113
+ send(response, 500, "History query failed");
2114
+ }
2115
+ }
2116
+ const ASSET_TYPES = {
2117
+ ".js": "text/javascript; charset=utf-8",
2118
+ ".css": "text/css; charset=utf-8",
2119
+ ".woff2": "font/woff2"
1692
2120
  };
1693
- //#endregion
1694
- //#region src/dev-telemetry-store.ts
2121
+ function serveAsset(response, name) {
2122
+ if (!/^[\w.-]+$/.test(name) || name.startsWith(".")) {
2123
+ send(response, 404, "Not found");
2124
+ return;
2125
+ }
2126
+ const directory = assetsDirectory();
2127
+ if (!directory) {
2128
+ send(response, 503, "Dashboard assets are missing. Build them with: bun run --filter @brickkit/cli build");
2129
+ return;
2130
+ }
2131
+ readFile(join(directory, name)).then((body) => send(response, 200, body, {
2132
+ "content-type": ASSET_TYPES[extname(name)] ?? "application/octet-stream",
2133
+ "cache-control": "no-store"
2134
+ }), () => send(response, 404, "Not found"));
2135
+ }
2136
+ function send(response, status, body, headers = { "content-type": "text/plain; charset=utf-8" }) {
2137
+ response.writeHead(status, headers);
2138
+ response.end(body);
2139
+ }
2140
+ // src/dev-telemetry-store.ts
1695
2141
  const LIMITS = {
1696
2142
  traces: 200,
1697
2143
  spansPerTrace: 500,
@@ -2034,7 +2480,6 @@ function numberAttribute(attributes, key) {
2034
2480
  const value = attributes?.[key];
2035
2481
  return typeof value === "number" ? value : void 0;
2036
2482
  }
2037
- //#endregion
2038
- export { isLoopbackHost as a, startDevDashboard as i, DocsHost as n, openHistory as o, DEFAULT_DASHBOARD_PORT as r, startInspector as s, DevTelemetryStore as t };
2483
+ export { writeDashboardExtension as a, openHistory as c, themeCss as i, startInspector as l, DEFAULT_DASHBOARD_PORT as n, DocsHost as o, startDevDashboard as r, isLoopbackHost as s, DevTelemetryStore as t };
2039
2484
 
2040
2485
  //# sourceMappingURL=dev-telemetry-store.js.map