diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index e535a648..4e2acc44 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -38,7 +38,7 @@ The package has three entry points:
| `src/build/` | The build itself, independent of tsdown's plugin API:
`options.ts` resolves `builder()` options.
`build.ts` resolves a `BuildPlan` and runs the steps before and after the bundle.
`loader.ts` imports module code and checks that Node can load it.
`package.ts` holds the `package.json` checks.
`types.ts` and `module-declarations.ts` write `types.d.mts` and the declarations `prepare` generates.
`aliases.ts` rewrites `#app` in declarations. |
| `src/transpile/` | `transpileDir()`, the internal rolldown plugin that transpiles a directory file by file. It transforms scripts with oxc and `.vue` files with `vue.ts`, compiles stylesheets with `stylesheets.ts`, emits declarations with `declarations.ts`, rewrites import specifiers with `specifiers.ts`, and resolves the tsconfig of each file with `tsconfig.ts`. It imports nothing outside the directory but `src/utils.ts`, so it can be extracted later. |
| `src/legacy/` | Compatibility with v1 and unbuild (see [Legacy code](#legacy-code)). |
-| `src/utils.ts` | Path, file and regex helpers shared across directories. |
+| `src/utils.ts` | Path, file and regex helpers shared across directories, and `logger`, through which every build message goes. |
### `tsdown` with `builder()`
diff --git a/package.json b/package.json
index a51822d5..ca045158 100644
--- a/package.json
+++ b/package.json
@@ -56,14 +56,11 @@
}
},
"dependencies": {
+ "@clack/prompts": "^1.8.1",
"browserslist": "^4.29.5",
- "citty": "^0.2.2",
- "consola": "^3.4.2",
"get-tsconfig": "^4.14.3",
"lightningcss": "^1.33.0",
- "mlly": "^1.8.2",
"pathe": "^2.0.3",
- "pkg-types": "^2.4.0",
"tinyglobby": "^0.2.17",
"vue-sfc-transformer": "^0.3.3"
},
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 6290a30a..a6010ce0 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -175,30 +175,21 @@ importers:
.:
dependencies:
+ '@clack/prompts':
+ specifier: ^1.8.1
+ version: 1.9.0
browserslist:
specifier: ^4.29.5
version: 4.29.5
- citty:
- specifier: ^0.2.2
- version: 0.2.2
- consola:
- specifier: ^3.4.2
- version: 3.4.2
get-tsconfig:
specifier: ^4.14.3
version: 4.14.3
lightningcss:
specifier: ^1.33.0
version: 1.33.0
- mlly:
- specifier: ^1.8.2
- version: 1.8.2
pathe:
specifier: ^2.0.3
version: 2.0.3
- pkg-types:
- specifier: ^2.4.0
- version: 2.4.0
tinyglobby:
specifier: ^0.2.17
version: 0.2.17
diff --git a/src/build/build.ts b/src/build/build.ts
index 30210122..55e883c8 100644
--- a/src/build/build.ts
+++ b/src/build/build.ts
@@ -2,10 +2,8 @@ import { createHash } from 'node:crypto'
import { existsSync, readdirSync, readFileSync } from 'node:fs'
import { readFile, rm } from 'node:fs/promises'
import { dirname, join, normalize, relative, resolve } from 'pathe'
-import { consola } from 'consola'
import type { NuxtModule } from '@nuxt/schema'
import type { TsConfigResult } from 'get-tsconfig'
-import type { PackageJson } from 'pkg-types'
import { glob, globSync } from 'tinyglobby'
import builderPkg from '../../package.json' with { type: 'json' }
@@ -13,7 +11,8 @@ import { scriptExtension, valueSpecifiers } from '../transpile/specifiers.ts'
import { EXCLUDE } from '../transpile/transpile-dir.ts'
import type { ResolveExternal } from '../transpile/transpile-dir.ts'
import { createTsconfigResolver, declarationPaths, hasIsolatedDeclarations, namedCachePath, tsconfigPaths, writeDependencyImports, writeDerivedTsconfig, writeServerRoutesStub } from '../transpile/tsconfig.ts'
-import { findPackageDir, findUp, isInside, isSourceScript, probe, relativeSpecifier, SCRIPT_RE, writeIfChanged } from '../utils.ts'
+import { findPackageDir, findUp, isInside, isSourceScript, logger, probe, relativeSpecifier, SCRIPT_RE, writeIfChanged } from '../utils.ts'
+import type { PackageJson } from '../utils.ts'
import { rewriteRuntimeDeclarations } from './aliases.ts'
import { guide } from './guide.ts'
import { assertLoadableModuleCode, importModule, loadOxc } from './loader.ts'
@@ -97,7 +96,7 @@ export async function resolveBuild({ cwd, pkg, outDir, sourcemap, config }: Pick
if (tsconfigs.replaced) {
const path = relative(cwd, tsconfigs.replaced)
const advice = !isInside(cwd, tsconfigs.replaced) ? 'Add a `tsconfig.json` in the module directory that extends `./.nuxt/tsconfig.json`.' : 'Extend `./.nuxt/tsconfig.json` in the module\'s tsconfig.'
- consola.info(`\`${path}\` takes its generated types from another app's \`.nuxt\`; declarations are generated with \`.nuxt/tsconfig.json\` instead. ${advice} ${guide('module-tsconfig')}`)
+ logger.info(`\`${path}\` takes its generated types from another app's \`.nuxt\`; declarations are generated with \`.nuxt/tsconfig.json\` instead. ${advice} ${guide('module-tsconfig')}`)
}
const directories: DirectoryEntry[] = [{ srcDir: resolve(cwd, 'src/runtime'), outDir: join(outDir, 'runtime'), ext: 'js' }, ...config.directories]
@@ -204,10 +203,10 @@ export async function onBuildError(plan: BuildPlan, error: unknown, { directory
await rm(plan.outDir, { recursive: true, force: true })
}
if (plan.isolatedDeclarations && !directory) {
- consola.error(ISOLATED_DECLARATIONS_HINT)
+ logger.error(ISOLATED_DECLARATIONS_HINT)
}
else if (/\bTS\d{4}\b/.test(String((error as Error | undefined)?.message))) {
- consola.error(TYPE_ERROR_HINT)
+ logger.error(TYPE_ERROR_HINT)
}
}
@@ -249,7 +248,7 @@ export async function finishBuild(plan: BuildPlan, { outputs, builder, keepOutpu
if (shouldNudge(plan.isolatedDeclarations)) {
const project = plan.moduleProject && relative(cwd, plan.moduleProject)
const where = !project ? 'your `tsconfig.json`' : project.startsWith('.nuxt') ? 'a `tsconfig.module.json` that extends `./.nuxt/tsconfig.node.json`' : `\`${project}\``
- consola.info(`Built in ${duration}ms. Set \`isolatedDeclarations: true\` in ${where} to use the faster oxc declaration generator. ${guide('isolated-declarations')}`)
+ logger.info(`Built in ${duration}ms. Set \`isolatedDeclarations: true\` in ${where} to use the faster oxc declaration generator. ${guide('isolated-declarations')}`)
}
await checkPublishedPaths(cwd)
@@ -292,7 +291,7 @@ function valueImports(roots: string[]) {
}
found.add(file)
const { code } = transformSync(file, readFileSync(file, 'utf8'), { lang: file.match(/\.[cm]?([jt]sx?)$/)![1], jsx: 'preserve', typescript: { onlyRemoveTypeImports: false } })
- for (const specifier of valueSpecifiers(code)) {
+ for (const specifier of valueSpecifiers(code, file)) {
const target = probe(resolve(dirname(file), specifier))
if (target && isSourceScript(target)) {
queue.push(normalize(target))
diff --git a/src/build/loader.ts b/src/build/loader.ts
index e04be434..42719e8a 100644
--- a/src/build/loader.ts
+++ b/src/build/loader.ts
@@ -1,19 +1,22 @@
import { existsSync, readFileSync } from 'node:fs'
import { createRequire, registerHooks } from 'node:module'
import { fileURLToPath, pathToFileURL } from 'node:url'
-import { dirname, relative, resolve } from 'pathe'
-import { resolvePathSync } from 'mlly'
+import { dirname, join, relative, resolve } from 'pathe'
import { createPathsMatcher, getTsconfig } from 'get-tsconfig'
import type ts from 'typescript'
import type { Transform } from '../transpile/transpile-dir.ts'
-import { isInside, NODE_MODULES_RE, probe, relativeSpecifier, SCRIPT_RE, TYPESCRIPT_RE } from '../utils.ts'
+import { packageName } from '../transpile/tsconfig.ts'
+import { findPackageDir, findUp, isFile, isInside, isPlainObject, NODE_MODULES_RE, probe, relativeSpecifier, resolveFrom, SCRIPT_RE, TYPESCRIPT_RE } from '../utils.ts'
+import type { PackageJson } from '../utils.ts'
import { guide } from './guide.ts'
+import { importsKeyFor } from './package.ts'
const VIRTUAL_ALIAS_RE = /^#(?:app|imports|build)(?:\/|$)/
const PATH_ALIAS_RE = /^(?:~|@\/)/
const JSON_RE = /\.json$/
const UNLOADABLE_RE = /\.(?:vue|[jt]sx)$/
+const IMPORT_CONDITIONS = new Set(['import', 'node', 'default'])
export interface ImportModuleOptions {
/** Module root, inside which `version` applies. */
@@ -214,20 +217,6 @@ function walkSources(cwd: string, entries: string[], visit: (file: string, analy
}
}
-function resolvesAsPackage(specifier: string, parentDir: string) {
- try {
- return resolvePathSync(specifier, { url: pathToFileURL(resolve(parentDir, 'index.js')), conditions: ['import', 'node', 'default'] })
- }
- catch {
- try {
- return createRequire(resolve(parentDir, 'index.js')).resolve(specifier)
- }
- catch {
- return undefined
- }
- }
-}
-
/**
* The module source `specifier` reaches: a relative file, an entry in the `imports` of the
* module's `package.json`, or a tsconfig `paths` alias. Packages and the aliases only a
@@ -241,10 +230,16 @@ function resolveSource(specifier: string, parentDir: string, cwd: string, matchP
const file = probe(resolve(parentDir, specifier))
return file ? { file, via: 'relative' } : undefined
}
- const resolved = PATH_ALIAS_RE.test(specifier) ? undefined : resolvesAsPackage(specifier, parentDir)
+ const resolved = PATH_ALIAS_RE.test(specifier)
+ ? undefined
+ : (specifier.startsWith('#') && resolvePackageImport(specifier, parentDir)) || resolveFrom(resolve(parentDir, 'index.js'), specifier)
if (resolved) {
return specifier.startsWith('#') && isInside(cwd, resolved) && !NODE_MODULES_RE.test(resolved) ? { file: resolved, via: 'imports' } : undefined
}
+ const name = packageName(specifier)
+ if (name && findPackageDir(name, parentDir)) {
+ return
+ }
for (const candidate of matchPath?.(specifier) || []) {
const file = probe(candidate)
if (file) {
@@ -253,6 +248,37 @@ function resolveSource(specifier: string, parentDir: string, cwd: string, matchP
}
}
+/** The file that `specifier` maps to through the `imports` of the closest `package.json`, with the conditions of `import`. */
+function resolvePackageImport(specifier: string, parentDir: string) {
+ const scope = findUp(parentDir, dir => existsSync(join(dir, 'package.json')) ? dir : undefined)
+ const { imports } = scope ? JSON.parse(readFileSync(join(scope, 'package.json'), 'utf8').replace(/^\uFEFF/, '')) as PackageJson : {}
+ const key = isPlainObject(imports) ? importsKeyFor(Object.keys(imports), specifier) : undefined
+ if (!scope || !key) {
+ return
+ }
+ const star = key.indexOf('*')
+ const target = importTarget((imports as Record)[key], star === -1 ? undefined : specifier.slice(star, specifier.length - key.length + star + 1))
+ const file = target?.startsWith('./') ? resolve(scope, target) : undefined
+ return file && isFile(file) ? file : undefined
+}
+
+function importTarget(target: unknown, match: string | undefined): string | undefined {
+ if (typeof target === 'string') {
+ return match === undefined ? target : target.replaceAll('*', match)
+ }
+ if (Array.isArray(target)) {
+ return target.map(item => importTarget(item, match)).find(item => item !== undefined)
+ }
+ if (isPlainObject(target)) {
+ for (const [condition, value] of Object.entries(target)) {
+ const resolved = IMPORT_CONDITIONS.has(condition) ? importTarget(value, match) : undefined
+ if (resolved !== undefined) {
+ return resolved
+ }
+ }
+ }
+}
+
let typescript: typeof ts | undefined
function scriptKind(ts: typeof import('typescript'), filename: string) {
diff --git a/src/build/module-declarations.ts b/src/build/module-declarations.ts
index ca43a098..b86bd9a4 100644
--- a/src/build/module-declarations.ts
+++ b/src/build/module-declarations.ts
@@ -1,12 +1,11 @@
import { mkdir, readFile, writeFile } from 'node:fs/promises'
-import { consola } from 'consola'
import type { TsConfigResult } from 'get-tsconfig'
import { dirname, join, normalize, relative, resolve } from 'pathe'
import { createDeclarationProgram } from '../transpile/declarations.ts'
import { rewriteSpecifiers } from '../transpile/specifiers.ts'
import { hasIsolatedDeclarations, isModuleFile } from '../transpile/tsconfig.ts'
-import { isInside, isSourceScript, probe, RELATIVE_RE, relativeSpecifier, SCRIPT_RE } from '../utils.ts'
+import { isInside, isSourceScript, logger, probe, RELATIVE_RE, relativeSpecifier, SCRIPT_RE } from '../utils.ts'
import { loadOxc } from './loader.ts'
import { writeSourceTypes } from './types.ts'
@@ -65,12 +64,12 @@ export async function writeModuleDeclarations(cwd: string, dir: string, { tsconf
return relativeSpecifier(output, declaration).replace(/\.d\.([cm]?)ts$/, '.$1js')
}
return isRelative && target ? relativeSpecifier(output, target).replace(/\.d\.([cm]?)ts$/, '.$1js') : undefined
- })
+ }, output)
await mkdir(dirname(output), { recursive: true })
await writeFile(output, code)
}))
if (errors.length) {
- consola.warn([
+ logger.warn([
`Declarations of module code for the module's own app, server and shared type checks could not be generated for every file. The build reports the same errors:`,
...errors,
].join('\n'))
diff --git a/src/build/options.ts b/src/build/options.ts
index c34b9812..b55f6553 100644
--- a/src/build/options.ts
+++ b/src/build/options.ts
@@ -1,8 +1,8 @@
import { isAbsolute, normalize, relative, resolve } from 'pathe'
-import type { PackageJson } from 'pkg-types'
import { assertNoLegacyBuildConfig } from '../legacy/build-config.ts'
import { escapeRegExp, isInside, isPlainObject, probe, realpath } from '../utils.ts'
+import type { PackageJson } from '../utils.ts'
import type { BuildPlan } from './build.ts'
import { guide } from './guide.ts'
diff --git a/src/build/package.ts b/src/build/package.ts
index 3450730c..2e06b4cc 100644
--- a/src/build/package.ts
+++ b/src/build/package.ts
@@ -1,11 +1,8 @@
import { existsSync } from 'node:fs'
import { basename, join, relative, resolve } from 'pathe'
-import { consola } from 'consola'
-import { readPackageJSON } from 'pkg-types'
-import type { PackageJson } from 'pkg-types'
-
import { checkLegacyCJSPaths, checkLegacyDeclarationPaths, isLegacyPath } from '../legacy/package-paths.ts'
-import { DECLARATION_RE, isFile, isInside, TYPESCRIPT_RE } from '../utils.ts'
+import { DECLARATION_RE, isFile, isInside, logger, readPackageJson, TYPESCRIPT_RE } from '../utils.ts'
+import type { PackageJson } from '../utils.ts'
import { guide } from './guide.ts'
/** The fields of `package.json` whose paths are checked for whether they can be published. */
@@ -267,7 +264,7 @@ function exportTarget(target: unknown): string | undefined {
* The paths are read as published, with `publishConfig` applied.
*/
export async function checkPublishedPaths(cwd: string): Promise {
- const read = await readPackageJSON(cwd).catch(() => undefined)
+ const read = await readPackageJson(cwd).catch(() => undefined)
if (!read) {
return
}
@@ -282,7 +279,7 @@ export async function checkPublishedPaths(cwd: string): Promise {
/** Warns with `message` when `condition` holds, and returns `condition`. */
export function warnWhen(condition: boolean, message: string): boolean {
if (condition) {
- consola.warn(message)
+ logger.warn(message)
}
return condition
}
diff --git a/src/build/types.ts b/src/build/types.ts
index 72f7a03e..aa7063d3 100644
--- a/src/build/types.ts
+++ b/src/build/types.ts
@@ -1,18 +1,29 @@
import { existsSync, promises as fsp, readFileSync } from 'node:fs'
import { dirname, relative, resolve } from 'pathe'
-import { findExports, findTypeExports } from 'mlly'
-import type { ESMExport } from 'mlly'
+import type ts from 'typescript'
-import { getOrCreate, probe, writeIfChanged } from '../utils.ts'
+import { parseModule } from '../transpile/specifiers.ts'
+import { probe, writeIfChanged } from '../utils.ts'
+
+interface ExportedName {
+ name: string
+ /** Whether this export only exports a type: `export type`, `export { type Foo }`, an interface or a type alias. */
+ typeOnly: boolean
+}
+
+interface ModuleExport {
+ names: ExportedName[]
+ specifier?: string
+ /** For `export *` and `export * as`, whether it is `export type *`. */
+ star?: { typeOnly: boolean }
+}
-const TYPE_ONLY_DECLARATIONS = new Set(['interface', 'type'])
const DECLARATION_SUFFIXES: Record = {
'': ['.d.ts', '.d.mts', '.d.cts', '/index.d.ts', '/index.d.mts'],
'.js': ['.d.ts'],
'.mjs': ['.d.mts'],
'.cjs': ['.d.cts'],
}
-const VALUE_DECLARATION_RE = /\bexport\s+declare\s+(?:async\s+function|function|const\s+enum|const|let|var|class|enum)\s+([$\w]+)/g
/**
* Writes `module.d.mts`, which re-exports `entry`, and the `types.d.mts` that adds its type
@@ -21,7 +32,7 @@ const VALUE_DECLARATION_RE = /\bexport\s+declare\s+(?:async\s+function|function|
*/
export async function writeSourceTypes(dir: string, entry: string, reExported: string = entry): Promise {
const source = await fsp.readFile(entry, 'utf8')
- const hasDefaultExport = findExports(source).some(e => e.type === 'default' || e.names?.includes('default'))
+ const hasDefaultExport = parseExports(source, entry).some(e => e.names.some(({ name }) => name === 'default'))
// TypeScript resolves the `.js` specifier to the `.ts` source, or to its declaration, without `allowImportingTsExtensions`.
const path = relative(dir, reExported).replace(/\.([cm]?)tsx?$/, '.$1js')
const specifier = path.startsWith('.') ? path : `./${path}`
@@ -42,25 +53,14 @@ export async function writeSourceTypes(dir: string, entry: string, reExported: s
export async function writeTypes(distDir: string, source?: { exports: Set | undefined }): Promise {
const dtsFile = resolve(distDir, 'types.d.mts')
- const moduleReExports: ESMExport[] = []
+ let moduleReExports: ModuleExport[] = []
let typeOnlyExports = new Set()
if (!source) {
const moduleTypes = await fsp.readFile(resolve(distDir, 'module.d.mts'), 'utf8').catch(() => '')
- const exports = findExports(withoutTypeModifiers(moduleTypes))
- const typeExports = findTypeExports(moduleTypes)
- moduleReExports.push(...exports, ...typeExports)
- const namedExports = (list: ESMExport[]) => list.filter(e => e.type === 'named' || e.type === 'default').flatMap(e => e.names)
- const isTypeOnly = (e: ESMExport) => e.type === 'named' || (e.type === 'declaration' && TYPE_ONLY_DECLARATIONS.has(e.declarationType!))
- const valueExports = new Set([
- ...namedExports(findExports(moduleTypes)),
- ...typeExports.filter(e => !isTypeOnly(e)).flatMap(e => e.names),
- // `findTypeExports` drops a value declaration that shares its name with a type
- // export, so read those names from the generated declarations too.
- ...[...moduleTypes.matchAll(VALUE_DECLARATION_RE)].map(match => match[1]!),
- ])
- // `findExports` only reports `export { type Foo }` after the `type` keyword is removed,
- // so names it finds only in the normalised types are type-only.
- typeOnlyExports = new Set([...typeExports.filter(isTypeOnly).flatMap(e => e.names), ...namedExports(exports)].filter(name => !valueExports.has(name)))
+ moduleReExports = parseExports(moduleTypes, 'module.d.mts')
+ const names = moduleReExports.flatMap(e => e.names)
+ const valueExports = new Set(names.filter(e => !e.typeOnly).map(e => e.name))
+ typeOnlyExports = new Set(names.map(e => e.name).filter(name => !valueExports.has(name)))
}
const appShims: string[] = []
@@ -71,7 +71,7 @@ export async function writeTypes(distDir: string, source?: { exports: Set source
? !source.exports || source.exports.has(name)
- : moduleReExports.some(exp => exp.names?.includes(name))
+ : moduleReExports.some(e => e.names.some(exported => exported.name === name))
if (!hasTypeExport('ModuleOptions')) {
schemaImports.push('NuxtModule')
@@ -91,6 +91,7 @@ export async function writeTypes(distDir: string, source?: { exports: Set `\nexport { ${names.map(n => (n === 'default' || !typeOnlyExports.has(n) ? '' : 'type ') + n).join(', ')} } from '${specifier}'`).join('\n')}
-${moduleReExports.filter(e => e.type === 'star').map(e => `\nexport * from '${e.specifier || './module.mjs'}'`).join('\n')}
+${namedReExports.length ? `\nexport { ${namedReExports.map(n => (n === 'default' || !typeOnlyExports.has(n) ? '' : 'type ') + n).join(', ')} } from './module.mjs'` : ''}
+${moduleReExports.filter(e => e.star).map(e => `\nexport ${e.star!.typeOnly ? 'type ' : ''}*${e.names[0] ? ` as ${e.names[0].name}` : ''} from '${e.specifier}'`).join('\n')}
`.trim().replace(/[\n\r]{3,}/g, '\n\n') + '\n'
await writeIfChanged(dtsFile, dtsContents)
@@ -117,10 +118,9 @@ function exportedNames(file: string, seen = new Set()): Set | un
return names
}
seen.add(file)
- const code = readFileSync(file, 'utf8')
- for (const exp of [...findExports(withoutTypeModifiers(code).replace(/\bexport\s+type\s*\*/g, 'export *')), ...findTypeExports(code)]) {
- if (exp.type !== 'star' || exp.names?.length) {
- exp.names?.forEach(name => names.add(name))
+ for (const exp of parseExports(readFileSync(file, 'utf8'), file)) {
+ if (!exp.star || exp.names.length) {
+ exp.names.forEach(({ name }) => names.add(name))
continue
}
const target = exp.specifier?.startsWith('.') ? probeWithDeclarations(resolve(dirname(file), exp.specifier)) : undefined
@@ -140,21 +140,52 @@ function probeWithDeclarations(path: string) {
return probe(path) ?? DECLARATION_SUFFIXES[extension]!.map(suffix => base + suffix).find(candidate => existsSync(candidate))
}
-/** `code` with `export { type Foo }` written as `export { Foo }`, which `findExports` reports. */
-function withoutTypeModifiers(code: string) {
- return code.replace(/export\s*\{.*?\}/gs, match => match.replace(/\b(type|interface)\b/g, ''))
+function parseExports(code: string, filename: string): ModuleExport[] {
+ const { ts, sourceFile } = parseModule(code, filename)
+ const exports: ModuleExport[] = []
+ const hasModifier = (node: ts.Node, kind: ts.SyntaxKind) => ts.canHaveModifiers(node) && !!ts.getModifiers(node)?.some(modifier => modifier.kind === kind)
+ for (const statement of sourceFile.statements) {
+ if (ts.isExportDeclaration(statement)) {
+ const specifier = statement.moduleSpecifier && ts.isStringLiteral(statement.moduleSpecifier) ? statement.moduleSpecifier.text : undefined
+ const clause = statement.exportClause
+ if (clause && ts.isNamedExports(clause)) {
+ exports.push({ specifier, names: clause.elements.map(element => ({ name: element.name.text, typeOnly: statement.isTypeOnly || element.isTypeOnly })) })
+ }
+ else if (specifier) {
+ exports.push({ specifier, star: { typeOnly: statement.isTypeOnly }, names: clause ? [{ name: clause.name.text, typeOnly: statement.isTypeOnly }] : [] })
+ }
+ }
+ else if (ts.isExportAssignment(statement)) {
+ if (!statement.isExportEquals) {
+ exports.push({ names: [{ name: 'default', typeOnly: false }] })
+ }
+ }
+ else if (hasModifier(statement, ts.SyntaxKind.ExportKeyword)) {
+ const typeOnly = ts.isInterfaceDeclaration(statement) || ts.isTypeAliasDeclaration(statement)
+ const names = hasModifier(statement, ts.SyntaxKind.DefaultKeyword) ? ['default'] : declaredNames(ts, statement)
+ exports.push({ names: names.map(name => ({ name, typeOnly })) })
+ }
+ }
+ return exports
+}
+
+function declaredNames(ts: typeof import('typescript'), statement: ts.Statement): string[] {
+ if (ts.isVariableStatement(statement)) {
+ return statement.declarationList.declarations.flatMap(declaration => bindingNames(ts, declaration.name))
+ }
+ const name = (statement as ts.DeclarationStatement).name
+ return name && ts.isIdentifier(name) ? [name.text] : []
}
-function groupNamedReExports(exports: ESMExport[]) {
- const groups = new Map>()
- for (const e of exports) {
- if (e.type === 'named' || e.type === 'default' || e.type === 'declaration') {
- const names = getOrCreate(groups, e.specifier || './module.mjs', () => new Set())
- e.names.forEach(name => names.add(name))
- }
+function bindingNames(ts: typeof import('typescript'), name: ts.BindingName): string[] {
+ if (ts.isIdentifier(name)) {
+ return [name.text]
}
- return new Map([...groups].map(([specifier, names]) => [
- specifier,
- [...names].sort((a, b) => a === 'default' ? 1 : b === 'default' ? -1 : a.localeCompare(b)),
- ]))
+ return name.elements.flatMap(element => ts.isBindingElement(element) ? bindingNames(ts, element.name) : [])
+}
+
+/** The names that `exports` declare or re-export by name, sorted with `default` last. */
+function namedExports(exports: ModuleExport[]) {
+ const names = new Set(exports.flatMap(e => e.star ? [] : e.names.map(({ name }) => name)))
+ return [...names].sort((a, b) => a === 'default' ? 1 : b === 'default' ? -1 : a.localeCompare(b))
}
diff --git a/src/cli.ts b/src/cli.ts
index 1de49893..36d5532c 100644
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -1,22 +1,119 @@
#!/usr/bin/env node
-import { defineCommand, runMain } from 'citty'
-import type { CommandDef } from 'citty'
+import { parseArgs } from 'node:util'
+import type { ParseArgsOptionsConfig } from 'node:util'
import pkg from '../package.json' with { type: 'json' }
+import type { CommandDef } from './commands/_shared.ts'
+import { logger } from './utils.ts'
-const { name, description, version } = pkg
+const BIN = 'nuxt-module-build'
-const _rDefault = (r: unknown) => (r && typeof r === 'object' && 'default' in r ? r.default : r) as Promise
+const commands: Record Promise> = {
+ prepare: () => import('./commands/prepare.ts').then(module => module.default as CommandDef),
+ build: () => import('./commands/build.ts').then(module => module.default as CommandDef),
+}
-const main = defineCommand({
- meta: {
- name,
- description,
- version,
- },
- subCommands: {
- prepare: () => import('./commands/prepare.ts').then(_rDefault),
- build: () => import('./commands/build.ts').then(_rDefault),
- },
-})
+class UsageError extends Error {}
+
+const table = (rows: Array<[string, string]>) => {
+ const width = Math.max(...rows.map(([name]) => name.length))
+ return rows.map(([name, description]) => ` ${name.padEnd(width)} ${description}`)
+}
+
+async function mainUsage() {
+ const loaded = await Promise.all(Object.values(commands).map(load => load()))
+ return [
+ `${pkg.description} (${pkg.name} v${pkg.version})`,
+ '',
+ `Usage: ${BIN} [options]`,
+ '',
+ 'Commands:',
+ ...table(loaded.map(command => [command.meta.name, command.meta.description])),
+ '',
+ `Run \`${BIN} --help\` for the options of a command.`,
+ ].join('\n')
+}
+
+function commandUsage(command: CommandDef) {
+ const args = Object.entries(command.args)
+ const positionals = args.filter(([, arg]) => arg.type === 'positional')
+ const options = args.filter(([, arg]) => arg.type !== 'positional')
+ return [
+ `${command.meta.description} (${BIN} ${command.meta.name})`,
+ '',
+ `Usage: ${BIN} ${command.meta.name} [options]${positionals.map(([name]) => ` [${name.toUpperCase()}]`).join('')}`,
+ '',
+ ...positionals.length ? ['Arguments:', ...table(positionals.map(([name, arg]) => [name.toUpperCase(), arg.description])), ''] : [],
+ 'Options:',
+ ...table([
+ ...options.map(([name, arg]): [string, string] => [`--${name}${arg.type === 'string' ? `=<${arg.valueHint ?? 'value'}>` : ''}`, arg.description]),
+ ['-h, --help', 'Show this help'],
+ ]),
+ ].join('\n')
+}
-runMain(main)
+const kebabCase = (name: string) => name.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`)
+
+function parseCommandArgs(command: CommandDef, argv: string[]) {
+ const options: ParseArgsOptionsConfig = { help: { type: 'boolean', short: 'h' }, stub: { type: 'boolean' } }
+ for (const [name, arg] of Object.entries(command.args)) {
+ if (arg.type !== 'positional') {
+ options[name] = { type: arg.type }
+ options[kebabCase(name)] ??= { type: arg.type }
+ }
+ }
+ const normalised = argv.map((arg) => {
+ const [, name, value] = arg.match(/^--([^=]+)=(true|false)$/) ?? []
+ return name && options[name]?.type === 'boolean' ? `--${value === 'false' ? 'no-' : ''}${name}` : arg
+ })
+ const { values, positionals } = parseArgs({ args: normalised, options, allowPositionals: true, allowNegative: true }) as { values: Record, positionals: string[] }
+ const args: Record = { help: values.help, stub: values.stub }
+ for (const [name, arg] of Object.entries(command.args)) {
+ args[name] = arg.type === 'positional' ? positionals.shift() ?? arg.default : values[name] ?? values[kebabCase(name)] ?? arg.default
+ }
+ if (positionals.length) {
+ throw new UsageError(`Unexpected argument \`${positionals[0]}\``)
+ }
+ return args
+}
+
+async function main(argv: string[]) {
+ const [name, ...rest] = argv
+ if (name === '--help' || name === '-h') {
+ console.log(await mainUsage())
+ return
+ }
+ if (name === '--version' || name === '-v') {
+ console.log(pkg.version)
+ return
+ }
+ const load = name !== undefined && Object.hasOwn(commands, name) ? commands[name] : undefined
+ if (!load) {
+ console.error(await mainUsage())
+ throw new UsageError(name === undefined ? 'No command specified.' : `Unknown command \`${name}\``)
+ }
+ const command = await load()
+ let args
+ try {
+ args = parseCommandArgs(command, rest)
+ }
+ catch (error) {
+ console.error(commandUsage(command))
+ throw new UsageError((error as Error).message)
+ }
+ if (args.help) {
+ console.log(commandUsage(command))
+ return
+ }
+ await command.run({ args })
+}
+
+main(process.argv.slice(2)).catch((error: unknown) => {
+ if (error instanceof UsageError) {
+ console.error()
+ logger.error(error.message)
+ }
+ else {
+ console.error(error)
+ }
+ process.exit(1)
+})
diff --git a/src/commands/_shared.ts b/src/commands/_shared.ts
index 02b442be..b5642827 100644
--- a/src/commands/_shared.ts
+++ b/src/commands/_shared.ts
@@ -1,6 +1,24 @@
import { guide } from '../build/guide.ts'
import { realpath } from '../utils.ts'
+interface ArgDef {
+ type: 'string' | 'boolean' | 'positional'
+ description: string
+ valueHint?: string
+ default?: string
+}
+
+type ParsedArgs> = {
+ [Key in keyof Args]?: { boolean: boolean, string: string, positional: string }[Args[Key]['type']]
+}
+
+/** A subcommand of `nuxt-module-build`. */
+export interface CommandDef = Record> {
+ meta: { name: string, description: string }
+ args: Args
+ run(context: { args: ParsedArgs }): Promise
+}
+
export const sharedArgs = {
// cwd falls back to rootDir's default (indirect default)
cwd: {
@@ -12,7 +30,6 @@ export const sharedArgs = {
rootDir: {
type: 'positional',
description: 'Specifies the working directory (default: `.`)',
- required: false,
default: '.',
},
} as const
diff --git a/src/commands/build.ts b/src/commands/build.ts
index 633140e7..30edee33 100644
--- a/src/commands/build.ts
+++ b/src/commands/build.ts
@@ -1,10 +1,8 @@
-import { defineCommand } from 'citty'
-import type { CommandDef } from 'citty'
-import { consola } from 'consola'
-
import pkg from '../../package.json' with { type: 'json' }
import { guide } from '../build/guide.ts'
+import { logger } from '../utils.ts'
import { assertNoStubArg, resolveCwdArg, sharedArgs } from './_shared.ts'
+import type { CommandDef } from './_shared.ts'
export const MISSING_TSDOWN_HINT: string = `\`${pkg.name}\` builds with \`tsdown\`, which is a peer dependency. Install it in your module: \`pnpm add -D tsdown@"${pkg.peerDependencies.tsdown}"\`. ${guide('install-tsdown')}`
@@ -26,7 +24,7 @@ const buildArgs = {
},
} as const
-const command: CommandDef = defineCommand({
+const command: CommandDef = {
meta: {
name: 'build',
description: 'Build module for distribution',
@@ -40,12 +38,12 @@ const command: CommandDef = defineCommand(
const cwd = resolveCwdArg(context.args)
const { build } = await import('../tsdown/build.ts').catch((error) => {
if (isMissingTsdown(error)) {
- consola.error(MISSING_TSDOWN_HINT)
+ logger.error(MISSING_TSDOWN_HINT)
}
throw error
})
return build(cwd, { outDir: context.args.outDir, sourcemap: context.args.sourcemap })
},
-})
+}
export default command
diff --git a/src/commands/prepare.ts b/src/commands/prepare.ts
index 73399023..00ba0bc0 100644
--- a/src/commands/prepare.ts
+++ b/src/commands/prepare.ts
@@ -1,13 +1,8 @@
import { pathToFileURL } from 'node:url'
import type { Nuxt, NuxtConfig, NuxtModule } from '@nuxt/schema'
-import { defineCommand } from 'citty'
-import type { CommandDef } from 'citty'
import { readFile, writeFile } from 'node:fs/promises'
import { parseTsconfig } from 'get-tsconfig'
-import { resolvePath } from 'mlly'
import { dirname, join, relative, resolve } from 'pathe'
-import { readPackageJSON } from 'pkg-types'
-import type { PackageJson } from 'pkg-types'
import { glob } from 'tinyglobby'
import { assertLoadableModuleCode, importModule } from '../build/loader.ts'
import { moduleDeclarationPaths, writeModuleDeclarations } from '../build/module-declarations.ts'
@@ -17,8 +12,10 @@ import { selfReferencePaths } from '../build/package.ts'
import { writeSourceTypes } from '../build/types.ts'
import { loadBuildConfig } from '../legacy/build-config.ts'
import { createTsconfigResolver, isModuleFile, rootTsconfig } from '../transpile/tsconfig.ts'
-import { isInside, probe } from '../utils.ts'
+import { isInside, probe, readPackageJson, resolveFrom } from '../utils.ts'
+import type { PackageJson } from '../utils.ts'
import { assertNoStubArg, resolveCwdArg, sharedArgs } from './_shared.ts'
+import type { CommandDef } from './_shared.ts'
import { loadModuleConfig } from './config-file.ts'
const BUILD_DECLARATION_RE = /^declare module "#build\/(.+)";$/
@@ -31,7 +28,7 @@ interface PrepareConfig {
}
async function loadPrepareConfig(cwd: string): Promise {
- const pkg = await readPackageJSON(cwd)
+ const pkg = await readPackageJson(cwd)
const moduleConfig = await loadModuleConfig(cwd)
const outDir = resolve(cwd, moduleConfig?.outDir ?? 'dist')
const config = moduleConfig ? resolveModuleOptions(cwd, pkg, outDir, moduleConfig.options) : await loadBuildConfig(cwd, pkg, outDir)
@@ -280,15 +277,15 @@ function replaceEntries(modules: unknown[] | undefined, name: string, nuxtModule
/** `useNuxt` from the kit the module in `cwd` resolves, so hooks can read the Nuxt instance they run in. */
async function loadUseNuxt(cwd: string): Promise<(() => Nuxt) | undefined> {
- for (const id of ['@nuxt/kit', 'nuxt/kit']) {
- const path = await resolvePath(id, { url: pathToFileURL(`${cwd}/`) }).catch(() => undefined)
- if (path) {
- return (await import(pathToFileURL(path).href) as { useNuxt: () => Nuxt }).useNuxt
- }
+ const nuxt = resolveFrom(`${cwd}/`, 'nuxt/package.json')
+ // `nuxt/kit` re-exports the `@nuxt/kit` that `nuxt` depends on, and some versions of `nuxt` export it only for `import`.
+ const path = resolveFrom(`${cwd}/`, '@nuxt/kit') ?? (nuxt && resolveFrom(nuxt, '@nuxt/kit'))
+ if (path) {
+ return (await import(pathToFileURL(path).href) as { useNuxt: () => Nuxt }).useNuxt
}
}
-const command: CommandDef = defineCommand({
+const command: CommandDef = {
meta: {
name: 'prepare',
description: 'Prepare @nuxt/module-builder environment by writing types',
@@ -298,6 +295,6 @@ const command: CommandDef = defineCommand({
assertNoStubArg('prepare', context.args)
return prepareModule(resolveCwdArg(context.args))
},
-})
+}
export default command
diff --git a/src/legacy/build-config.ts b/src/legacy/build-config.ts
index 44253de4..71b248b1 100644
--- a/src/legacy/build-config.ts
+++ b/src/legacy/build-config.ts
@@ -5,8 +5,6 @@
import { existsSync } from 'node:fs'
import { readFile } from 'node:fs/promises'
import { relative, resolve } from 'pathe'
-import { consola } from 'consola'
-import type { PackageJson } from 'pkg-types'
import type { BuildPlan } from '../build/build.ts'
import { guide } from '../build/guide.ts'
@@ -14,7 +12,8 @@ import type { GuideSection } from '../build/guide.ts'
import { findModuleCodeIssues, formatModuleCodeIssues, importModule } from '../build/loader.ts'
import { bundledEntries, createOptionsCollector, entryName } from '../build/options.ts'
import type { BuildHookName, ModuleConfig } from '../build/options.ts'
-import { isPlainObject } from '../utils.ts'
+import { isPlainObject, logger } from '../utils.ts'
+import type { PackageJson } from '../utils.ts'
import type { BuildContext, BuildHook } from './define.ts'
const BUILD_CONFIG_FILES = ['build.config.ts', 'build.config.mts', 'build.config.js', 'build.config.mjs']
@@ -248,10 +247,10 @@ export function assertNoLegacyBuildConfig(cwd: string, pkg: PackageJson): void {
export function warnDeprecatedBuildConfig(config: LoadedBuildConfig): void {
for (const hook of config.ignoredHooks) {
- consola.warn(`Ignoring ${hook}: runtime files are no longer built with mkdist. Remove the hook. ${guide('hooks')}`)
+ logger.warn(`Ignoring ${hook}: runtime files are no longer built with mkdist. Remove the hook. ${guide('hooks')}`)
}
if (config.file) {
- consola.warn([
+ logger.warn([
`\`${config.file}\` is deprecated. Its options are still applied.`,
...config.importsUnbuild ? ['Import `defineBuildConfig` from `@nuxt/module-builder` instead of `unbuild`.'] : [],
'Move them into `builder()` in `tsdown.config.ts`.',
@@ -259,7 +258,7 @@ export function warnDeprecatedBuildConfig(config: LoadedBuildConfig): void {
].join(' '))
}
if (config.field === 'unbuild') {
- consola.warn(`The \`unbuild\` field of \`package.json\` is deprecated. Its options are still applied. Rename the field to \`build\`. ${guide('build-configuration')}`)
+ logger.warn(`The \`unbuild\` field of \`package.json\` is deprecated. Its options are still applied. Rename the field to \`build\`. ${guide('build-configuration')}`)
}
}
diff --git a/src/legacy/define.ts b/src/legacy/define.ts
index 4bb9bbf5..8a07a079 100644
--- a/src/legacy/define.ts
+++ b/src/legacy/define.ts
@@ -2,7 +2,7 @@
* `defineBuildConfig` and the types of a v1 module's `build.config.ts`, which
* `@nuxt/module-builder` still exports for modules that have not moved to `builder()`.
*/
-import type { PackageJson } from 'pkg-types'
+import type { PackageJson } from '../utils.ts'
export interface BuildEntry {
input: string
diff --git a/src/legacy/package-paths.ts b/src/legacy/package-paths.ts
index 4f3be881..f11576b8 100644
--- a/src/legacy/package-paths.ts
+++ b/src/legacy/package-paths.ts
@@ -2,10 +2,10 @@
* Advice for `package.json` paths to the `.d.ts` declarations and `module.cjs` that v1
* of `@nuxt/module-builder` generated for the module entry.
*/
-import type { PackageJson } from 'pkg-types'
import { guide } from '../build/guide.ts'
import { list, missingPaths, warnWhen } from '../build/package.ts'
+import type { PackageJson } from '../utils.ts'
const DECLARATION_RE = /(?:^|\/)(?:module|types)\.d\.ts$/
const CJS_MODULE_RE = /(?:^|\/)module\.cjs$/
diff --git a/src/transpile/specifiers.ts b/src/transpile/specifiers.ts
index c34681cb..5426ba0f 100644
--- a/src/transpile/specifiers.ts
+++ b/src/transpile/specifiers.ts
@@ -1,8 +1,12 @@
-import { findDynamicImports, findExports, findStaticImports, findTypeExports } from 'mlly'
+import { createRequire } from 'node:module'
+import type ts from 'typescript'
import { RELATIVE_RE } from '../utils.ts'
const JSX_RE = /\.[jt]sx$/
+const DYNAMIC_IMPORT_RE = /\bimport\s*(?:\(|\/[*/])/
+const VUE_SCRIPT_RE = /(\n`
+ expect(moduleSpecifiers(sfc, 'Component.vue').map(({ specifier }) => specifier)).toEqual(['./a'])
+ expect(rewriteSpecifiers(sfc, specifier => `${specifier}.js`, 'Component.vue')).toBe(sfc.replace(`'./a'`, `'./a.js'`))
+ })
+
+ it('should find the imports of a script block whose end tag has whitespace or attributes', () => {
+ const sfc = `\n\n`
+ expect(rewriteSpecifiers(sfc, specifier => `${specifier}.js`, 'Component.vue')).toBe(sfc.replace(`'./a'`, `'./a.js'`))
+ })
+
+ it('should escape a rewritten specifier for its quotes', () => {
+ const code = `import './it\\'s'\nimport "./say \\"hi\\""\nconst lazy = import(\`./back\\\`tick\`)\n`
+ expect(rewriteSpecifiers(code, specifier => `${specifier}.js`)).toBe(`import './it\\'s.js'\nimport "./say \\"hi\\".js"\nconst lazy = import(\`./back\\\`tick.js\`)\n`)
+ })
+
+ it('should find the imports of a script block with `>` in a quoted attribute', () => {
+ const sfc = `\n`
+ expect(rewriteSpecifiers(sfc, specifier => `${specifier}.js`, 'Component.vue')).toBe(sfc.replace(`'./x'`, `'./x.js'`))
})
it('should treat a dot-prefixed name as a path inside the directory', () => {
@@ -1247,6 +1323,12 @@ describe('build plan', () => {
expect(relativeSpecifier('/mod/src/module.ts', '/mod/shared.ts')).toBe('../shared.ts')
})
+ it('should read a `package.json` that starts with a byte order mark', async () => {
+ const cwd = await tempDir()
+ await writeFile(join(cwd, 'package.json'), `\uFEFF${JSON.stringify({ name: 'bom' })}`)
+ expect(await readPackageJson(cwd)).toEqual({ name: 'bom' })
+ })
+
it('should not follow declaration files when deciding which JSX to compile', async () => {
const cwd = await tempDir()
await mkdir(join(cwd, 'src/runtime/server'), { recursive: true })
diff --git a/test/utils.ts b/test/utils.ts
index d8b7bbc6..bec2aeaf 100644
--- a/test/utils.ts
+++ b/test/utils.ts
@@ -5,12 +5,19 @@ import { setTimeout as delay } from 'node:timers/promises'
import { fileURLToPath, pathToFileURL } from 'node:url'
import { dirname, join } from 'pathe'
import { exec } from 'tinyexec'
-import type { PackageJson } from 'pkg-types'
+import ts from 'typescript'
import { onTestFailed } from 'vitest'
import { publishedPackage } from '../src/build/package.ts'
+import type { PackageJson } from '../src/utils.ts'
export const repoRoot = fileURLToPath(new URL('..', import.meta.url))
+
+/** The static `import` declarations of `code`. */
+export function staticImports(code: string): Array<{ specifier: string, code: string }> {
+ const source = ts.createSourceFile('module.ts', code, ts.ScriptTarget.Latest)
+ return source.statements.filter(ts.isImportDeclaration).map(statement => ({ specifier: (statement.moduleSpecifier as ts.StringLiteral).text, code: statement.getText(source) }))
+}
export const exampleDir = join(repoRoot, 'example')
export const tsdownBin = join(repoRoot, 'node_modules/tsdown/dist/run.mjs')
export const cliBin = join(repoRoot, 'src/cli.ts')
diff --git a/test/watch.spec.ts b/test/watch.spec.ts
index d8220f4c..3039a548 100644
--- a/test/watch.spec.ts
+++ b/test/watch.spec.ts
@@ -3,10 +3,10 @@ import { mkdir, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises'
import { setTimeout as delay } from 'node:timers/promises'
import { pathToFileURL } from 'node:url'
import { join, relative } from 'pathe'
-import type { PackageJson } from 'pkg-types'
import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest'
import type { TestContext } from 'vitest'
+import type { PackageJson } from '../src/utils.ts'
import { builderImport, exists, fixture, read, repoRoot, run, succeed, tsdown, tsdownBin, waitFor, watch } from './utils.ts'
const PLUGIN = `export default {\n plugins: [builder()],\n}\n`