Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
170 changes: 170 additions & 0 deletions apps/cli/__tests__/preview/missing-imports-bundle-health.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
/**
* Owner's codespace, 2026-11-23: a Remix export imported `expo-clipboard` / `expo-sqlite` without
* declaring them (the players supply them), Metro answered the bundle with a 500 and the Preview
* was a white page announced as ready. The CLI now installs what the app imports, and a build
* error is a `preview_error` with Metro's text.
*/
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import * as http from 'node:http';
import type { AddressInfo } from 'node:net';
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import {
aliasPrefixes,
expoInstallCommand,
findMissingImports,
importSpecifiers,
packageOf,
} from '../../src/services/preview/missing-imports';
import {
addPreviewGitExcludes,
bundleErrorText,
checkAppBundle,
entryScriptOf,
} from '../../src/services/preview/bundle-health';

let dir: string;
const write = (rel: string, content: unknown): void => {
const file = path.join(dir, rel);
mkdirSync(path.dirname(file), { recursive: true });
writeFileSync(file, typeof content === 'string' ? content : JSON.stringify(content));
};
beforeEach(() => {
dir = mkdtempSync(path.join(tmpdir(), 'missing-imports-'));
});
afterEach(() => rmSync(dir, { recursive: true, force: true }));

describe('import scan', () => {
it('finds static, side-effect, dynamic and require imports, not commented ones', () => {
const src = [
"import * as Clipboard from 'expo-clipboard';",
"import { Storage } from 'expo-sqlite/kv-store';",
"import 'react-native-gesture-handler';",
"export { x } from './local';",
"const m = await import('@scope/pkg/sub');",
"const r = require('lodash');",
"// import nope from 'commented-out';",
"/* import alsoNope from 'block-commented'; */",
"const url = 'https://example.com/x';",
].join('\n');
expect(importSpecifiers(src).sort()).toEqual(
['./local', '@scope/pkg/sub', 'expo-clipboard', 'expo-sqlite/kv-store', 'lodash', 'react-native-gesture-handler'].sort(),
);
});
it('maps a specifier to its package, skipping relative, built-ins, aliases and invalid names', () => {
expect(packageOf('expo-sqlite/kv-store', [])).toBe('expo-sqlite');
expect(packageOf('@react-navigation/native/lib', [])).toBe('@react-navigation/native');
expect(packageOf('./x', [])).toBeNull();
expect(packageOf('fs', [])).toBeNull();
expect(packageOf('node:path', [])).toBeNull();
expect(packageOf('@/components/Button', ['@'])).toBeNull();
expect(packageOf('~/lib', [])).toBeNull(); // not an npm name
expect(packageOf('components/Button', ['components'])).toBeNull();
});
it('reads aliases from tsconfig paths (with comments) and babel module-resolver', () => {
write('tsconfig.json', '{ // comment\n "compilerOptions": { "paths": { "@app/*": ["src/*"], "ui": ["src/ui"] } }, }');
write('babel.config.js', "module.exports = { plugins: [['module-resolver', { alias: { 'components': './src/components', '@lib': './lib' } }]] };");
expect(aliasPrefixes(dir).sort()).toEqual(['@app', '@lib', 'components', 'ui'].sort());
});
it('lists packages neither declared nor installed, outside server/ and node_modules', () => {
write('package.json', { dependencies: { expo: '~54.0.0', react: '19.1.0' } });
write('App.tsx', "import React from 'react';\nimport { Text } from 'react-native';\nimport * as C from 'expo-clipboard';");
write('src/db.ts', "import { Storage } from 'expo-sqlite/kv-store';\nimport x from '@app/thing';");
write('tsconfig.json', { compilerOptions: { paths: { '@app/*': ['src/*'] } } });
write('server/index.ts', "import { Hono } from 'hono';");
write('node_modules/react-native/package.json', { name: 'react-native' });
write('node_modules/some-dep/index.js', "require('not-mine');");
expect(findMissingImports(dir)).toEqual(['expo-clipboard', 'expo-sqlite']);
});
it('installs through the project expo binary with --legacy-peer-deps', () => {
expect(expoInstallCommand(dir, ['expo-clipboard']).args).toEqual([
'--yes', 'expo', 'install', 'expo-clipboard', '--', '--legacy-peer-deps',
]);
write('node_modules/.bin/expo', '#!/bin/sh');
expect(expoInstallCommand(dir, ['a', 'b'])).toEqual({
cmd: path.join(dir, 'node_modules', '.bin', 'expo'),
args: ['install', 'a', 'b', '--', '--legacy-peer-deps'],
});
});
});

