Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - compiles real source files on disk.
2import * as NodeFS from "node:fs";
3import * as NodeModule from "node:module";
4import * as NodePath from "node:path";
5import { describe, expect, it } from "vite-plus/test";
6
7const mobileRoot = NodePath.resolve(__dirname, "..");
8const requireFromMobile = NodeModule.createRequire(NodePath.join(mobileRoot, "package.json"));
9const babel: {
10 transformFileSync: (file: string, options: Record<string, unknown>) => unknown;
11} = requireFromMobile("@babel/core");
12const metroConfig: Promise<{ transformer: { babelTransformerPath: string } }> =
13 requireFromMobile("./metro.config.js");
14
15// Files the compiler skips today. A skipped file still ships, just unmemoized.
16// This list only shrinks: the test fails when a file here starts compiling, so
17// delete its entry (and its manual useMemo/useCallback/memo) in the same change.
18const KNOWN_BAILOUTS: Record<string, string> = {
19 "src/components/ComposerAttachmentStrip.tsx": "unsupported syntax",
20 "src/components/ui/AndroidAnchoredMenu.tsx": "ref read during render",
21 "src/components/ui/Menu.tsx": "ref read during render",
22 "src/features/diffs/nativeReviewDiffSurface.ts": "ref read during render",
23 "src/features/home/thread-swipe-actions.tsx": "ref read during render",
24 "src/features/terminal/ThreadTerminalRouteScreen.tsx": "ref read during render",
25 "src/features/threads/PendingUserInputCard.tsx": "mutates a frozen value",
26 "src/features/threads/ThreadArrangementSheet.tsx": "ref read during render",
27 "src/features/voice-input/VoiceInputProvider.tsx": "ref read during render",
28 "src/features/voice-input/useVoiceInputController.ts": "ref read during render",
29 "src/native/StackHeader.tsx": "ref read during render",
30 "src/native/T3ComposerEditor.ios.tsx": "ref read during render",
31 "src/native/T3ComposerEditor.native.tsx": "ref read during render",
32};
33
34// Caller flags Metro passes for an iOS release bundle. supportsReactCompiler is
35// what `experiments.reactCompiler` in app.config.ts turns on.
36const metroCaller = {
37 name: "metro",
38 bundler: "metro",
39 platform: "ios",
40 isDev: false,
41 isServer: false,
42 isNodeModule: false,
43 supportsStaticESM: true,
44 supportsReactCompiler: true,
45};
46
47const sourceFiles = NodeFS.readdirSync(NodePath.join(mobileRoot, "src"), { recursive: true })
48 .map(String)
49 .filter((file) => /\.tsx?$/.test(file) && !/\.(test\.tsx?|d\.ts)$/.test(file))
50 .map((file) => `src/${file.split(NodePath.sep).join("/")}`)
51 .sort();
52
53type CompilerLoc = { readonly start?: { readonly line?: number } } | null;
54
55interface CompilerEvent {
56 readonly kind: string;
57 readonly detail?: {
58 readonly options?: {
59 readonly category?: string;
60 readonly reason?: string;
61 readonly loc?: CompilerLoc;
62 readonly details?: readonly { readonly loc?: CompilerLoc }[];
63 };
64 };
65}
66
67// babel.config.js is the file Metro loads; the logger rides on the preset's
68// own react-compiler option so the plugin runs with Metro's exact settings.
69function compileLikeMetro(file: string, events: CompilerEvent[], output: Record<string, unknown>) {
70 const babelConfig = requireFromMobile("./babel.config.js")({ cache: () => {} });
71 const presets = babelConfig.presets.map(([name, options]: [string, object]) =>
72 name === "babel-preset-expo"
73 ? [
74 requireFromMobile.resolve(name),
75 {
76 ...options,
77 "react-compiler": {
78 logger: { logEvent: (_: string, event: CompilerEvent) => events.push(event) },
79 },
80 },
81 ]
82 : [name, options],
83 );
84 return babel.transformFileSync(NodePath.join(mobileRoot, file), {
85 babelrc: false,
86 configFile: false,
87 cwd: mobileRoot,
88 presets,
89 caller: metroCaller,
90 code: false,
91 ...output,
92 });
93}
94
95function compilerBailouts(file: string): string[] {
96 const events: CompilerEvent[] = [];
97 compileLikeMetro(file, events, {});
98 return events
99 .filter((event) => event.kind === "CompileError" || event.kind === "CompileSkip")
100 .map(
101 (event) =>
102 `line ${(event.detail?.options?.loc ?? event.detail?.options?.details?.[0]?.loc)?.start?.line ?? "?"}: ${event.detail?.options?.category ?? event.kind} ${event.detail?.options?.reason ?? ""}`,
103 );
104}
105
106interface AstNode {
107 readonly type: string;
108 readonly [key: string]: unknown;
109}
110
111const isAstNode = (value: unknown): value is AstNode =>
112 typeof value === "object" && value !== null && "type" in value && typeof value.type === "string";
113
114function walkAst(
115 value: unknown,
116 visit: (node: AstNode, ancestors: readonly AstNode[]) => void,
117 ancestors: readonly AstNode[] = [],
118) {
119 if (typeof value !== "object" || value === null) return;
120 const node = isAstNode(value) ? value : null;
121 if (node) visit(node, ancestors);
122 const childAncestors = node ? [...ancestors, node] : ancestors;
123 for (const child of Object.values(value)) walkAst(child, visit, childAncestors);
124}
125
126// For each call to `callee`, whether it runs only on the cache-miss branch of
127// an `if ($[n] !== dep)` block rather than on every render.
128function compilerCachedCalls(file: string, callee: string): boolean[] {
129 const result = compileLikeMetro(file, [], { ast: true });
130 const cached: boolean[] = [];
131 if (typeof result !== "object" || result === null || !("ast" in result)) return cached;
132 walkAst(result.ast, (node, ancestors) => {
133 if (node.type !== "CallExpression" || !isAstNode(node.callee)) return;
134 if (node.callee.type !== "Identifier" || node.callee.name !== callee) return;
135 cached.push(
136 ancestors.some(
137 (ancestor, index) =>
138 ancestor.type === "IfStatement" &&
139 ancestors[index + 1] === ancestor.consequent &&
140 JSON.stringify(ancestor.test).includes('"name":"$"'),
141 ),
142 );
143 });
144 return cached;
145}
146
147describe("React Compiler coverage", () => {
148 it("Metro's transformer applies the compiler", async () => {
149 const { transformer } = await metroConfig;
150 const metroTransformer = requireFromMobile(transformer.babelTransformerPath);
151 const filename = NodePath.join(
152 mobileRoot,
153 "src/features/archive/ArchivedThreadsRouteScreen.tsx",
154 );
155 const transformed = (reactCompiler: string) => {
156 const { ast } = metroTransformer.transform({
157 filename,
158 src: NodeFS.readFileSync(filename, "utf8"),
159 plugins: [],
160 options: {
161 dev: false,
162 hot: false,
163 platform: "ios",
164 projectRoot: mobileRoot,
165 type: "module",
166 enableBabelRCLookup: false,
167 experimentalImportSupport: false,
168 customTransformOptions: { reactCompiler, routerRoot: "app" },
169 },
170 });
171 return JSON.stringify(ast.program.body);
172 };
173 expect(transformed("true")).toContain("react/compiler-runtime");
174 expect(transformed("false")).not.toContain("react/compiler-runtime");
175 });
176
177 it.each(sourceFiles)("compiles %s", (file) => {
178 const bailouts = compilerBailouts(file);
179 if (file in KNOWN_BAILOUTS) {
180 expect(bailouts, `${file} compiles now; remove it from KNOWN_BAILOUTS`).not.toEqual([]);
181 } else {
182 expect(bailouts).toEqual([]);
183 }
184 });
185
186 // The compiler once silently dropped this cache, so every
187 // ThreadFeed render rebuilt the feed and handed LegendList a new data array.
188 it("caches the thread feed derivation", () => {
189 expect(
190 compilerCachedCalls("src/features/threads/ThreadFeed.tsx", "deriveThreadFeedPresentation"),
191 ).toEqual([true]);
192 });
193
194 it("lists only files that exist", () => {
195 expect(Object.keys(KNOWN_BAILOUTS).filter((file) => !sourceFiles.includes(file))).toEqual([]);
196 });
197});