Skip to content

Commit 0f7c348

Browse files
committed
fix: resolve excessive relative import
1 parent 93011e0 commit 0f7c348

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

packages/parse/__tests__/collect.test.ts

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -259,6 +259,41 @@ describe('SourceCollector', () => {
259259
});
260260
});
261261

262+
it('should not resolve excessive ../ paths that go beyond root', () => {
263+
const files = [
264+
{
265+
path: 'packages/parse/src/main.ts',
266+
content: 'import { dec } from "../../../../docs/test.ts";',
267+
},
268+
{ path: 'docs/test.ts', content: 'export const dec = 1;' },
269+
];
270+
271+
const result = collector.collect('packages/parse/src/main.ts', files);
272+
273+
// Should only include the entry file, not the incorrectly resolved target
274+
expect(result).toEqual({
275+
'packages/parse/src/main.ts': 'import { dec } from "../../../../docs/test.ts";',
276+
});
277+
expect(result['docs/test.ts']).toBeUndefined();
278+
});
279+
280+
it('should handle multiple excessive ../ at the beginning', () => {
281+
const files = [
282+
{
283+
path: 'src/main.ts',
284+
content: 'import { foo } from "../../../../../../../../utils/helper.ts";',
285+
},
286+
{ path: 'utils/helper.ts', content: 'export const foo = 1;' },
287+
];
288+
289+
const result = collector.collect('src/main.ts', files);
290+
291+
expect(result).toEqual({
292+
'src/main.ts': 'import { foo } from "../../../../../../../../utils/helper.ts";',
293+
});
294+
expect(result['utils/helper.ts']).toBeUndefined();
295+
});
296+
262297
it('should handle files with only comments', () => {
263298
const files = [
264299
{ path: 'main.ts', content: '// This is a comment\n/* Block comment */' },

packages/parse/src/collect.ts

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -315,11 +315,18 @@ export class SourceCollector {
315315
const importParts = importPath.split('/');
316316

317317
let i = 0;
318-
while (i < importParts.length && importParts[i] === '..') {
318+
while (i < importParts.length && importParts[i] === '..' && pathParts.length > 0) {
319319
pathParts.pop();
320320
i++;
321321
}
322322

323+
// If there are still '..' parts but no more parent directories,
324+
// the path is invalid (goes beyond root)
325+
if (i < importParts.length && importParts[i] === '..') {
326+
// Return an invalid path that won't resolve
327+
return `__INVALID_PATH__/${importPath}`;
328+
}
329+
323330
const remainingParts = importParts.slice(i);
324331
return [...pathParts, ...remainingParts].join('/');
325332
}

0 commit comments

Comments
 (0)