From 919b735639466571a5ee45ca243c2af1e117333e Mon Sep 17 00:00:00 2001 From: Yusuke Tanaka Date: Fri, 6 Nov 2026 19:58:07 +0900 Subject: [PATCH 1/3] fix(clean): skip paths outside the project root --- docs/options/cleaning.md | 2 + docs/zh-CN/options/cleaning.md | 2 + schema.json | 4 +- skills/tsdown/references/option-cleaning.md | 4 + src/config/types.ts | 2 + src/features/clean.ts | 56 ++++++- ...ean-paths-outside-the-project-root.snap.md | 8 + tests/clean.test.ts | 155 +++++++++++++++++- 8 files changed, 227 insertions(+), 6 deletions(-) create mode 100644 tests/__snapshots__/clean/should-not-clean-paths-outside-the-project-root.snap.md diff --git a/docs/options/cleaning.md b/docs/options/cleaning.md index ebee8103e..390e8efdf 100644 --- a/docs/options/cleaning.md +++ b/docs/options/cleaning.md @@ -10,3 +10,5 @@ tsdown --no-clean > [!NOTE] > By default, all files in the output directory will be removed before the build process begins. Make sure this behavior aligns with your project requirements to avoid accidentally deleting important files. +> +> Paths outside the project root are never cleaned, and tsdown does not delete files through symbolic links. If tsdown skips a matched path for this reason, it logs a warning. diff --git a/docs/zh-CN/options/cleaning.md b/docs/zh-CN/options/cleaning.md index ba17f7e81..ae3eb4c4e 100644 --- a/docs/zh-CN/options/cleaning.md +++ b/docs/zh-CN/options/cleaning.md @@ -10,3 +10,5 @@ tsdown --no-clean > [!NOTE] > 默认情况下,输出目录中的所有文件将在构建过程开始之前被删除。请确保此行为符合您的项目需求,以避免意外删除重要文件。 +> +> 项目根目录之外的路径永远不会被清理,`tsdown` 也不会通过符号链接删除文件。如果 `tsdown` 因此跳过了匹配到的路径,会输出警告。 diff --git a/schema.json b/schema.json index 315e902af..71a02cb56 100644 --- a/schema.json +++ b/schema.json @@ -155,7 +155,7 @@ { "const": true }, { "type": "array", "items": { "type": "string" } } ], - "description": "Clean directories before build.\n\nDefault to output directory.", + "description": "Clean directories before build.\n\nDefault to output directory.\n\nPaths outside the project root are never cleaned.", "default": true }, "minify": { @@ -523,7 +523,7 @@ { "const": true }, { "type": "array", "items": { "type": "string" } } ], - "description": "Clean directories before build.\n\nDefault to output directory.", + "description": "Clean directories before build.\n\nDefault to output directory.\n\nPaths outside the project root are never cleaned.", "default": true }, "minify": { diff --git a/skills/tsdown/references/option-cleaning.md b/skills/tsdown/references/option-cleaning.md index 9afa0f806..86ee9e210 100644 --- a/skills/tsdown/references/option-cleaning.md +++ b/skills/tsdown/references/option-cleaning.md @@ -57,6 +57,10 @@ export default defineConfig({ - Preserving other files - Watch mode (faster rebuilds) +### Paths Outside the Project Root + +tsdown never cleans paths outside the project root, and it does not delete files through symbolic links. A symbolic link inside the project root is removed as a link, and its target is kept. If tsdown skips a matched path for this reason, it logs a warning. The `outDir` directory itself is never removed, only its contents. + ## Common Patterns ### Production Build diff --git a/src/config/types.ts b/src/config/types.ts index 1ce0d28a2..daecdf088 100644 --- a/src/config/types.ts +++ b/src/config/types.ts @@ -397,6 +397,8 @@ export interface UserConfig { * Clean directories before build. * * Default to output directory. + * + * Paths outside the project root are never cleaned. * @default true */ clean?: boolean | string[] diff --git a/src/features/clean.ts b/src/features/clean.ts index 5ab936b03..edebdf0c2 100644 --- a/src/features/clean.ts +++ b/src/features/clean.ts @@ -1,3 +1,4 @@ +import { realpath } from 'node:fs/promises' import path from 'node:path' import { createDebug } from 'obug' import { glob } from 'tinyglobby' @@ -13,6 +14,7 @@ const RE_LAST_SLASH = /[/\\]$/ export async function cleanOutDir(configs: ResolvedConfig[]): Promise { const removes = new Set() + const skipped = new Set() for (const config of configs) { if (config.devtools && (config.devtools.clean ?? true)) { @@ -33,13 +35,31 @@ export async function cleanOutDir(configs: ResolvedConfig[]): Promise { }) const normalizedOutDir = config.outDir.replace(RE_LAST_SLASH, '') + const realCwd = await realpath(config.cwd) + const realDirs = new Map>() for (const file of files) { const normalizedFile = file.replace(RE_LAST_SLASH, '') - if (normalizedFile !== normalizedOutDir) { - removes.add(file) + if (normalizedFile === normalizedOutDir) continue + if ( + !isInsideDir(normalizedFile, config.cwd) || + !(await isRealPathInside(normalizedFile, realCwd, realDirs)) + ) { + skipped.add(normalizedFile) + continue } + removes.add(file) } } + + if (skipped.size) { + const shown = [...skipped].slice(0, 5).map((file) => ` - ${file}`) + if (skipped.size > shown.length) { + shown.push(` ...and ${skipped.size - shown.length} more`) + } + globalLogger.warn( + `Skipped cleaning ${skipped.size} path(s) outside the project root:\n${shown.join('\n')}`, + ) + } if (!removes.size) return globalLogger.info(`Cleaning ${removes.size} files`) @@ -52,6 +72,38 @@ export async function cleanOutDir(configs: ResolvedConfig[]): Promise { debug('Removed %d files', removes.size) } +/** + * Checks the real location of `file` without following `file` itself, so a + * symlink inside the root is removed as a link, but nothing is removed through + * a symlinked parent directory. + */ +async function isRealPathInside( + file: string, + realCwd: string, + realDirs: Map>, +): Promise { + const dir = path.dirname(file) + let realDir = realDirs.get(dir) + if (!realDir) { + realDir = realpath(dir).catch(() => undefined) + realDirs.set(dir, realDir) + } + const resolved = await realDir + return ( + !!resolved && isInsideDir(path.join(resolved, path.basename(file)), realCwd) + ) +} + +function isInsideDir(file: string, dir: string): boolean { + const relative = path.relative(dir, file) + return ( + !!relative && + relative !== '..' && + !relative.startsWith(`..${path.sep}`) && + !path.isAbsolute(relative) + ) +} + export function resolveClean( clean: UserConfig['clean'], outDir: string, diff --git a/tests/__snapshots__/clean/should-not-clean-paths-outside-the-project-root.snap.md b/tests/__snapshots__/clean/should-not-clean-paths-outside-the-project-root.snap.md new file mode 100644 index 000000000..de6629e3f --- /dev/null +++ b/tests/__snapshots__/clean/should-not-clean-paths-outside-the-project-root.snap.md @@ -0,0 +1,8 @@ +## index.mjs + +```mjs +// index.ts +const hello = "world"; +export { hello }; + +``` diff --git a/tests/clean.test.ts b/tests/clean.test.ts index 2b25cf6b8..62696808c 100644 --- a/tests/clean.test.ts +++ b/tests/clean.test.ts @@ -1,9 +1,24 @@ -import { mkdir, writeFile } from 'node:fs/promises' +import { lstat, mkdir, rm, symlink, writeFile } from 'node:fs/promises' import path from 'node:path' -import { describe, expect, test } from 'vitest' +import process from 'node:process' +import { describe, expect, test, type TestContext } from 'vitest' import { fsExists } from '../src/utils/fs.ts' import { getTestDir, testBuild } from './utils.ts' +async function createOutsideDir( + context: TestContext, + testDir: string, +): Promise { + const outsidePath = `${testDir}-outside` + await rm(outsidePath, { recursive: true, force: true }) + context.onTestFinished(() => + rm(outsidePath, { recursive: true, force: true }), + ) + await mkdir(outsidePath, { recursive: true }) + await writeFile(path.join(outsidePath, 'keep.txt'), 'keep me') + return outsidePath +} + describe('clean', () => { test('should clean dist directory by default', async (context) => { const files = { @@ -159,6 +174,142 @@ describe('clean', () => { ).rejects.toThrow('Cannot clean the current working directory') }) + test('should not clean paths outside the project root', async (context) => { + const files = { + 'index.ts': 'export const hello = "world"', + } + + const testDir = getTestDir(context.task) + const outsidePath = await createOutsideDir(context, testDir) + + await testBuild({ + context, + files, + options: { + clean: [`../${path.basename(outsidePath)}`], + }, + }) + + expect(await fsExists(path.join(outsidePath, 'keep.txt'))).toBe(true) + }) + + test('should not clean outDir outside the project root', async (context) => { + const files = { + 'index.ts': 'export const hello = "world"', + } + + const testDir = getTestDir(context.task) + const outsidePath = await createOutsideDir(context, testDir) + + await testBuild({ + context, + files, + options: { + outDir: `../${path.basename(outsidePath)}`, + }, + snapshot: false, + }) + + expect(await fsExists(path.join(outsidePath, 'keep.txt'))).toBe(true) + }) + + test('should not clean through a symlinked directory', async (context) => { + const files = { + 'index.ts': 'export const hello = "world"', + } + + const testDir = getTestDir(context.task) + const outsidePath = await createOutsideDir(context, testDir) + await mkdir(path.join(testDir, 'temp'), { recursive: true }) + await symlink(outsidePath, path.join(testDir, 'temp', 'link'), 'junction') + + await testBuild({ + context, + files, + options: { + clean: ['temp/*/keep.txt'], + }, + snapshot: false, + }) + + expect(await fsExists(path.join(outsidePath, 'keep.txt'))).toBe(true) + }) + + test('should not clean under a symlinked parent directory', async (context) => { + const files = { + 'index.ts': 'export const hello = "world"', + } + + const testDir = getTestDir(context.task) + const outsidePath = await createOutsideDir(context, testDir) + await mkdir(path.join(outsidePath, 'session'), { recursive: true }) + await writeFile(path.join(outsidePath, 'session', 'keep.txt'), 'keep me') + await mkdir(testDir, { recursive: true }) + await symlink(outsidePath, path.join(testDir, 'cache'), 'junction') + + await testBuild({ + context, + files, + options: { + clean: ['cache/session/**'], + }, + snapshot: false, + }) + + expect(await fsExists(path.join(outsidePath, 'session', 'keep.txt'))).toBe( + true, + ) + }) + + test.skipIf(process.platform === 'win32')( + 'should remove a symlink itself, not its target', + async (context) => { + const files = { + 'index.ts': 'export const hello = "world"', + } + + const testDir = getTestDir(context.task) + const outsidePath = await createOutsideDir(context, testDir) + const linkPath = path.join(testDir, 'temp', 'link') + await mkdir(path.dirname(linkPath), { recursive: true }) + await symlink(path.join(outsidePath, 'keep.txt'), linkPath) + + await testBuild({ + context, + files, + options: { + clean: ['temp/link'], + }, + snapshot: false, + }) + + await expect(lstat(linkPath)).rejects.toThrow() + expect(await fsExists(path.join(outsidePath, 'keep.txt'))).toBe(true) + }, + ) + + test('should clean a directory whose name starts with ..', async (context) => { + const files = { + 'index.ts': 'export const hello = "world"', + } + + const testDir = getTestDir(context.task) + const dotDotPath = path.join(testDir, '..cache') + await mkdir(dotDotPath, { recursive: true }) + await writeFile(path.join(dotDotPath, 'old.txt'), 'old') + + await testBuild({ + context, + files, + options: { + clean: ['..cache'], + }, + snapshot: false, + }) + + expect(await fsExists(dotDotPath)).toBe(false) + }) + test('should clean nested directories', async (context) => { const files = { 'index.ts': 'export const hello = "world"', From 38484ee94795c1e7ea07a0403aff50147a4bfd01 Mon Sep 17 00:00:00 2001 From: Yusuke Tanaka Date: Sun, 8 Nov 2026 15:33:05 +0900 Subject: [PATCH 2/3] fix(clean): log skipped paths through the config logger Use each config's logger for the warning about skipped paths, so that failOnWarn, suppressWarnings, and customLogger apply to it. --- src/features/clean.ts | 20 +++++++++++--------- tests/clean.test.ts | 40 +++++++++++++++++++++++++++++++++++++++- 2 files changed, 50 insertions(+), 10 deletions(-) diff --git a/src/features/clean.ts b/src/features/clean.ts index edebdf0c2..cbda64f39 100644 --- a/src/features/clean.ts +++ b/src/features/clean.ts @@ -14,7 +14,6 @@ const RE_LAST_SLASH = /[/\\]$/ export async function cleanOutDir(configs: ResolvedConfig[]): Promise { const removes = new Set() - const skipped = new Set() for (const config of configs) { if (config.devtools && (config.devtools.clean ?? true)) { @@ -37,6 +36,7 @@ export async function cleanOutDir(configs: ResolvedConfig[]): Promise { const normalizedOutDir = config.outDir.replace(RE_LAST_SLASH, '') const realCwd = await realpath(config.cwd) const realDirs = new Map>() + const skipped = new Set() for (const file of files) { const normalizedFile = file.replace(RE_LAST_SLASH, '') if (normalizedFile === normalizedOutDir) continue @@ -49,17 +49,19 @@ export async function cleanOutDir(configs: ResolvedConfig[]): Promise { } removes.add(file) } - } - if (skipped.size) { - const shown = [...skipped].slice(0, 5).map((file) => ` - ${file}`) - if (skipped.size > shown.length) { - shown.push(` ...and ${skipped.size - shown.length} more`) + if (skipped.size) { + const shown = [...skipped].slice(0, 5).map((file) => ` - ${file}`) + if (skipped.size > shown.length) { + shown.push(` ...and ${skipped.size - shown.length} more`) + } + config.logger.warn( + config.nameLabel, + `Skipped cleaning ${skipped.size} path(s) outside the project root:\n${shown.join('\n')}`, + ) } - globalLogger.warn( - `Skipped cleaning ${skipped.size} path(s) outside the project root:\n${shown.join('\n')}`, - ) } + if (!removes.size) return globalLogger.info(`Cleaning ${removes.size} files`) diff --git a/tests/clean.test.ts b/tests/clean.test.ts index 62696808c..3bc73cb30 100644 --- a/tests/clean.test.ts +++ b/tests/clean.test.ts @@ -1,7 +1,7 @@ import { lstat, mkdir, rm, symlink, writeFile } from 'node:fs/promises' import path from 'node:path' import process from 'node:process' -import { describe, expect, test, type TestContext } from 'vitest' +import { describe, expect, test, vi, type TestContext } from 'vitest' import { fsExists } from '../src/utils/fs.ts' import { getTestDir, testBuild } from './utils.ts' @@ -193,6 +193,44 @@ describe('clean', () => { expect(await fsExists(path.join(outsidePath, 'keep.txt'))).toBe(true) }) + test('should warn through the configured logger when skipping paths', async (context) => { + const files = { + 'index.ts': 'export const hello = "world"', + } + + const testDir = getTestDir(context.task) + const outsidePath = await createOutsideDir(context, testDir) + const warn = vi.fn() + + await testBuild({ + context, + files, + options: { + clean: [`../${path.basename(outsidePath)}`], + customLogger: { + level: 'info', + info: vi.fn(), + warn, + warnOnce: vi.fn(), + error: vi.fn(), + success: vi.fn(), + clearScreen: vi.fn(), + }, + }, + snapshot: false, + }) + + const messages = warn.mock.calls + .flat() + .filter((arg) => typeof arg === 'string') + expect( + messages.some((message) => + message.includes('Skipped cleaning 2 path(s) outside the project root'), + ), + ).toBe(true) + expect(await fsExists(path.join(outsidePath, 'keep.txt'))).toBe(true) + }) + test('should not clean outDir outside the project root', async (context) => { const files = { 'index.ts': 'export const hello = "world"', From 971951670b819839b631e91aff145dfbb3faa00b Mon Sep 17 00:00:00 2001 From: Yusuke Tanaka Date: Sun, 8 Nov 2026 18:33:39 +0900 Subject: [PATCH 3/3] docs(clean): clarify that only symlinks leading outside the root are skipped --- docs/options/cleaning.md | 2 +- docs/zh-CN/options/cleaning.md | 2 +- skills/tsdown/references/option-cleaning.md | 2 +- src/features/clean.ts | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/options/cleaning.md b/docs/options/cleaning.md index 390e8efdf..f268e624f 100644 --- a/docs/options/cleaning.md +++ b/docs/options/cleaning.md @@ -11,4 +11,4 @@ tsdown --no-clean > [!NOTE] > By default, all files in the output directory will be removed before the build process begins. Make sure this behavior aligns with your project requirements to avoid accidentally deleting important files. > -> Paths outside the project root are never cleaned, and tsdown does not delete files through symbolic links. If tsdown skips a matched path for this reason, it logs a warning. +> Paths outside the project root are never cleaned, and tsdown does not delete files through a symbolic link that points outside the project root. If tsdown skips a matched path for this reason, it logs a warning. diff --git a/docs/zh-CN/options/cleaning.md b/docs/zh-CN/options/cleaning.md index ae3eb4c4e..97fe7eef0 100644 --- a/docs/zh-CN/options/cleaning.md +++ b/docs/zh-CN/options/cleaning.md @@ -11,4 +11,4 @@ tsdown --no-clean > [!NOTE] > 默认情况下,输出目录中的所有文件将在构建过程开始之前被删除。请确保此行为符合您的项目需求,以避免意外删除重要文件。 > -> 项目根目录之外的路径永远不会被清理,`tsdown` 也不会通过符号链接删除文件。如果 `tsdown` 因此跳过了匹配到的路径,会输出警告。 +> 项目根目录之外的路径永远不会被清理,`tsdown` 也不会通过指向项目根目录之外的符号链接删除文件。如果 `tsdown` 因此跳过了匹配到的路径,会输出警告。 diff --git a/skills/tsdown/references/option-cleaning.md b/skills/tsdown/references/option-cleaning.md index 86ee9e210..c3f8f79ef 100644 --- a/skills/tsdown/references/option-cleaning.md +++ b/skills/tsdown/references/option-cleaning.md @@ -59,7 +59,7 @@ export default defineConfig({ ### Paths Outside the Project Root -tsdown never cleans paths outside the project root, and it does not delete files through symbolic links. A symbolic link inside the project root is removed as a link, and its target is kept. If tsdown skips a matched path for this reason, it logs a warning. The `outDir` directory itself is never removed, only its contents. +tsdown never cleans paths outside the project root, and it does not delete files through a symbolic link that points outside the project root. Files reached through a symbolic link that points inside the project root are cleaned as usual. If a pattern matches a symbolic link itself, tsdown removes the link and keeps its target. If tsdown skips a matched path for this reason, it logs a warning. The `outDir` directory itself is never removed, only its contents. ## Common Patterns diff --git a/src/features/clean.ts b/src/features/clean.ts index cbda64f39..a8ca189b6 100644 --- a/src/features/clean.ts +++ b/src/features/clean.ts @@ -76,8 +76,8 @@ export async function cleanOutDir(configs: ResolvedConfig[]): Promise { /** * Checks the real location of `file` without following `file` itself, so a - * symlink inside the root is removed as a link, but nothing is removed through - * a symlinked parent directory. + * symlink inside the root is removed as a link, and nothing is removed through + * a symlinked parent directory that resolves outside the root. */ async function isRealPathInside( file: string,