describe('bundle health', () => {
it('finds Metro bundles and Vite module entries in the page', () => {
expect(entryScriptOf('<script src="/index.bundle?platform=web&dev=true" defer></script>')).toBe(
'/index.bundle?platform=web&dev=true',
);
expect(
entryScriptOf('<script type="module" src="/@vite/client"></script><script type="module" src="./src/main.tsx"></script>'),
).toBe('./src/main.tsx');
expect(entryScriptOf('<script src="/static/app.js"></script>')).toBeNull();
});
it("reads Metro's JSON error message", () => {
const body = JSON.stringify({
type: 'UnableToResolveError',
message: '\u001b[31mUnable to resolve module expo-clipboard from src/screens/parent/FamilyScreen.tsx\u001b[39m',
});
expect(bundleErrorText(body)).toBe('Unable to resolve module expo-clipboard from src/screens/parent/FamilyScreen.tsx');
});

const serve = (handler: http.RequestListener): Promise<http.Server> =>
new Promise((resolve) => {
const s = http.createServer(handler);
s.listen(0, '127.0.0.1', () => resolve(s));
});
const portOf = (s: http.Server): number => (s.address() as AddressInfo).port;

it('a bundle 500 is a failure with the build text; a 200 is ok', async () => {
let broken = true;
const metro = await serve((req, res) => {
if (req.url === '/') {
res.writeHead(200, { 'content-type': 'text/html' });
res.end('<html><script src="/index.bundle?platform=web"></script></html>');
} else if (broken) {
res.writeHead(500, { 'content-type': 'application/json' });
res.end(JSON.stringify({ message: 'Unable to resolve module expo-clipboard' }));
} else {
res.writeHead(200, { 'content-type': 'application/javascript' });
res.end('var a=1');
}
});
try {
expect(await checkAppBundle(portOf(metro))).toEqual({
ok: false,
status: 500,
error: 'Unable to resolve module expo-clipboard',
});
broken = false;
expect(await checkAppBundle(portOf(metro))).toEqual({ ok: true });
} finally {
metro.close();
}
});
it('a slow bundle is inconclusive, never a failure', async () => {
const metro = await serve((req, res) => {
if (req.url === '/') {
res.writeHead(200, { 'content-type': 'text/html' });
res.end('<script src="/index.bundle"></script>');
} else setTimeout(() => res.end('late'), 2_000);
});
try {
expect((await checkAppBundle(portOf(metro), { bundleTimeoutMs: 100 })).ok).toBe('unknown');
} finally {
metro.closeAllConnections();
metro.close();
}
});
});

describe('git exclude', () => {
it('adds our runtime paths once, keeping what the file had', () => {
const file = path.join(dir, '.git', 'info', 'exclude');
write('.git/info/exclude', '# git ls-files --others --exclude-from=.git/info/exclude\n*.local');
expect(addPreviewGitExcludes(file)).toBe(true);
expect(addPreviewGitExcludes(file)).toBe(false);
expect(readFileSync(file, 'utf8')).toBe(
'# git ls-files --others --exclude-from=.git/info/exclude\n*.local\n' +
'# CodeAgent preview runtime files\n/.wrangler/\n/.codeam/*\n!/.codeam/preview.json\n',
);
});
});
123 changes: 123 additions & 0 deletions apps/cli/src/services/preview/bundle-health.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
import { execFile } from 'child_process';
import * as fs from 'fs';
import * as path from 'path';

/**
* Does the app actually BUILD? A dev server can answer `/` with 200 while the app's own code
* can't be bundled: Metro serves the HTML shell and then answers the bundle with a 500
* ("Unable to resolve module expo-clipboard", owner's codespace 2026-11-23), and the Preview
* showed a white page with nothing in the panel. This asks for the page the way a browser does,
* then for its entry script (Metro's `*.bundle`, Vite's module entry), and returns the build
* error's own text when there is one.
*/

export type BundleHealth =
| { ok: true }
| { ok: false; status: number | null; error: string }
| { ok: 'unknown'; reason: string };

