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