Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

fix(build): keep server-only brownout code out of the CDN lib bundle, and catch the next one

nirholasb2545ffb72d5
diff --git a/scripts/check-browser-graph.mjs b/scripts/check-browser-graph.mjs
index cddc54d3e..0027baa43 100644
--- a/scripts/check-browser-graph.mjs
+++ b/scripts/check-browser-graph.mjs
@@ -63,8 +63,13 @@ function tracked(patterns) {
.filter((f) => existsSync(f)); // a tracked-but-deleted path is not our problem
}
+// Three shapes, in order: a static `import`/`export ... from '...'` (the name
+// clause may span lines, so newlines are allowed between the keyword and
+// `from`. A `[^'"\n]` class here silently skipped every multi-line import,
+// which is most of them in this repo and hid 44 real edges), a dynamic
+// `import('...')`, and a bare side-effect `import '...'`.
const IMPORT_RE =
- /(?:^|\n)\s*(?:import|export)[^'"\n]*?from\s*['"]([^'"]+)['"]|(?:^|[^.\w])import\(\s*['"]([^'"]+)['"]\s*\)/g;
+ /(?:^|\n)\s*(?:import|export)\b[^'"]*?from\s*['"]([^'"]+)['"]|(?:^|[^.\w])import\(\s*['"]([^'"]+)['"]\s*\)|(?:^|\n)\s*import\s*['"]([^'"]+)['"]/g;
/**
* Every specifier `file` imports, tagged static vs dynamic.
@@ -84,6 +89,7 @@ function specifiersOf(file) {
for (const m of src.matchAll(IMPORT_RE)) {
if (m[1]) out.push({ spec: m[1], dynamic: false });
else if (m[2]) out.push({ spec: m[2], dynamic: true });
+ else if (m[3]) out.push({ spec: m[3], dynamic: false });
}
return out;
}
@@ -101,87 +107,144 @@ function builtinName(spec) {
return NODE_BUILTINS.has(root) ? root : null;
}
-// ── Seed from what the browser actually loads: every tracked HTML entry ───────
-const parent = new Map();
-const queue = [];
+// ── Two browser targets, two graphs ──────────────────────────────────────────
+// The APP target (vite build → dist/) code-splits, so a dynamic import stays a
+// separate chunk that only the server branch ever fetches. The LIB target
+// (dist-lib/agent-3d.js, the <agent-3d> CDN embed) builds with
+// `rollupOptions.output.inlineDynamicImports` so CDN consumers get one file,
+// and that flattens EVERY dynamic import into the bundle. A `import()` behind a
+// `typeof window === 'undefined'` guard is therefore safe in the app and a hard
+// build break in the lib: on 2026-08-28 `src/shared/failover-fetch.js` reached
+// api/_lib/brownout/ that way and killed build:lib:full with
+// `"AsyncLocalStorage" is not exported by "__vite-browser-external"`, three
+// steps before the app build this script had already cleared.
+//
+// So each target is walked under its own rule for dynamic edges.
-function enqueue(file, from) {
- if (parent.has(file)) return;
- parent.set(file, from);
- queue.push(file);
-}
+/**
+ * @param {{label: string, seeds: () => Array<[string, string]>, inlineDynamic: boolean}} target
+ * seeds() yields [absolute file, human-readable origin] pairs.
+ */
+function walk(target) {
+ const parent = new Map();
+ const queue = [];
+ const leaks = [];
-for (const html of tracked(['pages/*.html', 'public/**/*.html', '*.html'])) {
- let src;
- try { src = readFileSync(html, 'utf8'); } catch { continue; }
- const label = relative(ROOT, html);
- for (const m of src.matchAll(/<script[^>]+src=["']([^"']+)["']/g)) {
- const spec = m[1];
- if (/^(https?:)?\/\//.test(spec)) continue;
- const abs = spec.startsWith('/')
- ? resolve(ROOT, spec.slice(1))
- : resolve(dirname(html), spec);
- if (existsSync(abs)) enqueue(abs, label);
+ function enqueue(file, from) {
+ if (parent.has(file)) return;
+ parent.set(file, from);
+ queue.push(file);
}
- for (const m of src.matchAll(IMPORT_RE)) {
- const spec = m[1] || m[2];
- if (!spec || /^(https?:)?\/\//.test(spec)) continue;
- const abs = spec.startsWith('/')
- ? resolve(ROOT, spec.slice(1))
- : resolveLocal(html, spec);
- if (abs && existsSync(abs)) enqueue(abs, label);
+
+ function chainTo(file) {
+ const chain = [];
+ let cur = file;
+ while (cur && typeof cur === 'string' && cur.startsWith('/')) {
+ chain.unshift(relative(ROOT, cur));
+ cur = parent.get(cur);
+ }
+ if (cur) chain.unshift(cur);
+ return chain;
}
-}
-// ── Walk it ──────────────────────────────────────────────────────────────────
-const leaks = [];
+ for (const [file, from] of target.seeds()) enqueue(file, from);
-function chainTo(file) {
- const chain = [];
- let cur = file;
- while (cur && typeof cur === 'string' && cur.startsWith('/')) {
- chain.unshift(relative(ROOT, cur));
- cur = parent.get(cur);
+ while (queue.length) {
+ const file = queue.shift();
+ for (const { spec, dynamic } of specifiersOf(file)) {
+ // A dynamic edge is followed only where the bundler inlines it.
+ const followed = !dynamic || target.inlineDynamic;
+ const builtin = builtinName(spec);
+ if (builtin) {
+ if (followed && !POLYFILLED.has(builtin)) {
+ leaks.push({ file, spec, chain: chainTo(file) });
+ }
+ continue;
+ }
+ if (!followed) continue;
+ if (!spec.startsWith('.')) continue; // bare package, the bundler's problem and not ours
+ const next = resolveLocal(file, spec);
+ if (next) enqueue(next, file);
+ }
}
- if (cur) chain.unshift(cur);
- return chain;
+
+ return { parent, leaks };
}
-while (queue.length) {
- const file = queue.shift();
- for (const { spec, dynamic } of specifiersOf(file)) {
- const builtin = builtinName(spec);
- if (builtin) {
- if (!dynamic && !POLYFILLED.has(builtin)) leaks.push({ file, spec, chain: chainTo(file) });
- continue;
+function htmlSeeds() {
+ const out = [];
+ for (const html of tracked(['pages/*.html', 'public/**/*.html', '*.html'])) {
+ let src;
+ try { src = readFileSync(html, 'utf8'); } catch { continue; }
+ const label = relative(ROOT, html);
+ for (const m of src.matchAll(/<script[^>]+src=["']([^"']+)["']/g)) {
+ const spec = m[1];
+ if (/^(https?:)?\/\//.test(spec)) continue;
+ const abs = spec.startsWith('/')
+ ? resolve(ROOT, spec.slice(1))
+ : resolve(dirname(html), spec);
+ if (existsSync(abs)) out.push([abs, label]);
+ }
+ for (const m of src.matchAll(IMPORT_RE)) {
+ const spec = m[1] || m[2] || m[3];
+ if (!spec || /^(https?:)?\/\//.test(spec)) continue;
+ const abs = spec.startsWith('/')
+ ? resolve(ROOT, spec.slice(1))
+ : resolveLocal(html, spec);
+ if (abs && existsSync(abs)) out.push([abs, label]);
}
- if (!spec.startsWith('.')) continue; // bare package — the bundler's problem, not ours
- const next = resolveLocal(file, spec);
- if (next) enqueue(next, file);
}
+ return out;
}
-if (!leaks.length) {
- console.log(`check:browser-graph — no Node-only imports reachable from ${parent.size} browser modules`);
- process.exit(0);
+// build.lib.entry in vite.config.js. Kept as a check, not a silent skip: if the
+// entry is ever renamed, this script must fail loudly rather than quietly stop
+// covering the CDN bundle.
+const LIB_ENTRY = resolve(ROOT, 'src/lib.js');
+if (!existsSync(LIB_ENTRY)) {
+ console.error(`check:browser-graph: lib entry ${relative(ROOT, LIB_ENTRY)} is missing.
+It is build.lib.entry in vite.config.js; update this script if it moved.`);
+ process.exit(1);
}
-// One report per (module, specifier); the shortest chain is the clearest.
-const byKey = new Map();
-for (const leak of leaks) {
- const key = `${relative(ROOT, leak.file)}::${leak.spec}`;
- const prev = byKey.get(key);
- if (!prev || leak.chain.length < prev.chain.length) byKey.set(key, leak);
+const TARGETS = [
+ { label: 'app (dist/)', seeds: htmlSeeds, inlineDynamic: false },
+ { label: 'lib (dist-lib/agent-3d.js)', seeds: () => [[LIB_ENTRY, 'build.lib.entry']], inlineDynamic: true },
+];
+
+const results = TARGETS.map((t) => ({ target: t, ...walk(t) }));
+const failures = results.filter((r) => r.leaks.length);
+
+if (!failures.length) {
+ const seen = new Set();
+ for (const r of results) for (const f of r.parent.keys()) seen.add(f);
+ console.log(`check:browser-graph: no Node-only imports reachable from ${seen.size} browser modules across ${TARGETS.length} targets`);
+ process.exit(0);
}
-console.error(`\ncheck:browser-graph — ${byKey.size} Node-only import(s) reachable from the browser bundle:\n`);
-for (const leak of byKey.values()) {
- console.error(` ${relative(ROOT, leak.file)} imports "${leak.spec}"`);
- console.error(` ${leak.chain.join('\n -> ')}\n`);
+for (const { target, leaks } of failures) {
+ // One report per (module, specifier); the shortest chain is the clearest.
+ const byKey = new Map();
+ for (const leak of leaks) {
+ const key = `${relative(ROOT, leak.file)}::${leak.spec}`;
+ const prev = byKey.get(key);
+ if (!prev || leak.chain.length < prev.chain.length) byKey.set(key, leak);
+ }
+
+ console.error(`\ncheck:browser-graph: ${byKey.size} Node-only import(s) reachable from the ${target.label} bundle:\n`);
+ for (const leak of byKey.values()) {
+ console.error(` ${relative(ROOT, leak.file)} imports "${leak.spec}"`);
+ console.error(` ${leak.chain.join('\n -> ')}\n`);
+ }
+ if (target.inlineDynamic) {
+ console.error(` (this target inlines dynamic imports, so a server-only \`import()\`
+ behind a window check counts here even though the app target tolerates it)\n`);
+ }
}
-console.error(`This breaks \`npm run build\` (rollup resolves the built-in to
-__vite-browser-external and fails on its named exports) — and it fails AFTER the
-vite step has wiped dist/.
+
+console.error(`This breaks the build (rollup resolves the built-in to
+__vite-browser-external and fails on its named exports), and for the app target
+it fails AFTER the vite step has wiped dist/.
Fix at the boundary, not with a polyfill: load the server-only module lazily
behind a server check, so the browser keeps correct local-only behaviour.
@@ -192,5 +255,12 @@ behind a server check, so the browser keeps correct local-only behaviour.
if (!_mod) _mod = import('./server-only.js').catch(() => null);
return _mod;
}
+
+If the leak is in the lib graph, that is not enough on its own: the specifier
+must also be unreadable to rollup, because inlineDynamicImports follows a
+literal one anyway. Build it at runtime, as src/shared/failover-fetch.js does:
+
+ const SPEC = ['.', 'server-only.js'].join('/');
+ _mod = import(/* @vite-ignore */ SPEC).catch(() => null);
`);
process.exit(1);
diff --git a/src/shared/failover-fetch.js b/src/shared/failover-fetch.js
index a15308fca..0272ce400 100644
--- a/src/shared/failover-fetch.js
+++ b/src/shared/failover-fetch.js
@@ -38,11 +38,22 @@ let _brownoutPromise;
// here would let a record arrive after its own response had already gone out.
// That is not a lost log line, it is a trace that omits the rung that answered.
let _brownoutMod = null;
+// The specifier is assembled at runtime instead of written as a literal, and it
+// has to stay that way. The CDN lib target builds with
+// `rollupOptions.output.inlineDynamicImports` (vite.config.js), which flattens
+// EVERY dynamic import into the single bundle. That turns this server-only
+// branch into a static edge, and the build dies on
+// `"AsyncLocalStorage" is not exported by "__vite-browser-external"` even though
+// the guard above means a browser never evaluates it. Rollup resolves a string
+// literal here regardless of @vite-ignore, and constant-folds a `const` holding
+// one, so the path is joined from parts: an expression no optimizer folds.
+// Node resolves it relative to this module, which is what the server needs.
+const BROWNOUT_SPECIFIER = ['..', '..', 'api', '_lib', 'brownout', 'index.js'].join('/');
function brownout() {
if (_brownoutPromise !== undefined) return _brownoutPromise;
_brownoutPromise = null;
if (typeof window === 'undefined') {
- _brownoutPromise = import('../../api/_lib/brownout/index.js')
+ _brownoutPromise = import(/* @vite-ignore */ BROWNOUT_SPECIFIER)
.then((m) => {
_brownoutMod = m;
return m;