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