Open History to see the last commit
1import { describe, expect, test } from 'vitest'
2import { getImportSources } from '../../src/import-protection/analysis'
3import { escapeRegExp } from '../../src/utils'
4β
5import {
6 buildResolutionCandidates,
7 buildSourceCandidates,
8 canonicalizeResolvedId,
9 checkFileDenial,
10 dedupeViolationKey,
11 dedupePatterns,
12 getOrCreate,
13 isInsideDirectory,
14 isFileExcluded,
15 normalizeFilePath,
16 relativizePath,
17 shouldDeferViolation,
18 stripQuery,
19 stripQueryAndHash,
20 withoutKnownExtension,
21} from '../../src/import-protection/utils'
22import { compileMatchers } from '../../src/import-protection/matchers'
23import { formatViolation } from '../../src/import-protection/trace'
24β
25describe('dedupePatterns', () => {
26 test('dedupes strings and preserves first occurrence order', () => {
27 expect(dedupePatterns(['a', 'b', 'a', 'c', 'b'])).toEqual(['a', 'b', 'c'])
28 })
29β
30 test('dedupes regexes by toString() and preserves first occurrence order', () => {
31 const a1 = /foo/i
32 const a2 = /foo/i
33 const b = /bar/
34β
35 const out = dedupePatterns([a1, b, a2, b])
36 expect(out).toEqual([a1, b])
37 })
38β
39 test('treats strings and regexes as distinct keys', () => {
40 const out = dedupePatterns(['/foo/i', /foo/i, '/foo/i', /foo/i])
41 expect(out).toEqual(['/foo/i', /foo/i])
42 })
43β
44 test('returns empty array for empty input', () => {
45 expect(dedupePatterns([])).toEqual([])
46 })
47})
48β
49describe('stripQueryAndHash', () => {
50 test('strips ?query params', () => {
51 expect(stripQueryAndHash('/a/b.ts?x=1')).toBe('/a/b.ts')
52 })
53β
54 test('strips #fragments', () => {
55 expect(stripQueryAndHash('/a/b.ts#hash')).toBe('/a/b.ts')
56 })
57β
58 test('strips whichever comes first of ? and #', () => {
59 expect(stripQueryAndHash('/a/b.ts?x=1#hash')).toBe('/a/b.ts')
60 expect(stripQueryAndHash('/a/b.ts#hash?x=1')).toBe('/a/b.ts')
61 })
62β
63 test('returns path unchanged when no query or fragment', () => {
64 expect(stripQueryAndHash('/a/b.ts')).toBe('/a/b.ts')
65 })
66})
67β
68describe('stripQuery', () => {
69 test('strips query params only', () => {
70 expect(stripQuery('/a/b.ts?x=1')).toBe('/a/b.ts')
71 expect(stripQuery('/a/b.ts#hash')).toBe('/a/b.ts#hash')
72 })
73})
74β
75describe('withoutKnownExtension', () => {
76 test('removes known source extension', () => {
77 expect(withoutKnownExtension('/a/b.ts')).toBe('/a/b')
78 expect(withoutKnownExtension('/a/b.tsx')).toBe('/a/b')
79 })
80β
81 test('keeps unknown extension', () => {
82 expect(withoutKnownExtension('/a/b.css')).toBe('/a/b.css')
83 })
84})
85β
86describe('buildSourceCandidates', () => {
87 test('includes source and resolved variants', () => {
88 const out = buildSourceCandidates('src/mod.ts', '/app/src/mod.ts', '/app')
89 expect(out.has('src/mod.ts')).toBe(true)
90 expect(out.has('src/mod')).toBe(true)
91 expect(out.has('/app/src/mod.ts')).toBe(true)
92 expect(out.has('/app/src/mod')).toBe(true)
93 expect(out.has('./src/mod.ts')).toBe(true)
94 expect(out.has('/src/mod.ts')).toBe(true)
95 })
96})
97β
98describe('checkFileDenial', () => {
99 test('returns matching file matcher when file is denied', () => {
100 const matchers = {
101 files: compileMatchers(['**/*.server.*']),
102 excludeFiles: compileMatchers([]),
103 }
104β
105 const result = checkFileDenial('src/secret.server.ts', matchers)
106β
107 expect(result?.pattern).toBe('**/*.server.*')
108 })
109β
110 test('returns undefined when file is excluded', () => {
111 const matchers = {
112 files: compileMatchers(['**/*.server.*']),
113 excludeFiles: compileMatchers(['**/node_modules/**']),
114 }
115β
116 expect(
117 checkFileDenial('node_modules/pkg/index.server.js', matchers),
118 ).toBeUndefined()
119 })
120})
121β
122describe('isFileExcluded', () => {
123 test('returns true when exclude matcher matches', () => {
124 const matchers = {
125 excludeFiles: compileMatchers(['**/node_modules/**']),
126 }
127β
128 expect(isFileExcluded('node_modules/pkg/index.server.js', matchers)).toBe(
129 true,
130 )
131 })
132β
133 test('returns false when exclude matcher does not match', () => {
134 const matchers = {
135 excludeFiles: compileMatchers(['**/node_modules/**']),
136 }
137β
138 expect(isFileExcluded('src/secret.server.ts', matchers)).toBe(false)
139 })
140})
141β
142describe('buildResolutionCandidates', () => {
143 test('returns deduped id variants', () => {
144 expect(buildResolutionCandidates('/a/b.ts?x=1')).toEqual([
145 '/a/b.ts?x=1',
146 '/a/b.ts',
147 ])
148 })
149})
150β
151describe('canonicalizeResolvedId', () => {
152 test('normalizes and resolves non-absolute ids against root', () => {
153 const root = process.cwd().replaceAll('\\', '/')
154 expect(canonicalizeResolvedId('src/a.ts?x=1', root, (id) => id)).toBe(
155 `${root}/src/a.ts`,
156 )
157 })
158β
159 test('keeps absolute ids as absolute', () => {
160 expect(
161 canonicalizeResolvedId('/app/src/a.ts?x=1', '/app', (id) => id),
162 ).toBe('/app/src/a.ts')
163 })
164})
165β
166describe('shouldDeferViolation', () => {
167 test('defers in build mode', () => {
168 expect(shouldDeferViolation({ isBuild: true, isDevMock: false })).toBe(true)
169 })
170β
171 test('defers in dev mock mode', () => {
172 expect(shouldDeferViolation({ isBuild: false, isDevMock: true })).toBe(true)
173 })
174β
175 test('defers in build + dev mock', () => {
176 expect(shouldDeferViolation({ isBuild: true, isDevMock: true })).toBe(true)
177 })
178β
179 test('does not defer in dev error mode', () => {
180 expect(shouldDeferViolation({ isBuild: false, isDevMock: false })).toBe(
181 false,
182 )
183 })
184})
185β
186describe('dedupeViolationKey', () => {
187 test('includes resolved path when present', () => {
188 expect(
189 dedupeViolationKey({
190 type: 'file',
191 importer: '/app/src/a.ts',
192 specifier: './secret.server',
193 resolved: '/app/src/secret.server.ts',
194 }),
195 ).toBe('file:/app/src/a.ts:./secret.server:/app/src/secret.server.ts')
196 })
197β
198 test('uses empty resolved segment when resolved is absent', () => {
199 expect(
200 dedupeViolationKey({
201 type: 'specifier',
202 importer: '/app/src/a.ts',
203 specifier: '@tanstack/react-start/server',
204 }),
205 ).toBe('specifier:/app/src/a.ts:@tanstack/react-start/server:')
206 })
207})
208β
209describe('isInsideDirectory', () => {
210 test('returns true for file inside directory', () => {
211 expect(isInsideDirectory('/app/src/foo.ts', '/app/src')).toBe(true)
212 })
213β
214 test('returns true for file in nested subdirectory', () => {
215 expect(isInsideDirectory('/app/src/deep/nested/foo.ts', '/app/src')).toBe(
216 true,
217 )
218 })
219β
220 test('returns false for sibling directory with same prefix', () => {
221 expect(isInsideDirectory('/app/src2/foo.ts', '/app/src')).toBe(false)
222 })
223β
224 test('returns false for parent directory', () => {
225 expect(isInsideDirectory('/app/foo.ts', '/app/src')).toBe(false)
226 })
227β
228 test('returns false for exact directory match (no file inside)', () => {
229 expect(isInsideDirectory('/app/src', '/app/src')).toBe(false)
230 })
231})
232β
233describe('normalizeFilePath', () => {
234 test('strips query params', () => {
235 expect(normalizeFilePath('/a/b.ts?v=123')).toBe('/a/b.ts')
236 })
237β
238 test('returns plain path unchanged', () => {
239 expect(normalizeFilePath('/a/b.ts')).toBe('/a/b.ts')
240 })
241β
242 test('returns cached result on second call', () => {
243 const input = '/unique/cache-test/file.ts?q=1'
244 const first = normalizeFilePath(input)
245 const second = normalizeFilePath(input)
246 expect(first).toBe(second)
247 expect(first).toBe('/unique/cache-test/file.ts')
248 })
249β
250 test('handles path with both query and hash', () => {
251 expect(normalizeFilePath('/a/b.ts?x=1#hash')).toBe('/a/b.ts')
252 })
253})
254β
255describe('getImportSources', () => {
256 test('extracts static import sources', () => {
257 const code = `import { foo } from 'bar'\nimport baz from "qux"`
258 expect(getImportSources(code)).toEqual(['bar', 'qux'])
259 })
260β
261 test('skips type-only static import sources', () => {
262 const code = [
263 `import type { Foo } from './foo.server'`,
264 `import { type Bar } from './bar.server'`,
265 ].join('\n')
266 expect(getImportSources(code)).toEqual([])
267 })
268β
269 test('keeps mixed type and value static import sources', () => {
270 const code = `import { type Foo, bar } from './mixed.server'`
271 expect(getImportSources(code)).toEqual(['./mixed.server'])
272 })
273β
274 test('keeps side-effect import sources', () => {
275 const code = `import './setup.server'`
276 expect(getImportSources(code)).toEqual(['./setup.server'])
277 })
278β
279 test('extracts re-export sources', () => {
280 const code = `export { a } from './mod'\nexport * from "./other"`
281 expect(getImportSources(code)).toEqual(['./mod', './other'])
282 })
283β
284 test('skips type-only re-export sources', () => {
285 const code = [
286 `export type { Foo } from './foo.server'`,
287 `export { type Bar } from './bar.server'`,
288 `export type * from './baz.server'`,
289 ].join('\n')
290 expect(getImportSources(code)).toEqual([])
291 })
292β
293 test('keeps mixed type and value re-export sources', () => {
294 const code = `export { type Foo, bar } from './mixed.server'`
295 expect(getImportSources(code)).toEqual(['./mixed.server'])
296 })
297β
298 test('extracts dynamic import sources', () => {
299 const code = `const m = import('./lazy')\nconst n = import("./lazy2")`
300 expect(getImportSources(code)).toEqual(['./lazy', './lazy2'])
301 })
302β
303 test('handles mixed import styles', () => {
304 const code = [
305 `import { a } from 'static'`,
306 `export { b } from './reexport'`,
307 `const c = import('./dynamic')`,
308 ].join('\n')
309 expect(getImportSources(code)).toEqual([
310 'static',
311 './reexport',
312 './dynamic',
313 ])
314 })
315β
316 test('extracts imports from decorated modules', () => {
317 const code = [
318 `@sealed class Example {}`,
319 `import { value } from 'broken'`,
320 ].join('\n')
321 expect(getImportSources(code)).toEqual(['broken'])
322 })
323β
324 test('returns empty array for code with no imports', () => {
325 expect(getImportSources('const x = 1')).toEqual([])
326 })
327β
328 test('handles empty string', () => {
329 expect(getImportSources('')).toEqual([])
330 })
331β
332 test('does not match import in comments or strings', () => {
333 const code = `// import { x } from 'commented'`
334 expect(getImportSources(code)).toEqual([])
335 })
336β
337 test('extracts import attributes syntax', () => {
338 const code = `import data from './data.json' with { type: 'json' }`
339 expect(getImportSources(code)).toEqual(['./data.json'])
340 })
341})
342β
343describe('escapeRegExp', () => {
344 test('escapes special regex characters', () => {
345 expect(escapeRegExp('a.b*c?d')).toBe('a\\.b\\*c\\?d')
346 })
347β
348 test('escapes all special characters', () => {
349 const specials = '.*+?^${}()|[]\\'
350 const escaped = escapeRegExp(specials)
351 expect(new RegExp(escaped).test(specials)).toBe(true)
352 })
353β
354 test('returns plain strings unchanged', () => {
355 expect(escapeRegExp('foobar')).toBe('foobar')
356 })
357β
358 test('handles empty string', () => {
359 expect(escapeRegExp('')).toBe('')
360 })
361})
362β
363describe('getOrCreate', () => {
364 test('creates value when key is absent', () => {
365 const map = new Map<string, Array<number>>()
366 const result = getOrCreate(map, 'a', () => [1, 2])
367 expect(result).toEqual([1, 2])
368 expect(map.get('a')).toBe(result)
369 })
370β
371 test('returns existing value without calling factory', () => {
372 const map = new Map<string, Array<number>>([['a', [1]]])
373 let factoryCalled = false
374 const result = getOrCreate(map, 'a', () => {
375 factoryCalled = true
376 return [99]
377 })
378 expect(result).toEqual([1])
379 expect(factoryCalled).toBe(false)
380 })
381β
382 test('works with Set values', () => {
383 const map = new Map<string, Set<string>>()
384 const set = getOrCreate(map, 'k', () => new Set())
385 set.add('v')
386 expect(map.get('k')?.has('v')).toBe(true)
387 })
388})
389β
390describe('relativizePath', () => {
391 test('strips root prefix and leading slash', () => {
392 expect(
393 relativizePath('/Users/foo/project/src/bar.ts', '/Users/foo/project'),
394 ).toBe('src/bar.ts')
395 })
396β
397 test('returns path as-is when it does not start with root', () => {
398 expect(relativizePath('some-module', '/Users/foo/project')).toBe(
399 'some-module',
400 )
401 })
402β
403 test('handles root with trailing content that is not a separator', () => {
404 // /Users/foo/project-extra should NOT match root /Users/foo/project
405 expect(
406 relativizePath('/Users/foo/project-extra/bar.ts', '/Users/foo/project'),
407 ).toBe('/Users/foo/project-extra/bar.ts')
408 })
409β
410 test('returns empty string when path equals root + slash', () => {
411 expect(relativizePath('/Users/foo/project/', '/Users/foo/project')).toBe('')
412 })
413})