brumate 0.2.0 → 0.4.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 (138) hide show
  1. package/README.md +2 -2
  2. package/check.d.ts +49 -0
  3. package/dist/{boot-D-IdPy7B.d.ts → boot-DLlRmD9z.d.ts} +11 -10
  4. package/dist/cli.js +275 -15
  5. package/dist/cli.js.map +1 -1
  6. package/dist/client-BvDsC6Qr.js +3463 -0
  7. package/dist/client-BvDsC6Qr.js.map +1 -0
  8. package/dist/client-DBwL2wKQ.d.ts +669 -0
  9. package/dist/{client-routes-JTbGtukf.js → client-routes-BtGpYCef.js} +60 -30
  10. package/dist/client-routes-BtGpYCef.js.map +1 -0
  11. package/dist/{cookies-Av5WFmcf.js → cookies-Cnbf4w-S.js} +15 -7
  12. package/dist/cookies-Cnbf4w-S.js.map +1 -0
  13. package/dist/{defer-D0bo1Gqx.js → defer-CKWZLv2K.js} +8 -4
  14. package/dist/defer-CKWZLv2K.js.map +1 -0
  15. package/dist/devtools-4uTPwR_v.js +597 -0
  16. package/dist/devtools-4uTPwR_v.js.map +1 -0
  17. package/dist/devtools-panel-Be9pxYgv.js +1994 -0
  18. package/dist/devtools-panel-Be9pxYgv.js.map +1 -0
  19. package/dist/events-LgLdp1R7.js +114 -0
  20. package/dist/events-LgLdp1R7.js.map +1 -0
  21. package/dist/features-CHY5Ekku.js +30 -0
  22. package/dist/features-CHY5Ekku.js.map +1 -0
  23. package/dist/files-WW4RlajL.js +506 -0
  24. package/dist/files-WW4RlajL.js.map +1 -0
  25. package/dist/forms-j1xPAR14.d.ts +281 -0
  26. package/dist/forms-nXK7-Lv_.js +440 -0
  27. package/dist/forms-nXK7-Lv_.js.map +1 -0
  28. package/dist/highlight.d.ts +17 -0
  29. package/dist/highlight.js +278 -0
  30. package/dist/highlight.js.map +1 -0
  31. package/dist/html-BtKRyi7g.js +305 -0
  32. package/dist/html-BtKRyi7g.js.map +1 -0
  33. package/dist/html-Bw9Qwu6F.d.ts +107 -0
  34. package/dist/index.d.ts +142 -11
  35. package/dist/index.js +641 -106
  36. package/dist/index.js.map +1 -1
  37. package/dist/{inspect-BJtACnQp.js → inspect-Y6y4uNZp.js} +4333 -681
  38. package/dist/inspect-Y6y4uNZp.js.map +1 -0
  39. package/dist/{loader-B18i3_-T.js → loader-BjKGJzLN.js} +21 -14
  40. package/dist/loader-BjKGJzLN.js.map +1 -0
  41. package/dist/logo-DQ_OYhBi.js +10 -0
  42. package/dist/logo-DQ_OYhBi.js.map +1 -0
  43. package/dist/{navigate-BwuZveDF.js → navigate-CfOr-TRF.js} +130 -24
  44. package/dist/navigate-CfOr-TRF.js.map +1 -0
  45. package/dist/nesting-DA5vJw9X.js +265 -0
  46. package/dist/nesting-DA5vJw9X.js.map +1 -0
  47. package/dist/produce-B7X9ori9.js +402 -0
  48. package/dist/produce-B7X9ori9.js.map +1 -0
  49. package/dist/produce-DIgHBVwL.d.ts +148 -0
  50. package/dist/{rpc-B-Zkn6Ch.js → rpc-Q-XkLwFh.js} +28 -13
  51. package/dist/rpc-Q-XkLwFh.js.map +1 -0
  52. package/dist/runtime/batch.js +9 -7
  53. package/dist/runtime/batch.js.map +1 -1
  54. package/dist/runtime/client.d.ts +4 -4
  55. package/dist/runtime/client.js +4 -4
  56. package/dist/runtime/devtools.d.ts +172 -5
  57. package/dist/runtime/devtools.js +3 -1
  58. package/dist/runtime/env.js +14 -2
  59. package/dist/runtime/env.js.map +1 -1
  60. package/dist/runtime/events.d.ts +38 -1
  61. package/dist/runtime/events.js +1 -1
  62. package/dist/runtime/forms.d.ts +2 -0
  63. package/dist/runtime/forms.js +1 -0
  64. package/dist/runtime/gather.d.ts +25 -0
  65. package/dist/runtime/gather.js +33 -0
  66. package/dist/runtime/gather.js.map +1 -0
  67. package/dist/runtime/hot.d.ts +1 -1
  68. package/dist/runtime/hot.js +5 -2
  69. package/dist/runtime/hot.js.map +1 -1
  70. package/dist/runtime/html.d.ts +2 -2
  71. package/dist/runtime/html.js +1 -1
  72. package/dist/runtime/loader.d.ts +2 -2
  73. package/dist/runtime/loader.js +2 -2
  74. package/dist/runtime/routes.js +4 -1
  75. package/dist/runtime/routes.js.map +1 -1
  76. package/dist/runtime/server.d.ts +5 -4
  77. package/dist/runtime/server.js +5 -5
  78. package/dist/runtime/signals.d.ts +75 -2
  79. package/dist/runtime/signals.js +44 -2
  80. package/dist/runtime/signals.js.map +1 -1
  81. package/dist/runtime/static-loader.d.ts +2 -2
  82. package/dist/runtime/static-loader.js +1 -1
  83. package/dist/runtime/testing.d.ts +18 -3
  84. package/dist/runtime/testing.js +150 -33
  85. package/dist/runtime/testing.js.map +1 -1
  86. package/dist/runtime/values.d.ts +2 -0
  87. package/dist/runtime/values.js +24 -0
  88. package/dist/runtime/values.js.map +1 -0
  89. package/dist/{server-BA9SJ2Vm.d.ts → server-BvPIg9pT.d.ts} +363 -32
  90. package/dist/{server-BqfM95r1.js → server-DjyOVJtJ.js} +1309 -220
  91. package/dist/server-DjyOVJtJ.js.map +1 -0
  92. package/dist/{static-loader-BzE9SRaj.d.ts → static-loader-BGgdp_Y5.d.ts} +2 -2
  93. package/dist/static-loader-BZR17hSw.js +312 -0
  94. package/dist/static-loader-BZR17hSw.js.map +1 -0
  95. package/dist/{stream-JaMHMdBD.js → stream-BP5AVmg5.js} +182 -17
  96. package/dist/stream-BP5AVmg5.js.map +1 -0
  97. package/dist/values-B8C7CLvG.d.ts +63 -0
  98. package/dist/vite.d.ts +20 -20
  99. package/dist/vite.js +2031 -539
  100. package/dist/vite.js.map +1 -1
  101. package/elements.d.ts +951 -0
  102. package/forms/forms.brm.ts +141 -0
  103. package/package.json +41 -3
  104. package/skills/brumate/SKILL.md +58 -0
  105. package/skills/brumate/references/errors.md +2078 -0
  106. package/skills/brumate/references/events.md +117 -0
  107. package/skills/brumate/references/signals.md +61 -0
  108. package/skills/brumate/references/state.md +235 -0
  109. package/skills/brumate/references/syntax.md +250 -0
  110. package/types.d.ts +4 -4
  111. package/dist/client-C0UCNL3J.js +0 -1643
  112. package/dist/client-C0UCNL3J.js.map +0 -1
  113. package/dist/client-MD0ZmcFR.d.ts +0 -354
  114. package/dist/client-routes-JTbGtukf.js.map +0 -1
  115. package/dist/cookies-Av5WFmcf.js.map +0 -1
  116. package/dist/defer-D0bo1Gqx.js.map +0 -1
  117. package/dist/devtools-C50VH8gZ.js +0 -113
  118. package/dist/devtools-C50VH8gZ.js.map +0 -1
  119. package/dist/devtools-panel-AYjfwPhj.js +0 -435
  120. package/dist/devtools-panel-AYjfwPhj.js.map +0 -1
  121. package/dist/events-BKWRqtMg.js +0 -52
  122. package/dist/events-BKWRqtMg.js.map +0 -1
  123. package/dist/files-Bnn1JqHx.js +0 -192
  124. package/dist/files-Bnn1JqHx.js.map +0 -1
  125. package/dist/html-bHZbkK-h.js +0 -170
  126. package/dist/html-bHZbkK-h.js.map +0 -1
  127. package/dist/html-y1q7-t7D.d.ts +0 -60
  128. package/dist/inspect-BJtACnQp.js.map +0 -1
  129. package/dist/loader-B18i3_-T.js.map +0 -1
  130. package/dist/navigate-BwuZveDF.js.map +0 -1
  131. package/dist/produce-CWfJ4byV.js +0 -167
  132. package/dist/produce-CWfJ4byV.js.map +0 -1
  133. package/dist/produce-D4K7qpaL.d.ts +0 -72
  134. package/dist/rpc-B-Zkn6Ch.js.map +0 -1
  135. package/dist/server-BqfM95r1.js.map +0 -1
  136. package/dist/static-loader-DOygOFj5.js +0 -216
  137. package/dist/static-loader-DOygOFj5.js.map +0 -1
  138. package/dist/stream-JaMHMdBD.js.map +0 -1
package/dist/vite.js CHANGED
@@ -1,37 +1,43 @@
1
- import { C as resolveFromDisk, E as analyzeProject, O as forEachNode, P as getLocation, S as isReactiveModule, _ as getComponentName, b as generateShared, d as instanceScope, f as slotIndex, g as functionId, i as scopeLabel, j as parse, k as resolveRelative, o as compile, r as report, t as formatReport, v as hash, w as builtin, y as SHARED_QUERY } from "./inspect-BJtACnQp.js";
2
- import { s as toNodeHeaders } from "./cookies-Av5WFmcf.js";
3
- import { a as hasServerMiddleware, c as serverExports, i as findServerFiles, l as serverModule, n as findFiles, o as hasUseServer, r as findScripts, s as isScriptFile, t as defaultExclude, u as serverStubs } from "./files-Bnn1JqHx.js";
1
+ import { A as analyzeProject, B as getLocation, C as isReactiveModule, E as originalPosition, F as resolveRelative, J as walk, L as parse, M as forEachNode, N as importSource, O as entryClasses, P as importedComponents, T as builtin, U as analyze, _ as functionId, a as scopeLabel, b as SHARED_QUERY, f as instanceScope, i as report, k as refreshedNames, n as formatReport, p as slotIndex, q as resolveMacros, s as compile, t as anchorLabel, v as getComponentName, w as resolveFromDisk, x as generateShared, y as hash } from "./inspect-Y6y4uNZp.js";
2
+ import { s as toNodeHeaders } from "./cookies-Cnbf4w-S.js";
3
+ import { t as LOGO } from "./logo-DQ_OYhBi.js";
4
+ import { _ as reachableFiles, a as findServerFiles, c as hasServerMiddleware, d as serverExports, f as serverModule, g as packageFileName, h as findPackages, i as findScripts, l as hasUseServer, m as findPackage, n as defaultExclude, o as findPackageServerFile, p as serverStubs, r as findFiles, u as isScriptFile, v as resolveComponentPackage } from "./files-WW4RlajL.js";
4
5
  import { parseSync } from "oxc-parser";
5
6
  import { createHash } from "node:crypto";
6
- import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
7
+ import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync } from "node:fs";
7
8
  import { mkdir, readFile, writeFile } from "node:fs/promises";
8
9
  import path, { resolve } from "node:path";
9
10
  import { fileURLToPath, pathToFileURL } from "node:url";
10
- import { isRunnableDevEnvironment, normalizePath, searchForWorkspaceRoot, transformWithOxc } from "vite";
11
+ import { isFileLoadingAllowed, isRunnableDevEnvironment, normalizePath, searchForWorkspaceRoot, transformWithOxc, version } from "vite";
11
12
  //#region src/env-file.ts
12
13
  /** The name of the function that declares the variables. */
13
14
  const DEFINE = "defineEnv";
14
15
  /** The names of the properties of an object literal. Other keys throw. */
15
- function keysOf(node, group, filename) {
16
+ function readKeys(node, group, filename) {
16
17
  if (node.type !== "ObjectExpression") throw new Error(`The ${group} variables of ${filename} must be an object literal, so the compiler can read their names`);
17
- return node.properties.map((property) => {
18
- if (property.type === "Property" && !property.computed) return property.key.type === "Identifier" ? property.key.name : String(property.key.value);
18
+ const keys = [];
19
+ for (const property of node.properties) {
20
+ if (property.type === "Property" && !property.computed) {
21
+ keys.push(property.key.type === "Identifier" ? property.key.name : String(property.key.value));
22
+ continue;
23
+ }
19
24
  throw new Error(`The ${group} variables of ${filename} must be plain properties, so the compiler can read their names`);
20
- });
25
+ }
26
+ return keys;
21
27
  }
22
28
  /** Finds the `defineEnv` call of the file. */
23
29
  function findCall(program) {
24
30
  let found;
25
- const visit = (node) => {
31
+ function visit(node) {
26
32
  if (found || typeof node !== "object" || node === null) return;
27
33
  const value = node;
28
34
  if (value.type === "CallExpression" && value.callee?.name === DEFINE) {
29
35
  found = value;
30
36
  return;
31
37
  }
32
- for (const child of Object.values(value)) if (Array.isArray(child)) child.forEach(visit);
38
+ for (const child of Object.values(value)) if (Array.isArray(child)) for (const item of child) visit(item);
33
39
  else if (typeof child === "object") visit(child);
34
- };
40
+ }
35
41
  visit(program);
36
42
  return found;
37
43
  }
@@ -52,21 +58,23 @@ function parseEnvFile(source, filename) {
52
58
  schemaEnd: schema.end,
53
59
  hasOptions: call.arguments.length > 1
54
60
  };
55
- schema.properties.forEach((property, index) => {
61
+ for (const [index, property] of schema.properties.entries()) {
56
62
  if (property.type !== "Property" || property.computed || property.key.type !== "Identifier") throw new Error(`${DEFINE} in ${filename} takes server and public variables only`);
57
63
  const group = property.key.name;
58
64
  if (group !== "server" && group !== "public") throw new Error(`${DEFINE} in ${filename} takes server and public variables, not ${group}`);
59
- result[group] = keysOf(property.value, group, filename);
65
+ result[group] = readKeys(property.value, group, filename);
60
66
  if (group === "server") {
61
67
  const next = schema.properties[index + 1];
62
68
  const comma = source.indexOf(",", property.end);
63
- const end = next ? next.start : comma !== -1 && comma < schema.end ? comma + 1 : property.end;
69
+ let end = property.end;
70
+ if (next) end = next.start;
71
+ else if (comma !== -1 && comma < schema.end) end = comma + 1;
64
72
  result.serverRange = {
65
73
  start: property.start,
66
74
  end
67
75
  };
68
76
  }
69
- });
77
+ }
70
78
  return result;
71
79
  }
