Open History to see the last commit
1import * as NodeFS from "node:fs";
2import * as NodePath from "node:path";
3import { describe, expect, it } from "vite-plus/test";
4
5/**
6 * Dynamic `import("...")` calls are excluded from this rule on purpose:
7 * they are the deliberate async escape hatch (e.g. composer-draft cleanup
8 * reaching `lib/attachmentUpload`), and Metro resolves them after both
9 * modules have initialized, so they cannot create an initialization cycle.
10 */
11
12const SOURCE_ROOT = __dirname;
13
14const PLATFORM_EXTENSION_ORDER = {
15 android: [".android.ts", ".android.tsx", ".native.ts", ".native.tsx", ".ts", ".tsx"],
16 ios: [".ios.ts", ".ios.tsx", ".native.ts", ".native.tsx", ".ts", ".tsx"],
17} as const;
18
19type Platform = keyof typeof PLATFORM_EXTENSION_ORDER;
20
21const PLATFORMS = Object.keys(PLATFORM_EXTENSION_ORDER) as ReadonlyArray<Platform>;
22
23const isGraphFile = (filePath: string): boolean =>
24 /\.tsx?$/.test(filePath) &&
25 !filePath.includes(".test.") &&
26 !filePath.includes("test-support") &&
27 !filePath.endsWith(".d.ts");
28
29function isRelevantForPlatform(filePath: string, platform: Platform): boolean {
30 const name = NodePath.basename(filePath);
31 if (platform === "android") {
32 return !name.includes(".ios.");
33 }
34 return !name.includes(".android.");
35}
36
37function collectSourceFiles(dir: string, out: string[] = []): string[] {
38 for (const entry of NodeFS.readdirSync(dir)) {
39 const filePath = NodePath.join(dir, entry);
40 if (NodeFS.statSync(filePath).isDirectory()) {
41 collectSourceFiles(filePath, out);
42 } else if (isGraphFile(filePath)) {
43 out.push(filePath);
44 }
45 }
46 return out;
47}
48
49function resolveRelative(
50 fromFile: string,
51 specifier: string,
52 extensionOrder: ReadonlyArray<string>,
53): string | null {
54 if (!specifier.startsWith(".")) {
55 return null;
56 }
57 const base = NodePath.resolve(NodePath.dirname(fromFile), specifier);
58 for (const ext of extensionOrder) {
59 for (const candidate of [base + ext, NodePath.join(base, `index${ext}`)]) {
60 try {
61 if (NodeFS.statSync(candidate).isFile()) {
62 const resolved = NodePath.resolve(candidate);
63 return resolved.startsWith(SOURCE_ROOT + NodePath.sep) ? resolved : null;
64 }
65 } catch {}
66 }
67 }
68 return null;
69}
70
71interface ParsedImport {
72 readonly specifier: string;
73 readonly isDynamic: boolean;
74}
75
76function parseImports(source: string): ParsedImport[] {
77 const parsed: ParsedImport[] = [];
78 const staticRe = /(?:^|\n)\s*(?:import|export)[\s\S]*?from\s+["']([^"']+)["']/g;
79 const bareRe = /(?:^|\n)\s*import\s+["']([^"']+)["']/g;
80 const dynamicRe = /\bimport\s*\(\s*["']([^"']+)["']\s*\)/g;
81 for (const match of source.matchAll(staticRe)) {
82 parsed.push({ specifier: match[1]!, isDynamic: false });
83 }
84 for (const match of source.matchAll(bareRe)) {
85 parsed.push({ specifier: match[1]!, isDynamic: false });
86 }
87 for (const match of source.matchAll(dynamicRe)) {
88 parsed.push({ specifier: match[1]!, isDynamic: true });
89 }
90 return parsed;
91}
92
93type Layer = "state" | "lib" | "components" | "native" | "features" | "other";
94
95function layerOf(relativePath: string): Layer {
96 const top = relativePath.split(NodePath.sep)[0]!;
97 if (top === "features") return "features";
98 return top === "state" || top === "lib" || top === "components" || top === "native"
99 ? (top as Layer)
100 : "other";
101}
102
103interface PlatformGraph {
104 readonly platform: Platform;
105 readonly files: ReadonlyArray<string>;
106 readonly staticEdges: ReadonlyMap<string, ReadonlyArray<string>>;
107 readonly crossLayerEdges: ReadonlySet<string>;
108}
109
110function buildPlatformGraph(platform: Platform): PlatformGraph {
111 const extensionOrder = PLATFORM_EXTENSION_ORDER[platform];
112 const files = collectSourceFiles(SOURCE_ROOT)
113 .filter((file) => isRelevantForPlatform(file, platform))
114 .sort();
115 const staticEdges = new Map<string, string[]>();
116 const crossLayerEdges = new Set<string>();
117 for (const file of files) {
118 const targets = new Set<string>();
119 for (const { specifier, isDynamic } of parseImports(NodeFS.readFileSync(file, "utf8"))) {
120 const resolved = resolveRelative(file, specifier, extensionOrder);
121 if (resolved === null || resolved === file) {
122 continue;
123 }
124 const from = NodePath.relative(SOURCE_ROOT, file);
125 const to = NodePath.relative(SOURCE_ROOT, resolved);
126 const fromLayer = layerOf(from);
127 const toLayer = layerOf(to);
128 const upward =
129 (fromLayer === "state" ||
130 fromLayer === "lib" ||
131 fromLayer === "components" ||
132 fromLayer === "native") &&
133 (toLayer === "features" || (fromLayer === "lib" && toLayer === "state"));
134 if (upward) {
135 crossLayerEdges.add(`${from} -> ${to}`);
136 }
137 if (!isDynamic) {
138 targets.add(resolved);
139 }
140 }
141 staticEdges.set(file, [...targets]);
142 }
143 return { platform, files, staticEdges, crossLayerEdges };
144}
145
146function findCycles(graph: PlatformGraph): ReadonlyArray<ReadonlyArray<string>> {
147 const index = new Map<string, number>();
148 const low = new Map<string, number>();
149 const onStack = new Set<string>();
150 const stack: string[] = [];
151 const cycles: string[][] = [];
152 let nextIndex = 0;
153
154 const enter = (node: string): void => {
155 index.set(node, nextIndex);
156 low.set(node, nextIndex);
157 nextIndex += 1;
158 stack.push(node);
159 onStack.add(node);
160 };
161
162 for (const root of graph.files) {
163 if (index.has(root)) continue;
164 const work: Array<[string, number]> = [[root, 0]];
165 enter(root);
166 while (work.length > 0) {
167 const frame = work[work.length - 1]!;
168 const neighbors = graph.staticEdges.get(frame[0]) ?? [];
169 let advanced = false;
170 for (let i = frame[1]; i < neighbors.length; i += 1) {
171 const child = neighbors[i]!;
172 if (!graph.staticEdges.has(child)) continue;
173 if (!index.has(child)) {
174 work[work.length - 1] = [frame[0], i + 1];
175 work.push([child, 0]);
176 enter(child);
177 advanced = true;
178 break;
179 } else if (onStack.has(child)) {
180 low.set(frame[0], Math.min(low.get(frame[0])!, index.get(child)!));
181 }
182 }
183 if (advanced) continue;
184 work.pop();
185 const parent = work[work.length - 1];
186 if (parent) {
187 low.set(parent[0], Math.min(low.get(parent[0])!, low.get(frame[0])!));
188 }
189 if (low.get(frame[0]) === index.get(frame[0])) {
190 const component: string[] = [];
191 let member: string;
192 do {
193 member = stack.pop()!;
194 onStack.delete(member);
195 component.push(member);
196 } while (member !== frame[0]);
197 if (component.length > 1) {
198 cycles.push(component.sort().map((file) => NodePath.relative(SOURCE_ROOT, file)));
199 }
200 }
201 }
202 }
203 return cycles;
204}
205
206const graphs = PLATFORMS.map(buildPlatformGraph);
207
208function upwardEdges(): string[] {
209 const union = new Set<string>();
210 for (const graph of graphs) {
211 for (const edge of graph.crossLayerEdges) {
212 union.add(edge);
213 }
214 }
215 return [...union].sort();
216}
217
218describe("mobile dependency graph", () => {
219 it.each(PLATFORMS)("has no circular imports under %s resolution", (platform) => {
220 const graph = graphs.find((candidate) => candidate.platform === platform)!;
221 expect(graph.files.length).toBeGreaterThan(500);
222 expect(findCycles(graph)).toEqual([]);
223 });
224
225 it("keeps upward imports from state/lib/components/native into features at the ceiling", () => {
226 const edges = upwardEdges();
227 const edgesFor = (from: Layer, to: Layer): string[] =>
228 edges.filter((edge) => {
229 const [source, target] = edge.split(" -> ");
230 return layerOf(source!) === from && layerOf(target!) === to;
231 });
232
233 const ceilings: ReadonlyArray<readonly [Layer, Layer, number, string]> = [
234 ["state", "features", 6, "state must not add imports from features"],
235 ["lib", "features", 7, "lib must not add imports from features"],
236 // components -> features: mostly the appearance preferences provider
237 // and the layout toolbar bridges.
238 ["components", "features", 30, "components must not add imports from features"],
239 // native -> features: native glue reading appearance/keyboard/review features.
240 ["native", "features", 8, "native must not add imports from features"],
241 ["lib", "state", 10, "lib must not add imports from state"],
242 ];
243
244 for (const [from, to, ceiling, message] of ceilings) {
245 const layerEdges = edgesFor(from, to);
246 expect(
247 layerEdges.length,
248 `${message}. ${layerEdges.length} edges remain:\n${layerEdges.join("\n")}`,
249 ).toBeLessThanOrEqual(ceiling);
250 }
251 });
252});