brumate 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/README.md +2 -2
  2. package/check.d.ts +49 -0
  3. package/dist/{boot-C25Sa6vq.d.ts → boot-SCWYwuUd.d.ts} +8 -10
  4. package/dist/cli.js +275 -15
  5. package/dist/cli.js.map +1 -1
  6. package/dist/client-BBtVTOIt.js +3506 -0
  7. package/dist/client-BBtVTOIt.js.map +1 -0
  8. package/dist/{client-D0CqSxoO.d.ts → client-Cs3o4key.d.ts} +390 -181
  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-BzllthiF.js → cookies-Cnbf4w-S.js} +14 -7
  12. package/dist/cookies-Cnbf4w-S.js.map +1 -0
  13. package/dist/{defer-BbD7JQhj.js → defer-BLJjxqVc.js} +4 -4
  14. package/dist/defer-BLJjxqVc.js.map +1 -0
  15. package/dist/{devtools-CQgD7NPB.js → devtools-DTpsVFbn.js} +56 -82
  16. package/dist/devtools-DTpsVFbn.js.map +1 -0
  17. package/dist/{devtools-panel-BVB-W5q4.js → devtools-panel-C1Dfv6nq.js} +397 -333
  18. package/dist/devtools-panel-C1Dfv6nq.js.map +1 -0
  19. package/dist/{events-CSs7OwIC.js → events-LgLdp1R7.js} +34 -5
  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-DZIiMDnS.js +506 -0
  24. package/dist/files-DZIiMDnS.js.map +1 -0
  25. package/dist/{forms-Cl21hkHt.d.ts → forms-j1xPAR14.d.ts} +3 -3
  26. package/dist/{forms-Bg-CwGqX.js → forms-nXK7-Lv_.js} +78 -44
  27. package/dist/forms-nXK7-Lv_.js.map +1 -0
  28. package/dist/highlight.js +31 -22
  29. package/dist/highlight.js.map +1 -1
  30. package/dist/{html-mNTKzaDD.js → html-DS9B1H-M.js} +92 -22
  31. package/dist/html-DS9B1H-M.js.map +1 -0
  32. package/dist/{html-Bq1rFxX_.d.ts → html-Gggepsf-.d.ts} +22 -5
  33. package/dist/index.d.ts +98 -10
  34. package/dist/index.js +639 -104
  35. package/dist/index.js.map +1 -1
  36. package/dist/{inspect-BHpOw1LF.js → inspect-DomFHy5O.js} +3832 -695
  37. package/dist/inspect-DomFHy5O.js.map +1 -0
  38. package/dist/{loader-Dos_3NP0.js → loader-D62komKu.js} +20 -14
  39. package/dist/loader-D62komKu.js.map +1 -0
  40. package/dist/logo-DQ_OYhBi.js +10 -0
  41. package/dist/logo-DQ_OYhBi.js.map +1 -0
  42. package/dist/{navigate-O78d_zGN.js → navigate-CfOr-TRF.js} +94 -31
  43. package/dist/navigate-CfOr-TRF.js.map +1 -0
  44. package/dist/nesting-DA5vJw9X.js +265 -0
  45. package/dist/nesting-DA5vJw9X.js.map +1 -0
  46. package/dist/{produce-Doc91GkX.js → produce-BNIpmZq2.js} +138 -9
  47. package/dist/produce-BNIpmZq2.js.map +1 -0
  48. package/dist/{produce-D0V0ICkz.d.ts → produce-CRfouraC.d.ts} +44 -5
  49. package/dist/{rpc-ygMRPmN4.js → rpc-BTMb8jap.js} +11 -6
  50. package/dist/rpc-BTMb8jap.js.map +1 -0
  51. package/dist/runtime/batch.js +9 -7
  52. package/dist/runtime/batch.js.map +1 -1
  53. package/dist/runtime/client.d.ts +4 -4
  54. package/dist/runtime/client.js +4 -4
  55. package/dist/runtime/devtools.d.ts +11 -29
  56. package/dist/runtime/devtools.js +3 -1
  57. package/dist/runtime/env.js +14 -2
  58. package/dist/runtime/env.js.map +1 -1
  59. package/dist/runtime/events.d.ts +23 -1
  60. package/dist/runtime/events.js +1 -1
  61. package/dist/runtime/forms.d.ts +2 -2
  62. package/dist/runtime/forms.js +1 -1
  63. package/dist/runtime/hot.d.ts +1 -1
  64. package/dist/runtime/hot.js +5 -2
  65. package/dist/runtime/hot.js.map +1 -1
  66. package/dist/runtime/html.d.ts +2 -2
  67. package/dist/runtime/html.js +1 -1
  68. package/dist/runtime/loader.d.ts +2 -2
  69. package/dist/runtime/loader.js +2 -2
  70. package/dist/runtime/routes.js +4 -1
  71. package/dist/runtime/routes.js.map +1 -1
  72. package/dist/runtime/server.d.ts +5 -5
  73. package/dist/runtime/server.js +5 -5
  74. package/dist/runtime/signals.d.ts +38 -1
  75. package/dist/runtime/signals.js +33 -1
  76. package/dist/runtime/signals.js.map +1 -1
  77. package/dist/runtime/static-loader.d.ts +2 -2
  78. package/dist/runtime/static-loader.js +1 -1
  79. package/dist/runtime/testing.d.ts +18 -3
  80. package/dist/runtime/testing.js +150 -33
  81. package/dist/runtime/testing.js.map +1 -1
  82. package/dist/{server-CxVDYE_V.js → server-BTtsQFFw.js} +633 -163
  83. package/dist/server-BTtsQFFw.js.map +1 -0
  84. package/dist/{server-DuFYRXrd.d.ts → server-CYw15Dsg.d.ts} +103 -22
  85. package/dist/{static-loader-nZssh66R.js → static-loader-C_GYIFtt.js} +79 -99
  86. package/dist/static-loader-C_GYIFtt.js.map +1 -0
  87. package/dist/{static-loader-Drpr0AzI.d.ts → static-loader-DVuLmXeu.d.ts} +2 -2
  88. package/dist/{stream-DCYZO4IF.js → stream-r4V5zBKm.js} +102 -16
  89. package/dist/stream-r4V5zBKm.js.map +1 -0
  90. package/dist/vite.d.ts +13 -20
  91. package/dist/vite.js +1956 -554
  92. package/dist/vite.js.map +1 -1
  93. package/elements.d.ts +951 -0
  94. package/forms/forms.brm.ts +3 -3
  95. package/package.json +12 -3
  96. package/skills/brumate/SKILL.md +58 -0
  97. package/skills/brumate/references/errors.md +2078 -0
  98. package/skills/brumate/references/events.md +117 -0
  99. package/skills/brumate/references/signals.md +61 -0
  100. package/skills/brumate/references/state.md +235 -0
  101. package/skills/brumate/references/syntax.md +250 -0
  102. package/types.d.ts +4 -4
  103. package/dist/client-BD6XT-s5.js +0 -1968
  104. package/dist/client-BD6XT-s5.js.map +0 -1
  105. package/dist/client-routes-JTbGtukf.js.map +0 -1
  106. package/dist/cookies-BzllthiF.js.map +0 -1
  107. package/dist/defer-BbD7JQhj.js.map +0 -1
  108. package/dist/devtools-CQgD7NPB.js.map +0 -1
  109. package/dist/devtools-panel-BVB-W5q4.js.map +0 -1
  110. package/dist/events-CSs7OwIC.js.map +0 -1
  111. package/dist/files-BXSSrQgc.js +0 -205
  112. package/dist/files-BXSSrQgc.js.map +0 -1
  113. package/dist/forms-Bg-CwGqX.js.map +0 -1
  114. package/dist/html-mNTKzaDD.js.map +0 -1
  115. package/dist/inspect-BHpOw1LF.js.map +0 -1
  116. package/dist/loader-Dos_3NP0.js.map +0 -1
  117. package/dist/navigate-O78d_zGN.js.map +0 -1
  118. package/dist/produce-Doc91GkX.js.map +0 -1
  119. package/dist/rpc-ygMRPmN4.js.map +0 -1
  120. package/dist/server-CxVDYE_V.js.map +0 -1
  121. package/dist/static-loader-nZssh66R.js.map +0 -1
  122. package/dist/stream-DCYZO4IF.js.map +0 -1
package/dist/vite.js CHANGED
@@ -1,9 +1,10 @@
1
- import { A as analyzeProject, C as isReactiveModule, E as originalPosition, F as parse, M as forEachNode, N as resolveRelative, O as entryClasses, R as getLocation, T as builtin, _ as functionId, a as scopeLabel, b as SHARED_QUERY, f as instanceScope, i as report, k as refreshedNames, n as formatReport, p as slotIndex, s as compile, t as anchorLabel, v as getComponentName, w as resolveFromDisk, x as generateShared, y as hash } from "./inspect-BHpOw1LF.js";
2
- import { s as toNodeHeaders } from "./cookies-BzllthiF.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-BXSSrQgc.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-DomFHy5O.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-DZIiMDnS.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";
@@ -12,26 +13,31 @@ import { isFileLoadingAllowed, isRunnableDevEnvironment, normalizePath, searchFo
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,11 +58,11 @@ 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);
@@ -68,7 +74,7 @@ function parseEnvFile(source, filename) {
68
74
  end
69
75
  };
70
76
  }
71
- });
77
+ }
72
78
  return result;
73
79
  }
74
80
  /**
@@ -103,6 +109,86 @@ function clientEnvModule(source, filename, values) {
103
109
  return result + source.slice(position);
104
110
  }
105
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
106
192
  //#region src/builds.ts
107
193
  /** The file in the client build that names its build. */
108
194
  const BUILD_FILE = ".brumate/build.json";
@@ -138,7 +224,9 @@ function pruneBuilds(directory, id, files, keep, now = Date.now()) {
138
224
  } catch {
139
225
  builds = [];
140
226
  }
