Skip to content

Commit 8e33b05

Browse files
fix(mobile): catch platform-hidden type cycles in dependency guard
Review of #13151 found the dependency-graph guard resolved `./X` to the generic `.tsx` before the `.android.tsx` variant, hiding a real Android cycle: `ThemedSwitch` imports `MaterialSwitch` (which resolves to the `.android.tsx` variant on Android) while that variant type-imports `ThemedSwitchProps` back from `ThemedSwitch`. - Extract `ThemedSwitchProps` to `components/MaterialSwitch.types.ts`; `ThemedSwitch` re-exports it, the Android variant imports from the types module. Acyclic under any resolution order. - The guard now models Metro's per-platform resolution (platform ext before `.native` before generic, and each platform's graph excludes the other platform's variant files) and asserts zero circular static imports under both iOS and Android resolution. Verified against the seeded Android-only cycle the review described. - Ceiling counts now dedupe unique `from -> to` module pairs across both platforms (same numbers as before: 6/7/33/8/11). Done by callstack/Apex in pi.
1 parent 3597143 commit 8e33b05

4 files changed

Lines changed: 129 additions & 85 deletions

File tree

‎apps/mobile/src/components/MaterialSwitch.android.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { Host, Switch as ComposeSwitch } from "@expo/ui/jetpack-compose";
22
import { View } from "react-native";
3-
import type { ThemedSwitchProps } from "./ThemedSwitch";
3+
import type { ThemedSwitchProps } from "./MaterialSwitch.types";
44

55
import { useAppearancePreferences } from "../features/settings/appearance/AppearancePreferencesProvider";
66

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import type { SwitchProps } from "react-native";
2+
3+
export type ThemedSwitchProps = Pick<
4+
SwitchProps,
5+
| "accessibilityHint"
6+
| "accessibilityLabel"
7+
| "disabled"
8+
| "onValueChange"
9+
| "style"
10+
| "testID"
11+
| "value"
12+
>;

‎apps/mobile/src/components/ThemedSwitch.tsx‎

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,9 @@
1-
import { Platform, Switch, type SwitchProps } from "react-native";
1+
import { Platform, Switch } from "react-native";
22

33
import { MaterialSwitch } from "./MaterialSwitch";
4+
import type { ThemedSwitchProps } from "./MaterialSwitch.types";
45

5-
export type ThemedSwitchProps = Pick<
6-
SwitchProps,
7-
| "accessibilityHint"
8-
| "accessibilityLabel"
9-
| "disabled"
10-
| "onValueChange"
11-
| "style"
12-
| "testID"
13-
| "value"
14-
>;
6+
export type { ThemedSwitchProps } from "./MaterialSwitch.types";
157

