ui-steps-api.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. /**
  2. * `GET /api/steps` — what happens from a screen, as typed steps.
  3. *
  4. * Against a real index of a small Expo + React Native app, shaped to cross
  5. * every boundary the endpoint classifies: a screen whose handler (a
  6. * `useCallback`) calls a Swift method through an `RCT_EXTERN_MODULE` shim,
  7. * the Swift side sending an event the screen listens to, the listener calling
  8. * an API function that leaves the index (`client.post`), a store action in a
  9. * store file, and a navigation to a second screen behind a condition. The
  10. * pure layout is tested without an index in `ui-steps-model.test.ts`.
  11. */
  12. import { describe, it, expect, beforeAll, afterAll } from 'vitest';
  13. import * as fs from 'fs';
  14. import * as os from 'os';
  15. import * as path from 'path';
  16. import { CodeGraph } from '../src';
  17. import { initGrammars, loadAllGrammars } from '../src/extraction/grammars';
  18. import { buildSteps, crossing, effectCategory, isStoreFile } from '../src/ui-server/api/steps';
  19. let tmpDir: string;
  20. let cg: CodeGraph;
  21. function write(rel: string, content: string): void {
  22. const full = path.join(tmpDir, rel);
  23. fs.mkdirSync(path.dirname(full), { recursive: true });
  24. fs.writeFileSync(full, content);
  25. }
  26. beforeAll(async () => {
  27. await initGrammars();
  28. await loadAllGrammars();
  29. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-ui-steps-'));
  30. write('package.json', JSON.stringify({ name: 'app', dependencies: { expo: '52', 'expo-router': '4', 'react-native': '0.76' } }));
  31. write('src/app/_layout.tsx', 'export default function Layout() { return null }\n');
  32. write('src/app/index.tsx', "import { router } from 'expo-router'\nexport default function Home() {\n return null\n}\n");
  33. write(
  34. 'src/components/capture/capture-view.tsx',
  35. "import { NativeModules, NativeEventEmitter } from 'react-native'\n" +
  36. 'export const captureView = NativeModules.CaptureView\n' +
  37. 'export const nativeEmitter = new NativeEventEmitter(NativeModules.CaptureEvents)\n'
  38. );
  39. write('src/api/client.ts', "import axios from 'axios'\nexport const client = axios.create({ baseURL: 'x' })\n");
  40. write(
  41. 'src/api/frames.ts',
  42. "import { client } from './client'\n" +
  43. 'export async function uploadARCapture(uri: string) {\n' +
  44. " await client.post('/frames', { uri })\n" +
  45. " return client.get('/frames/status')\n" +
  46. '}\n'
  47. );
  48. write(
  49. 'src/storage/capture.storage.ts',
  50. "import { create } from 'zustand'\n" +
  51. 'const useCaptureStorage = create<State>((set) => ({\n' +
  52. ' zipUri: null,\n' +
  53. ' setZipUri: (zipUri: string) => set({ zipUri }),\n' +
  54. '}))\n' +
  55. 'export default useCaptureStorage\n'
  56. );
  57. write(
  58. 'src/app/capture/review.tsx',
  59. "import { useCallback, useEffect } from 'react'\n" +
  60. "import { router } from 'expo-router'\n" +
  61. "import { captureView, nativeEmitter } from '../../components/capture/capture-view'\n" +
  62. "import { uploadARCapture } from '../../api/frames'\n" +
  63. "import useCaptureStorage from '../../storage/capture.storage'\n" +
  64. 'export default function ReviewScreen({ unlimited }: { unlimited: boolean }) {\n' +
  65. ' const setZipUri = useCaptureStorage((s) => s.setZipUri)\n' +
  66. ' const handleApprove = useCallback(() => {\n' +
  67. ' captureView.finalizeCaptureSession()\n' +
  68. ' }, [])\n' +
  69. ' const handleZipComplete = useCallback(async (data: { uri: string }) => {\n' +
  70. ' setZipUri(data.uri)\n' +
  71. ' await uploadARCapture(data.uri)\n' +
  72. " Alert.alert('Uploaded', data.uri, [{ text: 'OK' }])\n" +
  73. " if (unlimited) router.replace('/')\n" +
  74. ' }, [unlimited])\n' +
  75. ' useEffect(() => {\n' +
  76. " const sub = nativeEmitter.addListener('onZipComplete', handleZipComplete)\n" +
  77. ' return () => sub.remove()\n' +
  78. ' }, [handleZipComplete])\n' +
  79. ' const form = useForm({ onSubmit: () => handleSubmit() })\n' +
  80. ' function handleSubmit() {\n' +
  81. ' captureView.finalizeCaptureSession()\n' +
  82. ' }\n' +
  83. ' return <Button onPress={handleApprove} />\n' +
  84. '}\n'
  85. );
  86. write(
  87. 'src/app/capture/index.tsx',
  88. "import { memo, useCallback } from 'react'\n" +
  89. "import { captureView } from '../../components/capture/capture-view'\n" +
  90. 'function CaptureComponent() {\n' +
  91. ' const handleOpen = useCallback(() => {\n' +
  92. ' captureView.finalizeCaptureSession()\n' +
  93. ' }, [])\n' +
  94. ' return <Button onPress={() => handleOpen()} />\n' +
  95. '}\n' +
  96. 'const MemoizedCaptureComponent = memo(CaptureComponent)\n' +
  97. 'export default function CapturePage() {\n' +
  98. ' return <MemoizedCaptureComponent />\n' +
  99. '}\n'
  100. );
  101. write(
  102. 'ios/CaptureView.m',
  103. '#import <React/RCTViewManager.h>\n@interface RCT_EXTERN_MODULE(CaptureView, RCTViewManager)\nRCT_EXTERN_METHOD(finalizeCaptureSession)\n@end\n'
  104. );
  105. write(
  106. 'ios/CaptureView.swift',
  107. 'import Foundation\n' +
  108. 'class CaptureView: RCTViewManager {\n' +
  109. ' @objc func finalizeCaptureSession() {\n' +
  110. ' let result = zip()\n' +
  111. ' if result {\n' +
  112. ' CaptureEvents.shared.emitZipComplete()\n' +
  113. ' }\n' +
  114. ' }\n' +
  115. ' func zip() -> Bool { return true }\n' +
  116. '}\n'
  117. );
  118. write(
  119. 'ios/CaptureEvents.swift',
  120. 'import Foundation\n' +
  121. 'class CaptureEvents: RCTEventEmitter {\n' +
  122. ' static let shared = CaptureEvents()\n' +
  123. ' func emitZipComplete() {\n' +
  124. ' sendEvent(withName: "onZipComplete", body: nil)\n' +
  125. ' }\n' +
  126. '}\n'
  127. );
  128. cg = CodeGraph.initSync(tmpDir);
  129. await cg.indexAll();
  130. });
  131. afterAll(() => {
  132. cg?.close();
  133. if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
  134. });
  135. const q = (params: Record<string, string>) => new URLSearchParams(params);
  136. describe('classification helpers', () => {
  137. it('crossing: JS → native is a bridge, native → JS an event, anything else nothing', () => {
  138. expect(crossing('tsx', 'swift')).toBe('bridge');
  139. expect(crossing('swift', 'tsx')).toBe('event');
  140. expect(crossing('typescript', 'javascript')).toBeNull();
  141. expect(crossing('swift', 'objc')).toBeNull();
  142. });
  143. it('store files', () => {
  144. expect(isStoreFile('src/storage/capture.storage.ts')).toBe(true);
  145. expect(isStoreFile('src/stores/user.ts')).toBe(true);
  146. expect(isStoreFile('src/features/cart/cart.slice.ts')).toBe(true);
  147. expect(isStoreFile('src/components/button.tsx')).toBe(false);
  148. expect(isStoreFile('src/restore/thing.ts')).toBe(false);
  149. });
  150. it('effects: a curated table, by reference text', () => {
  151. expect(effectCategory('client.post')).toBe('network');
  152. expect(effectCategory('fetch')).toBe('network');
  153. expect(effectCategory('AsyncStorage.setItem')).toBe('storage');
  154. expect(effectCategory('Linking.openURL')).toBe('device');
  155. expect(effectCategory('DdRum.addAction')).toBe('telemetry');
  156. expect(effectCategory('Math.max')).toBeNull();
  157. expect(effectCategory('i18n.t')).toBeNull();
  158. });
  159. });
  160. describe('buildSteps', () => {
  161. it('walks a screen through its handler, the bridge, the event, the store and the request', async () => {
  162. const review = cg.getNodesByKind('route').find((r) => r.name === '/capture/review')!;
  163. expect(review).toBeDefined();
  164. const payload = await buildSteps(cg, tmpDir, q({ anchor: review.id }));
  165. const byLabel = new Map(payload.steps.map((s) => [s.label, s]));
  166. const kinds = Object.fromEntries(payload.steps.map((s) => [s.label, s.kind]));
  167. expect(kinds['/capture/review']).toBe('screen');
  168. expect(payload.steps.find((s) => s.anchor)?.label).toBe('/capture/review');
  169. // The handler is wired to the tap, so it is a trigger; the call it makes
  170. // crosses into Swift, so that is a bridge; the Swift side's event lands
  171. // on the named listener; the listener writes the store, leaves the index
  172. // through `client.post`, and navigates home behind `unlimited`.
  173. expect(kinds['handleApprove']).toBe('trigger');
  174. expect(kinds['finalizeCaptureSession']).toBe('bridge');
  175. expect(kinds['handleZipComplete']).toBe('event');
  176. expect(byLabel.get('handleZipComplete')?.event).toBe('onZipComplete');
  177. expect(byLabel.get('handleZipComplete')?.events).toEqual(['onZipComplete']);
  178. expect(kinds['setZipUri']).toBe('store');
  179. // One box per (function, category): both calls the upload makes into the
  180. // network, labelled by the first and counting the rest.
  181. const network = payload.steps.find((s) => s.kind === 'effect' && s.effect?.category === 'network')!;
  182. expect(network.label).toBe('client.post +1');
  183. expect(network.effect?.apis).toEqual(['client.post', 'client.get']);
  184. expect(network.effect?.by.name).toBe('uploadARCapture');
  185. expect(kinds['/']).toBe('screen');
  186. // Another screen is a boundary: drawn, marked, not entered.
  187. expect(byLabel.get('/')?.cut).toBe('screen');
  188. const link = (from: string, to: string) =>
  189. payload.links.find((l) => l.from === byLabel.get(from)!.id && l.to === byLabel.get(to)!.id);
  190. const req = link('handleZipComplete', 'client.post +1');
  191. const tap = link('/capture/review', 'handleApprove');
  192. expect(tap?.kind).toBe('handler');
  193. // What fires it — read at the site: the JSX prop and its element, and the
  194. // function that writes the binding.
  195. expect(tap?.trigger).toEqual({ kind: 'prop', name: 'onPress', of: 'Button', in: 'ReviewScreen' });
  196. expect(byLabel.get('handleApprove')?.trigger).toEqual({ kind: 'prop', name: 'onPress', of: 'Button', in: 'ReviewScreen' });
  197. // A function called from under an `on*` option is a handler too — the
  198. // Formik shape — and the option names what fires it.
  199. expect(kinds['handleSubmit']).toBe('trigger');
  200. expect(link('/capture/review', 'handleSubmit')?.trigger).toEqual({ kind: 'option', name: 'onSubmit', of: 'useForm', in: 'ReviewScreen' });
  201. // The listener registration is a callback binding on the handler link.
  202. expect(link('/capture/review', 'handleZipComplete')?.trigger).toEqual({ kind: 'callback', name: 'addListener', of: "'onZipComplete'", in: 'ReviewScreen' });
  203. expect(link('handleApprove', 'finalizeCaptureSession')?.kind).toBe('bridge');
  204. const evt = link('finalizeCaptureSession', 'handleZipComplete');
  205. expect(evt?.kind).toBe('event');
  206. expect(evt?.synthesized).toBe(true);
  207. expect(evt?.via.map((v) => v.name)).toEqual(['emitZipComplete']);
  208. expect(evt?.when).toBe('result');
  209. expect(evt?.label).toContain('event onZipComplete');
  210. const storeLink = link('handleZipComplete', 'setZipUri');
  211. expect(storeLink?.kind).toBe('store');
  212. // Every call-shaped site says what it passes.
  213. expect(storeLink?.sites[0]?.args).toBe('data.uri');
  214. expect(link('handleApprove', 'finalizeCaptureSession')?.sites[0]?.args).toBe('');
  215. // One call behind an effect box: the box says it. Several: the panel does.
  216. const alert = payload.steps.find((s) => s.kind === 'effect' && s.effect?.category === 'device')!;
  217. expect(alert.label).toBe("Alert.alert('Uploaded', data.uri, […])");
  218. expect(network.label).toBe('client.post +1');
  219. expect(req?.sites.map((s) => `${s.text}(${s.args})`)).toEqual(["client.post('/frames', { uri })", "client.get('/frames/status')"]);
  220. expect(req?.kind).toBe('effect');
  221. expect(req?.via.map((v) => v.name)).toEqual(['uploadARCapture']);
  222. const nav = link('handleZipComplete', '/');
  223. expect(nav?.kind).toBe('navigates');
  224. expect(nav?.when).toBe('unlimited');
  225. expect(nav?.sites[0]?.text).toBe('replace /');
  226. // Every site carries the whole condition it runs under — one scenario each.
  227. expect(nav?.sites[0]?.when).toBe('unlimited');
  228. expect(evt?.sites[0]?.when).toBe('result');
  229. expect(storeLink?.sites[0]?.when).toBe('');
  230. // Rows: the anchor on 0, then one more step away each. The listener is
  231. // registered BY the screen (`addListener('onZipComplete', handleZipComplete)`),
  232. // so it sits one step from the anchor as a handler and the native event
  233. // arrives at it from further down — a link back up the picture — and
  234. // names the event on the box.
  235. expect(byLabel.get('/capture/review')?.depth).toBe(0);
  236. expect(byLabel.get('handleApprove')?.depth).toBe(1);
  237. expect(byLabel.get('finalizeCaptureSession')?.depth).toBe(2);
  238. expect(byLabel.get('handleZipComplete')?.depth).toBe(1);
  239. expect(link('/capture/review', 'handleZipComplete')?.kind).toBe('handler');
  240. expect(network.depth).toBe(2);
  241. expect(payload.through).toBe(false);
  242. expect(payload.truncated).toEqual({ steps: 0, hubs: 0, chrome: 0 });
  243. // No cap fired; the only thing not entered is the other screen.
  244. expect(payload.steps.filter((s) => s.cut !== null).map((s) => [s.label, s.cut])).toEqual([['/', 'screen']]);
  245. });
  246. it('walks through a memo-wrapped component into the screen body', async () => {
  247. const capture = cg.getNodesByKind('route').find((r) => r.name === '/capture')!;
  248. const payload = await buildSteps(cg, tmpDir, q({ anchor: capture.id }));
  249. const kinds = Object.fromEntries(payload.steps.map((s) => [s.label, s.kind]));
  250. // The wrapper and the component are render hops, folded into the link;
  251. // the handler — called from an inline arrow under `onPress` — is the
  252. // first box, the native call the next.
  253. expect(kinds['handleOpen']).toBe('trigger');
  254. expect(kinds['finalizeCaptureSession']).toBe('bridge');
  255. const toHandler = payload.links.find((l) => l.to === payload.steps.find((s) => s.label === 'handleOpen')!.id)!;
  256. expect(toHandler.via.map((v) => v.name)).toEqual(['MemoizedCaptureComponent', 'CaptureComponent']);
  257. expect(toHandler.trigger).toEqual({ kind: 'prop', name: 'onPress', of: 'Button', in: 'CaptureComponent' });
  258. expect(payload.steps.map((s) => s.label)).not.toContain('CaptureComponent');
  259. });
  260. it('enters other screens when asked to continue through them', async () => {
  261. const review = cg.getNodesByKind('route').find((r) => r.name === '/capture/review')!;
  262. const payload = await buildSteps(cg, tmpDir, q({ anchor: review.id, through: '1' }));
  263. expect(payload.through).toBe(true);
  264. expect(payload.steps.find((s) => s.label === '/')?.cut).toBeNull();
  265. });
  266. it('anchors by name, prefers the screen, and lists the rest as ambiguous', async () => {
  267. const payload = await buildSteps(cg, tmpDir, q({ symbol: 'handleApprove' }));
  268. expect(payload.anchor.name).toBe('handleApprove');
  269. expect(payload.steps[0]?.kind).toBe('anchor');
  270. expect(payload.steps.map((s) => s.label)).toContain('finalizeCaptureSession');
  271. });
  272. it('a depth cap is announced on the step it stopped at', async () => {
  273. const review = cg.getNodesByKind('route').find((r) => r.name === '/capture/review')!;
  274. const payload = await buildSteps(cg, tmpDir, q({ anchor: review.id, depth: '2' }));
  275. // The bridge is two steps out: drawn, not explored — and says so.
  276. const bridge = payload.steps.find((s) => s.label === 'finalizeCaptureSession')!;
  277. expect(bridge.cut).toBe('depth');
  278. expect(payload.links.some((l) => l.kind === 'event')).toBe(false);
  279. // The listener still sits one step out, so the event step keeps its
  280. // handler kind: nothing arrived at it from native within the cap.
  281. expect(payload.steps.find((s) => s.label === 'handleZipComplete')?.kind).toBe('trigger');
  282. });
  283. it('refuses a missing anchor and an unknown id', async () => {
  284. await expect(buildSteps(cg, tmpDir, q({}))).rejects.toThrow(/anchor/);
  285. await expect(buildSteps(cg, tmpDir, q({ anchor: 'function:nope' }))).rejects.toThrow(/No symbol/);
  286. await expect(buildSteps(cg, tmpDir, q({ symbol: 'nothingNamedThis' }))).rejects.toThrow(/Nothing/);
  287. });
  288. });