141
- 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;
142
230
  builds.push({
143
231
  id,
144
232
  at: now,
@@ -147,224 +235,15 @@ function pruneBuilds(directory, id, files, keep, now = Date.now()) {
147
235
  builds.sort((a, b) => a.at - b.at);
148
236
  const kept = builds.slice(Math.max(0, builds.length - 1 - keep));
149
237
  const dropped = builds.slice(0, builds.length - kept.length);
150
- 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);
151
240
  for (const build of dropped) for (const file of build.files) if (!keptFiles.has(file)) rmSync(path.join(directory, file), { force: true });
152
241
  mkdirSync(path.join(directory, ".brumate"), { recursive: true });
153
242
  writeFileSync(path.join(directory, BUILD_FILE), `${JSON.stringify({ build: id })}\n`);
154
243
  writeFileSync(list, `${JSON.stringify({ builds: kept }, null, 2)}\n`);
155
- return dropped.map((build) => build.id);
156
- }
157
- //#endregion
158
- //#region src/packages.ts
159
- const toPosix = (file) => file.split(path.sep).join("/");
160
- function readJson(file) {
161
- try {
162
- return JSON.parse(readFileSync(file, "utf8"));
163
- } catch {
164
- return;
165
- }
166
- }
167
- /** The real directory of a package that code in `from` can import, or undefined. */
168
- function findPackageDirectory(name, from) {
169
- for (let directory = from;; directory = path.dirname(directory)) {
170
- const candidate = path.join(directory, "node_modules", name);
171
- if (existsSync(path.join(candidate, "package.json"))) return toPosix(realpathSync(candidate));
172
- if (path.dirname(directory) === directory) return;
173
- }
174
- }
175
- /** The directory of the nearest package.json at or above a directory. */
176
- function packageRoot(directory) {
177
- for (let current = directory;; current = path.dirname(current)) {
178
- if (existsSync(path.join(current, "package.json"))) return current;
179
- if (path.dirname(current) === current) return;
180
- }
181
- }
182
- /** The directories that the `brumate` field names, or undefined when the package does not opt in. */
183
- function directoriesOf(root, field, name) {
184
- if (field === true) return [root];
185
- if (typeof field === "object" && field !== null) {
186
- const { dir, version = 1 } = field;
187
- 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.`);
188
- if (dir === void 0) return [root];
189
- return (Array.isArray(dir) ? dir : [dir]).map((item) => toPosix(path.resolve(root, item)));
190
- }
191
- }
192
- /**
193
- * Finds the dependencies of the app at `root` that ship `.brm` files, and
194
- * theirs. The app's dependencies come from its package.json: `dependencies`,
195
- * `devDependencies`, `optionalDependencies` and `peerDependencies`. A package
196
- * opts in with `"brumate": true`, or `"brumate": { "dir": "src" }` to search
197
- * only that directory. Symbolic links, such as those of pnpm, resolve to the
198
- * real directory.
199
- */
200
- function findPackages(root) {
201
- const app = packageRoot(path.resolve(root));
202
- if (!app) return [];
203
- const found = /* @__PURE__ */ new Map();
204
- const visit = (directory, json, own) => {
205
- const names = /* @__PURE__ */ new Set([
206
- ...Object.keys(json.dependencies ?? {}),
207
- ...Object.keys(json.optionalDependencies ?? {}),
208
- ...Object.keys(json.peerDependencies ?? {}),
209
- ...own ? Object.keys(json.devDependencies ?? {}) : []
210
- ]);
211
- for (const name of [...names].toSorted()) {
212
- const real = findPackageDirectory(name, directory);
213
- if (!real || found.has(real)) continue;
214
- const dependency = readJson(`${real}/package.json`);
215
- const directories = dependency && directoriesOf(real, dependency.brumate, name);
216
- if (!dependency || !directories) continue;
217
- found.set(real, {
218
- name: dependency.name ?? name,
219
- version: dependency.version ?? "0.0.0",
220
- root: real,
221
- directories,
222
- linked: !real.includes("/node_modules/")
223
- });
224
- visit(real, dependency, false);
225
- }
226
- };
227
- visit(app, readJson(path.join(app, "package.json")) ?? {}, true);
228
- const list = [...found.values()];
229
- const versions = /* @__PURE__ */ new Map();
230
- for (const item of list) versions.set(item.name, (versions.get(item.name) ?? /* @__PURE__ */ new Set()).add(item.version));
231
- return list.map((item) => Object.assign(item, { prefix: versions.get(item.name).size > 1 ? `${item.name}@${item.version}` : item.name }));
232
- }
233
- /** The package that a file belongs to, or undefined for a file of the app. */
234
- function packageOf(packages, file) {
235
- return packages.find((item) => file.startsWith(`${item.root}/`));
236
- }
237
- /**
238
- * The name of a file of a package, which its IDs come from: the prefix of
239
- * the package and the path of the file in it, such as `@acme/ui/src/Button.brm`.
240
- * It is the same wherever the package is installed.
241
- */
242
- function packageFileName(item, file) {
243
- return `${item.prefix}/${file.slice(item.root.length + 1)}`;
244
- }
245
- /** The name and the subpath of a bare specifier, such as `@acme/ui` and `./Button.brm`. */
246
- function splitSpecifier(specifier) {
247
- if (specifier.startsWith(".") || specifier.startsWith("/") || /^[a-z]+:/i.test(specifier)) return;
248
- const parts = specifier.split("/");
249
- const count = specifier.startsWith("@") ? 2 : 1;
250
- if (parts.length < count || parts.slice(0, count).some((part) => part === "")) return;
251
- const rest = parts.slice(count).join("/");
252
- return {
253
- name: parts.slice(0, count).join("/"),
254
- subpath: rest ? `./${rest}` : "."
255
- };
256
- }
257
- /** The conditions of `exports` that a `.brm` file or a source module can be under. */
258
- const CONDITIONS = /* @__PURE__ */ new Set([
259
- "brumate",
260
- "import",
261
- "module",
262
- "node",
263
- "browser",
264
- "default"
265
- ]);
266
- function resolveTarget(target, star) {
267
- if (typeof target === "string") return target.replaceAll("*", star);
268
- if (Array.isArray(target)) {
269
- for (const item of target) {
270
- const result = resolveTarget(item, star);
271
- if (result) return result;
272
- }
273
- return;
274
- }
275
- if (typeof target === "object" && target !== null) {
276
- for (const [condition, value] of Object.entries(target)) if (CONDITIONS.has(condition)) {
277
- const result = resolveTarget(value, star);
278
- if (result) return result;
279
- }
280
- }
281
- }
282
- /** Resolves a subpath through the `exports` of a package.json, or undefined if it does not export it. */
283
- function resolveExports(exports, subpath) {
284
- const map = typeof exports === "object" && exports !== null && !Array.isArray(exports) && Object.keys(exports).some((key) => key.startsWith(".")) ? exports : { ".": exports };
285
- if (subpath in map) return resolveTarget(map[subpath], "");
286
- let best;
287
- for (const key of Object.keys(map)) {
288
- const index = key.indexOf("*");
289
- if (index === -1) continue;
290
- const before = key.slice(0, index);
291
- const after = key.slice(index + 1);
292
- if (subpath.startsWith(before) && subpath.endsWith(after) && subpath.length >= key.length - 1 && (!best || before.length > best.key.indexOf("*"))) best = {
293
- key,
294
- star: subpath.slice(before.length, subpath.length - after.length)
295
- };
296
- }
297
- return best && resolveTarget(map[best.key], best.star);
298
- }
299
- /**
300
- * Resolves a bare specifier, such as `@acme/ui/Button.brm`, to the real path
301
- * of the file, through the `exports` of the package. Returns undefined when
302
- * it is not a bare specifier or names no file.
303
- */
304
- function resolvePackageImport(specifier, importer) {
305
- const split = splitSpecifier(specifier);
306
- if (!split) return;
307
- const directory = findPackageDirectory(split.name, path.dirname(importer));
308
- if (!directory) return;
309
- const json = readJson(`${directory}/package.json`);
310
- const target = json?.exports === void 0 ? split.subpath : resolveExports(json.exports, split.subpath);
311
- if (!target) return;
312
- const file = path.resolve(directory, target);
313
- return existsSync(file) ? toPosix(realpathSync(file)) : void 0;
314
- }
315
- /** The specifiers that a file imports or exports from, found by a pattern, so it can only find more. */
316
- function importSpecifiers(source) {
317
- const result = [];
318
- for (const match of source.matchAll(/(?:\bfrom|\bimport\s*\(?)\s*(['"])([^'"\n]+)\1/g)) result.push(match[2]);
319
- return result;
320
- }
321
- /** The extensions that an import without one can name. */
322
- const EXTENSIONS = [
323
- "",
324
- ".ts",
325
- ".tsx",
326
- ".js",
327
- ".mjs",
328
- "/index.ts",
329
- "/index.js"
330
- ];
331
- /**
332
- * The files of packages that the app reaches: the files of packages that
333
- * files of the app import, and the files of packages that those import, and
334
- * so on. Only these become server functions of the app.
335
- */
336
- function reachableFiles(packages, appFiles, read) {
337
- const reached = /* @__PURE__ */ new Set();
338
- const names = new Set(packages.map((item) => item.name));
339
- const pending = [];
340
- const add = (file) => {
341
- if (file && !reached.has(file) && packageOf(packages, file)) {
342
- reached.add(file);
343
- pending.push(file);
344
- }
345
- };
346
- const resolve = (specifier, importer) => {
347
- if (specifier.startsWith(".")) {
348
- const stem = path.resolve(path.dirname(importer), specifier.split("?")[0]);
349
- const found = EXTENSIONS.map((extension) => stem + extension).find((candidate) => statSync(candidate, { throwIfNoEntry: false })?.isFile());
350
- return found && toPosix(realpathSync(found));
351
- }
352
- const name = splitSpecifier(specifier)?.name;
353
- return name && names.has(name) ? resolvePackageImport(specifier.split("?")[0], importer) : void 0;
354
- };
355
- const visit = (file, own) => {
356
- const source = read(file);
357
- if (source === void 0) return;
358
- for (const specifier of importSpecifiers(source)) {
359
- if (own && specifier.startsWith(".")) continue;
360
- try {
361
- add(resolve(specifier, file));
362
- } catch {}
363
- }
364
- };
365
- for (const file of appFiles) visit(file, true);
366
- while (pending.length > 0) visit(pending.pop(), false);
367
- return reached;
244
+ const droppedIds = [];
245
+ for (const build of dropped) droppedIds.push(build.id);
246
+ return droppedIds;
368
247
  }
369
248
  //#endregion
370
249
  //#region src/version.ts
@@ -459,9 +338,970 @@ hot.on('vite:beforeUpdate', () => location.reload());
459
338
  `;
460
339
  }
461
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
462
1302
  //#region src/prerender.ts
463
1303
  /** The file of a page: `index.html` in a folder of its path. */
464
- function fileOf(pathname) {
1304
+ function getPageFile(pathname) {
465
1305
  const clean = pathname.replace(/^\/+|\/+$/g, "");
466
1306
  return clean ? `${clean}/index.html` : "index.html";
467
1307
  }
@@ -495,7 +1335,11 @@ function scriptHashes(html) {
495
1335
  async function prerender(routes, root, base, options) {
496
1336
  const client = path.resolve(root, options.client ?? "dist/client");
497
1337
  const manifest = JSON.parse(await readFile(path.join(client, ".vite/manifest.json"), "utf8"));
498
- 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
+ }
499
1343
  if (!entry) throw new Error("The client build has no entry. Build the client before the server.");
500
1344
  const { handle } = await import(pathToFileURL(routes).href);
501
1345
  const document = {
@@ -512,12 +1356,12 @@ async function prerender(routes, root, base, options) {
512
1356
  const response = await handle(new Request(`http://localhost${pathname}`), document);
513
1357
  if (!response?.headers.get("content-type")?.includes("text/html") || response.status !== 200) continue;
514
1358
  const html = await response.text();
515
- const file = path.join(client, fileOf(pathname));
1359
+ const file = path.join(client, getPageFile(pathname));
516
1360
  await mkdir(path.dirname(file), { recursive: true });
517
1361
  await writeFile(file, html);
518
1362
  written.push(pathname);
519
1363
  pages[pathname] = {
520
- file: fileOf(pathname),
1364
+ file: getPageFile(pathname),
521
1365
  scripts: scriptHashes(html)
522
1366
  };
523
1367
  if (options.crawl !== false) {
@@ -537,9 +1381,11 @@ async function prerender(routes, root, base, options) {
537
1381
  scripts: scriptHashes(html)
538
1382
  };
539
1383
  }
1384
+ const scripts = /* @__PURE__ */ new Set();
1385
+ for (const page of Object.values(pages)) for (const script of page.scripts) scripts.add(script);
540
1386
  const result = {
541
1387
  pages,
542
- scripts: [...new Set(Object.values(pages).flatMap((page) => page.scripts))]
1388
+ scripts: [...scripts]
543
1389
  };
544
1390
  await mkdir(path.join(client, ".brumate"), { recursive: true });
545
1391
  await writeFile(path.join(client, ".brumate/prerender.json"), `${JSON.stringify(result, null, 2)}\n`);
@@ -588,118 +1434,101 @@ function routeEntries(node, resolve, path = "", layouts = []) {
588
1434
  return result;
589
1435
  }
590
1436
  /** Measures the client build. */
591
- function buildReport({ chunks: list, sources, routes, events: handlers, budget, relative = (file) => file }) {
592
- const chunks = new Map(list.map((chunk) => [chunk.fileName, chunk]));
593
- const sizes = new Map(list.map((chunk) => [chunk.fileName, gzipSize(chunk.code)]));
594
- 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) {
595
1445
  let total = 0;
596
1446
  for (const name of names) total += sizes.get(name) ?? 0;
597
1447
  return total;
598
- };
1448
+ }
599
1449
  const loaderChunks = /* @__PURE__ */ new Set();
600
1450
  for (const chunk of list) if (chunk.isEntry) withImports(chunk.fileName, chunks, loaderChunks);
601
- 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
+ }
602
1463
  const coreChunks = coreChunk ? withImports(coreChunk.fileName, chunks) : /* @__PURE__ */ new Set();
603
1464
  for (const name of loaderChunks) coreChunks.delete(name);
604
1465
  const byFile = /* @__PURE__ */ new Map();
605
- const byModule = /* @__PURE__ */ new Map();
1466
+ const shares = /* @__PURE__ */ new Map();
606
1467
  const everyPage = /* @__PURE__ */ new Set([...loaderChunks, ...coreChunks]);
607
- for (const chunk of list) for (const id of chunk.moduleIds) {
608
- const file = /^(.*\.brm)\?brumate-client/.exec(id)?.[1];
609
- if (file) {
610
- const set = byFile.get(file) ?? /* @__PURE__ */ new Set();
611
- withImports(chunk.fileName, chunks, set);
612
- byFile.set(file, set);
613
- 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);
614
1487
  }
615
1488
  }
616
1489
  for (const set of byFile.values()) for (const name of everyPage) set.delete(name);
617
- const components = [...byFile].map(([file, names]) => ({
1490
+ const components = [];
1491
+ for (const [file, bytes] of shares) components.push({
618
1492
  file,
619
- bytes: sum(names)
620
- })).toSorted((a, b) => b.bytes - a.bytes);
621
- const eventChunks = (event) => {
622
- const names = /* @__PURE__ */ new Set();
623
- const entry = byModule.get(`${event.file}?brumate-client`);
624
- if (entry) withImports(entry, chunks, names);
625
- for (const part of event.parts) {
626
- const chunk = byModule.get(`${event.file}?brumate-client&part=${part}`);
627
- if (chunk) withImports(chunk, chunks, names);
628
- }
629
- for (const name of everyPage) names.delete(name);
630
- return names;
631
- };
632
- const measured = (handlers ?? partEvents(byModule.keys())).map((event) => {
633
- const names = eventChunks(event);
634
- return {
635
- event,
636
- names,
637
- bytes: sum(names)
638
- };
1493
+ bytes: Math.round(bytes)
639
1494
  });
640
- const events = measured.map(({ event, bytes }) => ({
641
- file: event.file,
642
- label: event.label,
643
- bytes
644
- })).toSorted((a, b) => b.bytes - a.bytes);
645
- const reachable = (files) => {
1495
+ components.sort((a, b) => b.bytes - a.bytes);
1496
+ function reachable(files) {
646
1497
  const seen = /* @__PURE__ */ new Set();
647
- const visit = (file) => {
1498
+ function visit(file) {
648
1499
  if (!seen.has(file)) {
649
1500
  seen.add(file);
650
1501
  for (const imported of componentImports(file, sources.get(file) ?? "")) visit(imported);
651
1502
  }
652
- };
653
- files.forEach(visit);
1503
+ }
1504
+ for (const file of files) visit(file);
654
1505
  return seen;
655
- };
656
- 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) : []) {
657
1509
  const reached = reachable(files);
658
1510
  const names = new Set(coreChunks);
659
1511
  for (const file of reached) for (const name of byFile.get(file) ?? []) names.add(name);
660
- return {
1512
+ routeSizes.push({
661
1513
  path,
662
1514
  bytes: sum(names),
663
1515
  components: reached.size
664
- };
665
- }).toSorted((a, b) => b.bytes - a.bytes);
1516
+ });
1517
+ }
1518
+ routeSizes.sort((a, b) => b.bytes - a.bytes);
666
1519
  const loader = sum(loaderChunks);
667
1520
  const overBudget = [];
668
1521
  if (budget?.loader !== void 0 && loader > budget.loader) overBudget.push(`The loader is ${formatBytes(loader)}, over the budget of ${formatBytes(budget.loader)}.`);
669
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)}.`);
670
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)}.`);
671
- for (const { event, names, bytes } of measured.toSorted((a, b) => b.bytes - a.bytes)) if (budget?.event !== void 0 && bytes > budget.event) {
672
- const imports = largestImports(names, chunks);
673
- 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(", ")}.` : ""}`);
674
- }
675
1524
  return {
676
1525
  loader,
677
1526
  core: sum(coreChunks),
678
1527
  components,
679
1528
  routes: routeSizes,
680
- events,
681
1529
  overBudget
682
1530
  };
683
1531
  }
684
- /** Each part of a client module as a handler of its own, when the build does not name them. */
685
- function partEvents(ids) {
686
- const result = [];
687
- for (const id of ids) {
688
- const match = /^(.*\.brm)\?brumate-client&part=(.+)$/.exec(id);
689
- if (match && match[2] !== "update" && match[2] !== "shared") result.push({
690
- file: match[1],
691
- label: `part ${match[2]}`,
692
- parts: [match[2]]
693
- });
694
- }
695
- return result;
696
- }
697
- /** The three largest modules in the chunks that are not client modules of components. */
698
- function largestImports(names, chunks) {
699
- const sizes = [];
700
- 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]);
701
- return sizes.toSorted((a, b) => b[1] - a[1]).slice(0, 3).map(([id]) => id);
702
- }
703
1532
  function formatBytes(bytes) {
704
1533
  return bytes < 1024 ? `${bytes} B` : `${(bytes / 1024).toFixed(1)} kB`;
705
1534
  }
