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