Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

reactCompilerCoverage.test.ts

194 lines7.3 KB

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