/** The app's entry script in a served HTML page: Metro's bundle, else Vite's module entry. */
export function entryScriptOf(html: string): string | null {
const scripts = [...html.matchAll(/<script\b[^>]*\bsrc=["']([^"']+)["'][^>]*>/gi)].map((m) => ({
src: m[1],
tag: m[0],
}));
const bundle = scripts.find((s) => /\.bundle(?:\?|$)/.test(s.src));
if (bundle) return bundle.src;
const mod = scripts.find((s) => /type=["']module["']/i.test(s.tag) && !s.src.includes('/@vite/client'));
return mod ? mod.src : null;
}

const ANSI_RE = /\u001b\[[0-9;]*[A-Za-z]/g;

/** The readable error in a failed bundle response: Metro's JSON `message`, else the text. */
export function bundleErrorText(body: string): string {
let text = body;
try {
const parsed = JSON.parse(body) as { message?: unknown; type?: unknown };
if (typeof parsed.message === 'string') text = parsed.message;
} catch {
/* not JSON: plain text / HTML */
}
return text.replace(ANSI_RE, '').replace(/<[^>]+>/g, ' ').replace(/\n{3,}/g, '\n\n').trim().slice(0, 1_500);
}

async function get(
url: string,
timeoutMs: number,
headers: Record<string, string> = {},
): Promise<{ status: number; body: string } | 'timeout' | 'error'> {
const ac = new AbortController();
const timer = setTimeout(() => ac.abort(), timeoutMs);
try {
const res = await fetch(url, { headers, signal: ac.signal, redirect: 'follow' });
return { status: res.status, body: await res.text() };
} catch {
return ac.signal.aborted ? 'timeout' : 'error';
} finally {
clearTimeout(timer);
}
}

/**
* Page, then its entry script, on the local dev server. A first Metro build of a big app takes a
* while, so the bundle gets `bundleTimeoutMs`; running out of time is `unknown`, never a failure.
*/
export async function checkAppBundle(
port: number,
opts: { bundleTimeoutMs?: number; host?: string } = {},
): Promise<BundleHealth> {
const origin = `http://${opts.host ?? '127.0.0.1'}:${port}`;
const page = await get(`${origin}/`, 30_000, { Accept: 'text/html' });
if (page === 'timeout' || page === 'error') return { ok: 'unknown', reason: `page ${page}` };
if (page.status >= 500) return { ok: false, status: page.status, error: bundleErrorText(page.body) };
const entry = entryScriptOf(page.body);
if (!entry) return { ok: 'unknown', reason: 'no entry script in the page' };
const url = new URL(entry, `${origin}/`);
if (url.origin !== origin) return { ok: 'unknown', reason: 'entry script on another origin' };
const bundle = await get(url.toString(), opts.bundleTimeoutMs ?? 240_000);
if (bundle === 'timeout' || bundle === 'error') return { ok: 'unknown', reason: `bundle ${bundle}` };
if (bundle.status >= 400) {
return { ok: false, status: bundle.status, error: bundleErrorText(bundle.body) };
}
return { ok: true };
}

/**
* Keep the preview's runtime files out of the user's `git status` (the change card counted 21
* files / +8788 lines of `.wrangler/` + `.codeam/`). Written to `.git/info/exclude` — never the
* user's `.gitignore` — and only once. A committed `.codeam/preview.json` stays visible.
*/
export const GIT_EXCLUDE_LINES = [
'# CodeAgent preview runtime files',
'/.wrangler/',
'/.codeam/*',
'!/.codeam/preview.json',
];

export function addPreviewGitExcludes(excludeFile: string): boolean {
let current = '';
try {
current = fs.readFileSync(excludeFile, 'utf8');
} catch {
/* no exclude file yet */
}
const have = new Set(current.split('\n').map((l) => l.trim()));
const missing = GIT_EXCLUDE_LINES.filter((l) => !have.has(l));
if (missing.length === 0 || (missing.length === 1 && missing[0].startsWith('#'))) return false;
fs.mkdirSync(path.dirname(excludeFile), { recursive: true });
const sep = current.length === 0 || current.endsWith('\n') ? '' : '\n';
fs.appendFileSync(excludeFile, `${sep}${missing.join('\n')}\n`);
return true;
}

/** `git rev-parse --git-path info/exclude` for `cwd`; null outside a git repo. */
export function gitExcludePath(cwd: string): Promise<string | null> {
return new Promise((resolve) => {
execFile('git', ['rev-parse', '--git-path', 'info/exclude'], { cwd, timeout: 5_000 }, (err, out) => {
if (err) return resolve(null);
const p = out.trim();
resolve(p ? path.resolve(cwd, p) : null);
});
});
}
2 changes: 2 additions & 0 deletions apps/cli/src/services/preview/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ export * from './setup-deps';
export * from './script-candidates';
export * from './known-project';
export * from './remix-app-server';
export * from './missing-imports';
export * from './bundle-health';
export * from './prewarm-deps';
export * from './tunnel-bringup';
export * from './port-registry';
Expand Down
Loading
Loading