168
export function ThemedSwitch(props: ThemedSwitchProps) {
179
if (Platform.OS === "android") {

‎apps/mobile/src/dependency-graph.test.ts‎

Lines changed: 113 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -5,40 +5,51 @@ import { describe, expect, it } from "vite-plus/test";
55
/**
66
* Dependency-graph guards for the mobile source tree (audit #13).
77
*
8-
* 1. No circular imports. Cycles were the source of module-init hazards and
9-
* made the state/lib/features boundaries unmaintainable; shared shapes now
10-
* live in `.types.ts` modules (e.g. `ConfirmDialog.types.ts`) and the
11-
* composer preview-retention lease lives in `lib/`.
12-
* Dynamic `import("...")` calls are excluded on purpose: they are the
13-
* deliberate async escape hatch (e.g. composer-draft cleanup reaching
14-
* `lib/attachmentUpload`), and Metro resolves them after both modules have
15-
* initialized, so they cannot create an initialization cycle.
8+
* 1. No circular imports, checked once per platform the way Metro resolves
9+
* modules (`<name>.<platform>.*` before `<name>.native.*` before the
10+
* generic file). A cycle can hide behind platform resolution: a `.tsx`
11+
* base importing a component whose `.android.tsx` variant type-imports
12+
* back into the base is acyclic on iOS but circular on Android.
13+
* Dynamic `import("...")` calls are excluded from this rule on purpose:
14+
* they are the deliberate async escape hatch (e.g. composer-draft cleanup
15+
* reaching `lib/attachmentUpload`), and Metro resolves them after both
16+
* modules have initialized, so they cannot create an initialization cycle.
1617
*
1718
* 2. Cross-layer edges are ceilinged, not yet banned. `state`, `lib`,
1819
* `native`, and `components` still reach upward into `features` at known
1920
* sites (the app composition root `lib/runtime.ts` legitimately wires
20-
* feature layers). The ceiling may only shrink: when you remove one of
21-
* these imports, lower the constant in the same PR.
21+
* feature layers). Ceilings count unique `from -> to` module pairs across
22+
* all platforms, including dynamic imports, and may only shrink: when you
23+
* remove one of these imports, lower the constant in the same PR.
2224
*/
2325

2426
const SOURCE_ROOT = __dirname;
2527

26-
/** Metro-style resolution order for relative specifiers. */
27-
const RESOLVE_CANDIDATES = [
28-
".ts",
29-
".tsx",
30-
".ios.ts",
31-
".ios.tsx",
32-
".android.ts",
33-
".android.tsx",
34-
] as const;
28+
/** Metro candidate order per platform (platform, then native, then generic). */
29+
const PLATFORM_EXTENSION_ORDER = {
30+
android: [".android.ts", ".android.tsx", ".native.ts", ".native.tsx", ".ts", ".tsx"],
31+
ios: [".ios.ts", ".ios.tsx", ".native.ts", ".native.tsx", ".ts", ".tsx"],
32+
} as const;
33+
34+
type Platform = keyof typeof PLATFORM_EXTENSION_ORDER;
35+
36+
const PLATFORMS = Object.keys(PLATFORM_EXTENSION_ORDER) as ReadonlyArray<Platform>;
3537

3638
const isGraphFile = (filePath: string): boolean =>
3739
/\.tsx?$/.test(filePath) &&
3840
!filePath.includes(".test.") &&
3941
!filePath.includes("test-support") &&
4042
!filePath.endsWith(".d.ts");
4143

44+
/** Files Metro would not even bundle for the other platform. */
45+
function isRelevantForPlatform(filePath: string, platform: Platform): boolean {
46+
const name = NodePath.basename(filePath);
47+
if (platform === "android") {
48+
return !name.includes(".ios.");
49+
}
50+
return !name.includes(".android.");
51+
}
52+
4253
function collectSourceFiles(dir: string, out: string[] = []): string[] {
4354
for (const entry of NodeFS.readdirSync(dir)) {
4455
const filePath = NodePath.join(dir, entry);
@@ -51,22 +62,25 @@ function collectSourceFiles(dir: string, out: string[] = []): string[] {
5162
return out;
5263
}
5364

54-
function resolveRelative(fromFile: string, specifier: string): string | null {
65+
function resolveRelative(
66+
fromFile: string,
67+
specifier: string,
68+
extensionOrder: ReadonlyArray<string>,
69+
): string | null {
5570
if (!specifier.startsWith(".")) {
5671
return null;
5772
}
5873
const base = NodePath.resolve(NodePath.dirname(fromFile), specifier);
59-
for (const candidate of [
60-
...RESOLVE_CANDIDATES.map((ext) => base + ext),
61-
...RESOLVE_CANDIDATES.map((ext) => NodePath.join(base, `index${ext}`)),
62-
]) {
63-
try {
64-
if (NodeFS.statSync(candidate).isFile()) {
65-
const resolved = NodePath.resolve(candidate);
66-
return resolved.startsWith(SOURCE_ROOT + NodePath.sep) ? resolved : null;
74+
for (const ext of extensionOrder) {
75+
for (const candidate of [base + ext, NodePath.join(base, `index${ext}`)]) {
76+
try {
77+
if (NodeFS.statSync(candidate).isFile()) {
78+
const resolved = NodePath.resolve(candidate);
79+
return resolved.startsWith(SOURCE_ROOT + NodePath.sep) ? resolved : null;
80+
}
81+
} catch {
82+
// Candidate does not exist; try the next one.
6783
}
68-
} catch {
69-
// Candidate does not exist; try the next one.
7084
}
7185
}
7286
return null;
@@ -104,88 +118,103 @@ function layerOf(relativePath: string): Layer {
104118
: "other";
105119
}
106120

107-
interface Graph {
121+
interface PlatformGraph {
122+
readonly platform: Platform;
108123
readonly files: ReadonlyArray<string>;
109124
/** Static (type or value) import edges keyed by source file. */
110125
readonly staticEdges: ReadonlyMap<string, ReadonlyArray<string>>;
111-
/** Every cross-layer edge, static and dynamic, as "fromRel -> toRel". */
112-
readonly crossLayerEdges: ReadonlyArray<string>;
126+
/** Unique cross-layer edges, static and dynamic, as "fromRel -> toRel". */
127+
readonly crossLayerEdges: ReadonlySet<string>;
113128
}
114129

115-
function buildGraph(): Graph {
116-
const files = collectSourceFiles(SOURCE_ROOT).sort();
130+
function buildPlatformGraph(platform: Platform): PlatformGraph {
131+
const extensionOrder = PLATFORM_EXTENSION_ORDER[platform];
132+
const files = collectSourceFiles(SOURCE_ROOT)
133+
.filter((file) => isRelevantForPlatform(file, platform))
134+
.sort();
117135
const staticEdges = new Map<string, string[]>();
118-
const crossLayerEdges: string[] = [];
136+
const crossLayerEdges = new Set<string>();
119137
for (const file of files) {
120138
const targets = new Set<string>();
121139
for (const { specifier, isDynamic } of parseImports(NodeFS.readFileSync(file, "utf8"))) {
122-
const resolved = resolveRelative(file, specifier);
140+
const resolved = resolveRelative(file, specifier, extensionOrder);
123141
if (resolved === null || resolved === file) {
124142
continue;
125143
}
126-
crossLayerEdges.push(
127-
`${NodePath.relative(SOURCE_ROOT, file)} -> ${NodePath.relative(SOURCE_ROOT, resolved)}`,
128-
);
144+
const from = NodePath.relative(SOURCE_ROOT, file);
145+
const to = NodePath.relative(SOURCE_ROOT, resolved);
146+
const fromLayer = layerOf(from);
147+
const toLayer = layerOf(to);
148+
const upward =
149+
(fromLayer === "state" ||
150+
fromLayer === "lib" ||
151+
fromLayer === "components" ||
152+
fromLayer === "native") &&
153+
(toLayer === "features" || (fromLayer === "lib" && toLayer === "state"));
154+
if (upward) {
155+
crossLayerEdges.add(`${from} -> ${to}`);
156+
}
129157
if (!isDynamic) {
130158
targets.add(resolved);
131159
}
132160
}
133161
staticEdges.set(file, [...targets]);
134162
}
135-
return { files, staticEdges, crossLayerEdges };
163+
return { platform, files, staticEdges, crossLayerEdges };
136164
}
137165

138166
/** Tarjan strongly-connected components, iterative to bound stack depth. */
139-
function findCycles(graph: Graph): ReadonlyArray<ReadonlyArray<string>> {
167+
function findCycles(graph: PlatformGraph): ReadonlyArray<ReadonlyArray<string>> {
140168
const index = new Map<string, number>();
141169
const low = new Map<string, number>();
142170
const onStack = new Set<string>();
143171
const stack: string[] = [];
144172
const cycles: string[][] = [];
145173
let nextIndex = 0;
146174

175+
const enter = (node: string): void => {
176+
index.set(node, nextIndex);
177+
low.set(node, nextIndex);
178+
nextIndex += 1;
179+
stack.push(node);
180+
onStack.add(node);
181+
};
182+
147183
for (const root of graph.files) {
148184
if (index.has(root)) continue;
149-
const work: Array<readonly [string, number]> = [[root, 0]];
150-
const enter = (node: string): void => {
151-
index.set(node, nextIndex);
152-
low.set(node, nextIndex);
153-
nextIndex += 1;
154-
stack.push(node);
155-
onStack.add(node);
156-
};
185+
const work: Array<[string, number]> = [[root, 0]];
157186
enter(root);
158187
while (work.length > 0) {
159-
const [node, edge] = work[work.length - 1]!;
160-
const neighbors = graph.staticEdges.get(node) ?? [];
188+
const frame = work[work.length - 1]!;
189+
const neighbors = graph.staticEdges.get(frame[0]) ?? [];
161190
let advanced = false;
162-
for (let i = edge; i < neighbors.length; i += 1) {
191+
for (let i = frame[1]; i < neighbors.length; i += 1) {
163192
const child = neighbors[i]!;
164193
if (!graph.staticEdges.has(child)) continue;
165194
if (!index.has(child)) {
166-
work[work.length - 1] = [node, i + 1];
195+
work[work.length - 1] = [frame[0], i + 1];
167196
work.push([child, 0]);
168197
enter(child);
169198
advanced = true;
170199
break;
171200
} else if (onStack.has(child)) {
172-
low.set(node, Math.min(low.get(node)!, index.get(child)!));
201+
low.set(frame[0], Math.min(low.get(frame[0])!, index.get(child)!));
173202
}
174203
}
175204
if (advanced) continue;
176205
work.pop();
177206
const parent = work[work.length - 1];
178207
if (parent) {
179-
low.set(parent[0], Math.min(low.get(parent[0])!, low.get(node)!));
208+
low.set(parent[0], Math.min(low.get(parent[0])!, low.get(frame[0])!));
180209
}
181-
if (low.get(node) === index.get(node)) {
210+
if (low.get(frame[0]) === index.get(frame[0])) {
182211
const component: string[] = [];
183212
let member: string;
184213
do {
185214
member = stack.pop()!;
186215
onStack.delete(member);
187216
component.push(member);
188-
} while (member !== node);
217+
} while (member !== frame[0]);
189218
if (component.length > 1) {
190219
cycles.push(component.sort().map((file) => NodePath.relative(SOURCE_ROOT, file)));
191220
}
@@ -195,24 +224,35 @@ function findCycles(graph: Graph): ReadonlyArray<ReadonlyArray<string>> {
195224
return cycles;
196225
}
197226

198-
const graph = buildGraph();
199-
const edgesBetween = (from: Layer, to: Layer): string[] =>
200-
graph.crossLayerEdges
201-
.filter((edge) => {
202-
const [source, target] = edge.split(" -> ");
203-
return layerOf(source!) === from && layerOf(target!) === to;
204-
})
205-
.sort();
227+
const graphs = PLATFORMS.map(buildPlatformGraph);
228+
229+
/** Unique upward edge pairs across every platform, sorted for stable diffs. */
230+
function upwardEdges(): string[] {
231+
const union = new Set<string>();
232+
for (const graph of graphs) {
233+
for (const edge of graph.crossLayerEdges) {
234+
union.add(edge);
235+
}
236+
}
237+
return [...union].sort();
238+
}
206239

207240
describe("mobile dependency graph", () => {
208-
it("has no circular imports among source modules", () => {
241+
it.each(PLATFORMS)("has no circular imports under %s resolution", (platform) => {
242+
const graph = graphs.find((candidate) => candidate.platform === platform)!;
243+
// The graph must see real files; a resolution regression here would make
244+
// both rules vacuously pass.
245+
expect(graph.files.length).toBeGreaterThan(500);
209246
expect(findCycles(graph)).toEqual([]);
210247
});
211248

212249
it("keeps upward imports from state/lib/components/native into features at the ceiling", () => {
213-
// The graph must see real files; a resolution regression here would make
214-
// every ceiling vacuously pass.
215-
expect(graph.files.length).toBeGreaterThan(400);
250+
const edges = upwardEdges();
251+
const edgesFor = (from: Layer, to: Layer): string[] =>
252+
edges.filter((edge) => {
253+
const [source, target] = edge.split(" -> ");
254+
return layerOf(source!) === from && layerOf(target!) === to;
255+
});
216256

217257
const ceilings: ReadonlyArray<readonly [Layer, Layer, number, string]> = [
218258
// state -> features: thread ordering reaching the thread-list model,
@@ -235,10 +275,10 @@ describe("mobile dependency graph", () => {
235275
];
236276

237277
for (const [from, to, ceiling, message] of ceilings) {
238-
const edges = edgesBetween(from, to);
278+
const layerEdges = edgesFor(from, to);
239279
expect(
240-
edges.length,
241-
`${message}. ${edges.length} edges remain:\n${edges.join("\n")}`,
280+
layerEdges.length,
281+
`${message}. ${layerEdges.length} edges remain:\n${layerEdges.join("\n")}`,
242282
).toBeLessThanOrEqual(ceiling);
243283
}
244284
});

0 commit comments

Comments
 (0)