Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

sourceLocation.test.ts

595 lines16.4 KB

1import { transformWithOxc } from 'vite'
2import { describe, expect, test } from 'vitest'
3import {
4 createImportSpecifierLocationIndex,
5 ImportLocCache,
6 addTraceImportLocations,
7 buildCodeSnippet,
8 buildLineIndex,
9 findImportStatementLocationFromTransformed,
10 findOriginalUsageLocation,
11 findPostCompileUsageLocation,
12 getOrCreateOriginalTransformResult,
13 normalizeSourceMap,
14 pickOriginalCodeFromSourcesContent,
15} from '../../src/import-protection/sourceLocation'
16import type {
17 SourceMapLike,
18 TransformResult,
19 TransformResultProvider,
20} from '../../src/import-protection/sourceLocation'
21​
22describe('pickOriginalCodeFromSourcesContent', () => {
23 test('picks exact matching source by path', () => {
24 const map = {
25 version: 3,
26 sources: ['src/a.ts', 'src/b.ts'],
27 names: [],
28 mappings: '',
29 sourcesContent: ['A', 'B'],
30 } satisfies SourceMapLike
31​
32 const picked = pickOriginalCodeFromSourcesContent(
33 map,
34 '/project/src/b.ts',
35 '/project',
36 )
37​
38 expect(picked).toBe('B')
39 })
40​
41 test('falls back to sourcesContent[0] when no match exists', () => {
42 const map = {
43 version: 3,
44 sources: ['src/a.ts'],
45 names: [],
46 mappings: '',
47 sourcesContent: ['A'],
48 } satisfies SourceMapLike
49​
50 const picked = pickOriginalCodeFromSourcesContent(
51 map,
52 '/project/src/does-not-exist.ts',
53 '/project',
54 )
55​
56 expect(picked).toBe('A')
57 })
58​
59 test('returns undefined when map is undefined', () => {
60 expect(
61 pickOriginalCodeFromSourcesContent(undefined, '/a.ts', '/'),
62 ).toBeUndefined()
63 })
64​
65 test('returns undefined when sourcesContent is missing', () => {
66 const map = {
67 version: 3,
68 sources: ['a.ts'],
69 names: [],
70 mappings: '',
71 } satisfies SourceMapLike
72​
73 expect(
74 pickOriginalCodeFromSourcesContent(map, '/a.ts', '/'),
75 ).toBeUndefined()
76 })
77​
78 test('returns undefined when sources array is empty', () => {
79 const map = {
80 version: 3,
81 sources: [],
82 names: [],
83 mappings: '',
84 sourcesContent: [],
85 } satisfies SourceMapLike
86​
87 expect(
88 pickOriginalCodeFromSourcesContent(map, '/a.ts', '/'),
89 ).toBeUndefined()
90 })
91​
92 test('picks best suffix-matching source when no exact match', () => {
93 const map = {
94 version: 3,
95 sources: ['../lib/util.ts', '../routes/page.tsx'],
96 names: [],
97 mappings: '',
98 sourcesContent: ['UTIL', 'PAGE'],
99 } satisfies SourceMapLike
100​
101 const picked = pickOriginalCodeFromSourcesContent(
102 map,
103 '/project/src/routes/page.tsx',
104 '/project',
105 )
106​
107 expect(picked).toBe('PAGE')
108 })
109​
110 test('skips null entries in sourcesContent', () => {
111 const map = {
112 version: 3,
113 sources: ['src/a.ts', 'src/b.ts'],
114 names: [],
115 mappings: '',
116 sourcesContent: [null, 'B'],
117 } satisfies SourceMapLike
118​
119 const picked = pickOriginalCodeFromSourcesContent(
120 map,
121 '/project/src/a.ts',
122 '/project',
123 )
124​
125 expect(picked).toBeUndefined()
126 })
127})
128​
129describe('buildLineIndex', () => {
130 test('single line — one offset at 0', () => {
131 const idx = buildLineIndex('hello')
132 expect(idx.offsets).toEqual([0])
133 })
134​
135 test('multiple lines', () => {
136 const idx = buildLineIndex('a\nb\nc')
137 // Lines start at offsets 0, 2, 4
138 expect(idx.offsets).toEqual([0, 2, 4])
139 })
140​
141 test('empty string', () => {
142 const idx = buildLineIndex('')
143 expect(idx.offsets).toEqual([0])
144 })
145​
146 test('trailing newline', () => {
147 const idx = buildLineIndex('a\n')
148 expect(idx.offsets).toEqual([0, 2])
149 })
150})
151​
152function makeTransformResult(code: string): TransformResult {
153 return {
154 code,
155 map: undefined,
156 originalCode: undefined,
157 }
159​
160describe('createImportSpecifierLocationIndex', () => {
161 test('finds first matching import location across static and dynamic forms', () => {
162 const finder = createImportSpecifierLocationIndex()
163 const code = [
164 `const later = import('./secret.server')`,
165 `import { getSecret } from './secret.server'`,
166 ].join('\n')
167​
168 expect(
169 finder.find(makeTransformResult(code), './secret.server'),
170 ).toBeGreaterThanOrEqual(0)
171 })
172​
173 test('reuses cached per-result index without changing results', () => {
174 const finder = createImportSpecifierLocationIndex()
175 const result = makeTransformResult(
176 `import { getSecret } from './secret.server'`,
177 )
178​
179 const first = finder.find(result, './secret.server')
180 const second = finder.find(result, './secret.server')
181​
182 expect(second).toBe(first)
183 expect(result.analysis?.importSpecifierLocationIndex).toBeDefined()
184 })
185​
186 test('returns -1 when source is absent', () => {
187 const finder = createImportSpecifierLocationIndex()
188 expect(
189 finder.find(makeTransformResult('const x = 1'), './secret.server'),
190 ).toBe(-1)
191 })
192​
193 test('finds dynamic imports with options', () => {
194 const finder = createImportSpecifierLocationIndex()
195 const code =
196 "const data = import('./secret.server', { with: { type: 'json' } })"
197​
198 expect(
199 finder.find(makeTransformResult(code), './secret.server'),
200 ).toBeGreaterThanOrEqual(0)
201 })
202​
203 test('finds specifier locations in decorated modules', () => {
204 const finder = createImportSpecifierLocationIndex()
205 const code = [
206 `@sealed class Example {}`,
207 `import { value } from './secret.server'`,
208 ].join('\n')
209​
210 expect(finder.find(makeTransformResult(code), './secret.server')).toBe(
211 code.indexOf('./secret.server'),
212 )
213 })
214​
215 test('finds import attributes syntax', () => {
216 const finder = createImportSpecifierLocationIndex()
217 const code = "import data from './secret.server' with { type: 'json' }"
218​
219 expect(
220 finder.find(makeTransformResult(code), './secret.server'),
221 ).toBeGreaterThanOrEqual(0)
222 })
223​
224 test('finds export-all declarations', () => {
225 const finder = createImportSpecifierLocationIndex()
226 const code = "export * from './secret.server'"
227​
228 expect(
229 finder.find(makeTransformResult(code), './secret.server'),
230 ).toBeGreaterThanOrEqual(0)
231 })
232​
233 test('returns earliest occurrence when the same specifier appears multiple times', () => {
234 const finder = createImportSpecifierLocationIndex()
235 const code = [
236 `export * from './secret.server'`,
237 `import { getSecret } from './secret.server'`,
238 `const later = import('./secret.server')`,
239 ].join('\n')
240​
241 const idx = finder.find(makeTransformResult(code), './secret.server')
242 expect(idx).toBe(code.indexOf('./secret.server'))
243 })
244​
245 test('reuses a lazily created original transform result', () => {
246 const result = makeTransformResult(`import { x } from './safe'`)
247 result.originalCode = `import { y } from './secret.server'`
248​
249 const first = getOrCreateOriginalTransformResult(result)
250 const second = getOrCreateOriginalTransformResult(result)
251​
252 expect(first).toBe(second)
253 expect(first?.code).toBe(result.originalCode)
254 })
255})
256​
257describe('normalizeSourceMap', () => {
258 test('normalizes sourcemap version, file, names, and sourcesContent', () => {
259 const normalized = normalizeSourceMap({
260 version: '3',
261 sources: ['src/a.ts'],
262 names: undefined as unknown as Array<string>,
263 sourcesContent: [null, 'A'],
264 mappings: '',
265 })
266​
267 expect(normalized).toEqual({
268 version: 3,
269 file: '',
270 sources: ['src/a.ts'],
271 names: [],
272 sourcesContent: ['', 'A'],
273 mappings: '',
274 })
275 })
276​
277 test('returns undefined for missing map', () => {
278 expect(normalizeSourceMap(undefined)).toBeUndefined()
279 expect(normalizeSourceMap(null)).toBeUndefined()
280 })
281})
282​
283describe('buildCodeSnippet', () => {
284 function makeProvider(
285 code: string,
286 originalCode?: string,
287 ): TransformResultProvider {
288 return {
289 getTransformResult: () => ({
290 code,
291 map: undefined,
292 originalCode,
293 }),
294 }
295 }
296​
297 test('builds snippet with context lines around target', () => {
298 const code = ['line1', 'line2', 'line3', 'line4', 'line5'].join('\n')
299 const provider = makeProvider(code)
300 const snippet = buildCodeSnippet(provider, '/test.ts', {
301 line: 3,
302 column: 1,
303 })
304​
305 expect(snippet).toBeDefined()
306 expect(snippet!.highlightLine).toBe(3)
307 expect(snippet!.lines.length).toBeGreaterThanOrEqual(5)
308 const markerLine = snippet!.lines.find((l) => l.startsWith(' >'))
309 expect(markerLine).toContain('line3')
310 })
311​
312 test('uses originalCode over transformed code when available', () => {
313 const provider = makeProvider('transformed', 'original line 1')
314 const snippet = buildCodeSnippet(provider, '/test.ts', {
315 line: 1,
316 column: 1,
317 })
318​
319 expect(snippet).toBeDefined()
320 const content = snippet!.lines.join('\n')
321 expect(content).toContain('original line 1')
322 expect(content).not.toContain('transformed')
323 })
324​
325 test('returns undefined when no transform result', () => {
326 const provider: TransformResultProvider = {
327 getTransformResult: () => undefined,
328 }
329 expect(
330 buildCodeSnippet(provider, '/test.ts', { line: 1, column: 1 }),
331 ).toBeUndefined()
332 })
333​
334 test('returns undefined when target line is out of range', () => {
335 const provider = makeProvider('one line')
336 expect(
337 buildCodeSnippet(provider, '/test.ts', { line: 999, column: 1 }),
338 ).toBeUndefined()
339 })
340​
341 test('includes column pointer on target line', () => {
342 const provider = makeProvider('const x = 1')
343 const snippet = buildCodeSnippet(provider, '/test.ts', {
344 line: 1,
345 column: 7,
346 })
347​
348 expect(snippet).toBeDefined()
349 const pointerLine = snippet!.lines.find((l) => l.includes('^'))
350 expect(pointerLine).toBeDefined()
351 })
352​
353 test('location string includes file:line:col', () => {
354 const provider = makeProvider('code')
355 const snippet = buildCodeSnippet(provider, '/test.ts', {
356 line: 1,
357 column: 5,
358 })
359​
360 expect(snippet!.location).toBe('/test.ts:1:5')
361 })
362​
363 test('respects custom contextLines parameter', () => {
364 const code = Array.from({ length: 20 }, (_, i) => `line${i + 1}`).join('\n')
365 const provider = makeProvider(code)
366 const snippet = buildCodeSnippet(
367 provider,
368 '/test.ts',
369 { line: 10, column: 1 },
370 1,
371 )
372​
373 expect(snippet).toBeDefined()
374 expect(snippet!.lines.length).toBe(4)
375 })
376})
377​
378describe('findOriginalUsageLocation', () => {
379 function makeProvider(
380 code: string,
381 originalCode?: string,
382 ): TransformResultProvider {
383 return {
384 getTransformResult: () => ({
385 code,
386 map: undefined,
387 originalCode,
388 }),
389 }
390 }
391​
392 test('prefers original usage site over import site when original code is available', () => {
393 const provider = makeProvider(
394 'const secretServerFn = createServerFn().handler(rpc())\n',
395 [
396 "import { createServerFn } from '@tanstack/react-start'",
397 "import { getSecret } from './secret.server'",
398 '',
399 'export const secretServerFn = createServerFn().handler(async () => {',
400 ' return getSecret()',
401 '})',
402 '',
403 'export function leakyReference() {',
404 ' return getSecret()',
405 '}',
406 ].join('\n'),
407 )
408​
409 expect(
410 findOriginalUsageLocation(
411 provider,
412 '/test/compiler-leak.ts',
413 './secret.server',
414 'client',
415 ),
416 ).toEqual({
417 file: '/test/compiler-leak.ts',
418 line: 9,
419 column: 10,
420 })
421 })
422​
423 test('returns undefined when original usage only exists inside compiler-safe boundary', () => {
424 const provider = makeProvider(
425 'export const safe = noop\n',
426 [
427 "import { createServerOnlyFn } from '@tanstack/react-start'",
428 "import { getSecret } from './secret.server'",
429 '',
430 'export const safe = createServerOnlyFn(() => {',
431 ' return getSecret()',
432 '})',
433 ].join('\n'),
434 )
435​
436 expect(
437 findOriginalUsageLocation(
438 provider,
439 '/test/boundary-safe.ts',
440 './secret.server',
441 'client',
442 ),
443 ).toBeUndefined()
444 })
445})
446​
447describe('ImportLocCache', () => {
448 test('stores and retrieves values', () => {
449 const cache = new ImportLocCache()
450 const entry = { line: 1, column: 1 }
451 cache.set('/a.ts::./b', entry)
452 expect(cache.get('/a.ts::./b')).toBe(entry)
453 expect(cache.has('/a.ts::./b')).toBe(true)
454 })
455​
456 test('returns undefined for missing keys', () => {
457 const cache = new ImportLocCache()
458 expect(cache.get('/missing::./b')).toBeUndefined()
459 expect(cache.has('/missing::./b')).toBe(false)
460 })
461​
462 test('stores null values (negative cache)', () => {
463 const cache = new ImportLocCache()
464 cache.set('/a.ts::./b', null)
465 expect(cache.has('/a.ts::./b')).toBe(true)
466 expect(cache.get('/a.ts::./b')).toBeNull()
467 })
468​
469 test('deleteByFile removes all entries for a file', () => {
470 const cache = new ImportLocCache()
471 cache.set('/a.ts::./x', { line: 1, column: 1 })
472 cache.set('/a.ts::./y', { line: 2, column: 1 })
473 cache.set('/b.ts::./x', { line: 3, column: 1 })
474​
475 cache.deleteByFile('/a.ts')
476​
477 expect(cache.has('/a.ts::./x')).toBe(false)
478 expect(cache.has('/a.ts::./y')).toBe(false)
479 expect(cache.has('/b.ts::./x')).toBe(true)
480 })
481​
482 test('deleteByFile is a no-op for unknown files', () => {
483 const cache = new ImportLocCache()
484 cache.set('/a.ts::./x', { line: 1, column: 1 })
485 cache.deleteByFile('/unknown.ts')
486 expect(cache.has('/a.ts::./x')).toBe(true)
487 })
488​
489 test('clear removes all entries', () => {
490 const cache = new ImportLocCache()
491 cache.set('/a.ts::./x', { line: 1, column: 1 })
492 cache.set('/b.ts::./y', { line: 2, column: 1 })
493 cache.clear()
494 expect(cache.has('/a.ts::./x')).toBe(false)
495 expect(cache.has('/b.ts::./y')).toBe(false)
496 })
497})
498​
499describe('locations through a real source map', () => {
500 const file = '/root/src/page.tsx'
501 // Multi-byte characters before the import shift every generated column.
502 const original = `// ünïcödé 👨‍👩‍👧 comment
503import type { Shape } from './types'
504import { getSecret } from './secret.server'
505interface Props { shape: Shape }
506export const Page = ({ shape }: Props) => <div title="é">{getSecret(shape)}</div>
508​
509 const importLocation = {
510 file,
511 line: 3,
512 column: original.split('\n')[2]!.indexOf("'./secret.server'") + 1,
513 }
514​
515 async function createProvider(): Promise<TransformResultProvider> {
516 const output = await transformWithOxc(original, file, {
517 jsx: 'preserve',
518 sourcemap: true,
519 })
520 const result: TransformResult = {
521 code: output.code,
522 map: {
523 ...output.map!,
524 file: undefined,
525 sourceRoot: '/root/',
526 sources: ['src/page.tsx'],
527 sourcesContent: [original],
528 },
529 originalCode: undefined,
530 filename: file,
531 }
532 return { getTransformResult: () => result }
533 }
534​
535 function findSpecifier() {
536 const index = createImportSpecifierLocationIndex()
537 return (result: TransformResult, source: string) =>
538 index.find(result, source)
539 }
540​
541 test('import and usage locations map back to the original source', async () => {
542 const provider = await createProvider()
543 expect(
544 await findImportStatementLocationFromTransformed(
545 provider,
546 file,
547 './secret.server',
548 new ImportLocCache(),
549 findSpecifier(),
550 ),
551 ).toEqual(importLocation)
552 const usageLine = original.split('\n')[4]!
553 const usage = { file, line: 5, column: usageLine.indexOf('getSecret(') + 1 }
554 expect(
555 await findPostCompileUsageLocation(provider, file, './secret.server'),
556 ).toEqual(usage)
557 expect(
558 findOriginalUsageLocation(
559 provider,
560 file,
561 './secret.server',
562 'client',
563 '/root',
564 ),
565 ).toEqual(usage)
566 })
567​
568 test('trace steps that import a specifier get the original import line', async () => {
569 const provider = await createProvider()
570 const trace: Array<{
571 file: string
572 specifier?: string
573 line?: number
574 column?: number
575 }> = [
576 { file: '/root/src/entry.tsx' },
577 { file, specifier: './secret.server' },
578 // A second lookup of the same specifier exercises the cache-hit path.
579 { file, specifier: './secret.server' },
580 { file, specifier: './types', line: 1, column: 1 },
581 ]
582 await addTraceImportLocations(
583 provider,
584 trace,
585 new ImportLocCache(),
586 findSpecifier(),
587 )
588 expect(trace).toEqual([
589 { file: '/root/src/entry.tsx' },
590 { specifier: './secret.server', ...importLocation },
591 { specifier: './secret.server', ...importLocation },
592 { file, specifier: './types', line: 1, column: 1 },
593 ])
594 })
595})