Open History to see the last commit
1import { describe, expect, test } from 'vitest'
2import {
3 ImportGraph,
4 buildTrace,
5 formatViolation,
6} from '../../src/import-protection/trace'
7import type { ViolationInfo } from '../../src/import-protection/trace'
8
9describe('ImportGraph', () => {
10 test('addEdge and reverse lookup', () => {
11 const graph = new ImportGraph()
12 graph.addEdge('/src/secret.server.ts', '/src/edge-a.ts', './secret.server')
13 graph.addEdge(
14 '/src/edge-a.ts',
15 '/src/routes/index.tsx',
16 './violations/edge-a',
17 )
18
19 const edges = graph.getEdges('/src/secret.server.ts')
20 expect(edges).toBeDefined()
21 expect(edges!.size).toBe(1)
22
23 const firstEdge = [...edges!][0]!
24 expect(firstEdge.importer).toBe('/src/edge-a.ts')
25 expect(firstEdge.specifier).toBe('./secret.server')
26 })
27
28 test('addEntry marks entries', () => {
29 const graph = new ImportGraph()
30 graph.addEntry('/src/main.tsx')
31 expect(graph.entries.has('/src/main.tsx')).toBe(true)
32 })
33
34 test('clear resets everything', () => {
35 const graph = new ImportGraph()
36 graph.addEdge('/a', '/b', './a')
37 graph.addEntry('/b')
38 graph.clear()
39 expect(graph.reverseEdges.size).toBe(0)
40 expect(graph.entries.size).toBe(0)
41 })
42
43 test('invalidate removes edges involving a module', () => {
44 const graph = new ImportGraph()
45 graph.addEdge('/a', '/b', './a')
46 graph.addEdge('/c', '/b', './c')
47 graph.addEdge('/d', '/a', './d')
48
49 graph.invalidate('/b')
50
51 // Edges where /b is importer should be removed
52 const edgesForA = graph.getEdges('/a')
53 expect(edgesForA).toBeDefined()
54 expect(edgesForA!.size).toBe(0)
55
56 const edgesForC = graph.getEdges('/c')
57 expect(edgesForC).toBeDefined()
58 expect(edgesForC!.size).toBe(0)
59
60 const edgesForD = graph.getEdges('/d')
61 expect(edgesForD).toBeDefined()
62 expect(edgesForD!.size).toBe(1)
63 })
64
65 test('getEdges returns undefined for unknown ID', () => {
66 const graph = new ImportGraph()
67 expect(graph.getEdges('/nonexistent')).toBeUndefined()
68 })
69
70 test('invalidate also removes reverseEdges entry for the invalidated module', () => {
71 const graph = new ImportGraph()
72 graph.addEdge('/a', '/b', './a')
73 graph.invalidate('/a')
74 // /a's own reverse-edge map should be gone
75 expect(graph.reverseEdges.has('/a')).toBe(false)
76 })
77
78 test('invalidate is safe on unknown ID', () => {
79 const graph = new ImportGraph()
80 graph.addEdge('/a', '/b', './a')
81 graph.invalidate('/unknown')
82 expect(graph.getEdges('/a')!.size).toBe(1)
83 })
84
85 test('addEdge overwrites specifier for same importer→resolved pair', () => {
86 const graph = new ImportGraph()
87 graph.addEdge('/a', '/b', './a-old')
88 graph.addEdge('/a', '/b', './a-new')
89 const edges = graph.getEdges('/a')
90 expect(edges!.size).toBe(1)
91 expect([...edges!][0]!.specifier).toBe('./a-new')
92 })
93})
94
95describe('buildTrace', () => {
96 test('builds a trace from entry to denied module', () => {
97 const graph = new ImportGraph()
98 graph.addEntry('/src/main.tsx')
99
100 // main.tsx -> routes/index.tsx -> violations/edge-a.ts -> violations/secret.server.ts
101 graph.addEdge('/src/routes/index.tsx', '/src/main.tsx', './routes/index')
102 graph.addEdge(
103 '/src/violations/edge-a.ts',
104 '/src/routes/index.tsx',
105 './violations/edge-a',
106 )
107 graph.addEdge(
108 '/src/violations/secret.server.ts',
109 '/src/violations/edge-a.ts',
110 './secret.server',
111 )
112
113 // Build trace starting from edge-a (the importer of the denied module)
114 const trace = buildTrace(graph, '/src/violations/edge-a.ts')
115
116 expect(trace.length).toBeGreaterThanOrEqual(2)
117 expect(trace[0]!.file).toBe('/src/main.tsx')
118 expect(trace[trace.length - 1]!.file).toBe('/src/violations/edge-a.ts')
119 })
120
121 test('respects maxDepth', () => {
122 const graph = new ImportGraph()
123 graph.addEntry('/entry')
124
125 // Chain: /entry -> /a -> /b -> /c -> /d -> /e
126 graph.addEdge('/a', '/entry', './a')
127 graph.addEdge('/b', '/a', './b')
128 graph.addEdge('/c', '/b', './c')
129 graph.addEdge('/d', '/c', './d')
130 graph.addEdge('/e', '/d', './e')
131
132 const trace = buildTrace(graph, '/e', 2)
133 expect(trace.length).toBeLessThanOrEqual(4)
134 })
135
136 test('handles single node with no importers', () => {
137 const graph = new ImportGraph()
138 const trace = buildTrace(graph, '/orphan')
139 expect(trace.length).toBe(1)
140 expect(trace[0]!.file).toBe('/orphan')
141 })
142
143 test('treats node with no reverse-edge map entry as entry', () => {
144 const graph = new ImportGraph()
145 graph.addEdge('/b', '/a', './b')
146
147 const trace = buildTrace(graph, '/b')
148 expect(trace[0]!.file).toBe('/a')
149 expect(trace[trace.length - 1]!.file).toBe('/b')
150 })
151
152 test('treats node with empty importers map as entry', () => {
153 const graph = new ImportGraph()
154 graph.addEdge('/a', '/b', './a')
155 graph.addEdge('/b', '/a', './b')
156 graph.invalidate('/a')
157
158 graph.addEdge('/b', '/a', './b')
159
160 const trace = buildTrace(graph, '/b')
161 expect(trace[0]!.file).toBe('/a')
162 expect(trace[trace.length - 1]!.file).toBe('/b')
163 })
164
165 test('prefers explicit entry over implicit no-importers entry', () => {
166 const graph = new ImportGraph()
167 graph.addEntry('/entry') // /entry -> /mid -> /leaf
168 graph.addEdge('/mid', '/entry', './mid')
169 graph.addEdge('/leaf', '/mid', './leaf')
170
171 const trace = buildTrace(graph, '/leaf')
172 expect(trace[0]!.file).toBe('/entry')
173 expect(trace[trace.length - 1]!.file).toBe('/leaf')
174 })
175
176 test('handles cycles without infinite loop', () => {
177 const graph = new ImportGraph()
178 graph.addEntry('/entry')
179 graph.addEdge('/a', '/entry', './a')
180 graph.addEdge('/b', '/a', './b')
181 graph.addEdge('/a', '/b', './a') // cycle: /a -> /b -> /a
182
183 const trace = buildTrace(graph, '/b')
184 // Should terminate and produce a trace ending at /b
185 expect(trace[trace.length - 1]!.file).toBe('/b')
186 expect(trace.length).toBeGreaterThanOrEqual(2)
187 })
188
189 test('handles fully disconnected node (no edges at all)', () => {
190 const graph = new ImportGraph()
191 const trace = buildTrace(graph, '/island')
192 expect(trace).toEqual([{ file: '/island', specifier: undefined }])
193 })
194})
195
196describe('formatViolation', () => {
197 test('formats specifier violation correctly', () => {
198 const info: ViolationInfo = {
199 env: 'client',
200 envType: 'client',
201 type: 'specifier',
202 behavior: 'error',
203 pattern: '@tanstack/react-start/server',
204 specifier: '@tanstack/react-start/server',
205 importer: '/project/src/routes/index.tsx',
206 trace: [
207 { file: '/project/src/main.tsx' },
208 { file: '/project/src/routes/index.tsx', specifier: './routes/index' },
209 ],
210 }
211
212 const formatted = formatViolation(info, '/project')
213
214 expect(formatted).toContain('Import denied in client environment')
215 expect(formatted).toContain('specifier pattern')
216 expect(formatted).toContain('@tanstack/react-start/server')
217 expect(formatted).toContain('src/routes/index.tsx')
218 expect(formatted).toContain('Trace:')
219 expect(formatted).toContain('(entry)')
220 })
221
222 test('formats file violation correctly', () => {
223 const info: ViolationInfo = {
224 env: 'client',
225 envType: 'client',
226 type: 'file',
227 behavior: 'mock',
228 pattern: '**/*.server.*',
229 specifier: './secret.server',
230 importer: '/project/src/edge-a.ts',
231 resolved: '/project/src/secret.server.ts',
232 trace: [],
233 }
234
235 const formatted = formatViolation(info, '/project')
236
237 expect(formatted).toContain('file pattern')
238 expect(formatted).toContain('**/*.server.*')
239 expect(formatted).toContain('src/secret.server.ts')
240 expect(formatted).toContain('Suggestions:')
241 expect(formatted).toContain('createServerFn().handler')
242 expect(formatted).toContain('createServerOnlyFn')
243 expect(formatted).toContain('createIsomorphicFn')
244 expect(formatted).toContain('Move the server-only import')
245 })
246
247 test('formats marker violation correctly', () => {
248 const info: ViolationInfo = {
249 env: 'client',
250 envType: 'client',
251 type: 'marker',
252 behavior: 'error',
253 specifier: '@tanstack/react-start/server-only',
254 importer: '/project/src/routes/index.tsx',
255 trace: [],
256 }
257
258 const formatted = formatViolation(info, '/project')
259
260 expect(formatted).toContain('marker')
261 expect(formatted).toContain('restricted to the opposite environment')
262 expect(formatted).toContain('Suggestions:')
263 expect(formatted).toContain('createServerFn')
264 })
265
266 test('client-in-server violation includes client-only suggestions', () => {
267 const info: ViolationInfo = {
268 env: 'ssr',
269 envType: 'server',
270 type: 'file',
271 behavior: 'mock',
272 pattern: '**/*.client.*',
273 specifier: './browser-api.client',
274 importer: '/project/src/routes/page.tsx',
275 resolved: '/project/src/browser-api.client.ts',
276 trace: [],
277 }
278
279 const formatted = formatViolation(info, '/project')
280
281 expect(formatted).toContain('Suggestions:')
282 expect(formatted).toContain('createClientOnlyFn')
283 expect(formatted).toContain('createIsomorphicFn')
284 expect(formatted).toContain('Move the client-only import')
285 expect(formatted).not.toContain('<ClientOnly')
286 })
287
288 test('env is printed with env type suffix', () => {
289 const info: ViolationInfo = {
290 env: 'ssr',
291 envType: 'server',
292 type: 'specifier',
293 behavior: 'error',
294 pattern: /^node:/,
295 specifier: 'node:fs',
296 importer: '/project/src/routes/page.tsx',
297 trace: [],
298 }
299
300 const formatted = formatViolation(info, '/project')
301 expect(formatted).toContain('Import denied in server environment')
302 })
303
304 test('client-in-server violation with JSX suggests ClientOnly', () => {
305 const info: ViolationInfo = {
306 env: 'ssr',
307 envType: 'server',
308 type: 'file',
309 behavior: 'mock',
310 pattern: '**/*.client.*',
311 specifier: './browser-api.client',
312 importer: '/project/src/routes/page.tsx',
313 resolved: '/project/src/browser-api.client.ts',
314 trace: [],
315 snippet: {
316 lines: [
317 ' 15 | <div>',
318 ' 16 | <h1>Page</h1>',
319 ' > 17 | <p>{getBrowserTitle()}</p>',
320 ' | ^',
321 ' 18 | </div>',
322 ],
323 highlightLine: 17,
324 location: '/project/src/routes/page.tsx:17:11',
325 },
326 }
327
328 const formatted = formatViolation(info, '/project')
329
330 expect(formatted).toContain('Suggestions:')
331 expect(formatted).toContain(
332 '<ClientOnly fallback={<Loading />}>...</ClientOnly>',
333 )
334 expect(formatted).toContain('createClientOnlyFn')
335 expect(formatted).toContain('createIsomorphicFn')
336 })
337
338 test('specifier violation in client env gets server-in-client suggestions', () => {
339 const info: ViolationInfo = {
340 env: 'client',
341 envType: 'client',
342 type: 'specifier',
343 behavior: 'error',
344 pattern: '@tanstack/react-start/server',
345 specifier: '@tanstack/react-start/server',
346 importer: '/project/src/routes/index.tsx',
347 trace: [],
348 }
349
350 const formatted = formatViolation(info, '/project')
351
352 expect(formatted).toContain('Suggestions:')
353 expect(formatted).toContain('createServerFn')
354 expect(formatted).toContain('createServerOnlyFn')
355 expect(formatted).toContain('createIsomorphicFn')
356 })
357
358 test('marker violation in server env gets client-in-server suggestions', () => {
359 const info: ViolationInfo = {
360 env: 'ssr',
361 envType: 'server',
362 type: 'marker',
363 behavior: 'error',
364 specifier: '@tanstack/react-start/client-only',
365 importer: '/project/src/routes/page.tsx',
366 trace: [],
367 }
368
369 const formatted = formatViolation(info, '/project')
370
371 expect(formatted).toContain('Suggestions:')
372 expect(formatted).toContain('createClientOnlyFn')
373 expect(formatted).toContain('createIsomorphicFn')
374 })
375
376 test('relativizes absolute-path specifiers in Import line and trace steps', () => {
377 // When an alias (e.g. ~/) is resolved by a transform plugin before
378 // resolveId, the specifier stored in the graph can be an absolute path.
379 // formatViolation should display it as a root-relative path.
380 const info: ViolationInfo = {
381 env: 'client',
382 envType: 'client',
383 type: 'file',
384 behavior: 'error',
385 pattern: '**/client/**',
386 specifier: '/project/src/utils/prisma',
387 importer: '/project/src/routes/signup.tsx',
388 resolved: '/project/src/utils/prisma.ts',
389 trace: [
390 { file: '/project/src/routes/signup.tsx' },
391 {
392 file: '/project/src/routes/signup.tsx',
393 specifier: '/project/src/utils/prisma',
394 },
395 ],
396 }
397
398 const formatted = formatViolation(info, '/project')
399
400 expect(formatted).toContain('Import: "src/utils/prisma"')
401 expect(formatted).not.toContain('Import: "/project/src/utils/prisma"')
402
403 expect(formatted).toContain('(import "src/utils/prisma")')
404 expect(formatted).not.toContain('(import "/project/src/utils/prisma")')
405 })
406
407 test('leaves non-absolute specifiers unchanged', () => {
408 const info: ViolationInfo = {
409 env: 'client',
410 envType: 'client',
411 type: 'specifier',
412 behavior: 'error',
413 pattern: '@tanstack/react-start/server',
414 specifier: '@tanstack/react-start/server',
415 importer: '/project/src/routes/index.tsx',
416 trace: [
417 {
418 file: '/project/src/routes/index.tsx',
419 specifier: './secret.server',
420 },
421 ],
422 }
423
424 const formatted = formatViolation(info, '/project')
425
426 expect(formatted).toContain('Import: "@tanstack/react-start/server"')
427 expect(formatted).toContain('(import "./secret.server")')
428 })
429})