Repository navigation
feat(module): add module build and module prepare commands
#1687
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
atinux
wants to merge
5
commits into
main
Choose a base branch
from
feat/module-build-prepare
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
74af69b
feat(module): add `module build` and `module prepare` commands
atinux ce5baf5
fix(module): install peers within the builder's range and from its im…
atinux 4fbcbaa
test(module): disable inherited FORCE_COLOR in the module builder spec
atinux 900e14e
chore(module): clean up docs prose and narrated comments
atinux 0891454
Apply batched suggestions from code review
atinux File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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<T extends ArgsDef>(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<string, string> | ||
| } | ||
|
|
||
| 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<PackageJson, 'bin' | 'peerDependencies' | 'peerDependenciesMeta'> | ||
| 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<string> { | ||
| 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<void> { | ||
| 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]! | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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', | ||
| }, | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| import { defineModuleBuilderCommand } from './_builder' | ||
|
|
||
| export default defineModuleBuilderCommand('prepare', 'Prepare a module environment by writing types', {}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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.') | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.