Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/options/cleaning.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 a symbolic link that points outside the project root. If tsdown skips a matched path for this reason, it logs a warning.
2 changes: 2 additions & 0 deletions docs/zh-CN/options/cleaning.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,5 @@ tsdown --no-clean

> [!NOTE]
> 默认情况下,输出目录中的所有文件将在构建过程开始之前被删除。请确保此行为符合您的项目需求,以避免意外删除重要文件。
>
> 项目根目录之外的路径永远不会被清理,`tsdown` 也不会通过指向项目根目录之外的符号链接删除文件。如果 `tsdown` 因此跳过了匹配到的路径,会输出警告。
4 changes: 2 additions & 2 deletions schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down Expand Up @@ -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": {
Expand Down
4 changes: 4 additions & 0 deletions skills/tsdown/references/option-cleaning.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 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

### Production Build
Expand Down
2 changes: 2 additions & 0 deletions src/config/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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[]
Expand Down
58 changes: 56 additions & 2 deletions src/features/clean.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { realpath } from 'node:fs/promises'
import path from 'node:path'
import { createDebug } from 'obug'
import { glob } from 'tinyglobby'
Expand Down Expand Up @@ -33,13 +34,34 @@ export async function cleanOutDir(configs: ResolvedConfig[]): Promise<void> {
})

const normalizedOutDir = config.outDir.replace(RE_LAST_SLASH, '')
const realCwd = await realpath(config.cwd)
const realDirs = new Map<string, Promise<string | undefined>>()
const skipped = new Set<string>()
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))
Comment thread
magurotuna marked this conversation as resolved.
Resolved
) {
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`)
}
config.logger.warn(
config.nameLabel,
`Skipped cleaning ${skipped.size} path(s) outside the project root:\n${shown.join('\n')}`,
)
}
}

if (!removes.size) return

globalLogger.info(`Cleaning ${removes.size} files`)
Expand All @@ -52,6 +74,38 @@ export async function cleanOutDir(configs: ResolvedConfig[]): Promise<void> {
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, and nothing is removed through
* a symlinked parent directory that resolves outside the root.
*/
async function isRealPathInside(
file: string,
realCwd: string,
realDirs: Map<string, Promise<string | undefined>>,
): Promise<boolean> {
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,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
## index.mjs

```mjs
// index.ts
const hello = "world";
export { hello };

```
193 changes: 191 additions & 2 deletions tests/clean.test.ts
Original file line number Diff line number Diff line change
@@ -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, vi, 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<string> {
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 = {
Expand Down Expand Up @@ -159,6 +174,180 @@ 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 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"',
}

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"',
Expand Down
Loading