mirror of
https://github.com/morluto/rea.git
synced 2026-11-14 18:52:48 +00:00
Every rea process imported and registered all 52 command registrars
(about 1,900 modules) before running any command. A one-shot command
now loads only the registrar that defines its top-level command.
- src/cli/cliCommandRegistrations.ts holds every registrar in one table,
grouped by tool family, with its module loader and its call. The
complete createCli registers the table with static imports, and the
types check that each entry matches its module.
- src/cli/cliShell.ts owns what does not depend on which commands are
registered: identity, globals, argument policy, completions and the
registration builtins. The full and lazy paths share it.
- scripts/record-cli-commands.mjs records, after tsc, which registrar
defines each top-level command, from the same compiled table. The
bundle keeps the record as an external dist module.
- cli/cliLoader.ts selects the recorded registrar when a known top-level
command runs. It loads the complete CLI for help, --schema, --llms,
completions, builtins, unknown names ("did you mean"), or a missing
record.
- Process-owned CLI resources register their closers when their module
loads (cli/cliResources.ts), so the shell no longer imports
JavaScript-analysis and guidance owners just to close them.
Measured on one pinned core (median of 5 warm runs, base main vs this
change):
- guidance: 1.95 s / 253 MB → 0.42 s / 101 MB
- list-cutter-sessions: 1.97 s → 0.49 s
- inspect-go-binary: 1.95 s → 0.95 s
- setup --dry-run: 2.40 s → 1.88 s
- analyze: 2.39 s → 1.78 s
- --help: 1.99 s → 2.04 s (complete CLI, as before)
Co-Authored-By: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>
148 lines
5.6 KiB
JavaScript
148 lines
5.6 KiB
JavaScript
import { parse } from "@babel/parser";
|
|
import { readFile } from "node:fs/promises";
|
|
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
|
|
/**
|
|
* Reduce filesystem resolution during CLI and MCP startup. Keep dependencies
|
|
* external and original compiled worker entrypoints. Dynamic imports can split
|
|
* into lazy chunks unless the same module is also statically reachable.
|
|
*/
|
|
export const bundleRuntime = async (root) => {
|
|
const compiledRoot = resolve(root, "dist");
|
|
// CLI, MCP, workers and updater fixtures share one release-identity owner.
|
|
// The recorded CLI command registrars stay one replaceable build fact too.
|
|
const recordedModules = new Set(
|
|
["generatedPackageMetadata.js", "recordedCliCommandRegistrations.js"].map(
|
|
(name) => join(compiledRoot, name),
|
|
),
|
|
);
|
|
const isMetadataModule = (id) =>
|
|
isAbsolute(id) && recordedModules.has(resolve(id));
|
|
const { rolldown, RUNTIME_MODULE_ID } = await import("rolldown");
|
|
const { imports = {} } = JSON.parse(
|
|
await readFile(join(root, "package.json"), "utf8"),
|
|
);
|
|
for (const [directory, entries] of [
|
|
["mcp", { main: "main.js" }],
|
|
[
|
|
"cli-runtime",
|
|
{
|
|
cli: "cli.js",
|
|
cliOneShot: "cliOneShot.js",
|
|
cliBuiltinArguments: "cliBuiltinArguments.js",
|
|
cliResultOutput: "cli/cliResultOutput.js",
|
|
mcpDoctor: "mcpDoctor.js",
|
|
},
|
|
],
|
|
]) {
|
|
const bundle = await rolldown({
|
|
input: Object.fromEntries(
|
|
Object.entries(entries).map(([name, path]) => [
|
|
name,
|
|
join(compiledRoot, path),
|
|
]),
|
|
),
|
|
platform: "node",
|
|
treeshake: false,
|
|
external: (source) =>
|
|
isMetadataModule(source) ||
|
|
(!source.startsWith(".") && !isAbsolute(source)),
|
|
plugins: [
|
|
{
|
|
name: "preserve-compiled-module-locations",
|
|
transform(code, id) {
|
|
if (id === RUNTIME_MODULE_ID) return null;
|
|
if (!code.includes("import.meta")) return null;
|
|
const sourcePath = relative(compiledRoot, id);
|
|
if (
|
|
isAbsolute(sourcePath) ||
|
|
sourcePath === ".." ||
|
|
sourcePath.startsWith(`..${sep}`)
|
|
)
|
|
throw new Error(`Runtime bundle input is outside dist: ${id}`);
|
|
// Each output directory is directly under dist. Preserve the original
|
|
// module URL, including URL escaping, for bridges and createRequire.
|
|
const moduleUrl = `new URL(${JSON.stringify(`../${sourcePath.split(sep).map(encodeURIComponent).join("/")}`)}, import.meta.url).href`;
|
|
const edits = [];
|
|
const visit = (node) => {
|
|
if (node === null || typeof node !== "object") return;
|
|
const isMeta = (value) =>
|
|
value?.type === "MetaProperty" &&
|
|
value.meta.name === "import" &&
|
|
value.property.name === "meta";
|
|
if (
|
|
node.type === "CallExpression" &&
|
|
node.callee.type === "MemberExpression" &&
|
|
!node.callee.computed &&
|
|
isMeta(node.callee.object) &&
|
|
node.callee.property.name === "resolve" &&
|
|
node.arguments.length === 1 &&
|
|
node.arguments[0].type === "StringLiteral" &&
|
|
Object.hasOwn(imports, node.arguments[0].value)
|
|
)
|
|
// Package imports resolve in the same package scope after bundling.
|
|
return;
|
|
if (
|
|
node.type === "MemberExpression" &&
|
|
!node.computed &&
|
|
isMeta(node.object) &&
|
|
node.property.name === "url"
|
|
) {
|
|
edits.push({ start: node.start, end: node.end });
|
|
return;
|
|
}
|
|
if (isMeta(node))
|
|
throw new Error(
|
|
`Unsupported import.meta use in runtime bundle: ${id}`,
|
|
);
|
|
for (const value of Object.values(node)) {
|
|
if (Array.isArray(value)) value.forEach(visit);
|
|
else visit(value);
|
|
}
|
|
};
|
|
visit(parse(code, { sourceType: "module" }).program);
|
|
for (const { start, end } of edits.sort(
|
|
(a, b) => b.start - a.start,
|
|
))
|
|
code = code.slice(0, start) + moduleUrl + code.slice(end);
|
|
return { code, map: null };
|
|
},
|
|
},
|
|
],
|
|
});
|
|
try {
|
|
await bundle.write({
|
|
dir: join(compiledRoot, directory),
|
|
format: "esm",
|
|
entryFileNames: "[name].js",
|
|
chunkFileNames:
|
|
directory === "mcp"
|
|
? "[name]-[hash].js"
|
|
: (chunk) => {
|
|
// Keep lazy facades distinguishable when source basenames repeat.
|
|
if (typeof chunk.facadeModuleId !== "string")
|
|
return "[name]-[hash].js";
|
|
const path = relative(compiledRoot, chunk.facadeModuleId);
|
|
return `${path.replace(/\.js$/u, "").split(sep).join("__")}-[hash].js`;
|
|
},
|
|
paths: (id) =>
|
|
isMetadataModule(id) ? `../${relative(compiledRoot, id)}` : id,
|
|
minifyInternalExports: directory === "mcp",
|
|
codeSplitting: true,
|
|
strictExecutionOrder: true,
|
|
minify: false,
|
|
sourcemap: false,
|
|
});
|
|
} finally {
|
|
await bundle.close();
|
|
}
|
|
}
|
|
};
|
|
|
|
if (
|
|
process.argv[1] !== undefined &&
|
|
pathToFileURL(resolve(process.argv[1])).href === import.meta.url
|
|
)
|
|
await bundleRuntime(resolve(dirname(fileURLToPath(import.meta.url)), ".."));
|