screens.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. /**
  2. * `GET /api/screens` — the app as a reader experiences it: screens, and the
  3. * transitions between them, each labelled with what has to be true for it to
  4. * happen.
  5. *
  6. * The graph already holds the pieces: a `route` node per screen file (Expo
  7. * Router, and any framework that binds a route to the component that renders
  8. * it), and a `navigates` edge from the function that pushes a path to the
  9. * route it names. What a reader wants is neither of those nodes — it is
  10. * "from the Home screen, tapping an object card opens Object Detail, but only
  11. * for a collected object". That sentence is three hops away from the edge:
  12. *
  13. * HomeScreen ─renders→ ItemsGrid ─renders→ ItemCard ─calls→ openObjectDetail ─navigates→ /object-detail
  14. *
  15. * So for every `navigates` edge this walks BACKWARDS from its source through
  16. * `calls` edges (the JSX-render synthesizer's edges among them) until it
  17. * reaches a component that a route renders. That component's screen is where
  18. * the transition starts; the nodes passed on the way are the `via` chain, and
  19. * the branch conditions at each call site along it (`graph/branch-guards.ts`)
  20. * are joined into the link's `when`. A navigation whose walk reaches no screen
  21. * within the hop cap — a store action, a service that runs after login — is
  22. * kept as an `origin` rather than dropped: it is a real transition with a real
  23. * trigger, just not a screen.
  24. *
  25. * Read from the graph at request time, never cached: the `when` labels are
  26. * read from the source as it stands. Seventy-odd transitions and a few
  27. * hundred guarded call sites resolve in tens of milliseconds.
  28. */
  29. import type CodeGraph from '../../index';
  30. import type { Edge, Node } from '../../types';
  31. import { createWhenReader } from './when';
  32. import { toNodeRef, type WireNodeRef } from './wire';
  33. // =============================================================================
  34. // Wire shapes
  35. // =============================================================================
  36. export interface WireScreen {
  37. /** The route node's id — what a link's `from`/`to` name. */
  38. id: string;
  39. /** The screen's path: `/object-detail`, `/item/[id]`. */
  40. path: string;
  41. file: string;
  42. line: number;
  43. /** The component the route renders, when the graph bound one. */
  44. component: WireNodeRef | null;
  45. /** Transitions into and out of this screen. */
  46. incoming: number;
  47. outgoing: number;
  48. }
  49. /**
  50. * A navigation whose start is not one screen: a function no screen reaches
  51. * (a store action after login), or a component so many screens render (a
  52. * top bar) that attributing its navigation to each of them would draw the
  53. * same three arrows from every box.
  54. */
  55. export interface WireScreenOrigin {
  56. id: string;
  57. node: WireNodeRef;
  58. outgoing: number;
  59. /** For shared chrome: how many screens render it. */
  60. sharedBy?: number;
  61. }
  62. export interface WireScreenSite {
  63. file: string;
  64. line: number;
  65. /** The href as written at the call, `${…}` for interpolations. */
  66. href: string;
  67. /** `push`, `replace`, `navigate`, or `return` for a helper's return value. */
  68. method: string;
  69. /**
  70. * The conditions THIS site runs under — the whole chain's plus its own,
  71. * joined; '' when unconditional. A link with several sites is several
  72. * scenarios; the link's `when` is only their summary.
  73. */
  74. when: string;
  75. }
  76. export interface WireScreenLink {
  77. id: string;
  78. /** A screen id, or an origin id. */
  79. from: string;
  80. /** Always a screen id. */
  81. to: string;
  82. /** True when `from` is an origin, not a screen. */
  83. fromOrigin: boolean;
  84. /**
  85. * The symbols the transition passes through, from just below the screen's
  86. * component down to the one that holds the navigation call. Empty when the
  87. * screen's own component navigates.
  88. */
  89. via: WireNodeRef[];
  90. /** Conditions along the whole chain, joined; '' when unconditional. */
  91. when: string;
  92. /** Every call site behind this link (same screen, same chain end). */
  93. sites: WireScreenSite[];
  94. /**
  95. * The destination was inferred, not written at the call: it came back from
  96. * a helper's return value. (A synthesized render hop on the way — every
  97. * parent → child component step is one — does not count: that would dash
  98. * nearly every arrow.)
  99. */
  100. synthesized: boolean;
  101. }
  102. export interface WireScreensPayload {
  103. /** False when the graph holds no screen navigation at all. */
  104. routed: boolean;
  105. /** The route named `/`, when there is one. */
  106. entry: string | null;
  107. screens: WireScreen[];
  108. origins: WireScreenOrigin[];
  109. links: WireScreenLink[];
  110. /** Navigations dropped because the backwards walk hit a cap. */
  111. dropped: number;
  112. index: { lastIndexedAt: number | null; edges: number; files: number };
  113. timing: { elapsedMs: number };
  114. }
  115. // =============================================================================
  116. // Caps
  117. // =============================================================================
  118. /** Hops walked back from a navigation call before giving up on a screen. */
  119. const MAX_DEPTH = 7;
  120. /** Callers expanded per node — a hub (`useToast`) is a dead end, not a path. */
  121. const MAX_CALLERS_PER_NODE = 30;
  122. /** Nodes visited per navigation. */
  123. const MAX_VISITED = 800;
  124. /** Call sites labelled with conditions per request. */
  125. const MAX_WHEN_SITES = 600;
  126. /**
  127. * Edges walked backwards from a navigation call. `contains` because a handler
  128. * declared inside a screen component (`function handleContinue() {…}` in the
  129. * body) is reached from the component by containment, not by a call; a
  130. * `references` edge is followed only when it passes the function as a value
  131. * (`onPress={handleContinue}`), never for a type mention.
  132. */
  133. const WALK_KINDS: Edge['kind'][] = ['calls', 'instantiates', 'contains', 'references'];
  134. /** A component rendered by at least this many screens is chrome, not a screen's own behaviour. */
  135. const SHARED_CHROME_MIN = 3;
  136. // =============================================================================
  137. // The endpoint
  138. // =============================================================================
  139. export async function buildScreens(cg: CodeGraph, projectRoot: string): Promise<WireScreensPayload> {
  140. const started = Date.now();
  141. const stats = cg.getStats();
  142. const index = { lastIndexedAt: cg.getLastIndexedAt() ?? null, edges: stats.edgeCount, files: stats.fileCount };
  143. const routes = cg.getNodesByKind('route');
  144. const routeIds = routes.map((r) => r.id);
  145. const navEdges = routeIds.length === 0 ? [] : cg.getIncomingEdgesTo(routeIds, ['navigates']);
  146. if (navEdges.length === 0) {
  147. return {
  148. routed: false,
  149. entry: null,
  150. screens: [],
  151. origins: [],
  152. links: [],
  153. dropped: 0,
  154. index,
  155. timing: { elapsedMs: Date.now() - started },
  156. };
  157. }
  158. // Route → the component it renders; component → its route.
  159. const routeById = new Map(routes.map((r) => [r.id, r]));
  160. const routeByFile = new Map(routes.map((r) => [r.filePath, r.id]));
  161. const renders = cg.getOutgoingEdgesFrom(routeIds, ['calls', 'instantiates']);
  162. const componentIds = new Set(renders.map((e) => e.target));
  163. const nodesById = cg.getNodesByIds([...componentIds, ...navEdges.map((e) => e.source)]);
  164. const componentOf = new Map<string, Node>();
  165. const screenOfComponent = new Map<string, string>();
  166. for (const edge of renders) {
  167. const component = nodesById.get(edge.target);
  168. if (!component || componentOf.has(edge.source)) continue;
  169. componentOf.set(edge.source, component);
  170. screenOfComponent.set(component.id, edge.source);
  171. }
  172. const readWhen = createWhenReader(cg, projectRoot, MAX_WHEN_SITES);
  173. const whenAt = (caller: Node, edge: Edge): Promise<string> => readWhen(caller, { line: edge.line, column: edge.column });
  174. const links = new Map<string, WireScreenLink>();
  175. const origins = new Map<string, WireScreenOrigin>();
  176. const counts = new Map<string, { incoming: number; outgoing: number }>();
  177. const bump = (id: string, key: 'incoming' | 'outgoing') => {
  178. const c = counts.get(id) ?? { incoming: 0, outgoing: 0 };
  179. c[key]++;
  180. counts.set(id, c);
  181. };
  182. let dropped = 0;
  183. for (const nav of navEdges) {
  184. const holder = nodesById.get(nav.source);
  185. const target = routeById.get(nav.target);
  186. if (!holder || !target) continue;
  187. const meta = (nav.metadata ?? {}) as Record<string, unknown>;
  188. const site: WireScreenSite = {
  189. file: toPosix(holder.filePath),
  190. line: nav.line ?? holder.startLine,
  191. href: typeof meta.href === 'string' ? meta.href : target.name,
  192. method: nav.provenance === 'heuristic' ? 'return' : typeof meta.navMethod === 'string' ? meta.navMethod : 'push',
  193. when: nav.provenance === 'heuristic' ? '' : await whenAt(holder, nav),
  194. };
  195. let starts = await attribute(cg, holder, screenOfComponent, routeByFile, nodesById);
  196. if (starts === null) {
  197. dropped++;
  198. continue;
  199. }
  200. starts = collapseSharedChrome(starts, origins);
  201. const attributions =
  202. starts.length > 0
  203. ? starts
  204. : [{ screenId: null as string | null, path: [{ node: holder, edge: null }] as Array<{ node: Node; edge: Edge | null }> }];
  205. for (const start of attributions) {
  206. let fromId: string;
  207. let fromOrigin = false;
  208. if (start.screenId !== null) fromId = start.screenId;
  209. else {
  210. // The origin is the chain's head: the holder itself, or the shared
  211. // component the chain was collapsed onto.
  212. const head = start.path[0]!.node;
  213. fromId = head.id;
  214. fromOrigin = true;
  215. if (!origins.has(head.id)) origins.set(head.id, { id: head.id, node: toNodeRef(head), outgoing: 0 });
  216. }
  217. // `path` is [screen component, …, holder]; `path[i].edge` is the call
  218. // from `path[i-1]` into `path[i]`, so its site is in `path[i-1]`'s file.
  219. // The component itself is not "via" — it IS the screen.
  220. const via = start.path.slice(1).map((h) => toNodeRef(h.node));
  221. const whens: string[] = [];
  222. const synthesized = nav.provenance === 'heuristic';
  223. for (let i = 1; i < start.path.length; i++) {
  224. const edge = start.path[i]!.edge;
  225. if (!edge) continue;
  226. const w = await whenAt(start.path[i - 1]!.node, edge);
  227. if (w && !whens.includes(w)) whens.push(w);
  228. }
  229. if (site.when && !whens.includes(site.when)) whens.push(site.when);
  230. site.when = whens.join(' && ');
  231. const viaKey = via.map((v) => v.id).join('>');
  232. if (fromOrigin && start.path[0]!.node.id !== holder.id) {
  233. // A collapsed chain: the origin's own name is not "via".
  234. }
  235. const id = `${fromId}�${target.id}�${viaKey}`;
  236. const existing = links.get(id);
  237. if (existing) {
  238. existing.sites.push(site);
  239. const mine = whens.join(' && ');
  240. if (mine !== existing.when) {
  241. // `if (x) push(A) else push(A)`: the two arms together are "always".
  242. if (complementary(mine, existing.when)) existing.when = '';
  243. else if (mine && existing.when) existing.when = `${existing.when} || ${mine}`;
  244. else if (!mine) existing.when = '';
  245. }
  246. continue;
  247. }
  248. links.set(id, {
  249. id,
  250. from: fromId,
  251. to: target.id,
  252. fromOrigin,
  253. via,
  254. when: whens.join(' && '),
  255. sites: [site],
  256. synthesized,
  257. });
  258. bump(target.id, 'incoming');
  259. if (fromOrigin) origins.get(fromId)!.outgoing++;
  260. else bump(fromId, 'outgoing');
  261. }
  262. }
  263. const screens: WireScreen[] = routes
  264. .map((route) => {
  265. const component = componentOf.get(route.id) ?? null;
  266. const c = counts.get(route.id) ?? { incoming: 0, outgoing: 0 };
  267. return {
  268. id: route.id,
  269. path: route.name,
  270. file: toPosix(route.filePath),
  271. line: route.startLine,
  272. component: component ? toNodeRef(component) : null,
  273. incoming: c.incoming,
  274. outgoing: c.outgoing,
  275. };
  276. })
  277. .sort((a, b) => a.path.localeCompare(b.path));
  278. const entry = screens.find((s) => s.path === '/')?.id ?? null;
  279. const ordered = [...links.values()].sort((a, b) => a.id.localeCompare(b.id));
  280. return {
  281. routed: true,
  282. entry,
  283. screens,
  284. origins: [...origins.values()].sort((a, b) => a.node.name.localeCompare(b.node.name)),
  285. links: ordered,
  286. dropped,
  287. index,
  288. timing: { elapsedMs: Date.now() - started },
  289. };
  290. }
  291. // =============================================================================
  292. // Attribution: which screen does this navigation start from?
  293. // =============================================================================
  294. interface Attribution {
  295. screenId: string | null;
  296. /** [screen component, …, holder], each with the edge that led INTO it from the previous. */
  297. path: Array<{ node: Node; edge: Edge | null }>;
  298. }
  299. /**
  300. * Every screen whose component reaches `holder` through calls, each with the
  301. * shortest chain (breadth-first). `[]` when none does within the caps but the
  302. * walk completed; `null` when the walk was cut short — a hub so wide the
  303. * answer would be a guess.
  304. */
  305. async function attribute(
  306. cg: CodeGraph,
  307. holder: Node,
  308. screenOfComponent: Map<string, string>,
  309. routeByFile: Map<string, string>,
  310. known: Map<string, Node>
  311. ): Promise<Attribution[] | null> {
  312. // The holder IS a screen component: the transition starts on that screen.
  313. const own = screenOfComponent.get(holder.id);
  314. if (own) return [{ screenId: own, path: [{ node: holder, edge: null }] }];
  315. const parent = new Map<string, { prev: string | null; edge: Edge | null }>();
  316. parent.set(holder.id, { prev: null, edge: null });
  317. const nodes = new Map<string, Node>([[holder.id, holder]]);
  318. let frontier = [holder.id];
  319. const found: Attribution[] = [];
  320. let truncated = false;
  321. for (let depth = 0; depth < MAX_DEPTH && frontier.length > 0; depth++) {
  322. const incoming = cg.getIncomingEdgesTo(frontier, WALK_KINDS);
  323. const byTarget = new Map<string, Edge[]>();
  324. for (const e of incoming) {
  325. if (e.kind === 'references' && (e.metadata as Record<string, unknown> | undefined)?.fnRef !== true) continue;
  326. const list = byTarget.get(e.target) ?? [];
  327. list.push(e);
  328. byTarget.set(e.target, list);
  329. }
  330. const nextIds: string[] = [];
  331. const wanted = new Set<string>();
  332. for (const [, edges] of byTarget) {
  333. if (edges.length > MAX_CALLERS_PER_NODE) {
  334. truncated = true;
  335. continue;
  336. }
  337. for (const e of edges) if (!parent.has(e.source)) wanted.add(e.source);
  338. }
  339. if (parent.size + wanted.size > MAX_VISITED) truncated = true;
  340. const fetched = wanted.size === 0 ? new Map<string, Node>() : cg.getNodesByIds([...wanted]);
  341. for (const [, edges] of byTarget) {
  342. if (edges.length > MAX_CALLERS_PER_NODE) continue;
  343. for (const e of edges) {
  344. if (parent.has(e.source)) continue;
  345. const caller = fetched.get(e.source) ?? known.get(e.source);
  346. // A file's top level or a route node is not a place a user is.
  347. if (!caller || caller.kind === 'file' || caller.kind === 'route') continue;
  348. parent.set(e.source, { prev: e.target, edge: e });
  349. nodes.set(e.source, caller);
  350. const screen = screenOfComponent.get(caller.id);
  351. if (screen) {
  352. found.push({ screenId: screen, path: pathFrom(caller.id, parent, nodes) });
  353. continue; // a screen is where the walk stops
  354. }
  355. nextIds.push(e.source);
  356. if (parent.size >= MAX_VISITED) break;
  357. }
  358. }
  359. frontier = nextIds;
  360. if (parent.size >= MAX_VISITED) {
  361. truncated = true;
  362. break;
  363. }
  364. }
  365. if (found.length > 0) return found;
  366. // No screen component reached, but the chain passed through a screen's
  367. // FILE: a component that file defines for itself (a wrapper the render
  368. // synthesizer did not see through) belongs to that screen. Nearest first,
  369. // so the holder's own file wins over a helper's.
  370. for (const [id] of parent) {
  371. const node = nodes.get(id);
  372. const screen = node ? routeByFile.get(node.filePath) : undefined;
  373. if (screen) return [{ screenId: screen, path: pathFrom(id, parent, nodes) }];
  374. }
  375. return truncated ? null : [];
  376. }
  377. /**
  378. * Shared chrome: when the same first-hop component carries this navigation
  379. * to {@link SHARED_CHROME_MIN} or more screens, those attributions collapse
  380. * into ONE from that component, marked with how many screens render it. A top
  381. * bar's "Account settings" link is one fact about the top bar, not twelve
  382. * facts about twelve screens.
  383. */
  384. function collapseSharedChrome(starts: Attribution[], origins: Map<string, WireScreenOrigin>): Attribution[] {
  385. const byFirstHop = new Map<string, Attribution[]>();
  386. for (const s of starts) {
  387. if (s.screenId === null || s.path.length < 2) continue;
  388. const key = s.path[1]!.node.id;
  389. byFirstHop.set(key, [...(byFirstHop.get(key) ?? []), s]);
  390. }
  391. const out: Attribution[] = [];
  392. const collapsed = new Set<Attribution>();
  393. for (const [, group] of byFirstHop) {
  394. const screens = new Set(group.map((g) => g.screenId));
  395. if (screens.size < SHARED_CHROME_MIN) continue;
  396. const head = group[0]!.path[1]!.node;
  397. const existing = origins.get(head.id);
  398. if (existing) existing.sharedBy = Math.max(existing.sharedBy ?? 0, screens.size);
  399. else origins.set(head.id, { id: head.id, node: toNodeRef(head), outgoing: 0, sharedBy: screens.size });
  400. // One attribution, headed by the shared component, chain continuing below it.
  401. out.push({ screenId: null, path: group[0]!.path.slice(1) });
  402. for (const g of group) collapsed.add(g);
  403. }
  404. for (const s of starts) if (!collapsed.has(s)) out.push(s);
  405. return out;
  406. }
  407. /** The chain from `start` down to the holder, following `prev` links. */
  408. function pathFrom(
  409. start: string,
  410. parent: Map<string, { prev: string | null; edge: Edge | null }>,
  411. nodes: Map<string, Node>
  412. ): Array<{ node: Node; edge: Edge | null }> {
  413. const out: Array<{ node: Node; edge: Edge | null }> = [];
  414. let id: string | null = start;
  415. let edgeInto: Edge | null = null;
  416. while (id !== null) {
  417. const node = nodes.get(id)!;
  418. out.push({ node, edge: edgeInto });
  419. const step: { prev: string | null; edge: Edge | null } = parent.get(id)!;
  420. edgeInto = step.edge;
  421. id = step.prev;
  422. }
  423. return out;
  424. }
  425. // =============================================================================
  426. // Conditions
  427. // =============================================================================
  428. /** `x` and `!x`, or `a && x` and `a && !x`. */
  429. function complementary(a: string, b: string): boolean {
  430. if (!a || !b) return false;
  431. const pa = a.split(' && ');
  432. const pb = b.split(' && ');
  433. if (pa.length !== pb.length) return false;
  434. let flips = 0;
  435. for (let i = 0; i < pa.length; i++) {
  436. if (pa[i] === pb[i]) continue;
  437. if (pa[i] === `!${pb[i]}` || pb[i] === `!${pa[i]}`) flips++;
  438. else return false;
  439. }
  440. return flips === 1;
  441. }
  442. function toPosix(p: string): string {
  443. return p.replace(/\\/g, '/');
  444. }