brumate 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/check.d.ts +49 -0
- package/dist/{boot-C25Sa6vq.d.ts → boot-DLlRmD9z.d.ts} +8 -10
- package/dist/cli.js +275 -15
- package/dist/cli.js.map +1 -1
- package/dist/client-BvDsC6Qr.js +3463 -0
- package/dist/client-BvDsC6Qr.js.map +1 -0
- package/dist/{client-D0CqSxoO.d.ts → client-DBwL2wKQ.d.ts} +390 -181
- package/dist/{client-routes-JTbGtukf.js → client-routes-BtGpYCef.js} +60 -30
- package/dist/client-routes-BtGpYCef.js.map +1 -0
- package/dist/{cookies-BzllthiF.js → cookies-Cnbf4w-S.js} +14 -7
- package/dist/cookies-Cnbf4w-S.js.map +1 -0
- package/dist/{defer-BbD7JQhj.js → defer-CKWZLv2K.js} +4 -4
- package/dist/defer-CKWZLv2K.js.map +1 -0
- package/dist/{devtools-CQgD7NPB.js → devtools-4uTPwR_v.js} +56 -82
- package/dist/devtools-4uTPwR_v.js.map +1 -0
- package/dist/{devtools-panel-BVB-W5q4.js → devtools-panel-Be9pxYgv.js} +397 -333
- package/dist/devtools-panel-Be9pxYgv.js.map +1 -0
- package/dist/{events-CSs7OwIC.js → events-LgLdp1R7.js} +34 -5
- package/dist/events-LgLdp1R7.js.map +1 -0
- package/dist/features-CHY5Ekku.js +30 -0
- package/dist/features-CHY5Ekku.js.map +1 -0
- package/dist/files-WW4RlajL.js +506 -0
- package/dist/files-WW4RlajL.js.map +1 -0
- package/dist/{forms-Cl21hkHt.d.ts → forms-j1xPAR14.d.ts} +3 -3
- package/dist/{forms-Bg-CwGqX.js → forms-nXK7-Lv_.js} +78 -44
- package/dist/forms-nXK7-Lv_.js.map +1 -0
- package/dist/highlight.js +31 -22
- package/dist/highlight.js.map +1 -1
- package/dist/{html-mNTKzaDD.js → html-BtKRyi7g.js} +86 -22
- package/dist/html-BtKRyi7g.js.map +1 -0
- package/dist/{html-Bq1rFxX_.d.ts → html-Bw9Qwu6F.d.ts} +20 -5
- package/dist/index.d.ts +96 -10
- package/dist/index.js +639 -104
- package/dist/index.js.map +1 -1
- package/dist/{inspect-BHpOw1LF.js → inspect-Y6y4uNZp.js} +3751 -676
- package/dist/inspect-Y6y4uNZp.js.map +1 -0
- package/dist/{loader-Dos_3NP0.js → loader-BjKGJzLN.js} +20 -14
- package/dist/loader-BjKGJzLN.js.map +1 -0
- package/dist/logo-DQ_OYhBi.js +10 -0
- package/dist/logo-DQ_OYhBi.js.map +1 -0
- package/dist/{navigate-O78d_zGN.js → navigate-CfOr-TRF.js} +94 -31
- package/dist/navigate-CfOr-TRF.js.map +1 -0
- package/dist/nesting-DA5vJw9X.js +265 -0
- package/dist/nesting-DA5vJw9X.js.map +1 -0
- package/dist/{produce-Doc91GkX.js → produce-B7X9ori9.js} +137 -9
- package/dist/produce-B7X9ori9.js.map +1 -0
- package/dist/{produce-D0V0ICkz.d.ts → produce-DIgHBVwL.d.ts} +39 -5
- package/dist/{rpc-ygMRPmN4.js → rpc-Q-XkLwFh.js} +11 -6
- package/dist/rpc-Q-XkLwFh.js.map +1 -0
- package/dist/runtime/batch.js +9 -7
- package/dist/runtime/batch.js.map +1 -1
- package/dist/runtime/client.d.ts +4 -4
- package/dist/runtime/client.js +4 -4
- package/dist/runtime/devtools.d.ts +11 -29
- package/dist/runtime/devtools.js +3 -1
- package/dist/runtime/env.js +14 -2
- package/dist/runtime/env.js.map +1 -1
- package/dist/runtime/events.d.ts +23 -1
- package/dist/runtime/events.js +1 -1
- package/dist/runtime/forms.d.ts +2 -2
- package/dist/runtime/forms.js +1 -1
- package/dist/runtime/hot.d.ts +1 -1
- package/dist/runtime/hot.js +5 -2
- package/dist/runtime/hot.js.map +1 -1
- package/dist/runtime/html.d.ts +2 -2
- package/dist/runtime/html.js +1 -1
- package/dist/runtime/loader.d.ts +2 -2
- package/dist/runtime/loader.js +2 -2
- package/dist/runtime/routes.js +4 -1
- package/dist/runtime/routes.js.map +1 -1
- package/dist/runtime/server.d.ts +5 -5
- package/dist/runtime/server.js +5 -5
- package/dist/runtime/signals.d.ts +38 -1
- package/dist/runtime/signals.js +33 -1
- package/dist/runtime/signals.js.map +1 -1
- package/dist/runtime/static-loader.d.ts +2 -2
- package/dist/runtime/static-loader.js +1 -1
- package/dist/runtime/testing.d.ts +18 -3
- package/dist/runtime/testing.js +150 -33
- package/dist/runtime/testing.js.map +1 -1
- package/dist/{server-DuFYRXrd.d.ts → server-BvPIg9pT.d.ts} +84 -22
- package/dist/{server-CxVDYE_V.js → server-DjyOVJtJ.js} +598 -164
- package/dist/server-DjyOVJtJ.js.map +1 -0
- package/dist/{static-loader-Drpr0AzI.d.ts → static-loader-BGgdp_Y5.d.ts} +2 -2
- package/dist/{static-loader-nZssh66R.js → static-loader-BZR17hSw.js} +78 -99
- package/dist/static-loader-BZR17hSw.js.map +1 -0
- package/dist/{stream-DCYZO4IF.js → stream-BP5AVmg5.js} +102 -16
- package/dist/stream-BP5AVmg5.js.map +1 -0
- package/dist/vite.d.ts +13 -20
- package/dist/vite.js +1890 -548
- package/dist/vite.js.map +1 -1
- package/elements.d.ts +951 -0
- package/forms/forms.brm.ts +3 -3
- package/package.json +12 -3
- package/skills/brumate/SKILL.md +58 -0
- package/skills/brumate/references/errors.md +2078 -0
- package/skills/brumate/references/events.md +117 -0
- package/skills/brumate/references/signals.md +61 -0
- package/skills/brumate/references/state.md +235 -0
- package/skills/brumate/references/syntax.md +250 -0
- package/types.d.ts +4 -4
- package/dist/client-BD6XT-s5.js +0 -1968
- package/dist/client-BD6XT-s5.js.map +0 -1
- package/dist/client-routes-JTbGtukf.js.map +0 -1
- package/dist/cookies-BzllthiF.js.map +0 -1
- package/dist/defer-BbD7JQhj.js.map +0 -1
- package/dist/devtools-CQgD7NPB.js.map +0 -1
- package/dist/devtools-panel-BVB-W5q4.js.map +0 -1
- package/dist/events-CSs7OwIC.js.map +0 -1
- package/dist/files-BXSSrQgc.js +0 -205
- package/dist/files-BXSSrQgc.js.map +0 -1
- package/dist/forms-Bg-CwGqX.js.map +0 -1
- package/dist/html-mNTKzaDD.js.map +0 -1
- package/dist/inspect-BHpOw1LF.js.map +0 -1
- package/dist/loader-Dos_3NP0.js.map +0 -1
- package/dist/navigate-O78d_zGN.js.map +0 -1
- package/dist/produce-Doc91GkX.js.map +0 -1
- package/dist/rpc-ygMRPmN4.js.map +0 -1
- package/dist/server-CxVDYE_V.js.map +0 -1
- package/dist/static-loader-nZssh66R.js.map +0 -1
- 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
|
|
2
|
-
import { s as toNodeHeaders } from "./cookies-
|
|
3
|
-
import {
|
|
1
|
+
import { A as analyzeProject, B as getLocation, C as isReactiveModule, E as originalPosition, F as resolveRelative, J as walk, L as parse, M as forEachNode, N as importSource, O as entryClasses, P as importedComponents, T as builtin, U as analyze, _ as functionId, a as scopeLabel, b as SHARED_QUERY, f as instanceScope, i as report, k as refreshedNames, n as formatReport, p as slotIndex, q as resolveMacros, s as compile, t as anchorLabel, v as getComponentName, w as resolveFromDisk, x as generateShared, y as hash } from "./inspect-Y6y4uNZp.js";
|
|
2
|
+
import { s as toNodeHeaders } from "./cookies-Cnbf4w-S.js";
|
|
3
|
+
import { t as LOGO } from "./logo-DQ_OYhBi.js";
|
|
4
|
+
import { _ as reachableFiles, a as findServerFiles, c as hasServerMiddleware, d as serverExports, f as serverModule, g as packageFileName, h as findPackages, i as findScripts, l as hasUseServer, m as findPackage, n as defaultExclude, o as findPackageServerFile, p as serverStubs, r as findFiles, u as isScriptFile, v as resolveComponentPackage } from "./files-WW4RlajL.js";
|
|
4
5
|
import { parseSync } from "oxc-parser";
|
|
5
6
|
import { createHash } from "node:crypto";
|
|
6
|
-
import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync,
|
|
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
|
|
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
|
-
|
|
18
|
-
|
|
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
|
-
|
|
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
|
|
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.
|
|
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] =
|
|
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
|
-
|
|
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(
|
|
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
|
-
|
|
156
|
-
|
|
157
|
-
|
|
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<T>()</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
|
|
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
|
-
|
|
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,
|
|
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:
|
|
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: [...
|
|
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,
|
|
592
|
-
const chunks = new Map(
|
|
593
|
-
const sizes =
|
|
594
|
-
const
|
|
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
|
-
|
|
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
|
|
1466
|
+
const shares = /* @__PURE__ */ new Map();
|
|
606
1467
|
const everyPage = /* @__PURE__ */ new Set([...loaderChunks, ...coreChunks]);
|
|
607
|
-
for (const chunk of list)
|
|
608
|
-
const
|
|
609
|
-
|
|
610
|
-
const
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
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 = [
|
|
1490
|
+
const components = [];
|
|
1491
|
+
for (const [file, bytes] of shares) components.push({
|
|
618
1492
|
file,
|
|
619
|
-
bytes:
|
|
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
|
-
|
|
641
|
-
|
|
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
|
-
|
|
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
|
|
1503
|
+
}
|
|
1504
|
+
for (const file of files) visit(file);
|
|
654
1505
|
return seen;
|
|
655
|
-
}
|
|
656
|
-
const routeSizes =
|
|
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
|
-
|
|
1512
|
+
routeSizes.push({
|
|
661
1513
|
path,
|
|
662
1514
|
bytes: sum(names),
|
|
663
1515
|
components: reached.size
|
|
664
|
-
};
|
|
665
|
-
}
|
|
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
|
-
`
|
|
711
|
-
` The 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("
|
|
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
|
-
|
|
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
|
-
|
|
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 =
|
|
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
|
-
|
|
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
|
-
...
|
|
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. */
|
|
@@ -893,13 +1738,17 @@ const INSPECT = "/__brumate/inspect";
|
|
|
893
1738
|
const POSITION = "/__brumate/position";
|
|
894
1739
|
/** The dev server sends the source of a file for the Errors tab of the devtools at this path. */
|
|
895
1740
|
const SOURCE = "/__brumate/source";
|
|
1741
|
+
/** The workbench of the dev server, which shows the components that depend only on their props. */
|
|
1742
|
+
const WORKBENCH = "/__brumate/workbench";
|
|
896
1743
|
/** What tells two lists of packages of components apart. */
|
|
897
1744
|
function packagesKey(list) {
|
|
898
|
-
|
|
1745
|
+
const rows = [];
|
|
1746
|
+
for (const item of list) rows.push([
|
|
899
1747
|
item.prefix,
|
|
900
1748
|
item.root,
|
|
901
1749
|
item.directories
|
|
902
|
-
])
|
|
1750
|
+
]);
|
|
1751
|
+
return JSON.stringify(rows);
|
|
903
1752
|
}
|
|
904
1753
|
/** Skips the `node_modules` and hidden directories of a package of components. */
|
|
905
1754
|
function packageExclude(directory) {
|
|
@@ -912,7 +1761,7 @@ async function readBody(request) {
|
|
|
912
1761
|
return Buffer.concat(chunks);
|
|
913
1762
|
}
|
|
914
1763
|
/** Removes the scripts, styles and event handlers of a file, which leaves the markup of its page. */
|
|
915
|
-
function
|
|
1764
|
+
function getMarkup(result) {
|
|
916
1765
|
const { file } = result;
|
|
917
1766
|
const ranges = [
|
|
918
1767
|
...file.instanceScript ? [file.instanceScript] : [],
|
|
@@ -933,21 +1782,39 @@ function markupOf(result) {
|
|
|
933
1782
|
}
|
|
934
1783
|
return markup + file.source.slice(position);
|
|
935
1784
|
}
|
|
936
|
-
function
|
|
937
|
-
const
|
|
938
|
-
const
|
|
1785
|
+
function getShape(result) {
|
|
1786
|
+
const labels = [];
|
|
1787
|
+
const slots = {};
|
|
1788
|
+
const signals = [];
|
|
1789
|
+
for (const layout of result.plan.scopes.values()) {
|
|
1790
|
+
const names = [];
|
|
1791
|
+
for (const slot of layout.slots) {
|
|
1792
|
+
names.push(slot.name);
|
|
1793
|
+
if (slot.kind === "signal") signals.push(slot.name);
|
|
1794
|
+
}
|
|
1795
|
+
labels.push(`${layout.scope.id}:${names.join(",")}`);
|
|
1796
|
+
slots[layout.scope.id] = names;
|
|
1797
|
+
}
|
|
939
1798
|
return {
|
|
940
1799
|
layout: JSON.stringify([
|
|
941
1800
|
result.table,
|
|
942
|
-
|
|
943
|
-
|
|
1801
|
+
labels,
|
|
1802
|
+
getMarkup(result)
|
|
944
1803
|
]),
|
|
945
1804
|
css: result.css,
|
|
946
1805
|
code: JSON.stringify([result.client, result.parts]),
|
|
947
|
-
slots
|
|
948
|
-
signals
|
|
1806
|
+
slots,
|
|
1807
|
+
signals
|
|
949
1808
|
};
|
|
950
1809
|
}
|
|
1810
|
+
/**
|
|
1811
|
+
* The cache key of a module for Vitest: the hash of this build of brumate. A component is never
|
|
1812
|
+
* cached, because its code depends on other files, such as the `.brm.ts` modules that it calls
|
|
1813
|
+
* and the props that other components pass it. A key of its own source would go stale.
|
|
1814
|
+
*/
|
|
1815
|
+
function cacheKey({ id }) {
|
|
1816
|
+
return id.split("?")[0].endsWith(".brm") ? false : buildFingerprint();
|
|
1817
|
+
}
|
|
951
1818
|
let fingerprint;
|
|
952
1819
|
/**
|
|
953
1820
|
* A hash of the code of this build of brumate. A new build can compile the
|
|
@@ -956,13 +1823,13 @@ let fingerprint;
|
|
|
956
1823
|
function buildFingerprint() {
|
|
957
1824
|
if (fingerprint === void 0) {
|
|
958
1825
|
const digest = createHash("sha1");
|
|
959
|
-
|
|
1826
|
+
function visit(directory) {
|
|
960
1827
|
for (const entry of readdirSync(directory, { withFileTypes: true }).toSorted((a, b) => a.name < b.name ? -1 : 1)) {
|
|
961
1828
|
const file = path.join(directory, entry.name);
|
|
962
1829
|
if (entry.isDirectory()) visit(file);
|
|
963
1830
|
else if (/\.[jt]s$/.test(entry.name) && !entry.name.endsWith(".d.ts")) digest.update(entry.name).update(readFileSync(file));
|
|
964
1831
|
}
|
|
965
|
-
}
|
|
1832
|
+
}
|
|
966
1833
|
visit(path.dirname(fileURLToPath(import.meta.url)));
|
|
967
1834
|
fingerprint = digest.digest("hex").slice(0, 16);
|
|
968
1835
|
}
|
|
@@ -972,7 +1839,7 @@ function buildFingerprint() {
|
|
|
972
1839
|
function brumate(options = {}) {
|
|
973
1840
|
const rpc = options.rpc ?? "/_brumate";
|
|
974
1841
|
/** The entry middleware, when the app has one. */
|
|
975
|
-
|
|
1842
|
+
function middlewareFile() {
|
|
976
1843
|
if (options.middleware === false) return;
|
|
977
1844
|
const file = normalizePath(path.resolve(root, options.middleware ?? "src/middleware.ts"));
|
|
978
1845
|
if (!existsSync(file)) {
|
|
@@ -980,9 +1847,9 @@ function brumate(options = {}) {
|
|
|
980
1847
|
return;
|
|
981
1848
|
}
|
|
982
1849
|
return file;
|
|
983
|
-
}
|
|
1850
|
+
}
|
|
984
1851
|
/** The serial entry, when the app has one. */
|
|
985
|
-
|
|
1852
|
+
function serialFile() {
|
|
986
1853
|
if (options.serial === false) return;
|
|
987
1854
|
const file = normalizePath(path.resolve(root, options.serial ?? "src/serial.ts"));
|
|
988
1855
|
if (!existsSync(file)) {
|
|
@@ -990,10 +1857,10 @@ function brumate(options = {}) {
|
|
|
990
1857
|
return;
|
|
991
1858
|
}
|
|
992
1859
|
return file;
|
|
993
|
-
}
|
|
1860
|
+
}
|
|
994
1861
|
/** The classes that the plugins of the serial entry send, read from its `instanceof` checks. */
|
|
995
1862
|
let serialRead;
|
|
996
|
-
|
|
1863
|
+
function serialClasses() {
|
|
997
1864
|
const file = serialFile();
|
|
998
1865
|
if (!file) return [];
|
|
999
1866
|
const source = readFileSync(file, "utf8");
|
|
@@ -1005,18 +1872,18 @@ function brumate(options = {}) {
|
|
|
1005
1872
|
};
|
|
1006
1873
|
}
|
|
1007
1874
|
return serialRead.classes;
|
|
1008
|
-
}
|
|
1875
|
+
}
|
|
1009
1876
|
/** The lines that give the server the serial entry, before anything is written or read. */
|
|
1010
|
-
|
|
1877
|
+
function serialImports() {
|
|
1011
1878
|
const file = serialFile();
|
|
1012
1879
|
return file ? [
|
|
1013
1880
|
`import * as $$serial from ${JSON.stringify(file)};`,
|
|
1014
1881
|
"import { useSerialEntry } from 'brumate/server';",
|
|
1015
1882
|
"useSerialEntry($$serial);"
|
|
1016
1883
|
] : [];
|
|
1017
|
-
}
|
|
1884
|
+
}
|
|
1018
1885
|
/** The file of environment variables, when the app has one. */
|
|
1019
|
-
|
|
1886
|
+
function envFile() {
|
|
1020
1887
|
if (options.env === false) return;
|
|
1021
1888
|
const file = normalizePath(path.resolve(root, options.env ?? "src/env.ts"));
|
|
1022
1889
|
if (!existsSync(file)) {
|
|
@@ -1024,10 +1891,10 @@ function brumate(options = {}) {
|
|
|
1024
1891
|
return;
|
|
1025
1892
|
}
|
|
1026
1893
|
return file;
|
|
1027
|
-
}
|
|
1894
|
+
}
|
|
1028
1895
|
/** The names of the server variables, read from the env file, by its source. */
|
|
1029
1896
|
let envKeys;
|
|
1030
|
-
|
|
1897
|
+
function serverEnvKeys() {
|
|
1031
1898
|
const file = envFile();
|
|
1032
1899
|
if (!file) return;
|
|
1033
1900
|
const source = readFileSync(file, "utf8");
|
|
@@ -1036,7 +1903,7 @@ function brumate(options = {}) {
|
|
|
1036
1903
|
server: parseEnvFile(source, file).server
|
|
1037
1904
|
};
|
|
1038
1905
|
return envKeys.server;
|
|
1039
|
-
}
|
|
1906
|
+
}
|
|
1040
1907
|
const exclude = options.exclude ?? defaultExclude;
|
|
1041
1908
|
let root = process.cwd();
|
|
1042
1909
|
let outDir = "";
|
|
@@ -1050,7 +1917,7 @@ function brumate(options = {}) {
|
|
|
1050
1917
|
const compiled = /* @__PURE__ */ new Map();
|
|
1051
1918
|
/** Files that a component depends on, such as SCSS that it imports or modules that it calls into, with the components. */
|
|
1052
1919
|
const dependents = /* @__PURE__ */ new Map();
|
|
1053
|
-
/** What the browser has of each component, from its last compile. See `
|
|
1920
|
+
/** What the browser has of each component, from its last compile. See `getShape`. */
|
|
1054
1921
|
const shapes = /* @__PURE__ */ new Map();
|
|
1055
1922
|
/** The props that parents can change, by absolute file path. */
|
|
1056
1923
|
let liveProps = /* @__PURE__ */ new Map();
|
|
@@ -1058,113 +1925,172 @@ function brumate(options = {}) {
|
|
|
1058
1925
|
let refreshed;
|
|
1059
1926
|
/** The dependencies of the app that ship `.brm` files. See `packages.ts`. */
|
|
1060
1927
|
let packages = [];
|
|
1061
|
-
|
|
1928
|
+
function relative(file) {
|
|
1929
|
+
return normalizePath(path.relative(root, file));
|
|
1930
|
+
}
|
|
1062
1931
|
/**
|
|
1063
1932
|
* The name of a file, which its IDs come from: its path relative to the root,
|
|
1064
1933
|
* or for a file of a package, the name of the package and its path in it.
|
|
1065
1934
|
*/
|
|
1066
|
-
|
|
1935
|
+
function getFileName(file) {
|
|
1067
1936
|
let normalized = normalizePath(file);
|
|
1068
|
-
let owner =
|
|
1937
|
+
let owner = findPackage(packages, normalized);
|
|
1069
1938
|
if (!owner && normalized.includes("/node_modules/") && existsSync(normalized)) {
|
|
1070
1939
|
normalized = normalizePath(realpathSync(normalized));
|
|
1071
|
-
owner =
|
|
1940
|
+
owner = findPackage(packages, normalized);
|
|
1072
1941
|
}
|
|
1073
1942
|
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
|
-
};
|
|
1943
|
+
}
|
|
1080
1944
|
/** Files of server functions: scripts whose first statement is `'use server'`, by ID. */
|
|
1081
1945
|
const serverFiles = /* @__PURE__ */ new Map();
|
|
1082
1946
|
/** The scripts of the app, when it uses packages of components. */
|
|
1083
1947
|
let appScripts = [];
|
|
1084
1948
|
/** The ID of a function that a component imports from a 'use server' file, by a relative path. */
|
|
1085
|
-
|
|
1949
|
+
function serverImport(importer, specifier, name) {
|
|
1086
1950
|
if (!specifier.startsWith(".")) {
|
|
1087
|
-
const file =
|
|
1088
|
-
return file
|
|
1951
|
+
const file = findPackageServerFile(packages, importer, specifier);
|
|
1952
|
+
return file ? functionId(serverFileId(file), name, !isServe) : void 0;
|
|
1089
1953
|
}
|
|
1090
1954
|
const stem = path.resolve(path.dirname(importer), specifier);
|
|
1091
|
-
const
|
|
1955
|
+
const candidates = [stem];
|
|
1956
|
+
for (const extension of [
|
|
1092
1957
|
".ts",
|
|
1093
1958
|
".tsx",
|
|
1094
1959
|
".js",
|
|
1095
1960
|
".mjs"
|
|
1096
|
-
].
|
|
1961
|
+
]) candidates.push(stem + extension);
|
|
1962
|
+
let found;
|
|
1963
|
+
for (const candidate of candidates) if (isScriptFile(candidate) && existsSync(candidate) && hasUseServer(readFileSync(candidate, "utf8"))) {
|
|
1964
|
+
found = candidate;
|
|
1965
|
+
break;
|
|
1966
|
+
}
|
|
1097
1967
|
return found && functionId(serverFileId(normalizePath(found)), name, !isServe);
|
|
1098
|
-
}
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1968
|
+
}
|
|
1969
|
+
function serverFileId(file) {
|
|
1970
|
+
return `${path.basename(file).replace(/\.[^.]+$/, "")}_${hash(getFileName(file))}`;
|
|
1971
|
+
}
|
|
1972
|
+
function componentId(file) {
|
|
1973
|
+
const filename = getFileName(file);
|
|
1102
1974
|
return `${getComponentName(filename)}_${hash(filename)}`;
|
|
1103
|
-
}
|
|
1104
|
-
|
|
1105
|
-
const directories =
|
|
1106
|
-
const
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1975
|
+
}
|
|
1976
|
+
async function scan() {
|
|
1977
|
+
const directories = [];
|
|
1978
|
+
for (const item of packages) for (const directory of item.directories) if (existsSync(directory)) directories.push(directory);
|
|
1979
|
+
function ownFile(file) {
|
|
1980
|
+
return !findPackage(packages, file);
|
|
1981
|
+
}
|
|
1982
|
+
const searches = [findFiles(root, exclude), findServerFiles(root, exclude)];
|
|
1983
|
+
for (const directory of directories) searches.push(findFiles(directory, packageExclude), findServerFiles(directory, packageExclude));
|
|
1984
|
+
const [own, ownServer, ...found] = await Promise.all(searches);
|
|
1985
|
+
const scripts = [];
|
|
1986
|
+
if (packages.length > 0) {
|
|
1987
|
+
for (const file of await findScripts(root, exclude)) if (ownFile(file)) scripts.push(file);
|
|
1988
|
+
}
|
|
1989
|
+
appScripts = scripts;
|
|
1113
1990
|
files.clear();
|
|
1114
1991
|
serverFiles.clear();
|
|
1115
|
-
for (const file of own
|
|
1116
|
-
for (const file of ownServer
|
|
1992
|
+
for (const file of own) if (ownFile(file)) files.set(componentId(file), file);
|
|
1993
|
+
for (const file of ownServer) if (ownFile(file)) serverFiles.set(serverFileId(file), file);
|
|
1117
1994
|
for (const [index, list] of found.entries()) for (const file of list) if (index % 2 === 0) files.set(componentId(file), file);
|
|
1118
1995
|
else serverFiles.set(serverFileId(file), file);
|
|
1119
|
-
|
|
1120
|
-
|
|
1996
|
+
try {
|
|
1997
|
+
await analyze();
|
|
1998
|
+
} finally {
|
|
1999
|
+
workbenchList = void 0;
|
|
2000
|
+
}
|
|
2001
|
+
}
|
|
1121
2002
|
/**
|
|
1122
2003
|
* The files of packages that the app reaches through its imports. A server
|
|
1123
2004
|
* function of a package becomes an endpoint of the app only when the app
|
|
1124
2005
|
* reaches its file, so installing a package does not expose all of them.
|
|
1125
2006
|
*/
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
2007
|
+
function reachable() {
|
|
2008
|
+
const roots = [];
|
|
2009
|
+
for (const file of files.values()) if (!findPackage(packages, file)) roots.push(file);
|
|
2010
|
+
return reachableFiles(packages, [...roots, ...appScripts], (file) => {
|
|
2011
|
+
try {
|
|
2012
|
+
return readFileSync(file, "utf8");
|
|
2013
|
+
} catch {
|
|
2014
|
+
return;
|
|
2015
|
+
}
|
|
2016
|
+
});
|
|
2017
|
+
}
|
|
1133
2018
|
/** The files of packages in the last server registry. */
|
|
1134
2019
|
let registered = /* @__PURE__ */ new Set();
|
|
1135
2020
|
/** Resolves a `.brm` file that a component imports: next to it, or from a package of components. */
|
|
1136
|
-
|
|
1137
|
-
|
|
2021
|
+
function resolveComponent(specifier, importer) {
|
|
2022
|
+
return resolveRelative(specifier, importer) ?? (specifier.endsWith(".brm") ? resolveComponentPackage(packages, specifier, importer) : void 0);
|
|
2023
|
+
}
|
|
2024
|
+
async function analyze() {
|
|
1138
2025
|
const list = [...files.values()];
|
|
1139
|
-
const contents = await
|
|
1140
|
-
const sources = new Map(
|
|
2026
|
+
const contents = await inBatches(list, (file) => readFile(file, "utf8"));
|
|
2027
|
+
const sources = /* @__PURE__ */ new Map();
|
|
2028
|
+
for (const [index, file] of list.entries()) sources.set(file, contents[index]);
|
|
1141
2029
|
liveProps = analyzeProject(sources, resolveComponent);
|
|
1142
2030
|
const scripts = await findScripts(root, exclude);
|
|
1143
|
-
const scriptSources = await
|
|
2031
|
+
const scriptSources = await inBatches([.../* @__PURE__ */ new Set([...scripts, ...serverFiles.values()])], (file) => readFile(file, "utf8").catch(() => ""));
|
|
1144
2032
|
refreshed = refreshedNames([...contents, ...scriptSources]);
|
|
1145
2033
|
compiled.clear();
|
|
1146
|
-
}
|
|
2034
|
+
}
|
|
2035
|
+
/** The features of the core that the components of the build use, once for each build. */
|
|
2036
|
+
let builtFeatures;
|
|
2037
|
+
/** The files that `builtFeatures` counted, and the features it found. */
|
|
2038
|
+
let counted = /* @__PURE__ */ new Set();
|
|
2039
|
+
let knownFeatures;
|
|
2040
|
+
/** The components that the client build loaded. */
|
|
2041
|
+
const loadedComponents = /* @__PURE__ */ new Set();
|
|
2042
|
+
function buildFeatures() {
|
|
2043
|
+
return builtFeatures ??= (async () => {
|
|
2044
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2045
|
+
const all = [];
|
|
2046
|
+
async function visit(file) {
|
|
2047
|
+
if (seen.has(file)) return;
|
|
2048
|
+
seen.add(file);
|
|
2049
|
+
const { result } = await compileFile(file);
|
|
2050
|
+
all.push(getFeatures(result));
|
|
2051
|
+
const imported = [];
|
|
2052
|
+
for (const specifier of importedComponents(result.file)) {
|
|
2053
|
+
const target = resolveComponent(specifier, file);
|
|
2054
|
+
if (target !== void 0 && existsSync(target)) imported.push(target);
|
|
2055
|
+
}
|
|
2056
|
+
await inBatches(imported, visit);
|
|
2057
|
+
}
|
|
2058
|
+
await inBatches([...files.values()], visit);
|
|
2059
|
+
const features = joinFeatures(all);
|
|
2060
|
+
let loading = false;
|
|
2061
|
+
for (const file of seen) if (path.basename(file) === "_loading.brm") {
|
|
2062
|
+
loading = true;
|
|
2063
|
+
break;
|
|
2064
|
+
}
|
|
2065
|
+
features.lateMarkup ||= options.navigate !== false || loading;
|
|
2066
|
+
counted = seen;
|
|
2067
|
+
knownFeatures = features;
|
|
2068
|
+
return features;
|
|
2069
|
+
})();
|
|
2070
|
+
}
|
|
1147
2071
|
/** The options of the compile of a file. */
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
2072
|
+
function compileOptions(file) {
|
|
2073
|
+
return {
|
|
2074
|
+
filename: getFileName(file),
|
|
2075
|
+
liveProps: liveProps.get(file),
|
|
2076
|
+
refreshed,
|
|
2077
|
+
path: file,
|
|
2078
|
+
merge: options.merge ?? 4096,
|
|
2079
|
+
a11y: options.a11y,
|
|
2080
|
+
hideNames: !isServe,
|
|
2081
|
+
sendableClasses: serialClasses(),
|
|
2082
|
+
serverImport: (specifier, name) => serverImport(file, specifier, name),
|
|
2083
|
+
resolveModule: (specifier, importer) => {
|
|
2084
|
+
const local = resolveFromDisk(specifier, importer);
|
|
2085
|
+
const found = local === void 0 ? resolveComponentPackage(packages, specifier, importer) : void 0;
|
|
2086
|
+
return found ? {
|
|
2087
|
+
path: found,
|
|
2088
|
+
source: readFileSync(found, "utf8")
|
|
2089
|
+
} : local;
|
|
2090
|
+
}
|
|
2091
|
+
};
|
|
2092
|
+
}
|
|
2093
|
+
async function compileFile(file) {
|
|
1168
2094
|
const source = await readFile(file, "utf8");
|
|
1169
2095
|
let cached = compiled.get(file);
|
|
1170
2096
|
if (cached?.source !== source) {
|
|
@@ -1173,10 +2099,10 @@ function brumate(options = {}) {
|
|
|
1173
2099
|
result: compile(source, compileOptions(file))
|
|
1174
2100
|
};
|
|
1175
2101
|
compiled.set(file, cached);
|
|
1176
|
-
shapes.set(file,
|
|
2102
|
+
shapes.set(file, getShape(cached.result));
|
|
1177
2103
|
}
|
|
1178
2104
|
return cached;
|
|
1179
|
-
}
|
|
2105
|
+
}
|
|
1180
2106
|
/** The compiles whose imports were checked for the env file. */
|
|
1181
2107
|
const envChecked = /* @__PURE__ */ new WeakSet();
|
|
1182
2108
|
/**
|
|
@@ -1184,15 +2110,17 @@ function brumate(options = {}) {
|
|
|
1184
2110
|
* when one of its imports resolves to it, by any specifier, such as an
|
|
1185
2111
|
* alias. The compile fails when code that runs in the browser reads one.
|
|
1186
2112
|
*/
|
|
1187
|
-
|
|
2113
|
+
async function checkEnvReads(file, { source, result }, resolve) {
|
|
1188
2114
|
const env = envFile();
|
|
1189
2115
|
if (!env || envChecked.has(result)) return;
|
|
1190
2116
|
const specifiers = /* @__PURE__ */ new Set();
|
|
1191
2117
|
for (const declaration of result.plan.graph.model.declarations) if (declaration.imported) specifiers.add(declaration.imported.source);
|
|
1192
|
-
const
|
|
2118
|
+
const pending = [];
|
|
2119
|
+
for (const specifier of specifiers) pending.push((async () => {
|
|
1193
2120
|
return (await resolve(specifier, file))?.id.split("?")[0] === env ? specifier : void 0;
|
|
1194
|
-
}));
|
|
1195
|
-
const imports = new Set(
|
|
2121
|
+
})());
|
|
2122
|
+
const imports = /* @__PURE__ */ new Set();
|
|
2123
|
+
for (const specifier of await Promise.all(pending)) if (specifier !== void 0) imports.add(specifier);
|
|
1196
2124
|
if (imports.size > 0) {
|
|
1197
2125
|
const server = serverEnvKeys() ?? [];
|
|
1198
2126
|
compile(source, {
|
|
@@ -1201,13 +2129,141 @@ function brumate(options = {}) {
|
|
|
1201
2129
|
});
|
|
1202
2130
|
}
|
|
1203
2131
|
envChecked.add(result);
|
|
1204
|
-
}
|
|
1205
|
-
|
|
2132
|
+
}
|
|
2133
|
+
/** The components that a component imports, by file. */
|
|
2134
|
+
async function componentImports(file) {
|
|
2135
|
+
const { result } = await compileFile(file);
|
|
2136
|
+
const found = [];
|
|
2137
|
+
for (const declaration of result.plan.graph.model.declarations) {
|
|
2138
|
+
const source = declaration.imported?.source;
|
|
2139
|
+
const target = source?.endsWith(".brm") ? resolveComponent(source, file) : void 0;
|
|
2140
|
+
if (target !== void 0) found.push(target);
|
|
2141
|
+
}
|
|
2142
|
+
return found;
|
|
2143
|
+
}
|
|
2144
|
+
/**
|
|
2145
|
+
* The bundles of a build: for each component that no other component imports, such as a
|
|
2146
|
+
* route or a page, the components with client code that it can render. The page loads the
|
|
2147
|
+
* bundles of its roots at once, as one chunk each, so its code comes in one request.
|
|
2148
|
+
* Components that only import each other get a bundle too.
|
|
2149
|
+
*/
|
|
2150
|
+
async function bundles(kept) {
|
|
2151
|
+
const imports = /* @__PURE__ */ new Map();
|
|
2152
|
+
await inBatches([...files.values()], async (file) => {
|
|
2153
|
+
try {
|
|
2154
|
+
imports.set(file, await componentImports(file));
|
|
2155
|
+
} catch {
|
|
2156
|
+
imports.set(file, []);
|
|
2157
|
+
}
|
|
2158
|
+
});
|
|
2159
|
+
const imported = /* @__PURE__ */ new Set();
|
|
2160
|
+
for (const targets of imports.values()) for (const target of targets) imported.add(target);
|
|
2161
|
+
const result = /* @__PURE__ */ new Map();
|
|
2162
|
+
const reached = /* @__PURE__ */ new Set();
|
|
2163
|
+
function addRoot(id, file) {
|
|
2164
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2165
|
+
function walk(current) {
|
|
2166
|
+
if (seen.has(current)) return;
|
|
2167
|
+
seen.add(current);
|
|
2168
|
+
reached.add(current);
|
|
2169
|
+
for (const next of imports.get(current) ?? []) walk(next);
|
|
2170
|
+
}
|
|
2171
|
+
walk(file);
|
|
2172
|
+
const members = [];
|
|
2173
|
+
for (const member of seen) if (kept.has(member)) members.push(member);
|
|
2174
|
+
if (members.length > 0) result.set(id, members);
|
|
2175
|
+
}
|
|
2176
|
+
for (const [id, file] of files) if (!imported.has(file)) addRoot(id, file);
|
|
2177
|
+
for (const [id, file] of files) if (!reached.has(file) && kept.has(file)) addRoot(id, file);
|
|
2178
|
+
return result;
|
|
2179
|
+
}
|
|
2180
|
+
/** The ID of each component file. */
|
|
2181
|
+
function findComponentId(file) {
|
|
2182
|
+
for (const [id, other] of files) if (other === file) return id;
|
|
2183
|
+
}
|
|
2184
|
+
/** A bundle module: the client modules of a root component and of those it renders. */
|
|
2185
|
+
async function bundleModule(root) {
|
|
1206
2186
|
const list = [...files];
|
|
1207
|
-
const needed = await
|
|
2187
|
+
const needed = await inBatches(list, async ([, file]) => (await compileFile(file)).result.clientCode);
|
|
2188
|
+
const kept = /* @__PURE__ */ new Set();
|
|
2189
|
+
for (const [index, [, file]] of list.entries()) if (needed[index]) kept.add(file);
|
|
2190
|
+
const members = (await bundles(kept)).get(root) ?? [];
|
|
2191
|
+
const imports = [];
|
|
2192
|
+
const objects = [];
|
|
2193
|
+
for (const [index, file] of members.entries()) {
|
|
2194
|
+
const { result } = await compileFile(file);
|
|
2195
|
+
const codes = [result.client];
|
|
2196
|
+
for (const [name, code] of Object.entries(result.parts)) if (name !== "shared") codes.push(code);
|
|
2197
|
+
const names = exportNames(codes);
|
|
2198
|
+
const aliased = [];
|
|
2199
|
+
const fields = [];
|
|
2200
|
+
for (const name of names) {
|
|
2201
|
+
aliased.push(`${name} as $$c${index}_${name}`);
|
|
2202
|
+
fields.push(`${name}: $$c${index}_${name}`);
|
|
2203
|
+
}
|
|
2204
|
+
imports.push(`import { ${aliased.join(", ")} } from ${JSON.stringify(`${file}${CLIENT_QUERY}`)};`);
|
|
2205
|
+
objects.push(` ${JSON.stringify(findComponentId(file))}: { ${fields.join(", ")} },`);
|
|
2206
|
+
}
|
|
2207
|
+
return [
|
|
2208
|
+
...imports,
|
|
2209
|
+
"export const modules = {",
|
|
2210
|
+
...objects,
|
|
2211
|
+
"};"
|
|
2212
|
+
].join("\n");
|
|
2213
|
+
}
|
|
2214
|
+
async function manifest() {
|
|
2215
|
+
const list = [...files];
|
|
2216
|
+
const needed = await inBatches(list, async ([, file]) => isServe || (await compileFile(file)).result.clientCode);
|
|
2217
|
+
const kept = [];
|
|
2218
|
+
for (const [index, entry] of list.entries()) if (needed[index]) kept.push(entry);
|
|
2219
|
+
if (!isServe) {
|
|
2220
|
+
const keptFiles = /* @__PURE__ */ new Set();
|
|
2221
|
+
for (const [, file] of kept) keptFiles.add(file);
|
|
2222
|
+
const groups = await bundles(keptFiles);
|
|
2223
|
+
const owners = /* @__PURE__ */ new Map();
|
|
2224
|
+
for (const [root, members] of groups) for (const member of members) {
|
|
2225
|
+
const id = findComponentId(member);
|
|
2226
|
+
if (id !== void 0 && !owners.has(id)) owners.set(id, root);
|
|
2227
|
+
}
|
|
2228
|
+
const bundleLines = [];
|
|
2229
|
+
for (const root of groups.keys()) bundleLines.push(` ${JSON.stringify(root)}: () => import(${JSON.stringify(`${BUNDLE}${root}`)}),`);
|
|
2230
|
+
return [
|
|
2231
|
+
"const bundles = {",
|
|
2232
|
+
...bundleLines,
|
|
2233
|
+
"};",
|
|
2234
|
+
`const owners = ${JSON.stringify(Object.fromEntries(owners))};`,
|
|
2235
|
+
"const loaded = new Map();",
|
|
2236
|
+
"const pending = new Map();",
|
|
2237
|
+
"/** Loads the bundle of a root component of the page. Undefined for a component that is not a root. */",
|
|
2238
|
+
"export function loadBundle(root) {",
|
|
2239
|
+
" let promise = pending.get(root);",
|
|
2240
|
+
" if (!promise && bundles[root]) {",
|
|
2241
|
+
" promise = bundles[root]().then((bundle) => {",
|
|
2242
|
+
" for (const [id, module] of Object.entries(bundle.modules)) {",
|
|
2243
|
+
" loaded.set(id, module);",
|
|
2244
|
+
" }",
|
|
2245
|
+
" });",
|
|
2246
|
+
" pending.set(root, promise);",
|
|
2247
|
+
" promise.catch(() => pending.delete(root));",
|
|
2248
|
+
" }",
|
|
2249
|
+
" return promise;",
|
|
2250
|
+
"}",
|
|
2251
|
+
"/** The client module of a component, from the bundles of the page, or else from a bundle that holds it. */",
|
|
2252
|
+
"export function load(id) {",
|
|
2253
|
+
" if (loaded.has(id)) {",
|
|
2254
|
+
" return Promise.resolve(loaded.get(id));",
|
|
2255
|
+
" }",
|
|
2256
|
+
" const waiting = [...pending.values()];",
|
|
2257
|
+
" const owner = () => (loaded.has(id) || !owners[id] ? loaded.get(id) : loadBundle(owners[id]).then(() => loaded.get(id)));",
|
|
2258
|
+
" return waiting.length > 0 ? Promise.allSettled(waiting).then(owner) : owners[id] ? owner() : undefined;",
|
|
2259
|
+
"}"
|
|
2260
|
+
].join("\n");
|
|
2261
|
+
}
|
|
2262
|
+
const entries = [];
|
|
2263
|
+
for (const [id, file] of kept) entries.push(` ${JSON.stringify(id)}: () => import(${JSON.stringify(`${file}${CLIENT_QUERY}`)}),`);
|
|
1208
2264
|
return [
|
|
1209
2265
|
"const modules = {",
|
|
1210
|
-
...
|
|
2266
|
+
...entries,
|
|
1211
2267
|
"};",
|
|
1212
2268
|
"export function load(id) {",
|
|
1213
2269
|
...isServe ? [
|
|
@@ -1219,38 +2275,57 @@ function brumate(options = {}) {
|
|
|
1219
2275
|
] : [" return modules[id]?.();"],
|
|
1220
2276
|
"}"
|
|
1221
2277
|
].join("\n");
|
|
1222
|
-
}
|
|
2278
|
+
}
|
|
1223
2279
|
/**
|
|
1224
2280
|
* The module of every server function of the app, by ID. With `server`, in
|
|
1225
2281
|
* a DOM test, it imports the server code of each file, which that
|
|
1226
2282
|
* environment would give as browser code.
|
|
1227
2283
|
*/
|
|
1228
|
-
|
|
2284
|
+
function serverRegistry(server = false) {
|
|
1229
2285
|
const query = server ? SERVER_QUERY : "";
|
|
1230
2286
|
registered = packages.length > 0 ? reachable() : /* @__PURE__ */ new Set();
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
2287
|
+
function keep(file) {
|
|
2288
|
+
return registered.has(file) || !findPackage(packages, file);
|
|
2289
|
+
}
|
|
2290
|
+
const components = [];
|
|
2291
|
+
for (const file of files.values()) if (keep(file)) components.push(file);
|
|
2292
|
+
function importAll(prefix, list) {
|
|
2293
|
+
if (!isServe) {
|
|
2294
|
+
const lines = [];
|
|
2295
|
+
for (const [index, file] of list.entries()) lines.push(`import * as ${prefix}${index} from ${JSON.stringify(file + query)};`);
|
|
2296
|
+
return lines;
|
|
2297
|
+
}
|
|
1235
2298
|
if (list.length === 0) return [];
|
|
1236
|
-
const loads =
|
|
1237
|
-
|
|
1238
|
-
|
|
2299
|
+
const loads = [];
|
|
2300
|
+
const names = [];
|
|
2301
|
+
for (const [index, file] of list.entries()) {
|
|
2302
|
+
loads.push(`import(${JSON.stringify(file + query)})`);
|
|
2303
|
+
names.push(`${prefix}${index}`);
|
|
2304
|
+
}
|
|
2305
|
+
return [`const [${names.join(", ")}] = (await Promise.allSettled([${loads.join(", ")}])).map((result) => (result.status === 'fulfilled' ? result.value : {}));`];
|
|
2306
|
+
}
|
|
1239
2307
|
const imports = importAll("m", components);
|
|
1240
|
-
const spreads =
|
|
1241
|
-
const
|
|
1242
|
-
const
|
|
2308
|
+
const spreads = [];
|
|
2309
|
+
for (const index of components.keys()) spreads.push(` ...m${index}.rpc,`);
|
|
2310
|
+
const functionFiles = [];
|
|
2311
|
+
for (const entry of serverFiles) if (keep(entry[1])) functionFiles.push(entry);
|
|
2312
|
+
const functionPaths = [];
|
|
2313
|
+
for (const [, file] of functionFiles) functionPaths.push(file);
|
|
2314
|
+
const fileImports = importAll("f", functionPaths);
|
|
1243
2315
|
const guards = [];
|
|
1244
|
-
const fileSpreads =
|
|
2316
|
+
const fileSpreads = [];
|
|
2317
|
+
for (const [index, [id, file]] of functionFiles.entries()) {
|
|
1245
2318
|
const source = readFileSync(file, "utf8");
|
|
1246
2319
|
const names = serverExports(source, file);
|
|
1247
2320
|
const guarded = hasServerMiddleware(source, file);
|
|
1248
|
-
|
|
2321
|
+
const lines = [];
|
|
2322
|
+
for (const name of names) {
|
|
1249
2323
|
const key = JSON.stringify(functionId(id, name, !isServe));
|
|
1250
2324
|
if (guarded) guards.push(` ${key}: f${index}.middleware,`);
|
|
1251
|
-
|
|
1252
|
-
}
|
|
1253
|
-
|
|
2325
|
+
lines.push(` ${key}: f${index}[${JSON.stringify(name)}],`);
|
|
2326
|
+
}
|
|
2327
|
+
fileSpreads.push(lines.join("\n"));
|
|
2328
|
+
}
|
|
1254
2329
|
const env = envFile();
|
|
1255
2330
|
const entry = middlewareFile();
|
|
1256
2331
|
return [
|
|
@@ -1271,12 +2346,15 @@ function brumate(options = {}) {
|
|
|
1271
2346
|
` return handleRequest(functions, request, ${JSON.stringify(rpc)}, { origins: ${JSON.stringify(options.origins ?? [])}, ${entry ? "middleware, " : ""}fileMiddleware${buildId === void 0 ? "" : `, build: ${JSON.stringify(buildId)}`}, ...options });`,
|
|
1272
2347
|
"}"
|
|
1273
2348
|
].join("\n");
|
|
1274
|
-
}
|
|
1275
|
-
|
|
2349
|
+
}
|
|
2350
|
+
function routesDirectory() {
|
|
2351
|
+
return normalizePath(path.resolve(root, options.routes ?? "src/routes"));
|
|
2352
|
+
}
|
|
1276
2353
|
/** The route files, from the `.brm` files found and the `.ts` files of the directory. */
|
|
1277
|
-
|
|
2354
|
+
function currentRoutes() {
|
|
1278
2355
|
const directory = routesDirectory();
|
|
1279
|
-
const paths = [
|
|
2356
|
+
const paths = [];
|
|
2357
|
+
for (const file of files.values()) if (file.startsWith(`${directory}/`)) paths.push(file.slice(directory.length + 1));
|
|
1280
2358
|
if (existsSync(directory)) for (const entry of readdirSync(directory, {
|
|
1281
2359
|
recursive: true,
|
|
1282
2360
|
encoding: "utf8"
|
|
@@ -1285,70 +2363,102 @@ function brumate(options = {}) {
|
|
|
1285
2363
|
if (file.endsWith(".ts") && !file.endsWith(".d.ts")) paths.push(file);
|
|
1286
2364
|
}
|
|
1287
2365
|
return routeFiles(paths);
|
|
1288
|
-
}
|
|
2366
|
+
}
|
|
1289
2367
|
/**
|
|
1290
2368
|
* The modules that every page loads early, which the client build wrote,
|
|
1291
2369
|
* or none before a client build or in development.
|
|
1292
2370
|
*/
|
|
1293
|
-
|
|
2371
|
+
function clientHints() {
|
|
1294
2372
|
const file = path.join(clientBuildDirectory(root, options.prerender), HINTS_FILE);
|
|
1295
|
-
|
|
1296
|
-
|
|
2373
|
+
if (isServe || !existsSync(file)) return {
|
|
2374
|
+
all: [],
|
|
2375
|
+
bundles: {}
|
|
2376
|
+
};
|
|
2377
|
+
const read = JSON.parse(readFileSync(file, "utf8"));
|
|
2378
|
+
return Array.isArray(read) ? {
|
|
2379
|
+
all: read,
|
|
2380
|
+
bundles: {}
|
|
2381
|
+
} : read;
|
|
2382
|
+
}
|
|
1297
2383
|
/** The route tree module. A DOM test gets the server version of each component in it. */
|
|
1298
|
-
|
|
2384
|
+
function routeTree(server = false) {
|
|
1299
2385
|
const env = envFile();
|
|
1300
|
-
const code = routeModule(currentRoutes(), (file) => `${routesDirectory()}/${file}${server && file.endsWith(".brm") ? SERVER_QUERY : ""}`, rpc, options.origins, isServe, middlewareFile(), buildId, clientHints());
|
|
2386
|
+
const code = routeModule(currentRoutes(), (file) => `${routesDirectory()}/${file}${server && file.endsWith(".brm") ? SERVER_QUERY : ""}`, rpc, options.origins, isServe, middlewareFile(), buildId, clientHints().all, clientHints().bundles);
|
|
1301
2387
|
const serial = serialImports().join("\n");
|
|
1302
|
-
|
|
2388
|
+
const parts = [];
|
|
2389
|
+
for (const part of [
|
|
1303
2390
|
env ? `import ${JSON.stringify(env)};` : "",
|
|
1304
2391
|
serial,
|
|
1305
2392
|
code
|
|
1306
|
-
]
|
|
1307
|
-
|
|
2393
|
+
]) if (part) parts.push(part);
|
|
2394
|
+
return parts.join("\n");
|
|
2395
|
+
}
|
|
1308
2396
|
/** Writes the paths of the routes as types for `href`, when they changed. */
|
|
1309
|
-
|
|
2397
|
+
function writeRouteTypes() {
|
|
1310
2398
|
if (options.routeTypes === false || !existsSync(routesDirectory())) return;
|
|
1311
2399
|
const file = path.resolve(root, options.routeTypes ?? "src/brumate-routes.d.ts");
|
|
1312
2400
|
const text = routeTypes(currentRoutes());
|
|
1313
2401
|
if (!existsSync(file) || readFileSync(file, "utf8") !== text) writeFileSync(file, text);
|
|
1314
|
-
}
|
|
2402
|
+
}
|
|
1315
2403
|
/** What the devtools panel shows about a component: its name, its scopes and its report. */
|
|
1316
|
-
|
|
2404
|
+
async function inspectComponent(id) {
|
|
1317
2405
|
const file = files.get(id);
|
|
1318
2406
|
if (!file) return;
|
|
1319
2407
|
const { source, result } = await compileFile(file);
|
|
1320
2408
|
const { plan } = result;
|
|
1321
2409
|
const scopes = {};
|
|
1322
|
-
|
|
2410
|
+
function siteLabel(site) {
|
|
1323
2411
|
const at = result.locate(site.range.start);
|
|
1324
2412
|
const where = at.file === void 0 ? getLocation(source, at.offset) : void 0;
|
|
1325
2413
|
return where ? `${site.label} ${where.line}:${where.column}` : site.label;
|
|
1326
|
-
}
|
|
1327
|
-
const liveSites = new Set(
|
|
1328
|
-
for (const
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
readers
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
2414
|
+
}
|
|
2415
|
+
const liveSites = /* @__PURE__ */ new Set();
|
|
2416
|
+
for (const node of plan.graph.live) if ("site" in node) liveSites.add(node.site);
|
|
2417
|
+
for (const layout of plan.scopes.values()) {
|
|
2418
|
+
const slotNames = [];
|
|
2419
|
+
const readers = [];
|
|
2420
|
+
for (const slot of layout.slots) {
|
|
2421
|
+
slotNames.push(slot.name);
|
|
2422
|
+
const labels = /* @__PURE__ */ new Set();
|
|
2423
|
+
for (const ref of slot.reads) if (plan.graph.reached.has(ref.site) || liveSites.has(ref.site)) labels.add(siteLabel(ref.site));
|
|
2424
|
+
readers.push([...labels]);
|
|
2425
|
+
}
|
|
2426
|
+
scopes[layout.scope.id] = {
|
|
2427
|
+
label: scopeLabel(result.file.source, layout.scope),
|
|
2428
|
+
slots: slotNames,
|
|
2429
|
+
readers
|
|
2430
|
+
};
|
|
2431
|
+
}
|
|
2432
|
+
const nodes = [];
|
|
2433
|
+
const indexes = /* @__PURE__ */ new Map();
|
|
2434
|
+
for (const node of plan.graph.nodes) if (plan.graph.live.has(node)) {
|
|
2435
|
+
indexes.set(node, nodes.length);
|
|
2436
|
+
nodes.push(node);
|
|
2437
|
+
}
|
|
2438
|
+
const graphNodes = [];
|
|
2439
|
+
for (const node of nodes) {
|
|
2440
|
+
if (node.kind === "source" || node.kind === "memo") {
|
|
2441
|
+
graphNodes.push({
|
|
1338
2442
|
kind: node.kind === "memo" ? "memo" : node.declaration.kind,
|
|
1339
2443
|
label: node.declaration.name,
|
|
1340
2444
|
scope: instanceScope(plan, node.declaration.scope).id,
|
|
1341
2445
|
slot: slotIndex(plan, node.declaration)
|
|
1342
|
-
};
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
}
|
|
1350
|
-
|
|
1351
|
-
|
|
2446
|
+
});
|
|
2447
|
+
continue;
|
|
2448
|
+
}
|
|
2449
|
+
const at = result.locate(node.site.range.start);
|
|
2450
|
+
const where = at.file === void 0 ? getLocation(source, at.offset) : void 0;
|
|
2451
|
+
graphNodes.push({
|
|
2452
|
+
kind: node.kind,
|
|
2453
|
+
label: where ? `${node.site.label} ${where.line}:${where.column}` : node.site.label,
|
|
2454
|
+
scope: instanceScope(plan, node.site.scope).id
|
|
2455
|
+
});
|
|
2456
|
+
}
|
|
2457
|
+
const graphEdges = [];
|
|
2458
|
+
for (const edge of plan.graph.edges) if (indexes.has(edge.from) && indexes.has(edge.to)) graphEdges.push([indexes.get(edge.from), indexes.get(edge.to)]);
|
|
2459
|
+
const graph = {
|
|
2460
|
+
nodes: graphNodes,
|
|
2461
|
+
edges: graphEdges
|
|
1352
2462
|
};
|
|
1353
2463
|
const anchors = {};
|
|
1354
2464
|
for (const [target, index] of plan.anchors) {
|
|
@@ -1380,7 +2490,7 @@ function brumate(options = {}) {
|
|
|
1380
2490
|
const text = formatReport(report(source, result, liveProps.get(file)));
|
|
1381
2491
|
return {
|
|
1382
2492
|
name: plan.name,
|
|
1383
|
-
file:
|
|
2493
|
+
file: getFileName(file),
|
|
1384
2494
|
path: file,
|
|
1385
2495
|
url: file.startsWith(`${normalizePath(root)}/`) ? file.slice(normalizePath(root).length) : `/@fs${file}`,
|
|
1386
2496
|
scopes,
|
|
@@ -1388,12 +2498,165 @@ function brumate(options = {}) {
|
|
|
1388
2498
|
graph,
|
|
1389
2499
|
text
|
|
1390
2500
|
};
|
|
1391
|
-
}
|
|
1392
|
-
|
|
2501
|
+
}
|
|
2502
|
+
/** The components of the app for the workbench, with what each one needs and its controls. */
|
|
2503
|
+
/**
|
|
2504
|
+
* The stories of a component: the named exports of the `.stories.ts` file next to it, each a
|
|
2505
|
+
* set of props. Values that JSON cannot hold, such as functions, are left out.
|
|
2506
|
+
*/
|
|
2507
|
+
async function workbenchStories(server, file) {
|
|
2508
|
+
const storiesFile = file.replace(/\.brm$/, ".stories.ts");
|
|
2509
|
+
if (!existsSync(storiesFile)) return { stories: [] };
|
|
2510
|
+
try {
|
|
2511
|
+
const module = await server.ssrLoadModule(storiesFile);
|
|
2512
|
+
const stories = [];
|
|
2513
|
+
for (const [name, props] of Object.entries(module)) if (name !== "default" && props && typeof props === "object") stories.push({
|
|
2514
|
+
name,
|
|
2515
|
+
props: JSON.parse(JSON.stringify(props))
|
|
2516
|
+
});
|
|
2517
|
+
return { stories };
|
|
2518
|
+
} catch (error) {
|
|
2519
|
+
return {
|
|
2520
|
+
stories: [],
|
|
2521
|
+
storiesError: error instanceof Error ? error.message : String(error)
|
|
2522
|
+
};
|
|
2523
|
+
}
|
|
2524
|
+
}
|
|
2525
|
+
/** The group of a component of a package: its name, and the folder under the directory of its files. */
|
|
2526
|
+
function packageGroup(owner, file) {
|
|
2527
|
+
let directory = owner.root;
|
|
2528
|
+
for (const item of owner.directories) if (file.startsWith(`${item}/`)) {
|
|
2529
|
+
directory = item;
|
|
2530
|
+
break;
|
|
2531
|
+
}
|
|
2532
|
+
const folder = path.posix.dirname(file.slice(directory.length + 1));
|
|
2533
|
+
return folder === "." ? owner.name : `${owner.name}/${folder}`;
|
|
2534
|
+
}
|
|
2535
|
+
async function workbenchComponents(server) {
|
|
2536
|
+
const routes = `${routesDirectory()}/`;
|
|
2537
|
+
const list = [...new Set(files.values())];
|
|
2538
|
+
const contents = await inBatches(list, (file) => readFile(file, "utf8"));
|
|
2539
|
+
const sources = /* @__PURE__ */ new Map();
|
|
2540
|
+
for (const [index, file] of list.entries()) sources.set(file, contents[index]);
|
|
2541
|
+
const classes = classifyComponents(sources, {
|
|
2542
|
+
resolve: resolveComponent,
|
|
2543
|
+
serverImport: (file, specifier, name) => serverImport(file, specifier, name) !== void 0
|
|
2544
|
+
});
|
|
2545
|
+
function relative(file) {
|
|
2546
|
+
return normalizePath(path.relative(root, file));
|
|
2547
|
+
}
|
|
2548
|
+
const shown = [];
|
|
2549
|
+
for (const file of list) if (!file.startsWith(routes) && classes.has(file)) shown.push(file);
|
|
2550
|
+
const stories = await inBatches(shown, (file) => workbenchStories(server, file));
|
|
2551
|
+
const components = [];
|
|
2552
|
+
for (const [index, file] of shown.entries()) {
|
|
2553
|
+
const found = classes.get(file);
|
|
2554
|
+
let controls = [];
|
|
2555
|
+
try {
|
|
2556
|
+
controls = propControls(parse(sources.get(file), { filename: file }));
|
|
2557
|
+
} catch {
|
|
2558
|
+
controls = void 0;
|
|
2559
|
+
}
|
|
2560
|
+
const owner = findPackage(packages, file);
|
|
2561
|
+
const needs = [];
|
|
2562
|
+
for (const need of found.needs) needs.push({
|
|
2563
|
+
...need,
|
|
2564
|
+
via: need.via && relative(need.via)
|
|
2565
|
+
});
|
|
2566
|
+
components.push({
|
|
2567
|
+
file: relative(file),
|
|
2568
|
+
group: owner ? packageGroup(owner, file) : path.posix.dirname(relative(file)),
|
|
2569
|
+
label: owner ? `${packageGroup(owner, file)}/${path.basename(file)}` : relative(file),
|
|
2570
|
+
name: path.basename(file, ".brm"),
|
|
2571
|
+
selfContained: found.selfContained,
|
|
2572
|
+
needs,
|
|
2573
|
+
controls: controls ?? [],
|
|
2574
|
+
unreadProps: controls === void 0,
|
|
2575
|
+
...stories[index]
|
|
2576
|
+
});
|
|
2577
|
+
}
|
|
2578
|
+
return components.toSorted((a, b) => a.file.localeCompare(b.file));
|
|
2579
|
+
}
|
|
2580
|
+
let workbenchList;
|
|
2581
|
+
/** Makes the list of the workbench and keeps it, unless it fails, so a later read tries again. */
|
|
2582
|
+
function listWorkbench(server) {
|
|
2583
|
+
const list = workbenchComponents(server);
|
|
2584
|
+
workbenchList = list;
|
|
2585
|
+
list.catch(() => {
|
|
2586
|
+
if (workbenchList === list) workbenchList = void 0;
|
|
2587
|
+
});
|
|
2588
|
+
return list;
|
|
2589
|
+
}
|
|
2590
|
+
/**
|
|
2591
|
+
* Answers the workbench: its page, the list of components, and the frame that renders one
|
|
2592
|
+
* component on the server with props, and resumes it in the browser as a page does.
|
|
2593
|
+
*/
|
|
2594
|
+
async function serveWorkbench(server, request, response) {
|
|
2595
|
+
const url = new URL(request.url ?? "/", "http://localhost");
|
|
2596
|
+
if (url.pathname === WORKBENCH || url.pathname === `${WORKBENCH}/`) {
|
|
2597
|
+
response.setHeader("content-type", "text/html; charset=utf-8");
|
|
2598
|
+
response.end(workbenchPage(WORKBENCH));
|
|
2599
|
+
return;
|
|
2600
|
+
}
|
|
2601
|
+
if (url.pathname === `${WORKBENCH}/components`) {
|
|
2602
|
+
response.setHeader("content-type", "application/json");
|
|
2603
|
+
response.end(JSON.stringify(await listWorkbench(server)));
|
|
2604
|
+
return;
|
|
2605
|
+
}
|
|
2606
|
+
if (url.pathname !== `${WORKBENCH}/frame`) {
|
|
2607
|
+
response.statusCode = 404;
|
|
2608
|
+
response.end();
|
|
2609
|
+
return;
|
|
2610
|
+
}
|
|
2611
|
+
const asked = url.searchParams.get("file") ?? "";
|
|
2612
|
+
let listed = false;
|
|
2613
|
+
for (const component of await (workbenchList ?? listWorkbench(server))) if (component.file === asked && component.selfContained) {
|
|
2614
|
+
listed = true;
|
|
2615
|
+
break;
|
|
2616
|
+
}
|
|
2617
|
+
let file;
|
|
2618
|
+
if (listed) {
|
|
2619
|
+
for (const candidate of files.values()) if (normalizePath(path.relative(root, candidate)) === asked) {
|
|
2620
|
+
file = candidate;
|
|
2621
|
+
break;
|
|
2622
|
+
}
|
|
2623
|
+
}
|
|
2624
|
+
if (!file) {
|
|
2625
|
+
response.statusCode = 404;
|
|
2626
|
+
response.end(`No self-contained component "${asked}"`);
|
|
2627
|
+
return;
|
|
2628
|
+
}
|
|
2629
|
+
response.setHeader("content-type", "text/html; charset=utf-8");
|
|
2630
|
+
try {
|
|
2631
|
+
const props = JSON.parse(url.searchParams.get("props") || "{}");
|
|
2632
|
+
const component = (await server.ssrLoadModule(file)).default;
|
|
2633
|
+
const { renderToStream } = await server.ssrLoadModule("brumate/server");
|
|
2634
|
+
const reader = renderToStream(component, props, {
|
|
2635
|
+
start: `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${path.basename(file, ".brm")}</title></head><body>`,
|
|
2636
|
+
end: "</body></html>",
|
|
2637
|
+
scripts: `<script type="module" src="/@vite/client"><\/script><script type="module" src="/@id/__x00__${START}"><\/script>`
|
|
2638
|
+
}).getReader();
|
|
2639
|
+
for (;;) {
|
|
2640
|
+
const { done, value } = await reader.read();
|
|
2641
|
+
if (done) break;
|
|
2642
|
+
response.write(value);
|
|
2643
|
+
}
|
|
2644
|
+
response.end();
|
|
2645
|
+
} catch (error) {
|
|
2646
|
+
if (response.headersSent) {
|
|
2647
|
+
server.config.logger.error(error instanceof Error ? error.stack ?? error.message : String(error));
|
|
2648
|
+
response.end();
|
|
2649
|
+
return;
|
|
2650
|
+
}
|
|
2651
|
+
response.statusCode = 500;
|
|
2652
|
+
response.end(errorPage(error, server));
|
|
2653
|
+
}
|
|
2654
|
+
}
|
|
2655
|
+
async function handleDevRPC(server, request, response) {
|
|
1393
2656
|
const id = decodeURIComponent((request.url ?? "").slice(rpc.length + 1).split("?")[0]);
|
|
1394
2657
|
const owner = id.split("#")[0];
|
|
1395
2658
|
const file = files.get(owner) ?? serverFiles.get(owner);
|
|
1396
|
-
const reached = file &&
|
|
2659
|
+
const reached = file && findPackage(packages, file) ? reachable() : void 0;
|
|
1397
2660
|
if (!file || reached && !reached.has(file)) {
|
|
1398
2661
|
response.statusCode = 404;
|
|
1399
2662
|
response.end(`Unknown server function "${id}"`);
|
|
@@ -1405,9 +2668,11 @@ function brumate(options = {}) {
|
|
|
1405
2668
|
}
|
|
1406
2669
|
try {
|
|
1407
2670
|
const { handle } = await server.ssrLoadModule(SERVER);
|
|
2671
|
+
const headers = [];
|
|
2672
|
+
for (const [name, value] of Object.entries(request.headers)) if (value !== void 0) headers.push([name, String(value)]);
|
|
1408
2673
|
const webRequest = new Request(new URL(request.url ?? "/", "http://localhost"), {
|
|
1409
2674
|
method: "POST",
|
|
1410
|
-
headers
|
|
2675
|
+
headers,
|
|
1411
2676
|
body: new Uint8Array(await readBody(request))
|
|
1412
2677
|
});
|
|
1413
2678
|
const began = performance.now();
|
|
@@ -1421,30 +2686,30 @@ function brumate(options = {}) {
|
|
|
1421
2686
|
response.statusCode = 500;
|
|
1422
2687
|
response.end(String(error));
|
|
1423
2688
|
}
|
|
1424
|
-
}
|
|
2689
|
+
}
|
|
1425
2690
|
/** Updates the page in the browser after a change to a component, or reloads it. */
|
|
1426
2691
|
async function updateClient(file, server, timestamp) {
|
|
1427
2692
|
const normalized = normalizePath(file);
|
|
1428
2693
|
const targets = file.endsWith(".brm") ? [normalized] : [...dependents.get(normalized) ?? []];
|
|
1429
2694
|
if (targets.length === 0) return;
|
|
1430
|
-
|
|
2695
|
+
function invalidate() {
|
|
1431
2696
|
for (const module of server.moduleGraph.idToModuleMap.values()) {
|
|
1432
2697
|
const id = module.id ?? "";
|
|
1433
2698
|
if (id.includes(".brm") || id === `\0${MANIFEST}` || id === `\0${SERVER}` || id === `\0${ROUTES}`) server.moduleGraph.invalidateModule(module);
|
|
1434
2699
|
}
|
|
1435
|
-
}
|
|
1436
|
-
|
|
2700
|
+
}
|
|
2701
|
+
function reload() {
|
|
1437
2702
|
invalidate();
|
|
1438
2703
|
server.ws.send({ type: "full-reload" });
|
|
1439
2704
|
return [];
|
|
1440
|
-
}
|
|
2705
|
+
}
|
|
1441
2706
|
await analyze();
|
|
1442
2707
|
const updates = [];
|
|
1443
2708
|
for (const target of targets) {
|
|
1444
2709
|
const before = shapes.get(target);
|
|
1445
2710
|
let after;
|
|
1446
2711
|
try {
|
|
1447
|
-
after =
|
|
2712
|
+
after = getShape((await compileFile(target)).result);
|
|
1448
2713
|
} catch {
|
|
1449
2714
|
return reload();
|
|
1450
2715
|
}
|
|
@@ -1453,7 +2718,13 @@ function brumate(options = {}) {
|
|
|
1453
2718
|
const id = componentId(target);
|
|
1454
2719
|
const modules = [...server.moduleGraph.getModulesByFile(target) ?? [], ...target === normalized ? [] : server.moduleGraph.getModulesByFile(normalized) ?? []];
|
|
1455
2720
|
for (const module of modules) server.moduleGraph.invalidateModule(module, /* @__PURE__ */ new Set(), timestamp, true);
|
|
1456
|
-
|
|
2721
|
+
let entry;
|
|
2722
|
+
for (const module of server.moduleGraph.getModulesByFile(target) ?? []) if (module.id?.endsWith(CLIENT_QUERY)) {
|
|
2723
|
+
entry = module;
|
|
2724
|
+
break;
|
|
2725
|
+
}
|
|
2726
|
+
const kept = [];
|
|
2727
|
+
for (const name of after.signals) if (before.signals.includes(name)) kept.push(name);
|
|
1457
2728
|
updates.push({
|
|
1458
2729
|
id,
|
|
1459
2730
|
css: before.css === after.css ? void 0 : after.css,
|
|
@@ -1461,11 +2732,16 @@ function brumate(options = {}) {
|
|
|
1461
2732
|
remount: remount ? {
|
|
1462
2733
|
before: before.slots,
|
|
1463
2734
|
after: after.slots,
|
|
1464
|
-
signals:
|
|
2735
|
+
signals: kept
|
|
1465
2736
|
} : void 0
|
|
1466
2737
|
});
|
|
1467
2738
|
}
|
|
1468
|
-
|
|
2739
|
+
let remounts = false;
|
|
2740
|
+
for (const update of updates) if (update.remount) {
|
|
2741
|
+
remounts = true;
|
|
2742
|
+
break;
|
|
2743
|
+
}
|
|
2744
|
+
if (remounts) invalidate();
|
|
1469
2745
|
server.ws.send({
|
|
1470
2746
|
type: "custom",
|
|
1471
2747
|
event: "brumate:update",
|
|
@@ -1481,19 +2757,22 @@ function brumate(options = {}) {
|
|
|
1481
2757
|
* or their `.brm` and `'use server'` files would not reach this plugin, and the
|
|
1482
2758
|
* server build compiles them instead of importing them from `node_modules`.
|
|
1483
2759
|
*/
|
|
1484
|
-
|
|
2760
|
+
function packageConfig(config) {
|
|
1485
2761
|
if (packages.length === 0) return {};
|
|
1486
|
-
const
|
|
2762
|
+
const nameSet = /* @__PURE__ */ new Set();
|
|
2763
|
+
for (const item of packages) nameSet.add(item.name);
|
|
2764
|
+
const names = [...nameSet];
|
|
1487
2765
|
const result = {
|
|
1488
2766
|
optimizeDeps: { exclude: names },
|
|
1489
2767
|
ssr: { noExternal: names },
|
|
1490
2768
|
resolve: { dedupe: ["brumate"] }
|
|
1491
2769
|
};
|
|
1492
2770
|
const workspace = normalizePath(searchForWorkspaceRoot(path.resolve(config.root ?? ".")));
|
|
1493
|
-
const outside =
|
|
2771
|
+
const outside = [];
|
|
2772
|
+
for (const item of packages) if (item.root !== workspace && !item.root.startsWith(`${workspace}/`)) outside.push(item.root);
|
|
1494
2773
|
if (outside.length > 0) result.server = { fs: { allow: [workspace, ...outside] } };
|
|
1495
2774
|
return result;
|
|
1496
|
-
}
|
|
2775
|
+
}
|
|
1497
2776
|
/** The module ID of `brumate/client`, and the chunks of the loader and the core in a client build. */
|
|
1498
2777
|
let coreModule;
|
|
1499
2778
|
let loaderChunk;
|
|
@@ -1521,7 +2800,8 @@ function brumate(options = {}) {
|
|
|
1521
2800
|
modulePreload: { resolveDependencies(filename, deps, context) {
|
|
1522
2801
|
const list = resolve ? resolve(filename, deps, context) : deps;
|
|
1523
2802
|
if (context.hostId !== loaderChunk || !coreChunk) return list;
|
|
1524
|
-
const rest =
|
|
2803
|
+
const rest = [];
|
|
2804
|
+
for (const dep of list) if (dep !== coreChunk) rest.push(dep);
|
|
1525
2805
|
return rest.length === 1 && rest[0] === filename ? [] : rest;
|
|
1526
2806
|
} }
|
|
1527
2807
|
}
|
|
@@ -1532,8 +2812,10 @@ function brumate(options = {}) {
|
|
|
1532
2812
|
const input = typeof ssr === "string" ? ssr : config.build?.rolldownOptions?.input;
|
|
1533
2813
|
let entries;
|
|
1534
2814
|
if (typeof input === "string") entries = { [path.basename(input).replace(/\.[^.]+$/, "")]: input };
|
|
1535
|
-
else if (Array.isArray(input))
|
|
1536
|
-
|
|
2815
|
+
else if (Array.isArray(input)) {
|
|
2816
|
+
entries = {};
|
|
2817
|
+
for (const item of input) entries[path.basename(item).replace(/\.[^.]+$/, "")] = item;
|
|
2818
|
+
} else entries = { ...input };
|
|
1537
2819
|
return {
|
|
1538
2820
|
...shared,
|
|
1539
2821
|
build: {
|
|
@@ -1546,7 +2828,7 @@ function brumate(options = {}) {
|
|
|
1546
2828
|
};
|
|
1547
2829
|
},
|
|
1548
2830
|
configureVitest(context) {
|
|
1549
|
-
(context.defineCacheKeyGenerator ?? context.experimental_defineCacheKeyGenerator)?.(
|
|
2831
|
+
(context.defineCacheKeyGenerator ?? context.experimental_defineCacheKeyGenerator)?.(cacheKey);
|
|
1550
2832
|
},
|
|
1551
2833
|
configResolved(config) {
|
|
1552
2834
|
root = config.root;
|
|
@@ -1557,6 +2839,13 @@ function brumate(options = {}) {
|
|
|
1557
2839
|
},
|
|
1558
2840
|
async generateBundle(_output, bundle) {
|
|
1559
2841
|
if (isSsrBuild) return;
|
|
2842
|
+
for (const file of knownFeatures ? loadedComponents : []) {
|
|
2843
|
+
if (counted.has(file)) continue;
|
|
2844
|
+
const used = getFeatures((await compileFile(file)).result);
|
|
2845
|
+
const missing = [];
|
|
2846
|
+
for (const name of Object.keys(used)) if (used[name] && !knownFeatures[name]) missing.push(name);
|
|
2847
|
+
if (missing.length > 0) this.error(`${getFileName(file)} uses ${missing.join(", ")}, which the client build left out of the core, since no component that the build found uses them. Import it from a .brm component of the app, or set \`features: 'all'\`.`);
|
|
2848
|
+
}
|
|
1560
2849
|
loaderChunk = void 0;
|
|
1561
2850
|
coreChunk = void 0;
|
|
1562
2851
|
for (const item of Object.values(bundle)) {
|
|
@@ -1566,66 +2855,87 @@ function brumate(options = {}) {
|
|
|
1566
2855
|
}
|
|
1567
2856
|
if (!options.report && !options.budget) return;
|
|
1568
2857
|
const chunks = [];
|
|
1569
|
-
for (const item of Object.values(bundle)) if (item.type === "chunk")
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
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
|
-
}
|
|
2858
|
+
for (const item of Object.values(bundle)) if (item.type === "chunk") {
|
|
2859
|
+
const modules = {};
|
|
2860
|
+
for (const [id, module] of Object.entries(item.modules)) modules[id] = module.renderedLength;
|
|
2861
|
+
chunks.push({
|
|
2862
|
+
fileName: item.fileName,
|
|
2863
|
+
code: item.code,
|
|
2864
|
+
isEntry: item.isEntry,
|
|
2865
|
+
imports: item.imports,
|
|
2866
|
+
moduleIds: item.moduleIds,
|
|
2867
|
+
modules
|
|
2868
|
+
});
|
|
1590
2869
|
}
|
|
2870
|
+
const list = [...files.values()];
|
|
2871
|
+
const contents = await inBatches(list, (file) => readFile(file, "utf8"));
|
|
2872
|
+
const sources = /* @__PURE__ */ new Map();
|
|
2873
|
+
for (const [index, file] of list.entries()) sources.set(file, contents[index]);
|
|
1591
2874
|
const measured = buildReport({
|
|
1592
2875
|
chunks,
|
|
1593
|
-
sources
|
|
2876
|
+
sources,
|
|
1594
2877
|
routes: existsSync(routesDirectory()) ? {
|
|
1595
2878
|
tree: currentRoutes(),
|
|
1596
2879
|
resolve: (file) => `${routesDirectory()}/${file}`
|
|
1597
2880
|
} : void 0,
|
|
1598
|
-
events,
|
|
1599
2881
|
budget: options.budget,
|
|
1600
|
-
relative:
|
|
2882
|
+
relative: getFileName
|
|
1601
2883
|
});
|
|
1602
|
-
if (options.report) this.info(`\n${formatBuildReport(measured,
|
|
2884
|
+
if (options.report) this.info(`\n${formatBuildReport(measured, getFileName)}`);
|
|
1603
2885
|
if (measured.overBudget.length > 0) this.error(measured.overBudget.join("\n"));
|
|
1604
2886
|
},
|
|
1605
2887
|
async writeBundle(_output, bundle) {
|
|
1606
2888
|
if (!isSsrBuild) {
|
|
1607
|
-
const chunks = new Map(
|
|
2889
|
+
const chunks = /* @__PURE__ */ new Map();
|
|
2890
|
+
for (const item of Object.values(bundle)) if (item.type === "chunk") chunks.set(item.fileName, item);
|
|
1608
2891
|
const hints = /* @__PURE__ */ new Set();
|
|
1609
|
-
|
|
2892
|
+
function add(name) {
|
|
1610
2893
|
const chunk = name === void 0 ? void 0 : chunks.get(name);
|
|
1611
2894
|
if (chunk && !hints.has(chunk.fileName)) {
|
|
1612
2895
|
hints.add(chunk.fileName);
|
|
1613
|
-
chunk.imports
|
|
2896
|
+
for (const imported of chunk.imports) add(imported);
|
|
1614
2897
|
}
|
|
1615
|
-
}
|
|
2898
|
+
}
|
|
1616
2899
|
add(loaderChunk);
|
|
1617
2900
|
add(coreChunk);
|
|
2901
|
+
const bundleHints = {};
|
|
2902
|
+
for (const chunk of chunks.values()) {
|
|
2903
|
+
const facade = chunk.facadeModuleId ?? "";
|
|
2904
|
+
if (!facade.startsWith(`\0${BUNDLE}`)) continue;
|
|
2905
|
+
const files = /* @__PURE__ */ new Set();
|
|
2906
|
+
function walk(name) {
|
|
2907
|
+
const found = chunks.get(name);
|
|
2908
|
+
if (found && !files.has(name) && !hints.has(name)) {
|
|
2909
|
+
files.add(name);
|
|
2910
|
+
for (const imported of found.imports) walk(imported);
|
|
2911
|
+
}
|
|
2912
|
+
}
|
|
2913
|
+
walk(chunk.fileName);
|
|
2914
|
+
const urls = [];
|
|
2915
|
+
for (const name of files) urls.push(`${base}${name}`);
|
|
2916
|
+
bundleHints[facade.slice(24)] = urls;
|
|
2917
|
+
}
|
|
1618
2918
|
await mkdir(path.join(outDir, ".brumate"), { recursive: true });
|
|
1619
|
-
|
|
2919
|
+
const all = [];
|
|
2920
|
+
for (const name of hints) all.push(`${base}${name}`);
|
|
2921
|
+
await writeFile(path.join(outDir, HINTS_FILE), JSON.stringify({
|
|
2922
|
+
all,
|
|
2923
|
+
bundles: bundleHints
|
|
2924
|
+
}));
|
|
1620
2925
|
if (buildId !== void 0) {
|
|
1621
|
-
const written =
|
|
2926
|
+
const written = [];
|
|
2927
|
+
for (const item of Object.values(bundle)) written.push(item.fileName);
|
|
1622
2928
|
const removed = pruneBuilds(outDir, buildId, written, options.skew?.keep ?? 0);
|
|
1623
2929
|
if (removed.length > 0) this.info(`Removed the files of ${removed.length} older builds`);
|
|
1624
2930
|
}
|
|
1625
2931
|
return;
|
|
1626
2932
|
}
|
|
1627
2933
|
if (!options.prerender || !isSsrBuild) return;
|
|
1628
|
-
|
|
2934
|
+
let chunk;
|
|
2935
|
+
for (const item of Object.values(bundle)) if (item.type === "chunk" && item.isEntry && item.name === PRERENDER_ENTRY) {
|
|
2936
|
+
chunk = item;
|
|
2937
|
+
break;
|
|
2938
|
+
}
|
|
1629
2939
|
if (!chunk) return;
|
|
1630
2940
|
const settings = options.prerender === true ? {} : options.prerender;
|
|
1631
2941
|
const written = await prerender(path.join(outDir, chunk.fileName), root, base, settings);
|
|
@@ -1641,10 +2951,13 @@ function brumate(options = {}) {
|
|
|
1641
2951
|
}
|
|
1642
2952
|
coreModule = isServe ? void 0 : (await this.resolve("brumate/client", path.join(root, "index.html")))?.id;
|
|
1643
2953
|
await scan();
|
|
2954
|
+
builtFeatures = void 0;
|
|
2955
|
+
knownFeatures = void 0;
|
|
2956
|
+
loadedComponents.clear();
|
|
1644
2957
|
writeRouteTypes();
|
|
1645
2958
|
},
|
|
1646
2959
|
async resolveId(id, importer, resolveOptions) {
|
|
1647
|
-
if (id === START || id === MANIFEST || id === SERVER || id === ROUTES || id === TESTING) return `\0${id}`;
|
|
2960
|
+
if (id === START || id === MANIFEST || id === SERVER || id === ROUTES || id === TESTING || id.startsWith(BUNDLE)) return `\0${id}`;
|
|
1648
2961
|
const env = resolveOptions?.ssr ? void 0 : envFile();
|
|
1649
2962
|
const from = importer?.split("?")[0];
|
|
1650
2963
|
if (env && importer && from && from !== env && isScriptFile(from) && !importer.startsWith("\0") && !importer.includes(SERVER_QUERY) && !importer.includes("/node_modules/")) {
|
|
@@ -1660,7 +2973,7 @@ function brumate(options = {}) {
|
|
|
1660
2973
|
...resolveOptions,
|
|
1661
2974
|
skipSelf: true
|
|
1662
2975
|
});
|
|
1663
|
-
if (!resolved || resolved.external || resolved.id.includes("?") || resolved.id.includes("/node_modules/") && !
|
|
2976
|
+
if (!resolved || resolved.external || resolved.id.includes("?") || resolved.id.includes("/node_modules/") && !findPackage(packages, resolved.id)) return resolved;
|
|
1664
2977
|
const file = resolved.id;
|
|
1665
2978
|
return isScriptFile(file) && existsSync(file) && hasUseServer(readFileSync(file, "utf8")) ? {
|
|
1666
2979
|
...resolved,
|
|
@@ -1685,15 +2998,16 @@ function brumate(options = {}) {
|
|
|
1685
2998
|
}
|
|
1686
2999
|
if (id === `\0${START}`) return [
|
|
1687
3000
|
options.navigate === false ? "import { startWithoutNavigation as start } from 'brumate/static-loader';" : "import { start } from 'brumate/loader';",
|
|
1688
|
-
`import { load } from ${JSON.stringify(MANIFEST)};`,
|
|
3001
|
+
`import { load${isServe ? "" : ", loadBundle"} } from ${JSON.stringify(MANIFEST)};`,
|
|
1689
3002
|
...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)}${
|
|
3003
|
+
`start({ load${isServe ? ": hotLoad(import.meta.hot, load)" : ", loadBundle"}${serialFile() ? `, serial: () => import(${JSON.stringify(serialFile())})` : ""}, rpc: ${JSON.stringify(rpc)}, navigate: ${JSON.stringify(options.navigate ?? true)}${buildId === void 0 ? "" : `, build: ${JSON.stringify(buildId)}`} });`,
|
|
1691
3004
|
...isServe && options.devtools !== false ? [`import('brumate/devtools').then((m) => m.installDevtools(${JSON.stringify(INSPECT)}, ${JSON.stringify(rpc)}, ${JSON.stringify({
|
|
1692
3005
|
version: BRUMATE_VERSION,
|
|
1693
3006
|
vite: version
|
|
1694
3007
|
})}, import.meta.hot));`] : []
|
|
1695
3008
|
].join("\n");
|
|
1696
3009
|
if (id === `\0${MANIFEST}`) return await manifest();
|
|
3010
|
+
if (id.startsWith(`\0${BUNDLE}`)) return await bundleModule(id.slice(24));
|
|
1697
3011
|
if (id === `\0${SERVER}`) return serverRegistry(!loadOptions?.ssr);
|
|
1698
3012
|
if (id === `\0${ROUTES}`) return routeTree(!loadOptions?.ssr);
|
|
1699
3013
|
if (id === `\0${TESTING}`) {
|
|
@@ -1738,6 +3052,7 @@ function brumate(options = {}) {
|
|
|
1738
3052
|
});
|
|
1739
3053
|
}
|
|
1740
3054
|
const { source, result } = output;
|
|
3055
|
+
if (!isServe && !isSsrBuild && isClient) loadedComponents.add(file);
|
|
1741
3056
|
for (const dependency of [...result.plan.styles.dependencies, ...result.modules]) {
|
|
1742
3057
|
const normalized = normalizePath(dependency);
|
|
1743
3058
|
this.addWatchFile(normalized);
|
|
@@ -1746,7 +3061,7 @@ function brumate(options = {}) {
|
|
|
1746
3061
|
}
|
|
1747
3062
|
for (const warning of isClient && !params.has("part") ? result.warnings : []) {
|
|
1748
3063
|
const { line, column } = getLocation(source, warning.range.start);
|
|
1749
|
-
this.warn(`${warning.message} (${
|
|
3064
|
+
this.warn(`${warning.message} (${getFileName(file)}:${line}:${column})`);
|
|
1750
3065
|
}
|
|
1751
3066
|
const part = params.get("part");
|
|
1752
3067
|
let code;
|
|
@@ -1764,15 +3079,21 @@ function brumate(options = {}) {
|
|
|
1764
3079
|
code = isClient ? result.client : result.server;
|
|
1765
3080
|
map = isClient ? result.maps.client : result.maps.server;
|
|
1766
3081
|
}
|
|
3082
|
+
const sources = [];
|
|
3083
|
+
if (map) for (const [index, name] of map.sources.entries()) sources.push(index === 0 ? file : name);
|
|
1767
3084
|
return {
|
|
1768
3085
|
code,
|
|
1769
3086
|
map: map && {
|
|
1770
3087
|
...map,
|
|
1771
|
-
sources
|
|
3088
|
+
sources
|
|
1772
3089
|
}
|
|
1773
3090
|
};
|
|
1774
3091
|
},
|
|
1775
3092
|
async transform(code, id, transformOptions) {
|
|
3093
|
+
if (!isServe && !isSsrBuild && !transformOptions?.ssr && readsFeatures(code)) return {
|
|
3094
|
+
code: writeFeatures(code, options.features === "all" ? allFeatures() : await buildFeatures()),
|
|
3095
|
+
map: null
|
|
3096
|
+
};
|
|
1776
3097
|
const [file] = id.split("?");
|
|
1777
3098
|
if (file && !transformOptions?.ssr && file === envFile()) try {
|
|
1778
3099
|
return {
|
|
@@ -1820,14 +3141,17 @@ function brumate(options = {}) {
|
|
|
1820
3141
|
};
|
|
1821
3142
|
},
|
|
1822
3143
|
configureServer(server) {
|
|
1823
|
-
const linked =
|
|
3144
|
+
const linked = [];
|
|
3145
|
+
for (const item of packages) if (item.linked) linked.push(...item.directories);
|
|
1824
3146
|
if (linked.length > 0) server.watcher.add(linked);
|
|
1825
|
-
const manifests = [path.join(root, "package.json")
|
|
3147
|
+
const manifests = [normalizePath(path.join(root, "package.json"))];
|
|
3148
|
+
for (const item of packages) manifests.push(normalizePath(`${item.root}/package.json`));
|
|
1826
3149
|
server.watcher.add(manifests);
|
|
1827
3150
|
server.watcher.on("change", (file) => {
|
|
1828
3151
|
if (manifests.includes(normalizePath(file)) && packagesKey(findPackages(root)) !== packagesKey(packages)) server.restart();
|
|
1829
3152
|
});
|
|
1830
3153
|
server.watcher.on("all", (event, file) => {
|
|
3154
|
+
workbenchList = void 0;
|
|
1831
3155
|
if (normalizePath(file) === envFile()) compiled.clear();
|
|
1832
3156
|
for (const importer of dependents.get(normalizePath(file)) ?? []) {
|
|
1833
3157
|
compiled.delete(importer);
|
|
@@ -1839,8 +3163,10 @@ function brumate(options = {}) {
|
|
|
1839
3163
|
}
|
|
1840
3164
|
if (isScriptFile(file)) {
|
|
1841
3165
|
const normalized = normalizePath(file);
|
|
1842
|
-
if (packages.length > 0 && !
|
|
1843
|
-
|
|
3166
|
+
if (packages.length > 0 && !findPackage(packages, normalized)) {
|
|
3167
|
+
const rest = [];
|
|
3168
|
+
for (const item of appScripts) if (item !== normalized) rest.push(item);
|
|
3169
|
+
appScripts = rest;
|
|
1844
3170
|
if (event !== "unlink") appScripts.push(normalized);
|
|
1845
3171
|
}
|
|
1846
3172
|
const id = serverFileId(normalized);
|
|
@@ -1892,6 +3218,10 @@ function brumate(options = {}) {
|
|
|
1892
3218
|
}).catch(next);
|
|
1893
3219
|
return;
|
|
1894
3220
|
}
|
|
3221
|
+
if (request.method === "GET" && request.url?.startsWith(WORKBENCH)) {
|
|
3222
|
+
serveWorkbench(server, request, response).catch(next);
|
|
3223
|
+
return;
|
|
3224
|
+
}
|
|
1895
3225
|
if (request.method === "GET" && request.url?.startsWith(`${INSPECT}/`)) {
|
|
1896
3226
|
inspectComponent(decodeURIComponent(request.url.slice(19))).then((info) => {
|
|
1897
3227
|
response.statusCode = info ? 200 : 404;
|
|
@@ -1921,6 +3251,18 @@ function brumate(options = {}) {
|
|
|
1921
3251
|
}
|
|
1922
3252
|
};
|
|
1923
3253
|
}
|
|
3254
|
+
/** The names that compiled client code exports, such as `h4`, `u5` and `g`. */
|
|
3255
|
+
function exportNames(codes) {
|
|
3256
|
+
const names = /* @__PURE__ */ new Set();
|
|
3257
|
+
for (const code of codes) for (const match of code.matchAll(/^export (?:async )?(?:function\*? |const |let |var )([\w$]+)|^export \{([^}]*)\}/gm)) {
|
|
3258
|
+
if (match[1]) names.add(match[1]);
|
|
3259
|
+
for (const item of match[2]?.split(",") ?? []) {
|
|
3260
|
+
const name = item.trim().split(/\s+as\s+/).pop();
|
|
3261
|
+
if (name) names.add(name);
|
|
3262
|
+
}
|
|
3263
|
+
}
|
|
3264
|
+
return [...names];
|
|
3265
|
+
}
|
|
1924
3266
|
//#endregion
|
|
1925
3267
|
export { brumate as default, errorPage };
|
|
1926
3268
|
|