72
80
  /**
@@ -101,6 +109,86 @@ function clientEnvModule(source, filename, values) {
101
109
  return result + source.slice(position);
102
110
  }
103
111
  //#endregion
112
+ //#region src/features.ts
113
+ /** No feature at all, which a build that has no component uses. */
114
+ function noFeatures() {
115
+ return {
116
+ children: false,
117
+ templates: false,
118
+ titles: false,
119
+ bindings: false,
120
+ lateMarkup: false,
121
+ blocks: false,
122
+ listeners: false,
123
+ actions: false,
124
+ clientHTML: false
125
+ };
126
+ }
127
+ /** Every feature, for a build that compiles components in the browser. */
128
+ function allFeatures() {
129
+ const all = noFeatures();
130
+ for (const name of Object.keys(all)) all[name] = true;
131
+ return all;
132
+ }
133
+ /** The features of the core that a compiled component uses. */
134
+ function getFeatures(result) {
135
+ const client = [
136
+ result.client,
137
+ result.render,
138
+ ...Object.values(result.parts)
139
+ ].join("\n");
140
+ const all = `${result.server}\n${client}`;
141
+ return {
142
+ children: result.plan.childrenRenders.size > 0 || /\$\$b\.children\(/.test(client),
143
+ templates: /\bexport (?:const|function) t\d+\b/.test(client),
144
+ titles: /\bb-t\b/.test(all),
145
+ bindings: /\$\$b\.binding\(/.test(all),
146
+ lateMarkup: /\$\$ctx\.(?:boundary|defer|deferBlock)\(|\bgather\(/.test(result.server),
147
+ blocks: /\bb-(?:client|defer)\b/.test(all),
148
+ listeners: /\bb-listen\b/.test(all),
149
+ actions: /\$\$b\.action\(/.test(all),
150
+ clientHTML: /\breturn \$\$html;/.test(client)
151
+ };
152
+ }
153
+ /** The features of several components together. */
154
+ function joinFeatures(all) {
155
+ const joined = noFeatures();
156
+ for (const features of all) {
157
+ joined.children ||= features.children;
158
+ joined.templates ||= features.templates;
159
+ joined.titles ||= features.titles;
160
+ joined.bindings ||= features.bindings;
161
+ joined.lateMarkup ||= features.lateMarkup;
162
+ joined.blocks ||= features.blocks;
163
+ joined.listeners ||= features.listeners;
164
+ joined.actions ||= features.actions;
165
+ joined.clientHTML ||= features.clientHTML;
166
+ }
167
+ return joined;
168
+ }
169
+ /** The names of the globals of `runtime/features.ts`, by feature. */
170
+ const GLOBALS = {
171
+ children: "__BRUMATE_HAS_CHILDREN__",
172
+ templates: "__BRUMATE_HAS_TEMPLATES__",
173
+ titles: "__BRUMATE_HAS_TITLES__",
174
+ bindings: "__BRUMATE_HAS_BINDINGS__",
175
+ lateMarkup: "__BRUMATE_HAS_LATE_MARKUP__",
176
+ blocks: "__BRUMATE_HAS_BLOCKS__",
177
+ listeners: "__BRUMATE_HAS_LISTENERS__",
178
+ actions: "__BRUMATE_HAS_ACTIONS__",
179
+ clientHTML: "__BRUMATE_HAS_CLIENT_HTML__"
180
+ };
181
+ /** True for code that reads a feature, such as the core. */
182
+ function readsFeatures(code) {
183
+ return code.includes("__BRUMATE_HAS_");
184
+ }
185
+ /** The code with each feature written in as `true` or `false`. */
186
+ function writeFeatures(code, features) {
187
+ let result = code;
188
+ for (const [name, global] of Object.entries(GLOBALS)) result = result.replace(new RegExp(`(?<!declare const )\\b${global}\\b`, "g"), String(features[name]));
189
+ return result;
190
+ }
191
+ //#endregion
104
192
  //#region src/builds.ts
105
193
  /** The file in the client build that names its build. */
106
194
  const BUILD_FILE = ".brumate/build.json";
@@ -136,7 +224,9 @@ function pruneBuilds(directory, id, files, keep, now = Date.now()) {
136
224
  } catch {
137
225
  builds = [];
138
226
  }
139
- builds = builds.filter((build) => build.id !== id);
227
+ const others = [];
228
+ for (const build of builds) if (build.id !== id) others.push(build);
229
+ builds = others;
140
230
  builds.push({
141
231
  id,
142
232
  at: now,
@@ -145,225 +235,20 @@ function pruneBuilds(directory, id, files, keep, now = Date.now()) {
145
235
  builds.sort((a, b) => a.at - b.at);
146
236
  const kept = builds.slice(Math.max(0, builds.length - 1 - keep));
147
237
  const dropped = builds.slice(0, builds.length - kept.length);
148
- const keptFiles = new Set(kept.flatMap((build) => build.files));
238
+ const keptFiles = /* @__PURE__ */ new Set();
239
+ for (const build of kept) for (const file of build.files) keptFiles.add(file);
149
240
  for (const build of dropped) for (const file of build.files) if (!keptFiles.has(file)) rmSync(path.join(directory, file), { force: true });
150
241
  mkdirSync(path.join(directory, ".brumate"), { recursive: true });
151
242
  writeFileSync(path.join(directory, BUILD_FILE), `${JSON.stringify({ build: id })}\n`);
152
243
  writeFileSync(list, `${JSON.stringify({ builds: kept }, null, 2)}\n`);
153
- return dropped.map((build) => build.id);
244
+ const droppedIds = [];
245
+ for (const build of dropped) droppedIds.push(build.id);
246
+ return droppedIds;
154
247
  }
155
248
  //#endregion
156
- //#region src/packages.ts
157
- const toPosix = (file) => file.split(path.sep).join("/");
158
- function readJson(file) {
159
- try {
160
- return JSON.parse(readFileSync(file, "utf8"));
161
- } catch {
162
- return;
163
- }
164
- }
165
- /** The real directory of a package that code in `from` can import, or undefined. */
166
- function findPackageDirectory(name, from) {
167
- for (let directory = from;; directory = path.dirname(directory)) {
168
- const candidate = path.join(directory, "node_modules", name);
169
- if (existsSync(path.join(candidate, "package.json"))) return toPosix(realpathSync(candidate));
170
- if (path.dirname(directory) === directory) return;
171
- }
172
- }
173
- /** The directory of the nearest package.json at or above a directory. */
174
- function packageRoot(directory) {
175
- for (let current = directory;; current = path.dirname(current)) {
176
- if (existsSync(path.join(current, "package.json"))) return current;
177
- if (path.dirname(current) === current) return;
178
- }
179
- }
180
- /** The directories that the `brumate` field names, or undefined when the package does not opt in. */
181
- function directoriesOf(root, field, name) {
182
- if (field === true) return [root];
183
- if (typeof field === "object" && field !== null) {
184
- const { dir, version = 1 } = field;
185
- if (version !== 1) throw new Error(`The package ${name} has "brumate": { "version": ${version} }, but this version of brumate reads version 1. Install a version of ${name} or of brumate that matches.`);
186
- if (dir === void 0) return [root];
187
- return (Array.isArray(dir) ? dir : [dir]).map((item) => toPosix(path.resolve(root, item)));
188
- }
189
- }
190
- /**
191
- * Finds the dependencies of the app at `root` that ship `.brm` files, and
192
- * theirs. The app's dependencies come from its package.json: `dependencies`,
193
- * `devDependencies`, `optionalDependencies` and `peerDependencies`. A package
194
- * opts in with `"brumate": true`, or `"brumate": { "dir": "src" }` to search
195
- * only that directory. Symbolic links, such as those of pnpm, resolve to the
196
- * real directory.
197
- */
198
- function findPackages(root) {
199
- const app = packageRoot(path.resolve(root));
200
- if (!app) return [];
201
- const found = /* @__PURE__ */ new Map();
202
- const visit = (directory, json, own) => {
203
- const names = /* @__PURE__ */ new Set([
204
- ...Object.keys(json.dependencies ?? {}),
205
- ...Object.keys(json.optionalDependencies ?? {}),
206
- ...Object.keys(json.peerDependencies ?? {}),
207
- ...own ? Object.keys(json.devDependencies ?? {}) : []
208
- ]);
209
- for (const name of [...names].toSorted()) {
210
- const real = findPackageDirectory(name, directory);
211
- if (!real || found.has(real)) continue;
212
- const dependency = readJson(`${real}/package.json`);
213
- const directories = dependency && directoriesOf(real, dependency.brumate, name);
214
- if (!dependency || !directories) continue;
215
- found.set(real, {
216
- name: dependency.name ?? name,
217
- version: dependency.version ?? "0.0.0",
218
- root: real,
219
- directories,
220
- linked: !real.includes("/node_modules/")
221
- });
222
- visit(real, dependency, false);
223
- }
224
- };
225
- visit(app, readJson(path.join(app, "package.json")) ?? {}, true);
226
- const list = [...found.values()];
227
- const versions = /* @__PURE__ */ new Map();
228
- for (const item of list) versions.set(item.name, (versions.get(item.name) ?? /* @__PURE__ */ new Set()).add(item.version));
229
- return list.map((item) => Object.assign(item, { prefix: versions.get(item.name).size > 1 ? `${item.name}@${item.version}` : item.name }));
230
- }
231
- /** The package that a file belongs to, or undefined for a file of the app. */
232
- function packageOf(packages, file) {
233
- return packages.find((item) => file.startsWith(`${item.root}/`));
234
- }
235
- /**
236
- * The name of a file of a package, which its IDs come from: the prefix of
237
- * the package and the path of the file in it, such as `@acme/ui/src/Button.brm`.
238
- * It is the same wherever the package is installed.
239
- */
240
- function packageFileName(item, file) {
241
- return `${item.prefix}/${file.slice(item.root.length + 1)}`;
242
- }
243
- /** The name and the subpath of a bare specifier, such as `@acme/ui` and `./Button.brm`. */
244
- function splitSpecifier(specifier) {
245
- if (specifier.startsWith(".") || specifier.startsWith("/") || /^[a-z]+:/i.test(specifier)) return;
246
- const parts = specifier.split("/");
247
- const count = specifier.startsWith("@") ? 2 : 1;
248
- if (parts.length < count || parts.slice(0, count).some((part) => part === "")) return;
249
- const rest = parts.slice(count).join("/");
250
- return {
251
- name: parts.slice(0, count).join("/"),
252
- subpath: rest ? `./${rest}` : "."
253
- };
254
- }
255
- /** The conditions of `exports` that a `.brm` file or a source module can be under. */
256
- const CONDITIONS = /* @__PURE__ */ new Set([
257
- "brumate",
258
- "import",
259
- "module",
260
- "node",
261
- "browser",
262
- "default"
263
- ]);
264
- function resolveTarget(target, star) {
265
- if (typeof target === "string") return target.replaceAll("*", star);
266
- if (Array.isArray(target)) {
267
- for (const item of target) {
268
- const result = resolveTarget(item, star);
269
- if (result) return result;
270
- }
271
- return;
272
- }
273
- if (typeof target === "object" && target !== null) {
274
- for (const [condition, value] of Object.entries(target)) if (CONDITIONS.has(condition)) {
275
- const result = resolveTarget(value, star);
276
- if (result) return result;
277
- }
278
- }
279
- }
280
- /** Resolves a subpath through the `exports` of a package.json, or undefined if it does not export it. */
281
- function resolveExports(exports, subpath) {
282
- const map = typeof exports === "object" && exports !== null && !Array.isArray(exports) && Object.keys(exports).some((key) => key.startsWith(".")) ? exports : { ".": exports };
283
- if (subpath in map) return resolveTarget(map[subpath], "");
284
- let best;
285
- for (const key of Object.keys(map)) {
286
- const index = key.indexOf("*");
287
- if (index === -1) continue;
288
- const before = key.slice(0, index);
289
- const after = key.slice(index + 1);
290
- if (subpath.startsWith(before) && subpath.endsWith(after) && subpath.length >= key.length - 1 && (!best || before.length > best.key.indexOf("*"))) best = {
291
- key,
292
- star: subpath.slice(before.length, subpath.length - after.length)
293
- };
294
- }
295
- return best && resolveTarget(map[best.key], best.star);
296
- }
297
- /**
298
- * Resolves a bare specifier, such as `@acme/ui/Button.brm`, to the real path
299
- * of the file, through the `exports` of the package. Returns undefined when
300
- * it is not a bare specifier or names no file.
301
- */
302
- function resolvePackageImport(specifier, importer) {
303
- const split = splitSpecifier(specifier);
304
- if (!split) return;
305
- const directory = findPackageDirectory(split.name, path.dirname(importer));
306
- if (!directory) return;
307
- const json = readJson(`${directory}/package.json`);
308
- const target = json?.exports === void 0 ? split.subpath : resolveExports(json.exports, split.subpath);
309
- if (!target) return;
310
- const file = path.resolve(directory, target);
311
- return existsSync(file) ? toPosix(realpathSync(file)) : void 0;
312
- }
313
- /** The specifiers that a file imports or exports from, found by a pattern, so it can only find more. */
314
- function importSpecifiers(source) {
315
- const result = [];
316
- for (const match of source.matchAll(/(?:\bfrom|\bimport\s*\(?)\s*(['"])([^'"\n]+)\1/g)) result.push(match[2]);
317
- return result;
318
- }
319
- /** The extensions that an import without one can name. */
320
- const EXTENSIONS = [
321
- "",
322
- ".ts",
323
- ".tsx",
324
- ".js",
325
- ".mjs",
326
- "/index.ts",
327
- "/index.js"
328
- ];
329
- /**
330
- * The files of packages that the app reaches: the files of packages that
331
- * files of the app import, and the files of packages that those import, and
332
- * so on. Only these become server functions of the app.
333
- */
334
- function reachableFiles(packages, appFiles, read) {
335
- const reached = /* @__PURE__ */ new Set();
336
- const names = new Set(packages.map((item) => item.name));
337
- const pending = [];
338
- const add = (file) => {
339
- if (file && !reached.has(file) && packageOf(packages, file)) {
340
- reached.add(file);
341
- pending.push(file);
342
- }
343
- };
344
- const resolve = (specifier, importer) => {
345
- if (specifier.startsWith(".")) {
346
- const stem = path.resolve(path.dirname(importer), specifier.split("?")[0]);
347
- const found = EXTENSIONS.map((extension) => stem + extension).find((candidate) => statSync(candidate, { throwIfNoEntry: false })?.isFile());
348
- return found && toPosix(realpathSync(found));
349
- }
350
- const name = splitSpecifier(specifier)?.name;
351
- return name && names.has(name) ? resolvePackageImport(specifier.split("?")[0], importer) : void 0;
352
- };
353
- const visit = (file, own) => {
354
- const source = read(file);
355
- if (source === void 0) return;
356
- for (const specifier of importSpecifiers(source)) {
357
- if (own && specifier.startsWith(".")) continue;
358
- try {
359
- add(resolve(specifier, file));
360
- } catch {}
361
- }
362
- };
363
- for (const file of appFiles) visit(file, true);
364
- while (pending.length > 0) visit(pending.pop(), false);
365
- return reached;
366
- }
249
+ //#region src/version.ts
250
+ /** The version of brumate, which the devtools show. `package.json` is next to `src` and `dist`. */
251
+ const BRUMATE_VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
367
252
  //#endregion
368
253
  //#region src/dev-error.ts
369
254
  /** The overlay payload of an error, with the file, line and lines around it for compile errors. */
@@ -428,11 +313,20 @@ function errorPage(error, server) {
428
313
  <script type="module">
429
314
  import { createHotContext } from '${base}@vite/client';
430
315
  const error = ${json};
431
- const Overlay = customElements.get('vite-error-overlay');
432
- if (Overlay) {
433
- document.body.append(new Overlay(error));
434
- } else {
435
- document.getElementById('brumate-error').textContent = [error.message, error.frame, error.stack].filter(Boolean).join('\\n\\n');
316
+ // The Errors tab of the devtools shows the error with its code. Vite's overlay is the fallback.
317
+ try {
318
+ const devtools = await import('${base}@id/brumate/devtools');
319
+ devtools.reportError(devtools.installDevtools(undefined, undefined, ${JSON.stringify({
320
+ version: BRUMATE_VERSION,
321
+ vite: version
322
+ })}), error, 'server');
323
+ } catch {
324
+ const Overlay = customElements.get('vite-error-overlay');
325
+ if (Overlay) {
326
+ document.body.append(new Overlay(error));
327
+ } else {
328
+ document.getElementById('brumate-error').textContent = [error.message, error.frame, error.stack].filter(Boolean).join('\\n\\n');
329
+ }
436
330
  }
437
331
  // A component that updates in place, after a fix, loads the page again.
438
332
  const hot = createHotContext('/@brumate/error');
@@ -444,9 +338,970 @@ hot.on('vite:beforeUpdate', () => location.reload());
444
338
  `;
445
339
  }
446
340
  //#endregion
341
+ //#region src/workbench-page.ts
342
+ /** The HTML of the workbench page. `base` is the path of the workbench, such as `/__brumate/workbench`. */
343
+ function workbenchPage(base) {
344
+ return `<!doctype html>
345
+ <html lang="en">
346
+ <head>
347
+ <meta charset="utf-8">
348
+ <meta name="viewport" content="width=device-width, initial-scale=1">
349
+ <title>Workbench · brumate</title>
350
+ <link rel="icon" type="image/svg+xml" href="data:image/svg+xml,${encodeURIComponent(LOGO.replace("<svg ", "<svg xmlns=\"http://www.w3.org/2000/svg\" "))}">
351
+ <style>
352
+ :root {
353
+ --bg: #121113; --surface: #19181a; --raised: #222023; --hover: #2a282c; --line: #2f2c31;
354
+ --text: #ece8e4; --dim: #a39a92; --faint: #6f6862; --accent: #ee7a3e; --accent-soft: #ee7a3e22;
355
+ --blue: #7cb7ff; --purple: #c49bff; --green: #7fd99a; --yellow: #ffd166; --red: #ff7a7a;
356
+ --mono: ui-monospace, SFMono-Regular, Menlo, monospace;
357
+ color-scheme: dark;
358
+ }
359
+ * { box-sizing: border-box; }
360
+ [hidden] { display: none !important; }
361
+ html, body { height: 100%; }
362
+ body {
363
+ margin: 0; display: grid; grid-template-columns: 260px minmax(0, 1fr) 300px;
364
+ background: var(--bg); color: var(--text); font: 13px/1.45 system-ui, -apple-system, sans-serif;
365
+ }
366
+ body.no-props { grid-template-columns: 260px minmax(0, 1fr); }
367
+ body.no-props #props { display: none; }
368
+ button, input, select, textarea { font: inherit; color: inherit; }
369
+ button:focus-visible, input:focus-visible, select:focus-visible, textarea:focus-visible {
370
+ outline: 2px solid var(--accent); outline-offset: 1px;
371
+ }
372
+ .mono { font-family: var(--mono); }
373
+
374
+ /* Sidebar */
375
+ #sidebar { display: flex; flex-direction: column; min-height: 0; border-right: 1px solid var(--line); background: var(--surface); }
376
+ .brand { display: flex; align-items: center; gap: 10px; padding: 16px 16px 12px; }
377
+ .brand .logo { display: block; width: 22px; height: 22px; }
378
+ .brand strong { font-size: 14px; }
379
+ .brand span { margin-left: auto; color: var(--faint); font-size: 12px; }
380
+ .search { margin: 0 12px 8px; position: relative; }
381
+ .search input {
382
+ width: 100%; padding: 7px 10px 7px 30px; border: 1px solid var(--line); border-radius: 8px;
383
+ background: var(--bg);
384
+ }
385
+ .search svg { position: absolute; left: 10px; top: 50%; transform: translateY(-50%); color: var(--faint); }
386
+ #tree { flex: 1; overflow: auto; padding: 4px 8px 16px; }
387
+ .group { margin-top: 10px; }
388
+ .group-head {
389
+ display: flex; align-items: center; gap: 6px; padding: 4px 8px; color: var(--faint);
390
+ font-size: 11px; font-weight: 600; letter-spacing: 0.04em; text-transform: uppercase;
391
+ }
392
+ .group-head .count { margin-left: auto; font-weight: 500; }
393
+ .item {
394
+ display: flex; align-items: center; gap: 8px; width: 100%; padding: 6px 8px; border: 0; border-radius: 6px;
395
+ background: none; text-align: left; cursor: pointer;
396
+ }
397
+ .item:hover { background: var(--hover); }
398
+ .item[aria-current="true"] { background: var(--accent-soft); box-shadow: inset 2px 0 0 var(--accent); }
399
+ .item[aria-current="true"] .label { color: #ffb48a; font-weight: 600; }
400
+ .item .glyph { flex: none; width: 16px; height: 16px; color: var(--faint); }
401
+ .item[aria-current="true"] .glyph { color: var(--accent); }
402
+ .item .label { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
403
+ .item .meta { margin-left: auto; color: var(--faint); font-size: 11px; white-space: nowrap; }
404
+ .env .item .label { color: var(--dim); }
405
+ .env .group-head { cursor: pointer; }
406
+ .env .group-head .chev { transition: transform 0.15s; }
407
+ .env.closed .group-head .chev { transform: rotate(-90deg); }
408
+ .env.closed .items { display: none; }
409
+ .kinds { display: flex; gap: 3px; margin-left: auto; }
410
+ .dot { width: 7px; height: 7px; border-radius: 50%; }
411
+ .note { padding: 6px 8px; color: var(--faint); font-size: 12px; }
412
+
413
+ /* Kinds of needs */
414
+ .k-server { --k: var(--blue); } .k-request { --k: var(--purple); } .k-route { --k: var(--green); }
415
+ .k-action { --k: var(--red); } .k-defer { --k: var(--accent); }
416
+ .k-dynamic { --k: var(--dim); } .k-component { --k: var(--faint); }
417
+ .dot { background: var(--k); }
418
+ .tag {
419
+ display: inline-flex; align-items: center; gap: 6px; padding: 2px 8px; border-radius: 999px;
420
+ background: color-mix(in srgb, var(--k) 16%, transparent); color: var(--k); font-size: 11px; font-weight: 600;
421
+ }
422
+
423
+ /* Canvas */
424
+ #main { display: grid; grid-template-rows: auto minmax(0, 1fr); min-width: 0; }
425
+ .toolbar {
426
+ display: flex; align-items: center; gap: 10px; min-height: 52px; padding: 8px 16px;
427
+ border-bottom: 1px solid var(--line); background: var(--surface);
428
+ }
429
+ .title { display: flex; align-items: baseline; gap: 10px; min-width: 0; }
430
+ .title h1 { margin: 0; font-size: 15px; font-weight: 650; white-space: nowrap; }
431
+ .title button { padding: 0; border: 0; background: none; color: var(--faint); font: 12px var(--mono); cursor: pointer;
432
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
433
+ .title button:hover { color: var(--blue); text-decoration: underline; }
434
+ .tools { display: flex; align-items: center; gap: 6px; margin-left: auto; }
435
+ .segment { display: flex; padding: 2px; border: 1px solid var(--line); border-radius: 8px; background: var(--bg); }
436
+ .segment button, .tool {
437
+ display: grid; place-items: center; height: 26px; min-width: 28px; padding: 0 8px; border: 0; border-radius: 6px;
438
+ background: none; color: var(--dim); cursor: pointer;
439
+ }
440
+ .segment button[aria-pressed="true"] { background: var(--raised); color: var(--text); }
441
+ .tool { border: 1px solid var(--line); background: var(--bg); }
442
+ .tool:hover, .segment button:hover { color: var(--text); }
443
+ .canvas { position: relative; display: grid; place-items: center; overflow: auto; padding: 24px; }
444
+ .canvas.dots { background: radial-gradient(circle, #ffffff14 1px, transparent 1px) 0 0 / 16px 16px, var(--bg); }
445
+ .canvas.light { background: #f4f1ec; }
446
+ .canvas.dark { background: #0b0a0b; }
447
+ .device {
448
+ width: 100%; height: 100%; border: 1px solid var(--line); border-radius: 10px; overflow: hidden;
449
+ background: #fff; box-shadow: 0 12px 40px #0006; transition: width 0.2s, height 0.2s;
450
+ }
451
+ .device iframe { display: block; width: 100%; height: 100%; border: 0; background: #fff; }
452
+ .size { position: absolute; right: 16px; bottom: 10px; color: var(--faint); font: 11px var(--mono); }
453
+
454
+ /* Cards on the canvas: the start, and a component that needs the environment */
455
+ .card {
456
+ width: min(520px, 100%); padding: 24px 26px; border: 1px solid var(--line); border-radius: 14px; background: var(--surface);
457
+ }
458
+ .card .eyebrow { color: var(--accent); font-size: 12px; font-weight: 600; }
459
+ .card h2 { margin: 6px 0 8px; font-size: 18px; }
460
+ .card p { margin: 0 0 14px; color: var(--dim); }
461
+ .needs { display: grid; gap: 8px; margin: 0 0 16px; padding: 0; list-style: none; }
462
+ .needs li { display: grid; grid-template-columns: auto 1fr; gap: 4px 12px; align-items: baseline;
463
+ padding: 10px 12px; border-radius: 10px; background: var(--raised); }
464
+ .needs .what { font-family: var(--mono); }
465
+ .needs .via { grid-column: 2; color: var(--faint); font-size: 12px; }
466
+ .hint { padding: 10px 12px; border-left: 2px solid var(--accent); border-radius: 0 8px 8px 0; background: var(--accent-soft);
467
+ color: var(--dim); font-size: 12px; }
468
+ .hint code { color: #ffb48a; }
469
+ .stats { display: flex; gap: 18px; margin-top: 4px; }
470
+ .stats div { color: var(--faint); font-size: 12px; }
471
+ .stats strong { display: block; color: var(--text); font-size: 22px; font-weight: 650; }
472
+
473
+ /* Props */
474
+ #props { display: flex; flex-direction: column; min-height: 0; border-left: 1px solid var(--line); background: var(--surface); }
475
+ .panel-head { display: flex; align-items: center; gap: 8px; min-height: 52px; padding: 8px 16px; border-bottom: 1px solid var(--line); }
476
+ .panel-head h2 { margin: 0; font-size: 13px; }
477
+ .panel-head button { margin-left: auto; }
478
+ #controls { flex: 1; overflow: auto; padding: 8px 0; }
479
+ .prop { padding: 10px 16px; border-bottom: 1px solid #ffffff08; }
480
+ .prop-head { display: flex; align-items: center; gap: 6px; margin-bottom: 6px; }
481
+ .prop-head .name { color: #ffc28f; font-family: var(--mono); }
482
+ .prop-head .req { color: var(--accent); }
483
+ .prop-head .type { margin-left: auto; color: var(--faint); font: 11px var(--mono); }
484
+ .prop-head .reset { padding: 0 4px; border: 0; background: none; color: var(--faint); cursor: pointer; visibility: hidden; }
485
+ .prop.changed .reset { visibility: visible; }
486
+ .prop-head .reset:hover { color: var(--text); }
487
+ .prop input[type="text"], .prop input[type="number"], .prop select, .prop textarea {
488
+ width: 100%; padding: 6px 8px; border: 1px solid var(--line); border-radius: 6px; background: var(--bg);
489
+ }
490
+ .prop textarea { min-height: 76px; resize: vertical; font: 12px/1.5 var(--mono); }
491
+ .prop .invalid { border-color: var(--red); }
492
+ .error { margin-top: 4px; color: var(--red); font-size: 11px; }
493
+ .switch { position: relative; display: inline-flex; align-items: center; gap: 8px; cursor: pointer; color: var(--dim); }
494
+ .switch input { position: absolute; opacity: 0; }
495
+ .switch span { width: 30px; height: 18px; border-radius: 999px; background: var(--raised); border: 1px solid var(--line); position: relative; transition: background 0.15s; }
496
+ .switch span::after { content: ''; position: absolute; top: 2px; left: 2px; width: 12px; height: 12px; border-radius: 50%; background: var(--dim); transition: transform 0.15s; }
497
+ .switch input:checked + span { background: var(--accent); border-color: var(--accent); }
498
+ .switch input:checked + span::after { transform: translateX(12px); background: #fff; }
499
+ .switch input:focus-visible + span { outline: 2px solid var(--accent); outline-offset: 1px; }
500
+ .choices { display: flex; flex-wrap: wrap; gap: 4px; }
501
+ .choices button { padding: 3px 9px; border: 1px solid var(--line); border-radius: 6px; background: var(--bg); color: var(--dim); cursor: pointer; font: 12px var(--mono); }
502
+ .choices button[aria-pressed="true"] { border-color: var(--accent); background: var(--accent-soft); color: #ffb48a; }
503
+ .empty-props { padding: 16px; color: var(--faint); }
504
+ .stories { padding: 12px 16px; border-bottom: 1px solid var(--line); }
505
+ .stories-head { margin-bottom: 8px; color: var(--faint); font-size: 11px; font-weight: 600; letter-spacing: 0.04em; text-transform: uppercase; }
506
+ .stories .choices button { font-family: inherit; }
507
+ .stories-error { color: var(--red); font-size: 12px; }
508
+ .footer { padding: 10px 16px; border-top: 1px solid var(--line); color: var(--faint); font-size: 11px; }
509
+ </style>
510
+ </head>
511
+ <body class="no-props">
512
+ <aside id="sidebar">
513
+ <div class="brand"><span class="logo">${LOGO}</span><strong>Workbench</strong><span id="total"></span></div>
514
+ <label class="search">
515
+ <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true"><circle cx="7" cy="7" r="5" stroke="currentColor" stroke-width="1.5"/><path d="m11 11 3 3" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg>
516
+ <input id="filter" type="search" placeholder="Find a component" aria-label="Find a component">
517
+ </label>
518
+ <nav id="tree" aria-label="Components"></nav>
519
+ </aside>
520
+ <main id="main">
521
+ <div class="toolbar">
522
+ <div class="title"><h1 id="name">Workbench</h1><button id="file" type="button" title="Open in your editor" hidden></button></div>
523
+ <div class="tools" id="tools" hidden>
524
+ <div class="segment" role="group" aria-label="Width">
525
+ <button type="button" data-width="" aria-pressed="true" title="Fill the canvas">Fill</button>
526
+ <button type="button" data-width="390" title="Phone, 390 px">390</button>
527
+ <button type="button" data-width="768" title="Tablet, 768 px">768</button>
528
+ <button type="button" data-width="1280" title="Desktop, 1280 px">1280</button>
529
+ </div>
530
+ <div class="segment" role="group" aria-label="Background">
531
+ <button type="button" data-canvas="dots" aria-pressed="true" title="Dots">Dots</button>
532
+ <button type="button" data-canvas="light" title="Light">Light</button>
533
+ <button type="button" data-canvas="dark" title="Dark">Dark</button>
534
+ </div>
535
+ <button class="tool" id="reload" type="button" title="Render again">
536
+ <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true"><path d="M13.5 8a5.5 5.5 0 1 1-1.6-3.9M13.5 2.5v3h-3" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
537
+ </button>
538
+ <a class="tool" id="open" target="_blank" title="Open alone in a new tab">
539
+ <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true"><path d="M9 3h4v4M13 3 7.5 8.5M12 9.5V13H3V4h3.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
540
+ </a>
541
+ </div>
542
+ </div>
543
+ <div class="canvas dots" id="canvas"></div>
544
+ </main>
545
+ <aside id="props">
546
+ <div class="panel-head"><h2>Props</h2><button class="tool" id="resetAll" type="button" title="Reset every prop">Reset</button></div>
547
+ <div id="stories" class="stories" hidden></div>
548
+ <div id="controls"></div>
549
+ <div class="footer">From the type of <span class="mono">$props&lt;T&gt;()</span>. Function props have no control.</div>
550
+ </aside>
551
+ <script type="module">
552
+ const base = ${JSON.stringify(base)};
553
+ const $ = (id) => document.getElementById(id);
554
+ const make = (tag, props = {}, ...children) => {
555
+ const node = document.createElement(tag);
556
+ for (const [key, value] of Object.entries(props)) {
557
+ if (key === 'class') node.className = value;
558
+ else if (key.startsWith('on')) node.addEventListener(key.slice(2), value);
559
+ else if (value !== undefined && value !== false) node.setAttribute(key, value === true ? '' : value);
560
+ }
561
+ node.append(...children.filter((child) => child !== undefined && child !== null));
562
+ return node;
563
+ };
564
+ const svg = (markup) => {
565
+ const holder = document.createElement('span');
566
+ holder.innerHTML = markup;
567
+ return holder.firstChild;
568
+ };
569
+ const COMPONENT = '<svg class="glyph" viewBox="0 0 16 16" fill="none"><rect x="2.5" y="2.5" width="11" height="11" rx="3" stroke="currentColor" stroke-width="1.4"/><path d="M5.5 8h5" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/></svg>';
570
+ const LOCKED = '<svg class="glyph" viewBox="0 0 16 16" fill="none"><rect x="3" y="7" width="10" height="7" rx="2" stroke="currentColor" stroke-width="1.4"/><path d="M5.5 7V5a2.5 2.5 0 0 1 5 0v2" stroke="currentColor" stroke-width="1.4"/></svg>';
571
+ const FOLDER = '<svg width="12" height="12" viewBox="0 0 16 16" fill="none"><path d="M2 4.5A1.5 1.5 0 0 1 3.5 3h3l1.5 1.5h4.5A1.5 1.5 0 0 1 14 6v5.5a1.5 1.5 0 0 1-1.5 1.5h-9A1.5 1.5 0 0 1 2 11.5z" stroke="currentColor" stroke-width="1.4"/></svg>';
572
+ const CHEVRON = '<svg class="chev" width="10" height="10" viewBox="0 0 16 16" fill="none"><path d="m4 6 4 4 4-4" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></svg>';
573
+
574
+ // What each kind of need is, in words, for the tags and the card.
575
+ const KINDS = {
576
+ server: ['Server', 'calls the server function'],
577
+ request: ['Request', 'reads the request with'],
578
+ route: ['Route', 'reads the route with'],
579
+ action: ['Action', 'has the form action'],
580
+ defer: ['Defer', 'has a block that the server renders later:'],
581
+ dynamic: ['Dynamic tag', 'renders a dynamic tag'],
582
+ component: ['Unknown', 'renders a component that the workbench cannot find:'],
583
+ };
584
+ const TYPES = { text: 'string', number: 'number', boolean: 'boolean', json: 'JSON' };
585
+
586
+ const components = await (await fetch(base + '/components')).json();
587
+ const ready = components.filter((component) => component.selfContained);
588
+ const others = components.filter((component) => !component.selfContained);
589
+ let current;
590
+ // The story of the component that is picked, whose props start the controls.
591
+ let story;
592
+ let values = {};
593
+ let start = {};
594
+ let timer;
595
+ let width = '';
596
+ let envOpen = false;
597
+
598
+ function frameUrl() {
599
+ return base + '/frame?file=' + encodeURIComponent(current.file) + '&props=' + encodeURIComponent(JSON.stringify(values));
600
+ }
601
+
602
+ function render() {
603
+ const url = frameUrl();
604
+ $('open').href = url;
605
+ let frame = $('canvas').querySelector('iframe');
606
+ if (!frame) {
607
+ frame = make('iframe', { title: current.name });
608
+ $('canvas').replaceChildren(make('div', { class: 'device', id: 'device' }, frame), make('div', { class: 'size', id: 'size' }));
609
+ applyWidth();
610
+ }
611
+ frame.src = url;
612
+ }
613
+
614
+ function later() {
615
+ clearTimeout(timer);
616
+ timer = setTimeout(render, 200);
617
+ }
618
+
619
+ function applyWidth() {
620
+ const device = $('device');
621
+ if (!device) return;
622
+ device.style.width = width ? width + 'px' : '100%';
623
+ device.style.maxWidth = '100%';
624
+ $('size').textContent = width ? width + ' px' : '';
625
+ }
626
+
627
+ function set(name, value) {
628
+ if (value === undefined) delete values[name];
629
+ else values[name] = value;
630
+ for (const row of $('controls').querySelectorAll('.prop')) {
631
+ row.classList.toggle('changed', JSON.stringify(values[row.dataset.name]) !== JSON.stringify(start[row.dataset.name]));
632
+ }
633
+ later();
634
+ }
635
+
636
+ function input(spec) {
637
+ const value = values[spec.name];
638
+ if (spec.kind === 'boolean') {
639
+ const box = make('input', { type: 'checkbox', onchange: () => set(spec.name, box.checked) });
640
+ box.checked = Boolean(value);
641
+ return make('label', { class: 'switch' }, box, make('span'), spec.name);
642
+ }
643
+ if (spec.kind === 'choice') {
644
+ const options = spec.optional ? [undefined, ...spec.options] : spec.options;
645
+ if (options.length <= 5) {
646
+ const group = make('div', { class: 'choices', role: 'group', 'aria-label': spec.name });
647
+ for (const option of options) {
648
+ const button = make('button', {
649
+ type: 'button',
650
+ 'aria-pressed': String(option === value),
651
+ onclick: () => {
652
+ for (const other of group.children) other.setAttribute('aria-pressed', String(other === button));
653
+ set(spec.name, option);
654
+ },
655
+ }, option === undefined ? 'none' : String(option));
656
+ group.append(button);
657
+ }
658
+ return group;
659
+ }
660
+ const select = make('select', { 'aria-label': spec.name, onchange: () => set(spec.name, options[select.selectedIndex]) });
661
+ for (const option of options) select.append(make('option', {}, option === undefined ? 'none' : String(option)));
662
+ select.selectedIndex = Math.max(0, options.indexOf(value));
663
+ return select;
664
+ }
665
+ if (spec.kind === 'json') {
666
+ const area = make('textarea', { spellcheck: 'false', 'aria-label': spec.name });
667
+ const error = make('div', { class: 'error', hidden: true });
668
+ area.value = value === undefined ? '' : JSON.stringify(value, null, 2);
669
+ area.addEventListener('input', () => {
670
+ if (area.value.trim() === '') {
671
+ area.classList.remove('invalid');
672
+ error.hidden = true;
673
+ set(spec.name, undefined);
674
+ return;
675
+ }
676
+ try {
677
+ const parsed = JSON.parse(area.value);
678
+ area.classList.remove('invalid');
679
+ error.hidden = true;
680
+ set(spec.name, parsed);
681
+ } catch (problem) {
682
+ area.classList.add('invalid');
683
+ error.hidden = false;
684
+ error.textContent = String(problem.message ?? problem);
685
+ }
686
+ });
687
+ return make('div', {}, area, error);
688
+ }
689
+ const field = make('input', {
690
+ type: spec.kind === 'number' ? 'number' : 'text',
691
+ 'aria-label': spec.name,
692
+ placeholder: spec.optional ? 'undefined' : '',
693
+ oninput: () => set(spec.name, field.value === '' ? undefined : spec.kind === 'number' ? Number(field.value) : field.value),
694
+ });
695
+ field.value = value === undefined ? '' : String(value);
696
+ return field;
697
+ }
698
+
699
+ function typeOf(spec) {
700
+ if (spec.kind === 'choice') return spec.options.map((option) => JSON.stringify(option)).join(' | ');
701
+ return TYPES[spec.kind];
702
+ }
703
+
704
+ function stories() {
705
+ const box = $('stories');
706
+ box.replaceChildren();
707
+ box.hidden = !current.stories?.length && !current.storiesError;
708
+ if (current.storiesError) {
709
+ box.append(make('div', { class: 'stories-error' }, 'The stories do not load: ' + current.storiesError));
710
+ return;
711
+ }
712
+ if (!current.stories?.length) return;
713
+ box.append(make('div', { class: 'stories-head' }, 'Stories'));
714
+ const list = make('div', { class: 'choices' });
715
+ for (const item of [{ name: 'Default', props: {} }, ...current.stories]) {
716
+ list.append(make('button', {
717
+ type: 'button',
718
+ 'aria-pressed': String((story?.name ?? 'Default') === item.name),
719
+ onclick: () => pickStory(item.name === 'Default' ? undefined : item),
720
+ }, item.name));
721
+ }
722
+ box.append(list);
723
+ }
724
+
725
+ /** Starts the controls from the props of a story, or from the defaults without one. */
726
+ function pickStory(next) {
727
+ story = next;
728
+ start = { ...initial(current), ...(next?.props ?? {}) };
729
+ values = structuredClone(start);
730
+ history.replaceState(null, '', '#' + current.file + (next ? '@' + next.name : ''));
731
+ stories();
732
+ controls();
733
+ render();
734
+ }
735
+
736
+ function controls() {
737
+ const box = $('controls');
738
+ box.replaceChildren();
739
+ if (current.unreadProps) {
740
+ box.append(make('div', { class: 'empty-props' }, 'The workbench cannot read the type of the props, such as a type that the file imports. Declare it in the file to get controls.'));
741
+ return;
742
+ }
743
+ if (!current.controls.length) {
744
+ box.append(make('div', { class: 'empty-props' }, 'This component takes no props that the workbench can set.'));
745
+ return;
746
+ }
747
+ for (const spec of current.controls) {
748
+ const reset = make('button', { class: 'reset', type: 'button', title: 'Reset', onclick: () => {
749
+ set(spec.name, start[spec.name]);
750
+ controls();
751
+ } }, '↺');
752
+ box.append(make('div', { class: 'prop', 'data-name': spec.name },
753
+ make('div', { class: 'prop-head' },
754
+ make('span', { class: 'name' }, spec.name),
755
+ spec.optional ? undefined : make('span', { class: 'req', title: 'Required' }, '*'),
756
+ reset,
757
+ make('span', { class: 'type', title: typeOf(spec) }, typeOf(spec).length > 28 ? 'union' : typeOf(spec))),
758
+ input(spec)));
759
+ }
760
+ }
761
+
762
+ function initial(component) {
763
+ const props = {};
764
+ for (const spec of component.controls) {
765
+ if (spec.default !== undefined) props[spec.name] = spec.default;
766
+ // A required prop gets a value, so the component renders at once.
767
+ else if (!spec.optional) {
768
+ props[spec.name] =
769
+ spec.kind === 'text' ? spec.name
770
+ : spec.kind === 'number' ? 0
771
+ : spec.kind === 'boolean' ? false
772
+ : spec.kind === 'choice' ? spec.options[0]
773
+ : (spec.empty ?? null);
774
+ }
775
+ }
776
+ return props;
777
+ }
778
+
779
+ function title(component) {
780
+ $('name').textContent = component ? component.name : 'Workbench';
781
+ $('file').hidden = !component;
782
+ if (component) $('file').textContent = component.label ?? component.file;
783
+ }
784
+
785
+ function select(component) {
786
+ current = component;
787
+ for (const item of $('tree').querySelectorAll('.item')) item.setAttribute('aria-current', String(item.dataset.file === component.file));
788
+ title(component);
789
+ history.replaceState(null, '', '#' + component.file);
790
+ if (!component.selfContained) {
791
+ document.body.classList.add('no-props');
792
+ $('tools').hidden = true;
793
+ explain(component);
794
+ return;
795
+ }
796
+ document.body.classList.remove('no-props');
797
+ $('tools').hidden = false;
798
+ $('canvas').replaceChildren();
799
+ pickStory(undefined);
800
+ }
801
+
802
+ function explain(component) {
803
+ const list = make('ul', { class: 'needs' });
804
+ for (const need of component.needs) {
805
+ const [label, words] = KINDS[need.kind] ?? [need.kind, ''];
806
+ list.append(make('li', {},
807
+ make('span', { class: 'tag k-' + need.kind }, label),
808
+ make('span', {}, words + ' ', make('span', { class: 'what' }, need.name)),
809
+ need.via ? make('span', { class: 'via' }, 'through ' + need.via) : undefined));
810
+ }
811
+ const hint = make('div', { class: 'hint' });
812
+ hint.append('Test it in a page: ', make('code', {}, 'visit()'), ' from ', make('code', {}, 'brumate/testing'),
813
+ ', or an end-to-end test. Its parts that depend only on their props show here.');
814
+ $('canvas').replaceChildren(make('div', { class: 'card' },
815
+ make('div', { class: 'eyebrow' }, 'Needs the environment'),
816
+ make('h2', {}, component.name + ' needs more than its props'),
817
+ make('p', {}, 'The workbench renders a component with nothing around it: no request, no route, no server data and no providers. This one needs:'),
818
+ list, hint));
819
+ }
820
+
821
+ function welcome() {
822
+ const stats = make('div', { class: 'stats' },
823
+ make('div', {}, make('strong', {}, String(ready.length)), 'can show here'),
824
+ make('div', {}, make('strong', {}, String(others.length)), 'need the environment'));
825
+ $('canvas').replaceChildren(make('div', { class: 'card' },
826
+ make('div', { class: 'eyebrow' }, 'Workbench'),
827
+ make('h2', {}, 'Pick a component'),
828
+ make('p', {}, 'Each component renders on the server with the props that you set, and resumes in the browser, as it does in a page.'),
829
+ stats));
830
+ }
831
+
832
+ function item(component) {
833
+ const kinds = [...new Set(component.needs.map((need) => need.kind))];
834
+ return make('button', {
835
+ class: 'item', type: 'button', 'data-file': component.file,
836
+ 'aria-current': String(component === current),
837
+ title: component.file,
838
+ onclick: () => select(component),
839
+ },
840
+ svg(component.selfContained ? COMPONENT : LOCKED),
841
+ make('span', { class: 'label' }, component.name),
842
+ component.selfContained
843
+ ? make('span', { class: 'meta' }, component.stories?.length
844
+ ? component.stories.length + (component.stories.length === 1 ? ' story' : ' stories')
845
+ : component.controls.length ? component.controls.length + (component.controls.length === 1 ? ' prop' : ' props') : '')
846
+ : make('span', { class: 'kinds' }, ...kinds.map((kind) => make('span', { class: 'dot k-' + kind, title: KINDS[kind]?.[0] ?? kind }))));
847
+ }
848
+
849
+ function tree() {
850
+ const query = $('filter').value.trim().toLowerCase();
851
+ const match = (component) => !query || component.name.toLowerCase().includes(query) || component.file.toLowerCase().includes(query);
852
+ const box = $('tree');
853
+ box.replaceChildren();
854
+ const folders = new Map();
855
+ for (const component of ready.filter(match)) {
856
+ const folder = component.group || '.';
857
+ if (!folders.has(folder)) folders.set(folder, []);
858
+ folders.get(folder).push(component);
859
+ }
860
+ for (const [folder, items] of [...folders].sort(([a], [b]) => a.localeCompare(b))) {
861
+ box.append(make('div', { class: 'group' },
862
+ make('div', { class: 'group-head' }, svg(FOLDER), folder, make('span', { class: 'count' }, String(items.length))),
863
+ ...items.map(item)));
864
+ }
865
+ if (!folders.size) box.append(make('div', { class: 'note' }, query ? 'No component matches.' : 'No component depends only on its props.'));
866
+ const shown = others.filter(match);
867
+ if (shown.length) {
868
+ const group = make('div', { class: 'group env' + (envOpen || query ? '' : ' closed') });
869
+ const head = make('div', { class: 'group-head', role: 'button', tabindex: '0', 'aria-expanded': String(envOpen || Boolean(query)) },
870
+ svg(CHEVRON), 'Needs the environment', make('span', { class: 'count' }, String(shown.length)));
871
+ const toggle = () => {
872
+ envOpen = group.classList.toggle('closed') === false;
873
+ head.setAttribute('aria-expanded', String(envOpen));
874
+ };
875
+ head.addEventListener('click', toggle);
876
+ head.addEventListener('keydown', (event) => { if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); toggle(); } });
877
+ group.append(head, make('div', { class: 'items' }, ...shown.map(item)));
878
+ box.append(group);
879
+ }
880
+ }
881
+
882
+ $('total').textContent = components.length + ' components';
883
+ $('filter').addEventListener('input', tree);
884
+ $('file').addEventListener('click', () => {
885
+ if (current) fetch('/__open-in-editor?file=' + encodeURIComponent(current.file));
886
+ });
887
+ $('reload').addEventListener('click', render);
888
+ $('resetAll').addEventListener('click', () => {
889
+ values = structuredClone(start);
890
+ controls();
891
+ render();
892
+ });
893
+ for (const button of document.querySelectorAll('[data-width]')) {
894
+ button.addEventListener('click', () => {
895
+ width = button.dataset.width;
896
+ for (const other of document.querySelectorAll('[data-width]')) other.setAttribute('aria-pressed', String(other === button));
897
+ applyWidth();
898
+ });
899
+ }
900
+ for (const button of document.querySelectorAll('[data-canvas]')) {
901
+ button.addEventListener('click', () => {
902
+ $('canvas').className = 'canvas ' + button.dataset.canvas;
903
+ for (const other of document.querySelectorAll('[data-canvas]')) other.setAttribute('aria-pressed', String(other === button));
904
+ });
905
+ }
906
+ // The hash names the component, so a link or the back button can pick one.
907
+ function fromHash() {
908
+ // The hash is the file, and the name of a story after \`@\`.
909
+ const [chosen, storyName] = decodeURIComponent(location.hash.slice(1)).split('@');
910
+ const found = components.find((component) => component.file === chosen);
911
+ if (!found) {
912
+ welcome();
913
+ return;
914
+ }
915
+ const named = found.stories?.find((item) => item.name === storyName);
916
+ if (found === current && named === story) return;
917
+ if (!found.selfContained && !envOpen) {
918
+ envOpen = true;
919
+ tree();
920
+ }
921
+ if (found !== current) select(found);
922
+ if (found.selfContained && named !== story) pickStory(named);
923
+ }
924
+ tree();
925
+ fromHash();
926
+ addEventListener('hashchange', fromHash);
927
+ <\/script>
928
+ </body>
929
+ </html>`;
930
+ }
931
+ //#endregion
932
+ //#region src/workbench.ts
933
+ /** True for a string literal, such as `'button'`. */
934
+ function isElementName(node) {
935
+ return node?.type === "Literal" && typeof node.value === "string";
936
+ }
937
+ /** The props that destructure with an element name as their default, such as `as = 'button'`. */
938
+ function elementDefaults(file) {
939
+ const names = /* @__PURE__ */ new Set();
940
+ for (const statement of file.instanceScript?.program.body ?? []) {
941
+ if (statement.type !== "VariableDeclaration") continue;
942
+ for (const declarator of statement.declarations) {
943
+ const call = declarator.init;
944
+ if (call?.type !== "CallExpression" || call.callee.type !== "Identifier" || call.callee.name !== "$props" || declarator.id.type !== "ObjectPattern") continue;
945
+ for (const property of declarator.id.properties) if (property.type === "Property" && property.value.type === "AssignmentPattern" && property.value.left.type === "Identifier" && isElementName(property.value.right)) names.add(property.value.left.name);
946
+ }
947
+ }
948
+ return names;
949
+ }
950
+ /**
951
+ * True for the tag of a dynamic tag that renders an element when the caller gives none: a
952
+ * string, `as ?? 'button'`, or a prop with an element as its default. A part such as a button
953
+ * that takes `as` depends only on its props this way.
954
+ */
955
+ function hasElementDefault(tag, defaults) {
956
+ if (isElementName(tag)) return true;
957
+ if (tag.type === "Identifier") return defaults.has(tag.name);
958
+ if (tag.type === "LogicalExpression" && (tag.operator === "??" || tag.operator === "||")) return isElementName(tag.right) || hasElementDefault(tag.right, defaults);
959
+ if (tag.type === "ConditionalExpression") return hasElementDefault(tag.consequent, defaults) && hasElementDefault(tag.alternate, defaults);
960
+ return tag.type === "ParenthesizedExpression" && hasElementDefault(tag.expression, defaults);
961
+ }
962
+ /** The needs of one file, without those of the components that it renders. */
963
+ function ownNeeds(file, options) {
964
+ const needs = [];
965
+ const model = analyze(file);
966
+ for (const declaration of model.declarations) if (declaration.kind === "server-function") needs.push({
967
+ kind: "server",
968
+ name: declaration.name
969
+ });
970
+ else if (declaration.kind === "action") needs.push({
971
+ kind: "action",
972
+ name: declaration.name
973
+ });
974
+ else if (declaration.imported) {
975
+ const { source, name } = declaration.imported;
976
+ if (source === "brumate/server") needs.push({
977
+ kind: "request",
978
+ name
979
+ });
980
+ else if (options.serverImport?.(file.filename, source, name)) needs.push({
981
+ kind: "server",
982
+ name
983
+ });
984
+ }
985
+ const namespaces = /* @__PURE__ */ new Map();
986
+ for (const script of [file.moduleScript, file.instanceScript]) for (const statement of script?.program.body ?? []) {
987
+ if (statement.type !== "ImportDeclaration" || statement.importKind === "type") continue;
988
+ for (const specifier of statement.specifiers) if (specifier.type === "ImportNamespaceSpecifier") namespaces.set(specifier.local.start, statement.source.value);
989
+ }
990
+ for (const declaration of model.declarations) {
991
+ const source = namespaces.get(declaration.range.start);
992
+ if (declaration.kind !== "import" || source === void 0 || declaration.reads.length === 0) continue;
993
+ const name = `* as ${declaration.name}`;
994
+ if (source === "brumate/server") needs.push({
995
+ kind: "request",
996
+ name
997
+ });
998
+ else if (options.serverImport?.(file.filename, source, "*")) needs.push({
999
+ kind: "server",
1000
+ name
1001
+ });
1002
+ }
1003
+ const functions = [];
1004
+ const calls = [];
1005
+ walk([
1006
+ file.moduleScript?.program,
1007
+ file.instanceScript?.program,
1008
+ file.children,
1009
+ file.templates
1010
+ ], (node) => {
1011
+ if (node.type === "ArrowFunctionExpression" || node.type === "FunctionExpression" || node.type === "FunctionDeclaration") functions.push(node);
1012
+ else if (node.type === "CallExpression" && node.callee.type === "Identifier" && (node.callee.name === "$route" || node.callee.name === "$navigation")) calls.push(node);
1013
+ });
1014
+ for (const call of calls) {
1015
+ let inside = false;
1016
+ for (const fn of functions) if (fn.start <= call.start && call.end <= fn.end) {
1017
+ inside = true;
1018
+ break;
1019
+ }
1020
+ if (!inside) needs.push({
1021
+ kind: "route",
1022
+ name: call.callee.name
1023
+ });
1024
+ }
1025
+ const defaults = elementDefaults(file);
1026
+ function visit(node) {
1027
+ if (node.kind === "defer") needs.push({
1028
+ kind: "defer",
1029
+ name: "#defer"
1030
+ });
1031
+ else if (node.kind === "dynamic" && !hasElementDefault(node.tag.ast, defaults)) needs.push({
1032
+ kind: "dynamic",
1033
+ name: "<{…}>"
1034
+ });
1035
+ }
1036
+ forEachNode(file.children, visit);
1037
+ for (const template of file.templates) forEachNode(template.body.children, visit);
1038
+ return needs;
1039
+ }
1040
+ /** The import specifiers of the components that a file renders. */
1041
+ function renderedComponents(file) {
1042
+ const sources = /* @__PURE__ */ new Set();
1043
+ function visit(node) {
1044
+ if (node.kind === "component") {
1045
+ const source = importSource(file, node.name.split(".")[0]);
1046
+ if (source) sources.add(source);
1047
+ }
1048
+ }
1049
+ forEachNode(file.children, visit);
1050
+ for (const template of file.templates) forEachNode(template.body.children, visit);
1051
+ return sources;
1052
+ }
1053
+ function key(need) {
1054
+ return `${need.kind}:${need.name}`;
1055
+ }
1056
+ /**
1057
+ * Classifies every component of a project, by file. A file that does not parse or analyze is
1058
+ * not classified, because the workbench could not render it either.
1059
+ */
1060
+ function classifyComponents(files, options = {}) {
1061
+ const resolve = options.resolve ?? resolveRelative;
1062
+ const needs = /* @__PURE__ */ new Map();
1063
+ const children = /* @__PURE__ */ new Map();
1064
+ for (const [filename, source] of files) {
1065
+ let file;
1066
+ let own;
1067
+ try {
1068
+ file = parse(source, { filename });
1069
+ own = ownNeeds(file, options);
1070
+ } catch {
1071
+ continue;
1072
+ }
1073
+ const map = /* @__PURE__ */ new Map();
1074
+ for (const need of own) map.set(key(need), need);
1075
+ const found = [];
1076
+ for (const specifier of renderedComponents(file)) {
1077
+ const target = resolve(specifier, filename);
1078
+ if (target !== void 0 && files.has(target)) found.push(target);
1079
+ else if (specifier.endsWith(".brm")) map.set(`component:${specifier}`, {
1080
+ kind: "component",
1081
+ name: specifier
1082
+ });
1083
+ }
1084
+ needs.set(filename, map);
1085
+ children.set(filename, found);
1086
+ }
1087
+ for (let changed = true; changed;) {
1088
+ changed = false;
1089
+ for (const [filename, map] of needs) for (const child of children.get(filename)) for (const need of needs.get(child)?.values() ?? []) {
1090
+ const id = key(need);
1091
+ if (!map.has(id)) {
1092
+ map.set(id, {
1093
+ ...need,
1094
+ via: child
1095
+ });
1096
+ changed = true;
1097
+ }
1098
+ }
1099
+ }
1100
+ const result = /* @__PURE__ */ new Map();
1101
+ for (const [filename, map] of needs) {
1102
+ const list = [...map.values()];
1103
+ result.set(filename, {
1104
+ selfContained: list.length === 0,
1105
+ needs: list
1106
+ });
1107
+ }
1108
+ return result;
1109
+ }
1110
+ /** The interface or type alias of the scripts that has this name. */
1111
+ function localType(name, file) {
1112
+ for (const script of [file.moduleScript, file.instanceScript]) for (let statement of script?.program.body ?? []) {
1113
+ if (statement.type === "ExportNamedDeclaration" && statement.declaration) statement = statement.declaration;
1114
+ if ((statement.type === "TSInterfaceDeclaration" || statement.type === "TSTypeAliasDeclaration") && statement.id.name === name) return statement;
1115
+ }
1116
+ }
1117
+ /**
1118
+ * The name of a property or a method of a type, or undefined for a computed one or a signature
1119
+ * without a name. A method replaces a prop of the same name that its interface extends.
1120
+ */
1121
+ function memberName(member) {
1122
+ if (member.type !== "TSPropertySignature" && member.type !== "TSMethodSignature" || member.computed) return;
1123
+ return member.key.type === "Identifier" ? member.key.name : String(member.key.value);
1124
+ }
1125
+ /**
1126
+ * The members of the type of `$props<T>()`: a literal, an interface or alias of the scripts and
1127
+ * what it extends, an intersection of those, or `Partial` of one. Undefined for a type that the
1128
+ * workbench cannot read, such as one that the file imports.
1129
+ */
1130
+ /**
1131
+ * Merges lists of members by name. A later member takes the place of an earlier one with the
1132
+ * same name. With `required`, as for an intersection, the prop is required when any list
1133
+ * requires it.
1134
+ */
1135
+ function mergeMembers(lists, required) {
1136
+ const byName = /* @__PURE__ */ new Map();
1137
+ for (const list of lists) for (const member of list) {
1138
+ const id = memberName(member) ?? Symbol("member");
1139
+ const before = byName.get(id);
1140
+ byName.set(id, required && before && !(before.optional && member.optional) ? {
1141
+ ...member,
1142
+ optional: false
1143
+ } : member);
1144
+ }
1145
+ return [...byName.values()];
1146
+ }
1147
+ function propsMembers(type, file, seen = /* @__PURE__ */ new Set(), known = /* @__PURE__ */ new Map()) {
1148
+ if (type.type === "TSTypeLiteral") return type.members;
1149
+ if (type.type === "TSIntersectionType") {
1150
+ const lists = [];
1151
+ for (const item of type.types) {
1152
+ const found = propsMembers(item, file, seen, known);
1153
+ if (!found) return;
1154
+ lists.push(found);
1155
+ }
1156
+ return mergeMembers(lists, true);
1157
+ }
1158
+ if (type.type !== "TSTypeReference" || type.typeName.type !== "Identifier") return;
1159
+ const name = type.typeName.name;
1160
+ const argument = type.typeArguments?.params[0];
1161
+ if (name !== "Partial" && type.typeArguments) return;
1162
+ if (name === "Partial" && argument) {
1163
+ const members = propsMembers(argument, file, seen, known);
1164
+ if (!members) return;
1165
+ const optional = [];
1166
+ for (const member of members) optional.push({
1167
+ ...member,
1168
+ optional: true
1169
+ });
1170
+ return optional;
1171
+ }
1172
+ if (known.has(name)) return known.get(name);
1173
+ const declaration = seen.has(name) ? void 0 : localType(name, file);
1174
+ if (!declaration || declaration.typeParameters) return;
1175
+ const path = new Set(seen).add(name);
1176
+ let members;
1177
+ if (declaration.type === "TSTypeAliasDeclaration") members = propsMembers(declaration.typeAnnotation, file, path, known);
1178
+ else if (declaration.type === "TSInterfaceDeclaration") {
1179
+ const lists = [];
1180
+ let readable = true;
1181
+ for (const heritage of declaration.extends ?? []) {
1182
+ const found = heritage.expression.type === "Identifier" ? propsMembers({
1183
+ type: "TSTypeReference",
1184
+ typeName: heritage.expression,
1185
+ typeArguments: heritage.typeArguments
1186
+ }, file, path, known) : void 0;
1187
+ if (!found) {
1188
+ readable = false;
1189
+ break;
1190
+ }
1191
+ lists.push(found);
1192
+ }
1193
+ members = readable ? mergeMembers([...lists, declaration.body.body], false) : void 0;
1194
+ }
1195
+ known.set(name, members);
1196
+ return members;
1197
+ }
1198
+ /** The value of a literal default, such as `'info'` in `{ tone = 'info' }`. */
1199
+ function literalValue(node) {
1200
+ if (node.type === "Literal") return node.value;
1201
+ if (node.type === "TemplateLiteral" && node.expressions.length === 0) return node.quasis[0]?.value.cooked;
1202
+ if (node.type === "UnaryExpression" && node.operator === "-" && node.argument.type === "Literal") return -Number(node.argument.value);
1203
+ }
1204
+ /** The control for a type, or undefined for a function, which the workbench cannot make. */
1205
+ function getControl(type, file, seen = /* @__PURE__ */ new Set()) {
1206
+ if (!type) return { kind: "json" };
1207
+ if (type.type === "TSTypeReference" && type.typeName.type === "Identifier" && type.typeName.name === "Bindable" && type.typeArguments?.params[0]) return getControl(type.typeArguments.params[0], file, seen);
1208
+ switch (type.type) {
1209
+ case "TSStringKeyword": return { kind: "text" };
1210
+ case "TSNumberKeyword": return { kind: "number" };
1211
+ case "TSBooleanKeyword": return { kind: "boolean" };
1212
+ case "TSFunctionType":
1213
+ case "TSConstructorType": return;
1214
+ case "TSParenthesizedType": return getControl(type.typeAnnotation, file, seen);
1215
+ case "TSArrayType":
1216
+ case "TSTupleType": return {
1217
+ kind: "json",
1218
+ empty: []
1219
+ };
1220
+ case "TSTypeLiteral": return {
1221
+ kind: "json",
1222
+ empty: {}
1223
+ };
1224
+ case "TSTypeReference":
1225
+ if (type.typeName.type === "Identifier") {
1226
+ if (type.typeName.name === "Array" || type.typeName.name === "ReadonlyArray") return {
1227
+ kind: "json",
1228
+ empty: []
1229
+ };
1230
+ if (type.typeName.name === "Record") return {
1231
+ kind: "json",
1232
+ empty: {}
1233
+ };
1234
+ const name = type.typeName.name;
1235
+ const declaration = seen.has(name) ? void 0 : localType(name, file);
1236
+ if (declaration?.type === "TSInterfaceDeclaration") return {
1237
+ kind: "json",
1238
+ empty: {}
1239
+ };
1240
+ if (declaration?.type === "TSTypeAliasDeclaration") return getControl(declaration.typeAnnotation, file, new Set(seen).add(name));
1241
+ }
1242
+ return { kind: "json" };
1243
+ case "TSUnionType": {
1244
+ const types = [];
1245
+ for (const item of type.types) if (item.type !== "TSUndefinedKeyword" && item.type !== "TSNullKeyword") types.push(item);
1246
+ const options = [];
1247
+ for (const item of types) {
1248
+ const value = item.type === "TSLiteralType" ? literalValue(item.literal) : void 0;
1249
+ if (typeof value !== "string" && typeof value !== "number") return types.length === 1 ? getControl(types[0], file, seen) : { kind: "json" };
1250
+ options.push(value);
1251
+ }
1252
+ return {
1253
+ kind: "choice",
1254
+ options
1255
+ };
1256
+ }
1257
+ default: return { kind: "json" };
1258
+ }
1259
+ }
1260
+ /**
1261
+ * The controls for the props of a component, from the type of `$props<T>()` and the defaults
1262
+ * of its destructuring. A prop whose type is a function, such as a handler, has none. Undefined
1263
+ * when the workbench cannot read the type, such as one that the file imports.
1264
+ */
1265
+ function propControls(file) {
1266
+ resolveMacros(file);
1267
+ for (const statement of file.instanceScript?.program.body ?? []) {
1268
+ if (statement.type !== "VariableDeclaration") continue;
1269
+ for (const declarator of statement.declarations) {
1270
+ const call = declarator.init;
1271
+ if (call?.type !== "CallExpression" || call.callee.type !== "Identifier" || call.callee.name !== "$props") continue;
1272
+ const defaults = /* @__PURE__ */ new Map();
1273
+ if (declarator.id.type === "ObjectPattern") {
1274
+ for (const property of declarator.id.properties) if (property.type === "Property" && property.key.type === "Identifier" && property.value.type === "AssignmentPattern") defaults.set(property.key.name, literalValue(property.value.right));
1275
+ }
1276
+ const type = call.typeArguments?.params[0];
1277
+ const members = type ? propsMembers(type, file) : [];
1278
+ if (!members) return;
1279
+ const byName = /* @__PURE__ */ new Map();
1280
+ for (const member of members) {
1281
+ const name = memberName(member);
1282
+ if (name === void 0 || member.type !== "TSPropertySignature") continue;
1283
+ const control = name === "children" ? { kind: "text" } : getControl(member.typeAnnotation?.typeAnnotation, file);
1284
+ if (!control) {
1285
+ byName.delete(name);
1286
+ continue;
1287
+ }
1288
+ const value = defaults.get(name);
1289
+ byName.set(name, {
1290
+ name,
1291
+ optional: member.optional,
1292
+ ...control,
1293
+ ...value === void 0 ? {} : { default: value }
1294
+ });
1295
+ }
1296
+ return [...byName.values()];
1297
+ }
1298
+ }
1299
+ return [];
1300
+ }
1301
+ //#endregion
447
1302
  //#region src/prerender.ts
448
1303
  /** The file of a page: `index.html` in a folder of its path. */
449
- function fileOf(pathname) {
1304
+ function getPageFile(pathname) {
450
1305
  const clean = pathname.replace(/^\/+|\/+$/g, "");
451
1306
  return clean ? `${clean}/index.html` : "index.html";
452
1307
  }
@@ -480,7 +1335,11 @@ function scriptHashes(html) {
480
1335
  async function prerender(routes, root, base, options) {
481
1336
  const client = path.resolve(root, options.client ?? "dist/client");
482
1337
  const manifest = JSON.parse(await readFile(path.join(client, ".vite/manifest.json"), "utf8"));
483
- const entry = Object.values(manifest).find((chunk) => chunk.isEntry);
1338
+ let entry;
1339
+ for (const chunk of Object.values(manifest)) if (chunk.isEntry) {
1340
+ entry = chunk;
1341
+ break;
1342
+ }
484
1343
  if (!entry) throw new Error("The client build has no entry. Build the client before the server.");
485
1344
  const { handle } = await import(pathToFileURL(routes).href);
486
1345
  const document = {
@@ -497,12 +1356,12 @@ async function prerender(routes, root, base, options) {
497
1356
  const response = await handle(new Request(`http://localhost${pathname}`), document);
498
1357
  if (!response?.headers.get("content-type")?.includes("text/html") || response.status !== 200) continue;
499
1358
  const html = await response.text();
500
- const file = path.join(client, fileOf(pathname));
1359
+ const file = path.join(client, getPageFile(pathname));
501
1360
  await mkdir(path.dirname(file), { recursive: true });
502
1361
  await writeFile(file, html);
503
1362
  written.push(pathname);
504
1363
  pages[pathname] = {
505
- file: fileOf(pathname),
1364
+ file: getPageFile(pathname),
506
1365
  scripts: scriptHashes(html)
507
1366
  };
508
1367
  if (options.crawl !== false) {
@@ -522,9 +1381,11 @@ async function prerender(routes, root, base, options) {
522
1381
  scripts: scriptHashes(html)
523
1382
  };
524
1383
  }
1384
+ const scripts = /* @__PURE__ */ new Set();
1385
+ for (const page of Object.values(pages)) for (const script of page.scripts) scripts.add(script);
525
1386
  const result = {
526
1387
  pages,
527
- scripts: [...new Set(Object.values(pages).flatMap((page) => page.scripts))]
1388
+ scripts: [...scripts]
528
1389
  };
529
1390
  await mkdir(path.join(client, ".brumate"), { recursive: true });
530
1391
  await writeFile(path.join(client, ".brumate/prerender.json"), `${JSON.stringify(result, null, 2)}\n`);
@@ -573,118 +1434,101 @@ function routeEntries(node, resolve, path = "", layouts = []) {
573
1434
  return result;
574
1435
  }
575
1436
  /** Measures the client build. */
576
- function buildReport({ chunks: list, sources, routes, events: handlers, budget, relative = (file) => file }) {
577
- const chunks = new Map(list.map((chunk) => [chunk.fileName, chunk]));
578
- const sizes = new Map(list.map((chunk) => [chunk.fileName, gzipSize(chunk.code)]));
579
- const sum = (names) => {
1437
+ function buildReport({ chunks: list, sources, routes, budget, relative = (file) => file }) {
1438
+ const chunks = /* @__PURE__ */ new Map();
1439
+ const sizes = /* @__PURE__ */ new Map();
1440
+ for (const chunk of list) {
1441
+ chunks.set(chunk.fileName, chunk);
1442
+ sizes.set(chunk.fileName, gzipSize(chunk.code));
1443
+ }
1444
+ function sum(names) {
580
1445
  let total = 0;
581
1446
  for (const name of names) total += sizes.get(name) ?? 0;
582
1447
  return total;
583
- };
1448
+ }
584
1449
  const loaderChunks = /* @__PURE__ */ new Set();
585
1450
  for (const chunk of list) if (chunk.isEntry) withImports(chunk.fileName, chunks, loaderChunks);
586
- const coreChunk = list.find((chunk) => chunk.moduleIds.some((id) => /[\\/]runtime[\\/]client\.[jt]s$/.test(id)));
1451
+ let coreChunk;
1452
+ for (const chunk of list) {
1453
+ let isCore = false;
1454
+ for (const id of chunk.moduleIds) if (/[\\/]runtime[\\/]client\.[jt]s$/.test(id)) {
1455
+ isCore = true;
1456
+ break;
1457
+ }
1458
+ if (isCore) {
1459
+ coreChunk = chunk;
1460
+ break;
1461
+ }
1462
+ }
587
1463
  const coreChunks = coreChunk ? withImports(coreChunk.fileName, chunks) : /* @__PURE__ */ new Set();
588
1464
  for (const name of loaderChunks) coreChunks.delete(name);
589
1465
  const byFile = /* @__PURE__ */ new Map();
590
- const byModule = /* @__PURE__ */ new Map();
1466
+ const shares = /* @__PURE__ */ new Map();
591
1467
  const everyPage = /* @__PURE__ */ new Set([...loaderChunks, ...coreChunks]);
592
- for (const chunk of list) for (const id of chunk.moduleIds) {
593
- const file = /^(.*\.brm)\?brumate-client/.exec(id)?.[1];
594
- if (file) {
595
- const set = byFile.get(file) ?? /* @__PURE__ */ new Set();
596
- withImports(chunk.fileName, chunks, set);
597
- byFile.set(file, set);
598
- byModule.set(id, chunk.fileName);
1468
+ for (const chunk of list) {
1469
+ const owned = /* @__PURE__ */ new Map();
1470
+ for (const id of chunk.moduleIds) {
1471
+ const file = /^(.*\.brm)\?brumate-client/.exec(id)?.[1];
1472
+ if (file) {
1473
+ const set = byFile.get(file) ?? /* @__PURE__ */ new Set();
1474
+ withImports(chunk.fileName, chunks, set);
1475
+ byFile.set(file, set);
1476
+ owned.set(file, (owned.get(file) ?? 0) + (chunk.modules?.[id] ?? 1));
1477
+ }
1478
+ }
1479
+ let total = chunk.moduleIds.length;
1480
+ if (chunk.modules) {
1481
+ total = 0;
1482
+ for (const bytes of Object.values(chunk.modules)) total += bytes;
1483
+ }
1484
+ for (const [file, bytes] of owned) {
1485
+ const share = total > 0 ? (sizes.get(chunk.fileName) ?? 0) * bytes / total : 0;
1486
+ shares.set(file, (shares.get(file) ?? 0) + share);
599
1487
  }
600
1488
  }
601
1489
  for (const set of byFile.values()) for (const name of everyPage) set.delete(name);
602
- const components = [...byFile].map(([file, names]) => ({
1490
+ const components = [];
1491
+ for (const [file, bytes] of shares) components.push({
603
1492
  file,
604
- bytes: sum(names)
605
- })).toSorted((a, b) => b.bytes - a.bytes);
606
- const eventChunks = (event) => {
607
- const names = /* @__PURE__ */ new Set();
608
- const entry = byModule.get(`${event.file}?brumate-client`);
609
- if (entry) withImports(entry, chunks, names);
610
- for (const part of event.parts) {
611
- const chunk = byModule.get(`${event.file}?brumate-client&part=${part}`);
612
- if (chunk) withImports(chunk, chunks, names);
613
- }
614
- for (const name of everyPage) names.delete(name);
615
- return names;
616
- };
617
- const measured = (handlers ?? partEvents(byModule.keys())).map((event) => {
618
- const names = eventChunks(event);
619
- return {
620
- event,
621
- names,
622
- bytes: sum(names)
623
- };
1493
+ bytes: Math.round(bytes)
624
1494
  });
625
- const events = measured.map(({ event, bytes }) => ({
626
- file: event.file,
627
- label: event.label,
628
- bytes
629
- })).toSorted((a, b) => b.bytes - a.bytes);
630
- const reachable = (files) => {
1495
+ components.sort((a, b) => b.bytes - a.bytes);
1496
+ function reachable(files) {
631
1497
  const seen = /* @__PURE__ */ new Set();
632
- const visit = (file) => {
1498
+ function visit(file) {
633
1499
  if (!seen.has(file)) {
634
1500
  seen.add(file);
635
1501
  for (const imported of componentImports(file, sources.get(file) ?? "")) visit(imported);
636
1502
  }
637
- };
638
- files.forEach(visit);
1503
+ }
1504
+ for (const file of files) visit(file);
639
1505
  return seen;
640
- };
641
- const routeSizes = (routes ? routeEntries(routes.tree, routes.resolve) : []).map(({ path, files }) => {
1506
+ }
1507
+ const routeSizes = [];
1508
+ for (const { path, files } of routes ? routeEntries(routes.tree, routes.resolve) : []) {
642
1509
  const reached = reachable(files);
643
1510
  const names = new Set(coreChunks);
644
1511
  for (const file of reached) for (const name of byFile.get(file) ?? []) names.add(name);
645
- return {
1512
+ routeSizes.push({
646
1513
  path,
647
1514
  bytes: sum(names),
648
1515
  components: reached.size
649
- };
650
- }).toSorted((a, b) => b.bytes - a.bytes);
1516
+ });
1517
+ }
1518
+ routeSizes.sort((a, b) => b.bytes - a.bytes);
651
1519
  const loader = sum(loaderChunks);
652
1520
  const overBudget = [];
653
1521
  if (budget?.loader !== void 0 && loader > budget.loader) overBudget.push(`The loader is ${formatBytes(loader)}, over the budget of ${formatBytes(budget.loader)}.`);
654
1522
  for (const route of routeSizes) if (budget?.route !== void 0 && route.bytes > budget.route) overBudget.push(`The route ${route.path} can load ${formatBytes(route.bytes)}, over the budget of ${formatBytes(budget.route)}.`);
655
1523
  for (const component of components) if (budget?.component !== void 0 && component.bytes > budget.component) overBudget.push(`The component ${relative(component.file)} ships ${formatBytes(component.bytes)}, over the budget of ${formatBytes(budget.component)}.`);
656
- for (const { event, names, bytes } of measured.toSorted((a, b) => b.bytes - a.bytes)) if (budget?.event !== void 0 && bytes > budget.event) {
657
- const imports = largestImports(names, chunks);
658
- overBudget.push(`The handler ${event.label} of ${relative(event.file)} loads ${formatBytes(bytes)}, over the budget of ${formatBytes(budget.event)}.${imports.length > 0 ? ` Its largest imports are ${imports.map(relative).join(", ")}.` : ""}`);
659
- }
660
1524
  return {
661
1525
  loader,
662
1526
  core: sum(coreChunks),
663
1527
  components,
664
1528
  routes: routeSizes,
665
- events,
666
1529
  overBudget
667
1530
  };
668
1531
  }
669
- /** Each part of a client module as a handler of its own, when the build does not name them. */
670
- function partEvents(ids) {
671
- const result = [];
672
- for (const id of ids) {
673
- const match = /^(.*\.brm)\?brumate-client&part=(.+)$/.exec(id);
674
- if (match && match[2] !== "update" && match[2] !== "shared") result.push({
675
- file: match[1],
676
- label: `part ${match[2]}`,
677
- parts: [match[2]]
678
- });
679
- }
680
- return result;
681
- }
682
- /** The three largest modules in the chunks that are not client modules of components. */
683
- function largestImports(names, chunks) {
684
- const sizes = [];
685
- for (const name of names) for (const [id, bytes] of Object.entries(chunks.get(name)?.modules ?? {})) if (!id.includes("?brumate-client")) sizes.push([id.replace(/^\0/, ""), bytes]);
686
- return sizes.toSorted((a, b) => b[1] - a[1]).slice(0, 3).map(([id]) => id);
687
- }
688
1532
  function formatBytes(bytes) {
689
1533
  return bytes < 1024 ? `${bytes} B` : `${(bytes / 1024).toFixed(1)} kB`;
690
1534
  }
@@ -692,21 +1536,17 @@ function formatBytes(bytes) {
692
1536
  function formatBuildReport(report, relative) {
693
1537
  const lines = [
694
1538
  "brumate client report (gzip)",
695
- ` Every page, before its first event: ${formatBytes(report.loader)}`,
696
- ` The core, on the first event: ${formatBytes(report.core)}`
1539
+ ` The loader, on every page: ${formatBytes(report.loader)}`,
1540
+ ` The core, when the page starts: ${formatBytes(report.core)}`
697
1541
  ];
698
1542
  if (report.routes.length > 0) {
699
- lines.push(" The most each route loads after its first event, with the core");
1543
+ lines.push(" What each route loads when it starts, with the core");
700
1544
  for (const route of report.routes) lines.push(` ${route.path}: ${formatBytes(route.bytes)} (${route.components} components)`);
701
1545
  }
702
1546
  if (report.components.length > 0) {
703
1547
  lines.push(" Components, largest first");
704
1548
  for (const component of report.components) lines.push(` ${relative(component.file)}: ${formatBytes(component.bytes)}`);
705
1549
  }
706
- if (report.events.length > 0) {
707
- lines.push(" What the first run of a handler loads, largest first");
708
- for (const event of report.events.slice(0, 10)) lines.push(` ${relative(event.file)} ${event.label}: ${formatBytes(event.bytes)}`);
709
- }
710
1550
  return lines.join("\n");
711
1551
  }
712
1552
  //#endregion
@@ -774,14 +1614,15 @@ function routeFiles(paths) {
774
1614
  * `middleware` is the path of the entry middleware, which runs for every
775
1615
  * request, when the app has one.
776
1616
  */
777
- function routeModule(tree, resolve, rpc = "/_brumate", origins = [], dev = false, middleware, build, hints = []) {
1617
+ function routeModule(tree, resolve, rpc = "/_brumate", origins = [], dev = false, middleware, build, hints = [], bundleHints = {}) {
778
1618
  const imports = [];
779
- const load = (file) => {
1619
+ function load(file) {
1620
+ if (dev) return `() => import(${JSON.stringify(resolve(file))})`;
780
1621
  const name = `m${imports.length}`;
781
1622
  imports.push(`import * as ${name} from ${JSON.stringify(resolve(file))};`);
782
1623
  return `() => Promise.resolve(${name})`;
783
- };
784
- const write = (node) => {
1624
+ }
1625
+ function write(node) {
785
1626
  const fields = [];
786
1627
  for (const key of [
787
1628
  "layout",
@@ -798,7 +1639,8 @@ function routeModule(tree, resolve, rpc = "/_brumate", origins = [], dev = false
798
1639
  for (const key of ["static", "slots"]) {
799
1640
  const children = node[key];
800
1641
  if (children) {
801
- const entries = Object.entries(children).map(([name, value]) => `${JSON.stringify(name)}: ${write(value)}`);
1642
+ const entries = [];
1643
+ for (const [name, value] of Object.entries(children)) entries.push(`${JSON.stringify(name)}: ${write(value)}`);
802
1644
  fields.push(`${key}: { ${entries.join(", ")} }`);
803
1645
  }
804
1646
  }
@@ -807,7 +1649,7 @@ function routeModule(tree, resolve, rpc = "/_brumate", origins = [], dev = false
807
1649
  if (value) fields.push(`${key}: { name: ${JSON.stringify(value.name)}, node: ${write(value.node)} }`);
808
1650
  }
809
1651
  return `{ ${fields.join(", ")} }`;
810
- };
1652
+ }
811
1653
  const routes = write(tree);
812
1654
  return [
813
1655
  "import { handleRoute } from 'brumate/server';",
@@ -816,14 +1658,14 @@ function routeModule(tree, resolve, rpc = "/_brumate", origins = [], dev = false
816
1658
  ...imports,
817
1659
  `export const routes = ${routes};`,
818
1660
  "export function handle(request, options) {",
819
- ` return handleRoute(routes, request, { rpc: ${JSON.stringify(rpc)}, origins: ${JSON.stringify(origins)}, functions, fileMiddleware${middleware ? ", middleware" : ""}${dev ? ", dev: true" : ""}${build === void 0 ? "" : `, build: ${JSON.stringify(build)}`}${hints.length > 0 ? `, hints: ${JSON.stringify(hints)}` : ""}, ...options });`,
1661
+ ` return handleRoute(routes, request, { rpc: ${JSON.stringify(rpc)}, origins: ${JSON.stringify(origins)}, functions, fileMiddleware${middleware ? ", middleware" : ""}${dev ? ", dev: true" : ""}${build === void 0 ? "" : `, build: ${JSON.stringify(build)}`}${hints.length > 0 ? `, hints: ${JSON.stringify(hints)}` : ""}${Object.keys(bundleHints).length > 0 ? `, bundleHints: ${JSON.stringify(bundleHints)}` : ""}, ...options });`,
820
1662
  "}"
821
1663
  ].join("\n");
822
1664
  }
823
1665
  /** The paths of the pages and endpoints of a tree. Slots render at the paths of their layout. */
824
1666
  function routePaths(tree) {
825
1667
  const result = [];
826
- const visit = (node, path, params) => {
1668
+ function visit(node, path, params) {
827
1669
  if (node.page || node.endpoint) result.push({
828
1670
  path: path || "/",
829
1671
  params
@@ -831,22 +1673,27 @@ function routePaths(tree) {
831
1673
  for (const [segment, folder] of Object.entries(node.static ?? {})) visit(folder, `${path}/${segment}`, params);
832
1674
  if (node.dynamic) visit(node.dynamic.node, `${path}/[${node.dynamic.name}]`, [...params, node.dynamic.name]);
833
1675
  if (node.rest) visit(node.rest.node, `${path}/[...${node.rest.name}]`, [...params, node.rest.name]);
834
- };
1676
+ }
835
1677
  visit(tree, "", []);
836
1678
  return result.toSorted((a, b) => a.path.localeCompare(b.path));
837
1679
  }
838
1680
  /** A declaration file that adds the paths of a tree to `Routes` of `brumate/routes`. */
839
1681
  function routeTypes(tree) {
1682
+ const lines = [];
1683
+ for (const { path, params } of routePaths(tree)) {
1684
+ const names = [];
1685
+ for (const name of params) names.push(`${name}: string`);
1686
+ const fields = names.join("; ");
1687
+ const key = `'${path.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
1688
+ lines.push(` ${key}: {${fields ? ` ${fields} ` : ""}};`);
1689
+ }
840
1690
  return [
841
1691
  "// Written by the brumate Vite plugin from the route files. Do not edit.",
842
1692
  "export {};",
843
1693
  "",
844
1694
  "declare module 'brumate/routes' {",
845
1695
  " interface Routes {",
846
- ...routePaths(tree).map(({ path, params }) => {
847
- const fields = params.map((name) => `${name}: string`).join("; ");
848
- return ` ${`'${path.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`}: {${fields ? ` ${fields} ` : ""}};`;
849
- }),
1696
+ ...lines,
850
1697
  " }",
851
1698
  "}",
852
1699
  ""
@@ -855,9 +1702,23 @@ function routeTypes(tree) {
855
1702
  //#endregion
856
1703
  //#region src/vite.ts
857
1704
  /** `import 'virtual:brumate/start'` in the client entry starts the loader. */
1705
+ /** How many files a build reads or compiles at once, so a large project does not run out of file handles. */
1706
+ const BATCH = 32;
1707
+ /** Runs `run` for each item, one batch at a time. */
1708
+ async function inBatches(list, run) {
1709
+ const results = [];
1710
+ for (let start = 0; start < list.length; start += BATCH) {
1711
+ const batch = [];
1712
+ for (const item of list.slice(start, start + BATCH)) batch.push(run(item));
1713
+ results.push(...await Promise.all(batch));
1714
+ }
1715
+ return results;
1716
+ }
858
1717
  const START = "virtual:brumate/start";
859
1718
  /** Exports `load(id)`, which imports the client module of a component. */
860
1719
  const MANIFEST = "virtual:brumate/manifest";
1720
+ /** `virtual:brumate/bundle/<id>` imports the client modules of a root component and those it renders. */
1721
+ const BUNDLE = "virtual:brumate/bundle/";
861
1722
  /** Exports `functions` and `handle(request)` for server function calls. */
862
1723
  const SERVER = "virtual:brumate/server";
863
1724
  /** Exports `routes` and `handle(request, options)` for the files in the routes directory. */
@@ -873,13 +1734,21 @@ const TESTING = "virtual:brumate/testing";
873
1734
  const HINTS_FILE = ".brumate/hints.json";
874
1735
  /** The dev server answers the devtools panel about a component at this path. */
875
1736
  const INSPECT = "/__brumate/inspect";
1737
+ /** Maps a position of a module that the browser ran to its source, for the Errors tab. */
1738
+ const POSITION = "/__brumate/position";
1739
+ /** The dev server sends the source of a file for the Errors tab of the devtools at this path. */
1740
+ const SOURCE = "/__brumate/source";
1741
+ /** The workbench of the dev server, which shows the components that depend only on their props. */
1742
+ const WORKBENCH = "/__brumate/workbench";
876
1743
  /** What tells two lists of packages of components apart. */
877
1744
  function packagesKey(list) {
878
- return JSON.stringify(list.map((item) => [
1745
+ const rows = [];
1746
+ for (const item of list) rows.push([
879
1747
  item.prefix,
880
1748
  item.root,
881
1749
  item.directories
882
- ]));
1750
+ ]);
1751
+ return JSON.stringify(rows);
883
1752
  }
884
1753
  /** Skips the `node_modules` and hidden directories of a package of components. */
885
1754
  function packageExclude(directory) {
@@ -892,7 +1761,7 @@ async function readBody(request) {
892
1761
  return Buffer.concat(chunks);
893
1762
  }
894
1763
  /** Removes the scripts, styles and event handlers of a file, which leaves the markup of its page. */
895
- function markupOf(result) {
1764
+ function getMarkup(result) {
896
1765
  const { file } = result;
897
1766
  const ranges = [
898
1767
  ...file.instanceScript ? [file.instanceScript] : [],
@@ -913,21 +1782,39 @@ function markupOf(result) {
913
1782
  }
914
1783
  return markup + file.source.slice(position);
915
1784
  }
916
- function shapeOf(result) {
917
- const slots = [...result.plan.scopes.values()].map((layout) => `${layout.scope.id}:${layout.slots.map((slot) => slot.name).join(",")}`);
918
- const layouts = [...result.plan.scopes.values()];
1785
+ function getShape(result) {
1786
+ const labels = [];
1787
+ const slots = {};
1788
+ const signals = [];
1789
+ for (const layout of result.plan.scopes.values()) {
1790
+ const names = [];
1791
+ for (const slot of layout.slots) {
1792
+ names.push(slot.name);
1793
+ if (slot.kind === "signal") signals.push(slot.name);
1794
+ }
1795
+ labels.push(`${layout.scope.id}:${names.join(",")}`);
1796
+ slots[layout.scope.id] = names;
1797
+ }
919
1798
  return {
920
1799
  layout: JSON.stringify([
921
1800
  result.table,
922
- slots,
923
- markupOf(result)
1801
+ labels,
1802
+ getMarkup(result)
924
1803
  ]),
925
1804
  css: result.css,
926
1805
  code: JSON.stringify([result.client, result.parts]),
927
- slots: Object.fromEntries(layouts.map((layout) => [layout.scope.id, layout.slots.map((slot) => slot.name)])),
928
- signals: layouts.flatMap((layout) => layout.slots.filter((slot) => slot.kind === "signal").map((slot) => slot.name))
1806
+ slots,
1807
+ signals
929
1808
  };
930
1809
  }
1810
+ /**
1811
+ * The cache key of a module for Vitest: the hash of this build of brumate. A component is never
1812
+ * cached, because its code depends on other files, such as the `.brm.ts` modules that it calls
1813
+ * and the props that other components pass it. A key of its own source would go stale.
1814
+ */
1815
+ function cacheKey({ id }) {
1816
+ return id.split("?")[0].endsWith(".brm") ? false : buildFingerprint();
1817
+ }
931
1818
  let fingerprint;
932
1819
  /**
933
1820
  * A hash of the code of this build of brumate. A new build can compile the
@@ -936,13 +1823,13 @@ let fingerprint;
936
1823
  function buildFingerprint() {
937
1824
  if (fingerprint === void 0) {
938
1825
  const digest = createHash("sha1");
939
- const visit = (directory) => {
1826
+ function visit(directory) {
940
1827
  for (const entry of readdirSync(directory, { withFileTypes: true }).toSorted((a, b) => a.name < b.name ? -1 : 1)) {
941
1828
  const file = path.join(directory, entry.name);
942
1829
  if (entry.isDirectory()) visit(file);
943
1830
  else if (/\.[jt]s$/.test(entry.name) && !entry.name.endsWith(".d.ts")) digest.update(entry.name).update(readFileSync(file));
944
1831
  }
945
- };
1832
+ }
946
1833
  visit(path.dirname(fileURLToPath(import.meta.url)));
947
1834
  fingerprint = digest.digest("hex").slice(0, 16);
948
1835
  }
@@ -952,7 +1839,7 @@ function buildFingerprint() {
952
1839
  function brumate(options = {}) {
953
1840
  const rpc = options.rpc ?? "/_brumate";
954
1841
  /** The entry middleware, when the app has one. */
955
- const middlewareFile = () => {
1842
+ function middlewareFile() {
956
1843
  if (options.middleware === false) return;
957
1844
  const file = normalizePath(path.resolve(root, options.middleware ?? "src/middleware.ts"));
958
1845
  if (!existsSync(file)) {
@@ -960,9 +1847,43 @@ function brumate(options = {}) {
960
1847
  return;
961
1848
  }
962
1849
  return file;
963
- };
1850
+ }
1851
+ /** The serial entry, when the app has one. */
1852
+ function serialFile() {
1853
+ if (options.serial === false) return;
1854
+ const file = normalizePath(path.resolve(root, options.serial ?? "src/serial.ts"));
1855
+ if (!existsSync(file)) {
1856
+ if (options.serial !== void 0) throw new Error(`The serial entry ${options.serial} does not exist`);
1857
+ return;
1858
+ }
1859
+ return file;
1860
+ }
1861
+ /** The classes that the plugins of the serial entry send, read from its `instanceof` checks. */
1862
+ let serialRead;
1863
+ function serialClasses() {
1864
+ const file = serialFile();
1865
+ if (!file) return [];
1866
+ const source = readFileSync(file, "utf8");
1867
+ if (serialRead?.source !== source) {
1868
+ const { program } = parseSync(file, source, { lang: "ts" });
1869
+ serialRead = {
1870
+ source,
1871
+ classes: entryClasses(program)
1872
+ };
1873
+ }
1874
+ return serialRead.classes;
1875
+ }
1876
+ /** The lines that give the server the serial entry, before anything is written or read. */
1877
+ function serialImports() {
1878
+ const file = serialFile();
1879
+ return file ? [
1880
+ `import * as $$serial from ${JSON.stringify(file)};`,
1881
+ "import { useSerialEntry } from 'brumate/server';",
1882
+ "useSerialEntry($$serial);"
1883
+ ] : [];
1884
+ }
964
1885
  /** The file of environment variables, when the app has one. */
965
- const envFile = () => {
1886
+ function envFile() {
966
1887
  if (options.env === false) return;
967
1888
  const file = normalizePath(path.resolve(root, options.env ?? "src/env.ts"));
968
1889
  if (!existsSync(file)) {
@@ -970,10 +1891,10 @@ function brumate(options = {}) {
970
1891
  return;
971
1892
  }
972
1893
  return file;
973
- };
1894
+ }
974
1895
  /** The names of the server variables, read from the env file, by its source. */
975
1896
  let envKeys;
976
- const serverEnvKeys = () => {
1897
+ function serverEnvKeys() {
977
1898
  const file = envFile();
978
1899
  if (!file) return;
979
1900
  const source = readFileSync(file, "utf8");
@@ -982,7 +1903,7 @@ function brumate(options = {}) {
982
1903
  server: parseEnvFile(source, file).server
983
1904
  };
984
1905
  return envKeys.server;
985
- };
1906
+ }
986
1907
  const exclude = options.exclude ?? defaultExclude;
987
1908
  let root = process.cwd();
988
1909
  let outDir = "";
@@ -996,114 +1917,180 @@ function brumate(options = {}) {
996
1917
  const compiled = /* @__PURE__ */ new Map();
997
1918
  /** Files that a component depends on, such as SCSS that it imports or modules that it calls into, with the components. */
998
1919
  const dependents = /* @__PURE__ */ new Map();
999
- /** What the browser has of each component, from its last compile. See `shapeOf`. */
1920
+ /** What the browser has of each component, from its last compile. See `getShape`. */
1000
1921
  const shapes = /* @__PURE__ */ new Map();
1001
1922
  /** The props that parents can change, by absolute file path. */
1002
1923
  let liveProps = /* @__PURE__ */ new Map();
1924
+ /** The names of the server functions that the app refreshes, or undefined before the first scan. */
1925
+ let refreshed;
1003
1926
  /** The dependencies of the app that ship `.brm` files. See `packages.ts`. */
1004
1927
  let packages = [];
1005
- const relative = (file) => normalizePath(path.relative(root, file));
1928
+ function relative(file) {
1929
+ return normalizePath(path.relative(root, file));
1930
+ }
1006
1931
  /**
1007
1932
  * The name of a file, which its IDs come from: its path relative to the root,
1008
1933
  * or for a file of a package, the name of the package and its path in it.
1009
1934
  */
1010
- const nameOf = (file) => {
1935
+ function getFileName(file) {
1011
1936
  let normalized = normalizePath(file);
1012
- let owner = packageOf(packages, normalized);
1937
+ let owner = findPackage(packages, normalized);
1013
1938
  if (!owner && normalized.includes("/node_modules/") && existsSync(normalized)) {
1014
1939
  normalized = normalizePath(realpathSync(normalized));
1015
- owner = packageOf(packages, normalized);
1940
+ owner = findPackage(packages, normalized);
1016
1941
  }
1017
1942
  return owner ? packageFileName(owner, normalized) : relative(file);
1018
- };
1019
- /** True for a bare specifier that names a package of components. */
1020
- const isPackageSpecifier = (specifier) => {
1021
- const name = splitSpecifier(specifier)?.name;
1022
- return name !== void 0 && packages.some((item) => item.name === name);
1023
- };
1943
+ }
1024
1944
  /** Files of server functions: scripts whose first statement is `'use server'`, by ID. */
1025
1945
  const serverFiles = /* @__PURE__ */ new Map();
1026
1946
  /** The scripts of the app, when it uses packages of components. */
1027
1947
  let appScripts = [];
1028
1948
  /** The ID of a function that a component imports from a 'use server' file, by a relative path. */
1029
- const serverImport = (importer, specifier, name) => {
1949
+ function serverImport(importer, specifier, name) {
1030
1950
  if (!specifier.startsWith(".")) {
1031
- const file = isPackageSpecifier(specifier) ? resolvePackageImport(specifier, importer) : void 0;
1032
- return file && isScriptFile(file) && hasUseServer(readFileSync(file, "utf8")) ? functionId(serverFileId(file), name, !isServe) : void 0;
1951
+ const file = findPackageServerFile(packages, importer, specifier);
1952
+ return file ? functionId(serverFileId(file), name, !isServe) : void 0;
1033
1953
  }
1034
1954
  const stem = path.resolve(path.dirname(importer), specifier);
1035
- const found = [stem, ...[
1955
+ const candidates = [stem];
1956
+ for (const extension of [
1036
1957
  ".ts",
1037
1958
  ".tsx",
1038
1959
  ".js",
1039
1960
  ".mjs"
1040
- ].map((extension) => stem + extension)].find((candidate) => isScriptFile(candidate) && existsSync(candidate) && hasUseServer(readFileSync(candidate, "utf8")));
1961
+ ]) candidates.push(stem + extension);
1962
+ let found;
1963
+ for (const candidate of candidates) if (isScriptFile(candidate) && existsSync(candidate) && hasUseServer(readFileSync(candidate, "utf8"))) {
1964
+ found = candidate;
1965
+ break;
1966
+ }
1041
1967
  return found && functionId(serverFileId(normalizePath(found)), name, !isServe);
1042
- };
1043
- const serverFileId = (file) => `${path.basename(file).replace(/\.[^.]+$/, "")}_${hash(nameOf(file))}`;
1044
- const componentId = (file) => {
1045
- const filename = nameOf(file);
1968
+ }
1969
+ function serverFileId(file) {
1970
+ return `${path.basename(file).replace(/\.[^.]+$/, "")}_${hash(getFileName(file))}`;
1971
+ }
1972
+ function componentId(file) {
1973
+ const filename = getFileName(file);
1046
1974
  return `${getComponentName(filename)}_${hash(filename)}`;
1047
- };
1048
- const scan = async () => {
1049
- const directories = packages.flatMap((item) => item.directories.filter((directory) => existsSync(directory)));
1050
- const ownFile = (file) => !packageOf(packages, file);
1051
- const [own, ownServer, ...found] = await Promise.all([
1052
- findFiles(root, exclude),
1053
- findServerFiles(root, exclude),
1054
- ...directories.flatMap((directory) => [findFiles(directory, packageExclude), findServerFiles(directory, packageExclude)])
1055
- ]);
1056
- appScripts = packages.length > 0 ? (await findScripts(root, exclude)).filter(ownFile) : [];
1975
+ }
1976
+ async function scan() {
1977
+ const directories = [];
1978
+ for (const item of packages) for (const directory of item.directories) if (existsSync(directory)) directories.push(directory);
1979
+ function ownFile(file) {
1980
+ return !findPackage(packages, file);
1981
+ }
1982
+ const searches = [findFiles(root, exclude), findServerFiles(root, exclude)];
1983
+ for (const directory of directories) searches.push(findFiles(directory, packageExclude), findServerFiles(directory, packageExclude));
1984
+ const [own, ownServer, ...found] = await Promise.all(searches);
1985
+ const scripts = [];
1986
+ if (packages.length > 0) {
1987
+ for (const file of await findScripts(root, exclude)) if (ownFile(file)) scripts.push(file);
1988
+ }
1989
+ appScripts = scripts;
1057
1990
  files.clear();
1058
1991
  serverFiles.clear();
1059
- for (const file of own.filter(ownFile)) files.set(componentId(file), file);
1060
- for (const file of ownServer.filter(ownFile)) serverFiles.set(serverFileId(file), file);
1992
+ for (const file of own) if (ownFile(file)) files.set(componentId(file), file);
1993
+ for (const file of ownServer) if (ownFile(file)) serverFiles.set(serverFileId(file), file);
1061
1994
  for (const [index, list] of found.entries()) for (const file of list) if (index % 2 === 0) files.set(componentId(file), file);
1062
1995
  else serverFiles.set(serverFileId(file), file);
1063
- await analyze();
1064
- };
1996
+ try {
1997
+ await analyze();
1998
+ } finally {
1999
+ workbenchList = void 0;
2000
+ }
2001
+ }
1065
2002
  /**
1066
2003
  * The files of packages that the app reaches through its imports. A server
1067
2004
  * function of a package becomes an endpoint of the app only when the app
1068
2005
  * reaches its file, so installing a package does not expose all of them.
1069
2006
  */
1070
- const reachable = () => reachableFiles(packages, [...[...files.values()].filter((file) => !packageOf(packages, file)), ...appScripts], (file) => {
1071
- try {
1072
- return readFileSync(file, "utf8");
1073
- } catch {
1074
- return;
1075
- }
1076
- });
2007
+ function reachable() {
2008
+ const roots = [];
2009
+ for (const file of files.values()) if (!findPackage(packages, file)) roots.push(file);
2010
+ return reachableFiles(packages, [...roots, ...appScripts], (file) => {
2011
+ try {
2012
+ return readFileSync(file, "utf8");
2013
+ } catch {
2014
+ return;
2015
+ }
2016
+ });
2017
+ }
1077
2018
  /** The files of packages in the last server registry. */
1078
2019
  let registered = /* @__PURE__ */ new Set();
1079
2020
  /** Resolves a `.brm` file that a component imports: next to it, or from a package of components. */
1080
- const resolveComponent = (specifier, importer) => resolveRelative(specifier, importer) ?? (specifier.endsWith(".brm") && isPackageSpecifier(specifier) ? resolvePackageImport(specifier, importer) : void 0);
1081
- const analyze = async () => {
2021
+ function resolveComponent(specifier, importer) {
2022
+ return resolveRelative(specifier, importer) ?? (specifier.endsWith(".brm") ? resolveComponentPackage(packages, specifier, importer) : void 0);
2023
+ }
2024
+ async function analyze() {
1082
2025
  const list = [...files.values()];
1083
- const contents = await Promise.all(list.map((file) => readFile(file, "utf8")));
1084
- const sources = new Map(list.map((file, index) => [file, contents[index]]));
2026
+ const contents = await inBatches(list, (file) => readFile(file, "utf8"));
2027
+ const sources = /* @__PURE__ */ new Map();
2028
+ for (const [index, file] of list.entries()) sources.set(file, contents[index]);
1085
2029
  liveProps = analyzeProject(sources, resolveComponent);
2030
+ const scripts = await findScripts(root, exclude);
2031
+ const scriptSources = await inBatches([.../* @__PURE__ */ new Set([...scripts, ...serverFiles.values()])], (file) => readFile(file, "utf8").catch(() => ""));
2032
+ refreshed = refreshedNames([...contents, ...scriptSources]);
1086
2033
  compiled.clear();
1087
- };
2034
+ }
2035
+ /** The features of the core that the components of the build use, once for each build. */
2036
+ let builtFeatures;
2037
+ /** The files that `builtFeatures` counted, and the features it found. */
2038
+ let counted = /* @__PURE__ */ new Set();
2039
+ let knownFeatures;
2040
+ /** The components that the client build loaded. */
2041
+ const loadedComponents = /* @__PURE__ */ new Set();
2042
+ function buildFeatures() {
2043
+ return builtFeatures ??= (async () => {
2044
+ const seen = /* @__PURE__ */ new Set();
2045
+ const all = [];
2046
+ async function visit(file) {
2047
+ if (seen.has(file)) return;
2048
+ seen.add(file);
2049
+ const { result } = await compileFile(file);
2050
+ all.push(getFeatures(result));
2051
+ const imported = [];
2052
+ for (const specifier of importedComponents(result.file)) {
2053
+ const target = resolveComponent(specifier, file);
2054
+ if (target !== void 0 && existsSync(target)) imported.push(target);
2055
+ }
2056
+ await inBatches(imported, visit);
2057
+ }
2058
+ await inBatches([...files.values()], visit);
2059
+ const features = joinFeatures(all);
2060
+ let loading = false;
2061
+ for (const file of seen) if (path.basename(file) === "_loading.brm") {
2062
+ loading = true;
2063
+ break;
2064
+ }
2065
+ features.lateMarkup ||= options.navigate !== false || loading;
2066
+ counted = seen;
2067
+ knownFeatures = features;
2068
+ return features;
2069
+ })();
2070
+ }
1088
2071
  /** The options of the compile of a file. */
1089
- const compileOptions = (file) => ({
1090
- filename: nameOf(file),
1091
- liveProps: liveProps.get(file),
1092
- path: file,
1093
- merge: options.merge ?? 4096,
1094
- a11y: options.a11y,
1095
- hideNames: !isServe,
1096
- serverImport: (specifier, name) => serverImport(file, specifier, name),
1097
- resolveModule: (specifier, importer) => {
1098
- const local = resolveFromDisk(specifier, importer);
1099
- const found = local === void 0 && isPackageSpecifier(specifier) ? resolvePackageImport(specifier, importer) : void 0;
1100
- return found ? {
1101
- path: found,
1102
- source: readFileSync(found, "utf8")
1103
- } : local;
1104
- }
1105
- });
1106
- const compileFile = async (file) => {
2072
+ function compileOptions(file) {
2073
+ return {
2074
+ filename: getFileName(file),
2075
+ liveProps: liveProps.get(file),
2076
+ refreshed,
2077
+ path: file,
2078
+ merge: options.merge ?? 4096,
2079
+ a11y: options.a11y,
2080
+ hideNames: !isServe,
2081
+ sendableClasses: serialClasses(),
2082
+ serverImport: (specifier, name) => serverImport(file, specifier, name),
2083
+ resolveModule: (specifier, importer) => {
2084
+ const local = resolveFromDisk(specifier, importer);
2085
+ const found = local === void 0 ? resolveComponentPackage(packages, specifier, importer) : void 0;
2086
+ return found ? {
2087
+ path: found,
2088
+ source: readFileSync(found, "utf8")
2089
+ } : local;
2090
+ }
2091
+ };
2092
+ }
2093
+ async function compileFile(file) {
1107
2094
  const source = await readFile(file, "utf8");
1108
2095
  let cached = compiled.get(file);
1109
2096
  if (cached?.source !== source) {
@@ -1112,10 +2099,10 @@ function brumate(options = {}) {
1112
2099
  result: compile(source, compileOptions(file))
1113
2100
  };
1114
2101
  compiled.set(file, cached);
1115
- shapes.set(file, shapeOf(cached.result));
2102
+ shapes.set(file, getShape(cached.result));
1116
2103
  }
1117
2104
  return cached;
1118
- };
2105
+ }
1119
2106
  /** The compiles whose imports were checked for the env file. */
1120
2107
  const envChecked = /* @__PURE__ */ new WeakSet();
1121
2108
  /**
@@ -1123,15 +2110,17 @@ function brumate(options = {}) {
1123
2110
  * when one of its imports resolves to it, by any specifier, such as an
1124
2111
  * alias. The compile fails when code that runs in the browser reads one.
1125
2112
  */
1126
- const checkEnvReads = async (file, { source, result }, resolve) => {
2113
+ async function checkEnvReads(file, { source, result }, resolve) {
1127
2114
  const env = envFile();
1128
2115
  if (!env || envChecked.has(result)) return;
1129
2116
  const specifiers = /* @__PURE__ */ new Set();
1130
2117
  for (const declaration of result.plan.graph.model.declarations) if (declaration.imported) specifiers.add(declaration.imported.source);
1131
- const resolved = await Promise.all([...specifiers].map(async (specifier) => {
2118
+ const pending = [];
2119
+ for (const specifier of specifiers) pending.push((async () => {
1132
2120
  return (await resolve(specifier, file))?.id.split("?")[0] === env ? specifier : void 0;
1133
- }));
1134
- const imports = new Set(resolved.filter((specifier) => specifier !== void 0));
2121
+ })());
2122
+ const imports = /* @__PURE__ */ new Set();
2123
+ for (const specifier of await Promise.all(pending)) if (specifier !== void 0) imports.add(specifier);
1135
2124
  if (imports.size > 0) {
1136
2125
  const server = serverEnvKeys() ?? [];
1137
2126
  compile(source, {
@@ -1140,13 +2129,141 @@ function brumate(options = {}) {
1140
2129
  });
1141
2130
  }
1142
2131
  envChecked.add(result);
1143
- };
1144
- const manifest = async () => {
2132
+ }
2133
+ /** The components that a component imports, by file. */
2134
+ async function componentImports(file) {
2135
+ const { result } = await compileFile(file);
2136
+ const found = [];
2137
+ for (const declaration of result.plan.graph.model.declarations) {
2138
+ const source = declaration.imported?.source;
2139
+ const target = source?.endsWith(".brm") ? resolveComponent(source, file) : void 0;
2140
+ if (target !== void 0) found.push(target);
2141
+ }
2142
+ return found;
2143
+ }
2144
+ /**
2145
+ * The bundles of a build: for each component that no other component imports, such as a
2146
+ * route or a page, the components with client code that it can render. The page loads the
2147
+ * bundles of its roots at once, as one chunk each, so its code comes in one request.
2148
+ * Components that only import each other get a bundle too.
2149
+ */
2150
+ async function bundles(kept) {
2151
+ const imports = /* @__PURE__ */ new Map();
2152
+ await inBatches([...files.values()], async (file) => {
2153
+ try {
2154
+ imports.set(file, await componentImports(file));
2155
+ } catch {
2156
+ imports.set(file, []);
2157
+ }
2158
+ });
2159
+ const imported = /* @__PURE__ */ new Set();
2160
+ for (const targets of imports.values()) for (const target of targets) imported.add(target);
2161
+ const result = /* @__PURE__ */ new Map();
2162
+ const reached = /* @__PURE__ */ new Set();
2163
+ function addRoot(id, file) {
2164
+ const seen = /* @__PURE__ */ new Set();
2165
+ function walk(current) {
2166
+ if (seen.has(current)) return;
2167
+ seen.add(current);
2168
+ reached.add(current);
2169
+ for (const next of imports.get(current) ?? []) walk(next);
2170
+ }
2171
+ walk(file);
2172
+ const members = [];
2173
+ for (const member of seen) if (kept.has(member)) members.push(member);
2174
+ if (members.length > 0) result.set(id, members);
2175
+ }
2176
+ for (const [id, file] of files) if (!imported.has(file)) addRoot(id, file);
2177
+ for (const [id, file] of files) if (!reached.has(file) && kept.has(file)) addRoot(id, file);
2178
+ return result;
2179
+ }
2180
+ /** The ID of each component file. */
2181
+ function findComponentId(file) {
2182
+ for (const [id, other] of files) if (other === file) return id;
2183
+ }
2184
+ /** A bundle module: the client modules of a root component and of those it renders. */
2185
+ async function bundleModule(root) {
1145
2186
  const list = [...files];
1146
- const needed = await Promise.all(list.map(async ([, file]) => isServe || (await compileFile(file)).result.clientCode));
2187
+ const needed = await inBatches(list, async ([, file]) => (await compileFile(file)).result.clientCode);
2188
+ const kept = /* @__PURE__ */ new Set();
2189
+ for (const [index, [, file]] of list.entries()) if (needed[index]) kept.add(file);
2190
+ const members = (await bundles(kept)).get(root) ?? [];
2191
+ const imports = [];
2192
+ const objects = [];
2193
+ for (const [index, file] of members.entries()) {
2194
+ const { result } = await compileFile(file);
2195
+ const codes = [result.client];
2196
+ for (const [name, code] of Object.entries(result.parts)) if (name !== "shared") codes.push(code);
2197
+ const names = exportNames(codes);
2198
+ const aliased = [];
2199
+ const fields = [];
2200
+ for (const name of names) {
2201
+ aliased.push(`${name} as $$c${index}_${name}`);
2202
+ fields.push(`${name}: $$c${index}_${name}`);
2203
+ }
2204
+ imports.push(`import { ${aliased.join(", ")} } from ${JSON.stringify(`${file}${CLIENT_QUERY}`)};`);
2205
+ objects.push(` ${JSON.stringify(findComponentId(file))}: { ${fields.join(", ")} },`);
2206
+ }
2207
+ return [
2208
+ ...imports,
2209
+ "export const modules = {",
2210
+ ...objects,
2211
+ "};"
2212
+ ].join("\n");
2213
+ }
2214
+ async function manifest() {
2215
+ const list = [...files];
2216
+ const needed = await inBatches(list, async ([, file]) => isServe || (await compileFile(file)).result.clientCode);
2217
+ const kept = [];
2218
+ for (const [index, entry] of list.entries()) if (needed[index]) kept.push(entry);
2219
+ if (!isServe) {
2220
+ const keptFiles = /* @__PURE__ */ new Set();
2221
+ for (const [, file] of kept) keptFiles.add(file);
2222
+ const groups = await bundles(keptFiles);
2223
+ const owners = /* @__PURE__ */ new Map();
2224
+ for (const [root, members] of groups) for (const member of members) {
2225
+ const id = findComponentId(member);
2226
+ if (id !== void 0 && !owners.has(id)) owners.set(id, root);
2227
+ }
2228
+ const bundleLines = [];
2229
+ for (const root of groups.keys()) bundleLines.push(` ${JSON.stringify(root)}: () => import(${JSON.stringify(`${BUNDLE}${root}`)}),`);
2230
+ return [
2231
+ "const bundles = {",
2232
+ ...bundleLines,
2233
+ "};",
2234
+ `const owners = ${JSON.stringify(Object.fromEntries(owners))};`,
2235
+ "const loaded = new Map();",
2236
+ "const pending = new Map();",
2237
+ "/** Loads the bundle of a root component of the page. Undefined for a component that is not a root. */",
2238
+ "export function loadBundle(root) {",
2239
+ " let promise = pending.get(root);",
2240
+ " if (!promise && bundles[root]) {",
2241
+ " promise = bundles[root]().then((bundle) => {",
2242
+ " for (const [id, module] of Object.entries(bundle.modules)) {",
2243
+ " loaded.set(id, module);",
2244
+ " }",
2245
+ " });",
2246
+ " pending.set(root, promise);",
2247
+ " promise.catch(() => pending.delete(root));",
2248
+ " }",
2249
+ " return promise;",
2250
+ "}",
2251
+ "/** The client module of a component, from the bundles of the page, or else from a bundle that holds it. */",
2252
+ "export function load(id) {",
2253
+ " if (loaded.has(id)) {",
2254
+ " return Promise.resolve(loaded.get(id));",
2255
+ " }",
2256
+ " const waiting = [...pending.values()];",
2257
+ " const owner = () => (loaded.has(id) || !owners[id] ? loaded.get(id) : loadBundle(owners[id]).then(() => loaded.get(id)));",
2258
+ " return waiting.length > 0 ? Promise.allSettled(waiting).then(owner) : owners[id] ? owner() : undefined;",
2259
+ "}"
2260
+ ].join("\n");
2261
+ }
2262
+ const entries = [];
2263
+ for (const [id, file] of kept) entries.push(` ${JSON.stringify(id)}: () => import(${JSON.stringify(`${file}${CLIENT_QUERY}`)}),`);
1147
2264
  return [
1148
2265
  "const modules = {",
1149
- ...list.filter((_, index) => needed[index]).map(([id, file]) => ` ${JSON.stringify(id)}: () => import(${JSON.stringify(`${file}${CLIENT_QUERY}`)}),`),
2266
+ ...entries,
1150
2267
  "};",
1151
2268
  "export function load(id) {",
1152
2269
  ...isServe ? [
@@ -1158,36 +2275,62 @@ function brumate(options = {}) {
1158
2275
  ] : [" return modules[id]?.();"],
1159
2276
  "}"
1160
2277
  ].join("\n");
1161
- };
2278
+ }
1162
2279
  /**
1163
2280
  * The module of every server function of the app, by ID. With `server`, in
1164
2281
  * a DOM test, it imports the server code of each file, which that
1165
2282
  * environment would give as browser code.
1166
2283
  */
1167
- const serverRegistry = (server = false) => {
2284
+ function serverRegistry(server = false) {
1168
2285
  const query = server ? SERVER_QUERY : "";
1169
2286
  registered = packages.length > 0 ? reachable() : /* @__PURE__ */ new Set();
1170
- const keep = (file) => registered.has(file) || !packageOf(packages, file);
1171
- const components = [...files.values()].filter(keep);
1172
- const imports = components.map((file, index) => `import * as m${index} from ${JSON.stringify(file + query)};`);
1173
- const spreads = components.map((_, index) => ` ...m${index}.rpc,`);
1174
- const functionFiles = [...serverFiles.entries()].filter(([, file]) => keep(file));
1175
- const fileImports = functionFiles.map(([, file], index) => `import * as f${index} from ${JSON.stringify(file + query)};`);
2287
+ function keep(file) {
2288
+ return registered.has(file) || !findPackage(packages, file);
2289
+ }
2290
+ const components = [];
2291
+ for (const file of files.values()) if (keep(file)) components.push(file);
2292
+ function importAll(prefix, list) {
2293
+ if (!isServe) {
2294
+ const lines = [];
2295
+ for (const [index, file] of list.entries()) lines.push(`import * as ${prefix}${index} from ${JSON.stringify(file + query)};`);
2296
+ return lines;
2297
+ }
2298
+ if (list.length === 0) return [];
2299
+ const loads = [];
2300
+ const names = [];
2301
+ for (const [index, file] of list.entries()) {
2302
+ loads.push(`import(${JSON.stringify(file + query)})`);
2303
+ names.push(`${prefix}${index}`);
2304
+ }
2305
+ return [`const [${names.join(", ")}] = (await Promise.allSettled([${loads.join(", ")}])).map((result) => (result.status === 'fulfilled' ? result.value : {}));`];
2306
+ }
2307
+ const imports = importAll("m", components);
2308
+ const spreads = [];
2309
+ for (const index of components.keys()) spreads.push(` ...m${index}.rpc,`);
2310
+ const functionFiles = [];
2311
+ for (const entry of serverFiles) if (keep(entry[1])) functionFiles.push(entry);
2312
+ const functionPaths = [];
2313
+ for (const [, file] of functionFiles) functionPaths.push(file);
2314
+ const fileImports = importAll("f", functionPaths);
1176
2315
  const guards = [];
1177
- const fileSpreads = functionFiles.map(([id, file], index) => {
2316
+ const fileSpreads = [];
2317
+ for (const [index, [id, file]] of functionFiles.entries()) {
1178
2318
  const source = readFileSync(file, "utf8");
1179
2319
  const names = serverExports(source, file);
1180
2320
  const guarded = hasServerMiddleware(source, file);
1181
- return names.map((name) => {
2321
+ const lines = [];
2322
+ for (const name of names) {
1182
2323
  const key = JSON.stringify(functionId(id, name, !isServe));
1183
2324
  if (guarded) guards.push(` ${key}: f${index}.middleware,`);
1184
- return ` ${key}: f${index}[${JSON.stringify(name)}],`;
1185
- }).join("\n");
1186
- });
2325
+ lines.push(` ${key}: f${index}[${JSON.stringify(name)}],`);
2326
+ }
2327
+ fileSpreads.push(lines.join("\n"));
2328
+ }
1187
2329
  const env = envFile();
1188
2330
  const entry = middlewareFile();
1189
2331
  return [
1190
2332
  ...env ? [`import ${JSON.stringify(env)};`] : [],
2333
+ ...serialImports(),
1191
2334
  "import { handleRequest } from 'brumate/server';",
1192
2335
  ...entry ? [`import middleware from ${JSON.stringify(entry)};`] : [],
1193
2336
  ...imports,
@@ -1203,12 +2346,15 @@ function brumate(options = {}) {
1203
2346
  ` return handleRequest(functions, request, ${JSON.stringify(rpc)}, { origins: ${JSON.stringify(options.origins ?? [])}, ${entry ? "middleware, " : ""}fileMiddleware${buildId === void 0 ? "" : `, build: ${JSON.stringify(buildId)}`}, ...options });`,
1204
2347
  "}"
1205
2348
  ].join("\n");
1206
- };
1207
- const routesDirectory = () => normalizePath(path.resolve(root, options.routes ?? "src/routes"));
2349
+ }
2350
+ function routesDirectory() {
2351
+ return normalizePath(path.resolve(root, options.routes ?? "src/routes"));
2352
+ }
1208
2353
  /** The route files, from the `.brm` files found and the `.ts` files of the directory. */
1209
- const currentRoutes = () => {
2354
+ function currentRoutes() {
1210
2355
  const directory = routesDirectory();
1211
- const paths = [...files.values()].filter((file) => file.startsWith(`${directory}/`)).map((file) => file.slice(directory.length + 1));
2356
+ const paths = [];
2357
+ for (const file of files.values()) if (file.startsWith(`${directory}/`)) paths.push(file.slice(directory.length + 1));
1212
2358
  if (existsSync(directory)) for (const entry of readdirSync(directory, {
1213
2359
  recursive: true,
1214
2360
  encoding: "utf8"
@@ -1217,73 +2363,300 @@ function brumate(options = {}) {
1217
2363
  if (file.endsWith(".ts") && !file.endsWith(".d.ts")) paths.push(file);
1218
2364
  }
1219
2365
  return routeFiles(paths);
1220
- };
2366
+ }
1221
2367
  /**
1222
2368
  * The modules that every page loads early, which the client build wrote,
1223
2369
  * or none before a client build or in development.
1224
2370
  */
1225
- const clientHints = () => {
2371
+ function clientHints() {
1226
2372
  const file = path.join(clientBuildDirectory(root, options.prerender), HINTS_FILE);
1227
- return !isServe && existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : [];
1228
- };
2373
+ if (isServe || !existsSync(file)) return {
2374
+ all: [],
2375
+ bundles: {}
2376
+ };
2377
+ const read = JSON.parse(readFileSync(file, "utf8"));
2378
+ return Array.isArray(read) ? {
2379
+ all: read,
2380
+ bundles: {}
2381
+ } : read;
2382
+ }
1229
2383
  /** The route tree module. A DOM test gets the server version of each component in it. */
1230
- const routeTree = (server = false) => {
2384
+ function routeTree(server = false) {
1231
2385
  const env = envFile();
1232
- const code = routeModule(currentRoutes(), (file) => `${routesDirectory()}/${file}${server && file.endsWith(".brm") ? SERVER_QUERY : ""}`, rpc, options.origins, isServe, middlewareFile(), buildId, clientHints());
1233
- return env ? `import ${JSON.stringify(env)};\n${code}` : code;
1234
- };
2386
+ const code = routeModule(currentRoutes(), (file) => `${routesDirectory()}/${file}${server && file.endsWith(".brm") ? SERVER_QUERY : ""}`, rpc, options.origins, isServe, middlewareFile(), buildId, clientHints().all, clientHints().bundles);
2387
+ const serial = serialImports().join("\n");
2388
+ const parts = [];
2389
+ for (const part of [
2390
+ env ? `import ${JSON.stringify(env)};` : "",
2391
+ serial,
2392
+ code
2393
+ ]) if (part) parts.push(part);
2394
+ return parts.join("\n");
2395
+ }
1235
2396
  /** Writes the paths of the routes as types for `href`, when they changed. */
1236
- const writeRouteTypes = () => {
2397
+ function writeRouteTypes() {
1237
2398
  if (options.routeTypes === false || !existsSync(routesDirectory())) return;
1238
2399
  const file = path.resolve(root, options.routeTypes ?? "src/brumate-routes.d.ts");
1239
2400
  const text = routeTypes(currentRoutes());
1240
2401
  if (!existsSync(file) || readFileSync(file, "utf8") !== text) writeFileSync(file, text);
1241
- };
2402
+ }
1242
2403
  /** What the devtools panel shows about a component: its name, its scopes and its report. */
1243
- const inspectComponent = async (id) => {
2404
+ async function inspectComponent(id) {
1244
2405
  const file = files.get(id);
1245
2406
  if (!file) return;
1246
2407
  const { source, result } = await compileFile(file);
1247
2408
  const { plan } = result;
1248
2409
  const scopes = {};
1249
- for (const layout of plan.scopes.values()) scopes[layout.scope.id] = {
1250
- label: scopeLabel(result.file.source, layout.scope),
1251
- slots: layout.slots.map((slot) => slot.name)
1252
- };
1253
- const nodes = plan.graph.nodes.filter((node) => plan.graph.live.has(node));
1254
- const indexes = new Map(nodes.map((node, index) => [node, index]));
1255
- const graph = {
1256
- nodes: nodes.map((node) => {
1257
- if (node.kind === "source" || node.kind === "memo") return {
2410
+ function siteLabel(site) {
2411
+ const at = result.locate(site.range.start);
2412
+ const where = at.file === void 0 ? getLocation(source, at.offset) : void 0;
2413
+ return where ? `${site.label} ${where.line}:${where.column}` : site.label;
2414
+ }
2415
+ const liveSites = /* @__PURE__ */ new Set();
2416
+ for (const node of plan.graph.live) if ("site" in node) liveSites.add(node.site);
2417
+ for (const layout of plan.scopes.values()) {
2418
+ const slotNames = [];
2419
+ const readers = [];
2420
+ for (const slot of layout.slots) {
2421
+ slotNames.push(slot.name);
2422
+ const labels = /* @__PURE__ */ new Set();
2423
+ for (const ref of slot.reads) if (plan.graph.reached.has(ref.site) || liveSites.has(ref.site)) labels.add(siteLabel(ref.site));
2424
+ readers.push([...labels]);
2425
+ }
2426
+ scopes[layout.scope.id] = {
2427
+ label: scopeLabel(result.file.source, layout.scope),
2428
+ slots: slotNames,
2429
+ readers
2430
+ };
2431
+ }
2432
+ const nodes = [];
2433
+ const indexes = /* @__PURE__ */ new Map();
2434
+ for (const node of plan.graph.nodes) if (plan.graph.live.has(node)) {
2435
+ indexes.set(node, nodes.length);
2436
+ nodes.push(node);
2437
+ }
2438
+ const graphNodes = [];
2439
+ for (const node of nodes) {
2440
+ if (node.kind === "source" || node.kind === "memo") {
2441
+ graphNodes.push({
1258
2442
  kind: node.kind === "memo" ? "memo" : node.declaration.kind,
1259
2443
  label: node.declaration.name,
1260
2444
  scope: instanceScope(plan, node.declaration.scope).id,
1261
2445
  slot: slotIndex(plan, node.declaration)
1262
- };
1263
- const at = result.locate(node.site.range.start);
1264
- const where = at.file === void 0 ? getLocation(source, at.offset) : void 0;
1265
- return {
1266
- kind: node.kind,
1267
- label: where ? `${node.site.label} ${where.line}:${where.column}` : node.site.label,
1268
- scope: instanceScope(plan, node.site.scope).id
1269
- };
1270
- }),
1271
- edges: plan.graph.edges.filter((edge) => indexes.has(edge.from) && indexes.has(edge.to)).map((edge) => [indexes.get(edge.from), indexes.get(edge.to)])
2446
+ });
2447
+ continue;
2448
+ }
2449
+ const at = result.locate(node.site.range.start);
2450
+ const where = at.file === void 0 ? getLocation(source, at.offset) : void 0;
2451
+ graphNodes.push({
2452
+ kind: node.kind,
2453
+ label: where ? `${node.site.label} ${where.line}:${where.column}` : node.site.label,
2454
+ scope: instanceScope(plan, node.site.scope).id
2455
+ });
2456
+ }
2457
+ const graphEdges = [];
2458
+ for (const edge of plan.graph.edges) if (indexes.has(edge.from) && indexes.has(edge.to)) graphEdges.push([indexes.get(edge.from), indexes.get(edge.to)]);
2459
+ const graph = {
2460
+ nodes: graphNodes,
2461
+ edges: graphEdges
1272
2462
  };
2463
+ const anchors = {};
2464
+ for (const [target, index] of plan.anchors) {
2465
+ const scope = plan.anchorScopes.get(target);
2466
+ if (!scope) continue;
2467
+ const at = result.locate("range" in target ? target.range.start : target.start);
2468
+ const where = at.file === void 0 ? getLocation(source, at.offset) : void 0;
2469
+ const reads = /* @__PURE__ */ new Set();
2470
+ for (const edge of plan.graph.edges) {
2471
+ const node = edge.to;
2472
+ if (node.kind === "source" || node.kind === "memo") continue;
2473
+ const site = node.site;
2474
+ const range = !("range" in target) && target.kind === "insert" ? target : void 0;
2475
+ if (site === target || site.owner === target || site.block === target || range && site.range.start >= range.start && site.range.end <= range.end) {
2476
+ if (edge.from.kind === "source" || edge.from.kind === "memo") reads.add(edge.from.declaration.name);
2477
+ }
2478
+ }
2479
+ const known = anchors[scope.id]?.[index];
2480
+ if (known) {
2481
+ known.reads = [.../* @__PURE__ */ new Set([...known.reads, ...reads])];
2482
+ continue;
2483
+ }
2484
+ (anchors[scope.id] ??= {})[index] = {
2485
+ label: anchorLabel(target),
2486
+ ...where ? { at: `${where.line}:${where.column}` } : {},
2487
+ reads: [...reads]
2488
+ };
2489
+ }
1273
2490
  const text = formatReport(report(source, result, liveProps.get(file)));
1274
2491
  return {
1275
2492
  name: plan.name,
1276
- file: nameOf(file),
2493
+ file: getFileName(file),
2494
+ path: file,
2495
+ url: file.startsWith(`${normalizePath(root)}/`) ? file.slice(normalizePath(root).length) : `/@fs${file}`,
1277
2496
  scopes,
2497
+ anchors,
1278
2498
  graph,
1279
2499
  text
1280
2500
  };
1281
- };
1282
- const handleDevRPC = async (server, request, response) => {
2501
+ }
2502
+ /** The components of the app for the workbench, with what each one needs and its controls. */
2503
+ /**
2504
+ * The stories of a component: the named exports of the `.stories.ts` file next to it, each a
2505
+ * set of props. Values that JSON cannot hold, such as functions, are left out.
2506
+ */
2507
+ async function workbenchStories(server, file) {
2508
+ const storiesFile = file.replace(/\.brm$/, ".stories.ts");
2509
+ if (!existsSync(storiesFile)) return { stories: [] };
2510
+ try {
2511
+ const module = await server.ssrLoadModule(storiesFile);
2512
+ const stories = [];
2513
+ for (const [name, props] of Object.entries(module)) if (name !== "default" && props && typeof props === "object") stories.push({
2514
+ name,
2515
+ props: JSON.parse(JSON.stringify(props))
2516
+ });
2517
+ return { stories };
2518
+ } catch (error) {
2519
+ return {
2520
+ stories: [],
2521
+ storiesError: error instanceof Error ? error.message : String(error)
2522
+ };
2523
+ }
2524
+ }
2525
+ /** The group of a component of a package: its name, and the folder under the directory of its files. */
2526
+ function packageGroup(owner, file) {
2527
+ let directory = owner.root;
2528
+ for (const item of owner.directories) if (file.startsWith(`${item}/`)) {
2529
+ directory = item;
2530
+ break;
2531
+ }
2532
+ const folder = path.posix.dirname(file.slice(directory.length + 1));
2533
+ return folder === "." ? owner.name : `${owner.name}/${folder}`;
2534
+ }
2535
+ async function workbenchComponents(server) {
2536
+ const routes = `${routesDirectory()}/`;
2537
+ const list = [...new Set(files.values())];
2538
+ const contents = await inBatches(list, (file) => readFile(file, "utf8"));
2539
+ const sources = /* @__PURE__ */ new Map();
2540
+ for (const [index, file] of list.entries()) sources.set(file, contents[index]);
2541
+ const classes = classifyComponents(sources, {
2542
+ resolve: resolveComponent,
2543
+ serverImport: (file, specifier, name) => serverImport(file, specifier, name) !== void 0
2544
+ });
2545
+ function relative(file) {
2546
+ return normalizePath(path.relative(root, file));
2547
+ }
2548
+ const shown = [];
2549
+ for (const file of list) if (!file.startsWith(routes) && classes.has(file)) shown.push(file);
2550
+ const stories = await inBatches(shown, (file) => workbenchStories(server, file));
2551
+ const components = [];
2552
+ for (const [index, file] of shown.entries()) {
2553
+ const found = classes.get(file);
2554
+ let controls = [];
2555
+ try {
2556
+ controls = propControls(parse(sources.get(file), { filename: file }));
2557
+ } catch {
2558
+ controls = void 0;
2559
+ }
2560
+ const owner = findPackage(packages, file);
2561
+ const needs = [];
2562
+ for (const need of found.needs) needs.push({
2563
+ ...need,
2564
+ via: need.via && relative(need.via)
2565
+ });
2566
+ components.push({
2567
+ file: relative(file),
2568
+ group: owner ? packageGroup(owner, file) : path.posix.dirname(relative(file)),
2569
+ label: owner ? `${packageGroup(owner, file)}/${path.basename(file)}` : relative(file),
2570
+ name: path.basename(file, ".brm"),
2571
+ selfContained: found.selfContained,
2572
+ needs,
2573
+ controls: controls ?? [],
2574
+ unreadProps: controls === void 0,
2575
+ ...stories[index]
2576
+ });
2577
+ }
2578
+ return components.toSorted((a, b) => a.file.localeCompare(b.file));
2579
+ }
2580
+ let workbenchList;
2581
+ /** Makes the list of the workbench and keeps it, unless it fails, so a later read tries again. */
2582
+ function listWorkbench(server) {
2583
+ const list = workbenchComponents(server);
2584
+ workbenchList = list;
2585
+ list.catch(() => {
2586
+ if (workbenchList === list) workbenchList = void 0;
2587
+ });
2588
+ return list;
2589
+ }
2590
+ /**
2591
+ * Answers the workbench: its page, the list of components, and the frame that renders one
2592
+ * component on the server with props, and resumes it in the browser as a page does.
2593
+ */
2594
+ async function serveWorkbench(server, request, response) {
2595
+ const url = new URL(request.url ?? "/", "http://localhost");
2596
+ if (url.pathname === WORKBENCH || url.pathname === `${WORKBENCH}/`) {
2597
+ response.setHeader("content-type", "text/html; charset=utf-8");
2598
+ response.end(workbenchPage(WORKBENCH));
2599
+ return;
2600
+ }
2601
+ if (url.pathname === `${WORKBENCH}/components`) {
2602
+ response.setHeader("content-type", "application/json");
2603
+ response.end(JSON.stringify(await listWorkbench(server)));
2604
+ return;
2605
+ }
2606
+ if (url.pathname !== `${WORKBENCH}/frame`) {
2607
+ response.statusCode = 404;
2608
+ response.end();
2609
+ return;
2610
+ }
2611
+ const asked = url.searchParams.get("file") ?? "";
2612
+ let listed = false;
2613
+ for (const component of await (workbenchList ?? listWorkbench(server))) if (component.file === asked && component.selfContained) {
2614
+ listed = true;
2615
+ break;
2616
+ }
2617
+ let file;
2618
+ if (listed) {
2619
+ for (const candidate of files.values()) if (normalizePath(path.relative(root, candidate)) === asked) {
2620
+ file = candidate;
2621
+ break;
2622
+ }
2623
+ }
2624
+ if (!file) {
2625
+ response.statusCode = 404;
2626
+ response.end(`No self-contained component "${asked}"`);
2627
+ return;
2628
+ }
2629
+ response.setHeader("content-type", "text/html; charset=utf-8");
2630
+ try {
2631
+ const props = JSON.parse(url.searchParams.get("props") || "{}");
2632
+ const component = (await server.ssrLoadModule(file)).default;
2633
+ const { renderToStream } = await server.ssrLoadModule("brumate/server");
2634
+ const reader = renderToStream(component, props, {
2635
+ start: `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${path.basename(file, ".brm")}</title></head><body>`,
2636
+ end: "</body></html>",
2637
+ scripts: `<script type="module" src="/@vite/client"><\/script><script type="module" src="/@id/__x00__${START}"><\/script>`
2638
+ }).getReader();
2639
+ for (;;) {
2640
+ const { done, value } = await reader.read();
2641
+ if (done) break;
2642
+ response.write(value);
2643
+ }
2644
+ response.end();
2645
+ } catch (error) {
2646
+ if (response.headersSent) {
2647
+ server.config.logger.error(error instanceof Error ? error.stack ?? error.message : String(error));
2648
+ response.end();
2649
+ return;
2650
+ }
2651
+ response.statusCode = 500;
2652
+ response.end(errorPage(error, server));
2653
+ }
2654
+ }
2655
+ async function handleDevRPC(server, request, response) {
1283
2656
  const id = decodeURIComponent((request.url ?? "").slice(rpc.length + 1).split("?")[0]);
1284
2657
  const owner = id.split("#")[0];
1285
2658
  const file = files.get(owner) ?? serverFiles.get(owner);
1286
- const reached = file && packageOf(packages, file) ? reachable() : void 0;
2659
+ const reached = file && findPackage(packages, file) ? reachable() : void 0;
1287
2660
  if (!file || reached && !reached.has(file)) {
1288
2661
  response.statusCode = 404;
1289
2662
  response.end(`Unknown server function "${id}"`);
@@ -1295,11 +2668,16 @@ function brumate(options = {}) {
1295
2668
  }
1296
2669
  try {
1297
2670
  const { handle } = await server.ssrLoadModule(SERVER);
1298
- const answer = await handle(new Request(new URL(request.url ?? "/", "http://localhost"), {
2671
+ const headers = [];
2672
+ for (const [name, value] of Object.entries(request.headers)) if (value !== void 0) headers.push([name, String(value)]);
2673
+ const webRequest = new Request(new URL(request.url ?? "/", "http://localhost"), {
1299
2674
  method: "POST",
1300
- headers: Object.entries(request.headers).flatMap(([name, value]) => value === void 0 ? [] : [[name, String(value)]]),
2675
+ headers,
1301
2676
  body: new Uint8Array(await readBody(request))
1302
- }), { address: request.socket.remoteAddress });
2677
+ });
2678
+ const began = performance.now();
2679
+ const answer = await handle(webRequest, { address: request.socket.remoteAddress });
2680
+ answer.headers.append("server-timing", `brumate;dur=${(performance.now() - began).toFixed(1)};desc="server function"`);
1303
2681
  response.statusCode = answer.status;
1304
2682
  for (const [name, value] of Object.entries(toNodeHeaders(answer.headers))) response.setHeader(name, value);
1305
2683
  response.end(await answer.text());
@@ -1308,30 +2686,30 @@ function brumate(options = {}) {
1308
2686
  response.statusCode = 500;
1309
2687
  response.end(String(error));
1310
2688
  }
1311
- };
2689
+ }
1312
2690
  /** Updates the page in the browser after a change to a component, or reloads it. */
1313
2691
  async function updateClient(file, server, timestamp) {
1314
2692
  const normalized = normalizePath(file);
1315
2693
  const targets = file.endsWith(".brm") ? [normalized] : [...dependents.get(normalized) ?? []];
1316
2694
  if (targets.length === 0) return;
1317
- const invalidate = () => {
2695
+ function invalidate() {
1318
2696
  for (const module of server.moduleGraph.idToModuleMap.values()) {
1319
2697
  const id = module.id ?? "";
1320
2698
  if (id.includes(".brm") || id === `\0${MANIFEST}` || id === `\0${SERVER}` || id === `\0${ROUTES}`) server.moduleGraph.invalidateModule(module);
1321
2699
  }
1322
- };
1323
- const reload = () => {
2700
+ }
2701
+ function reload() {
1324
2702
  invalidate();
1325
2703
  server.ws.send({ type: "full-reload" });
1326
2704
  return [];
1327
- };
2705
+ }
1328
2706
  await analyze();
1329
2707
  const updates = [];
1330
2708
  for (const target of targets) {
1331
2709
  const before = shapes.get(target);
1332
2710
  let after;
1333
2711
  try {
1334
- after = shapeOf((await compileFile(target)).result);
2712
+ after = getShape((await compileFile(target)).result);
1335
2713
  } catch {
1336
2714
  return reload();
1337
2715
  }
@@ -1340,7 +2718,13 @@ function brumate(options = {}) {
1340
2718
  const id = componentId(target);
1341
2719
  const modules = [...server.moduleGraph.getModulesByFile(target) ?? [], ...target === normalized ? [] : server.moduleGraph.getModulesByFile(normalized) ?? []];
1342
2720
  for (const module of modules) server.moduleGraph.invalidateModule(module, /* @__PURE__ */ new Set(), timestamp, true);
1343
- const entry = [...server.moduleGraph.getModulesByFile(target) ?? []].find((module) => module.id?.endsWith(CLIENT_QUERY));
2721
+ let entry;
2722
+ for (const module of server.moduleGraph.getModulesByFile(target) ?? []) if (module.id?.endsWith(CLIENT_QUERY)) {
2723
+ entry = module;
2724
+ break;
2725
+ }
2726
+ const kept = [];
2727
+ for (const name of after.signals) if (before.signals.includes(name)) kept.push(name);
1344
2728
  updates.push({
1345
2729
  id,
1346
2730
  css: before.css === after.css ? void 0 : after.css,
@@ -1348,11 +2732,16 @@ function brumate(options = {}) {
1348
2732
  remount: remount ? {
1349
2733
  before: before.slots,
1350
2734
  after: after.slots,
1351
- signals: after.signals.filter((name) => before.signals.includes(name))
2735
+ signals: kept
1352
2736
  } : void 0
1353
2737
  });
1354
2738
  }
1355
- if (updates.some((update) => update.remount)) invalidate();
2739
+ let remounts = false;
2740
+ for (const update of updates) if (update.remount) {
2741
+ remounts = true;
2742
+ break;
2743
+ }
2744
+ if (remounts) invalidate();
1356
2745
  server.ws.send({
1357
2746
  type: "custom",
1358
2747
  event: "brumate:update",
@@ -1368,19 +2757,22 @@ function brumate(options = {}) {
1368
2757
  * or their `.brm` and `'use server'` files would not reach this plugin, and the
1369
2758
  * server build compiles them instead of importing them from `node_modules`.
1370
2759
  */
1371
- const packageConfig = (config) => {
2760
+ function packageConfig(config) {
1372
2761
  if (packages.length === 0) return {};
1373
- const names = [...new Set(packages.map((item) => item.name))];
2762
+ const nameSet = /* @__PURE__ */ new Set();
2763
+ for (const item of packages) nameSet.add(item.name);
2764
+ const names = [...nameSet];
1374
2765
  const result = {
1375
2766
  optimizeDeps: { exclude: names },
1376
2767
  ssr: { noExternal: names },
1377
2768
  resolve: { dedupe: ["brumate"] }
1378
2769
  };
1379
2770
  const workspace = normalizePath(searchForWorkspaceRoot(path.resolve(config.root ?? ".")));
1380
- const outside = packages.filter((item) => item.root !== workspace && !item.root.startsWith(`${workspace}/`)).map((item) => item.root);
2771
+ const outside = [];
2772
+ for (const item of packages) if (item.root !== workspace && !item.root.startsWith(`${workspace}/`)) outside.push(item.root);
1381
2773
  if (outside.length > 0) result.server = { fs: { allow: [workspace, ...outside] } };
1382
2774
  return result;
1383
- };
2775
+ }
1384
2776
  /** The module ID of `brumate/client`, and the chunks of the loader and the core in a client build. */
1385
2777
  let coreModule;
1386
2778
  let loaderChunk;
@@ -1391,6 +2783,8 @@ function brumate(options = {}) {
1391
2783
  config(config, env) {
1392
2784
  packages = findPackages(path.resolve(config.root ?? process.cwd()));
1393
2785
  const shared = packageConfig(config);
2786
+ const hmr = config.server?.hmr;
2787
+ if (env.command === "serve" && options.devtools !== false && hmr !== false && (typeof hmr !== "object" || hmr.overlay === void 0)) shared.server = { hmr: { overlay: false } };
1394
2788
  if (!env.isSsrBuild) {
1395
2789
  const preload = config.build?.modulePreload;
1396
2790
  const keep = options.skew?.keep ? { build: { emptyOutDir: false } } : {};
@@ -1406,7 +2800,8 @@ function brumate(options = {}) {
1406
2800
  modulePreload: { resolveDependencies(filename, deps, context) {
1407
2801
  const list = resolve ? resolve(filename, deps, context) : deps;
1408
2802
  if (context.hostId !== loaderChunk || !coreChunk) return list;
1409
- const rest = list.filter((dep) => dep !== coreChunk);
2803
+ const rest = [];
2804
+ for (const dep of list) if (dep !== coreChunk) rest.push(dep);
1410
2805
  return rest.length === 1 && rest[0] === filename ? [] : rest;
1411
2806
  } }
1412
2807
  }
@@ -1415,7 +2810,12 @@ function brumate(options = {}) {
1415
2810
  if (!options.prerender) return shared;
1416
2811
  const ssr = config.build?.ssr;
1417
2812
  const input = typeof ssr === "string" ? ssr : config.build?.rolldownOptions?.input;
1418
- const entries = typeof input === "string" ? { [path.basename(input).replace(/\.[^.]+$/, "")]: input } : Array.isArray(input) ? Object.fromEntries(input.map((item) => [path.basename(item).replace(/\.[^.]+$/, ""), item])) : { ...input };
2813
+ let entries;
2814
+ if (typeof input === "string") entries = { [path.basename(input).replace(/\.[^.]+$/, "")]: input };
2815
+ else if (Array.isArray(input)) {
2816
+ entries = {};
2817
+ for (const item of input) entries[path.basename(item).replace(/\.[^.]+$/, "")] = item;
2818
+ } else entries = { ...input };
1419
2819
  return {
1420
2820
  ...shared,
1421
2821
  build: {
@@ -1428,7 +2828,7 @@ function brumate(options = {}) {
1428
2828
  };
1429
2829
  },
1430
2830
  configureVitest(context) {
1431
- (context.defineCacheKeyGenerator ?? context.experimental_defineCacheKeyGenerator)?.(buildFingerprint);
2831
+ (context.defineCacheKeyGenerator ?? context.experimental_defineCacheKeyGenerator)?.(cacheKey);
1432
2832
  },
1433
2833
  configResolved(config) {
1434
2834
  root = config.root;
@@ -1439,6 +2839,13 @@ function brumate(options = {}) {
1439
2839
  },
1440
2840
  async generateBundle(_output, bundle) {
1441
2841
  if (isSsrBuild) return;
2842
+ for (const file of knownFeatures ? loadedComponents : []) {
2843
+ if (counted.has(file)) continue;
2844
+ const used = getFeatures((await compileFile(file)).result);
2845
+ const missing = [];
2846
+ for (const name of Object.keys(used)) if (used[name] && !knownFeatures[name]) missing.push(name);
2847
+ if (missing.length > 0) this.error(`${getFileName(file)} uses ${missing.join(", ")}, which the client build left out of the core, since no component that the build found uses them. Import it from a .brm component of the app, or set \`features: 'all'\`.`);
2848
+ }
1442
2849
  loaderChunk = void 0;
1443
2850
  coreChunk = void 0;
1444
2851
  for (const item of Object.values(bundle)) {
@@ -1448,66 +2855,87 @@ function brumate(options = {}) {
1448
2855
  }
1449
2856
  if (!options.report && !options.budget) return;
1450
2857
  const chunks = [];
1451
- for (const item of Object.values(bundle)) if (item.type === "chunk") chunks.push({
1452
- fileName: item.fileName,
1453
- code: item.code,
1454
- isEntry: item.isEntry,
1455
- imports: item.imports,
1456
- moduleIds: item.moduleIds,
1457
- modules: Object.fromEntries(Object.entries(item.modules).map(([id, module]) => [id, module.renderedLength]))
1458
- });
1459
- const list = [...files.values()];
1460
- const contents = await Promise.all(list.map((file) => readFile(file, "utf8")));
1461
- const events = [];
1462
- for (const [file, { source, result }] of compiled) for (const [site, symbol] of result.plan.symbols) {
1463
- const loads = result.loaders[symbol];
1464
- if (loads) {
1465
- const { line, column } = getLocation(source, site.range.start);
1466
- events.push({
1467
- file,
1468
- label: `${site.label} (${line}:${column})`,
1469
- parts: loads
1470
- });
1471
- }
2858
+ for (const item of Object.values(bundle)) if (item.type === "chunk") {
2859
+ const modules = {};
2860
+ for (const [id, module] of Object.entries(item.modules)) modules[id] = module.renderedLength;
2861
+ chunks.push({
2862
+ fileName: item.fileName,
2863
+ code: item.code,
2864
+ isEntry: item.isEntry,
2865
+ imports: item.imports,
2866
+ moduleIds: item.moduleIds,
2867
+ modules
2868
+ });
1472
2869
  }
2870
+ const list = [...files.values()];
2871
+ const contents = await inBatches(list, (file) => readFile(file, "utf8"));
2872
+ const sources = /* @__PURE__ */ new Map();
2873
+ for (const [index, file] of list.entries()) sources.set(file, contents[index]);
1473
2874
  const measured = buildReport({
1474
2875
  chunks,
1475
- sources: new Map(list.map((file, index) => [file, contents[index]])),
2876
+ sources,
1476
2877
  routes: existsSync(routesDirectory()) ? {
1477
2878
  tree: currentRoutes(),
1478
2879
  resolve: (file) => `${routesDirectory()}/${file}`
1479
2880
  } : void 0,
1480
- events,
1481
2881
  budget: options.budget,
1482
- relative: nameOf
2882
+ relative: getFileName
1483
2883
  });
1484
- if (options.report) this.info(`\n${formatBuildReport(measured, nameOf)}`);
2884
+ if (options.report) this.info(`\n${formatBuildReport(measured, getFileName)}`);
1485
2885
  if (measured.overBudget.length > 0) this.error(measured.overBudget.join("\n"));
1486
2886
  },
1487
2887
  async writeBundle(_output, bundle) {
1488
2888
  if (!isSsrBuild) {
1489
- const chunks = new Map(Object.values(bundle).flatMap((item) => item.type === "chunk" ? [[item.fileName, item]] : []));
2889
+ const chunks = /* @__PURE__ */ new Map();
2890
+ for (const item of Object.values(bundle)) if (item.type === "chunk") chunks.set(item.fileName, item);
1490
2891
  const hints = /* @__PURE__ */ new Set();
1491
- const add = (name) => {
2892
+ function add(name) {
1492
2893
  const chunk = name === void 0 ? void 0 : chunks.get(name);
1493
2894
  if (chunk && !hints.has(chunk.fileName)) {
1494
2895
  hints.add(chunk.fileName);
1495
- chunk.imports.forEach(add);
2896
+ for (const imported of chunk.imports) add(imported);
1496
2897
  }
1497
- };
2898
+ }
1498
2899
  add(loaderChunk);
1499
2900
  add(coreChunk);
2901
+ const bundleHints = {};
2902
+ for (const chunk of chunks.values()) {
2903
+ const facade = chunk.facadeModuleId ?? "";
2904
+ if (!facade.startsWith(`\0${BUNDLE}`)) continue;
2905
+ const files = /* @__PURE__ */ new Set();
2906
+ function walk(name) {
2907
+ const found = chunks.get(name);
2908
+ if (found && !files.has(name) && !hints.has(name)) {
2909
+ files.add(name);
2910
+ for (const imported of found.imports) walk(imported);
2911
+ }
2912
+ }
2913
+ walk(chunk.fileName);
2914
+ const urls = [];
2915
+ for (const name of files) urls.push(`${base}${name}`);
2916
+ bundleHints[facade.slice(24)] = urls;
2917
+ }
1500
2918
  await mkdir(path.join(outDir, ".brumate"), { recursive: true });
1501
- await writeFile(path.join(outDir, HINTS_FILE), JSON.stringify([...hints].map((name) => `${base}${name}`)));
2919
+ const all = [];
2920
+ for (const name of hints) all.push(`${base}${name}`);
2921
+ await writeFile(path.join(outDir, HINTS_FILE), JSON.stringify({
2922
+ all,
2923
+ bundles: bundleHints
2924
+ }));
1502
2925
  if (buildId !== void 0) {
1503
- const written = Object.values(bundle).map((item) => item.fileName);
2926
+ const written = [];
2927
+ for (const item of Object.values(bundle)) written.push(item.fileName);
1504
2928
  const removed = pruneBuilds(outDir, buildId, written, options.skew?.keep ?? 0);
1505
2929
  if (removed.length > 0) this.info(`Removed the files of ${removed.length} older builds`);
1506
2930
  }
1507
2931
  return;
1508
2932
  }
1509
2933
  if (!options.prerender || !isSsrBuild) return;
1510
- const chunk = Object.values(bundle).find((item) => item.type === "chunk" && item.isEntry && item.name === PRERENDER_ENTRY);
2934
+ let chunk;
2935
+ for (const item of Object.values(bundle)) if (item.type === "chunk" && item.isEntry && item.name === PRERENDER_ENTRY) {
2936
+ chunk = item;
2937
+ break;
2938
+ }
1511
2939
  if (!chunk) return;
1512
2940
  const settings = options.prerender === true ? {} : options.prerender;
1513
2941
  const written = await prerender(path.join(outDir, chunk.fileName), root, base, settings);
@@ -1523,10 +2951,13 @@ function brumate(options = {}) {
1523
2951
  }
1524
2952
  coreModule = isServe ? void 0 : (await this.resolve("brumate/client", path.join(root, "index.html")))?.id;
1525
2953
  await scan();
2954
+ builtFeatures = void 0;
2955
+ knownFeatures = void 0;
2956
+ loadedComponents.clear();
1526
2957
  writeRouteTypes();
1527
2958
  },
1528
2959
  async resolveId(id, importer, resolveOptions) {
1529
- if (id === START || id === MANIFEST || id === SERVER || id === ROUTES || id === TESTING) return `\0${id}`;
2960
+ if (id === START || id === MANIFEST || id === SERVER || id === ROUTES || id === TESTING || id.startsWith(BUNDLE)) return `\0${id}`;
1530
2961
  const env = resolveOptions?.ssr ? void 0 : envFile();
1531
2962
  const from = importer?.split("?")[0];
1532
2963
  if (env && importer && from && from !== env && isScriptFile(from) && !importer.startsWith("\0") && !importer.includes(SERVER_QUERY) && !importer.includes("/node_modules/")) {
@@ -1542,7 +2973,7 @@ function brumate(options = {}) {
1542
2973
  ...resolveOptions,
1543
2974
  skipSelf: true
1544
2975
  });
1545
- if (!resolved || resolved.external || resolved.id.includes("?") || resolved.id.includes("/node_modules/") && !packageOf(packages, resolved.id)) return resolved;
2976
+ if (!resolved || resolved.external || resolved.id.includes("?") || resolved.id.includes("/node_modules/") && !findPackage(packages, resolved.id)) return resolved;
1546
2977
  const file = resolved.id;
1547
2978
  return isScriptFile(file) && existsSync(file) && hasUseServer(readFileSync(file, "utf8")) ? {
1548
2979
  ...resolved,
@@ -1567,12 +2998,16 @@ function brumate(options = {}) {
1567
2998
  }
1568
2999
  if (id === `\0${START}`) return [
1569
3000
  options.navigate === false ? "import { startWithoutNavigation as start } from 'brumate/static-loader';" : "import { start } from 'brumate/loader';",
1570
- `import { load } from ${JSON.stringify(MANIFEST)};`,
3001
+ `import { load${isServe ? "" : ", loadBundle"} } from ${JSON.stringify(MANIFEST)};`,
1571
3002
  ...isServe ? ["import { hotLoad } from 'brumate/hot';"] : [],
1572
- `start({ load${isServe ? ": hotLoad(import.meta.hot, load)" : ""}, rpc: ${JSON.stringify(rpc)}, navigate: ${JSON.stringify(options.navigate ?? true)}${options.preload === false ? ", preload: false" : ""}${buildId === void 0 ? "" : `, build: ${JSON.stringify(buildId)}`} });`,
1573
- ...isServe && options.devtools !== false ? [`import('brumate/devtools').then((m) => m.installDevtools(${JSON.stringify(INSPECT)}, ${JSON.stringify(rpc)}));`] : []
3003
+ `start({ load${isServe ? ": hotLoad(import.meta.hot, load)" : ", loadBundle"}${serialFile() ? `, serial: () => import(${JSON.stringify(serialFile())})` : ""}, rpc: ${JSON.stringify(rpc)}, navigate: ${JSON.stringify(options.navigate ?? true)}${buildId === void 0 ? "" : `, build: ${JSON.stringify(buildId)}`} });`,
3004
+ ...isServe && options.devtools !== false ? [`import('brumate/devtools').then((m) => m.installDevtools(${JSON.stringify(INSPECT)}, ${JSON.stringify(rpc)}, ${JSON.stringify({
3005
+ version: BRUMATE_VERSION,
3006
+ vite: version
3007
+ })}, import.meta.hot));`] : []
1574
3008
  ].join("\n");
1575
3009
  if (id === `\0${MANIFEST}`) return await manifest();
3010
+ if (id.startsWith(`\0${BUNDLE}`)) return await bundleModule(id.slice(24));
1576
3011
  if (id === `\0${SERVER}`) return serverRegistry(!loadOptions?.ssr);
1577
3012
  if (id === `\0${ROUTES}`) return routeTree(!loadOptions?.ssr);
1578
3013
  if (id === `\0${TESTING}`) {
@@ -1617,6 +3052,7 @@ function brumate(options = {}) {
1617
3052
  });
1618
3053
  }
1619
3054
  const { source, result } = output;
3055
+ if (!isServe && !isSsrBuild && isClient) loadedComponents.add(file);
1620
3056
  for (const dependency of [...result.plan.styles.dependencies, ...result.modules]) {
1621
3057
  const normalized = normalizePath(dependency);
1622
3058
  this.addWatchFile(normalized);
@@ -1625,7 +3061,7 @@ function brumate(options = {}) {
1625
3061
  }
1626
3062
  for (const warning of isClient && !params.has("part") ? result.warnings : []) {
1627
3063
  const { line, column } = getLocation(source, warning.range.start);
1628
- this.warn(`${warning.message} (${nameOf(file)}:${line}:${column})`);
3064
+ this.warn(`${warning.message} (${getFileName(file)}:${line}:${column})`);
1629
3065
  }
1630
3066
  const part = params.get("part");
1631
3067
  let code;
@@ -1643,15 +3079,21 @@ function brumate(options = {}) {
1643
3079
  code = isClient ? result.client : result.server;
1644
3080
  map = isClient ? result.maps.client : result.maps.server;
1645
3081
  }
3082
+ const sources = [];
3083
+ if (map) for (const [index, name] of map.sources.entries()) sources.push(index === 0 ? file : name);
1646
3084
  return {
1647
3085
  code,
1648
3086
  map: map && {
1649
3087
  ...map,
1650
- sources: map.sources.map((name, index) => index === 0 ? file : name)
3088
+ sources
1651
3089
  }
1652
3090
  };
1653
3091
  },
1654
3092
  async transform(code, id, transformOptions) {
3093
+ if (!isServe && !isSsrBuild && !transformOptions?.ssr && readsFeatures(code)) return {
3094
+ code: writeFeatures(code, options.features === "all" ? allFeatures() : await buildFeatures()),
3095
+ map: null
3096
+ };
1655
3097
  const [file] = id.split("?");
1656
3098
  if (file && !transformOptions?.ssr && file === envFile()) try {
1657
3099
  return {
@@ -1668,8 +3110,11 @@ function brumate(options = {}) {
1668
3110
  map: null
1669
3111
  };
1670
3112
  if (id.includes(SERVER_QUERY)) {
3113
+ let lang = "jsx";
3114
+ if (/\.[cm]?ts$/.test(file)) lang = "ts";
3115
+ else if (file.endsWith(".tsx")) lang = "tsx";
1671
3116
  const result = await transformWithOxc(serverModule(code, file, fileId), file, {
1672
- lang: /\.[cm]?ts$/.test(file) ? "ts" : file.endsWith(".tsx") ? "tsx" : "jsx",
3117
+ lang,
1673
3118
  sourcemap: true
1674
3119
  });
1675
3120
  return {
@@ -1696,14 +3141,17 @@ function brumate(options = {}) {
1696
3141
  };
1697
3142
  },
1698
3143
  configureServer(server) {
1699
- const linked = packages.filter((item) => item.linked).flatMap((item) => item.directories);
3144
+ const linked = [];
3145
+ for (const item of packages) if (item.linked) linked.push(...item.directories);
1700
3146
  if (linked.length > 0) server.watcher.add(linked);
1701
- const manifests = [path.join(root, "package.json"), ...packages.map((item) => `${item.root}/package.json`)].map((file) => normalizePath(file));
3147
+ const manifests = [normalizePath(path.join(root, "package.json"))];
3148
+ for (const item of packages) manifests.push(normalizePath(`${item.root}/package.json`));
1702
3149
  server.watcher.add(manifests);
1703
3150
  server.watcher.on("change", (file) => {
1704
3151
  if (manifests.includes(normalizePath(file)) && packagesKey(findPackages(root)) !== packagesKey(packages)) server.restart();
1705
3152
  });
1706
3153
  server.watcher.on("all", (event, file) => {
3154
+ workbenchList = void 0;
1707
3155
  if (normalizePath(file) === envFile()) compiled.clear();
1708
3156
  for (const importer of dependents.get(normalizePath(file)) ?? []) {
1709
3157
  compiled.delete(importer);
@@ -1715,8 +3163,10 @@ function brumate(options = {}) {
1715
3163
  }
1716
3164
  if (isScriptFile(file)) {
1717
3165
  const normalized = normalizePath(file);
1718
- if (packages.length > 0 && !packageOf(packages, normalized)) {
1719
- appScripts = appScripts.filter((item) => item !== normalized);
3166
+ if (packages.length > 0 && !findPackage(packages, normalized)) {
3167
+ const rest = [];
3168
+ for (const item of appScripts) if (item !== normalized) rest.push(item);
3169
+ appScripts = rest;
1720
3170
  if (event !== "unlink") appScripts.push(normalized);
1721
3171
  }
1722
3172
  const id = serverFileId(normalized);
@@ -1742,6 +3192,36 @@ function brumate(options = {}) {
1742
3192
  handleDevRPC(server, request, response);
1743
3193
  return;
1744
3194
  }
3195
+ if (request.method === "GET" && request.url?.startsWith(`${SOURCE}?`)) {
3196
+ const asked = new URL(request.url, "http://localhost").searchParams.get("file") ?? "";
3197
+ const file = normalizePath(path.isAbsolute(asked) && existsSync(asked) ? asked : path.join(server.config.root, asked));
3198
+ if (!existsSync(file) || !isFileLoadingAllowed(server.config, file)) {
3199
+ response.statusCode = 404;
3200
+ response.end();
3201
+ return;
3202
+ }
3203
+ response.setHeader("content-type", "text/plain; charset=utf-8");
3204
+ response.end(readFileSync(file, "utf8"));
3205
+ return;
3206
+ }
3207
+ if (request.method === "GET" && request.url?.startsWith(`${POSITION}?`)) {
3208
+ const params = new URL(request.url, "http://localhost").searchParams;
3209
+ server.environments.client.moduleGraph.getModuleByUrl(params.get("url") ?? "").then((module) => {
3210
+ const map = module?.transformResult?.map;
3211
+ const place = map && module?.file ? originalPosition(map, Number(params.get("line")), Number(params.get("column"))) : void 0;
3212
+ const file = place && normalizePath(place.source.startsWith("/") && !existsSync(place.source) ? path.join(server.config.root, place.source) : path.resolve(path.dirname(module.file), place.source));
3213
+ response.setHeader("content-type", "application/json");
3214
+ response.end(JSON.stringify(place ? {
3215
+ ...place,
3216
+ file
3217
+ } : null));
3218
+ }).catch(next);
3219
+ return;
3220
+ }
3221
+ if (request.method === "GET" && request.url?.startsWith(WORKBENCH)) {
3222
+ serveWorkbench(server, request, response).catch(next);
3223
+ return;
3224
+ }
1745
3225
  if (request.method === "GET" && request.url?.startsWith(`${INSPECT}/`)) {
1746
3226
  inspectComponent(decodeURIComponent(request.url.slice(19))).then((info) => {
1747
3227
  response.statusCode = info ? 200 : 404;
@@ -1771,6 +3251,18 @@ function brumate(options = {}) {
1771
3251
  }
1772
3252
  };
1773
3253
  }
3254
+ /** The names that compiled client code exports, such as `h4`, `u5` and `g`. */
3255
+ function exportNames(codes) {
3256
+ const names = /* @__PURE__ */ new Set();
3257
+ for (const code of codes) for (const match of code.matchAll(/^export (?:async )?(?:function\*? |const |let |var )([\w$]+)|^export \{([^}]*)\}/gm)) {
3258
+ if (match[1]) names.add(match[1]);
3259
+ for (const item of match[2]?.split(",") ?? []) {
3260
+ const name = item.trim().split(/\s+as\s+/).pop();
3261
+ if (name) names.add(name);
3262
+ }
3263
+ }
3264
+ return [...names];
3265
+ }
1774
3266
  //#endregion
1775
3267
  export { brumate as default, errorPage };
1776
3268