diff --git a/docs/module.md b/docs/module.md index e343f1cb4..086f822c4 100644 --- a/docs/module.md +++ b/docs/module.md @@ -1,6 +1,6 @@ --- title: "nuxt module" -description: "Search, add and remove modules in your Nuxt application with the command line." +description: "Search, add, remove, and build Nuxt modules from the command line." links: - label: Source icon: i-simple-icons-github @@ -135,3 +135,71 @@ npx nuxt module search pinia ``` Use `--json` to get the results as machine-readable JSON. + +## `nuxt module build` + + +```bash [Terminal] +npx nuxt module build [ROOTDIR] [--cwd=] [--outDir=] [--sourcemap] +``` + + +### Arguments + + +| Argument | Description | +|-----------|-----------------------------------------------------| +| `ROOTDIR` | The root directory of your Nuxt module (default: .) | + + +### Options + + +| Option | Default | Description | +|------------------------|---------|----------------------------------------------------------------------------------------------------------| +| `--cwd=` | | Specify the root directory of your Nuxt module | +| `--outDir=` | | Output directory, relative to the module root. Overrides `outDir` in the tsdown config (default: `dist`) | +| `--sourcemap` | | Emit source maps. Overrides `sourcemap` in the tsdown config | + + +The command builds your module for publishing with [`@nuxt/module-builder`](/docs/api/module-builder/commands#build) and passes all arguments to `nuxt-module-build build`. + +If `@nuxt/module-builder`, `tsdown`, or `typescript` aren't installed, it prompts you to install them as dev dependencies. In non-interactive environments, it prints the install command instead. + +**Example:** + +```bash [Terminal] +npx nuxt module build +``` + +## `nuxt module prepare` + + +```bash [Terminal] +npx nuxt module prepare [ROOTDIR] [--cwd=] +``` + + +### Arguments + + +| Argument | Description | +|-----------|-----------------------------------------------------| +| `ROOTDIR` | The root directory of your Nuxt module (default: .) | + + +### Options + + +| Option | Default | Description | +|---------------------|---------|------------------------------------------------| +| `--cwd=` | | Specify the root directory of your Nuxt module | + + +The command creates the `.nuxt` directory and generates types for your module with [`@nuxt/module-builder`](/docs/api/module-builder/commands#prepare). Like `nuxt module build`, it prompts you to install any missing build dependencies. + +**Example:** + +```bash [Terminal] +npx nuxt module prepare +``` diff --git a/packages/nuxt-cli/src/commands/module/_builder.ts b/packages/nuxt-cli/src/commands/module/_builder.ts new file mode 100644 index 000000000..9dd0632ee --- /dev/null +++ b/packages/nuxt-cli/src/commands/module/_builder.ts @@ -0,0 +1,178 @@ +import type { ArgsDef } from 'citty' +import type { DetectResult } from 'package-manager-detector' +import type { PackageJson } from 'pkg-types' + +import { readFileSync } from 'node:fs' +import process from 'node:process' +import { styleText } from 'node:util' + +import { cancel, confirm, isCancel } from '@clack/prompts' +import { defineCommand } from 'citty' +import { resolveModulePath } from 'exsolve' +import { resolveCommand } from 'package-manager-detector/commands' +import { dirname, resolve } from 'pathe' +import { x } from 'tinyexec' + +import { ActionableError } from '../../utils/errors' +import { createInstallLog, runInstall } from '../../utils/install' +import { logger } from '../../utils/logger' +import { defaultPackageManager, detectPackageManager } from '../../utils/package-managers' +import { relativeToProcess, resolveRootDir } from '../../utils/paths' +import { withNodePath } from '../../utils/resolve-nuxt' +import { createSpinner } from '../../utils/spinner' +import { isInteractive } from '../../utils/stdout' +import { globalCwdArgs } from '../_shared' + +const MODULE_BUILDER = '@nuxt/module-builder' +const PEERS = ['tsdown', 'typescript'] +const WHITESPACE_RE = /\s/ + +const moduleRootArgs = { + rootDir: { + type: 'positional', + description: 'The root directory of your Nuxt module (default: .)', + required: false, + default: undefined, + }, + cwd: { + ...globalCwdArgs.cwd, + description: 'Specify the root directory of your Nuxt module', + }, +} as const satisfies ArgsDef + +// `args` populate `--help` and generated docs; `ctx.rawArgs` forwards all flags to `nuxt-module-build`. +export function defineModuleBuilderCommand(name: 'build' | 'prepare', description: string, args: T) { + return defineCommand({ + meta: { name, description }, + args: { ...moduleRootArgs, ...args }, + async run(ctx) { + const rootDir = resolveRootDir(ctx.args) + const bin = await ensureModuleBuilder(rootDir, name) + + const result = await x(process.execPath, [bin, name, ...ctx.rawArgs], { + nodeOptions: { stdio: 'inherit' }, + throwOnError: false, + }) + if (result.exitCode !== 0) { + process.exit(result.exitCode ?? 1) + } + }, + }) +} + +interface ModuleBuilder { + bin: string + dir: string + peers: Record +} + +function resolveModuleBuilder(rootDir: string): ModuleBuilder | undefined { + const manifest = resolveModulePath(`${MODULE_BUILDER}/package.json`, { from: withNodePath(rootDir), try: true, cache: false }) + if (!manifest) { + return + } + const pkg = JSON.parse(readFileSync(manifest, 'utf8')) as Pick + const script = typeof pkg.bin === 'string' ? pkg.bin : pkg.bin?.['nuxt-module-build'] + if (!script) { + return + } + const dir = dirname(manifest) + const peers = Object.entries(pkg.peerDependencies ?? {}) + .filter(([name]) => PEERS.includes(name) && !pkg.peerDependenciesMeta?.[name]?.optional) + return { bin: resolve(dir, script), dir, peers: Object.fromEntries(peers) } +} + +// Pick the last `||` branch (`^5.9.3 || ^6.0.0` -> `^6.0.0`) so union ranges stay a single argument, +// and fall back to the bare name for `*` or ranges with spaces (`>=3 <5`). +function packageSpec(name: string, range: string | undefined): string { + const target = range?.split('||').at(-1)?.trim() + return target && target !== '*' && !WHITESPACE_RE.test(target) ? `${name}@${target}` : name +} + +async function ensureModuleBuilder(rootDir: string, command: string): Promise { + let builder = resolveModuleBuilder(rootDir) + // Resolve without `NODE_PATH` because ESM imports in `@nuxt/module-builder` ignore it. + const resolveFrom = builder?.dir ?? rootDir + const missingPeers = (builder ? Object.keys(builder.peers) : PEERS) + .filter(name => !resolveModulePath(name, { from: resolveFrom, try: true, cache: false })) + if (builder && missingPeers.length === 0) { + return builder.bin + } + + const packageManager = await detectPackageManager(rootDir) ?? defaultPackageManager + if (!isInteractive()) { + if (builder) { + const { peers } = builder + const deps = missingPeers.map(name => packageSpec(name, peers[name])) + throw new ActionableError(`${describeMissing(command, missingPeers)} Install ${deps.length > 1 ? 'them' : 'it'} with ${formatInstallCommand(rootDir, packageManager, deps)}.`) + } + throw new ActionableError(`${describeMissing(command, [MODULE_BUILDER])} Install it with ${formatInstallCommand(rootDir, packageManager, [MODULE_BUILDER])}.`) + } + + const missing = [...builder ? [] : [MODULE_BUILDER], ...missingPeers] + const list = formatList(missing) + + logger.warn(describeMissing(command, missing)) + const answer = await confirm({ message: `Install ${list} as ${missing.length > 1 ? 'devDependencies' : 'a devDependency'}?`, initialValue: true }) + if (isCancel(answer) || !answer) { + cancel('Skipping installation.') + process.exit(1) + } + + if (!builder) { + await installDevDependencies(rootDir, packageManager, [MODULE_BUILDER]) + builder = resolveModuleBuilder(rootDir) + if (!builder) { + throw new ActionableError(`${MODULE_BUILDER} was installed but its \`nuxt-module-build\` command could not be found.`) + } + } + + // Reuse `missingPeers` from before installing the builder so auto-installed peers + // are still added to the module's own `devDependencies`. + const { peers } = builder + const peerSpecs = missingPeers.filter(name => name in peers).map(name => packageSpec(name, peers[name])) + if (peerSpecs.length > 0) { + await installDevDependencies(rootDir, packageManager, peerSpecs) + } + + return builder.bin +} + +async function installDevDependencies(rootDir: string, packageManager: DetectResult, dependencies: string[]): Promise { + const list = formatList(dependencies) + const installLog = createInstallLog() + const controller = new AbortController() + const spinner = createSpinner({ indicator: 'timer', onCancel: () => controller.abort() }) + spinner.start(`Installing ${list} with ${styleText('cyan', packageManager.name)}`) + const result = await runInstall({ + cwd: rootDir, + packageManager, + dependencies, + dev: true, + onOutput: installLog.onOutput, + onStatus: message => spinner.message(message), + signal: controller.signal, + }) + if (!result.success) { + spinner.error(result.error ?? 'Install failed') + installLog.finish(result) + throw new ActionableError(`Could not install ${list}. Install ${dependencies.length > 1 ? 'them' : 'it'} with ${formatInstallCommand(rootDir, packageManager, dependencies)}.`) + } + spinner.stop(`Installed ${list}`) + installLog.finish(result) +} + +function describeMissing(command: string, missing: string[]): string { + return `${styleText('cyan', `nuxt module ${command}`)} needs ${formatList(missing)}, which ${missing.length > 1 ? 'are' : 'is'} not installed in this module.` +} + +function formatInstallCommand(rootDir: string, packageManager: DetectResult, dependencies: string[]): string { + const { command, args } = resolveCommand(packageManager.agent, 'add', ['-D', ...dependencies])! + const install = styleText('bold', [command, ...args].join(' ')) + return rootDir === resolve('.') ? install : `${install} in ${styleText('cyan', relativeToProcess(rootDir))}` +} + +function formatList(names: string[]): string { + const styled = names.map(name => styleText('cyan', name)) + return styled.length > 1 ? `${styled.slice(0, -1).join(', ')} and ${styled.at(-1)}` : styled[0]! +} diff --git a/packages/nuxt-cli/src/commands/module/build.ts b/packages/nuxt-cli/src/commands/module/build.ts new file mode 100644 index 000000000..70cff0c48 --- /dev/null +++ b/packages/nuxt-cli/src/commands/module/build.ts @@ -0,0 +1,13 @@ +import { defineModuleBuilderCommand } from './_builder' + +export default defineModuleBuilderCommand('build', 'Build a module for publishing', { + outDir: { + type: 'string', + valueHint: 'directory', + description: 'Output directory, relative to the module root. Overrides `outDir` in the tsdown config (default: `dist`)', + }, + sourcemap: { + type: 'boolean', + description: 'Emit source maps. Overrides `sourcemap` in the tsdown config', + }, +}) diff --git a/packages/nuxt-cli/src/commands/module/index.ts b/packages/nuxt-cli/src/commands/module/index.ts index 01407b028..8432b9872 100644 --- a/packages/nuxt-cli/src/commands/module/index.ts +++ b/packages/nuxt-cli/src/commands/module/index.ts @@ -10,5 +10,7 @@ export default defineCommand({ add: () => import('./add').then(r => r.default || r), remove: () => import('./remove').then(r => r.default || r), search: () => import('./search').then(r => r.default || r), + build: () => import('./build').then(r => r.default || r), + prepare: () => import('./prepare').then(r => r.default || r), }, }) diff --git a/packages/nuxt-cli/src/commands/module/prepare.ts b/packages/nuxt-cli/src/commands/module/prepare.ts new file mode 100644 index 000000000..db7509b47 --- /dev/null +++ b/packages/nuxt-cli/src/commands/module/prepare.ts @@ -0,0 +1,3 @@ +import { defineModuleBuilderCommand } from './_builder' + +export default defineModuleBuilderCommand('prepare', 'Prepare a module environment by writing types', {}) diff --git a/packages/nuxt-cli/test/e2e/module-builder.spec.ts b/packages/nuxt-cli/test/e2e/module-builder.spec.ts new file mode 100644 index 000000000..0dbbadc76 --- /dev/null +++ b/packages/nuxt-cli/test/e2e/module-builder.spec.ts @@ -0,0 +1,80 @@ +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import process from 'node:process' +import { fileURLToPath } from 'node:url' + +import { x } from 'tinyexec' +import { afterEach, describe, expect, it } from 'vitest' + +const nuxi = fileURLToPath(new URL('../../bin/nuxi.mjs', import.meta.url)) +const tempDirs: string[] = [] + +afterEach(async () => { + await Promise.all(tempDirs.splice(0).map(dir => rm(dir, { recursive: true, force: true }))) +}) + +async function createModule({ withBuilder, installed = [] }: { withBuilder: boolean, installed?: string[] }) { + const parent = await mkdtemp(join(tmpdir(), 'nuxt-module-builder-')) + tempDirs.push(parent) + const rootDir = join(parent, 'my-module') + await mkdir(rootDir) + await writeFile(join(rootDir, 'package.json'), JSON.stringify({ name: 'my-module' })) + + if (withBuilder) { + const packageDir = join(rootDir, 'node_modules/@nuxt/module-builder') + await mkdir(packageDir, { recursive: true }) + await writeFile(join(packageDir, 'package.json'), JSON.stringify({ + name: '@nuxt/module-builder', + bin: { 'nuxt-build-module': './cli.mjs', 'nuxt-module-build': './cli.mjs' }, + exports: { './package.json': './package.json' }, + peerDependencies: { tsdown: '^0.23.7', typescript: '^5.9.3 || ^6.0.0' }, + })) + await writeFile(join(packageDir, 'cli.mjs'), 'console.log(JSON.stringify(process.argv.slice(2))); process.exit(3)') + } + + for (const name of installed) { + const packageDir = join(rootDir, 'node_modules', name) + await mkdir(packageDir, { recursive: true }) + await writeFile(join(packageDir, 'package.json'), JSON.stringify({ name, main: './index.js' })) + await writeFile(join(packageDir, 'index.js'), '') + } + + return { parent, rootDir } +} + +function run(args: string[], cwd: string) { + return x('node', [nuxi, ...args], { + nodeOptions: { cwd, env: { ...process.env, NO_COLOR: '1', FORCE_COLOR: '0', CI: '1' } }, + }) +} + +describe('nuxt module build', () => { + it('forwards every argument, including a --cwd passed before the command', { timeout: 60_000 }, async () => { + const { parent } = await createModule({ withBuilder: true, installed: ['tsdown', 'typescript'] }) + + const res = await run(['--cwd', 'my-module', 'module', 'build', '--unknown', 'value', '--sourcemap'], parent) + + expect(res.exitCode).toBe(3) + const forwarded = JSON.parse(res.stdout.trim().split('\n').at(-1)!) + expect(forwarded).toEqual(['build', '--cwd', 'my-module', '--unknown', 'value', '--sourcemap']) + }) + + it('prints the install command when the module builder is missing', { timeout: 60_000 }, async () => { + const { rootDir } = await createModule({ withBuilder: false }) + + const res = await run(['module', 'prepare'], rootDir) + + expect(res.exitCode).toBe(1) + expect(res.stdout + res.stderr).toContain('nuxt module prepare needs @nuxt/module-builder, which is not installed in this module. Install it with npm i -D @nuxt/module-builder.') + }) + + it('prints the install command for missing peers within the ranges the builder declares', { timeout: 60_000 }, async () => { + const { parent } = await createModule({ withBuilder: true }) + + const res = await run(['module', 'build', '--cwd', 'my-module'], parent) + + expect(res.exitCode).toBe(1) + expect(res.stdout + res.stderr).toContain('nuxt module build needs tsdown and typescript, which are not installed in this module. Install them with npm i -D tsdown@^0.23.7 typescript@^6.0.0 in my-module.') + }) +}) diff --git a/packages/nuxt-cli/test/unit/help.spec.ts b/packages/nuxt-cli/test/unit/help.spec.ts index c7450e226..b32931873 100644 --- a/packages/nuxt-cli/test/unit/help.spec.ts +++ b/packages/nuxt-cli/test/unit/help.spec.ts @@ -335,13 +335,15 @@ describe('help', () => { expect(await usage(commands.module, main)).toMatchInlineSnapshot(` "Manage Nuxt modules (nuxt module v0.0.0) - USAGE nuxt module add|remove|search + USAGE nuxt module add|remove|search|build|prepare COMMANDS - add Add Nuxt modules - remove Remove Nuxt modules - search Search in Nuxt modules + add Add Nuxt modules + remove Remove Nuxt modules + search Search in Nuxt modules + build Build a module for publishing + prepare Prepare a module environment by writing types Use nuxt module --help for more information about a command." `) diff --git a/scripts/generate-command-docs.ts b/scripts/generate-command-docs.ts index 4447a3e72..64c94793a 100644 --- a/scripts/generate-command-docs.ts +++ b/scripts/generate-command-docs.ts @@ -79,6 +79,8 @@ const DOCS: DocEntry[] = [ { id: 'module-add', file: 'module.md', command: ['module', 'add'] }, { id: 'module-remove', file: 'module.md', command: ['module', 'remove'] }, { id: 'module-search', file: 'module.md', command: ['module', 'search'] }, + { id: 'module-build', file: 'module.md', command: ['module', 'build'] }, + { id: 'module-prepare', file: 'module.md', command: ['module', 'prepare'] }, { id: 'prepare', file: 'prepare.md', command: ['prepare'] }, { id: 'preview', file: 'preview.md', command: ['preview'] }, { id: 'task-list', file: 'task.md', command: ['task', 'list'] },