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
13 changes: 11 additions & 2 deletions src/config/file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,16 @@ export async function loadViteConfig(
}
}

const configPrefix = 'tsdown.config'
export const configPrefix = 'tsdown.config'
export const configExtensions: string[] = [
'ts',
'mts',
'cts',
'js',
'mjs',
'cjs',
'json',
]

export async function loadConfigFile(
inlineConfig: InlineConfig,
Expand Down Expand Up @@ -110,7 +119,7 @@ export async function loadConfigFile(
: [
{
files: [configPrefix],
extensions: ['ts', 'mts', 'cts', 'js', 'mjs', 'cjs', 'json'],
extensions: configExtensions,
parser,
},
{ files: ['package.json'], parser },
Expand Down
4 changes: 4 additions & 0 deletions src/config/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,10 @@ export interface Workspace {
/**
* Workspace directories. Glob patterns are supported.
* - `auto`: Automatically detect `package.json` files in the workspace.
*
* Matched directories that contain neither a `package.json` nor a
* `tsdown.config.*` file are skipped. Set {@link Workspace.config} to an
* explicit file path to keep every matched directory.
* @default 'auto'
*/
include?: 'auto' | (string & {}) | string[]
Expand Down
148 changes: 148 additions & 0 deletions src/config/workspace.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
import { mkdir, writeFile } from 'node:fs/promises'
import path from 'node:path'
import { describe, expect, test, type TestContext } from 'vitest'
import { getTestDir } from '../../tests/utils.ts'
import { resolveWorkspace } from './workspace.ts'
import type { UserConfigFnContext, Workspace } from './types.ts'

const context: UserConfigFnContext = {
ci: false,
watch: {
restart: () => Promise.reject(new Error('not watching')),
close: () => Promise.resolve(),
},
}

async function writeTree(
testContext: TestContext,
files: Record<string, string>,
directories: string[] = [],
): Promise<string> {
const rootCwd = getTestDir(testContext.task)
await Promise.all(
directories.map((dir) =>
mkdir(path.resolve(rootCwd, dir), { recursive: true }),
),
)
await Promise.all(
Object.entries(files).map(async ([file, content]) => {
const filePath = path.resolve(rootCwd, file)
await mkdir(path.dirname(filePath), { recursive: true })
await writeFile(filePath, content)
}),
)
return rootCwd
}

function config(name: string) {
return JSON.stringify({ name })
}

async function resolveNames(
rootCwd: string,
workspace: Workspace,
): Promise<(string | undefined)[]> {
const { configs } = await resolveWorkspace(
{ workspace, cwd: rootCwd },
{},
context,
)
return configs.map((resolved) => resolved.name).toSorted()
}

describe('workspace include filter', () => {
test('drops matched directories without package.json or tsdown config', async (testContext) => {
const rootCwd = await writeTree(
testContext,
{
'pkgs/a/package.json': JSON.stringify({ name: 'a' }),
'pkgs/a/tsdown.config.json': config('a'),
'pkgs/b/tsdown.config.json': config('b'),
},
['pkgs/ghost'],
)

await expect(
resolveNames(rootCwd, { include: ['pkgs/*'] }),
).resolves.toEqual(['a', 'b'])
})

test('keeps a directory whose only marker is package.json', async (testContext) => {
const rootCwd = await writeTree(
testContext,
{ 'pkgs/a/package.json': JSON.stringify({ name: 'a' }) },
['pkgs/ghost'],
)

const { configs } = await resolveWorkspace(
{ workspace: { include: ['pkgs/*'] }, cwd: rootCwd },
{},
context,
)
expect(configs).toHaveLength(1)
})

test('keeps every matched directory when workspace.config is a file path', async (testContext) => {
const rootCwd = await writeTree(
testContext,
{
'pkgs/a/package.json': JSON.stringify({ name: 'a' }),
'shared.config.json': config('shared'),
},
['pkgs/ghost'],
)

const { configs } = await resolveWorkspace(
{
workspace: {
include: ['pkgs/*'],
config: path.resolve(rootCwd, 'shared.config.json'),
},
cwd: rootCwd,
},
{},
context,
)
expect(configs.map((resolved) => resolved.name)).toEqual([
'shared',
'shared',
])
})

test('reports how many directories were skipped when none survive', async (testContext) => {
const rootCwd = await writeTree(testContext, {}, [
'pkgs/ghost',
'pkgs/other',
])

await expect(
resolveWorkspace({ workspace: ['pkgs/*'], cwd: rootCwd }, {}, context),
).rejects.toThrow(
'No workspace packages found, please check your config (2 matched directories contain no package.json or tsdown config)',
)
})

test('keeps the original message when the globs match nothing', async (testContext) => {
const rootCwd = await writeTree(testContext, {}, ['pkgs'])

await expect(
resolveWorkspace({ workspace: ['pkgs/*'], cwd: rootCwd }, {}, context),
).rejects.toThrow('No workspace packages found, please check your config')
})

test('leaves the auto branch alone', async (testContext) => {
const rootCwd = await writeTree(
testContext,
{
'package.json': JSON.stringify({ name: 'root' }),
'pkgs/a/package.json': JSON.stringify({ name: 'a' }),
'pkgs/a/tsdown.config.json': config('a'),
},
['pkgs/ghost'],
)

await expect(resolveNames(rootCwd, { include: 'auto' })).resolves.toEqual([
'a',
])
})
})
40 changes: 38 additions & 2 deletions src/config/workspace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ import path from 'node:path'
import process from 'node:process'
import { createDebug } from 'obug'
import { glob } from 'tinyglobby'
import { fsExists } from '../utils/fs.ts'
import { slash } from '../utils/general.ts'
import { loadConfigFile } from './file.ts'
import { configExtensions, configPrefix, loadConfigFile } from './file.ts'
import { mergeConfig } from './options.ts'
import type { InlineConfig, UserConfig, UserConfigFnContext } from './types.ts'

Expand All @@ -16,6 +17,19 @@ const DEFAULT_EXCLUDE_WORKSPACE = [
'**/t?(e)mp/**',
]

const PACKAGE_MARKERS = [
'package.json',
...configExtensions.map((ext) => `${configPrefix}.${ext}`),
]

/** A directory is only a workspace package if it holds a package.json or a tsdown config. */
async function isPackageDirectory(dir: string): Promise<boolean> {
const found = await Promise.all(
PACKAGE_MARKERS.map((marker) => fsExists(path.resolve(dir, marker))),
)
return found.includes(true)
}

export async function resolveWorkspace(
config: UserConfig,
inlineConfig: InlineConfig,
Expand Down Expand Up @@ -45,6 +59,7 @@ export async function resolveWorkspace(
exclude = DEFAULT_EXCLUDE_WORKSPACE,
config: workspaceConfig,
} = workspace
let skipped = 0
if (packages === 'auto') {
packages = (
await glob('**/package.json', {
Expand All @@ -65,10 +80,31 @@ export async function resolveWorkspace(
expandDirectories: false,
})
).map((file) => slash(path.resolve(file)))

// An explicit config path names the config, so package-ness is not the signal.
if (typeof workspaceConfig !== 'string') {
const isPackage = await Promise.all(packages.map(isPackageDirectory))
const matched = packages.length
packages = packages.filter((dir, index) => {
if (!isPackage[index]) {
debug(
'skipping directory without package.json or tsdown config %s',
dir,
)
}
return isPackage[index]
})
skipped = matched - packages.length
}
}

if (packages.length === 0) {
throw new Error('No workspace packages found, please check your config')
const detail = skipped
? ` (${skipped} matched ${skipped === 1 ? 'directory contains' : 'directories contain'} no package.json or tsdown config)`
: ''
throw new Error(
`No workspace packages found, please check your config${detail}`,
)
}

context = { ...context, rootConfig: normalized }
Expand Down
9 changes: 9 additions & 0 deletions tests/__snapshots__/issues/1067.snap.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
## pkgs/a/dist/index.mjs

```mjs
//#region index.ts
const a = 1;
//#endregion
export { a };

```
15 changes: 15 additions & 0 deletions tests/issues.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -298,4 +298,19 @@ button {
expect(fileMap['index.mjs']).toContain('polyfill-uuid')
expect(fileMap['index.mjs']).not.toMatch(/from ['"]crypto['"]/)
})

test('#1067', async (context) => {
const { outputFiles } = await testBuild({
context,
files: {
'pkgs/a/package.json': JSON.stringify({ name: 'a' }),
'pkgs/a/index.ts': `export const a = 1`,
'pkgs/ghost/README.md': 'stale directory, holds no package',
},
options: { workspace: ['pkgs/*'] },
expectDir: '..',
expectPattern: '**/dist',
})
expect(outputFiles).toContain('pkgs/a/dist/index.mjs')
})
})
Loading