@@ -707,21 +1536,17 @@ function formatBytes(bytes) {
707
1536
  function formatBuildReport(report, relative) {
708
1537
  const lines = [
709
1538
  "brumate client report (gzip)",
710
- ` Every page, before its first event: ${formatBytes(report.loader)}`,
711
- ` 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)}`
712
1541
  ];
713
1542
  if (report.routes.length > 0) {
714
- 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");
715
1544
  for (const route of report.routes) lines.push(` ${route.path}: ${formatBytes(route.bytes)} (${route.components} components)`);
716
1545
  }
717
1546
  if (report.components.length > 0) {
718
1547
  lines.push(" Components, largest first");
719
1548
  for (const component of report.components) lines.push(` ${relative(component.file)}: ${formatBytes(component.bytes)}`);
720
1549
  }
721
- if (report.events.length > 0) {
722
- lines.push(" What the first run of a handler loads, largest first");
723
- for (const event of report.events.slice(0, 10)) lines.push(` ${relative(event.file)} ${event.label}: ${formatBytes(event.bytes)}`);
724
- }
725
1550
  return lines.join("\n");
726
1551
  }
727
1552
  //#endregion
@@ -789,15 +1614,15 @@ function routeFiles(paths) {
789
1614
  * `middleware` is the path of the entry middleware, which runs for every
790
1615
  * request, when the app has one.
791
1616
  */
792
- 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 = {}) {
793
1618
  const imports = [];
794
- const load = (file) => {
1619
+ function load(file) {
795
1620
  if (dev) return `() => import(${JSON.stringify(resolve(file))})`;
796
1621
  const name = `m${imports.length}`;
797
1622
  imports.push(`import * as ${name} from ${JSON.stringify(resolve(file))};`);
798
1623
  return `() => Promise.resolve(${name})`;
799
- };
800
- const write = (node) => {
1624
+ }
1625
+ function write(node) {
801
1626
  const fields = [];
802
1627
  for (const key of [
803
1628
  "layout",
@@ -814,7 +1639,8 @@ function routeModule(tree, resolve, rpc = "/_brumate", origins = [], dev = false
814
1639
  for (const key of ["static", "slots"]) {
815
1640
  const children = node[key];
816
1641
  if (children) {
817
- 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)}`);
818
1644
  fields.push(`${key}: { ${entries.join(", ")} }`);
819
1645
  }
820
1646
  }
@@ -823,7 +1649,7 @@ function routeModule(tree, resolve, rpc = "/_brumate", origins = [], dev = false
823
1649
  if (value) fields.push(`${key}: { name: ${JSON.stringify(value.name)}, node: ${write(value.node)} }`);
824
1650
  }
825
1651
  return `{ ${fields.join(", ")} }`;
826
- };
1652
+ }
827
1653
  const routes = write(tree);
828
1654
  return [
829
1655
  "import { handleRoute } from 'brumate/server';",
@@ -832,14 +1658,14 @@ function routeModule(tree, resolve, rpc = "/_brumate", origins = [], dev = false
832
1658
  ...imports,
833
1659
  `export const routes = ${routes};`,
834
1660
  "export function handle(request, options) {",
835
- ` 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 });`,
836
1662
  "}"
837
1663
  ].join("\n");
838
1664
  }
839
1665
  /** The paths of the pages and endpoints of a tree. Slots render at the paths of their layout. */
840
1666
  function routePaths(tree) {
841
1667
  const result = [];
842
- const visit = (node, path, params) => {
1668
+ function visit(node, path, params) {
843
1669
  if (node.page || node.endpoint) result.push({
844
1670
  path: path || "/",
845
1671
  params
@@ -847,22 +1673,27 @@ function routePaths(tree) {
847
1673
  for (const [segment, folder] of Object.entries(node.static ?? {})) visit(folder, `${path}/${segment}`, params);
848
1674
  if (node.dynamic) visit(node.dynamic.node, `${path}/[${node.dynamic.name}]`, [...params, node.dynamic.name]);
849
1675
  if (node.rest) visit(node.rest.node, `${path}/[...${node.rest.name}]`, [...params, node.rest.name]);
850
- };
1676
+ }
851
1677
  visit(tree, "", []);
852
1678
  return result.toSorted((a, b) => a.path.localeCompare(b.path));
853
1679
  }
854
1680
  /** A declaration file that adds the paths of a tree to `Routes` of `brumate/routes`. */
855
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
+ }
856
1690
  return [
857
1691
  "// Written by the brumate Vite plugin from the route files. Do not edit.",
858
1692
  "export {};",
859
1693
  "",
860
1694
  "declare module 'brumate/routes' {",
861
1695
  " interface Routes {",
862
- ...routePaths(tree).map(({ path, params }) => {
863
- const fields = params.map((name) => `${name}: string`).join("; ");
864
- return ` ${`'${path.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`}: {${fields ? ` ${fields} ` : ""}};`;
865
- }),
1696
+ ...lines,
866
1697
  " }",
867
1698
  "}",
868
1699
  ""
@@ -871,9 +1702,23 @@ function routeTypes(tree) {
871
1702
  //#endregion
872
1703
  //#region src/vite.ts
873
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
+ }
874
1717
  const START = "virtual:brumate/start";
875
1718
  /** Exports `load(id)`, which imports the client module of a component. */
876
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/";
877
1722
  /** Exports `functions` and `handle(request)` for server function calls. */
878
1723
  const SERVER = "virtual:brumate/server";
879
1724
  /** Exports `routes` and `handle(request, options)` for the files in the routes directory. */
@@ -885,6 +1730,44 @@ const RENDER_QUERY = "?brumate-render";
885
1730
  const SERVER_QUERY = "?brumate-server";
886
1731
  /** Exports `mount` from `brumate/testing`, with the loader of this project's client modules. */
887
1732
  const TESTING = "virtual:brumate/testing";
1733
+ /** The ID of the module of Vite's preload helper, which a client build gets from `preloadHelper`. */
1734
+ const PRELOAD_HELPER = "\0vite/preload-helper.js";
1735
+ /**
1736
+ * Vite's preload helper wraps every `import()` of a client build and preloads the scripts and
1737
+ * the stylesheets of the chunk. This one waits for the stylesheets only, so a lazy chunk shows
1738
+ * styled, and preloads the imports of the chunk. The scripts of a page come with the `Link`
1739
+ * headers of the server (see `hints`).
1740
+ */
1741
+ function preloadHelper(base, relative) {
1742
+ return [
1743
+ `export const __vitePreload = (load, deps, from) => {`,
1744
+ ` const links = [];`,
1745
+ ` for (const dep of deps || []) {`,
1746
+ ` const href = ${relative ? "new URL(dep, from)" : `new URL(${JSON.stringify(base)} + dep, location.href)`}.href;`,
1747
+ ` const rel = dep.endsWith('.css') ? 'stylesheet' : 'modulepreload';`,
1748
+ ` let found = false;`,
1749
+ ` for (const link of document.getElementsByTagName('link')) {`,
1750
+ ` found ||= link.rel === rel && link.href === href;`,
1751
+ ` }`,
1752
+ ` if (!found) {`,
1753
+ ` const link = document.createElement('link');`,
1754
+ ` link.rel = rel;`,
1755
+ ` link.crossOrigin = '';`,
1756
+ ` link.href = href;`,
1757
+ ` document.head.appendChild(link);`,
1758
+ ` // A script loads along with the chunk, so only a stylesheet is waited for.`,
1759
+ ` if (rel === 'stylesheet') {`,
1760
+ ` links.push(new Promise((resolve, reject) => {`,
1761
+ ` link.onload = resolve;`,
1762
+ ` link.onerror = reject;`,
1763
+ ` }));`,
1764
+ ` }`,
1765
+ ` }`,
1766
+ ` }`,
1767
+ ` return Promise.all(links).then(load);`,
1768
+ `};`
1769
+ ].join("\n");
1770
+ }
888
1771
  /** The modules that every page loads early, in the client build. See `hints` of `handleRoute`. */
889
1772
  const HINTS_FILE = ".brumate/hints.json";
890
1773
  /** The dev server answers the devtools panel about a component at this path. */
@@ -893,13 +1776,17 @@ const INSPECT = "/__brumate/inspect";
893
1776
  const POSITION = "/__brumate/position";
894
1777
  /** The dev server sends the source of a file for the Errors tab of the devtools at this path. */
895
1778
  const SOURCE = "/__brumate/source";
1779
+ /** The workbench of the dev server, which shows the components that depend only on their props. */
1780
+ const WORKBENCH = "/__brumate/workbench";
896
1781
  /** What tells two lists of packages of components apart. */
897
1782
  function packagesKey(list) {
898
- return JSON.stringify(list.map((item) => [
1783
+ const rows = [];
1784
+ for (const item of list) rows.push([
899
1785
  item.prefix,
900
1786
  item.root,
901
1787
  item.directories
902
- ]));
1788
+ ]);
1789
+ return JSON.stringify(rows);
903
1790
  }
904
1791
  /** Skips the `node_modules` and hidden directories of a package of components. */
905
1792
  function packageExclude(directory) {
@@ -912,7 +1799,7 @@ async function readBody(request) {
912
1799
  return Buffer.concat(chunks);
913
1800
  }
914
1801
  /** Removes the scripts, styles and event handlers of a file, which leaves the markup of its page. */
915
- function markupOf(result) {
1802
+ function getMarkup(result) {
916
1803
  const { file } = result;
917
1804
  const ranges = [
918
1805
  ...file.instanceScript ? [file.instanceScript] : [],
@@ -933,21 +1820,39 @@ function markupOf(result) {
933
1820
  }
934
1821
  return markup + file.source.slice(position);
935
1822
  }
936
- function shapeOf(result) {
937
- const slots = [...result.plan.scopes.values()].map((layout) => `${layout.scope.id}:${layout.slots.map((slot) => slot.name).join(",")}`);
938
- const layouts = [...result.plan.scopes.values()];
1823
+ function getShape(result) {
1824
+ const labels = [];
1825
+ const slots = {};
1826
+ const signals = [];
1827
+ for (const layout of result.plan.scopes.values()) {
1828
+ const names = [];
1829
+ for (const slot of layout.slots) {
1830
+ names.push(slot.name);
1831
+ if (slot.kind === "signal") signals.push(slot.name);
1832
+ }
1833
+ labels.push(`${layout.scope.id}:${names.join(",")}`);
1834
+ slots[layout.scope.id] = names;
1835
+ }
939
1836
  return {
940
1837
  layout: JSON.stringify([
941
1838
  result.table,
942
- slots,
943
- markupOf(result)
1839
+ labels,
1840
+ getMarkup(result)
944
1841
  ]),
945
1842
  css: result.css,
946
1843
  code: JSON.stringify([result.client, result.parts]),
947
- slots: Object.fromEntries(layouts.map((layout) => [layout.scope.id, layout.slots.map((slot) => slot.name)])),
948
- signals: layouts.flatMap((layout) => layout.slots.filter((slot) => slot.kind === "signal").map((slot) => slot.name))
1844
+ slots,
1845
+ signals
949
1846
  };
950
1847
  }
1848
+ /**
1849
+ * The cache key of a module for Vitest: the hash of this build of brumate. A component is never
1850
+ * cached, because its code depends on other files, such as the `.brm.ts` modules that it calls
1851
+ * and the props that other components pass it. A key of its own source would go stale.
1852
+ */
1853
+ function cacheKey({ id }) {
1854
+ return id.split("?")[0].endsWith(".brm") ? false : buildFingerprint();
1855
+ }
951
1856
  let fingerprint;
952
1857
  /**
953
1858
  * A hash of the code of this build of brumate. A new build can compile the
@@ -956,13 +1861,13 @@ let fingerprint;
956
1861
  function buildFingerprint() {
957
1862
  if (fingerprint === void 0) {
958
1863
  const digest = createHash("sha1");
959
- const visit = (directory) => {
1864
+ function visit(directory) {
960
1865
  for (const entry of readdirSync(directory, { withFileTypes: true }).toSorted((a, b) => a.name < b.name ? -1 : 1)) {
961
1866
  const file = path.join(directory, entry.name);
962
1867
  if (entry.isDirectory()) visit(file);
963
1868
  else if (/\.[jt]s$/.test(entry.name) && !entry.name.endsWith(".d.ts")) digest.update(entry.name).update(readFileSync(file));
964
1869
  }
965
- };
1870
+ }
966
1871
  visit(path.dirname(fileURLToPath(import.meta.url)));
967
1872
  fingerprint = digest.digest("hex").slice(0, 16);
968
1873
  }
@@ -972,7 +1877,7 @@ function buildFingerprint() {
972
1877
  function brumate(options = {}) {
973
1878
  const rpc = options.rpc ?? "/_brumate";
974
1879
  /** The entry middleware, when the app has one. */
975
- const middlewareFile = () => {
1880
+ function middlewareFile() {
976
1881
  if (options.middleware === false) return;
977
1882
  const file = normalizePath(path.resolve(root, options.middleware ?? "src/middleware.ts"));
978
1883
  if (!existsSync(file)) {
@@ -980,9 +1885,9 @@ function brumate(options = {}) {
980
1885
  return;
981
1886
  }
982
1887
  return file;
983
- };
1888
+ }
984
1889
  /** The serial entry, when the app has one. */
985
- const serialFile = () => {
1890
+ function serialFile() {
986
1891
  if (options.serial === false) return;
987
1892
  const file = normalizePath(path.resolve(root, options.serial ?? "src/serial.ts"));
988
1893
  if (!existsSync(file)) {
@@ -990,10 +1895,10 @@ function brumate(options = {}) {
990
1895
  return;
991
1896
  }
992
1897
  return file;
993
- };
1898
+ }
994
1899
  /** The classes that the plugins of the serial entry send, read from its `instanceof` checks. */
995
1900
  let serialRead;
996
- const serialClasses = () => {
1901
+ function serialClasses() {
997
1902
  const file = serialFile();
998
1903
  if (!file) return [];
999
1904
  const source = readFileSync(file, "utf8");
@@ -1005,18 +1910,18 @@ function brumate(options = {}) {
1005
1910
  };
1006
1911
  }
1007
1912
  return serialRead.classes;
1008
- };
1913
+ }
1009
1914
  /** The lines that give the server the serial entry, before anything is written or read. */
1010
- const serialImports = () => {
1915
+ function serialImports() {
1011
1916
  const file = serialFile();
1012
1917
  return file ? [
1013
1918
  `import * as $$serial from ${JSON.stringify(file)};`,
1014
1919
  "import { useSerialEntry } from 'brumate/server';",
1015
1920
  "useSerialEntry($$serial);"
1016
1921
  ] : [];
1017
- };
1922
+ }
1018
1923
  /** The file of environment variables, when the app has one. */
1019
- const envFile = () => {
1924
+ function envFile() {
1020
1925
  if (options.env === false) return;
1021
1926
  const file = normalizePath(path.resolve(root, options.env ?? "src/env.ts"));
1022
1927
  if (!existsSync(file)) {
@@ -1024,10 +1929,10 @@ function brumate(options = {}) {
1024
1929
  return;
1025
1930
  }
1026
1931
  return file;
1027
- };
1932
+ }
1028
1933
  /** The names of the server variables, read from the env file, by its source. */
1029
1934
  let envKeys;
1030
- const serverEnvKeys = () => {
1935
+ function serverEnvKeys() {
1031
1936
  const file = envFile();
1032
1937
  if (!file) return;
1033
1938
  const source = readFileSync(file, "utf8");
@@ -1036,13 +1941,15 @@ function brumate(options = {}) {
1036
1941
  server: parseEnvFile(source, file).server
1037
1942
  };
1038
1943
  return envKeys.server;
1039
- };
1944
+ }
1040
1945
  const exclude = options.exclude ?? defaultExclude;
1041
1946
  let root = process.cwd();
1042
1947
  let outDir = "";
1043
1948
  /** The ID of the build, for skew protection. Undefined on the dev server. */
1044
1949
  let buildId;
1045
1950
  let base = "/";
1951
+ /** Whether a build writes URLs that need the URL of the importing chunk to resolve. */
1952
+ let relativeUrls = false;
1046
1953
  let isSsrBuild = false;
1047
1954
  let isServe = false;
1048
1955
  /** Component IDs to absolute file paths. */
@@ -1050,7 +1957,7 @@ function brumate(options = {}) {
1050
1957
  const compiled = /* @__PURE__ */ new Map();
1051
1958
  /** Files that a component depends on, such as SCSS that it imports or modules that it calls into, with the components. */
1052
1959
  const dependents = /* @__PURE__ */ new Map();
1053
- /** What the browser has of each component, from its last compile. See `shapeOf`. */
1960
+ /** What the browser has of each component, from its last compile. See `getShape`. */
1054
1961
  const shapes = /* @__PURE__ */ new Map();
1055
1962
  /** The props that parents can change, by absolute file path. */
1056
1963
  let liveProps = /* @__PURE__ */ new Map();
@@ -1058,113 +1965,172 @@ function brumate(options = {}) {
1058
1965
  let refreshed;
1059
1966
  /** The dependencies of the app that ship `.brm` files. See `packages.ts`. */
1060
1967
  let packages = [];
1061
- const relative = (file) => normalizePath(path.relative(root, file));
1968
+ function relative(file) {
1969
+ return normalizePath(path.relative(root, file));
1970
+ }
1062
1971
  /**
1063
1972
  * The name of a file, which its IDs come from: its path relative to the root,
1064
1973
  * or for a file of a package, the name of the package and its path in it.
1065
1974
  */
1066
- const nameOf = (file) => {
1975
+ function getFileName(file) {
1067
1976
  let normalized = normalizePath(file);
1068
- let owner = packageOf(packages, normalized);
1977
+ let owner = findPackage(packages, normalized);
1069
1978
  if (!owner && normalized.includes("/node_modules/") && existsSync(normalized)) {
1070
1979
  normalized = normalizePath(realpathSync(normalized));
1071
- owner = packageOf(packages, normalized);
1980
+ owner = findPackage(packages, normalized);
1072
1981
  }
1073
1982
  return owner ? packageFileName(owner, normalized) : relative(file);
1074
- };
1075
- /** True for a bare specifier that names a package of components. */
1076
- const isPackageSpecifier = (specifier) => {
1077
- const name = splitSpecifier(specifier)?.name;
1078
- return name !== void 0 && packages.some((item) => item.name === name);
1079
- };
1983
+ }
1080
1984
  /** Files of server functions: scripts whose first statement is `'use server'`, by ID. */
1081
1985
  const serverFiles = /* @__PURE__ */ new Map();
1082
1986
  /** The scripts of the app, when it uses packages of components. */
1083
1987
  let appScripts = [];
1084
1988
  /** The ID of a function that a component imports from a 'use server' file, by a relative path. */
1085
- const serverImport = (importer, specifier, name) => {
1989
+ function serverImport(importer, specifier, name) {
1086
1990
  if (!specifier.startsWith(".")) {
1087
- const file = isPackageSpecifier(specifier) ? resolvePackageImport(specifier, importer) : void 0;
1088
- return file && isScriptFile(file) && hasUseServer(readFileSync(file, "utf8")) ? functionId(serverFileId(file), name, !isServe) : void 0;
1991
+ const file = findPackageServerFile(packages, importer, specifier);
1992
+ return file ? functionId(serverFileId(file), name, !isServe) : void 0;
1089
1993
  }
1090
1994
  const stem = path.resolve(path.dirname(importer), specifier);
1091
- const found = [stem, ...[
1995
+ const candidates = [stem];
1996
+ for (const extension of [
1092
1997
  ".ts",
1093
1998
  ".tsx",
1094
1999
  ".js",
1095
2000
  ".mjs"
1096
- ].map((extension) => stem + extension)].find((candidate) => isScriptFile(candidate) && existsSync(candidate) && hasUseServer(readFileSync(candidate, "utf8")));
2001
+ ]) candidates.push(stem + extension);
2002
+ let found;
2003
+ for (const candidate of candidates) if (isScriptFile(candidate) && existsSync(candidate) && hasUseServer(readFileSync(candidate, "utf8"))) {
2004
+ found = candidate;
2005
+ break;
2006
+ }
1097
2007
  return found && functionId(serverFileId(normalizePath(found)), name, !isServe);
1098
- };
1099
- const serverFileId = (file) => `${path.basename(file).replace(/\.[^.]+$/, "")}_${hash(nameOf(file))}`;
1100
- const componentId = (file) => {
1101
- const filename = nameOf(file);
2008
+ }
2009
+ function serverFileId(file) {
2010
+ return `${path.basename(file).replace(/\.[^.]+$/, "")}_${hash(getFileName(file))}`;
2011
+ }
2012
+ function componentId(file) {
2013
+ const filename = getFileName(file);
1102
2014
  return `${getComponentName(filename)}_${hash(filename)}`;
1103
- };
1104
- const scan = async () => {
1105
- const directories = packages.flatMap((item) => item.directories.filter((directory) => existsSync(directory)));
1106
- const ownFile = (file) => !packageOf(packages, file);
1107
- const [own, ownServer, ...found] = await Promise.all([
1108
- findFiles(root, exclude),
1109
- findServerFiles(root, exclude),
1110
- ...directories.flatMap((directory) => [findFiles(directory, packageExclude), findServerFiles(directory, packageExclude)])
1111
- ]);
1112
- appScripts = packages.length > 0 ? (await findScripts(root, exclude)).filter(ownFile) : [];
2015
+ }
2016
+ async function scan() {
2017
+ const directories = [];
2018
+ for (const item of packages) for (const directory of item.directories) if (existsSync(directory)) directories.push(directory);
2019
+ function ownFile(file) {
2020
+ return !findPackage(packages, file);
2021
+ }
2022
+ const searches = [findFiles(root, exclude), findServerFiles(root, exclude)];
2023
+ for (const directory of directories) searches.push(findFiles(directory, packageExclude), findServerFiles(directory, packageExclude));
2024
+ const [own, ownServer, ...found] = await Promise.all(searches);
2025
+ const scripts = [];
2026
+ if (packages.length > 0) {
2027
+ for (const file of await findScripts(root, exclude)) if (ownFile(file)) scripts.push(file);
2028
+ }
2029
+ appScripts = scripts;
1113
2030
  files.clear();
1114
2031
  serverFiles.clear();
1115
- for (const file of own.filter(ownFile)) files.set(componentId(file), file);
1116
- for (const file of ownServer.filter(ownFile)) serverFiles.set(serverFileId(file), file);
2032
+ for (const file of own) if (ownFile(file)) files.set(componentId(file), file);
2033
+ for (const file of ownServer) if (ownFile(file)) serverFiles.set(serverFileId(file), file);
1117
2034
  for (const [index, list] of found.entries()) for (const file of list) if (index % 2 === 0) files.set(componentId(file), file);
1118
2035
  else serverFiles.set(serverFileId(file), file);
1119
- await analyze();
1120
- };
2036
+ try {
2037
+ await analyze();
2038
+ } finally {
2039
+ workbenchList = void 0;
2040
+ }
2041
+ }
1121
2042
  /**
1122
2043
  * The files of packages that the app reaches through its imports. A server
1123
2044
  * function of a package becomes an endpoint of the app only when the app
1124
2045
  * reaches its file, so installing a package does not expose all of them.
1125
2046
  */
1126
- const reachable = () => reachableFiles(packages, [...[...files.values()].filter((file) => !packageOf(packages, file)), ...appScripts], (file) => {
1127
- try {
1128
- return readFileSync(file, "utf8");
1129
- } catch {
1130
- return;
1131
- }
1132
- });
2047
+ function reachable() {
2048
+ const roots = [];
2049
+ for (const file of files.values()) if (!findPackage(packages, file)) roots.push(file);
2050
+ return reachableFiles(packages, [...roots, ...appScripts], (file) => {
2051
+ try {
2052
+ return readFileSync(file, "utf8");
2053
+ } catch {
2054
+ return;
2055
+ }
2056
+ });
2057
+ }
1133
2058
  /** The files of packages in the last server registry. */
1134
2059
  let registered = /* @__PURE__ */ new Set();
1135
2060
  /** Resolves a `.brm` file that a component imports: next to it, or from a package of components. */
1136
- const resolveComponent = (specifier, importer) => resolveRelative(specifier, importer) ?? (specifier.endsWith(".brm") && isPackageSpecifier(specifier) ? resolvePackageImport(specifier, importer) : void 0);
1137
- const analyze = async () => {
2061
+ function resolveComponent(specifier, importer) {
2062
+ return resolveRelative(specifier, importer) ?? (specifier.endsWith(".brm") ? resolveComponentPackage(packages, specifier, importer) : void 0);
2063
+ }
2064
+ async function analyze() {
1138
2065
  const list = [...files.values()];
1139
- const contents = await Promise.all(list.map((file) => readFile(file, "utf8")));
1140
- const sources = new Map(list.map((file, index) => [file, contents[index]]));
2066
+ const contents = await inBatches(list, (file) => readFile(file, "utf8"));
2067
+ const sources = /* @__PURE__ */ new Map();
2068
+ for (const [index, file] of list.entries()) sources.set(file, contents[index]);
1141
2069
  liveProps = analyzeProject(sources, resolveComponent);
1142
2070
  const scripts = await findScripts(root, exclude);
1143
- const scriptSources = await Promise.all([.../* @__PURE__ */ new Set([...scripts, ...serverFiles.values()])].map((file) => readFile(file, "utf8").catch(() => "")));
2071
+ const scriptSources = await inBatches([.../* @__PURE__ */ new Set([...scripts, ...serverFiles.values()])], (file) => readFile(file, "utf8").catch(() => ""));
1144
2072
  refreshed = refreshedNames([...contents, ...scriptSources]);
1145
2073
  compiled.clear();
1146
- };
2074
+ }
2075
+ /** The features of the core that the components of the build use, once for each build. */
2076
+ let builtFeatures;
2077
+ /** The files that `builtFeatures` counted, and the features it found. */
2078
+ let counted = /* @__PURE__ */ new Set();
2079
+ let knownFeatures;
2080
+ /** The components that the client build loaded. */
2081
+ const loadedComponents = /* @__PURE__ */ new Set();
2082
+ function buildFeatures() {
2083
+ return builtFeatures ??= (async () => {
2084
+ const seen = /* @__PURE__ */ new Set();
2085
+ const all = [];
2086
+ async function visit(file) {
2087
+ if (seen.has(file)) return;
2088
+ seen.add(file);
2089
+ const { result } = await compileFile(file);
2090
+ all.push(getFeatures(result));
2091
+ const imported = [];
2092
+ for (const specifier of importedComponents(result.file)) {
2093
+ const target = resolveComponent(specifier, file);
2094
+ if (target !== void 0 && existsSync(target)) imported.push(target);
2095
+ }
2096
+ await inBatches(imported, visit);
2097
+ }
2098
+ await inBatches([...files.values()], visit);
2099
+ const features = joinFeatures(all);
2100
+ let loading = false;
2101
+ for (const file of seen) if (path.basename(file) === "_loading.brm") {
2102
+ loading = true;
2103
+ break;
2104
+ }
2105
+ features.lateMarkup ||= options.navigate !== false || loading;
2106
+ counted = seen;
2107
+ knownFeatures = features;
2108
+ return features;
2109
+ })();
2110
+ }
1147
2111
  /** The options of the compile of a file. */
1148
- const compileOptions = (file) => ({
1149
- filename: nameOf(file),
1150
- liveProps: liveProps.get(file),
1151
- refreshed,
1152
- path: file,
1153
- merge: options.merge ?? 4096,
1154
- a11y: options.a11y,
1155
- hideNames: !isServe,
1156
- sendableClasses: serialClasses(),
1157
- serverImport: (specifier, name) => serverImport(file, specifier, name),
1158
- resolveModule: (specifier, importer) => {
1159
- const local = resolveFromDisk(specifier, importer);
1160
- const found = local === void 0 && isPackageSpecifier(specifier) ? resolvePackageImport(specifier, importer) : void 0;
1161
- return found ? {
1162
- path: found,
1163
- source: readFileSync(found, "utf8")
1164
- } : local;
1165
- }
1166
- });
1167
- const compileFile = async (file) => {
2112
+ function compileOptions(file) {
2113
+ return {
2114
+ filename: getFileName(file),
2115
+ liveProps: liveProps.get(file),
2116
+ refreshed,
2117
+ path: file,
2118
+ merge: options.merge ?? 4096,
2119
+ a11y: options.a11y,
2120
+ hideNames: !isServe,
2121
+ sendableClasses: serialClasses(),
2122
+ serverImport: (specifier, name) => serverImport(file, specifier, name),
2123
+ resolveModule: (specifier, importer) => {
2124
+ const local = resolveFromDisk(specifier, importer);
2125
+ const found = local === void 0 ? resolveComponentPackage(packages, specifier, importer) : void 0;
2126
+ return found ? {
2127
+ path: found,
2128
+ source: readFileSync(found, "utf8")
2129
+ } : local;
2130
+ }
2131
+ };
2132
+ }
2133
+ async function compileFile(file) {
1168
2134
  const source = await readFile(file, "utf8");
1169
2135
  let cached = compiled.get(file);
1170
2136
  if (cached?.source !== source) {
@@ -1173,10 +2139,10 @@ function brumate(options = {}) {
1173
2139
  result: compile(source, compileOptions(file))
1174
2140
  };
1175
2141
  compiled.set(file, cached);
1176
- shapes.set(file, shapeOf(cached.result));
2142
+ shapes.set(file, getShape(cached.result));
1177
2143
  }
1178
2144
  return cached;
1179
- };
2145
+ }
1180
2146
  /** The compiles whose imports were checked for the env file. */
1181
2147
  const envChecked = /* @__PURE__ */ new WeakSet();
1182
2148
  /**
@@ -1184,15 +2150,17 @@ function brumate(options = {}) {
1184
2150
  * when one of its imports resolves to it, by any specifier, such as an
1185
2151
  * alias. The compile fails when code that runs in the browser reads one.
1186
2152
  */
1187
- const checkEnvReads = async (file, { source, result }, resolve) => {
2153
+ async function checkEnvReads(file, { source, result }, resolve) {
1188
2154
  const env = envFile();
1189
2155
  if (!env || envChecked.has(result)) return;
1190
2156
  const specifiers = /* @__PURE__ */ new Set();
1191
2157
  for (const declaration of result.plan.graph.model.declarations) if (declaration.imported) specifiers.add(declaration.imported.source);
1192
- const resolved = await Promise.all([...specifiers].map(async (specifier) => {
2158
+ const pending = [];
2159
+ for (const specifier of specifiers) pending.push((async () => {
1193
2160
  return (await resolve(specifier, file))?.id.split("?")[0] === env ? specifier : void 0;
1194
- }));
1195
- const imports = new Set(resolved.filter((specifier) => specifier !== void 0));
2161
+ })());
2162
+ const imports = /* @__PURE__ */ new Set();
2163
+ for (const specifier of await Promise.all(pending)) if (specifier !== void 0) imports.add(specifier);
1196
2164
  if (imports.size > 0) {
1197
2165
  const server = serverEnvKeys() ?? [];
1198
2166
  compile(source, {
@@ -1201,13 +2169,143 @@ function brumate(options = {}) {
1201
2169
  });
1202
2170
  }
1203
2171
  envChecked.add(result);
1204
- };
1205
- const manifest = async () => {
2172
+ }
2173
+ /** The components that a component imports, by file. */
2174
+ async function componentImports(file) {
2175
+ const { result } = await compileFile(file);
2176
+ const found = [];
2177
+ for (const declaration of result.plan.graph.model.declarations) {
2178
+ const source = declaration.imported?.source;
2179
+ const target = source?.endsWith(".brm") ? resolveComponent(source, file) : void 0;
2180
+ if (target !== void 0) found.push(target);
2181
+ }
2182
+ return found;
2183
+ }
2184
+ /**
2185
+ * The bundles of a build: for each component that no other component imports, such as a
2186
+ * route or a page, the components with client code that it can render. The page loads the
2187
+ * bundles of its roots at once, as one chunk each, so its code comes in one request.
2188
+ * Components that only import each other get a bundle too.
2189
+ */
2190
+ async function bundles(kept) {
2191
+ const imports = /* @__PURE__ */ new Map();
2192
+ await inBatches([...files.values()], async (file) => {
2193
+ try {
2194
+ imports.set(file, await componentImports(file));
2195
+ } catch {
2196
+ imports.set(file, []);
2197
+ }
2198
+ });
2199
+ const imported = /* @__PURE__ */ new Set();
2200
+ for (const targets of imports.values()) for (const target of targets) imported.add(target);
2201
+ const result = /* @__PURE__ */ new Map();
2202
+ const reached = /* @__PURE__ */ new Set();
2203
+ function addRoot(id, file) {
2204
+ const seen = /* @__PURE__ */ new Set();
2205
+ function walk(current) {
2206
+ if (seen.has(current)) return;
2207
+ seen.add(current);
2208
+ reached.add(current);
2209
+ for (const next of imports.get(current) ?? []) walk(next);
2210
+ }
2211
+ walk(file);
2212
+ const members = [];
2213
+ for (const member of seen) if (kept.has(member)) members.push(member);
2214
+ if (members.length > 0) result.set(id, members);
2215
+ }
2216
+ for (const [id, file] of files) if (!imported.has(file)) addRoot(id, file);
2217
+ for (const [id, file] of files) if (!reached.has(file) && kept.has(file)) addRoot(id, file);
2218
+ return result;
2219
+ }
2220
+ /** The ID of each component file. */
2221
+ function findComponentId(file) {
2222
+ for (const [id, other] of files) if (other === file) return id;
2223
+ }
2224
+ /** A bundle module: the client modules of a root component and of those it renders. */
2225
+ async function bundleModule(root) {
1206
2226
  const list = [...files];
1207
- const needed = await Promise.all(list.map(async ([, file]) => isServe || (await compileFile(file)).result.clientCode));
2227
+ const needed = await inBatches(list, async ([, file]) => (await compileFile(file)).result.clientCode);
2228
+ const kept = /* @__PURE__ */ new Set();
2229
+ for (const [index, [, file]] of list.entries()) if (needed[index]) kept.add(file);
2230
+ const members = (await bundles(kept)).get(root) ?? [];
2231
+ const imports = [];
2232
+ const objects = [];
2233
+ for (const [index, file] of members.entries()) {
2234
+ const { result } = await compileFile(file);
2235
+ const codes = [result.client];
2236
+ for (const [name, code] of Object.entries(result.parts)) if (name !== "shared") codes.push(code);
2237
+ const names = exportNames(codes);
2238
+ const aliased = [];
2239
+ const fields = [];
2240
+ for (const name of names) {
2241
+ aliased.push(`${name} as $$c${index}_${name}`);
2242
+ fields.push(`${name}: $$c${index}_${name}`);
2243
+ }
2244
+ imports.push(`import { ${aliased.join(", ")} } from ${JSON.stringify(`${file}${CLIENT_QUERY}`)};`);
2245
+ objects.push(` ${JSON.stringify(findComponentId(file))}: { ${fields.join(", ")} },`);
2246
+ }
2247
+ return [
2248
+ ...imports,
2249
+ "export const modules = {",
2250
+ ...objects,
2251
+ "};"
2252
+ ].join("\n");
2253
+ }
2254
+ async function manifest() {
2255
+ const list = [...files];
2256
+ const needed = await inBatches(list, async ([, file]) => isServe || (await compileFile(file)).result.clientCode);
2257
+ const kept = [];
2258
+ for (const [index, entry] of list.entries()) if (needed[index]) kept.push(entry);
2259
+ if (!isServe) {
2260
+ const keptFiles = /* @__PURE__ */ new Set();
2261
+ for (const [, file] of kept) keptFiles.add(file);
2262
+ const groups = await bundles(keptFiles);
2263
+ const owners = /* @__PURE__ */ new Map();
2264
+ for (const [root, members] of groups) for (const member of members) {
2265
+ const id = findComponentId(member);
2266
+ if (id !== void 0 && !owners.has(id)) owners.set(id, root);
2267
+ }
2268
+ for (const [id, root] of owners) if (id === root) owners.delete(id);
2269
+ const bundleLines = [];
2270
+ for (const root of groups.keys()) bundleLines.push(` ${JSON.stringify(root)}: () => import(${JSON.stringify(`${BUNDLE}${root}`)}),`);
2271
+ return [
2272
+ "const bundles = {",
2273
+ ...bundleLines,
2274
+ "};",
2275
+ `const owners = ${JSON.stringify(Object.fromEntries(owners))};`,
2276
+ "const loaded = new Map();",
2277
+ "const pending = new Map();",
2278
+ "/** Loads the bundle of a root component of the page. Undefined for a component that is not a root. */",
2279
+ "export function loadBundle(root) {",
2280
+ " let promise = pending.get(root);",
2281
+ " if (!promise && bundles[root]) {",
2282
+ " promise = bundles[root]().then((bundle) => {",
2283
+ " for (const [id, module] of Object.entries(bundle.modules)) {",
2284
+ " loaded.set(id, module);",
2285
+ " }",
2286
+ " });",
2287
+ " pending.set(root, promise);",
2288
+ " promise.catch(() => pending.delete(root));",
2289
+ " }",
2290
+ " return promise;",
2291
+ "}",
2292
+ "/** The client module of a component, from the bundles of the page, or else from a bundle that holds it. */",
2293
+ "export function load(id) {",
2294
+ " if (loaded.has(id)) {",
2295
+ " return Promise.resolve(loaded.get(id));",
2296
+ " }",
2297
+ " const waiting = [...pending.values()];",
2298
+ " const root = owners[id] ?? (bundles[id] && id);",
2299
+ " const owner = () => (loaded.has(id) || !root ? loaded.get(id) : loadBundle(root).then(() => loaded.get(id)));",
2300
+ " return waiting.length > 0 ? Promise.allSettled(waiting).then(owner) : root ? owner() : undefined;",
2301
+ "}"
2302
+ ].join("\n");
2303
+ }
2304
+ const entries = [];
2305
+ for (const [id, file] of kept) entries.push(` ${JSON.stringify(id)}: () => import(${JSON.stringify(`${file}${CLIENT_QUERY}`)}),`);
1208
2306
  return [
1209
2307
  "const modules = {",
1210
- ...list.filter((_, index) => needed[index]).map(([id, file]) => ` ${JSON.stringify(id)}: () => import(${JSON.stringify(`${file}${CLIENT_QUERY}`)}),`),
2308
+ ...entries,
1211
2309
  "};",
1212
2310
  "export function load(id) {",
1213
2311
  ...isServe ? [
@@ -1219,38 +2317,57 @@ function brumate(options = {}) {
1219
2317
  ] : [" return modules[id]?.();"],
1220
2318
  "}"
1221
2319
  ].join("\n");
1222
- };
2320
+ }
1223
2321
  /**
1224
2322
  * The module of every server function of the app, by ID. With `server`, in
1225
2323
  * a DOM test, it imports the server code of each file, which that
1226
2324
  * environment would give as browser code.
1227
2325
  */
1228
- const serverRegistry = (server = false) => {
2326
+ function serverRegistry(server = false) {
1229
2327
  const query = server ? SERVER_QUERY : "";
1230
2328
  registered = packages.length > 0 ? reachable() : /* @__PURE__ */ new Set();
1231
- const keep = (file) => registered.has(file) || !packageOf(packages, file);
1232
- const components = [...files.values()].filter(keep);
1233
- const importAll = (prefix, list) => {
1234
- if (!isServe) return list.map((file, index) => `import * as ${prefix}${index} from ${JSON.stringify(file + query)};`);
2329
+ function keep(file) {
2330
+ return registered.has(file) || !findPackage(packages, file);
2331
+ }
2332
+ const components = [];
2333
+ for (const file of files.values()) if (keep(file)) components.push(file);
2334
+ function importAll(prefix, list) {
2335
+ if (!isServe) {
2336
+ const lines = [];
2337
+ for (const [index, file] of list.entries()) lines.push(`import * as ${prefix}${index} from ${JSON.stringify(file + query)};`);
2338
+ return lines;
2339
+ }
1235
2340
  if (list.length === 0) return [];
1236
- const loads = list.map((file) => `import(${JSON.stringify(file + query)})`);
1237
- return [`const [${list.map((_, index) => `${prefix}${index}`).join(", ")}] = (await Promise.allSettled([${loads.join(", ")}])).map((result) => (result.status === 'fulfilled' ? result.value : {}));`];
1238
- };
2341
+ const loads = [];
2342
+ const names = [];
2343
+ for (const [index, file] of list.entries()) {
2344
+ loads.push(`import(${JSON.stringify(file + query)})`);
2345
+ names.push(`${prefix}${index}`);
2346
+ }
2347
+ return [`const [${names.join(", ")}] = (await Promise.allSettled([${loads.join(", ")}])).map((result) => (result.status === 'fulfilled' ? result.value : {}));`];
2348
+ }
1239
2349
  const imports = importAll("m", components);
1240
- const spreads = components.map((_, index) => ` ...m${index}.rpc,`);
1241
- const functionFiles = [...serverFiles.entries()].filter(([, file]) => keep(file));
1242
- const fileImports = importAll("f", functionFiles.map(([, file]) => file));
2350
+ const spreads = [];
2351
+ for (const index of components.keys()) spreads.push(` ...m${index}.rpc,`);
2352
+ const functionFiles = [];
2353
+ for (const entry of serverFiles) if (keep(entry[1])) functionFiles.push(entry);
2354
+ const functionPaths = [];
2355
+ for (const [, file] of functionFiles) functionPaths.push(file);
2356
+ const fileImports = importAll("f", functionPaths);
1243
2357
  const guards = [];
1244
- const fileSpreads = functionFiles.map(([id, file], index) => {
2358
+ const fileSpreads = [];
2359
+ for (const [index, [id, file]] of functionFiles.entries()) {
1245
2360
  const source = readFileSync(file, "utf8");
1246
2361
  const names = serverExports(source, file);
1247
2362
  const guarded = hasServerMiddleware(source, file);
1248
- return names.map((name) => {
2363
+ const lines = [];
2364
+ for (const name of names) {
1249
2365
  const key = JSON.stringify(functionId(id, name, !isServe));
1250
2366
  if (guarded) guards.push(` ${key}: f${index}.middleware,`);
1251
- return ` ${key}: f${index}[${JSON.stringify(name)}],`;
1252
- }).join("\n");
1253
- });
2367
+ lines.push(` ${key}: f${index}[${JSON.stringify(name)}],`);
2368
+ }
2369
+ fileSpreads.push(lines.join("\n"));
2370
+ }
1254
2371
  const env = envFile();
1255
2372
  const entry = middlewareFile();
1256
2373
  return [
@@ -1271,12 +2388,15 @@ function brumate(options = {}) {
1271
2388
  ` return handleRequest(functions, request, ${JSON.stringify(rpc)}, { origins: ${JSON.stringify(options.origins ?? [])}, ${entry ? "middleware, " : ""}fileMiddleware${buildId === void 0 ? "" : `, build: ${JSON.stringify(buildId)}`}, ...options });`,
1272
2389
  "}"
1273
2390
  ].join("\n");
1274
- };
1275
- const routesDirectory = () => normalizePath(path.resolve(root, options.routes ?? "src/routes"));
2391
+ }
2392
+ function routesDirectory() {
2393
+ return normalizePath(path.resolve(root, options.routes ?? "src/routes"));
2394
+ }
1276
2395
  /** The route files, from the `.brm` files found and the `.ts` files of the directory. */
1277
- const currentRoutes = () => {
2396
+ function currentRoutes() {
1278
2397
  const directory = routesDirectory();
1279
- const paths = [...files.values()].filter((file) => file.startsWith(`${directory}/`)).map((file) => file.slice(directory.length + 1));
2398
+ const paths = [];
2399
+ for (const file of files.values()) if (file.startsWith(`${directory}/`)) paths.push(file.slice(directory.length + 1));
1280
2400
  if (existsSync(directory)) for (const entry of readdirSync(directory, {
1281
2401
  recursive: true,
1282
2402
  encoding: "utf8"
@@ -1285,70 +2405,102 @@ function brumate(options = {}) {
1285
2405
  if (file.endsWith(".ts") && !file.endsWith(".d.ts")) paths.push(file);
1286
2406
  }
1287
2407
  return routeFiles(paths);
1288
- };
2408
+ }
1289
2409
  /**
1290
2410
  * The modules that every page loads early, which the client build wrote,
1291
2411
  * or none before a client build or in development.
1292
2412
  */
1293
- const clientHints = () => {
2413
+ function clientHints() {
1294
2414
  const file = path.join(clientBuildDirectory(root, options.prerender), HINTS_FILE);
1295
- return !isServe && existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : [];
1296
- };
2415
+ if (isServe || !existsSync(file)) return {
2416
+ all: [],
2417
+ bundles: {}
2418
+ };
2419
+ const read = JSON.parse(readFileSync(file, "utf8"));
2420
+ return Array.isArray(read) ? {
2421
+ all: read,
2422
+ bundles: {}
2423
+ } : read;
2424
+ }
1297
2425
  /** The route tree module. A DOM test gets the server version of each component in it. */
1298
- const routeTree = (server = false) => {
2426
+ function routeTree(server = false) {
1299
2427
  const env = envFile();
1300
- const code = routeModule(currentRoutes(), (file) => `${routesDirectory()}/${file}${server && file.endsWith(".brm") ? SERVER_QUERY : ""}`, rpc, options.origins, isServe, middlewareFile(), buildId, clientHints());
2428
+ const code = routeModule(currentRoutes(), (file) => `${routesDirectory()}/${file}${server && file.endsWith(".brm") ? SERVER_QUERY : ""}`, rpc, options.origins, isServe, middlewareFile(), buildId, clientHints().all, clientHints().bundles);
1301
2429
  const serial = serialImports().join("\n");
1302
- return [
2430
+ const parts = [];
2431
+ for (const part of [
1303
2432
  env ? `import ${JSON.stringify(env)};` : "",
1304
2433
  serial,
1305
2434
  code
1306
- ].filter(Boolean).join("\n");
1307
- };
2435
+ ]) if (part) parts.push(part);
2436
+ return parts.join("\n");
2437
+ }
1308
2438
  /** Writes the paths of the routes as types for `href`, when they changed. */
1309
- const writeRouteTypes = () => {
2439
+ function writeRouteTypes() {
1310
2440
  if (options.routeTypes === false || !existsSync(routesDirectory())) return;
1311
2441
  const file = path.resolve(root, options.routeTypes ?? "src/brumate-routes.d.ts");
1312
2442
  const text = routeTypes(currentRoutes());
1313
2443
  if (!existsSync(file) || readFileSync(file, "utf8") !== text) writeFileSync(file, text);
1314
- };
2444
+ }
1315
2445
  /** What the devtools panel shows about a component: its name, its scopes and its report. */
1316
- const inspectComponent = async (id) => {
2446
+ async function inspectComponent(id) {
1317
2447
  const file = files.get(id);
1318
2448
  if (!file) return;
1319
2449
  const { source, result } = await compileFile(file);
1320
2450
  const { plan } = result;
1321
2451
  const scopes = {};
1322
- const siteLabel = (site) => {
2452
+ function siteLabel(site) {
1323
2453
  const at = result.locate(site.range.start);
1324
2454
  const where = at.file === void 0 ? getLocation(source, at.offset) : void 0;
1325
2455
  return where ? `${site.label} ${where.line}:${where.column}` : site.label;
1326
- };
1327
- const liveSites = new Set([...plan.graph.live].flatMap((node) => "site" in node ? [node.site] : []));
1328
- for (const layout of plan.scopes.values()) scopes[layout.scope.id] = {
1329
- label: scopeLabel(result.file.source, layout.scope),
1330
- slots: layout.slots.map((slot) => slot.name),
1331
- readers: layout.slots.map((slot) => [...new Set(slot.reads.filter((ref) => plan.graph.reached.has(ref.site) || liveSites.has(ref.site)).map((ref) => siteLabel(ref.site)))])
1332
- };
1333
- const nodes = plan.graph.nodes.filter((node) => plan.graph.live.has(node));
1334
- const indexes = new Map(nodes.map((node, index) => [node, index]));
1335
- const graph = {
1336
- nodes: nodes.map((node) => {
1337
- if (node.kind === "source" || node.kind === "memo") return {
2456
+ }
2457
+ const liveSites = /* @__PURE__ */ new Set();
2458
+ for (const node of plan.graph.live) if ("site" in node) liveSites.add(node.site);
2459
+ for (const layout of plan.scopes.values()) {
2460
+ const slotNames = [];
2461
+ const readers = [];
2462
+ for (const slot of layout.slots) {
2463
+ slotNames.push(slot.name);
2464
+ const labels = /* @__PURE__ */ new Set();
2465
+ for (const ref of slot.reads) if (plan.graph.reached.has(ref.site) || liveSites.has(ref.site)) labels.add(siteLabel(ref.site));
2466
+ readers.push([...labels]);
2467
+ }
2468
+ scopes[layout.scope.id] = {
2469
+ label: scopeLabel(result.file.source, layout.scope),
2470
+ slots: slotNames,
2471
+ readers
2472
+ };
2473
+ }
2474
+ const nodes = [];
2475
+ const indexes = /* @__PURE__ */ new Map();
2476
+ for (const node of plan.graph.nodes) if (plan.graph.live.has(node)) {
2477
+ indexes.set(node, nodes.length);
2478
+ nodes.push(node);
2479
+ }
2480
+ const graphNodes = [];
2481
+ for (const node of nodes) {
2482
+ if (node.kind === "source" || node.kind === "memo") {
2483
+ graphNodes.push({
1338
2484
  kind: node.kind === "memo" ? "memo" : node.declaration.kind,
1339
2485
  label: node.declaration.name,
1340
2486
  scope: instanceScope(plan, node.declaration.scope).id,
1341
2487
  slot: slotIndex(plan, node.declaration)
1342
- };
1343
- const at = result.locate(node.site.range.start);
1344
- const where = at.file === void 0 ? getLocation(source, at.offset) : void 0;
1345
- return {
1346
- kind: node.kind,
1347
- label: where ? `${node.site.label} ${where.line}:${where.column}` : node.site.label,
1348
- scope: instanceScope(plan, node.site.scope).id
1349
- };
1350
- }),
1351
- edges: plan.graph.edges.filter((edge) => indexes.has(edge.from) && indexes.has(edge.to)).map((edge) => [indexes.get(edge.from), indexes.get(edge.to)])
2488
+ });
2489
+ continue;
2490
+ }
2491
+ const at = result.locate(node.site.range.start);
2492
+ const where = at.file === void 0 ? getLocation(source, at.offset) : void 0;
2493
+ graphNodes.push({
2494
+ kind: node.kind,
2495
+ label: where ? `${node.site.label} ${where.line}:${where.column}` : node.site.label,
2496
+ scope: instanceScope(plan, node.site.scope).id
2497
+ });
2498
+ }
2499
+ const graphEdges = [];
2500
+ 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)]);
2501
+ const graph = {
2502
+ nodes: graphNodes,
2503
+ edges: graphEdges
1352
2504
  };
1353
2505
  const anchors = {};
1354
2506
  for (const [target, index] of plan.anchors) {
@@ -1380,7 +2532,7 @@ function brumate(options = {}) {
1380
2532
  const text = formatReport(report(source, result, liveProps.get(file)));
1381
2533
  return {
1382
2534
  name: plan.name,
1383
- file: nameOf(file),
2535
+ file: getFileName(file),
1384
2536
  path: file,
1385
2537
  url: file.startsWith(`${normalizePath(root)}/`) ? file.slice(normalizePath(root).length) : `/@fs${file}`,
1386
2538
  scopes,
@@ -1388,12 +2540,165 @@ function brumate(options = {}) {
1388
2540
  graph,
1389
2541
  text
1390
2542
  };
1391
- };
1392
- const handleDevRPC = async (server, request, response) => {
2543
+ }
2544
+ /** The components of the app for the workbench, with what each one needs and its controls. */
2545
+ /**
2546
+ * The stories of a component: the named exports of the `.stories.ts` file next to it, each a
2547
+ * set of props. Values that JSON cannot hold, such as functions, are left out.
2548
+ */
2549
+ async function workbenchStories(server, file) {
2550
+ const storiesFile = file.replace(/\.brm$/, ".stories.ts");
2551
+ if (!existsSync(storiesFile)) return { stories: [] };
2552
+ try {
2553
+ const module = await server.ssrLoadModule(storiesFile);
2554
+ const stories = [];
2555
+ for (const [name, props] of Object.entries(module)) if (name !== "default" && props && typeof props === "object") stories.push({
2556
+ name,
2557
+ props: JSON.parse(JSON.stringify(props))
2558
+ });
2559
+ return { stories };
2560
+ } catch (error) {
2561
+ return {
2562
+ stories: [],
2563
+ storiesError: error instanceof Error ? error.message : String(error)
2564
+ };
2565
+ }
2566
+ }
2567
+ /** The group of a component of a package: its name, and the folder under the directory of its files. */
2568
+ function packageGroup(owner, file) {
2569
+ let directory = owner.root;
2570
+ for (const item of owner.directories) if (file.startsWith(`${item}/`)) {
2571
+ directory = item;
2572
+ break;
2573
+ }
2574
+ const folder = path.posix.dirname(file.slice(directory.length + 1));
2575
+ return folder === "." ? owner.name : `${owner.name}/${folder}`;
2576
+ }
2577
+ async function workbenchComponents(server) {
2578
+ const routes = `${routesDirectory()}/`;
2579
+ const list = [...new Set(files.values())];
2580
+ const contents = await inBatches(list, (file) => readFile(file, "utf8"));
2581
+ const sources = /* @__PURE__ */ new Map();
2582
+ for (const [index, file] of list.entries()) sources.set(file, contents[index]);
2583
+ const classes = classifyComponents(sources, {
2584
+ resolve: resolveComponent,
2585
+ serverImport: (file, specifier, name) => serverImport(file, specifier, name) !== void 0
2586
+ });
2587
+ function relative(file) {
2588
+ return normalizePath(path.relative(root, file));
2589
+ }
2590
+ const shown = [];
2591
+ for (const file of list) if (!file.startsWith(routes) && classes.has(file)) shown.push(file);
2592
+ const stories = await inBatches(shown, (file) => workbenchStories(server, file));
2593
+ const components = [];
2594
+ for (const [index, file] of shown.entries()) {
2595
+ const found = classes.get(file);
2596
+ let controls = [];
2597
+ try {
2598
+ controls = propControls(parse(sources.get(file), { filename: file }));
2599
+ } catch {
2600
+ controls = void 0;
2601
+ }
2602
+ const owner = findPackage(packages, file);
2603
+ const needs = [];
2604
+ for (const need of found.needs) needs.push({
2605
+ ...need,
2606
+ via: need.via && relative(need.via)
2607
+ });
2608
+ components.push({
2609
+ file: relative(file),
2610
+ group: owner ? packageGroup(owner, file) : path.posix.dirname(relative(file)),
2611
+ label: owner ? `${packageGroup(owner, file)}/${path.basename(file)}` : relative(file),
2612
+ name: path.basename(file, ".brm"),
2613
+ selfContained: found.selfContained,
2614
+ needs,
2615
+ controls: controls ?? [],
2616
+ unreadProps: controls === void 0,
2617
+ ...stories[index]
2618
+ });
2619
+ }
2620
+ return components.toSorted((a, b) => a.file.localeCompare(b.file));
2621
+ }
2622
+ let workbenchList;
2623
+ /** Makes the list of the workbench and keeps it, unless it fails, so a later read tries again. */
2624
+ function listWorkbench(server) {
2625
+ const list = workbenchComponents(server);
2626
+ workbenchList = list;
2627
+ list.catch(() => {
2628
+ if (workbenchList === list) workbenchList = void 0;
2629
+ });
2630
+ return list;
2631
+ }
2632
+ /**
2633
+ * Answers the workbench: its page, the list of components, and the frame that renders one
2634
+ * component on the server with props, and resumes it in the browser as a page does.
2635
+ */
2636
+ async function serveWorkbench(server, request, response) {
2637
+ const url = new URL(request.url ?? "/", "http://localhost");
2638
+ if (url.pathname === WORKBENCH || url.pathname === `${WORKBENCH}/`) {
2639
+ response.setHeader("content-type", "text/html; charset=utf-8");
2640
+ response.end(workbenchPage(WORKBENCH));
2641
+ return;
2642
+ }
2643
+ if (url.pathname === `${WORKBENCH}/components`) {
2644
+ response.setHeader("content-type", "application/json");
2645
+ response.end(JSON.stringify(await listWorkbench(server)));
2646
+ return;
2647
+ }
2648
+ if (url.pathname !== `${WORKBENCH}/frame`) {
2649
+ response.statusCode = 404;
2650
+ response.end();
2651
+ return;
2652
+ }
2653
+ const asked = url.searchParams.get("file") ?? "";
2654
+ let listed = false;
2655
+ for (const component of await (workbenchList ?? listWorkbench(server))) if (component.file === asked && component.selfContained) {
2656
+ listed = true;
2657
+ break;
2658
+ }
2659
+ let file;
2660
+ if (listed) {
2661
+ for (const candidate of files.values()) if (normalizePath(path.relative(root, candidate)) === asked) {
2662
+ file = candidate;
2663
+ break;
2664
+ }
2665
+ }
2666
+ if (!file) {
2667
+ response.statusCode = 404;
2668
+ response.end(`No self-contained component "${asked}"`);
2669
+ return;
2670
+ }
2671
+ response.setHeader("content-type", "text/html; charset=utf-8");
2672
+ try {
2673
+ const props = JSON.parse(url.searchParams.get("props") || "{}");
2674
+ const component = (await server.ssrLoadModule(file)).default;
2675
+ const { renderToStream } = await server.ssrLoadModule("brumate/server");
2676
+ const reader = renderToStream(component, props, {
2677
+ 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>`,
2678
+ end: "</body></html>",
2679
+ scripts: `<script type="module" src="/@vite/client"><\/script><script type="module" src="/@id/__x00__${START}"><\/script>`
2680
+ }).getReader();
2681
+ for (;;) {
2682
+ const { done, value } = await reader.read();
2683
+ if (done) break;
2684
+ response.write(value);
2685
+ }
2686
+ response.end();
2687
+ } catch (error) {
2688
+ if (response.headersSent) {
2689
+ server.config.logger.error(error instanceof Error ? error.stack ?? error.message : String(error));
2690
+ response.end();
2691
+ return;
2692
+ }
2693
+ response.statusCode = 500;
2694
+ response.end(errorPage(error, server));
2695
+ }
2696
+ }
2697
+ async function handleDevRPC(server, request, response) {
1393
2698
  const id = decodeURIComponent((request.url ?? "").slice(rpc.length + 1).split("?")[0]);
1394
2699
  const owner = id.split("#")[0];
1395
2700
  const file = files.get(owner) ?? serverFiles.get(owner);
1396
- const reached = file && packageOf(packages, file) ? reachable() : void 0;
2701
+ const reached = file && findPackage(packages, file) ? reachable() : void 0;
1397
2702
  if (!file || reached && !reached.has(file)) {
1398
2703
  response.statusCode = 404;
1399
2704
  response.end(`Unknown server function "${id}"`);
@@ -1405,9 +2710,11 @@ function brumate(options = {}) {
1405
2710
  }
1406
2711
  try {
1407
2712
  const { handle } = await server.ssrLoadModule(SERVER);
2713
+ const headers = [];
2714
+ for (const [name, value] of Object.entries(request.headers)) if (value !== void 0) headers.push([name, String(value)]);
1408
2715
  const webRequest = new Request(new URL(request.url ?? "/", "http://localhost"), {
1409
2716
  method: "POST",
1410
- headers: Object.entries(request.headers).flatMap(([name, value]) => value === void 0 ? [] : [[name, String(value)]]),
2717
+ headers,
1411
2718
  body: new Uint8Array(await readBody(request))
1412
2719
  });
1413
2720
  const began = performance.now();
@@ -1421,30 +2728,30 @@ function brumate(options = {}) {
1421
2728
  response.statusCode = 500;
1422
2729
  response.end(String(error));
1423
2730
  }
1424
- };
2731
+ }
1425
2732
  /** Updates the page in the browser after a change to a component, or reloads it. */
1426
2733
  async function updateClient(file, server, timestamp) {
1427
2734
  const normalized = normalizePath(file);
1428
2735
  const targets = file.endsWith(".brm") ? [normalized] : [...dependents.get(normalized) ?? []];
1429
2736
  if (targets.length === 0) return;
1430
- const invalidate = () => {
2737
+ function invalidate() {
1431
2738
  for (const module of server.moduleGraph.idToModuleMap.values()) {
1432
2739
  const id = module.id ?? "";
1433
2740
  if (id.includes(".brm") || id === `\0${MANIFEST}` || id === `\0${SERVER}` || id === `\0${ROUTES}`) server.moduleGraph.invalidateModule(module);
1434
2741
  }
1435
- };
1436
- const reload = () => {
2742
+ }
2743
+ function reload() {
1437
2744
  invalidate();
1438
2745
  server.ws.send({ type: "full-reload" });
1439
2746
  return [];
1440
- };
2747
+ }
1441
2748
  await analyze();
1442
2749
  const updates = [];
1443
2750
  for (const target of targets) {
1444
2751
  const before = shapes.get(target);
1445
2752
  let after;
1446
2753
  try {
1447
- after = shapeOf((await compileFile(target)).result);
2754
+ after = getShape((await compileFile(target)).result);
1448
2755
  } catch {
1449
2756
  return reload();
1450
2757
  }
@@ -1453,7 +2760,13 @@ function brumate(options = {}) {
1453
2760
  const id = componentId(target);
1454
2761
  const modules = [...server.moduleGraph.getModulesByFile(target) ?? [], ...target === normalized ? [] : server.moduleGraph.getModulesByFile(normalized) ?? []];
1455
2762
  for (const module of modules) server.moduleGraph.invalidateModule(module, /* @__PURE__ */ new Set(), timestamp, true);
1456
- const entry = [...server.moduleGraph.getModulesByFile(target) ?? []].find((module) => module.id?.endsWith(CLIENT_QUERY));
2763
+ let entry;
2764
+ for (const module of server.moduleGraph.getModulesByFile(target) ?? []) if (module.id?.endsWith(CLIENT_QUERY)) {
2765
+ entry = module;
2766
+ break;
2767
+ }
2768
+ const kept = [];
2769
+ for (const name of after.signals) if (before.signals.includes(name)) kept.push(name);
1457
2770
  updates.push({
1458
2771
  id,
1459
2772
  css: before.css === after.css ? void 0 : after.css,
@@ -1461,11 +2774,16 @@ function brumate(options = {}) {
1461
2774
  remount: remount ? {
1462
2775
  before: before.slots,
1463
2776
  after: after.slots,
1464
- signals: after.signals.filter((name) => before.signals.includes(name))
2777
+ signals: kept
1465
2778
  } : void 0
1466
2779
  });
1467
2780
  }
1468
- if (updates.some((update) => update.remount)) invalidate();
2781
+ let remounts = false;
2782
+ for (const update of updates) if (update.remount) {
2783
+ remounts = true;
2784
+ break;
2785
+ }
2786
+ if (remounts) invalidate();
1469
2787
  server.ws.send({
1470
2788
  type: "custom",
1471
2789
  event: "brumate:update",
@@ -1481,23 +2799,29 @@ function brumate(options = {}) {
1481
2799
  * or their `.brm` and `'use server'` files would not reach this plugin, and the
1482
2800
  * server build compiles them instead of importing them from `node_modules`.
1483
2801
  */
1484
- const packageConfig = (config) => {
2802
+ function packageConfig(config) {
1485
2803
  if (packages.length === 0) return {};
1486
- const names = [...new Set(packages.map((item) => item.name))];
2804
+ const nameSet = /* @__PURE__ */ new Set();
2805
+ for (const item of packages) nameSet.add(item.name);
2806
+ const names = [...nameSet];
1487
2807
  const result = {
1488
2808
  optimizeDeps: { exclude: names },
1489
2809
  ssr: { noExternal: names },
1490
2810
  resolve: { dedupe: ["brumate"] }
1491
2811
  };
1492
2812
  const workspace = normalizePath(searchForWorkspaceRoot(path.resolve(config.root ?? ".")));
1493
- const outside = packages.filter((item) => item.root !== workspace && !item.root.startsWith(`${workspace}/`)).map((item) => item.root);
2813
+ const outside = [];
2814
+ for (const item of packages) if (item.root !== workspace && !item.root.startsWith(`${workspace}/`)) outside.push(item.root);
1494
2815
  if (outside.length > 0) result.server = { fs: { allow: [workspace, ...outside] } };
1495
2816
  return result;
1496
- };
2817
+ }
1497
2818
  /** The module ID of `brumate/client`, and the chunks of the loader and the core in a client build. */
1498
2819
  let coreModule;
1499
2820
  let loaderChunk;
1500
2821
  let coreChunk;
2822
+ /** The chunks that the loader and the core import, which the server hints at, and the chunks of the bundles. */
2823
+ let startChunks = /* @__PURE__ */ new Set();
2824
+ let bundleChunks = /* @__PURE__ */ new Set();
1501
2825
  return {
1502
2826
  name: "brumate",
1503
2827
  enforce: "pre",
@@ -1513,17 +2837,19 @@ function brumate(options = {}) {
1513
2837
  ...shared,
1514
2838
  ...keep
1515
2839
  };
1516
- const resolve = typeof preload === "object" ? preload.resolveDependencies : void 0;
1517
2840
  return {
1518
2841
  ...shared,
1519
2842
  build: {
1520
2843
  ...keep.build,
1521
- modulePreload: { resolveDependencies(filename, deps, context) {
1522
- const list = resolve ? resolve(filename, deps, context) : deps;
1523
- if (context.hostId !== loaderChunk || !coreChunk) return list;
1524
- const rest = list.filter((dep) => dep !== coreChunk);
1525
- return rest.length === 1 && rest[0] === filename ? [] : rest;
1526
- } }
2844
+ modulePreload: {
2845
+ ...typeof preload === "object" ? preload : {},
2846
+ resolveDependencies(filename, deps) {
2847
+ if (bundleChunks.has(filename)) return [];
2848
+ const rest = [];
2849
+ for (const dep of deps) if (dep !== filename && !startChunks.has(dep)) rest.push(dep);
2850
+ return rest;
2851
+ }
2852
+ }
1527
2853
  }
1528
2854
  };
1529
2855
  }
@@ -1532,8 +2858,10 @@ function brumate(options = {}) {
1532
2858
  const input = typeof ssr === "string" ? ssr : config.build?.rolldownOptions?.input;
1533
2859
  let entries;
1534
2860
  if (typeof input === "string") entries = { [path.basename(input).replace(/\.[^.]+$/, "")]: input };
1535
- else if (Array.isArray(input)) entries = Object.fromEntries(input.map((item) => [path.basename(item).replace(/\.[^.]+$/, ""), item]));
1536
- else entries = { ...input };
2861
+ else if (Array.isArray(input)) {
2862
+ entries = {};
2863
+ for (const item of input) entries[path.basename(item).replace(/\.[^.]+$/, "")] = item;
2864
+ } else entries = { ...input };
1537
2865
  return {
1538
2866
  ...shared,
1539
2867
  build: {
@@ -1546,17 +2874,25 @@ function brumate(options = {}) {
1546
2874
  };
1547
2875
  },
1548
2876
  configureVitest(context) {
1549
- (context.defineCacheKeyGenerator ?? context.experimental_defineCacheKeyGenerator)?.(buildFingerprint);
2877
+ (context.defineCacheKeyGenerator ?? context.experimental_defineCacheKeyGenerator)?.(cacheKey);
1550
2878
  },
1551
2879
  configResolved(config) {
1552
2880
  root = config.root;
1553
2881
  isServe = config.command === "serve";
1554
2882
  outDir = path.resolve(config.root, config.build.outDir);
1555
2883
  base = config.base;
2884
+ relativeUrls = config.base === "./" || config.base === "" || !!config.experimental.renderBuiltUrl;
1556
2885
  isSsrBuild = Boolean(config.build.ssr);
1557
2886
  },
1558
2887
  async generateBundle(_output, bundle) {
1559
2888
  if (isSsrBuild) return;
2889
+ for (const file of knownFeatures ? loadedComponents : []) {
2890
+ if (counted.has(file)) continue;
2891
+ const used = getFeatures((await compileFile(file)).result);
2892
+ const missing = [];
2893
+ for (const name of Object.keys(used)) if (used[name] && !knownFeatures[name]) missing.push(name);
2894
+ 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'\`.`);
2895
+ }
1560
2896
  loaderChunk = void 0;
1561
2897
  coreChunk = void 0;
1562
2898
  for (const item of Object.values(bundle)) {
@@ -1564,68 +2900,101 @@ function brumate(options = {}) {
1564
2900
  if (item.moduleIds.includes(`\0${MANIFEST}`)) loaderChunk = item.fileName;
1565
2901
  if (coreModule && item.moduleIds.includes(coreModule)) coreChunk = item.fileName;
1566
2902
  }
2903
+ startChunks = /* @__PURE__ */ new Set();
2904
+ bundleChunks = /* @__PURE__ */ new Set();
2905
+ function addStart(name) {
2906
+ const found = name === void 0 ? void 0 : bundle[name];
2907
+ if (found?.type === "chunk" && !startChunks.has(name)) {
2908
+ startChunks.add(name);
2909
+ for (const imported of found.imports) addStart(imported);
2910
+ }
2911
+ }
2912
+ addStart(loaderChunk);
2913
+ addStart(coreChunk);
2914
+ for (const item of Object.values(bundle)) if (item.type === "chunk" && item.facadeModuleId?.startsWith(`\0${BUNDLE}`)) bundleChunks.add(item.fileName);
1567
2915
  if (!options.report && !options.budget) return;
1568
2916
  const chunks = [];
1569
- for (const item of Object.values(bundle)) if (item.type === "chunk") chunks.push({
1570
- fileName: item.fileName,
1571
- code: item.code,
1572
- isEntry: item.isEntry,
1573
- imports: item.imports,
1574
- moduleIds: item.moduleIds,
1575
- modules: Object.fromEntries(Object.entries(item.modules).map(([id, module]) => [id, module.renderedLength]))
1576
- });
1577
- const list = [...files.values()];
1578
- const contents = await Promise.all(list.map((file) => readFile(file, "utf8")));
1579
- const events = [];
1580
- for (const [file, { source, result }] of compiled) for (const [site, symbol] of result.plan.symbols) {
1581
- const loads = result.loaders[symbol];
1582
- if (loads) {
1583
- const { line, column } = getLocation(source, site.range.start);
1584
- events.push({
1585
- file,
1586
- label: `${site.label} (${line}:${column})`,
1587
- parts: loads
1588
- });
1589
- }
2917
+ for (const item of Object.values(bundle)) if (item.type === "chunk") {
2918
+ const modules = {};
2919
+ for (const [id, module] of Object.entries(item.modules)) modules[id] = module.renderedLength;
2920
+ chunks.push({
2921
+ fileName: item.fileName,
2922
+ code: item.code,
2923
+ isEntry: item.isEntry,
2924
+ imports: item.imports,
2925
+ moduleIds: item.moduleIds,
2926
+ modules
2927
+ });
1590
2928
  }
2929
+ const list = [...files.values()];
2930
+ const contents = await inBatches(list, (file) => readFile(file, "utf8"));
2931
+ const sources = /* @__PURE__ */ new Map();
2932
+ for (const [index, file] of list.entries()) sources.set(file, contents[index]);
1591
2933
  const measured = buildReport({
1592
2934
  chunks,
1593
- sources: new Map(list.map((file, index) => [file, contents[index]])),
2935
+ sources,
1594
2936
  routes: existsSync(routesDirectory()) ? {
1595
2937
  tree: currentRoutes(),
1596
2938
  resolve: (file) => `${routesDirectory()}/${file}`
1597
2939
  } : void 0,
1598
- events,
1599
2940
  budget: options.budget,
1600
- relative: nameOf
2941
+ relative: getFileName
1601
2942
  });
1602
- if (options.report) this.info(`\n${formatBuildReport(measured, nameOf)}`);
2943
+ if (options.report) this.info(`\n${formatBuildReport(measured, getFileName)}`);
1603
2944
  if (measured.overBudget.length > 0) this.error(measured.overBudget.join("\n"));
1604
2945
  },
1605
2946
  async writeBundle(_output, bundle) {
1606
2947
  if (!isSsrBuild) {
1607
- const chunks = new Map(Object.values(bundle).flatMap((item) => item.type === "chunk" ? [[item.fileName, item]] : []));
2948
+ const chunks = /* @__PURE__ */ new Map();
2949
+ for (const item of Object.values(bundle)) if (item.type === "chunk") chunks.set(item.fileName, item);
1608
2950
  const hints = /* @__PURE__ */ new Set();
1609
- const add = (name) => {
2951
+ function add(name) {
1610
2952
  const chunk = name === void 0 ? void 0 : chunks.get(name);
1611
2953
  if (chunk && !hints.has(chunk.fileName)) {
1612
2954
  hints.add(chunk.fileName);
1613
- chunk.imports.forEach(add);
2955
+ for (const imported of chunk.imports) add(imported);
1614
2956
  }
1615
- };
2957
+ }
1616
2958
  add(loaderChunk);
1617
2959
  add(coreChunk);
2960
+ const bundleHints = {};
2961
+ for (const chunk of chunks.values()) {
2962
+ const facade = chunk.facadeModuleId ?? "";
2963
+ if (!facade.startsWith(`\0${BUNDLE}`)) continue;
2964
+ const files = /* @__PURE__ */ new Set();
2965
+ function walk(name) {
2966
+ const found = chunks.get(name);
2967
+ if (found && !files.has(name) && !hints.has(name)) {
2968
+ files.add(name);
2969
+ for (const imported of found.imports) walk(imported);
2970
+ }
2971
+ }
2972
+ walk(chunk.fileName);
2973
+ const urls = [];
2974
+ for (const name of files) urls.push(`${base}${name}`);
2975
+ bundleHints[facade.slice(24)] = urls;
2976
+ }
1618
2977
  await mkdir(path.join(outDir, ".brumate"), { recursive: true });
1619
- await writeFile(path.join(outDir, HINTS_FILE), JSON.stringify([...hints].map((name) => `${base}${name}`)));
2978
+ const all = [];
2979
+ for (const name of hints) all.push(`${base}${name}`);
2980
+ await writeFile(path.join(outDir, HINTS_FILE), JSON.stringify({
2981
+ all,
2982
+ bundles: bundleHints
2983
+ }));
1620
2984
  if (buildId !== void 0) {
1621
- const written = Object.values(bundle).map((item) => item.fileName);
2985
+ const written = [];
2986
+ for (const item of Object.values(bundle)) written.push(item.fileName);
1622
2987
  const removed = pruneBuilds(outDir, buildId, written, options.skew?.keep ?? 0);
1623
2988
  if (removed.length > 0) this.info(`Removed the files of ${removed.length} older builds`);
1624
2989
  }
1625
2990
  return;
1626
2991
  }
1627
2992
  if (!options.prerender || !isSsrBuild) return;
1628
- const chunk = Object.values(bundle).find((item) => item.type === "chunk" && item.isEntry && item.name === PRERENDER_ENTRY);
2993
+ let chunk;
2994
+ for (const item of Object.values(bundle)) if (item.type === "chunk" && item.isEntry && item.name === PRERENDER_ENTRY) {
2995
+ chunk = item;
2996
+ break;
2997
+ }
1629
2998
  if (!chunk) return;
1630
2999
  const settings = options.prerender === true ? {} : options.prerender;
1631
3000
  const written = await prerender(path.join(outDir, chunk.fileName), root, base, settings);
@@ -1641,10 +3010,13 @@ function brumate(options = {}) {
1641
3010
  }
1642
3011
  coreModule = isServe ? void 0 : (await this.resolve("brumate/client", path.join(root, "index.html")))?.id;
1643
3012
  await scan();
3013
+ builtFeatures = void 0;
3014
+ knownFeatures = void 0;
3015
+ loadedComponents.clear();
1644
3016
  writeRouteTypes();
1645
3017
  },
1646
3018
  async resolveId(id, importer, resolveOptions) {
1647
- if (id === START || id === MANIFEST || id === SERVER || id === ROUTES || id === TESTING) return `\0${id}`;
3019
+ if (id === START || id === MANIFEST || id === SERVER || id === ROUTES || id === TESTING || id.startsWith(BUNDLE)) return `\0${id}`;
1648
3020
  const env = resolveOptions?.ssr ? void 0 : envFile();
1649
3021
  const from = importer?.split("?")[0];
1650
3022
  if (env && importer && from && from !== env && isScriptFile(from) && !importer.startsWith("\0") && !importer.includes(SERVER_QUERY) && !importer.includes("/node_modules/")) {
@@ -1660,7 +3032,7 @@ function brumate(options = {}) {
1660
3032
  ...resolveOptions,
1661
3033
  skipSelf: true
1662
3034
  });
1663
- if (!resolved || resolved.external || resolved.id.includes("?") || resolved.id.includes("/node_modules/") && !packageOf(packages, resolved.id)) return resolved;
3035
+ if (!resolved || resolved.external || resolved.id.includes("?") || resolved.id.includes("/node_modules/") && !findPackage(packages, resolved.id)) return resolved;
1664
3036
  const file = resolved.id;
1665
3037
  return isScriptFile(file) && existsSync(file) && hasUseServer(readFileSync(file, "utf8")) ? {
1666
3038
  ...resolved,
@@ -1668,6 +3040,7 @@ function brumate(options = {}) {
1668
3040
  } : resolved;
1669
3041
  },
1670
3042
  async load(id, loadOptions) {
3043
+ if (id === PRELOAD_HELPER && !isServe) return preloadHelper(base, relativeUrls);
1671
3044
  if (id.endsWith("?brumate-shared")) {
1672
3045
  const module = id.slice(0, -SHARED_QUERY.length);
1673
3046
  this.addWatchFile(module);
@@ -1685,15 +3058,16 @@ function brumate(options = {}) {
1685
3058
  }
1686
3059
  if (id === `\0${START}`) return [
1687
3060
  options.navigate === false ? "import { startWithoutNavigation as start } from 'brumate/static-loader';" : "import { start } from 'brumate/loader';",
1688
- `import { load } from ${JSON.stringify(MANIFEST)};`,
3061
+ `import { load${isServe ? "" : ", loadBundle"} } from ${JSON.stringify(MANIFEST)};`,
1689
3062
  ...isServe ? ["import { hotLoad } from 'brumate/hot';"] : [],
1690
- `start({ load${isServe ? ": hotLoad(import.meta.hot, load)" : ""}${serialFile() ? `, serial: () => import(${JSON.stringify(serialFile())})` : ""}, rpc: ${JSON.stringify(rpc)}, navigate: ${JSON.stringify(options.navigate ?? true)}${options.preload === false ? ", preload: false" : ""}${buildId === void 0 ? "" : `, build: ${JSON.stringify(buildId)}`} });`,
3063
+ `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)}`} });`,
1691
3064
  ...isServe && options.devtools !== false ? [`import('brumate/devtools').then((m) => m.installDevtools(${JSON.stringify(INSPECT)}, ${JSON.stringify(rpc)}, ${JSON.stringify({
1692
3065
  version: BRUMATE_VERSION,
1693
3066
  vite: version
1694
3067
  })}, import.meta.hot));`] : []
1695
3068
  ].join("\n");
1696
3069
  if (id === `\0${MANIFEST}`) return await manifest();
3070
+ if (id.startsWith(`\0${BUNDLE}`)) return await bundleModule(id.slice(24));
1697
3071
  if (id === `\0${SERVER}`) return serverRegistry(!loadOptions?.ssr);
1698
3072
  if (id === `\0${ROUTES}`) return routeTree(!loadOptions?.ssr);
1699
3073
  if (id === `\0${TESTING}`) {
@@ -1738,6 +3112,7 @@ function brumate(options = {}) {
1738
3112
  });
1739
3113
  }
1740
3114
  const { source, result } = output;
3115
+ if (!isServe && !isSsrBuild && isClient) loadedComponents.add(file);
1741
3116
  for (const dependency of [...result.plan.styles.dependencies, ...result.modules]) {
1742
3117
  const normalized = normalizePath(dependency);
1743
3118
  this.addWatchFile(normalized);
@@ -1746,7 +3121,7 @@ function brumate(options = {}) {
1746
3121
  }
1747
3122
  for (const warning of isClient && !params.has("part") ? result.warnings : []) {
1748
3123
  const { line, column } = getLocation(source, warning.range.start);
1749
- this.warn(`${warning.message} (${nameOf(file)}:${line}:${column})`);
3124
+ this.warn(`${warning.message} (${getFileName(file)}:${line}:${column})`);
1750
3125
  }
1751
3126
  const part = params.get("part");
1752
3127
  let code;
@@ -1764,15 +3139,21 @@ function brumate(options = {}) {
1764
3139
  code = isClient ? result.client : result.server;
1765
3140
  map = isClient ? result.maps.client : result.maps.server;
1766
3141
  }
3142
+ const sources = [];
3143
+ if (map) for (const [index, name] of map.sources.entries()) sources.push(index === 0 ? file : name);
1767
3144
  return {
1768
3145
  code,
1769
3146
  map: map && {
1770
3147
  ...map,
1771
- sources: map.sources.map((name, index) => index === 0 ? file : name)
3148
+ sources
1772
3149
  }
1773
3150
  };
1774
3151
  },
1775
3152
  async transform(code, id, transformOptions) {
3153
+ if (!isServe && !isSsrBuild && !transformOptions?.ssr && readsFeatures(code)) return {
3154
+ code: writeFeatures(code, options.features === "all" ? allFeatures() : await buildFeatures()),
3155
+ map: null
3156
+ };
1776
3157
  const [file] = id.split("?");
1777
3158
  if (file && !transformOptions?.ssr && file === envFile()) try {
1778
3159
  return {
@@ -1820,14 +3201,17 @@ function brumate(options = {}) {
1820
3201
  };
1821
3202
  },
1822
3203
  configureServer(server) {
1823
- const linked = packages.filter((item) => item.linked).flatMap((item) => item.directories);
3204
+ const linked = [];
3205
+ for (const item of packages) if (item.linked) linked.push(...item.directories);
1824
3206
  if (linked.length > 0) server.watcher.add(linked);
1825
- const manifests = [path.join(root, "package.json"), ...packages.map((item) => `${item.root}/package.json`)].map((file) => normalizePath(file));
3207
+ const manifests = [normalizePath(path.join(root, "package.json"))];
3208
+ for (const item of packages) manifests.push(normalizePath(`${item.root}/package.json`));
1826
3209
  server.watcher.add(manifests);
1827
3210
  server.watcher.on("change", (file) => {
1828
3211
  if (manifests.includes(normalizePath(file)) && packagesKey(findPackages(root)) !== packagesKey(packages)) server.restart();
1829
3212
  });
1830
3213
  server.watcher.on("all", (event, file) => {
3214
+ workbenchList = void 0;
1831
3215
  if (normalizePath(file) === envFile()) compiled.clear();
1832
3216
  for (const importer of dependents.get(normalizePath(file)) ?? []) {
1833
3217
  compiled.delete(importer);
@@ -1839,8 +3223,10 @@ function brumate(options = {}) {
1839
3223
  }
1840
3224
  if (isScriptFile(file)) {
1841
3225
  const normalized = normalizePath(file);
1842
- if (packages.length > 0 && !packageOf(packages, normalized)) {
1843
- appScripts = appScripts.filter((item) => item !== normalized);
3226
+ if (packages.length > 0 && !findPackage(packages, normalized)) {
3227
+ const rest = [];
3228
+ for (const item of appScripts) if (item !== normalized) rest.push(item);
3229
+ appScripts = rest;
1844
3230
  if (event !== "unlink") appScripts.push(normalized);
1845
3231
  }
1846
3232
  const id = serverFileId(normalized);
@@ -1892,6 +3278,10 @@ function brumate(options = {}) {
1892
3278
  }).catch(next);
1893
3279
  return;
1894
3280
  }
3281
+ if (request.method === "GET" && request.url?.startsWith(WORKBENCH)) {
3282
+ serveWorkbench(server, request, response).catch(next);
3283
+ return;
3284
+ }
1895
3285
  if (request.method === "GET" && request.url?.startsWith(`${INSPECT}/`)) {
1896
3286
  inspectComponent(decodeURIComponent(request.url.slice(19))).then((info) => {
1897
3287
  response.statusCode = info ? 200 : 404;
@@ -1921,6 +3311,18 @@ function brumate(options = {}) {
1921
3311
  }
1922
3312
  };
1923
3313
  }
3314
+ /** The names that compiled client code exports, such as `h4`, `u5` and `g`. */
3315
+ function exportNames(codes) {
3316
+ const names = /* @__PURE__ */ new Set();
3317
+ for (const code of codes) for (const match of code.matchAll(/^export (?:async )?(?:function\*? |const |let |var )([\w$]+)|^export \{([^}]*)\}/gm)) {
3318
+ if (match[1]) names.add(match[1]);
3319
+ for (const item of match[2]?.split(",") ?? []) {
3320
+ const name = item.trim().split(/\s+as\s+/).pop();
3321
+ if (name) names.add(name);
3322
+ }
3323
+ }
3324
+ return [...names];
3325
+ }
1924
3326
  //#endregion
1925
3327
  export { brumate as default, errorPage };
1926
3328