From 1fb9b5eb2cd2bc5c401d9334b20271e8d6cd6abd Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Tue, 17 Nov 2026 08:22:53 +0000 Subject: [PATCH 01/21] test: consolidate fixtures into one spec per surface --- test/build.spec.ts | 1760 ----------------- test/builder.spec.ts | 310 +++ test/cli.spec.ts | 1534 ++++++++++++++ test/deprecations.spec.ts | 49 - test/legacy.spec.ts | 546 +++++ test/setup.ts | 12 + ...rolldown.spec.ts => transpile-dir.spec.ts} | 94 +- test/tsdown-cli.spec.ts | 157 -- test/tsdown-references.spec.ts | 305 --- test/tsdown-watch.spec.ts | 316 --- test/tsdown.spec.ts | 346 ---- test/unit.spec.ts | 220 +-- test/utils.ts | 176 +- test/watch.spec.ts | 290 +++ vitest.config.mts | 1 + 15 files changed, 2909 insertions(+), 3207 deletions(-) delete mode 100644 test/build.spec.ts create mode 100644 test/builder.spec.ts create mode 100644 test/cli.spec.ts delete mode 100644 test/deprecations.spec.ts create mode 100644 test/legacy.spec.ts create mode 100644 test/setup.ts rename test/{rolldown.spec.ts => transpile-dir.spec.ts} (88%) delete mode 100644 test/tsdown-cli.spec.ts delete mode 100644 test/tsdown-references.spec.ts delete mode 100644 test/tsdown-watch.spec.ts delete mode 100644 test/tsdown.spec.ts create mode 100644 test/watch.spec.ts diff --git a/test/build.spec.ts b/test/build.spec.ts deleted file mode 100644 index 626c89b7..00000000 --- a/test/build.spec.ts +++ /dev/null @@ -1,1760 +0,0 @@ -import { createHash } from 'node:crypto' -import { existsSync } from 'node:fs' -import { availableParallelism } from 'node:os' -import process from 'node:process' -import { fileURLToPath } from 'node:url' -import { cp, mkdir, readFile, readdir, rm, symlink, writeFile } from 'node:fs/promises' -import { beforeAll, describe, it, expect } from 'vitest' -import { exec as spawn } from 'tinyexec' -import { readPackageJSON } from 'pkg-types' -import { dirname, join, relative, resolve } from 'pathe' -import { findStaticImports } from 'mlly' -import { version as nuxtVersion } from 'nuxt/package.json' -import { satisfies } from 'verkit' -import { version } from '../package.json' -import { guide } from '../src/build/guide.ts' -import { publishedPackage } from '../src/build/package.ts' -import { npmPackFromPnpmScript, packProbeArgs, packProbeContext } from './pack-env.ts' -import { builderImport, repoRoot, tsdownBin } from './utils.ts' - -let running = 0 -const waiting: Array<() => void> = [] -async function exec(...args: Parameters) { - if (running < availableParallelism()) { - running++ - } - else { - await new Promise(resolve => waiting.push(resolve)) - } - try { - return await spawn(...args) - } - finally { - const next = waiting.shift() - if (next) { - next() - } - else { - running-- - } - } -} - -const listFiles = async (dir: string) => (await readdir(dir, { recursive: true })).map(file => file.replaceAll('\\', '/')) - -const unresolvedSpecifiers = async (dir: string) => { - const failures: string[] = [] - for (const entry of await listFiles(dir)) { - if (!/\.d\.[^/]*ts$/.test(entry)) { - continue - } - const file = join(dir, entry) - for (const [, specifier] of (await readFile(file, 'utf-8')).matchAll(/(?:\bfrom\s*|\bimport\s*\(\s*|\bimport\s+)['"](\.\.?\/[^'"]*)['"]/g)) { - const target = join(dirname(file), specifier!) - const candidates = specifier!.endsWith('.js') - ? [target.replace(/\.js$/, '.d.ts')] - : specifier!.endsWith('.mjs') - ? [target.replace(/\.mjs$/, '.d.mts')] - : specifier!.endsWith('.vue') - ? [`${target}.d.ts`, target.replace(/\.vue$/, '.d.vue.ts')] - : specifier!.endsWith('.css') ? [target] : [] - if (!candidates.some(candidate => existsSync(candidate))) { - failures.push(`${entry}: ${specifier}`) - } - } - } - return failures -} - -const RUNTIME_IMPORTS = ` -import { name } from './runtime/utils/name.ts' -import { aliased } from '#runtime/utils/aliased' -import { useShape } from './runtime/composables/useShape.ts' -import type TestMe from './runtime/components/TestMe.vue' -import type JsxComponent from './runtime/components/JsxComponent.tsx' -export const runtimeRefs = [name, aliased, useShape] -export type TestMeType = typeof TestMe -export type JsxComponentType = typeof JsxComponent -export type { NuxtApp } from '#app' -` - -const LEGACY_TSCONFIG = { extends: './.nuxt/tsconfig.json', exclude: ['dist', 'node_modules', 'playground', '../src'] } - -describe('module builder', () => { - const rootDir = fileURLToPath(new URL('../example', import.meta.url)) - const secondRootDir = rootDir.replace('example', '.temp-example-without-options') - const thirdRootDir = rootDir.replace('example', '.temp-example-with-runtime-imports') - const fourthRootDir = rootDir.replace('example', '.temp-example-single-runtime-dir') - const wildcardRootDir = rootDir.replace('example', '.temp-example-wildcard-paths') - const noRuntimeRootDir = rootDir.replace('example', '.temp-example-without-runtime') - const vueOnlyRootDir = rootDir.replace('example', '.temp-example-vue-only-runtime') - const packageImportsRootDir = rootDir.replace('example', '.temp-example-package-imports') - const prepareLoaderRootDir = rootDir.replace('example', '.temp-example-prepare-loader') - const extensionlessRootDir = rootDir.replace('example', '.temp-example-extensionless-imports') - const buildConfigRootDir = rootDir.replace('example', '.temp-example-build-config') - const replaceRootDir = rootDir.replace('example', '.temp-example-build-config-replace') - const unsupportedRootDir = rootDir.replace('example', '.temp-example-build-config-unsupported') - const stylesheetsRootDir = rootDir.replace('example', '.temp-example-stylesheets') - const transpileRootDir = rootDir.replace('example', '.temp-example-transpile-only') - const solutionRootDir = rootDir.replace('example', '.temp-example-solution-tsconfig') - const parentTsconfigRootDir = rootDir.replace('example', '.temp-example-parent-tsconfig') - const portableRootDir = rootDir.replace('example', '.temp-example-portable-types') - const valueExportsRootDir = rootDir.replace('example', '.temp-example-value-exports') - const valueExportsIsolatedRootDir = rootDir.replace('example', '.temp-example-value-exports-isolated') - const isolatedRootDir = rootDir.replace('example', '.temp-example-isolated-declarations') - const typeErrorRootDir = rootDir.replace('example', '.temp-example-type-error') - const semanticErrorRootDir = rootDir.replace('example', '.temp-example-semantic-error') - const vueErrorRootDir = rootDir.replace('example', '.temp-example-vue-error') - const nonErasableRootDir = rootDir.replace('example', '.temp-example-non-erasable-syntax') - const autoPrepareRootDir = rootDir.replace('example', '.temp-example-auto-prepare') - const annotatedRootDir = rootDir.replace('example', '.temp-example-isolated-annotated') - const runtimeShapeRootDir = rootDir.replace('example', '.temp-example-runtime-shape') - const routesRootDir = rootDir.replace('example', '.temp-example-routes/mod') - let routesBuild = '' - let buildConfigBuild = '' - const encodedRootDir = rootDir.replace('example', '.temp-example with spaces ΓΌ') - const sourceFlowRootDir = rootDir.replace('example', '.temp-example-source-flow') - const distFlowRootDir = rootDir.replace('example', '.temp-example-dist-flow') - const packDir = rootDir.replace('example', '.temp-packs') - const secondDistDir = join(secondRootDir, 'dist') - const thirdDistDir = join(thirdRootDir, 'dist') - const fourthDistDir = join(fourthRootDir, 'dist') - - const flows = [ - { - name: 'source exports', - rootDir: sourceFlowRootDir, - pack: ['pnpm', 'pack', '--pack-destination', join(packDir, 'source-exports')], - nodeTypeErrors: [expect.stringContaining(`src/runtime/plugins/plugin.ts(1,34): error TS2307: Cannot find module '#app'`)], - }, - { - name: 'dist', - rootDir: distFlowRootDir, - pack: ['npm', 'pack', '--pack-destination', join(packDir, 'dist')], - nodeTypeErrors: [], - }, - ] - const flowOutput = new Map() - - beforeAll(async () => { - const legacyRootDir = rootDir.replace('example', '.temp-example-legacy-tsconfig') - await rm(legacyRootDir, { force: true, recursive: true }) - await cp(rootDir, legacyRootDir, { recursive: true }) - await writeFile(join(legacyRootDir, 'tsconfig.json'), JSON.stringify(LEGACY_TSCONFIG, null, 2)) - await exec('pnpm', ['nuxt-module-build', 'prepare', legacyRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true }) - - const copyExample = async (target: string, transform: (contents: string) => string) => { - await mkdir(dirname(target), { recursive: true }) - await rm(target, { force: true, recursive: true }) - await cp(legacyRootDir, target, { recursive: true }) - const pkgPath = join(target, 'package.json') - const { publishConfig: _, ...pkg } = publishedPackage(JSON.parse(await readFile(pkgPath, 'utf-8'))) - await writeFile(pkgPath, JSON.stringify(pkg, null, 2)) - const moduleSrc = join(target, 'src/module.ts') - await writeFile(moduleSrc, transform(await readFile(moduleSrc, 'utf-8'))) - } - - const enableIsolatedDeclarations = async (target: string) => { - const tsconfig = join(target, 'tsconfig.json') - await writeFile(tsconfig, JSON.stringify({ ...JSON.parse(await readFile(tsconfig, 'utf-8')), compilerOptions: { isolatedDeclarations: true } })) - } - - // Builds the module declarations with oxc, for fixtures that do not test them - const isolate = async (target: string) => { - const moduleSrc = join(target, 'src/module.ts') - const contents = await readFile(moduleSrc, 'utf-8') - await writeFile(moduleSrc, [ - `import type { NuxtModule } from '@nuxt/schema'`, - contents.replace(/export default defineNuxtModule()?\(\{/, (_, options = '') => `const module: NuxtModule${options} = defineNuxtModule${options}({`), - 'export default module', - ].join('\n')) - await writeFile(join(target, 'src/utils.ts'), 'export const myModuleUtils = (): void => {}\n') - await enableIsolatedDeclarations(target) - } - - // Prepare second root directory without type export - await copyExample(secondRootDir, contents => contents.replace('export interface ModuleOptions', 'interface ModuleOptions')) - - // Prepare a root directory whose path is percent-encoded in file URLs - await copyExample(encodedRootDir, contents => contents + RUNTIME_IMPORTS) - - // Prepare third root directory whose module entry pulls in runtime code, through a - // relative specifier, a tsconfig alias and a `.vue` import - await copyExample(thirdRootDir, contents => contents + RUNTIME_IMPORTS) - - // Prepare a fourth root directory whose entire runtime tree lives in one - // subdirectory, and which contains no single-file components - await copyExample(fourthRootDir, contents => contents) - for (const directory of ['components', 'composables', 'assets']) { - await rm(join(fourthRootDir, 'src/runtime', directory), { force: true, recursive: true }) - } - await isolate(fourthRootDir) - - const minimalModule = (name: string) => () => `import { defineNuxtModule } from '@nuxt/kit' - -export default defineNuxtModule({ - meta: { name: '${name}', configKey: '${name}' }, - setup() {}, -}) -` - - await copyExample(prepareLoaderRootDir, contents => `import { deps } from './deps.ts'\nimport { deep } from './deep/a.ts'\n${contents}\nexport const loaded = [deps, deep]\n`) - await rm(join(prepareLoaderRootDir, '.nuxt'), { force: true, recursive: true }) - - await copyExample(extensionlessRootDir, contents => `${contents}\nexport { myModuleUtils } from './utils.js'\nexport { helper } from './helpers'\nexport { kit } from './kit'\nexport type { Kit } from './kit'\n`) - - await copyExample(packageImportsRootDir, () => `${minimalModule('package-imports')()}\nexport { nativeValue } from './native-helper.ts'\nexport { internal } from '#internal/value'\n`) - const packageImportsPkg = join(packageImportsRootDir, 'package.json') - await writeFile(packageImportsPkg, JSON.stringify({ ...JSON.parse(await readFile(packageImportsPkg, 'utf-8')), imports: { '#internal/*': './src/internal/*.ts' } }, null, 2)) - - await copyExample(noRuntimeRootDir, minimalModule('no-runtime')) - await rm(join(noRuntimeRootDir, 'src/runtime'), { force: true, recursive: true }) - await isolate(noRuntimeRootDir) - - await copyExample(vueOnlyRootDir, minimalModule('vue-only')) - for (const file of ['assets', 'composables', 'plugins', 'components/JsxComponent.tsx']) { - await rm(join(vueOnlyRootDir, 'src/runtime', file), { force: true, recursive: true }) - } - await isolate(vueOnlyRootDir) - - await copyExample(isolatedRootDir, contents => contents) - await enableIsolatedDeclarations(isolatedRootDir) - - const valueExports = `export function defineMyModuleConfig(): void {} -export const myModuleVersion = '1.0.0' -export const Mode = { Light: 0, Dark: 1 } as const -export type Mode = typeof Mode[keyof typeof Mode]` - const valueExportsConsumer = `import { Mode, defineMyModuleConfig, myModuleVersion } from 'my-module' -import type { ModuleOptions } from 'my-module' - -defineMyModuleConfig() -const options: ModuleOptions = { apiKey: myModuleVersion } -const light: number = Mode.Light -const dark: Mode = Mode.Dark -void [light, dark, options] -` - const valueExportsConsumerConfig = JSON.stringify({ - compilerOptions: { - moduleResolution: 'bundler', - module: 'ESNext', - target: 'ESNext', - lib: ['ESNext'], - strict: true, - noEmit: true, - skipLibCheck: true, - }, - include: ['consumer.ts'], - }, null, 2) - const prepareValueExportsConsumer = async (target: string) => { - await rm(join(target, 'playground/node_modules/my-module'), { force: true }) - await symlink(target, join(target, 'playground/node_modules/my-module')) - await writeFile(join(target, 'playground/consumer.ts'), valueExportsConsumer) - await writeFile(join(target, 'playground/consumer.tsconfig.json'), valueExportsConsumerConfig) - } - - await copyExample(valueExportsRootDir, contents => `${contents}\n${valueExports}\n`) - await prepareValueExportsConsumer(valueExportsRootDir) - - await copyExample(valueExportsIsolatedRootDir, contents => `${contents}\n${valueExports}\n`) - await prepareValueExportsConsumer(valueExportsIsolatedRootDir) - await isolate(valueExportsIsolatedRootDir) - - await copyExample(nonErasableRootDir, contents => `import { name as packageName } from '../package.json' -import { Level } from './levels.ts' - -enum Mode { Stub = 'stub' } -class Holder { constructor(public value: string) {} } -${contents.replace(`name: 'my-module'`, 'name: new Holder(`${packageName}-${Mode.Stub}-${Level.High}`).value')}`) - const nonErasablePkg = JSON.parse(await readFile(join(nonErasableRootDir, 'package.json'), 'utf-8')) - nonErasablePkg.exports['./plugin'] = './dist/runtime/plugins/plugin.js' - await writeFile(join(nonErasableRootDir, 'package.json'), JSON.stringify(nonErasablePkg, null, 2)) - await writeFile(join(nonErasableRootDir, 'src/levels.ts'), `export enum Level { High = 'high' }\n`) - - await copyExample(autoPrepareRootDir, contents => contents) - await rm(join(autoPrepareRootDir, '.nuxt'), { recursive: true, force: true }) - await isolate(autoPrepareRootDir) - - await copyExample(typeErrorRootDir, contents => contents) - await rm(join(typeErrorRootDir, 'src/runtime/components'), { recursive: true, force: true }) - await writeFile(join(typeErrorRootDir, 'src/runtime/utils.ts'), `export const Anonymous = class { private secret = 1 }\n`) - await copyExample(semanticErrorRootDir, minimalModule('semantic-error')) - await rm(join(semanticErrorRootDir, 'src/runtime'), { recursive: true, force: true }) - await mkdir(join(semanticErrorRootDir, 'src/runtime/utils'), { recursive: true }) - await writeFile(join(semanticErrorRootDir, 'src/runtime/utils/typo.ts'), `export const count: number = 'one'\nexport const double = (value: number): number => value * 2\n`) - await mkdir(join(semanticErrorRootDir, 'src/runtime/components'), { recursive: true }) - await writeFile(join(semanticErrorRootDir, 'src/runtime/components/Typo.vue'), `\n\n\n`) - await writeFile(join(semanticErrorRootDir, 'src/runtime/components/Sized.vue'), `\n\n\n\n\n`) - await mkdir(join(semanticErrorRootDir, 'src/runtime/composables'), { recursive: true }) - await writeFile(join(semanticErrorRootDir, 'src/runtime/composables/useSize.ts'), `import { computed } from 'vue'\nimport type { Props } from '../components/Sized.vue'\n\nexport function useSize(props: Props) {\n return computed(() => props.size)\n}\n`) - await copyExample(vueErrorRootDir, minimalModule('vue-error')) - await rm(join(vueErrorRootDir, 'src/runtime'), { recursive: true, force: true }) - await copyExample(annotatedRootDir, contents => contents) - await isolate(annotatedRootDir) - - // Prepare a root directory whose tsconfig maps every bare specifier into `src/`, - // with a file that shadows a real package - await copyExample(wildcardRootDir, () => `import { defineNuxtModule } from '@nuxt/kit' - -export default defineNuxtModule({ - meta: { name: 'wildcard-module', configKey: 'wildcardModule' }, - setup() {}, -}) -`) - await writeFile(join(wildcardRootDir, 'tsconfig.json'), JSON.stringify({ compilerOptions: { paths: { '*': ['./src/*'] } } }, null, 2)) - await mkdir(join(wildcardRootDir, 'src/@nuxt'), { recursive: true }) - await writeFile(join(wildcardRootDir, 'src/@nuxt/kit.ts'), 'export const defineNuxtModule = (_: unknown) => ({ SHADOWED: true })\n') - - const writeFiles = async (target: string, files: Record) => { - for (const [file, contents] of Object.entries(files)) { - await mkdir(dirname(join(target, file)), { recursive: true }) - await writeFile(join(target, file), contents) - } - } - - const fakeCache = { - 'node_modules/fake-cache/package.json': JSON.stringify({ name: 'fake-cache', type: 'module', exports: { '.': { types: './index.d.ts', default: './index.js' } } }), - 'node_modules/fake-cache/index.js': `export const defineCached = handler => handler\n`, - 'node_modules/fake-cache/index.d.ts': `import type { Handler } from 'fake-h3'\nexport declare const defineCached: (handler: () => string) => Handler\n`, - 'node_modules/fake-cache/node_modules/fake-h3/package.json': JSON.stringify({ name: 'fake-h3', type: 'module', exports: { '.': { types: './index.d.ts' } } }), - 'node_modules/fake-cache/node_modules/fake-h3/index.d.ts': `export interface Handler { (): string, __h3: 2 }\n`, - } - await writeFiles(packageImportsRootDir, { - 'src/native-helper.ts': `import { inner } from './nested/inner.ts'\n\nexport const nativeValue: string = inner\n`, - 'src/nested/inner.ts': `export const inner: string = 'loaded helper'\n`, - 'src/internal/value.ts': `export const internal: string = 'through imports'\n`, - }) - - await writeFiles(prepareLoaderRootDir, { - 'node_modules/fake-cjs-marker/package.json': JSON.stringify({ name: 'fake-cjs-marker', version: '1.0.0', main: 'index.js' }), - 'node_modules/fake-cjs-marker/index.js': `const marker = 'mentions import.meta in a string'\nmodule.exports = { value: marker.length }\n`, - 'node_modules/fake-esm-split/package.json': JSON.stringify({ name: 'fake-esm-split', version: '1.0.0', type: 'module', exports: { '.': { import: './index.js', require: './index.cjs' } } }), - 'node_modules/fake-esm-split/index.js': `export { value } from './inner.js'\nexport { other } from './other.js'\n`, - 'node_modules/fake-esm-split/inner.js': `import cjs from 'fake-cjs-marker'\nexport const value = cjs.value\n`, - 'node_modules/fake-esm-split/other.js': `import cjs from 'fake-cjs-marker'\nexport const other = cjs.value + 1\n`, - 'node_modules/fake-esm-split/index.cjs': `module.exports = { value: 0, other: 1 }\n`, - 'src/deps.ts': `// @ts-ignore untyped\nimport cjs from 'fake-cjs-marker'\n// @ts-ignore untyped\nimport { value, other } from 'fake-esm-split'\n\nexport const deps: unknown[] = [cjs, value, other]\n`, - 'src/deep/a.ts': `export { deep } from './b.ts'\n`, - 'src/deep/b.ts': `import pkg from '../../package.json' with { type: 'json' }\n\nexport const deep: string = pkg.name\n`, - }) - - for (const dir of [thirdRootDir, encodedRootDir]) { - const pkgPath = join(dir, 'package.json') - await writeFile(pkgPath, JSON.stringify({ ...JSON.parse(await readFile(pkgPath, 'utf-8')), imports: { '#runtime/*': './src/runtime/*.ts' } }, null, 2)) - await writeFiles(dir, { - 'src/runtime/composables/useShape.ts': `import { shape } from '../utils/shape.ts'\n\nexport const useShape = (): string => shape\n`, - 'src/runtime/utils/name.ts': `export const name: string = 'name'\n`, - 'src/runtime/utils/aliased.ts': `export const aliased: string = 'aliased'\n`, - 'src/runtime/utils/shape.ts': `export const shape: string = 'shape'\n`, - 'src/runtime/components/JsxCard.vue': `\n\n\n`, - 'src/runtime/components/JsxSlot.tsx': `import { defineComponent } from 'vue'\nimport { useNuxtApp } from '#app'\nimport JsxComponent from './JsxComponent'\n\nexport const useSlotApp = () => useNuxtApp()\n\nexport default defineComponent((_, { slots }) => () =>
{slots.default?.()}
)\n`, - 'src/runtime/server/render.tsx': `import { useSlotApp } from '../components/JsxSlot'\nimport { strong } from '../utils/strong'\n\nexport type SlotApp = ReturnType\n\nexport const render = (label: string) =>

{strong(label)}

\n`, - 'src/runtime/server/render.stories.ts': `import JsxSlot from '../components/JsxSlot'\n\nexport const tested = JsxSlot\n`, - 'src/runtime/utils/strong.tsx': `import { bold } from './bold'\n\nexport const strong = (label: string) => {bold(label)}\n`, - 'src/runtime/utils/bold.tsx': `export const bold = (label: string) => {label}\n`, - 'src/runtime/utils/label.tsx': `export const label = label\n`, - }) - } - - await writeFiles(extensionlessRootDir, { - 'src/helpers.ts': `export const helper = (): string => 'helper'\n`, - 'src/kit/index.ts': `export const kit = (): string => 'kit'\nexport type Kit = ReturnType\n`, - }) - await rm(join(extensionlessRootDir, 'dist'), { force: true, recursive: true }) - - await writeFiles(typeErrorRootDir, { - ...fakeCache, - 'src/runtime/server/cached.ts': `import { defineCached } from 'fake-cache'\n\nexport const defineCachedHandler = defineCached(() => 'cached')\n`, - }) - await writeFiles(vueErrorRootDir, { - ...fakeCache, - 'src/runtime/components/Cached.vue': `\n\n\n`, - 'src/runtime/server/cached.ts': `import { defineCached } from 'fake-cache'\n\nexport const defineCachedHandler = defineCached(() => 'cached')\n`, - }) - - await copyExample(buildConfigRootDir, contents => contents) - await writeFiles(buildConfigRootDir, { - 'build.config.ts': `import { appendFileSync, existsSync, writeFileSync } from 'node:fs' -import { join } from 'node:path' -import { defineBuildConfig } from '@nuxt/module-builder' -import { externals } from './build/externals.ts' - -const record = hook => ctx => appendFileSync(join(ctx.options.rootDir, 'hooks.log'), JSON.stringify({ - hook, - stub: ctx.options.stub, - meta: existsSync(join(ctx.options.outDir, 'module.json')), - entries: ctx.options.entries.map(entry => entry.name).sort(), -}) + '\\n') - -export default defineBuildConfig({ - hooks: { - 'build:before'(ctx) { - record('build:before')(ctx) - writeFileSync(join(ctx.options.rootDir, 'src/generated.ts'), 'export const generated = "from build:before"\\n') - }, - 'rollup:done': record('rollup:done'), - 'build:done': record('build:done'), - }, - declaration: true, - entries: [ - 'src/utils', - './src/vite.ts', - { input: 'src/content', name: 'content' }, - 'src/nested/helper', - { input: 'src/shared/', outDir: 'dist/shared' }, - ], - externals, - replace: { - __MODULE_VERSION__: JSON.stringify('1.2.3'), - }, - rollup: { - emitCJS: false, - }, -}) -`, - 'build/externals.ts': `export const externals = ['fake-pkg', '#content-alias', /^regex-pkg$/]\n`, - 'node_modules/fake-pkg/package.json': JSON.stringify({ name: 'fake-pkg', type: 'module', exports: { './sub': './sub.js' } }), - 'node_modules/fake-pkg/sub.js': `export const plugin = 'bundled-fake-pkg'\n`, - 'node_modules/regex-pkg/package.json': JSON.stringify({ name: 'regex-pkg', type: 'module', exports: './index.js' }), - 'node_modules/regex-pkg/index.js': `export default 'bundled-regex-pkg'\n`, - 'src/alias/config.ts': `export default 'bundled-alias'\n`, - 'src/vite.ts': `// @ts-ignore untyped -import { plugin } from 'fake-pkg/sub' -// @ts-ignore untyped -import virtual from 'regex-pkg' - -import { generated } from './generated.ts' - -declare const __MODULE_VERSION__: string - -export const version: string = __MODULE_VERSION__ -export const refs: unknown[] = [plugin, virtual, generated] -`, - 'src/content.ts': `// @ts-ignore build-time alias -import config from '#content-alias/config' - -export const content: unknown = config -`, - 'src/nested/helper.ts': `import plugin from '../runtime/plugins/plugin.ts'\n\nexport const helper = (): unknown => plugin\nexport const lazy = (): Promise => import('../runtime/composables/useWrappedFetch.ts')\n`, - 'src/shared/format.ts': `export const format = (value: string): string => value.trim()\n`, - 'src/features/flag.ts': `export const flag: boolean = true\n`, - }) - - const buildConfigPkg = join(buildConfigRootDir, 'package.json') - await writeFile(buildConfigPkg, JSON.stringify({ - ...JSON.parse(await readFile(buildConfigPkg, 'utf-8')), - imports: { '#content-alias/*': './src/alias/*.ts' }, - publishConfig: { imports: { '#content-alias/*': './dist/alias/*.mjs' } }, - build: { entries: [{ input: 'src/features/', outDir: 'dist/features', ext: 'js' }] }, - })) - - await copyExample(replaceRootDir, contents => contents) - await isolate(replaceRootDir) - await writeFiles(replaceRootDir, { - 'build.config.ts': `import { defineBuildConfig } from 'unbuild' - -export default defineBuildConfig({ - entries: ['./src/unplugin'], - externals: ['#build/ui'], - hooks: { - 'mkdist:entry:options'(ctx, entry, options) { - options.addRelativeDeclarationExtensions = false - }, - }, - rollup: { - replace: { - delimiters: ['', ''], - values: { - "process.argv.includes('--uiDev')": 'false', - }, - }, - }, -}) -`, - 'src/unplugin.ts': `// @ts-ignore untyped -import ext from 'ext-pkg' - -declare const process: { argv: string[] } - -export const isDev: boolean = process.argv.includes('--uiDev') -export const extRef: unknown = ext -`, - 'node_modules/ext-pkg/package.json': JSON.stringify({ name: 'ext-pkg', type: 'module', exports: './index.js' }), - 'node_modules/ext-pkg/index.js': `export default 'bundled-ext-pkg'\n`, - }) - const replacePkg = join(replaceRootDir, 'package.json') - await writeFile(replacePkg, JSON.stringify({ ...JSON.parse(await readFile(replacePkg, 'utf-8')), unbuild: { externals: ['ext-pkg'] } })) - - await copyExample(unsupportedRootDir, contents => contents) - await writeFiles(unsupportedRootDir, { - 'build.config.ts': `import { defineBuildConfig } from 'unbuild' - -export default defineBuildConfig({ - entries: [ - { input: 'src/runtime/', ext: 'cjs' }, - { input: 'src/schema', builder: 'untyped' }, - ], - hooks: { - 'build:prepare'() {}, - 'rollup:options'() {}, - 'mkdist:entry:options'() {}, - }, - rollup: { - emitCJS: true, - alias: {}, - }, - stub: true, - unknownOption: 1, -}) -`, - }) - - await copyExample(transpileRootDir, contents => `import type { DeepPartial } from 'fake-types' -import type FakeCjs from 'fake-cjs-types' -${contents} -export interface ExtraOptions { deep?: DeepPartial<{ a: string }>, cjs?: FakeCjs.Options } -`) - await writeFiles(transpileRootDir, { - 'node_modules/fake-cjs-types/package.json': JSON.stringify({ name: 'fake-cjs-types', types: './index.d.ts' }), - 'node_modules/fake-cjs-types/index.d.ts': `declare namespace FakeCjs { interface Options { level: number } }\nexport = FakeCjs\n`, - 'src/runtime/server/routes/[...slug].ts': `export default (slug: string) => slug\n`, - 'src/runtime/utils/self.ts': `import type { ModuleOptions } from 'my-module'\n\nexport const getApiKey = (options: ModuleOptions) => options.apiKey\n`, - 'node_modules/fake-dep/package.json': JSON.stringify({ name: 'fake-dep', type: 'module', exports: { '.': { types: './index.d.ts', default: './index.js' } } }), - 'node_modules/fake-dep/index.js': `export const helper = () => 'bundled-fake-dep'\n`, - 'node_modules/fake-dep/index.d.ts': `export declare const helper: () => string\n`, - 'node_modules/fake-types/package.json': JSON.stringify({ name: 'fake-types', types: './index.d.ts' }), - 'node_modules/fake-types/index.d.ts': `export type DeepPartial = { [K in keyof T]?: DeepPartial }\n`, - 'src/runtime/cache/lru.ts': `export const lru: string = 'lru'\n`, - 'src/runtime/server/handler.ts': `// @ts-ignore build-time virtual -import options from '#internal/nuxt.config.mjs' -// @ts-ignore app alias -import app from '~/app.config' -// @ts-ignore app alias -import root from '@/root' -import { useNuxtApp } from '#app' -import { helper } from 'fake-dep' -import { lru } from '#fixture-cache' -import { local } from '../utils/local' - -export default (): unknown[] => [options, app, root, useNuxtApp, helper(), lru, local] -`, - 'src/runtime/utils/local.ts': `export const local: string = 'local'\n`, - 'src/runtime/utils/options.ts': `import type { DeepPartial } from 'fake-types' -import { helper } from 'fake-dep' - -export type Options = DeepPartial<{ a: { b: string } }> -export const defineOptions = (options: Options) => ({ options, helper }) -`, - }) - const transpileNuxtTsconfig = join(transpileRootDir, '.nuxt/tsconfig.json') - const transpileNuxtConfig = JSON.parse(await readFile(transpileNuxtTsconfig, 'utf-8')) - transpileNuxtConfig.compilerOptions.paths['#fixture-cache'] = ['../src/runtime/cache/lru'] - await writeFile(transpileNuxtTsconfig, JSON.stringify(transpileNuxtConfig)) - - await copyExample(solutionRootDir, contents => contents) - await writeFiles(solutionRootDir, { - 'tsconfig.json': JSON.stringify({ files: [], references: [{ path: './tsconfig.app.json' }, { path: './tsconfig.server.json' }] }), - 'tsconfig.app.json': JSON.stringify({ extends: './.nuxt/tsconfig.json', include: ['.nuxt/nuxt.d.ts', 'src/**/*'], exclude: ['src/runtime/server/**'] }), - 'tsconfig.server.json': JSON.stringify({ extends: './.nuxt/tsconfig.json', compilerOptions: { paths: { '#server-only': ['./src/runtime/server/only.ts'] } }, include: ['src/runtime/server/**/*'] }), - 'src/runtime/server/only.ts': `export interface ServerOnly { id: string }\n`, - 'src/runtime/server/api/[id].get.ts': `import type { ServerOnly } from '#server-only'\n\nexport default (value: ServerOnly) => value.id\n`, - }) - - await copyExample(parentTsconfigRootDir, contents => contents) - await mkdir(join(parentTsconfigRootDir, 'packages/mod'), { recursive: true }) - for (const file of ['src', 'package.json']) { - await cp(join(parentTsconfigRootDir, file), join(parentTsconfigRootDir, 'packages/mod', file), { recursive: true }) - await rm(join(parentTsconfigRootDir, file), { recursive: true, force: true }) - } - const loggerStore = 'node_modules/.pnpm/fake-logger@1.0.0/node_modules/fake-logger' - await writeFiles(parentTsconfigRootDir, { - [`${loggerStore}/package.json`]: JSON.stringify({ name: 'fake-logger', type: 'module', types: './dist/index.d.ts', exports: { '.': { types: './dist/index.d.mts', default: './dist/index.mjs' }, './utils': { types: './dist/utils.d.mts', default: './dist/utils.mjs' } } }), - [`${loggerStore}/dist/utils.d.mts`]: `export declare const noop: () => void\n`, - [`${loggerStore}/dist/utils.mjs`]: `export const noop = () => {}\n`, - [`${loggerStore}/dist/core.d.ts`]: `export interface LoggerInstance { log: (message: string) => void }\n`, - [`${loggerStore}/dist/core.d.mts`]: `export interface LoggerInstance { log: (message: string) => void }\n`, - [`${loggerStore}/dist/index.d.ts`]: `import type { LoggerInstance } from './core'\nexport type { LoggerInstance }\nexport declare function createLogger(): LoggerInstance\n`, - [`${loggerStore}/dist/index.d.mts`]: `import type { LoggerInstance } from './core.mjs'\nexport type { LoggerInstance }\nexport declare function createLogger(): LoggerInstance\n`, - [`${loggerStore}/dist/index.mjs`]: `export const createLogger = () => ({ log: console.log })\n`, - 'packages/mod/src/runtime/logger.ts': `import { createLogger } from 'fake-logger'\nimport { noop } from 'fake-logger/utils'\n\nexport const logger = createLogger()\nexport const silence = noop\n`, - }) - await mkdir(join(parentTsconfigRootDir, 'packages/mod/node_modules'), { recursive: true }) - await symlink(join(parentTsconfigRootDir, loggerStore), join(parentTsconfigRootDir, 'packages/mod/node_modules/fake-logger')) - const parentNuxtTsconfig = join(parentTsconfigRootDir, '.nuxt/tsconfig.json') - const parentNuxtConfig = JSON.parse(await readFile(parentNuxtTsconfig, 'utf-8')) - parentNuxtConfig.compilerOptions.paths['fake-logger'] = [`../${loggerStore}`] - await writeFile(parentNuxtTsconfig, JSON.stringify(parentNuxtConfig)) - - await copyExample(portableRootDir, contents => `import { defineThing } from 'fake-kit'\n${contents}\nexport const thing = defineThing({ name: 'portable' })\n`) - const store = (name: string) => `node_modules/.pnpm/${name}@1.0.0/node_modules/${name}` - await writeFiles(portableRootDir, { - [`${store('fake-schema')}/package.json`]: JSON.stringify({ name: 'fake-schema', types: './index.d.ts' }), - [`${store('fake-schema')}/index.d.ts`]: `export interface Thing { options: T }\n`, - [`${store('fake-kit')}/package.json`]: JSON.stringify({ name: 'fake-kit', type: 'module', exports: { '.': { types: './index.d.ts', default: './index.js' } } }), - [`${store('fake-kit')}/index.d.ts`]: `import type { Thing } from 'fake-schema'\nexport declare function defineThing(options: T): Thing\n`, - [`${store('fake-kit')}/index.js`]: `export const defineThing = options => ({ options })\n`, - }) - await symlink(join(portableRootDir, store('fake-schema')), join(portableRootDir, 'node_modules/.pnpm/fake-kit@1.0.0/node_modules/fake-schema')) - await symlink(join(portableRootDir, store('fake-schema')), join(portableRootDir, 'node_modules/fake-schema')) - await symlink(join(portableRootDir, store('fake-kit')), join(portableRootDir, 'node_modules/fake-kit')) - const portableNuxtTsconfig = join(portableRootDir, '.nuxt/tsconfig.json') - const portableNuxtConfig = JSON.parse(await readFile(portableNuxtTsconfig, 'utf-8')) - portableNuxtConfig.compilerOptions.paths['fake-schema'] = [`../${store('fake-schema')}`] - await writeFile(portableNuxtTsconfig, JSON.stringify(portableNuxtConfig)) - const portableNuxtTypes = join(portableRootDir, '.nuxt/nuxt.d.ts') - await writeFile(portableNuxtTypes, `/// \n${await readFile(portableNuxtTypes, 'utf-8')}`) - - await copyExample(stylesheetsRootDir, contents => contents) - await isolate(stylesheetsRootDir) - await writeFiles(join(stylesheetsRootDir, 'src/runtime'), { - 'styles/card.css': `@import "./base.css";\n\n.card {\n user-select: none;\n & .title { font-weight: bold; }\n &:hover { color: rebeccapurple; }\n}\n`, - 'styles/base.css': `.base { margin: 0px 0px; }\n`, - 'styles/_variables.scss': `$primary: #00dc82;\n`, - 'styles/theme.scss': `@use "variables" as v;\n.theme { color: v.$primary; .nested { padding: 1px; } }\n`, - 'styles/indented.sass': `.indented\n color: blue\n`, - 'styles/legacy.less': `@c: red;\n.less { color: @c; }\n`, - 'types/ambient.d.ts': `declare global { interface Window { __fixture: true } }\nexport {}\n`, - 'types/app.d.ts': `import type { NuxtApp } from '#app'\nexport type App = NuxtApp\n`, - 'plugins/styled.ts': `import '../styles/card.css'\nimport '../styles/theme.scss'\n\nexport const styled = true\n`, - }) - - await copyExample(runtimeShapeRootDir, contents => contents) - const runtimeShapePkg = JSON.parse(await readFile(join(runtimeShapeRootDir, 'package.json'), 'utf-8')) - await writeFile(join(runtimeShapeRootDir, 'package.json'), JSON.stringify({ ...runtimeShapePkg, build: { entries: ['./src/utils', './src/utils/merge.ts', './src/data.json'] } }, null, 2)) - await writeFile(join(runtimeShapeRootDir, '.nuxt/app.config.ts'), `export default { theme: { buildMachineOnly: 'must-not-be-published' as const } }\n`) - await writeFile(join(runtimeShapeRootDir, 'external.ts'), `export const answer = 42\n`) - for (const name of ['fake-polyfill', 'fake-register']) { - await writeFiles(join(runtimeShapeRootDir, 'node_modules', name), { - 'package.json': JSON.stringify({ name, type: 'module', exports: { '.': { types: './index.d.ts', default: './index.js' } } }), - 'index.js': `globalThis.__order = [...globalThis.__order ?? [], '${name}']\n`, - 'index.d.ts': `export {}\n`, - }) - } - await writeFiles(join(runtimeShapeRootDir, 'src'), { - 'data.json': `{ "answer": 42 }\n`, - 'utils/merge.ts': `export const merge = (a: T, b: T): T => ({ ...a, ...b })\n`, - 'shared/constants.ts': `import { LIMIT } from './limits'\n\nexport const CONSTANT = LIMIT\n`, - 'shared/limits.ts': `export const LIMIT = 10\n`, - 'types.ts': `export interface RootType { root: string }\n`, - 'types/middlewares.ts': `export type RequestSizeLimiter = { maxRequestSizeInBytes: number }\n`, - 'runtime/server/limiter.ts': `import { type RequestSizeLimiter } from '../../types/middlewares'\nimport {} from 'nuxt/app'\nimport '../disabled/side'\n\nexport const limit = (options: RequestSizeLimiter) => options.maxRequestSizeInBytes\n`, - 'routing.ts': `import { readFileSync } from 'node:fs'\nimport { generate } from './kit/gen'\nimport type { RootType } from './types'\n\nexport interface RouteInfo { path: string, root: RootType }\nexport const localizeRoutes = (file: string): string => generate(readFileSync(file, 'utf8'))\n`, - 'kit/gen.ts': `import { createHash } from 'node:crypto'\n\nexport const generate = (input: string) => createHash('sha1').update(input).digest('hex')\n`, - 'runtime/composables/useLocaleRoute.ts': `import { RouteInfo } from '../../routing'\n\nexport const useLocaleRoute = (route: RouteInfo) => route\n`, - 'runtime/types.ts': `export interface RuntimeType { runtime: string }\n`, - 'runtime/server/uses.ts': [ - `import { merge } from '../../utils/merge'`, - `import { CONSTANT } from '../../shared/constants'`, - `import type { RootType } from '../../types'`, - `import type { RuntimeType } from '../types'`, - ``, - `export const combine = (a: RootType & RuntimeType, b: RootType & RuntimeType) => [merge(a, b), CONSTANT] as const`, - ``, - ].join('\n'), - 'runtime/escaping.ts': `export const load = () => import('../../external')\n`, - 'runtime/composables/mock.ts': `export const defineThing = () => 'mock'\n`, - 'runtime/disabled/composables/defineThing.ts': `export { defineThing } from '../../composables/mock'\n`, - 'runtime/disabled/index.ts': `import './side'\nexport { defineThing } from './composables/defineThing'\n`, - 'runtime/disabled/side.ts': `globalThis.__side = true\n`, - 'runtime/order/first.ts': `import 'fake-polyfill'\nimport 'vue'\nimport './order.css'\nimport './effect'\nimport 'fake-register'\nexport { level } from './levels'\n`, - 'runtime/order/interleaved.ts': [ - `import 'fake-register'`, - `import { level } from './levels'`, - `export * from './reexported'`, - `import './order.css'`, - `export { useState } from '#imports'`, - `import 'fake-polyfill'`, - `import './effect'`, - `import { ref } from 'vue'`, - ``, - `export const value = ref(level)`, - ``, - ].join('\n'), - 'runtime/order/levels.ts': `export const level = 1\n`, - 'runtime/order/reexported.ts': `export const reexported = 1\n`, - 'runtime/order/effect.ts': `globalThis.__effect = true\n`, - 'runtime/order/order.css': `.order { color: red }\n`, - 'runtime/content/index.ts': `export * from '../components/TestMe.vue'\nexport * from '../components/TestMeSetup.vue'\nexport * from './prose'\n`, - 'runtime/content/prose.ts': `export * from './levels'\nexport interface ProseThing { title: string }\n`, - 'runtime/content/levels.ts': `export const proseLevel = 1\n`, - 'runtime/utils/provider.ts': `import type { ModuleOptions } from '../../module'\n\nexport const defineProvider = (options: ModuleOptions) => options\n`, - 'runtime/utils/props.ts': `export interface BaseProps { size?: number }\n`, - 'runtime/composables/useThemeConfig.ts': `import appConfig from '#build/app.config'\n\nexport const useThemeConfig = () => appConfig.theme\n`, - 'runtime/composables/useButton.ts': `import theme, { variants } from '#build/ui/button'\nimport * as config from '#build/app.config'\n\nexport const useButton = () => ({ slots: theme.slots, size: variants.size, ui: config.default.ui })\n`, - 'runtime/components/Button.vue': `\n\n\n`, - 'runtime/components/Sized.vue': `\n\n\n`, - }) - - await copyExample(routesRootDir, contents => contents - .replace('import { defineNuxtModule, addPlugin, createResolver }', 'import { defineNuxtModule, addPlugin, addServerHandler, createResolver }') - .replace(`addPlugin(resolver.resolve('./runtime/plugins/plugin'))`, `addPlugin(resolver.resolve('./runtime/plugins/plugin'))\n addServerHandler({ route: '/api/own', handler: resolver.resolve('./runtime/server/api/own') })`)) - await writeFiles(routesRootDir, { - '.nuxtrc': `${(await readFile(join(rootDir, '.nuxtrc'), 'utf-8')).trimEnd()}\nworkspaceDir=..\n`, - '../tsconfig.json': JSON.stringify({ extends: './mod/playground/.nuxt/tsconfig.json', compilerOptions: { types: ['fake-global-types'] }, exclude: ['**/dist', '**/node_modules'] }), - 'node_modules/fake-global-types/package.json': JSON.stringify({ name: 'fake-global-types', types: 'index.d.ts' }), - 'node_modules/fake-global-types/index.d.ts': `declare namespace Fake {\n interface Thing { id: number }\n function current(): Thing\n}\n`, - 'src/runtime/composables/useGlobal.ts': `export const useGlobal = () => Fake.current()\n`, - 'src/runtime/server/api/own.ts': `export default () => ({ own: 'module-owned' as const })\n`, - 'src/runtime/composables/useOwn.ts': `import { useFetch } from '#app'\n\nexport const useOwn = () => useFetch('/api/own')\n`, - 'src/runtime/composables/useSecret.ts': `import { useFetch } from '#app'\n\nexport const useSecret = () => useFetch('/api/secret')\n`, - 'src/runtime/composables/useSibling.ts': `import { useFetch } from '#app'\n\nexport const useSibling = () => useFetch('/api/sibling')\n`, - 'src/runtime/composables/useDocs.ts': `import { useFetch } from '#app'\n\nexport const useDocs = () => useFetch('/api/docs')\n`, - 'src/runtime/components/Routes.vue': `\n\n\n`, - 'playground/server/api/secret.ts': `export default () => ({ localRoute: 'must-not-be-published' as const })\n`, - 'playground/types/routes.d.ts': `declare module 'nitropack/types' {\n interface InternalApi {\n '/api/secret': { default: 'must-not-be-published' }\n }\n}\n`, - 'docs/types/routes.d.ts': `declare module 'nitropack/types' {\n interface InternalApi {\n '/api/docs': { default: 'must-not-be-published' }\n }\n}\n`, - '../sibling/types/routes.d.ts': `declare module 'nitropack/types' {\n interface InternalApi {\n '/api/sibling': { default: 'must-not-be-published' }\n }\n}\n`, - }) - await rm(join(routesRootDir, 'tsconfig.json')) - await cp(join(rootDir, 'package.json'), join(routesRootDir, 'package.json')) - await rm(join(routesRootDir, 'playground/node_modules/my-module'), { force: true }) - await symlink(routesRootDir, join(routesRootDir, 'playground/node_modules/my-module')) - - await rm(sourceFlowRootDir, { recursive: true, force: true }) - await cp(rootDir, sourceFlowRootDir, { recursive: true }) - for (const dir of ['dist', '.nuxt', 'playground/.nuxt', 'playground/.output']) { - await rm(join(sourceFlowRootDir, dir), { recursive: true, force: true }) - } - await rm(join(sourceFlowRootDir, 'playground/node_modules/my-module'), { force: true }) - await symlink(sourceFlowRootDir, join(sourceFlowRootDir, 'playground/node_modules/my-module')) - - await copyExample(distFlowRootDir, contents => contents) - const { build: distFlowBuild, ...distFlowPkg } = JSON.parse(await readFile(join(distFlowRootDir, 'package.json'), 'utf-8')) - await writeFile(join(distFlowRootDir, 'package.json'), JSON.stringify({ - ...distFlowPkg, - scripts: { - ...distFlowPkg.scripts, - 'prepack': `node ${tsdownBin}`, - 'dev:prepare': `node ../src/cli.ts prepare && node ${tsdownBin} && nuxt prepare playground`, - }, - }, null, 2)) - await writeFile(join(distFlowRootDir, 'tsdown.config.ts'), `${builderImport}\n\nexport default {\n plugins: [builder(${JSON.stringify(distFlowBuild)})],\n}\n`) - for (const dir of ['dist', '.nuxt', 'playground/.nuxt']) { - await rm(join(distFlowRootDir, dir), { recursive: true, force: true }) - } - await rm(join(distFlowRootDir, 'playground/node_modules/my-module'), { force: true }) - await symlink(distFlowRootDir, join(distFlowRootDir, 'playground/node_modules/my-module')) - await rm(packDir, { recursive: true, force: true }) - await Promise.all(['source-exports', 'dist'].map(flow => mkdir(join(packDir, flow), { recursive: true }))) - - const nuxtEnv = { ...process.env, NUXT_TELEMETRY_DISABLED: '1' } - const runFlow = async ({ name, rootDir: dir, pack: [packCommand, ...packArgs] }: typeof flows[number]) => { - const playgroundDir = join(dir, 'playground') - await exec('pnpm', ['dev:prepare'], { nodeOptions: { cwd: dir, env: nuxtEnv }, throwOnError: true }) - const typecheck = (context: string) => exec('pnpm', ['exec', 'vue-tsc', '--noEmit', '-p', join(playgroundDir, `.nuxt/tsconfig.${context}.json`)], { nodeOptions: { cwd: repoRoot } }) - const [appTypes, nodeTypes] = await Promise.all([typecheck('app'), typecheck('node')]) - await exec('pnpm', ['exec', 'nuxt', 'generate', playgroundDir], { nodeOptions: { cwd: repoRoot, env: nuxtEnv }, throwOnError: true }) - const pack = await exec(packCommand!, packArgs, { nodeOptions: { cwd: dir }, throwOnError: true }) - flowOutput.set(name, { - appTypes: appTypes.stdout + appTypes.stderr, - nodeTypes: nodeTypes.stdout + nodeTypes.stderr, - pack: pack.stdout + pack.stderr, - }) - } - - await Promise.all([ - exec('pnpm', ['nuxt-module-build', 'prepare', routesRootDir], { nodeOptions: { cwd: repoRoot, env: nuxtEnv }, throwOnError: true }) - .then(() => exec('pnpm', ['exec', 'nuxt', 'prepare', join(routesRootDir, 'playground')], { nodeOptions: { cwd: repoRoot, env: nuxtEnv }, throwOnError: true })) - .then(() => exec('pnpm', ['nuxt-module-build', 'build', routesRootDir], { nodeOptions: { cwd: repoRoot, env: { ...process.env, NODE_ENV: '', TEST: '' } }, throwOnError: true })) - .then(({ stdout, stderr }) => { routesBuild = stdout + stderr }), - exec('pnpm', ['nuxt-module-build', 'build', stylesheetsRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true }), - exec('pnpm', ['nuxt-module-build', 'build', runtimeShapeRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true }), - ...flows.map(runFlow), - exec('pnpm', ['nuxt-module-build', 'prepare', secondRootDir], { nodeOptions: { cwd: repoRoot, env: nuxtEnv }, throwOnError: true }) - .then(() => exec('pnpm', ['nuxt-module-build', 'build', secondRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true })), - exec('pnpm', ['nuxt-module-build', 'build', encodedRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true }), - exec('pnpm', ['nuxt-module-build', 'build', thirdRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true }), - exec('pnpm', ['nuxt-module-build', 'build', fourthRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true }), - exec('pnpm', ['nuxt-module-build', 'build', noRuntimeRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true }), - exec('pnpm', ['nuxt-module-build', 'build', annotatedRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true }), - exec('pnpm', ['nuxt-module-build', 'build', vueOnlyRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true }), - exec('pnpm', ['nuxt-module-build', 'build', wildcardRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true }), - exec('pnpm', ['nuxt-module-build', 'build', buildConfigRootDir], { nodeOptions: { cwd: repoRoot, env: { ...process.env, CI: '' } }, throwOnError: true }) - .then(({ stdout, stderr }) => { buildConfigBuild = stdout + stderr }), - exec('pnpm', ['nuxt-module-build', 'build', replaceRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true }), - exec('pnpm', ['nuxt-module-build', 'build', transpileRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true }), - exec('pnpm', ['nuxt-module-build', 'build', solutionRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true }), - exec('pnpm', ['nuxt-module-build', 'build', join(parentTsconfigRootDir, 'packages/mod')], { nodeOptions: { cwd: repoRoot }, throwOnError: true }), - exec('pnpm', ['nuxt-module-build', 'build', portableRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true }), - exec('pnpm', ['nuxt-module-build', 'build', valueExportsRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true }), - exec('pnpm', ['nuxt-module-build', 'build', valueExportsIsolatedRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true }), - ]) - }, 300 * 1000) - - it('should build `build.config.ts` entries under the names unbuild gave them', async () => { - const files = await listFiles(join(buildConfigRootDir, 'dist')) - expect(files.filter(file => !file.startsWith('runtime')).sort()).toMatchInlineSnapshot(` - [ - "content.d.mts", - "content.mjs", - "features", - "features/flag.d.ts", - "features/flag.js", - "module.d.mts", - "module.json", - "module.mjs", - "nested", - "nested/helper.d.mts", - "nested/helper.mjs", - "shared", - "shared/format.d.mts", - "shared/format.mjs", - "types.d.mts", - "utils.d.mts", - "utils.mjs", - "vite.d.mts", - "vite.mjs", - ] - `) - }) - - it('should import runtime code relative to nested entries', async () => { - const helper = await readFile(join(buildConfigRootDir, 'dist/nested/helper.mjs'), 'utf-8') - expect(findStaticImports(helper).map(i => i.specifier)).toEqual(['../runtime/plugins/plugin.js']) - expect(helper).toContain('import("../runtime/composables/useWrappedFetch.js")') - expect(helper).not.toContain(buildConfigRootDir) - }) - - it('should run `build.config.ts` hooks in order with the build context', async () => { - const log = (await readFile(join(buildConfigRootDir, 'hooks.log'), 'utf-8')).trim().split('\n').map(line => JSON.parse(line)) - expect(log.slice(0, 3)).toEqual([ - expect.objectContaining({ hook: 'build:before', stub: false }), - expect.objectContaining({ hook: 'rollup:done', stub: false, meta: true }), - expect.objectContaining({ hook: 'build:done', stub: false, meta: true }), - ]) - expect(log[0].entries).toEqual(['content', 'features', 'module', 'nested/helper', 'runtime', 'shared', 'utils', 'vite']) - expect(await readFile(join(buildConfigRootDir, 'dist/vite.mjs'), 'utf-8')).toContain('from build:before') - }) - - it('should read the `unbuild` field of `package.json` in preference to `build`', async () => { - const unplugin = await readFile(join(replaceRootDir, 'dist/unplugin.mjs'), 'utf-8') - expect(unplugin).toContain('from "ext-pkg"') - expect(unplugin).not.toContain('bundled-ext-pkg') - expect(existsSync(join(replaceRootDir, 'dist/utils.mjs'))).toBe(false) - }) - - it('should keep `build.config.ts` externals external', async () => { - const vite = await readFile(join(buildConfigRootDir, 'dist/vite.mjs'), 'utf-8') - expect(vite).toContain('from "fake-pkg/sub"') - expect(vite).toContain('from "regex-pkg"') - const content = await readFile(join(buildConfigRootDir, 'dist/content.mjs'), 'utf-8') - expect(content).toContain('from "#content-alias/config"') - expect(vite + content).not.toContain('bundled-') - }) - - it('should apply `build.config.ts` replacements', async () => { - const vite = await readFile(join(buildConfigRootDir, 'dist/vite.mjs'), 'utf-8') - expect(vite).toContain('"1.2.3"') - expect(vite).not.toContain('__MODULE_VERSION__') - - const unplugin = await readFile(join(replaceRootDir, 'dist/unplugin.mjs'), 'utf-8') - expect(unplugin).not.toContain('--uiDev') - expect(unplugin).toMatch(/isDev = false/) - }) - - it('should fail on TypeScript syntax that Node cannot strip, with how to rewrite it', async () => { - for (const args of [['build'], ['prepare']]) { - const { stdout, stderr, exitCode } = await exec('pnpm', ['nuxt-module-build', ...args, nonErasableRootDir], { nodeOptions: { cwd: repoRoot } }) - expect(exitCode, args.join(' ')).not.toBe(0) - expect(stdout + stderr, args.join(' ')).toContain([ - 'Module code has to load with Node, which strips types and resolves imports as written:', - ' - src/levels.ts:1:1: `enum` (use an `as const` object and a union type of its values)', - ' - src/module.ts:1:37: `../package.json` is JSON (use `import pkg from \'../package.json\' with { type: \'json\' }` and read `pkg.version`; destructuring `pkg` bundles the whole file)', - ' - src/module.ts:4:1: `enum` (use an `as const` object and a union type of its values)', - ' - src/module.ts:5:28: parameter property (declare the field and assign it in the constructor)', - ].join('\n')) - expect(stdout + stderr, args.join(' ')).toMatch(/src\/module\.ts:\d+:\d+: angle-bracket type assertion \(write `value as Type`\)/) - expect(stdout + stderr, args.join(' ')).toContain(guide('module-code-loads-with-node')) - } - }) - - it('should refuse an `outDir` that contains the module root', async () => { - for (const outDir of ['.', '..']) { - const { stdout, stderr, exitCode } = await exec('pnpm', ['nuxt-module-build', 'build', '--outDir', outDir, noRuntimeRootDir], { nodeOptions: { cwd: repoRoot } }) - expect(exitCode).not.toBe(0) - expect(stdout + stderr).toContain(`\`--outDir ${outDir}\` resolves to \`${resolve(noRuntimeRootDir, outDir)}\`, which contains the module root; the build empties the output directory first. Use a directory inside the module such as \`dist\`. ${guide('output-directory')}`) - } - expect(existsSync(join(noRuntimeRootDir, 'package.json'))).toBe(true) - expect(existsSync(join(repoRoot, 'package.json'))).toBe(true) - }) - - it('should warn that `build.config.ts` is deprecated', () => { - expect(buildConfigBuild).toMatch(new RegExp(`\`build\\.config\\.ts\` is deprecated\\..*${guide('moving-from-buildconfigts')}`)) - expect(buildConfigBuild).not.toContain('instead of') - expect(buildConfigBuild).not.toContain('`unbuild` field') - }) - - it('should fail on every `build.config.ts` option without an equivalent', async () => { - const { stdout, stderr, exitCode } = await exec('pnpm', ['nuxt-module-build', 'build', unsupportedRootDir], { nodeOptions: { cwd: repoRoot } }) - expect(exitCode).not.toBe(0) - for (const option of ['entries[0].ext', 'entries[1].builder: \'untyped\'', 'hooks[\'build:prepare\']', 'hooks[\'rollup:options\']', 'rollup.emitCJS: true', 'rollup.alias', 'stub', 'unknownOption']) { - expect(stdout + stderr).toContain(`build.config.ts: ${option}`) - } - expect(stdout + stderr).not.toContain('build.config.ts: hooks[\'mkdist:entry:options\']') - expect(stdout + stderr).toContain(`build.config.ts: rollup.emitCJS: true (${guide('commonjs-output')})`) - expect(stdout + stderr).toContain(guide('unsupported-build-options')) - }) - - it('should surface isolated declaration diagnostics when the tsconfig opts in', async () => { - const { stdout, stderr, exitCode } = await exec('pnpm', ['nuxt-module-build', 'build', isolatedRootDir], { nodeOptions: { cwd: repoRoot } }) - expect(exitCode).not.toBe(0) - expect(stdout + stderr).toMatch(/Declaration generation failed under `?isolatedDeclarations/) - expect(stdout + stderr).toMatch(/TS90\d\d/) - expect(stdout + stderr).toContain(guide('isolated-declarations')) - expect(stdout + stderr).not.toMatch(/Type declarations could not be generated/) - }) - - it('should prepare a module without `.nuxt` before building it', async () => { - const { stdout, stderr, exitCode } = await exec('pnpm', ['nuxt-module-build', 'build', autoPrepareRootDir], { nodeOptions: { cwd: repoRoot, env: { ...process.env, NODE_ENV: '', TEST: '' } } }) - expect(exitCode).toBe(0) - expect(stdout + stderr).toMatch(new RegExp(`\\.nuxt\`? not found, running \`?nuxt-module-build prepare\`? first\\..*${guide('preparing-nuxt')}`)) - const declaration = await readFile(join(autoPrepareRootDir, 'dist/runtime/composables/useAliasedApp.d.ts'), 'utf-8') - expect(declaration).toMatch(/import\("nuxt\/app"\)\.NuxtApp/) - }) - - it('should prepare a module whose entry Node cannot import natively without handing it to jiti', async () => { - const { stderr, exitCode } = await exec('pnpm', ['nuxt-module-build', 'prepare', prepareLoaderRootDir], { nodeOptions: { cwd: repoRoot, env: { ...process.env, NUXT_TELEMETRY_DISABLED: '1' } } }) - expect(stderr).not.toContain('ERR_INTERNAL_ASSERTION') - expect(exitCode).toBe(0) - expect(await readFile(join(prepareLoaderRootDir, '.nuxt/nuxt.node.d.ts'), 'utf-8')).toContain('/// ') - const modulesDts = await readFile(join(prepareLoaderRootDir, '.nuxt/types/modules.d.ts'), 'utf-8') - expect(modulesDts).toContain(`typeof import(${JSON.stringify(join(prepareLoaderRootDir, 'src/module'))}).default`) - }) - - it('should explain type errors that prevent declaration generation', async () => { - const { stdout, stderr, exitCode } = await exec('pnpm', ['nuxt-module-build', 'build', typeErrorRootDir], { nodeOptions: { cwd: repoRoot } }) - expect(exitCode).not.toBe(0) - expect(stdout + stderr).toMatch(/TS4094/) - expect(stdout + stderr).toMatch(/Type declarations could not be generated/) - expect(stdout + stderr).toMatch(/cannot reference by name.*explicit type annotation, such as `ReturnType` for a value produced by an imported `fn`:\n- `defineCachedHandler` in \S*src\/runtime\/server\/cached\.ts:3\n/) - expect(stdout + stderr).toContain(guide('portability-errors')) - expect(existsSync(join(typeErrorRootDir, 'dist'))).toBe(false) - }) - - it('should fail on portability errors in a single-file component and in a script sharing its program', async () => { - const { stdout, stderr, exitCode } = await exec('pnpm', ['nuxt-module-build', 'build', vueErrorRootDir], { nodeOptions: { cwd: repoRoot } }) - expect(exitCode).not.toBe(0) - expect(stdout + stderr).toMatch(/components\/Cached\.vue\(4,14\): error TS(?:2742|2883)/) - expect(stdout + stderr).toMatch(/server\/cached\.ts\(3,14\): error TS(?:2742|2883)/) - expect(stdout + stderr).toMatch(/cannot reference by name.*:\n(?:- `\w+` in \S+\n)*- `cachedHandler` in \S*src\/runtime\/components\/Cached\.vue:4\n/) - expect(stdout + stderr).toMatch(/\n- `defineCachedHandler` in \S*src\/runtime\/server\/cached\.ts:3\n/) - expect(stdout + stderr).toContain(guide('portability-errors')) - expect(existsSync(join(vueErrorRootDir, 'dist'))).toBe(false) - }) - - it('should warn about type errors that do not affect runtime declarations and build anyway', async () => { - const { stdout, stderr, exitCode } = await exec('pnpm', ['nuxt-module-build', 'build', semanticErrorRootDir], { nodeOptions: { cwd: repoRoot } }) - expect(exitCode).toBe(0) - expect(stdout + stderr).toMatch(/2 type errors were reported while generating declarations for `?src\/runtime`?; the declarations were emitted\. If the module's own type check \(for example `?nuxt typecheck`? or `?vue-tsc --noEmit`?\) passes/) - expect(stdout + stderr).toContain('src/runtime/utils/typo.ts(1,14): error TS2322') - expect(stdout + stderr).toContain('src/runtime/components/Typo.vue(3,7): error TS2322') - expect((stdout + stderr).match(/type errors? (?:was|were) reported/g)).toHaveLength(1) - expect(stdout + stderr).toContain(guide('other-type-errors')) - expect(await readFile(join(semanticErrorRootDir, 'dist/runtime/utils/typo.d.ts'), 'utf-8')).toBe('export declare const count: number;\nexport declare const double: (value: number) => number;\n') - const component = await readFile(join(semanticErrorRootDir, 'dist/runtime/components/Typo.vue.d.ts'), 'utf-8') - expect(component).toContain('label: string') - expect(component).toBe(await readFile(join(semanticErrorRootDir, 'dist/runtime/components/Typo.d.vue.ts'), 'utf-8')) - expect(stdout + stderr).not.toContain('TS2307') - const composable = await readFile(join(semanticErrorRootDir, 'dist/runtime/composables/useSize.d.ts'), 'utf-8') - expect(composable).toContain(`import type { Props } from '../components/Sized.vue';`) - expect(composable).toMatch(/export declare function useSize\(props: Props\): import\("vue"\)\.ComputedRef<"xs" \| "sm" \| "md" \| undefined>;/) - }) - - it('should build an annotated module under `isolatedDeclarations` while still inferring runtime types', async () => { - const annotatedDistDir = join(annotatedRootDir, 'dist') - const moduleTypes = await readFile(join(annotatedDistDir, 'module.d.mts'), 'utf-8') - expect(moduleTypes).toContain('NuxtModule') - expect(moduleTypes).toMatch(/apiKey: string/) - const pluginTypes = await readFile(join(annotatedDistDir, 'runtime/plugins/plugin.d.ts'), 'utf-8') - expect(pluginTypes).toContain('import("nuxt/app").Plugin<') - expect(JSON.parse(await readFile(join(annotatedDistDir, 'module.json'), 'utf-8'))).toMatchObject({ name: 'my-module', configKey: 'myModule' }) - }) - - it('should not let a wildcard `paths` entry shadow real packages when loading meta', async () => { - const meta = JSON.parse(await readFile(join(wildcardRootDir, 'dist/module.json'), 'utf-8')) - expect(meta).toMatchObject({ name: 'wildcard-module', configKey: 'wildcardModule' }) - }) - - it('should mirror the runtime source tree even when it has a single subdirectory', async () => { - const files = await readdir(join(fourthDistDir, 'runtime'), { recursive: true, withFileTypes: true }) - const names = files.filter(file => file.isFile()).map(file => join(file.parentPath, file.name).replace(join(fourthDistDir, 'runtime') + '/', '')) - expect(names.sort()).toMatchInlineSnapshot(` - [ - "plugins/plugin.d.ts", - "plugins/plugin.js", - ] - `) - }) - - it('should bundle the `imports` of `package.json` and the files they point at', async () => { - await exec('pnpm', ['nuxt-module-build', 'build', packageImportsRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true }) - const built = await readFile(join(packageImportsRootDir, 'dist/module.mjs'), 'utf-8') - expect(built).toContain('loaded helper') - expect(built).toContain('through imports') - expect(built).not.toContain('#internal') - }) - - it('should re-export the module\'s default export from the types that `prepare` writes', async () => { - await exec('pnpm', ['nuxt-module-build', 'prepare', packageImportsRootDir], { nodeOptions: { cwd: repoRoot, env: { ...process.env, NUXT_TELEMETRY_DISABLED: '1' } }, throwOnError: true }) - const probe = join(packageImportsRootDir, 'probe.ts') - await writeFile(probe, `import type Module from './.nuxt/module-builder/types.mjs'\n\nexport const meta: Promise<{ configKey?: string }> = ({} as typeof Module).getMeta!()\n`) - const { stdout, stderr, exitCode } = await exec('pnpm', ['exec', 'tsc', '--ignoreConfig', '--noEmit', '--strict', '--skipLibCheck', '--allowImportingTsExtensions', '--module', 'nodenext', '--moduleResolution', 'nodenext', probe], { nodeOptions: { cwd: repoRoot } }) - expect(stdout + stderr).toBe('') - expect(exitCode).toBe(0) - }) - - it('should fail when module code imports relative files without their extension', async () => { - const sourceLine = (await readFile(join(extensionlessRootDir, 'src/module.ts'), 'utf-8')).split('\n').findIndex(line => line.includes('./utils.js')) + 1 - for (const args of [['build'], ['prepare']]) { - const { stdout, stderr, exitCode } = await exec('pnpm', ['nuxt-module-build', ...args, extensionlessRootDir], { nodeOptions: { cwd: repoRoot } }) - expect(exitCode).not.toBe(0) - expect(stdout + stderr).toContain([ - 'Module code has to load with Node, which strips types and resolves imports as written:', - ` - src/module.ts:${sourceLine}:31: \`./utils.js\` (use \`./utils.ts\`)`, - ` - src/module.ts:${sourceLine + 1}:24: \`./helpers\` (use \`./helpers.ts\`)`, - ` - src/module.ts:${sourceLine + 2}:21: \`./kit\` (use \`./kit/index.ts\`)`, - `Change each one as suggested. ${guide('module-code-loads-with-node')}`, - ].join('\n')) - expect(stdout + stderr).not.toContain(`:${sourceLine + 3}:`) - } - expect(existsSync(join(extensionlessRootDir, 'dist'))).toBe(false) - }) - - it('should build a module without a runtime directory', async () => { - const files = await readdir(join(noRuntimeRootDir, 'dist')) - expect(files.sort()).toEqual(['module.d.mts', 'module.json', 'module.mjs', 'types.d.mts', 'utils.d.mts', 'utils.mjs']) - }) - - it('should build a runtime directory that contains only single-file components', async () => { - const files = await listFiles(join(vueOnlyRootDir, 'dist/runtime')) - expect(files.sort()).toMatchInlineSnapshot(` - [ - "components", - "components/TestMe.css", - "components/TestMe.d.vue.ts", - "components/TestMe.vue", - "components/TestMe.vue.d.ts", - "components/TestMeSetup.d.vue.ts", - "components/TestMeSetup.vue", - "components/TestMeSetup.vue.d.ts", - ] - `) - }) - - it('should flatten, prefix and minify runtime CSS', async () => { - const card = await readFile(join(stylesheetsRootDir, 'dist/runtime/styles/card.css'), 'utf-8') - expect(card).toMatch(/^@import "\.\/base\.css";/) - expect(card).toContain('.card .title{font-weight:700}') - expect(card).toContain('.card:hover{color:#639}') - expect(card).toContain('-webkit-user-select:none') - expect(card).not.toMatch(/&|\n/) - }) - - it('should compile runtime Sass to CSS and skip partials', async () => { - const styles = join(stylesheetsRootDir, 'dist/runtime/styles') - expect((await readdir(styles)).sort()).toEqual(['base.css', 'card.css', 'indented.css', 'legacy.less', 'theme.css']) - expect(await readFile(join(styles, 'theme.css'), 'utf-8')).toMatch(/^\.theme \.nested \{\s*padding: 1px;\s*\}$/m) - expect(await readFile(join(styles, 'theme.css'), 'utf-8')).toContain('color: #00dc82;') - expect(await readFile(join(styles, 'indented.css'), 'utf-8')).toContain('color: blue;') - }) - - it('should copy runtime declaration files verbatim', async () => { - const file = 'types/ambient.d.ts' - expect(await readFile(join(stylesheetsRootDir, 'dist/runtime', file), 'utf-8')).toBe(await readFile(join(stylesheetsRootDir, 'src/runtime', file), 'utf-8')) - }) - - it('should rewrite `#app` in copied runtime declaration files', async () => { - expect(await readFile(join(stylesheetsRootDir, 'dist/runtime/types/app.d.ts'), 'utf-8')).toBe(`import type { NuxtApp } from 'nuxt/app'\nexport type App = NuxtApp\n`) - }) - - it('should point stylesheet imports in runtime scripts at the emitted files', async () => { - const styled = await readFile(join(stylesheetsRootDir, 'dist/runtime/plugins/styled.js'), 'utf-8') - expect(styled).toContain('import "../styles/card.css";') - expect(styled).toContain('import "../styles/theme.css";') - expect(styled).not.toContain('theme.scss') - }) - - it('should keep every non-relative runtime import as written', async () => { - const handler = await readFile(join(transpileRootDir, 'dist/runtime/server/handler.js'), 'utf-8') - expect(findStaticImports(handler).map(i => i.specifier)).toEqual([ - '#internal/nuxt.config.mjs', - '~/app.config', - '@/root', - '#app', - 'fake-dep', - '#fixture-cache', - '../utils/local.js', - ]) - const options = await readFile(join(transpileRootDir, 'dist/runtime/utils/options.d.ts'), 'utf-8') - expect(findStaticImports(options).map(i => i.specifier)).toEqual(['fake-types']) - }) - - it('should not emit dependencies or bundler helpers into the runtime directory', async () => { - const files = await listFiles(join(transpileRootDir, 'dist/runtime')) - expect(files.filter(file => /node_modules|_virtual/.test(file))).toEqual([]) - for (const file of files.filter(file => /\.m?[jt]s$/.test(file))) { - expect(await readFile(join(transpileRootDir, 'dist/runtime', file), 'utf-8'), file).not.toMatch(/bundled-fake-dep|DeepPartial/) - } - }) - - it('should keep types of packages that are not dependencies external in module declarations', async () => { - const types = await readFile(join(transpileRootDir, 'dist/module.d.mts'), 'utf-8') - expect(types).toMatch(/from "fake-types"/) - expect(types).toMatch(/from "fake-cjs-types"/) - expect(types).not.toMatch(/DeepPartial/) - }) - - it('should keep bracketed file names in runtime output', async () => { - expect(existsSync(join(transpileRootDir, 'dist/runtime/server/routes/[...slug].js'))).toBe(true) - expect(existsSync(join(transpileRootDir, 'dist/runtime/server/routes/[...slug].d.ts'))).toBe(true) - }) - - it('should resolve imports of the package itself to its source in declarations', async () => { - const types = await readFile(join(transpileRootDir, 'dist/runtime/utils/self.d.ts'), 'utf-8') - expect(types).toMatch(/=> string;/) - }) - - it('should generate declarations for each project of a solution-style tsconfig', async () => { - const route = await readFile(join(solutionRootDir, 'dist/runtime/server/api/[id].get.d.ts'), 'utf-8') - expect(route).toMatch(/=> string;/) - const app = await readFile(join(solutionRootDir, 'dist/runtime/composables/useAliasedApp.d.ts'), 'utf-8') - expect(app).toMatch(/import\("nuxt\/app"\)\.NuxtApp/) - expect(existsSync(join(solutionRootDir, 'dist/runtime/components/TestMe.vue.d.ts'))).toBe(true) - }) - - it('should use a tsconfig from a parent directory', async () => { - const app = await readFile(join(parentTsconfigRootDir, 'packages/mod/dist/runtime/composables/useAliasedApp.d.ts'), 'utf-8') - expect(app).toMatch(/import\("nuxt\/app"\)\.NuxtApp/) - }) - - it('should name runtime types by package when the generated tsconfig maps the package into the store', async () => { - const logger = await readFile(join(parentTsconfigRootDir, 'packages/mod/dist/runtime/logger.d.ts'), 'utf-8') - expect(logger).toMatch(/import\("fake-logger"\)\.LoggerInstance/) - }) - - it('should keep the imports and re-exports of each runtime file as written', async () => { - const dist = join(runtimeShapeRootDir, 'dist/runtime') - const read = (file: string) => readFile(join(dist, file), 'utf-8') - expect(await read('disabled/index.js')).toMatchInlineSnapshot(` - "import "./side.js"; - export { defineThing } from "./composables/defineThing.js"; - " - `) - expect(await read('disabled/composables/defineThing.js')).toMatchInlineSnapshot(` - "export { defineThing } from "../../composables/mock.js"; - " - `) - expect(await read('content/index.js')).toMatchInlineSnapshot(` - "export * from "../components/TestMe.vue"; - export * from "../components/TestMeSetup.vue"; - export * from "./prose.js"; - " - `) - expect(await read('content/index.d.ts')).toMatchInlineSnapshot(` - "export * from '../components/TestMe.vue'; - export * from '../components/TestMeSetup.vue'; - export * from './prose.js'; - " - `) - expect(await read('content/prose.js')).toMatchInlineSnapshot(` - "export * from "./levels.js"; - " - `) - expect(await read('content/prose.d.ts')).toMatchInlineSnapshot(` - "export * from './levels.js'; - export interface ProseThing { - title: string; - } - " - `) - }) - - it('should keep the source order of imports and re-exports in each runtime file', async () => { - const dist = join(runtimeShapeRootDir, 'dist/runtime/order') - expect(await readFile(join(dist, 'interleaved.js'), 'utf-8')).toMatchInlineSnapshot(` - "import "fake-register"; - import { level } from "./levels.js"; - export * from "./reexported.js"; - import "./order.css"; - export { useState } from "#imports"; - import "fake-polyfill"; - import "./effect.js"; - import { ref } from "vue"; - export const value = ref(level); - " - `) - }) - - it('should point runtime imports outside the runtime directory at the files emitted for them', async () => { - const dist = join(runtimeShapeRootDir, 'dist') - expect(await readFile(join(dist, 'runtime/server/uses.js'), 'utf-8')).toMatchInlineSnapshot(` - "import { merge } from "../../utils/merge.mjs"; - import { CONSTANT } from "../../shared/constants.js"; - export const combine = (a, b) => [merge(a, b), CONSTANT]; - " - `) - expect(await readFile(join(dist, 'runtime/server/uses.d.ts'), 'utf-8')).toMatchInlineSnapshot(` - "import type { RootType } from '../../_external/src/types.js'; - import type { RuntimeType } from '../types.js'; - export declare const combine: (a: RootType & RuntimeType, b: RootType & RuntimeType) => readonly [RootType & RuntimeType, 10]; - " - `) - expect(await readFile(join(dist, 'runtime/escaping.js'), 'utf-8')).toContain(`import("../_external/external.js")`) - expect(await readFile(join(dist, 'shared/constants.js'), 'utf-8')).toMatchInlineSnapshot(` - "import { LIMIT } from "./limits.js"; - export const CONSTANT = LIMIT; - " - `) - const files = await listFiles(dist) - expect(files.filter(file => !file.startsWith('runtime')).sort()).toMatchInlineSnapshot(` - [ - "_external", - "_external/external.d.ts", - "_external/external.js", - "_external/src", - "_external/src/types.d.ts", - "data.d.mts", - "data.mjs", - "module.d.mts", - "module.json", - "module.mjs", - "routing.d.ts", - "shared", - "shared/constants.d.ts", - "shared/constants.js", - "shared/limits.d.ts", - "shared/limits.js", - "types", - "types.d.mts", - "types/middlewares.d.ts", - "utils", - "utils.d.mts", - "utils.mjs", - "utils/merge.d.mts", - "utils/merge.mjs", - ] - `) - expect(files.filter(file => /^runtime\/(?:types|server|utils)/.test(file)).sort()).toMatchInlineSnapshot(` - [ - "runtime/server", - "runtime/server/limiter.d.ts", - "runtime/server/limiter.js", - "runtime/server/uses.d.ts", - "runtime/server/uses.js", - "runtime/types.d.ts", - "runtime/types.js", - "runtime/utils", - "runtime/utils/props.d.ts", - "runtime/utils/props.js", - "runtime/utils/provider.d.ts", - "runtime/utils/provider.js", - ] - `) - }) - - it('should emit only declarations for files outside the runtime directory that runtime files use as types', async () => { - const dist = join(runtimeShapeRootDir, 'dist') - expect(await readFile(join(dist, 'runtime/server/limiter.js'), 'utf-8')).toMatchInlineSnapshot(` - "import "../disabled/side.js"; - export const limit = (options) => options.maxRequestSizeInBytes; - " - `) - expect(await readFile(join(dist, 'runtime/composables/useLocaleRoute.js'), 'utf-8')).toMatchInlineSnapshot(` - "export const useLocaleRoute = (route) => route; - " - `) - expect(await readFile(join(dist, 'routing.d.ts'), 'utf-8')).toMatchInlineSnapshot(` - "import type { RootType } from './_external/src/types.js'; - export interface RouteInfo { - path: string; - root: RootType; - } - export declare const localizeRoutes: (file: string) => string; - " - `) - for (const file of ['routing.js', 'kit', 'types/middlewares.js', 'types.d.ts', 'types.js', '_external/src/types.js']) { - expect(existsSync(join(dist, file)), file).toBe(false) - } - }) - - it('should type imports of build-time aliases as `any` in declarations', async () => { - const dist = join(runtimeShapeRootDir, 'dist/runtime') - expect(await readFile(join(dist, 'composables/useThemeConfig.d.ts'), 'utf-8')).toContain('useThemeConfig: () => any;') - expect(await readFile(join(dist, 'composables/useButton.d.ts'), 'utf-8')).toMatchInlineSnapshot(` - "export declare const useButton: () => { - slots: any; - size: any; - ui: any; - }; - " - `) - expect(await readFile(join(dist, 'components/Button.d.vue.ts'), 'utf-8')).toMatchInlineSnapshot(` - "type __VLS_Props = { - size?: string; - }; - declare const __VLS_export: import("vue").DefineComponent<__VLS_Props, { - classes: any[]; - }, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<__VLS_Props> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>; - declare const _default: typeof __VLS_export; - export default _default; - " - `) - expect(existsSync(join(dist, 'components/Sized.vue.d.ts'))).toBe(true) - }) - - it('should generate declarations with the module\'s own `.nuxt` when the tsconfig takes its types from a playground', async () => { - expect(routesBuild).toMatch(new RegExp(`\\.\\./tsconfig.json\`? takes its generated types from another app's \`?.nuxt\`?; declarations are generated with \`?.nuxt/tsconfig.json\`? instead. Add a \`?tsconfig.json\`? in the module directory that extends \`?./.nuxt/tsconfig.json\`?. ${guide('module-tsconfig')}`)) - expect(await readFile(join(routesRootDir, 'playground/.nuxt/types/nitro-routes.d.ts'), 'utf-8')).toContain('/api/secret') - for (const file of await listFiles(join(routesRootDir, 'dist'))) { - if (file.includes('.')) { - expect(await readFile(join(routesRootDir, 'dist', file), 'utf-8'), file).not.toMatch(/must-not-be-published|playground|\.nuxt/) - } - } - }) - - it('should type the responses of routes the module registers and leave other routes unknown', async () => { - expect(await readFile(join(routesRootDir, '.nuxt/types/nitro-routes.d.ts'), 'utf-8')).toContain('/api/own') - const { default: ts } = await import('typescript') - const files = ts.getParsedCommandLineOfConfigFile(join(routesRootDir, '.nuxt/tsconfig.json'), {}, { ...ts.sys, onUnRecoverableConfigFileDiagnostic: () => {} })!.fileNames - expect(files.map(file => relative(routesRootDir, file)).filter(file => file.includes('routes.d.ts')).sort()).toEqual(['../sibling/types/routes.d.ts', 'docs/types/routes.d.ts', 'playground/types/routes.d.ts']) - expect(await readFile(join(routesRootDir, 'dist/runtime/composables/useOwn.d.ts'), 'utf-8')).toBe(`export declare const useOwn: () => import("nuxt/app").AsyncData<{\n own: "module-owned";\n} | undefined, import("nuxt/app").NuxtError | undefined>;\n`) - expect(await readFile(join(routesRootDir, 'dist/runtime/composables/useGlobal.d.ts'), 'utf-8')).toBe('export declare const useGlobal: () => Fake.Thing;\n') - expect(routesBuild).not.toMatch(/type errors? (?:was|were) reported/) - for (const name of ['useSecret', 'useSibling', 'useDocs']) { - expect(await readFile(join(routesRootDir, `dist/runtime/composables/${name}.d.ts`), 'utf-8'), name).toBe(`export declare const ${name}: () => import("nuxt/app").AsyncData | undefined>;\n`) - } - const component = await readFile(join(routesRootDir, 'dist/runtime/components/Routes.vue.d.ts'), 'utf-8') - expect(component).toContain('own: import("vue").Ref<{\n own: "module-owned";\n } | undefined, {\n own: "module-owned";\n } | undefined>;') - expect(component).toContain('secret: import("vue").Ref;') - }) - - it('should give every relative specifier in runtime declarations an extension that resolves', async () => { - expect(await unresolvedSpecifiers(join(runtimeShapeRootDir, 'dist'))).toEqual([]) - }) - - it('should name inferred types by package when the generated tsconfig maps a package to its real path', async () => { - const types = await readFile(join(portableRootDir, 'dist/module.d.mts'), 'utf-8') - expect(types).toMatch(/Thing<\{/) - expect(types).toMatch(/["']fake-schema["']/) - }) - - it('should keep value exports as values in `types.d.mts`', async () => { - const types = await readFile(join(valueExportsRootDir, 'dist/types.d.mts'), 'utf-8') - expect(types).toMatchInlineSnapshot(` - "import type { ModuleHooks, ModuleRuntimeHooks, ModuleRuntimeConfig, ModulePublicRuntimeConfig } from './module.mjs' - - declare module '#app' { - interface RuntimeNuxtHooks extends ModuleRuntimeHooks {} - } - - declare module '@nuxt/schema' { - interface NuxtHooks extends ModuleHooks {} - interface RuntimeConfig extends ModuleRuntimeConfig {} - interface PublicRuntimeConfig extends ModulePublicRuntimeConfig {} - } - - export { defineMyModuleConfig, Mode, type ModuleHooks, type ModuleOptions, type ModulePublicRuntimeConfig, type ModuleRuntimeConfig, type ModuleRuntimeHooks, myModuleVersion, default } from './module.mjs' - " - `) - expect(await readFile(join(valueExportsIsolatedRootDir, 'dist/types.d.mts'), 'utf-8')).toBe(types) - - for (const root of [valueExportsRootDir, valueExportsIsolatedRootDir]) { - const { stdout, stderr, exitCode } = await exec('pnpm', ['exec', 'tsc', '--noEmit', '-p', join(root, 'playground/consumer.tsconfig.json')], { nodeOptions: { cwd: repoRoot } }) - expect(stdout + stderr, root).toBe('') - expect(exitCode).toBe(0) - } - }) - - it('should generate types when no ModuleOptions are exported', async () => { - const types = await readFile(join(secondDistDir, 'types.d.mts'), 'utf-8') - expect(types).toMatchInlineSnapshot(` - "import type { NuxtModule } from '@nuxt/schema' - - import type { default as Module, ModuleHooks, ModuleRuntimeHooks, ModuleRuntimeConfig, ModulePublicRuntimeConfig } from './module.mjs' - - declare module '#app' { - interface RuntimeNuxtHooks extends ModuleRuntimeHooks {} - } - - declare module '@nuxt/schema' { - interface NuxtHooks extends ModuleHooks {} - interface RuntimeConfig extends ModuleRuntimeConfig {} - interface PublicRuntimeConfig extends ModulePublicRuntimeConfig {} - } - - export type ModuleOptions = typeof Module extends NuxtModule ? Partial : Record - - export { type ModuleHooks, type ModulePublicRuntimeConfig, type ModuleRuntimeConfig, type ModuleRuntimeHooks, default } from './module.mjs' - " - `) - }) - - it('should generate module metadata when the module entry imports runtime code', async () => { - const meta = await readFile(join(thirdDistDir, 'module.json'), 'utf-8') - expect(JSON.parse(meta)).toMatchObject({ configKey: 'myModule', name: 'my-module' }) - }) - - it('should externalise runtime imports made through relative, aliased and `.vue` specifiers', async () => { - const moduleCode = await readFile(join(thirdDistDir, 'module.mjs'), 'utf-8') - const specifiers = findStaticImports(moduleCode).map(i => i.specifier).filter(s => s.includes('runtime')) - expect(specifiers.sort()).toMatchInlineSnapshot(` - [ - "./runtime/composables/useShape.js", - "./runtime/utils/aliased.js", - "./runtime/utils/name.js", - ] - `) - }) - - it('should add extensions to runtime imports when the path has spaces or non-ASCII characters', async () => { - const moduleDts = await readFile(join(encodedRootDir, 'dist/module.d.mts'), 'utf-8') - const runtimeImport = findStaticImports(moduleDts).find(i => i.specifier.includes('runtime')) - expect(runtimeImport!.code.trim()).toBe(`import { SharedTypeFromRuntime } from "./runtime/plugins/plugin.js";`) - }) - - it('should build a module under a path with spaces and non-ASCII characters', async () => { - const encodedDistDir = join(encodedRootDir, 'dist') - const runtimeSpecifiers = (code: string) => findStaticImports(code).map(i => i.specifier).filter(s => s.includes('runtime')).sort() - - expect(runtimeSpecifiers(await readFile(join(encodedDistDir, 'module.mjs'), 'utf-8'))).toEqual([ - './runtime/composables/useShape.js', - './runtime/utils/aliased.js', - './runtime/utils/name.js', - ]) - expect(JSON.parse(await readFile(join(encodedDistDir, 'module.json'), 'utf-8'))).toMatchObject({ name: 'my-module', configKey: 'myModule' }) - expect(await readFile(join(encodedDistDir, 'types.d.mts'), 'utf-8')).toContain('from \'./module.mjs\'') - - const runtimeFiles = (dir: string) => listFiles(join(dir, 'runtime')).then(files => files.sort()) - expect(await runtimeFiles(encodedDistDir)).toEqual(await runtimeFiles(thirdDistDir)) - }) - - it('should point imports of a runtime JSX file at its `.jsx` output', async () => { - const runtime = join(thirdDistDir, 'runtime') - expect(await readFile(join(runtime, 'components/JsxCard.vue'), 'utf-8')).toContain(`import JsxComponent from "./JsxComponent.jsx";`) - expect(await readFile(join(runtime, 'components/JsxSlot.jsx'), 'utf-8')).toMatchInlineSnapshot(` - "import { defineComponent } from "vue"; - import { useNuxtApp } from "#app"; - import JsxComponent from "./JsxComponent.jsx"; - export const useSlotApp = () => useNuxtApp(); - export default defineComponent((_, { slots }) => () =>
{slots.default?.()}
); - " - `) - expect(await readFile(join(runtime, 'components/JsxSlot.d.ts'), 'utf-8')).toContain('export declare const useSlotApp: () => import("nuxt/app").NuxtApp;') - const moduleDts = await readFile(join(thirdDistDir, 'module.d.mts'), 'utf-8') - expect(findStaticImports(moduleDts).map(i => i.specifier)).toContain('./runtime/components/JsxComponent.jsx') - }) - - it('should compile JSX in server runtime files and the files they import, and preserve it elsewhere', async () => { - const runtime = join(thirdDistDir, 'runtime') - expect(existsSync(join(runtime, 'server/render.jsx'))).toBe(false) - for (const file of ['utils/strong.js', 'utils/bold.js']) { - expect(await readFile(join(runtime, file), 'utf-8'), file).toContain(`import { jsx as _jsx } from "vue/jsx-runtime";`) - } - expect(await readFile(join(runtime, 'utils/label.jsx'), 'utf-8')).toContain('label') - expect(JSON.parse(await readFile(join(thirdDistDir, 'module.json'), 'utf-8'))).toMatchObject({ name: 'my-module' }) - expect(await readFile(join(runtime, 'server/render.js'), 'utf-8')).toMatchInlineSnapshot(` - "import { strong } from "../utils/strong.js"; - import { jsx as _jsx } from "vue/jsx-runtime"; - export const render = (label) => /* @__PURE__ */ _jsx("p", { children: strong(label) }); - " - `) - expect(await readFile(join(runtime, 'server/render.d.ts'), 'utf-8')).toMatchInlineSnapshot(` - "import { useSlotApp } from '../components/JsxSlot.jsx'; - export type SlotApp = ReturnType; - export declare const render: (label: string) => import("vue/jsx-runtime").JSX.Element; - " - `) - }) - - describe('with plain `tsdown` and `builder()`', () => { - const env = { ...process.env, NODE_ENV: '', TEST: '' } - const ejectedExampleRootDir = rootDir.replace('example', '.temp-example-ejected') - - const hashDir = async (dir: string) => { - const files = (await readdir(dir, { recursive: true, withFileTypes: true })).filter(file => file.isFile()) - return Object.fromEntries(await Promise.all(files.map(async (file) => { - const path = join(file.parentPath, file.name) - return [relative(dir, path), createHash('sha256').update(await readFile(path)).digest('hex')] as const - }))) - } - - const writeTsdownConfig = (dir: string, options: string, { imports = [] as string[], hooks = [] as string[] } = {}) => writeFile(join(dir, 'tsdown.config.ts'), [ - builderImport, - ...imports, - '', - 'export default {', - ...hooks, - ` plugins: [builder(${options})],`, - '}', - '', - ].join('\n')) - - const eject = async (dir: string) => { - const pkgPath = join(dir, 'package.json') - const { build, ...pkg } = JSON.parse(await readFile(pkgPath, 'utf-8')) - await writeFile(pkgPath, JSON.stringify(pkg, null, 2)) - await writeTsdownConfig(dir, build ? JSON.stringify(build) : '') - } - - const ejectBuildConfig = async (dir: string) => { - const pkgPath = join(dir, 'package.json') - const { build: _, ...pkg } = JSON.parse(await readFile(pkgPath, 'utf-8')) - await writeFile(pkgPath, JSON.stringify(pkg, null, 2)) - await rm(join(dir, 'build.config.ts')) - await writeTsdownConfig(dir, `{ - entries: ['src/utils', './src/vite.ts', { input: 'src/content', name: 'content' }, 'src/nested/helper', { input: 'src/shared/', outDir: 'dist/shared' }, { input: 'src/features/', outDir: 'dist/features', ext: 'js' }], - externals, - replace: { __MODULE_VERSION__: JSON.stringify('1.2.3') }, - }`, { - imports: [`import { writeFileSync } from 'node:fs'`, `import { join } from 'node:path'`, `import { externals } from './build/externals.ts'`], - hooks: [ - ` hooks: {`, - ` 'build:prepare'(ctx) {`, - ` writeFileSync(join(ctx.options.cwd, 'src/generated.ts'), 'export const generated = "from build:before"\\n')`, - ` },`, - ` },`, - ], - }) - } - - const ejectReplace = async (dir: string) => { - const pkgPath = join(dir, 'package.json') - const { build: _build, unbuild: _unbuild, ...pkg } = JSON.parse(await readFile(pkgPath, 'utf-8')) - await writeFile(pkgPath, JSON.stringify(pkg, null, 2)) - await rm(join(dir, 'build.config.ts')) - await writeTsdownConfig(dir, `{ - entries: ['./src/unplugin'], - externals: ['#build/ui', 'ext-pkg'], - replace: { delimiters: ['', ''], values: { "process.argv.includes('--uiDev')": 'false' } }, - }`) - } - - it('should build the same `dist` as `nuxt-module-build build` did without it, for every module that builds', async () => { - await rm(ejectedExampleRootDir, { recursive: true, force: true }) - await cp(rootDir, ejectedExampleRootDir, { recursive: true }) - const fixtures: Array<[dir: string, eject: (dir: string) => Promise]> = [ - [ejectedExampleRootDir, eject], - ...[secondRootDir, thirdRootDir, fourthRootDir, encodedRootDir, noRuntimeRootDir, vueOnlyRootDir, annotatedRootDir, transpileRootDir, solutionRootDir, join(parentTsconfigRootDir, 'packages/mod'), portableRootDir, stylesheetsRootDir, runtimeShapeRootDir, routesRootDir, autoPrepareRootDir, semanticErrorRootDir].map(dir => [dir, eject] as [string, typeof eject]), - [buildConfigRootDir, ejectBuildConfig], - [replaceRootDir, ejectReplace], - ] - await Promise.all(fixtures.map(async ([dir, ejectFixture]) => { - await exec('pnpm', ['nuxt-module-build', 'build', dir], { nodeOptions: { cwd: repoRoot, env }, throwOnError: true }) - const built = await hashDir(join(dir, 'dist')) - expect(Object.keys(built), dir).toContain('module.json') - await ejectFixture(dir) - await exec('node', [tsdownBin], { nodeOptions: { cwd: dir, env }, throwOnError: true }) - expect(await hashDir(join(dir, 'dist')), dir).toEqual(built) - await exec('pnpm', ['nuxt-module-build', 'build', dir], { nodeOptions: { cwd: repoRoot, env }, throwOnError: true }) - expect(await hashDir(join(dir, 'dist')), dir).toEqual(built) - })) - }, 300 * 1000) - - it('should explain failed builds and remove their partial output', async () => { - await Promise.all([typeErrorRootDir, vueErrorRootDir, isolatedRootDir].map(eject)) - const [typeError, vueError, isolated] = await Promise.all([typeErrorRootDir, vueErrorRootDir, isolatedRootDir].map(dir => exec('node', [tsdownBin], { nodeOptions: { cwd: dir, env } }))) - for (const [result, dir] of [[typeError, typeErrorRootDir], [vueError, vueErrorRootDir]] as const) { - expect(result!.exitCode, dir).not.toBe(0) - expect(result!.stdout + result!.stderr, dir).toContain('Type declarations could not be generated') - expect(existsSync(join(dir, 'dist')), dir).toBe(false) - } - expect(isolated!.exitCode).not.toBe(0) - expect(isolated!.stdout + isolated!.stderr).toMatch(/Declaration generation failed under `?isolatedDeclarations/) - }) - }) - - it('should pack the `dist` paths in `publishConfig` with pnpm, and `dist` with npm, without warnings', async () => { - const packed = async (flow: string) => JSON.parse((await exec('tar', ['-xzOf', join(packDir, flow, 'my-module-1.0.0.tgz'), 'package/package.json'], { throwOnError: true })).stdout) - const { publishConfig } = JSON.parse(await readFile(join(rootDir, 'package.json'), 'utf-8')) - expect(await packed('source-exports')).toMatchObject({ exports: publishConfig.exports, main: publishConfig.main }) - expect(await packed('source-exports')).not.toHaveProperty('publishConfig') - expect(await packed('dist')).toMatchObject({ exports: publishConfig.exports, main: publishConfig.main }) - for (const flow of flows) { - const output = flowOutput.get(flow.name)!.pack - expect(output, flow.name).toContain('Build complete') - expect(output, flow.name).not.toContain('`package.json`') - } - }) - - it('should refuse to build source exports for a pack by npm, including when a pnpm script runs it', async () => { - const { stdout, stderr, exitCode } = await exec('node', [...packProbeArgs, join(repoRoot, 'src/cli.ts'), 'build'], { nodeOptions: { cwd: sourceFlowRootDir, env: npmPackFromPnpmScript() } }) - expect(exitCode, `${packProbeContext()}\n${stdout}${stderr}`).not.toBe(0) - expect(stdout + stderr).toMatch(/`npm(?:@[\d.]+)?` packs these fields of `package\.json` as written, and they point at TypeScript sources or paths that `files` leaves out: `exports`, `main` \(`\.\/\.nuxt\/module-builder\/types\.d\.mts`, `\.\/src\/module\.ts`, `\.\/src\/utils\.ts`\)\./) - expect(existsSync(join(sourceFlowRootDir, 'dist/module.mjs'))).toBe(true) - }) - - describe.each(flows)('$name flow', ({ name, rootDir, nodeTypeErrors }) => { - const distDir = join(rootDir, 'dist') - const runtimeDir = join(distDir, 'runtime') - const typeErrors = (output: string) => output.split('\n').filter(line => line.includes('error TS')) - - it('should type the playground and its config through the module\'s exports', () => { - expect(typeErrors(flowOutput.get(name)!.appTypes)).toEqual([]) - expect(typeErrors(flowOutput.get(name)!.nodeTypes)).toEqual(nodeTypeErrors) - }) - - it('should render the playground with the module installed by name', async () => { - expect(await readFile(join(rootDir, 'playground/.output/public/index.html'), 'utf-8')).toContain('Nuxt module playground!') - }) - - it('should reference `@nuxt/schema` rather than `nuxt/schema` in module declarations', async () => { - const types = await readFile(join(distDir, 'module.d.mts'), 'utf-8') - expect(types).toContain('import("@nuxt/schema")') - expect(types).not.toContain('import("nuxt/schema")') - }) - - it('should generate all files', async () => { - const files = await readdir(distDir) - expect(files).toMatchInlineSnapshot(` - [ - "module.d.mts", - "module.json", - "module.mjs", - "runtime", - "types.d.mts", - "utils.d.mts", - "utils.mjs", - ] - `) - - const runtime = await readdir(join(runtimeDir, 'plugins')) - expect(runtime).toMatchInlineSnapshot(` - [ - "plugin.d.ts", - "plugin.js", - ] - `) - }) - - it('should copy non-code files in the runtime directory', async () => { - expect(await readdir(join(runtimeDir, 'assets'))).toMatchInlineSnapshot(` - [ - "config.json", - ] - `) - expect(await readFile(join(runtimeDir, 'components/TestMe.css'), 'utf-8')).toBe('.test-me{color:#639}') - }) - - it('should give every relative specifier in runtime declarations an extension that resolves', async () => { - expect(await unresolvedSpecifiers(runtimeDir)).toEqual([]) - }) - - it('should write types to output directory', async () => { - const types = await readFile(join(distDir, 'types.d.mts'), 'utf-8') - expect(types).toMatchInlineSnapshot(` - "import type { ModuleHooks, ModuleRuntimeHooks, ModuleRuntimeConfig, ModulePublicRuntimeConfig } from './module.mjs' - - declare module '#app' { - interface RuntimeNuxtHooks extends ModuleRuntimeHooks {} - } - - declare module '@nuxt/schema' { - interface NuxtHooks extends ModuleHooks {} - interface RuntimeConfig extends ModuleRuntimeConfig {} - interface PublicRuntimeConfig extends ModulePublicRuntimeConfig {} - } - - export { type ModuleHooks, type ModuleOptions, type ModulePublicRuntimeConfig, type ModuleRuntimeConfig, type ModuleRuntimeHooks, default } from './module.mjs' - " - `) - }) - - it('should generate module metadata as separate JSON file', async () => { - const meta = await readFile(join(distDir, 'module.json'), 'utf-8') - const tsdownPkg = await readPackageJSON('tsdown') - expect(JSON.parse(meta)).toMatchObject( - { - builder: { - '@nuxt/module-builder': version, - 'tsdown': tsdownPkg.version, - }, - configKey: 'myModule', - name: 'my-module', - version: '1.0.0', - }, - ) - }) - - it('should generate typed plugin', async () => { - const pluginDts = await readFile(join(distDir, 'runtime/plugins/plugin.d.ts'), 'utf-8') - const appAlias = `import\\("nuxt/app"\\)` - expect(pluginDts).toMatch(/^export type SharedTypeFromRuntime = 'shared-type';$/m) - expect(pluginDts).toMatch( - new RegExp( - `declare const _default: ${appAlias}\\.Plugin<\\{\\s*injection: "injected";\\s*\\}> & ${appAlias}\\.ObjectPlugin<\\{\\s*injection: "injected";\\s*\\}>;`, - ), - ) - expect(pluginDts).toMatch(/^export default _default;$/m) - }) - - it('should not leak build-only virtual aliases into emitted runtime declarations', async () => { - const files = await listFiles(runtimeDir) - const declarations = files.filter(file => /\.d\.[^/]*ts$/.test(file)) - expect(declarations.length).toBeGreaterThan(0) - for (const file of declarations) { - const contents = await readFile(join(runtimeDir, file), 'utf-8') - expect(contents, file).not.toMatch(/(["'])#app(?:\/[^"']*)?\1/) - expect(contents, file).not.toMatch(/import\("#app(?:\/[^"]*)?"\)/) - } - }) - - it('should resolve every shape of `#app` alias in runtime declarations', async () => { - const declaration = await readFile(join(runtimeDir, 'composables/useAliasedApp.d.ts'), 'utf-8') - expect(declaration).toMatch(/declare const useAppInstance: \(\) => import\("nuxt\/app"\)\.NuxtApp;/) - expect(declaration).toMatch(/declare const useAppRouter: \(\) => import\("vue-router"\)\./) - expect(declaration).toMatch(/declare const useAppCookie: \(name: string\) => import\("nuxt\/app"\)\.CookieRef import\("nuxt\/app"\)\.NuxtApp;/) - }) - - it('should correctly add extensions to imports from runtime/ directory', async () => { - const moduleDts = await readFile(join(distDir, 'module.d.mts'), 'utf-8') - const runtimeImport = findStaticImports(moduleDts).find(i => i.specifier.includes('runtime')) - expect(runtimeImport!.code.trim()).toMatchInlineSnapshot(`"import { SharedTypeFromRuntime } from "./runtime/plugins/plugin.js";"`) - }) - - it('should generate components correctly', async () => { - const componentFile = await readFile(join(distDir, 'runtime/components/TestMe.vue'), 'utf-8') - await expect(componentFile.replace(/\r\n/g, '\n')).toMatchFileSnapshot('__snapshots__/TestMe.vue') - - const componentDeclarationFile = await readFile(join(distDir, 'runtime/components/TestMe.vue.d.ts'), 'utf-8') - await expect(componentDeclarationFile.replace(/\r\n/g, '\n')).toMatchFileSnapshot('__snapshots__/TestMe.vue.d.ts') - }) - - it('should generate components with \n\n\n`, + 'src/runtime/components/ThingState.vue': `\n\n\n`, + 'test/fixture/nuxt.config.ts': `export default defineNuxtConfig({})\n`, + 'src/runtime/fields.ts': FIELDS, + 'src/runtime/server/fields.ts': FIELDS, + 'tsconfig.server.json': JSON.stringify({ extends: './.nuxt/tsconfig.server.json', compilerOptions: { useDefineForClassFields: false } }), + [`${store('fake-logger')}/package.json`]: JSON.stringify({ name: 'fake-logger', type: 'module', exports: { '.': { types: './index.d.ts', default: './index.js' } } }), + [`${store('fake-logger')}/index.d.ts`]: `export interface LoggerInstance { log: (message: string) => void }\nexport declare function createLogger(): LoggerInstance\n`, + [`${store('fake-logger')}/index.js`]: `export const createLogger = () => ({ log: console.log })\n`, + [`${store('fake-shared')}/package.json`]: JSON.stringify({ name: 'fake-shared', type: 'module', exports: { '.': { types: './index.d.ts', default: './index.js' } } }), + [`${store('fake-shared')}/index.d.ts`]: `import { createLogger } from 'fake-logger'\nexport declare function createModuleLogger(name: string): ReturnType\n`, + [`${store('fake-shared')}/index.js`]: `import { createLogger } from 'fake-logger'\nexport const createModuleLogger = () => createLogger()\n`, + 'src/runtime/logger.ts': `import { createModuleLogger } from 'fake-shared'\n\nexport const logger = createModuleLogger('my-module')\n`, + 'src/runtime/server/log.ts': `import { createLogger } from 'fake-logger'\n\nexport const serverLogger = createLogger()\n`, + 'tsconfig.json': JSON.stringify({ ...JSON.parse(REFERENCES('./.nuxt/tsconfig.node.json', './tsconfig.server.json')), compilerOptions: { types: ['vitest/importMeta'] } }), + }, + links: { + 'node_modules/.pnpm/fake-shared@1.0.0/node_modules/fake-logger': store('fake-logger'), + 'node_modules/fake-logger': store('fake-logger'), + 'node_modules/fake-shared': store('fake-shared'), + }, + }) + + const moduleProject = { + 'tsconfig.module.json': JSON.stringify({ extends: './.nuxt/tsconfig.node.json', compilerOptions: { erasableSyntaxOnly: true, useDefineForClassFields: false } }), + 'tsconfig.override.json': JSON.stringify({ extends: './.nuxt/tsconfig.node.json', compilerOptions: { useDefineForClassFields: true } }), + 'tsconfig.json': REFERENCES('./tsconfig.module.json'), + } + dirs.moduleProject = await fixture('.temp-builder/module-project', { config: PLUGIN, module: source => source + FIELDS, files: moduleProject }) + dirs.tsconfigOption = await fixture('.temp-builder/tsconfig-option', { config: `export default { tsconfig: 'tsconfig.override.json', plugins: [builder()] }\n`, module: source => source + FIELDS, files: moduleProject }) + dirs.singleTsconfig = await fixture('.temp-builder/single-tsconfig', { + config: PLUGIN, + module: source => source + FIELDS, + files: { 'tsconfig.json': JSON.stringify({ extends: './.nuxt/tsconfig.json', exclude: ['dist', 'node_modules', 'playground'] }) }, + }) + + await Promise.all([ + step('compose', tsdown(dirs.compose)), + step('packageImports', tsdown(dirs.packageImports)), + ...['source', 'files'].flatMap(name => [ + step(`unpublishable-${name}:tsdown`, tsdown(dirs[`unpublishable-${name}`]!)), + step(`unpublishable-${name}:cli`, cli(['build', dirs[`unpublishable-${name}`]!])), + ]), + ...Object.keys(variants).map(name => step(name, tsdown(dirs[name]!))), + step('contexts', tsdown(dirs.contexts)).then(() => step('contexts:typecheck', run(bin('vue-tsc'), ['-b', '--noEmit'], { cwd: dirs.contexts }))), + step('moduleProject', tsdown(dirs.moduleProject, [], { CI: '' })), + step('tsconfigOption', tsdown(dirs.tsconfigOption)), + step('singleTsconfig', tsdown(dirs.singleTsconfig)), + step('published', run('node', [tsdownBin], { cwd: repoRoot })).then(() => step('published:import', run('node', ['--input-type=module', '-e', `const root = await import('@nuxt/module-builder')\nconst { builder } = await import('@nuxt/module-builder/tsdown')\nconsole.log(JSON.stringify(['builder' in root, builder().name]))`]))), + ]) +}, 300_000) + +describe('builder', () => { + it('should run the config\'s hooks before its own, so `build:prepare` can generate sources, and compose with its plugins and options', async () => { + const dir = dirs.compose! + expect(expectBuilt('compose')).not.toContain('Error') + expect((await read(dir, 'hooks.log')).trim().split('\n')).toEqual(['build:prepare', 'inputOptions', 'build:done true true']) + expect(exists(dir, 'dist/stale.txt')).toBe(false) + const module = await read(dir, 'dist/module.mjs') + expect(module).toContain('from build:prepare') + expect(module).toContain('replaced by a user plugin') + expect(module).toContain('from "fake-ext"') + expect(module).not.toContain('bundled-fake-ext') + expect(module).toContain('from "./runtime/utils/answer.js"') + expect(JSON.parse(await read(dir, 'dist/module.json'))).toMatchObject({ name: 'my-module', configKey: 'myModule' }) + }) + + it('should write files a plugin emits before checking the paths of `package.json`', async () => { + expect(await read(dirs.compose!, 'dist/config.cjs')).toBe('module.exports = {}\n') + const warning = expectBuilt('compose').split('\n').find(line => line.includes('do not exist after the build')) + expect(warning).toContain('./dist/missing.mjs') + expect(warning).not.toContain('config.cjs') + }) + + it('should refuse package `imports` that the output imports and that would not work once installed', async () => { + expect(expectFailed('packageImports')).toContain(`The build output imports these \`imports\` of \`package.json\`, which would not work once installed. Pointing at TypeScript sources, which Node does not load from \`node_modules\`: \`#ext/*\` (\`./src/ext/*.ts\`).`) + expect(await read(dirs.packageImports!, 'dist/module.mjs')).toContain('"#ext/value"') + const module = await read(dirs.compose!, 'dist/module.mjs') + expect(module).toContain('"#ext/value"') + expect(module).toContain('through imports') + expect(module).not.toContain('#internal/value') + }) + + it('should refuse to build when a published path points at a TypeScript source or at a file the pack leaves out', () => { + const messages = { + source: 'Pointing at TypeScript sources, which Node does not load from `node_modules`: `exports` (`./src/module.ts`).', + files: 'Pointing at paths that the pack leaves out: `exports` (`./lib/module.mjs`).', + } + for (const [name, message] of Object.entries(messages)) { + for (const command of ['tsdown', 'cli']) { + expect(expectFailed(`unpublishable-${name}:${command}`), command).toContain(message) + } + expect(exists(dirs[`unpublishable-${name}`]!, 'dist')).toBe(false) + } + }) + + it('should be published at `@nuxt/module-builder/tsdown`, not at the package root', () => { + expectBuilt('published') + expect(JSON.parse(expectBuilt('published:import'))).toEqual([false, 'nuxt-module-builder']) + }) + + it('should reject one plugin instance shared by two configs', () => { + expect(expectFailed('shared')).toContain('The same `builder()` plugin is used in more than one tsdown config.') + }) + + it.each(['format', 'entry', 'platform'])('should fail when another plugin changes `%s`, which it sets', (option) => { + expect(expectFailed(option)).toMatch(new RegExp(`Another tsdown plugin changed \`${option}\`.*, which \`builder\\(\\)\` sets\\. ${guide('options-builder-sets')}`)) + expect(exists(dirs[option]!, 'dist')).toBe(false) + }) + + it('should fail when `outputOptions` changes the file names of the bundled entries, and remove the partial output', () => { + expect(expectFailed('entryFileNames')).toMatch(/The build did not emit `(module|utils)\.mjs`, `(module|utils)\.mjs`\./) + expect(exists(dirs.entryFileNames!, 'dist')).toBe(false) + }) + + it('should break the size report down by entry and runtime directory only when it is a summary', () => { + expect(sizeRows(expectBuilt('compose'))).toEqual(['dist/module.mjs', 'dist/runtime/']) + expect(sizeRows(expectBuilt('summary'))).toEqual([]) + }) +}) + +describe('with a root tsconfig that only lists references', () => { + it('should type runtime components with their own context and pass the type check', async () => { + const dir = dirs.contexts! + expect(expectBuilt('contexts')).not.toContain('type error') + expect(await read(dir, 'dist/runtime/components/ThingState.d.vue.ts')).toMatch(/loggedIn: boolean;\s+user: \{\s+name: string;\s+\} \| null;/) + expect(await read(dir, 'dist/runtime/components/Triggered.vue')).toMatch(/type: \[\s*String,\s*Array,\s*Boolean\s*\]/) + const generated = async (name: string) => JSON.parse(await read(dir, `.nuxt/tsconfig.${name}.json`)) + for (const name of ['app', 'node', 'server', 'shared']) { + const config = await generated(name) + expect(config.files, name).toEqual(expect.arrayContaining([join(dir, 'src/env.d.ts'), join(dir, 'ambient.d.ts'), join(dir, 'types/virtual.d.ts')])) + expect(config.files, name).not.toContain(join(dir, 'src/augments.d.ts')) + expect(config.compilerOptions.types, name).toContain('vitest/importMeta') + } + for (const name of ['nuxt', 'nuxt.node']) { + expect(await read(dir, `.nuxt/${name}.d.ts`), name).toContain('/// ') + } + expect(await read(dir, '.nuxt/nuxt.shared.d.ts')).not.toContain('augments.d.ts') + expect(await read(dir, '.nuxt/nuxt.node.d.ts')).toContain('/// ') + const buildTypes = (await read(dir, '.nuxt/types/build.d.ts')).split('\n') + expect(buildTypes).toContain('declare module "#build/my-module-virtual";') + expect(buildTypes).not.toContain('declare module "#build/my-module-virtual.mjs";') + expect((await generated('app')).include).not.toContain('../**/*') + expect(expectBuilt('contexts:typecheck')).toBe('') + }) + + it('should transform each runtime file with the referenced project that includes it', async () => { + expect(await read(dirs.contexts!, 'dist/runtime/fields.js')).toContain('\tvalue;') + expect(await read(dirs.contexts!, 'dist/runtime/server/fields.js')).not.toContain('value;') + }) + + it('should name a dependency in runtime declarations by its package when only another part of the module imports it', async () => { + expect(await read(dirs.contexts!, 'dist/runtime/logger.d.ts')).toContain('import("fake-logger").LoggerInstance') + }) + + it('should give tsdown the project that includes the module entry, unless the config sets `tsconfig`', async () => { + const ownsField = async (dir: string) => (await read(dir, 'dist/module.mjs')).includes('\tvalue;') + const output = expectBuilt('moduleProject') + expect(output).toContain('tsconfig: tsconfig.module.json') + expect(output).toMatch(/Set `?isolatedDeclarations: true`? in `?tsconfig\.module\.json`?/) + expect(await ownsField(dirs.moduleProject!)).toBe(false) + expect(expectBuilt('tsconfigOption')).toContain('tsconfig: tsconfig.override.json') + expect(await ownsField(dirs.tsconfigOption!)).toBe(true) + expect(expectBuilt('singleTsconfig')).toContain('tsconfig: tsconfig.json') + expect(await read(dirs.singleTsconfig!, 'dist/module.d.mts')).toBe(await read(dirs.moduleProject!, 'dist/module.d.mts')) + }) +}) diff --git a/test/cli.spec.ts b/test/cli.spec.ts new file mode 100644 index 00000000..57cf0f89 --- /dev/null +++ b/test/cli.spec.ts @@ -0,0 +1,1534 @@ +import { mkdir, readFile, rename, symlink, writeFile } from 'node:fs/promises' +import { pathToFileURL } from 'node:url' +import { findStaticImports } from 'mlly' +import { version as nuxtVersion } from 'nuxt/package.json' +import { join, relative, resolve } from 'pathe' +import { readPackageJSON } from 'pkg-types' +import type { PackageJson } from 'pkg-types' +import { satisfies } from 'verkit' +import { beforeAll, describe, expect, it } from 'vitest' + +import { version } from '../package.json' +import { guide } from '../src/build/guide.ts' +import { npmPackFromPnpmScript, packProbeArgs, packProbeContext } from './pack-env.ts' +import type { Result } from './utils.ts' +import { bin, builderImport, cli, cliBin, exampleDir, exists, fixture, listFiles, read, repoRoot, run, succeed, tsdownBin, unresolvedSpecifiers } from './utils.ts' + +const LEGACY_TSCONFIG = { extends: './.nuxt/tsconfig.json', exclude: ['dist', 'node_modules', 'playground', '**/tsdown.config.ts'] } +const ISOLATED = { + 'tsconfig.json': JSON.stringify({ ...LEGACY_TSCONFIG, compilerOptions: { isolatedDeclarations: true } }), + 'src/utils.ts': 'export const myModuleUtils = (): void => {}\n', +} +const REFERENCES = (node: string) => JSON.stringify({ + files: [], + exclude: ['dist', 'node_modules', 'playground'], + references: [node, './.nuxt/tsconfig.app.json', './.nuxt/tsconfig.server.json', './.nuxt/tsconfig.shared.json'].map(path => ({ path })), +}) + +const annotate = (source: string) => [ + `import type { NuxtModule } from '@nuxt/schema'`, + source.replace(/export default defineNuxtModule()?\(\{/, (_, options = '') => `const module: NuxtModule${options} = defineNuxtModule${options}({`), + 'export default module', +].join('\n') + +const minimalModule = (name: string) => `import { defineNuxtModule } from '@nuxt/kit'\n\nexport default defineNuxtModule({\n meta: { name: '${name}', configKey: '${name}' },\n setup() {},\n})\n` + +const store = (name: string) => `node_modules/.pnpm/${name}@1.0.0/node_modules/${name}` + +const fakeCache = { + 'node_modules/fake-cache/package.json': JSON.stringify({ name: 'fake-cache', type: 'module', exports: { '.': { types: './index.d.ts', default: './index.js' } } }), + 'node_modules/fake-cache/index.js': `export const defineCached = handler => handler\n`, + 'node_modules/fake-cache/index.d.ts': `import type { Handler } from 'fake-h3'\nexport declare const defineCached: (handler: () => string) => Handler\n`, + 'node_modules/fake-cache/node_modules/fake-h3/package.json': JSON.stringify({ name: 'fake-h3', type: 'module', exports: { '.': { types: './index.d.ts' } } }), + 'node_modules/fake-cache/node_modules/fake-h3/index.d.ts': `export interface Handler { (): string, __h3: 2 }\n`, +} + +const VALUE_EXPORTS = `export function defineMyModuleConfig(): void {} +export const myModuleVersion = '1.0.0' +export const Mode = { Light: 0, Dark: 1 } as const +export type Mode = typeof Mode[keyof typeof Mode] +` + +const consumer = { + 'playground/consumer.ts': `import { Mode, defineMyModuleConfig, myModuleVersion } from 'my-module' +import type { ModuleOptions } from 'my-module' + +defineMyModuleConfig() +const options: ModuleOptions = { apiKey: myModuleVersion } +const light: number = Mode.Light +const dark: Mode = Mode.Dark +void [light, dark, options] +`, + 'playground/consumer.tsconfig.json': JSON.stringify({ + compilerOptions: { moduleResolution: 'bundler', module: 'ESNext', target: 'ESNext', lib: ['ESNext'], strict: true, noEmit: true, skipLibCheck: true }, + include: ['consumer.ts'], + }), +} + +const runtimeSpecifiers = (code: string) => findStaticImports(code).map(i => i.specifier).filter(s => s.includes('runtime')).sort() + +const dirs: Record = {} +let sourceWithoutDist = false +const results: Record = {} +const result = (name: string) => { + const found = results[name] + if (!found) { + throw new Error(`\`${name}\` did not run, as a step before it failed`) + } + return found +} +const output = (name: string) => result(name).output +const step = async (name: string, result: Promise) => { + const settled = await result + results[name] = settled + return settled +} +const inOrder = async (...steps: Array<[name: string, run: () => Promise]>) => { + for (const [name, run] of steps) { + if ((await step(name, run())).exitCode !== 0) { + return false + } + } + return true +} + +beforeAll(async () => { + const examplePkg = JSON.parse(await readFile(join(exampleDir, 'package.json'), 'utf-8')) + const base = await fixture('.temp-cli/base', { files: { 'tsconfig.json': JSON.stringify(LEGACY_TSCONFIG) } }) + await succeed(cli(['prepare', base])) + const from = base + + dirs.runtime = await fixture('.temp-cli/runtime with spaces ΓΌ', { + from, + module: source => [ + `import type { DeepPartial } from 'fake-types'`, + `import type FakeCjs from 'fake-cjs-types'`, + `import { defineThing } from 'fake-kit'`, + source, + `import { name } from './runtime/utils/name.ts'`, + `import { aliased } from '#runtime/utils/aliased'`, + `import { useShape } from './runtime/composables/useShape.ts'`, + `import type TestMe from './runtime/components/TestMe.vue'`, + `import type JsxComponent from './runtime/components/JsxComponent.tsx'`, + `export const runtimeRefs = [name, aliased, useShape]`, + `export type TestMeType = typeof TestMe`, + `export type JsxComponentType = typeof JsxComponent`, + `export type { NuxtApp } from '#app'`, + `export interface ExtraOptions { deep?: DeepPartial<{ a: string }>, cjs?: FakeCjs.Options }`, + `export const thing = defineThing({ name: 'portable' })`, + '', + ].join('\n'), + pkg: pkg => ({ ...pkg, imports: { '#runtime/*': './src/runtime/*.ts' } }), + files: { + 'src/runtime/composables/useShape.ts': `import { shape } from '../utils/shape.ts'\n\nexport const useShape = (): string => shape\n`, + 'src/runtime/utils/name.ts': `export const name: string = 'name'\n`, + 'src/runtime/utils/aliased.ts': `export const aliased: string = 'aliased'\n`, + 'src/runtime/utils/shape.ts': `export const shape: string = 'shape'\n`, + 'src/runtime/components/JsxCard.vue': `\n\n\n`, + 'src/runtime/components/JsxSlot.tsx': `import { defineComponent } from 'vue'\nimport { useNuxtApp } from '#app'\nimport JsxComponent from './JsxComponent'\n\nexport const useSlotApp = () => useNuxtApp()\n\nexport default defineComponent((_, { slots }) => () =>
{slots.default?.()}
)\n`, + 'src/runtime/server/render.tsx': `import { useSlotApp } from '../components/JsxSlot'\nimport { strong } from '../utils/strong'\n\nexport type SlotApp = ReturnType\n\nexport const render = (label: string) =>

{strong(label)}

\n`, + 'src/runtime/server/render.stories.ts': `import JsxSlot from '../components/JsxSlot'\n\nexport const tested = JsxSlot\n`, + 'src/runtime/utils/strong.tsx': `import { bold } from './bold'\n\nexport const strong = (label: string) => {bold(label)}\n`, + 'src/runtime/utils/bold.tsx': `export const bold = (label: string) => {label}\n`, + 'src/runtime/utils/label.tsx': `export const label = label\n`, + 'node_modules/fake-cjs-types/package.json': JSON.stringify({ name: 'fake-cjs-types', types: './index.d.ts' }), + 'node_modules/fake-cjs-types/index.d.ts': `declare namespace FakeCjs { interface Options { level: number } }\nexport = FakeCjs\n`, + 'node_modules/fake-dep/package.json': JSON.stringify({ name: 'fake-dep', type: 'module', exports: { '.': { types: './index.d.ts', default: './index.js' } } }), + 'node_modules/fake-dep/index.js': `export const helper = () => 'bundled-fake-dep'\n`, + 'node_modules/fake-dep/index.d.ts': `export declare const helper: () => string\n`, + 'node_modules/fake-types/package.json': JSON.stringify({ name: 'fake-types', types: './index.d.ts' }), + 'node_modules/fake-types/index.d.ts': `export type DeepPartial = { [K in keyof T]?: DeepPartial }\n`, + [`${store('fake-schema')}/package.json`]: JSON.stringify({ name: 'fake-schema', types: './index.d.ts' }), + [`${store('fake-schema')}/index.d.ts`]: `export interface Thing { options: T }\n`, + [`${store('fake-kit')}/package.json`]: JSON.stringify({ name: 'fake-kit', type: 'module', exports: { '.': { types: './index.d.ts', default: './index.js' } } }), + [`${store('fake-kit')}/index.d.ts`]: `import type { Thing } from 'fake-schema'\nexport declare function defineThing(options: T): Thing\n`, + [`${store('fake-kit')}/index.js`]: `export const defineThing = options => ({ options })\n`, + '.nuxt/nuxt.d.ts': source => `/// \n${source}`, + 'src/runtime/server/routes/[...slug].ts': `export default (slug: string) => slug\n`, + 'src/runtime/utils/self.ts': `import type { ModuleOptions } from 'my-module'\n\nexport const getApiKey = (options: ModuleOptions) => options.apiKey\n`, + 'src/runtime/cache/lru.ts': `export const lru: string = 'lru'\n`, + 'src/runtime/server/handler.ts': `// @ts-ignore build-time virtual +import options from '#internal/nuxt.config.mjs' +// @ts-ignore app alias +import app from '~/app.config' +// @ts-ignore app alias +import root from '@/root' +import { useNuxtApp } from '#app' +import { helper } from 'fake-dep' +import { lru } from '#fixture-cache' +import { local } from '../utils/local' + +export default (): unknown[] => [options, app, root, useNuxtApp, helper(), lru, local] +`, + 'src/runtime/utils/local.ts': `export const local: string = 'local'\n`, + 'src/runtime/utils/options.ts': `import type { DeepPartial } from 'fake-types'\nimport { helper } from 'fake-dep'\n\nexport type Options = DeepPartial<{ a: { b: string } }>\nexport const defineOptions = (options: Options) => ({ options, helper })\n`, + 'src/runtime/utils/typo.ts': `export const count: number = 'one'\nexport const double = (value: number): number => value * 2\n`, + 'src/runtime/components/Typo.vue': `\n\n\n`, + 'src/runtime/components/Sized.vue': `\n\n\n\n\n`, + 'src/runtime/composables/useSize.ts': `import { computed } from 'vue'\nimport type { Props } from '../components/Sized.vue'\n\nexport function useSize(props: Props) {\n return computed(() => props.size)\n}\n`, + }, + paths: { '#fixture-cache': ['../src/runtime/cache/lru'], 'fake-schema': [`../${store('fake-schema')}`] }, + links: { + 'node_modules/.pnpm/fake-kit@1.0.0/node_modules/fake-schema': store('fake-schema'), + 'node_modules/fake-schema': store('fake-schema'), + 'node_modules/fake-kit': store('fake-kit'), + }, + }) + + dirs.isolated = await fixture('.temp-cli/isolated', { + from, + module: source => annotate(`${source}\n${VALUE_EXPORTS}`), + remove: ['.nuxt'], + files: { + ...ISOLATED, + ...consumer, + 'src/runtime/styles/card.css': `@import "./base.css";\n\n.card {\n user-select: none;\n & .title { font-weight: bold; }\n &:hover { color: rebeccapurple; }\n}\n`, + 'src/runtime/styles/base.css': `.base { margin: 0px 0px; }\n`, + 'src/runtime/styles/_variables.scss': `$primary: #00dc82;\n`, + 'src/runtime/styles/theme.scss': `@use "variables" as v;\n.theme { color: v.$primary; .nested { padding: 1px; } }\n`, + 'src/runtime/styles/indented.sass': `.indented\n color: blue\n`, + 'src/runtime/styles/legacy.less': `@c: red;\n.less { color: @c; }\n`, + 'src/runtime/types/ambient.d.ts': `declare global { interface Window { __fixture: true } }\nexport {}\n`, + 'src/runtime/types/app.d.ts': `import type { NuxtApp } from '#app'\nexport type App = NuxtApp\n`, + 'src/runtime/plugins/styled.ts': `import '../styles/card.css'\nimport '../styles/theme.scss'\n\nexport const styled = true\n`, + }, + }) + + dirs.types = await fixture('.temp-cli/types', { + from, + module: source => `${source.replace('export interface ModuleOptions', 'interface ModuleOptions')}\n${VALUE_EXPORTS}`, + files: consumer, + }) + + dirs.minimal = await fixture('.temp-cli/minimal', { + from, + config: `export default {\n plugins: [builder({ entries: ['./src/utils', { input: 'src/components/', outDir: 'dist/components' }] })],\n}\n`, + module: annotate(minimalModule('minimal')), + remove: ['src/runtime'], + files: { + ...ISOLATED, + ...Object.fromEntries(await Promise.all(['TestMe.vue', 'TestMe.css', 'TestMeSetup.vue'].map(async file => [`src/components/${file}`, await read(exampleDir, 'src/runtime/components', file)]))), + }, + }) + + dirs.shape = await fixture('.temp-cli/shape', { + from, + config: `export default {\n plugins: [builder({ entries: ['./src/utils', './src/utils/merge.ts', './src/data.json'] })],\n}\n`, + files: { + '.nuxt/app.config.ts': `export default { theme: { buildMachineOnly: 'must-not-be-published' as const } }\n`, + 'external.ts': `export const answer = 42\n`, + ...Object.fromEntries(['fake-polyfill', 'fake-register'].flatMap(name => [ + [`node_modules/${name}/package.json`, JSON.stringify({ name, type: 'module', exports: { '.': { types: './index.d.ts', default: './index.js' } } })], + [`node_modules/${name}/index.js`, `globalThis.__order = [...globalThis.__order ?? [], '${name}']\n`], + [`node_modules/${name}/index.d.ts`, `export {}\n`], + ])), + 'src/data.json': `{ "answer": 42 }\n`, + 'src/utils/merge.ts': `export const merge = (a: T, b: T): T => ({ ...a, ...b })\n`, + 'src/shared/constants.ts': `import { LIMIT } from './limits'\n\nexport const CONSTANT = LIMIT\n`, + 'src/shared/limits.ts': `export const LIMIT = 10\n`, + 'src/types.ts': `export interface RootType { root: string }\n`, + 'src/types/middlewares.ts': `export type RequestSizeLimiter = { maxRequestSizeInBytes: number }\n`, + 'src/runtime/server/limiter.ts': `import { type RequestSizeLimiter } from '../../types/middlewares'\nimport {} from 'nuxt/app'\nimport '../disabled/side'\n\nexport const limit = (options: RequestSizeLimiter) => options.maxRequestSizeInBytes\n`, + 'src/routing.ts': `import { readFileSync } from 'node:fs'\nimport { generate } from './kit/gen'\nimport type { RootType } from './types'\n\nexport interface RouteInfo { path: string, root: RootType }\nexport const localizeRoutes = (file: string): string => generate(readFileSync(file, 'utf8'))\n`, + 'src/kit/gen.ts': `import { createHash } from 'node:crypto'\n\nexport const generate = (input: string) => createHash('sha1').update(input).digest('hex')\n`, + 'src/runtime/composables/useLocaleRoute.ts': `import { RouteInfo } from '../../routing'\n\nexport const useLocaleRoute = (route: RouteInfo) => route\n`, + 'src/runtime/types.ts': `export interface RuntimeType { runtime: string }\n`, + 'src/runtime/server/uses.ts': [ + `import { merge } from '../../utils/merge'`, + `import { CONSTANT } from '../../shared/constants'`, + `import type { RootType } from '../../types'`, + `import type { RuntimeType } from '../types'`, + ``, + `export const combine = (a: RootType & RuntimeType, b: RootType & RuntimeType) => [merge(a, b), CONSTANT] as const`, + ``, + ].join('\n'), + 'src/runtime/escaping.ts': `export const load = () => import('../../external')\n`, + 'src/runtime/composables/mock.ts': `export const defineThing = () => 'mock'\n`, + 'src/runtime/disabled/composables/defineThing.ts': `export { defineThing } from '../../composables/mock'\n`, + 'src/runtime/disabled/index.ts': `import './side'\nexport { defineThing } from './composables/defineThing'\n`, + 'src/runtime/disabled/side.ts': `globalThis.__side = true\n`, + 'src/runtime/order/interleaved.ts': [ + `import 'fake-register'`, + `import { level } from './levels'`, + `export * from './reexported'`, + `import './order.css'`, + `export { useState } from '#imports'`, + `import 'fake-polyfill'`, + `import './effect'`, + `import { ref } from 'vue'`, + ``, + `export const value = ref(level)`, + ``, + ].join('\n'), + 'src/runtime/order/levels.ts': `export const level = 1\n`, + 'src/runtime/order/reexported.ts': `export const reexported = 1\n`, + 'src/runtime/order/effect.ts': `globalThis.__effect = true\n`, + 'src/runtime/order/order.css': `.order { color: red }\n`, + 'src/runtime/content/index.ts': `export * from '../components/TestMe.vue'\nexport * from '../components/TestMeSetup.vue'\nexport * from './prose'\n`, + 'src/runtime/content/prose.ts': `export * from './levels'\nexport interface ProseThing { title: string }\n`, + 'src/runtime/content/levels.ts': `export const proseLevel = 1\n`, + 'src/runtime/utils/provider.ts': `import type { ModuleOptions } from '../../module'\n\nexport const defineProvider = (options: ModuleOptions) => options\n`, + 'src/runtime/utils/props.ts': `export interface BaseProps { size?: number }\n`, + 'src/runtime/composables/useThemeConfig.ts': `import appConfig from '#build/app.config'\n\nexport const useThemeConfig = () => appConfig.theme\n`, + 'src/runtime/composables/useButton.ts': `import theme, { variants } from '#build/ui/button'\nimport * as config from '#build/app.config'\n\nexport const useButton = () => ({ slots: theme.slots, size: variants.size, ui: config.default.ui })\n`, + 'src/runtime/components/Button.vue': `\n\n\n`, + 'src/runtime/components/Sized.vue': `\n\n\n`, + }, + }) + + dirs.loader = await fixture('.temp-cli/loader', { + from, + module: `import { deps } from './deps.ts'\nimport { deep } from './deep/a.ts'\n${minimalModule('my-module')}\nexport const loaded = [deps, deep]\nexport { nativeValue } from './native-helper.ts'\nexport { internal } from '#internal/value'\n`, + remove: ['.nuxt'], + pkg: pkg => ({ ...pkg, imports: { '#internal/*': './src/internal/*.ts' } }), + files: { + 'tsconfig.json': JSON.stringify({ compilerOptions: { paths: { '*': ['./src/*'] } } }), + 'src/@nuxt/kit.ts': 'export const defineNuxtModule = (_: unknown) => ({ SHADOWED: true })\n', + 'src/native-helper.ts': `import { inner } from './nested/inner.ts'\n\nexport const nativeValue: string = inner\n`, + 'src/nested/inner.ts': `export const inner: string = 'loaded helper'\n`, + 'src/internal/value.ts': `export const internal: string = 'through imports'\n`, + 'node_modules/fake-cjs-marker/package.json': JSON.stringify({ name: 'fake-cjs-marker', version: '1.0.0', main: 'index.js' }), + 'node_modules/fake-cjs-marker/index.js': `const marker = 'mentions import.meta in a string'\nmodule.exports = { value: marker.length }\n`, + 'node_modules/fake-esm-split/package.json': JSON.stringify({ name: 'fake-esm-split', version: '1.0.0', type: 'module', exports: { '.': { import: './index.js', require: './index.cjs' } } }), + 'node_modules/fake-esm-split/index.js': `export { value } from './inner.js'\nexport { other } from './other.js'\n`, + 'node_modules/fake-esm-split/inner.js': `import cjs from 'fake-cjs-marker'\nexport const value = cjs.value\n`, + 'node_modules/fake-esm-split/other.js': `import cjs from 'fake-cjs-marker'\nexport const other = cjs.value + 1\n`, + 'node_modules/fake-esm-split/index.cjs': `module.exports = { value: 0, other: 1 }\n`, + 'src/deps.ts': `// @ts-ignore untyped\nimport cjs from 'fake-cjs-marker'\n// @ts-ignore untyped\nimport { value, other } from 'fake-esm-split'\n\nexport const deps: unknown[] = [cjs, value, other]\n`, + 'src/deep/a.ts': `export { deep } from './b.ts'\n`, + 'src/deep/b.ts': `import pkg from '../../package.json' with { type: 'json' }\n\nexport const deep: string = pkg.name\n`, + 'probe.ts': `import type Module from './.nuxt/module-builder/types.mjs'\n\nexport const meta: Promise<{ configKey?: string }> = ({} as typeof Module).getMeta!()\n`, + }, + }) + + dirs.unloadable = await fixture('.temp-cli/unloadable', { + from, + module: source => `import { name as packageName } from '../package.json' +import { Level } from './levels.ts' + +enum Mode { Stub = 'stub' } +class Holder { constructor(public value: string) {} } +${source.replace(`name: 'my-module'`, 'name: new Holder(`${packageName}-${Mode.Stub}-${Level.High}`).value')} +export { myModuleUtils } from './utils.js' +export { helper } from './helpers' +export { kit } from './kit' +export type { Kit } from './kit' +`, + files: { + 'src/levels.ts': `export enum Level { High = 'high' }\n`, + 'src/helpers.ts': `export const helper = (): string => 'helper'\n`, + 'src/kit/index.ts': `export const kit = (): string => 'kit'\nexport type Kit = ReturnType\n`, + }, + }) + + dirs.isolatedError = await fixture('.temp-cli/isolated-error', { from, files: { 'tsconfig.json': ISOLATED['tsconfig.json'] } }) + + dirs.typeError = await fixture('.temp-cli/type-error', { + from, + remove: ['src/runtime/components'], + files: { + ...fakeCache, + 'src/runtime/utils.ts': `export const Anonymous = class { private secret = 1 }\n`, + 'src/runtime/server/cached.ts': `import { defineCached } from 'fake-cache'\n\nexport const defineCachedHandler = defineCached(() => 'cached')\n`, + }, + }) + + dirs.vueError = await fixture('.temp-cli/vue-error', { + from, + module: minimalModule('vue-error'), + remove: ['src/runtime'], + files: { + ...fakeCache, + 'src/runtime/components/Cached.vue': `\n\n\n`, + 'src/runtime/server/cached.ts': `import { defineCached } from 'fake-cache'\n\nexport const defineCachedHandler = defineCached(() => 'cached')\n`, + }, + }) + + dirs.solution = await fixture('.temp-cli/solution', { + from, + files: { + 'tsconfig.json': JSON.stringify({ files: [], references: [{ path: './tsconfig.app.json' }, { path: './tsconfig.server.json' }] }), + 'tsconfig.app.json': JSON.stringify({ extends: './.nuxt/tsconfig.json', include: ['.nuxt/nuxt.d.ts', 'src/**/*'], exclude: ['src/runtime/server/**'] }), + 'tsconfig.server.json': JSON.stringify({ extends: './.nuxt/tsconfig.json', compilerOptions: { paths: { '#server-only': ['./src/runtime/server/only.ts'] } }, include: ['src/runtime/server/**/*'] }), + 'src/runtime/server/only.ts': `export interface ServerOnly { id: string }\n`, + 'src/runtime/server/api/[id].get.ts': `import type { ServerOnly } from '#server-only'\n\nexport default (value: ServerOnly) => value.id\n`, + }, + }) + + const loggerStore = store('fake-logger') + const parent = await fixture('.temp-cli/parent', { + from, + files: { + [`${loggerStore}/package.json`]: JSON.stringify({ name: 'fake-logger', type: 'module', types: './dist/index.d.ts', exports: { '.': { types: './dist/index.d.mts', default: './dist/index.mjs' }, './utils': { types: './dist/utils.d.mts', default: './dist/utils.mjs' } } }), + [`${loggerStore}/dist/utils.d.mts`]: `export declare const noop: () => void\n`, + [`${loggerStore}/dist/utils.mjs`]: `export const noop = () => {}\n`, + [`${loggerStore}/dist/core.d.ts`]: `export interface LoggerInstance { log: (message: string) => void }\n`, + [`${loggerStore}/dist/core.d.mts`]: `export interface LoggerInstance { log: (message: string) => void }\n`, + [`${loggerStore}/dist/index.d.ts`]: `import type { LoggerInstance } from './core'\nexport type { LoggerInstance }\nexport declare function createLogger(): LoggerInstance\n`, + [`${loggerStore}/dist/index.d.mts`]: `import type { LoggerInstance } from './core.mjs'\nexport type { LoggerInstance }\nexport declare function createLogger(): LoggerInstance\n`, + [`${loggerStore}/dist/index.mjs`]: `export const createLogger = () => ({ log: console.log })\n`, + 'src/runtime/logger.ts': `import { createLogger } from 'fake-logger'\nimport { noop } from 'fake-logger/utils'\n\nexport const logger = createLogger()\nexport const silence = noop\n`, + }, + paths: { 'fake-logger': [`../${loggerStore}`] }, + }) + dirs.parent = join(parent, 'packages/mod') + await mkdir(join(dirs.parent, 'node_modules'), { recursive: true }) + for (const file of ['src', 'package.json', 'tsdown.config.ts']) { + await rename(join(parent, file), join(dirs.parent, file)) + } + await symlink(join(parent, loggerStore), join(dirs.parent, 'node_modules/fake-logger')) + + const { build: _, ...sourcePkg } = examplePkg + dirs.routes = await fixture('.temp-cli/routes/mod', { + from, + module: source => source + .replace('import { defineNuxtModule, addPlugin, createResolver }', 'import { defineNuxtModule, addPlugin, addServerHandler, createResolver }') + .replace(`addPlugin(resolver.resolve('./runtime/plugins/plugin'))`, `addPlugin(resolver.resolve('./runtime/plugins/plugin'))\n addServerHandler({ route: '/api/own', handler: resolver.resolve('./runtime/server/api/own') })`), + remove: ['tsconfig.json'], + pkg: () => sourcePkg, + files: { + '.nuxtrc': source => `${source.trimEnd()}\nworkspaceDir=..\n`, + '../tsconfig.json': JSON.stringify({ extends: './mod/playground/.nuxt/tsconfig.json', compilerOptions: { types: ['fake-global-types'] }, exclude: ['**/dist', '**/node_modules', '**/tsdown.config.ts'] }), + 'node_modules/fake-global-types/package.json': JSON.stringify({ name: 'fake-global-types', types: 'index.d.ts' }), + 'node_modules/fake-global-types/index.d.ts': `declare namespace Fake {\n interface Thing { id: number }\n function current(): Thing\n}\n`, + 'src/runtime/composables/useGlobal.ts': `export const useGlobal = () => Fake.current()\n`, + 'src/runtime/server/api/own.ts': `export default () => ({ own: 'module-owned' as const })\n`, + 'src/runtime/composables/useOwn.ts': `import { useFetch } from '#app'\n\nexport const useOwn = () => useFetch('/api/own')\n`, + 'src/runtime/composables/useSecret.ts': `import { useFetch } from '#app'\n\nexport const useSecret = () => useFetch('/api/secret')\n`, + 'src/runtime/composables/useSibling.ts': `import { useFetch } from '#app'\n\nexport const useSibling = () => useFetch('/api/sibling')\n`, + 'src/runtime/composables/useDocs.ts': `import { useFetch } from '#app'\n\nexport const useDocs = () => useFetch('/api/docs')\n`, + 'src/runtime/components/Routes.vue': `\n\n\n`, + 'playground/server/api/secret.ts': `export default () => ({ localRoute: 'must-not-be-published' as const })\n`, + 'playground/types/routes.d.ts': `declare module 'nitropack/types' {\n interface InternalApi {\n '/api/secret': { default: 'must-not-be-published' }\n }\n}\n`, + 'docs/types/routes.d.ts': `declare module 'nitropack/types' {\n interface InternalApi {\n '/api/docs': { default: 'must-not-be-published' }\n }\n}\n`, + '../sibling/types/routes.d.ts': `declare module 'nitropack/types' {\n interface InternalApi {\n '/api/sibling': { default: 'must-not-be-published' }\n }\n}\n`, + }, + }) + + const shapeOptions = (outDir: string) => `{ entries: [{ input: './src/utils', name: 'helpers' }, { input: 'src/shared/', outDir: '${outDir}/shared' }] }` + const shapes = { + object: `export default {\n outDir: 'out',\n sourcemap: true,\n plugins: [builder(${shapeOptions('out')})],\n}\n`, + array: `export default [\n { entry: { cli: 'src/cli.ts' }, outDir: 'dist-cli', dts: false },\n { plugins: [builder(${shapeOptions('out')})], outDir: 'out' },\n]\n`, + function: `export default (_, { watch: { restart } }) => ({\n plugins: [Promise.resolve(builder(${shapeOptions('dist')}))],\n})\n`, + } + for (const [shape, config] of Object.entries(shapes)) { + dirs[shape] = await fixture(`.temp-cli/${shape}-export`, { + config, + remove: ['.nuxt'], + module: source => `${source}export { other } from './shared/value.ts'\n`, + files: { + 'src/shared/value.ts': `export { other } from './other.ts'\n`, + 'src/shared/other.ts': `export const other: string = 'other'\n`, + 'src/cli.ts': `export const cli: string = 'cli'\n`, + }, + }) + } + dirs.flags = await fixture('.temp-cli/flags', { config: `export default {\n sourcemap: true,\n plugins: [builder()],\n}\n`, pkg: ({ typesVersions: _, ...pkg }) => pkg }) + + const failing = { + builderHooks: `export default {\n plugins: [builder({ hooks: { 'build:before': () => {} } })],\n}\n`, + configCwd: `export default {\n cwd: './elsewhere',\n plugins: [builder()],\n}\n`, + configEnum: `enum Mode { Build }\nexport default {\n define: { __MODE__: String(Mode.Build) },\n plugins: [builder()],\n}\n`, + withoutPlugin: `export default {}\n`, + entriesOnly: `export default [{ entry: { utils: 'src/utils.ts' }, dts: false }]\n`, + withoutTsdown: `export default {\n plugins: [builder({ entries: [{ input: './src/utils', name: 'helpers' }] })],\n}\n`, + } + for (const [name, config] of Object.entries(failing)) { + dirs[name] = await fixture(`.temp-cli/${name}`, { config }) + } + await writeFile(join(dirs.withoutTsdown, 'no-tsdown.mjs'), `import { registerHooks } from 'node:module'\n\nregisterHooks({\n resolve(specifier, context, nextResolve) {\n if (/^(?:tsdown|rolldown)(?:\\/|$)/.test(specifier)) {\n throw Object.assign(new Error(\`Cannot find package '\${specifier}'\`), { code: 'ERR_MODULE_NOT_FOUND' })\n }\n return nextResolve(specifier, context)\n },\n})\n`) + + dirs.starExports = await fixture('.temp-cli/star-exports', { + config: `export default {\n plugins: [builder()],\n}\n`, + module: `import { defineNuxtModule } from '@nuxt/kit'\nimport type { ModuleOptions } from './types/index.ts'\n\nexport * from './types/index.ts'\nexport type * from './types/runtime.ts'\n\nexport default defineNuxtModule({\n meta: { name: 'my-module', configKey: 'myModule' },\n defaults: { apiKey: '' },\n})\n`, + files: { + 'src/types/index.ts': `export * from './hooks.ts'\n\nexport interface ModuleOptions {\n apiKey: string\n}\n`, + 'src/types/hooks.ts': `export interface ModuleHooks {\n 'my-module:init': () => void\n}\n`, + 'src/types/runtime.ts': `export interface ModuleRuntimeHooks {\n 'my-module:runtime-hook': () => void\n}\n\nexport interface ModulePublicRuntimeConfig {\n NAME: string\n}\n`, + ...Object.fromEntries(['.nuxt/module-builder/types.mjs', 'dist/types.mjs'].flatMap((types, index) => [ + [`probe-${index}.ts`, `import type {} from './${types}'\nimport type { RuntimeNuxtHooks } from '#app'\nimport type { NuxtHooks, PublicRuntimeConfig } from '@nuxt/schema'\n\nexport type Augmented = [NuxtHooks['my-module:init'], RuntimeNuxtHooks['my-module:runtime-hook'], PublicRuntimeConfig['NAME']]\n`], + [`probe-${index}.tsconfig.json`, JSON.stringify({ extends: './.nuxt/tsconfig.json', compilerOptions: { noEmit: true, skipLibCheck: types.startsWith('.nuxt') }, include: [], files: [`probe-${index}.ts`] })], + ])), + }, + }) + + const selfListed = (pkg: PackageJson) => ({ ...pkg, name: 'self-listed-module' }) + const selfListedFiles = { + '.nuxtrc': (source: string) => `${source}\nmodules[]=self-listed-module\n`, + 'nuxt.config.ts': `export default { modules: [['self-listed-module', { apiKey: 'from-config' }]] }\n`, + } + const logOptions = (source: string) => source.replace('setup(_options, _nuxt) {', 'setup(_options, _nuxt) {\n console.log(`[setup] ${_options.apiKey}`)') + dirs.selfListedDist = await fixture('.temp-cli/self-listed-dist', { remove: ['.nuxt'], pkg: selfListed, module: logOptions, files: selfListedFiles }) + dirs.selfListedSource = await fixture('.temp-cli/self-listed-source', { remove: ['.nuxt'], pkg: pkg => ({ ...selfListed(pkg), exports: { '.': './src/module.ts' }, main: './src/module.ts' }), module: logOptions, files: selfListedFiles }) + + const addTypeTemplate = (source: string, extra = '') => source + .replace('import { defineNuxtModule, addPlugin, createResolver } from \'@nuxt/kit\'', 'import { defineNuxtModule, addPlugin, addTypeTemplate, createResolver } from \'@nuxt/kit\'') + .replace(' addPlugin(resolver.resolve(\'./runtime/plugins/plugin\'))', ` addPlugin(resolver.resolve('./runtime/plugins/plugin'))\n addTypeTemplate({ filename: 'types/my-module.d.ts', getContents: () => 'import type { ModuleOptions } from "my-module"\\ndeclare module "#app" {\\n interface NuxtApp {\\n $myModuleOptions: ModuleOptions\\n }\\n}\\nexport {}\\n' })\n const configured: unknown = _nuxt.options.myModule\n void configured${extra}`) + + dirs.ownPackage = await fixture('.temp-cli/own-package', { + config: 'export default { plugins: [builder()] }\n', + remove: ['.nuxt'], + pkg: pkg => ({ ...pkg, exports: examplePkg.exports, main: examplePkg.main, types: examplePkg.types, publishConfig: examplePkg.publishConfig, imports: { '#my-helpers': './src/helpers.ts' } }), + module: source => addTypeTemplate(source).replace(`createResolver } from '@nuxt/kit'`, `createResolver } from '@nuxt/kit'\n\nexport type { Helper } from '#my-helpers'\nexport type { Extra } from './extra'`), + files: { + 'tsconfig.json': source => JSON.stringify({ extends: './tsconfig.options.json', ...JSON.parse(source), exclude: undefined }), + 'tsconfig.options.json': JSON.stringify({ compilerOptions: { types: ['vitest/importMeta'] }, exclude: ['dist', 'node_modules', 'playground'] }), + 'src/helpers.ts': `export interface Helper {\n name: string\n}\n`, + 'src/extra.d.ts': `export interface Extra {\n id: string\n}\n`, + 'shared/options.ts': `import type { Extra, ModuleOptions } from 'my-module'\n\nexport const sharedApiKey = (options: ModuleOptions, extra: Extra): string => options.apiKey + extra.id\n// @ts-expect-error a string is not a number\nexport const extraId = (extra: Extra): number => extra.id\n`, + 'src/runtime/composables/useUtils.ts': `import { myModuleUtils } from 'my-module/utils'\n\nexport const useUtils = (): () => void => myModuleUtils\n`, + 'src/runtime/server/options.ts': `import type { ModuleOptions } from 'my-module'\n\nexport const apiKey = (options: ModuleOptions): string => options.apiKey\n`, + }, + }) + + dirs.ownPackageIsolated = await fixture('.temp-cli/own-package-isolated', { + config: 'export default { plugins: [builder()] }\n', + remove: ['.nuxt'], + pkg: pkg => ({ ...pkg, imports: { '#payload': './src/nested/payload.ts' } }), + module: [ + `import { defineNuxtModule } from '@nuxt/kit'`, + `import type { NuxtModule } from '@nuxt/schema'`, + `import type { Payload } from '#payload'`, + `import type { Shape } from './nested/shape.ts'`, + ``, + `export interface ModuleOptions {\n payload?: Payload\n shape?: Shape\n}`, + ``, + `const module: NuxtModule = defineNuxtModule({ meta: { name: 'my-module', configKey: 'myModule' } })`, + ``, + `export default module`, + ``, + ].join('\n'), + files: { + 'src/nested/payload.ts': `export interface Payload {\n value: string\n}\n`, + 'src/nested/shape.ts': `export interface Shape {\n sides: number\n}\n`, + 'src/utils.ts': `export const myModuleUtils = (): void => {}\n`, + 'src/runtime/composables/usePayload.ts': `import type { ModuleOptions } from 'my-module'\n\nexport const usePayload = (options: ModuleOptions): string | undefined => options.payload?.value\n`, + 'tsconfig.module.json': JSON.stringify({ extends: './.nuxt/tsconfig.node.json', compilerOptions: { isolatedDeclarations: true, declaration: true, allowJs: false } }), + 'tsconfig.json': REFERENCES('./tsconfig.module.json'), + }, + }) + + dirs.ownPackageError = await fixture('.temp-cli/own-package-error', { + config: 'export default { plugins: [builder()] }\n', + files: { + [`${store('fake-logger')}/package.json`]: JSON.stringify({ name: 'fake-logger', type: 'module', exports: { '.': { types: './index.d.ts', default: './index.js' } } }), + [`${store('fake-logger')}/index.d.ts`]: `export interface LoggerInstance { log: (message: string) => void }\nexport declare function createLogger(): LoggerInstance\n`, + [`${store('fake-shared')}/package.json`]: JSON.stringify({ name: 'fake-shared', type: 'module', exports: { '.': { types: './index.d.ts', default: './index.js' } } }), + [`${store('fake-shared')}/index.d.ts`]: `import { createLogger } from 'fake-logger'\nexport declare function createModuleLogger(name: string): ReturnType\n`, + 'src/logger.ts': `import { createModuleLogger } from 'fake-shared'\n\nexport const logger = createModuleLogger('my-module')\n`, + 'tsconfig.json': REFERENCES('./.nuxt/tsconfig.node.json'), + }, + links: { + 'node_modules/.pnpm/fake-shared@1.0.0/node_modules/fake-logger': store('fake-logger'), + 'node_modules/fake-shared': store('fake-shared'), + }, + }) + + dirs.legacyPrepare = await fixture('.temp-cli/legacy-prepare', { + config: 'export default { plugins: [builder()] }\n', + remove: ['.nuxt'], + module: source => addTypeTemplate(source, `\n void _nuxt.callHook('my-module:init', 'shared-type')`), + files: { + 'src/runtime/server/options.ts': `export const apiKey = (options: { apiKey: string }): string => options.apiKey\n`, + 'tsconfig.json': JSON.stringify({ extends: './.nuxt/tsconfig.json', exclude: ['dist', 'node_modules', 'playground', 'tsdown.config.ts', 'nuxt.config.ts'] }), + 'nuxt.config.ts': `export default { buildDir: '.nuxt-custom' }\n`, + }, + }) + + dirs.source = await fixture('.temp-cli/source', { + config: `export default {\n publint: true,\n plugins: [builder({ entries: ['./src/utils'] })],\n}\n`, + remove: ['.nuxt', 'playground/.nuxt', 'playground/.output'], + pkg: ({ typesVersions: _, ...pkg }) => ({ + ...pkg, + exports: { '.': { types: './.nuxt/module-builder/types.d.mts', default: './src/module.ts' }, './utils': './src/utils.ts' }, + main: './src/module.ts', + types: './.nuxt/module-builder/types.d.mts', + scripts: { prepack: `node ${JSON.stringify(cliBin)} build` }, + publishConfig: { + exports: { '.': { types: './dist/types.d.mts', default: './dist/module.mjs' }, './utils': { types: './dist/utils.d.mts', default: './dist/utils.mjs' } }, + main: './dist/module.mjs', + types: './dist/types.d.mts', + typesVersions: { '*': { utils: ['./dist/utils.d.mts'] } }, + }, + }), + module: source => source.replace(`import type { SharedTypeFromRuntime } from './runtime/plugins/plugin'`, `type SharedTypeFromRuntime = 'shared-type'`), + }) + + dirs.dist = await fixture('.temp-cli/dist', { + remove: ['.nuxt', 'playground/.nuxt'], + pkg: pkg => ({ ...pkg, scripts: { prepack: `node ${JSON.stringify(tsdownBin)}` } }), + }) + + const nuxt = (args: string[], cwd = repoRoot) => run('node', [join(repoRoot, 'node_modules/nuxt/bin/nuxt.mjs'), ...args], { cwd }) + const typecheck = (dir: string, context: string) => run(bin('vue-tsc'), ['--noEmit', '-p', join(dir, `playground/.nuxt/tsconfig.${context}.json`)], { cwd: dir }) + const consumerCheck = (dir: string) => run(bin('tsc'), ['--noEmit', '-p', join(dir, 'playground/consumer.tsconfig.json')]) + const listed = (dir: string, project: string) => run(bin('vue-tsc'), ['-p', project, '--noEmit', '--listFilesOnly'], { cwd: dir }) + const pack = (dir: string, command: string) => mkdir(join(dir, '.pack')).then(() => run(command, ['pack', '--pack-destination', join(dir, '.pack')], { cwd: dir })) + + await Promise.all([ + step('runtime', cli(['build', dirs.runtime])), + step('isolated', cli(['build', dirs.isolated])).then(() => step('isolated:consumer', consumerCheck(dirs.isolated))), + step('types', cli(['build', dirs.types])).then(() => step('types:consumer', consumerCheck(dirs.types))), + step('minimal', cli(['build', dirs.minimal])), + step('minimal:outDir', cli(['build', '--outDir', '..', dirs.minimal])), + step('minimal:stub', cli(['build', '--stub', dirs.minimal])), + step('minimal:prepare-stub', cli(['prepare', '--stub', dirs.minimal])), + step('shape', cli(['build', dirs.shape])), + step('loader:prepare', cli(['prepare', dirs.loader])).then(() => Promise.all([ + step('loader', cli(['build', dirs.loader])), + step('loader:probe', run(bin('tsc'), ['--ignoreConfig', '--noEmit', '--strict', '--skipLibCheck', '--allowImportingTsExtensions', '--module', 'nodenext', '--moduleResolution', 'nodenext', join(dirs.loader, 'probe.ts')])), + ])), + step('unloadable', cli(['build', dirs.unloadable])), + step('unloadable:prepare', cli(['prepare', dirs.unloadable])), + step('isolatedError', cli(['build', dirs.isolatedError])), + step('typeError', cli(['build', dirs.typeError])), + step('vueError', cli(['build', dirs.vueError])), + step('solution', cli(['build', dirs.solution])), + step('parent', cli(['build', dirs.parent])), + inOrder(['routes:prepare', () => cli(['prepare', dirs.routes!])], ['routes:playground', () => nuxt(['prepare', join(dirs.routes!, 'playground')])], ['routes', () => cli(['build', dirs.routes!])]), + ...['object', 'array', 'function'].map(shape => step(`${shape}:prepare`, cli(['prepare', dirs[shape]!])).then(() => step(shape, cli(['build', dirs[shape]!])))), + step('flags', cli(['build', '--outDir', 'custom', '--no-sourcemap', dirs.flags])), + step('builderHooks', cli(['build', dirs.builderHooks!])), + step('builderHooks:prepare', cli(['prepare', dirs.builderHooks!])), + step('configCwd', cli(['prepare', dirs.configCwd!])) + .then(() => writeFile(join(dirs.configCwd!, 'tsdown.config.ts'), `${builderImport}\nexport default {\n cwd: '.',\n plugins: [builder()],\n}\n`)) + .then(() => step('configCwd:fixed', cli(['prepare', dirs.configCwd!]))), + step('configEnum', cli(['build', dirs.configEnum!])), + step('configEnum:prepare', cli(['prepare', dirs.configEnum!])), + step('withoutPlugin', cli(['build', dirs.withoutPlugin!])), + step('withoutPlugin:prepare', cli(['prepare', dirs.withoutPlugin!])), + step('entriesOnly', cli(['build', dirs.entriesOnly!])), + step('withoutTsdown:root', run('node', ['--import', pathToFileURL(join(dirs.withoutTsdown!, 'no-tsdown.mjs')).href, '--input-type=module', '-e', `await import('tsdown').then(() => console.log('tsdown found'), () => {})\nconst root = await import(${JSON.stringify(pathToFileURL(join(repoRoot, 'src/index.ts')).href)})\nconsole.log(Object.keys(root).sort().join(','))`], { cwd: dirs.withoutTsdown })), + step('withoutTsdown', run('node', ['--import', pathToFileURL(join(dirs.withoutTsdown!, 'no-tsdown.mjs')).href, cliBin, 'build', dirs.withoutTsdown!], { cwd: dirs.withoutTsdown })), + step('starExports:prepare', cli(['prepare', dirs.starExports])).then(() => step('starExports', cli(['build', dirs.starExports]))).then(() => Promise.all([0, 1].map(index => + step(`starExports:probe-${index}`, run(bin('tsc'), ['-p', `probe-${index}.tsconfig.json`], { cwd: dirs.starExports })), + ))), + step('selfListedDist', cli(['build', dirs.selfListedDist])), + step('selfListedSource', cli(['prepare', dirs.selfListedSource])), + step('ownPackage', cli(['prepare', dirs.ownPackage])).then(() => Promise.all([ + step('ownPackage:typecheck', run(bin('vue-tsc'), ['-b', '--noEmit'], { cwd: dirs.ownPackage })), + ...['app', 'server', 'shared'].map(name => step(`ownPackage:${name}`, listed(dirs.ownPackage!, `.nuxt/tsconfig.${name}.json`))), + ])), + step('ownPackageIsolated', cli(['prepare', dirs.ownPackageIsolated])).then(() => Promise.all([ + step('ownPackageIsolated:typecheck', run(bin('vue-tsc'), ['-b', '--noEmit'], { cwd: dirs.ownPackageIsolated })), + step('ownPackageIsolated:app', listed(dirs.ownPackageIsolated!, '.nuxt/tsconfig.app.json')), + ])), + step('ownPackageError', cli(['prepare', dirs.ownPackageError])), + step('legacyPrepare', cli(['prepare', dirs.legacyPrepare])).then(() => Promise.all([ + step('legacyPrepare:typecheck', run(bin('vue-tsc'), ['--noEmit'], { cwd: dirs.legacyPrepare })), + step('legacyPrepare:files', run(bin('vue-tsc'), ['--noEmit', '--listFilesOnly'], { cwd: dirs.legacyPrepare })), + ])), + (async () => { + if (!await inOrder(['source:prepare', () => cli(['prepare', dirs.source!])], ['source:playground', () => nuxt(['prepare', 'playground'], dirs.source)])) { + return + } + await Promise.all([ + step('source:app', typecheck(dirs.source!, 'app')), + step('source:node', typecheck(dirs.source!, 'node')), + step('source:npm', run('node', [...packProbeArgs, cliBin, 'build'], { cwd: dirs.source, env: npmPackFromPnpmScript() })), + ]) + sourceWithoutDist = !exists(dirs.source!, 'dist') + await Promise.all([ + step('source:generate', nuxt(['generate', 'playground'], dirs.source)), + inOrder(['source:pack', () => pack(dirs.source!, 'pnpm')], ['source:attw', () => run(bin('attw'), [join(dirs.source!, '.pack/my-module-1.0.0.tgz'), '--ignore-rules', 'cjs-resolves-to-esm'], { cwd: dirs.source })]), + ]) + })(), + (async () => { + if (!await inOrder(['dist:prepare', () => cli(['prepare', dirs.dist!])], ['dist:build', () => run('node', [tsdownBin], { cwd: dirs.dist })], ['dist:playground', () => nuxt(['prepare', 'playground'], dirs.dist)])) { + return + } + await Promise.all([step('dist:app', typecheck(dirs.dist!, 'app')), step('dist:node', typecheck(dirs.dist!, 'node'))]) + await inOrder(['dist:generate', () => nuxt(['generate', 'playground'], dirs.dist)], ['dist:pack', () => pack(dirs.dist!, 'npm')]) + })(), + ]) +}, 300_000) + +const expectBuilt = (name: string) => { + const { exitCode, output } = result(name) + expect(exitCode, output).toBe(0) + return output +} + +const expectFailed = (name: string) => { + const { exitCode, output } = result(name) + expect(exitCode, output).not.toBe(0) + return output +} + +describe('a module that imports runtime code, under a path with spaces and non-ASCII characters', () => { + const dist = () => join(dirs.runtime!, 'dist') + + it('should generate module metadata', async () => { + expectBuilt('runtime') + expect(JSON.parse(await read(dist(), 'module.json'))).toMatchObject({ configKey: 'myModule', name: 'my-module' }) + }) + + it('should externalise runtime imports made through relative, aliased and `.vue` specifiers', async () => { + expect(runtimeSpecifiers(await read(dist(), 'module.mjs'))).toEqual([ + './runtime/composables/useShape.js', + './runtime/utils/aliased.js', + './runtime/utils/name.js', + ]) + const moduleDts = await read(dist(), 'module.d.mts') + expect(findStaticImports(moduleDts).find(i => i.specifier.includes('plugins'))!.code.trim()).toBe(`import { SharedTypeFromRuntime } from "./runtime/plugins/plugin.js";`) + expect(findStaticImports(moduleDts).map(i => i.specifier)).toContain('./runtime/components/JsxComponent.jsx') + }) + + it('should point imports of a runtime JSX file at its `.jsx` output', async () => { + expect(await read(dist(), 'runtime/components/JsxCard.vue')).toContain(`import JsxComponent from "./JsxComponent.jsx";`) + expect(await read(dist(), 'runtime/components/JsxSlot.jsx')).toMatchInlineSnapshot(` + "import { defineComponent } from "vue"; + import { useNuxtApp } from "#app"; + import JsxComponent from "./JsxComponent.jsx"; + export const useSlotApp = () => useNuxtApp(); + export default defineComponent((_, { slots }) => () =>
{slots.default?.()}
); + " + `) + expect(await read(dist(), 'runtime/components/JsxSlot.d.ts')).toContain('export declare const useSlotApp: () => import("nuxt/app").NuxtApp;') + }) + + it('should compile JSX in server runtime files and the files they import, and preserve it elsewhere', async () => { + expect(exists(dist(), 'runtime/server/render.jsx')).toBe(false) + for (const file of ['utils/strong.js', 'utils/bold.js']) { + expect(await read(dist(), 'runtime', file), file).toContain(`import { jsx as _jsx } from "vue/jsx-runtime";`) + } + expect(await read(dist(), 'runtime/utils/label.jsx')).toContain('label') + expect(await read(dist(), 'runtime/server/render.js')).toMatchInlineSnapshot(` + "import { strong } from "../utils/strong.js"; + import { jsx as _jsx } from "vue/jsx-runtime"; + export const render = (label) => /* @__PURE__ */ _jsx("p", { children: strong(label) }); + " + `) + expect(await read(dist(), 'runtime/server/render.d.ts')).toMatchInlineSnapshot(` + "import { useSlotApp } from '../components/JsxSlot.jsx'; + export type SlotApp = ReturnType; + export declare const render: (label: string) => import("vue/jsx-runtime").JSX.Element; + " + `) + }) + + it('should keep every non-relative runtime import as written', async () => { + expect(findStaticImports(await read(dist(), 'runtime/server/handler.js')).map(i => i.specifier)).toEqual([ + '#internal/nuxt.config.mjs', + '~/app.config', + '@/root', + '#app', + 'fake-dep', + '#fixture-cache', + '../utils/local.js', + ]) + expect(findStaticImports(await read(dist(), 'runtime/utils/options.d.ts')).map(i => i.specifier)).toEqual(['fake-types']) + }) + + it('should not emit dependencies or bundler helpers into the runtime directory', async () => { + const files = await listFiles(join(dist(), 'runtime')) + expect(files.filter(file => /node_modules|_virtual/.test(file))).toEqual([]) + for (const file of files.filter(file => /\.m?[jt]s$/.test(file))) { + expect(await read(dist(), 'runtime', file), file).not.toMatch(/bundled-fake-dep|DeepPartial/) + } + }) + + it('should keep types of packages that are not dependencies external in module declarations', async () => { + const types = await read(dist(), 'module.d.mts') + expect(types).toMatch(/from "fake-types"/) + expect(types).toMatch(/from "fake-cjs-types"/) + expect(types).not.toMatch(/DeepPartial/) + }) + + it('should name inferred types by package when the generated tsconfig maps a package to its real path', async () => { + const types = await read(dist(), 'module.d.mts') + expect(types).toMatch(/Thing<\{/) + expect(types).toMatch(/["']fake-schema["']/) + }) + + it('should keep bracketed file names in runtime output', () => { + expect(exists(dist(), 'runtime/server/routes/[...slug].js')).toBe(true) + expect(exists(dist(), 'runtime/server/routes/[...slug].d.ts')).toBe(true) + }) + + it('should resolve imports of the package itself to its source in declarations', async () => { + expect(await read(dist(), 'runtime/utils/self.d.ts')).toMatch(/=> string;/) + }) + + it('should warn about type errors that do not affect runtime declarations and build anyway', async () => { + const output = expectBuilt('runtime') + expect(output).toMatch(/2 type errors were reported while generating declarations for `?src\/runtime`?; the declarations were emitted\. If the module's own type check \(for example `?nuxt typecheck`? or `?vue-tsc --noEmit`?\) passes/) + expect(output).toContain('src/runtime/utils/typo.ts(1,14): error TS2322') + expect(output).toContain('src/runtime/components/Typo.vue(3,7): error TS2322') + expect(output.match(/type errors? (?:was|were) reported/g)).toHaveLength(1) + expect(output).toContain(guide('other-type-errors')) + expect(output).not.toContain('TS2307') + expect(await read(dist(), 'runtime/utils/typo.d.ts')).toBe('export declare const count: number;\nexport declare const double: (value: number) => number;\n') + const component = await read(dist(), 'runtime/components/Typo.vue.d.ts') + expect(component).toContain('label: string') + expect(component).toBe(await read(dist(), 'runtime/components/Typo.d.vue.ts')) + const composable = await read(dist(), 'runtime/composables/useSize.d.ts') + expect(composable).toContain(`import type { Props } from '../components/Sized.vue';`) + expect(composable).toMatch(/export declare function useSize\(props: Props\): import\("vue"\)\.ComputedRef<"xs" \| "sm" \| "md" \| undefined>;/) + }) + + it('should give every relative specifier in runtime declarations an extension that resolves', async () => { + expect(await unresolvedSpecifiers(dist())).toEqual([]) + }) +}) + +describe('a module with `isolatedDeclarations` and no `.nuxt`', () => { + const dist = () => join(dirs.isolated!, 'dist') + + it('should prepare the module before building it', async () => { + expect(expectBuilt('isolated')).toMatch(new RegExp(`\\.nuxt\`? not found, running \`?nuxt-module-build prepare\`? first\\..*${guide('preparing-nuxt')}`)) + expect(await read(dist(), 'runtime/composables/useAliasedApp.d.ts')).toMatch(/import\("nuxt\/app"\)\.NuxtApp/) + }) + + it('should build an annotated module while still inferring runtime types', async () => { + const moduleTypes = await read(dist(), 'module.d.mts') + expect(moduleTypes).toContain('NuxtModule') + expect(moduleTypes).toMatch(/apiKey: string/) + expect(await read(dist(), 'runtime/plugins/plugin.d.ts')).toContain('import("nuxt/app").Plugin<') + expect(JSON.parse(await read(dist(), 'module.json'))).toMatchObject({ name: 'my-module', configKey: 'myModule' }) + }) + + it('should keep value exports as values in `types.d.mts`', async () => { + expect(await read(dist(), 'types.d.mts')).toMatchInlineSnapshot(` + "import type { ModuleHooks, ModuleRuntimeHooks, ModuleRuntimeConfig, ModulePublicRuntimeConfig } from './module.mjs' + + declare module '#app' { + interface RuntimeNuxtHooks extends ModuleRuntimeHooks {} + } + + declare module '@nuxt/schema' { + interface NuxtHooks extends ModuleHooks {} + interface RuntimeConfig extends ModuleRuntimeConfig {} + interface PublicRuntimeConfig extends ModulePublicRuntimeConfig {} + } + + export { defineMyModuleConfig, Mode, type ModuleHooks, type ModuleOptions, type ModulePublicRuntimeConfig, type ModuleRuntimeConfig, type ModuleRuntimeHooks, myModuleVersion, default } from './module.mjs' + " + `) + expect(expectBuilt('isolated:consumer')).toBe('') + }) + + it('should flatten, prefix and minify runtime CSS', async () => { + const card = await read(dist(), 'runtime/styles/card.css') + expect(card).toMatch(/^@import "\.\/base\.css";/) + expect(card).toContain('.card .title{font-weight:700}') + expect(card).toContain('.card:hover{color:#639}') + expect(card).toContain('-webkit-user-select:none') + expect(card).not.toMatch(/&|\n/) + }) + + it('should compile runtime Sass to CSS and skip partials', async () => { + const styles = join(dist(), 'runtime/styles') + expect(await listFiles(styles)).toEqual(['base.css', 'card.css', 'indented.css', 'legacy.less', 'theme.css']) + expect(await read(styles, 'theme.css')).toMatch(/^\.theme \.nested \{\s*padding: 1px;\s*\}$/m) + expect(await read(styles, 'theme.css')).toContain('color: #00dc82;') + expect(await read(styles, 'indented.css')).toContain('color: blue;') + }) + + it('should copy runtime declaration files verbatim, apart from `#app`', async () => { + expect(await read(dist(), 'runtime/types/ambient.d.ts')).toBe(await read(dirs.isolated!, 'src/runtime/types/ambient.d.ts')) + expect(await read(dist(), 'runtime/types/app.d.ts')).toBe(`import type { NuxtApp } from 'nuxt/app'\nexport type App = NuxtApp\n`) + }) + + it('should point stylesheet imports in runtime scripts at the emitted files', async () => { + const styled = await read(dist(), 'runtime/plugins/styled.js') + expect(styled).toContain('import "../styles/card.css";') + expect(styled).toContain('import "../styles/theme.css";') + expect(styled).not.toContain('theme.scss') + }) +}) + +describe('a module without exported `ModuleOptions`', () => { + it('should generate types that infer them and keep value exports as values', async () => { + expectBuilt('types') + expect(await read(dirs.types!, 'dist/types.d.mts')).toMatchInlineSnapshot(` + "import type { NuxtModule } from '@nuxt/schema' + + import type { default as Module, ModuleHooks, ModuleRuntimeHooks, ModuleRuntimeConfig, ModulePublicRuntimeConfig } from './module.mjs' + + declare module '#app' { + interface RuntimeNuxtHooks extends ModuleRuntimeHooks {} + } + + declare module '@nuxt/schema' { + interface NuxtHooks extends ModuleHooks {} + interface RuntimeConfig extends ModuleRuntimeConfig {} + interface PublicRuntimeConfig extends ModulePublicRuntimeConfig {} + } + + export type ModuleOptions = typeof Module extends NuxtModule ? Partial : Record + + export { defineMyModuleConfig, Mode, type ModuleHooks, type ModulePublicRuntimeConfig, type ModuleRuntimeConfig, type ModuleRuntimeHooks, myModuleVersion, default } from './module.mjs' + " + `) + expect(expectBuilt('types:consumer')).toBe('') + }) +}) + +describe('a module without a runtime directory', () => { + it('should build its entries and a directory that contains only single-file components', async () => { + expectBuilt('minimal') + expect(await listFiles(join(dirs.minimal!, 'dist'))).toMatchInlineSnapshot(` + [ + "components", + "components/TestMe.css", + "components/TestMe.d.vue.ts", + "components/TestMe.vue", + "components/TestMe.vue.d.ts", + "components/TestMeSetup.d.vue.ts", + "components/TestMeSetup.vue", + "components/TestMeSetup.vue.d.ts", + "module.d.mts", + "module.json", + "module.mjs", + "types.d.mts", + "utils.d.mts", + "utils.mjs", + ] + `) + }) + + it('should refuse an `outDir` that contains the module root', () => { + expect(expectFailed('minimal:outDir')).toContain(`\`--outDir ..\` resolves to \`${resolve(dirs.minimal!, '..')}\`, which contains the module root; the build empties the output directory first. Use a directory inside the module such as \`dist\`. ${guide('output-directory')}`) + expect(exists(dirs.minimal!, 'package.json')).toBe(true) + }) + + it('should fail on `--stub` and point at what replaces it', () => { + for (const command of ['build', 'prepare']) { + expect(expectFailed(command === 'build' ? 'minimal:stub' : 'minimal:prepare-stub'), command).toContain(`\`nuxt-module-build ${command} --stub\` has been removed. With pnpm or Yarn 4, point \`package.json\` at the module's sources. Otherwise, build \`dist\` with \`tsdown\` and rebuild it with \`tsdown --watch\`. ${guide('stub-builds')}`) + } + }) +}) + +describe('a module whose runtime files import files around them', () => { + const dist = () => join(dirs.shape!, 'dist') + + it('should keep the imports and re-exports of each runtime file as written, in source order', async () => { + expectBuilt('shape') + const runtime = join(dist(), 'runtime') + expect(await read(runtime, 'disabled/index.js')).toMatchInlineSnapshot(` + "import "./side.js"; + export { defineThing } from "./composables/defineThing.js"; + " + `) + expect(await read(runtime, 'disabled/composables/defineThing.js')).toMatchInlineSnapshot(` + "export { defineThing } from "../../composables/mock.js"; + " + `) + expect(await read(runtime, 'content/index.js')).toMatchInlineSnapshot(` + "export * from "../components/TestMe.vue"; + export * from "../components/TestMeSetup.vue"; + export * from "./prose.js"; + " + `) + expect(await read(runtime, 'content/index.d.ts')).toMatchInlineSnapshot(` + "export * from '../components/TestMe.vue'; + export * from '../components/TestMeSetup.vue'; + export * from './prose.js'; + " + `) + expect(await read(runtime, 'content/prose.d.ts')).toMatchInlineSnapshot(` + "export * from './levels.js'; + export interface ProseThing { + title: string; + } + " + `) + expect(await read(runtime, 'order/interleaved.js')).toMatchInlineSnapshot(` + "import "fake-register"; + import { level } from "./levels.js"; + export * from "./reexported.js"; + import "./order.css"; + export { useState } from "#imports"; + import "fake-polyfill"; + import "./effect.js"; + import { ref } from "vue"; + export const value = ref(level); + " + `) + }) + + it('should point runtime imports outside the runtime directory at the files emitted for them', async () => { + expect(await read(dist(), 'runtime/server/uses.js')).toMatchInlineSnapshot(` + "import { merge } from "../../utils/merge.mjs"; + import { CONSTANT } from "../../shared/constants.js"; + export const combine = (a, b) => [merge(a, b), CONSTANT]; + " + `) + expect(await read(dist(), 'runtime/server/uses.d.ts')).toMatchInlineSnapshot(` + "import type { RootType } from '../../_external/src/types.js'; + import type { RuntimeType } from '../types.js'; + export declare const combine: (a: RootType & RuntimeType, b: RootType & RuntimeType) => readonly [RootType & RuntimeType, 10]; + " + `) + expect(await read(dist(), 'runtime/escaping.js')).toContain(`import("../_external/external.js")`) + expect(await read(dist(), 'shared/constants.js')).toMatchInlineSnapshot(` + "import { LIMIT } from "./limits.js"; + export const CONSTANT = LIMIT; + " + `) + const files = await listFiles(dist()) + expect(files.filter(file => !file.startsWith('runtime'))).toMatchInlineSnapshot(` + [ + "_external", + "_external/external.d.ts", + "_external/external.js", + "_external/src", + "_external/src/types.d.ts", + "data.d.mts", + "data.mjs", + "module.d.mts", + "module.json", + "module.mjs", + "routing.d.ts", + "shared", + "shared/constants.d.ts", + "shared/constants.js", + "shared/limits.d.ts", + "shared/limits.js", + "types", + "types.d.mts", + "types/middlewares.d.ts", + "utils", + "utils.d.mts", + "utils.mjs", + "utils/merge.d.mts", + "utils/merge.mjs", + ] + `) + expect(files.filter(file => /^runtime\/(?:types|server|utils)/.test(file))).toMatchInlineSnapshot(` + [ + "runtime/server", + "runtime/server/limiter.d.ts", + "runtime/server/limiter.js", + "runtime/server/uses.d.ts", + "runtime/server/uses.js", + "runtime/types.d.ts", + "runtime/types.js", + "runtime/utils", + "runtime/utils/props.d.ts", + "runtime/utils/props.js", + "runtime/utils/provider.d.ts", + "runtime/utils/provider.js", + ] + `) + }) + + it('should emit only declarations for files outside the runtime directory that runtime files use as types', async () => { + expect(await read(dist(), 'runtime/server/limiter.js')).toMatchInlineSnapshot(` + "import "../disabled/side.js"; + export const limit = (options) => options.maxRequestSizeInBytes; + " + `) + expect(await read(dist(), 'runtime/composables/useLocaleRoute.js')).toMatchInlineSnapshot(` + "export const useLocaleRoute = (route) => route; + " + `) + expect(await read(dist(), 'routing.d.ts')).toMatchInlineSnapshot(` + "import type { RootType } from './_external/src/types.js'; + export interface RouteInfo { + path: string; + root: RootType; + } + export declare const localizeRoutes: (file: string) => string; + " + `) + for (const file of ['routing.js', 'kit', 'types/middlewares.js', 'types.d.ts', 'types.js', '_external/src/types.js']) { + expect(exists(dist(), file), file).toBe(false) + } + }) + + it('should type imports of build-time aliases as `any` in declarations', async () => { + const runtime = join(dist(), 'runtime') + expect(await read(runtime, 'composables/useThemeConfig.d.ts')).toContain('useThemeConfig: () => any;') + expect(await read(runtime, 'composables/useButton.d.ts')).toMatchInlineSnapshot(` + "export declare const useButton: () => { + slots: any; + size: any; + ui: any; + }; + " + `) + expect(await read(runtime, 'components/Button.d.vue.ts')).toMatchInlineSnapshot(` + "type __VLS_Props = { + size?: string; + }; + declare const __VLS_export: import("vue").DefineComponent<__VLS_Props, { + classes: any[]; + }, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<__VLS_Props> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>; + declare const _default: typeof __VLS_export; + export default _default; + " + `) + expect(exists(runtime, 'components/Sized.vue.d.ts')).toBe(true) + }) + + it('should give every relative specifier in declarations an extension that resolves', async () => { + expect(await unresolvedSpecifiers(dist())).toEqual([]) + }) +}) + +describe('a module whose entry Node cannot import natively, with a wildcard `paths` entry', () => { + it('should prepare it without handing it to jiti', async () => { + expect(expectBuilt('loader:prepare')).not.toContain('ERR_INTERNAL_ASSERTION') + expect(await read(dirs.loader!, '.nuxt/nuxt.node.d.ts')).toContain('/// ') + expect(await read(dirs.loader!, '.nuxt/types/modules.d.ts')).toContain(`typeof import(${JSON.stringify(join(dirs.loader!, 'src/module'))}).default`) + }) + + it('should re-export the module\'s default export from the types that `prepare` writes', () => { + expect(expectBuilt('loader:probe')).toBe('') + }) + + it('should bundle the `imports` of `package.json` and the files they point at', async () => { + expectBuilt('loader') + const built = await read(dirs.loader!, 'dist/module.mjs') + expect(built).toContain('loaded helper') + expect(built).toContain('through imports') + expect(built).not.toContain('#internal') + }) + + it('should not let a wildcard `paths` entry shadow real packages when loading meta', async () => { + expect(JSON.parse(await read(dirs.loader!, 'dist/module.json'))).toMatchObject({ name: 'my-module', configKey: 'my-module' }) + }) +}) + +describe('a module whose code Node cannot load', () => { + it('should fail to build and prepare, with how to rewrite each import and each piece of syntax', async () => { + const line = (await read(dirs.unloadable!, 'src/module.ts')).split('\n').findIndex(line => line.includes('./utils.js')) + 1 + for (const name of ['unloadable', 'unloadable:prepare']) { + const output = expectFailed(name) + expect(output, name).toContain([ + 'Module code has to load with Node, which strips types and resolves imports as written:', + ' - src/levels.ts:1:1: `enum` (use an `as const` object and a union type of its values)', + ' - src/module.ts:1:37: `../package.json` is JSON (use `import pkg from \'../package.json\' with { type: \'json\' }` and read `pkg.version`; destructuring `pkg` bundles the whole file)', + ' - src/module.ts:4:1: `enum` (use an `as const` object and a union type of its values)', + ' - src/module.ts:5:28: parameter property (declare the field and assign it in the constructor)', + ].join('\n')) + expect(output, name).toMatch(/src\/module\.ts:\d+:\d+: angle-bracket type assertion \(write `value as Type`\)/) + expect(output, name).toContain([ + ` - src/module.ts:${line}:31: \`./utils.js\` (use \`./utils.ts\`)`, + ` - src/module.ts:${line + 1}:24: \`./helpers\` (use \`./helpers.ts\`)`, + ` - src/module.ts:${line + 2}:21: \`./kit\` (use \`./kit/index.ts\`)`, + `Change each one as suggested. ${guide('module-code-loads-with-node')}`, + ].join('\n')) + expect(output, name).not.toContain(`:${line + 3}:`) + } + expect(exists(dirs.unloadable!, 'dist')).toBe(false) + }) +}) + +describe('a module whose declarations cannot be generated', () => { + it('should surface isolated declaration diagnostics when the tsconfig opts in', () => { + const output = expectFailed('isolatedError') + expect(output).toMatch(/Declaration generation failed under `?isolatedDeclarations/) + expect(output).toMatch(/TS90\d\d/) + expect(output).toContain(guide('isolated-declarations')) + expect(output).not.toMatch(/Type declarations could not be generated/) + expect(exists(dirs.isolatedError!, 'dist')).toBe(false) + }) + + it('should explain type errors that prevent declaration generation', () => { + const output = expectFailed('typeError') + expect(output).toMatch(/TS4094/) + expect(output).toMatch(/Type declarations could not be generated/) + expect(output).toMatch(/cannot reference by name.*explicit type annotation, such as `ReturnType` for a value produced by an imported `fn`:\n- `defineCachedHandler` in \S*src\/runtime\/server\/cached\.ts:3\n/) + expect(output).toContain(guide('portability-errors')) + expect(exists(dirs.typeError!, 'dist')).toBe(false) + }) + + it('should fail on portability errors in a single-file component and in a script sharing its program', () => { + const output = expectFailed('vueError') + expect(output).toMatch(/components\/Cached\.vue\(4,14\): error TS(?:2742|2883)/) + expect(output).toMatch(/server\/cached\.ts\(3,14\): error TS(?:2742|2883)/) + expect(output).toMatch(/cannot reference by name.*:\n(?:- `\w+` in \S+\n)*- `cachedHandler` in \S*src\/runtime\/components\/Cached\.vue:4\n/) + expect(output).toMatch(/\n- `defineCachedHandler` in \S*src\/runtime\/server\/cached\.ts:3\n/) + expect(output).toContain(guide('portability-errors')) + expect(exists(dirs.vueError!, 'dist')).toBe(false) + }) +}) + +describe('tsconfig lookup', () => { + it('should generate declarations for each project of a solution-style tsconfig', async () => { + expectBuilt('solution') + expect(await read(dirs.solution!, 'dist/runtime/server/api/[id].get.d.ts')).toMatch(/=> string;/) + expect(await read(dirs.solution!, 'dist/runtime/composables/useAliasedApp.d.ts')).toMatch(/import\("nuxt\/app"\)\.NuxtApp/) + expect(exists(dirs.solution!, 'dist/runtime/components/TestMe.vue.d.ts')).toBe(true) + }) + + it('should use a tsconfig from a parent directory, naming runtime types by package when it maps the package into the store', async () => { + expectBuilt('parent') + expect(await read(dirs.parent!, 'dist/runtime/composables/useAliasedApp.d.ts')).toMatch(/import\("nuxt\/app"\)\.NuxtApp/) + expect(await read(dirs.parent!, 'dist/runtime/logger.d.ts')).toMatch(/import\("fake-logger"\)\.LoggerInstance/) + }) + + it('should generate declarations with the module\'s own `.nuxt` when the tsconfig takes its types from a playground', async () => { + expect(expectBuilt('routes')).toMatch(new RegExp(`\\.\\./tsconfig.json\`? takes its generated types from another app's \`?.nuxt\`?; declarations are generated with \`?.nuxt/tsconfig.json\`? instead. Add a \`?tsconfig.json\`? in the module directory that extends \`?./.nuxt/tsconfig.json\`?. ${guide('module-tsconfig')}`)) + expect(await read(dirs.routes!, 'playground/.nuxt/types/nitro-routes.d.ts')).toContain('/api/secret') + for (const file of await listFiles(join(dirs.routes!, 'dist'))) { + if (file.includes('.')) { + expect(await read(dirs.routes!, 'dist', file), file).not.toMatch(/must-not-be-published|playground|\.nuxt/) + } + } + }) + + it('should type the responses of routes the module registers and leave other routes unknown', async () => { + const dir = dirs.routes! + expect(await read(dir, '.nuxt/types/nitro-routes.d.ts')).toContain('/api/own') + const { default: ts } = await import('typescript') + const files = ts.getParsedCommandLineOfConfigFile(join(dir, '.nuxt/tsconfig.json'), {}, { ...ts.sys, onUnRecoverableConfigFileDiagnostic: () => {} })!.fileNames + expect(files.map(file => relative(dir, file)).filter(file => file.includes('routes.d.ts')).sort()).toEqual(['../sibling/types/routes.d.ts', 'docs/types/routes.d.ts', 'playground/types/routes.d.ts']) + expect(await read(dir, 'dist/runtime/composables/useOwn.d.ts')).toBe(`export declare const useOwn: () => import("nuxt/app").AsyncData<{\n own: "module-owned";\n} | undefined, import("nuxt/app").NuxtError | undefined>;\n`) + expect(await read(dir, 'dist/runtime/composables/useGlobal.d.ts')).toBe('export declare const useGlobal: () => Fake.Thing;\n') + expect(output('routes')).not.toMatch(/type errors? (?:was|were) reported/) + for (const name of ['useSecret', 'useSibling', 'useDocs']) { + expect(await read(dir, `dist/runtime/composables/${name}.d.ts`), name).toBe(`export declare const ${name}: () => import("nuxt/app").AsyncData | undefined>;\n`) + } + const component = await read(dir, 'dist/runtime/components/Routes.vue.d.ts') + expect(component).toContain('own: import("vue").Ref<{\n own: "module-owned";\n } | undefined, {\n own: "module-owned";\n } | undefined>;') + expect(component).toContain('secret: import("vue").Ref;') + }) +}) + +describe('tsdown configs', () => { + it.each([ + ['an object', 'object', 'out'], + ['an array', 'array', 'out'], + ['a function', 'function', 'dist'], + ])('should prepare and build a module whose tsdown config exports %s', async (_, shape, outDir) => { + expect(expectBuilt(`${shape}:prepare`)).not.toContain('ERROR') + expect(exists(dirs[shape]!, '.nuxt/tsconfig.json')).toBe(true) + expect(exists(dirs[shape]!, '.nuxt/module-builder/types.d.mts')).toBe(true) + expectBuilt(shape) + const out = join(dirs[shape]!, outDir) + expect(await read(out, 'shared/value.mjs')).toContain(`from "./other.mjs"`) + expect(exists(out, 'helpers.mjs')).toBe(true) + expect(exists(out, 'types.d.mts')).toBe(true) + expect(JSON.parse(await read(out, 'module.json'))).toMatchObject({ name: 'my-module' }) + if (shape === 'array') { + expect(await read(dirs[shape]!, 'dist-cli/cli.mjs')).toContain(`const cli = "cli"`) + } + }) + + it('should build with the tsdown config\'s `outDir` and `sourcemap` unless `--outDir` and `--sourcemap` override them', () => { + expect(exists(dirs.object!, 'out/module.mjs.map')).toBe(true) + expect(exists(dirs.object!, 'out/runtime/plugins/plugin.js.map')).toBe(true) + expect(exists(dirs.object!, 'dist')).toBe(false) + expectBuilt('flags') + expect(exists(dirs.flags!, 'custom/module.json')).toBe(true) + expect(exists(dirs.flags!, 'custom/module.mjs.map')).toBe(false) + expect(exists(dirs.flags!, 'custom/runtime/plugins/plugin.js.map')).toBe(false) + }) + + it('should refuse `hooks` in `builder()` and point at tsdown\'s own', () => { + for (const name of ['builderHooks', 'builderHooks:prepare']) { + expect(expectFailed(name), name).toContain(`\`builder()\` does not take \`hooks\`. Use tsdown's own \`hooks\` in the tsdown config, or a plugin that emits extra files. ${guide('hooks-in-a-tsdown-config')}`) + } + }) + + it('should fail to prepare with a tsdown config whose `cwd` is another directory', () => { + expect(expectFailed('configCwd')).toContain('`tsdown.config.ts` sets `cwd`, but `prepare` reads the module in the directory of the tsdown config.') + expectBuilt('configCwd:fixed') + }) + + it('should fail on a tsdown config that Node cannot load', () => { + for (const name of ['configEnum', 'configEnum:prepare']) { + const output = expectFailed(name) + expect(output, name).toContain('tsdown.config.ts:2:1: `enum` (use an `as const` object and a union type of its values)') + expect(output, name).toContain(guide('module-code-loads-with-node')) + } + }) + + it('should fail on a tsdown config without `builder()` and show how to add it', () => { + for (const name of ['withoutPlugin', 'withoutPlugin:prepare']) { + const output = expectFailed(name) + expect(output, name).toContain([ + '`tsdown.config.ts` does not build the module with `builder()`. Add the plugin:', + '', + ` import { builder } from '@nuxt/module-builder/tsdown'`, + ` import { defineConfig } from 'tsdown'`, + '', + ` export default defineConfig({`, + ` plugins: [builder()],`, + ` })`, + ].join('\n')) + expect(output, name).toContain(guide('tsdown-config')) + } + expect(expectFailed('entriesOnly')).toContain('`tsdown.config.ts` does not build the module with `builder()`.') + expect(exists(dirs.entriesOnly!, 'dist')).toBe(false) + }) + + it('should load the package root without tsdown, and point at installing it to build', () => { + expect(expectBuilt('withoutTsdown:root').trim()).toBe('build,defineBuildConfig,prepare') + expect(expectFailed('withoutTsdown')).toContain(guide('install-tsdown')) + }) +}) + +describe('prepare', () => { + it('should augment the same interfaces from the types `prepare` writes as from `dist`, through star re-exports', async () => { + expectBuilt('starExports:prepare') + expectBuilt('starExports') + const shims = async (file: string) => (await read(dirs.starExports!, file)).match(/^declare module '[^']+' \{\n[\s\S]*?\n\}$/gm) + const sourceShims = await shims('.nuxt/module-builder/types.d.mts') + expect(sourceShims).toEqual(await shims('dist/types.d.mts')) + expect(sourceShims).toEqual([ + `declare module '#app' {\n interface RuntimeNuxtHooks extends ModuleRuntimeHooks {}\n}`, + `declare module '@nuxt/schema' {\n interface NuxtHooks extends ModuleHooks {}\n interface PublicRuntimeConfig extends ModulePublicRuntimeConfig {}\n}`, + ]) + for (const index of [0, 1]) { + const { output } = result(`starExports:probe-${index}`) + expect(output.split('\n').filter(line => /^(?:src|dist|\.nuxt\/module-builder)\/|^probe-\d\.ts/.test(line)), String(index)).toEqual([]) + } + }) + + it('should prepare a module that lists its own package in `.nuxtrc` and `nuxt.config`, with or without `dist`', async () => { + const references = async (dir: string) => (await read(dir, '.nuxt/nuxt.node.d.ts')).split('\n').filter(line => line.includes('types="self-listed-module"') || line === '/// ') + for (const name of ['selfListedDist', 'selfListedSource']) { + expect(expectBuilt(name).match(/\[setup\] .*/g), name).toEqual(['[setup] from-config']) + expect(await references(dirs[name]!), name).toEqual(['/// ']) + } + }) + + it('should resolve the module\'s own package to declarations of module code in its app, server and shared tsconfigs', async () => { + const dir = dirs.ownPackage! + expectBuilt('ownPackage') + expect(expectBuilt('ownPackage:typecheck')).toBe('') + for (const name of ['app', 'server', 'shared']) { + const files = expectBuilt(`ownPackage:${name}`).split('\n').map(file => file.trim()) + expect(files, name).not.toContain(join(dir, 'src/module.ts')) + expect(files, name).not.toContain(join(dir, 'src/utils.ts')) + expect(files, name).not.toContain(join(dir, 'src/helpers.ts')) + expect(files, name).toContain(join(dir, '.nuxt/module-builder/declarations/src/module.d.ts')) + } + expect(output('ownPackage:app')).toContain(join(dir, '.nuxt/module-builder/declarations/src/utils.d.ts')) + }) + + it('should generate tsconfigs for the module entry, without the playground or the workspace, and with app aliases and root options for module code', async () => { + const generated = async (name: string) => JSON.parse(await read(dirs.ownPackage!, `.nuxt/tsconfig.${name}.json`)) + const [node, app] = [await generated('node'), await generated('app')] + expect(node.include).toContain('../src/*.ts') + expect(node.compilerOptions.paths['#app']).toBeDefined() + expect(node.compilerOptions.paths['#components']).toBeDefined() + expect(node.compilerOptions.types).toContain('vitest/importMeta') + expect(app.exclude).toContain('../playground') + expect(app.include).not.toContain('../../**/*') + expect(app.include).toContain('../src/runtime') + for (const name of ['app', 'node', 'server', 'shared']) { + const { include, exclude } = await generated(name) + expect([...include, ...exclude].filter((pattern: string) => pattern.startsWith('../src/dist')), name).toEqual([]) + } + }) + + it('should write the declarations of module code with oxc when its tsconfig sets `isolatedDeclarations`', async () => { + const dir = dirs.ownPackageIsolated! + expect(expectBuilt('ownPackageIsolated')).not.toContain('The build reports the same errors') + expect(await read(dir, '.nuxt/module-builder/declarations/src/nested/payload.d.ts')).toContain('interface Payload') + const moduleDeclaration = await read(dir, '.nuxt/module-builder/declarations/src/module.d.ts') + expect(moduleDeclaration).toContain('from "./nested/payload.js"') + expect(moduleDeclaration).toContain('from "./nested/shape.js"') + expect(expectBuilt('ownPackageIsolated:typecheck')).toBe('') + const files = expectBuilt('ownPackageIsolated:app') + expect(files).toContain(join(dir, '.nuxt/module-builder/declarations/src/nested/payload.d.ts')) + expect(files).not.toContain(join(dir, 'src/nested/payload.ts')) + expect(files).not.toContain(join(dir, 'src/nested/shape.ts')) + }) + + it('should warn about a declaration error in module code, and write the other declarations', () => { + const output = expectBuilt('ownPackageError') + expect(output).toContain('The build reports the same errors') + expect(output).toContain('src/logger.ts(3,14): error TS2883') + expect(exists(dirs.ownPackageError!, '.nuxt/module-builder/declarations/src/module.d.ts')).toBe(true) + expect(exists(dirs.ownPackageError!, '.nuxt/module-builder/declarations/types.d.mts')).toBe(true) + }) + + it('should keep `.nuxt/tsconfig.json` one program over the module\'s sources, with the generated tsconfigs adapted', async () => { + const dir = dirs.legacyPrepare! + expectBuilt('legacyPrepare') + const generated = async (name: string) => JSON.parse(await read(dir, `.nuxt/${name}.json`)) + expect((await generated('tsconfig.app')).compilerOptions.paths['my-module']).toEqual(['./module-builder/declarations/types.d.mts']) + const legacy = await generated('tsconfig') + expect(legacy.compilerOptions.paths['my-module']).toBeUndefined() + expect(legacy.include).not.toContain('./module-builder/declarations/types.d.mts') + expect(legacy.exclude).not.toContain('../src/runtime/server') + const typecheck = output('legacyPrepare:typecheck') + expect(typecheck).not.toMatch(/error TS5\d{3}/) + expect(typecheck.split('\n').filter(line => /^(?:src|\.nuxt)\//.test(line))).toEqual([]) + const files = output('legacyPrepare:files') + expect(files).toContain(join(dir, 'src/module.ts')) + expect(files).toContain(join(dir, 'src/runtime/server/options.ts')) + expect(files).not.toContain(join(dir, '.nuxt/module-builder/declarations/src/module.d.ts')) + }) +}) + +describe('the example', () => { + const typeErrors = (name: string) => output(name).split('\n').filter(line => line.includes('error TS')) + + it('should type the playground and its config through the module\'s exports, from its sources without `dist` and from `dist`', () => { + for (const name of ['source:app', 'source:node', 'dist:app', 'dist:node']) { + expect(typeErrors(name), name).toEqual([]) + } + expect(sourceWithoutDist).toBe(true) + }) + + it('should render the playground with the module installed by name', async () => { + for (const flow of ['source', 'dist']) { + expectBuilt(`${flow}:generate`) + expect(await read(dirs[flow]!, 'playground/.output/public/index.html')).toContain('Nuxt module playground!') + } + expect(await read(dirs.source!, 'playground/.nuxt/types/plugins.d.ts')).toContain('src/runtime/plugins/plugin') + }) + + it('should refuse to build source exports for a pack by npm, including when a pnpm script runs it', () => { + const { output, exitCode } = result('source:npm') + expect(exitCode, `${packProbeContext()}\n${output}`).not.toBe(0) + expect(output).toMatch(/`npm(?:@[\d.]+)?` packs these fields of `package\.json` as written, and they point at TypeScript sources or paths that `files` leaves out: `exports`, `main`, `types` \(`\.\/\.nuxt\/module-builder\/types\.d\.mts`, `\.\/src\/module\.ts`, `\.\/src\/utils\.ts`\)\./) + expect(output).toContain(guide('publishing-source-exports')) + }) + + it('should pack the `dist` paths in `publishConfig` with pnpm, and `dist` with npm, without warnings', async () => { + const packed = async (dir: string) => JSON.parse((await succeed(run('tar', ['-xzOf', join(dir, '.pack/my-module-1.0.0.tgz'), 'package/package.json'])))) + expect(await packed(dirs.source!)).toMatchObject({ + exports: { '.': { types: './dist/types.d.mts', default: './dist/module.mjs' } }, + main: './dist/module.mjs', + types: './dist/types.d.mts', + }) + expect(await packed(dirs.source!)).not.toHaveProperty('publishConfig') + const { publishConfig } = JSON.parse(await read(exampleDir, 'package.json')) + expect(await packed(dirs.dist!)).toMatchObject({ exports: publishConfig.exports, main: publishConfig.main }) + for (const name of ['source:pack', 'dist:pack']) { + const output = expectBuilt(name) + expect(output, name).toContain('Build complete') + expect(output, name).not.toMatch(/\bWARN\b/) + } + expect(output('source:pack')).toContain('[publint] No issues found') + expectBuilt('source:attw') + }) + + describe('`dist`', () => { + const dist = () => join(dirs.dist!, 'dist') + + it('should generate all files', async () => { + expect(await listFiles(dist())).toMatchInlineSnapshot(` + [ + "module.d.mts", + "module.json", + "module.mjs", + "runtime", + "runtime/assets", + "runtime/assets/config.json", + "runtime/components", + "runtime/components/JsxComponent.d.ts", + "runtime/components/JsxComponent.jsx", + "runtime/components/TestMe.css", + "runtime/components/TestMe.d.vue.ts", + "runtime/components/TestMe.vue", + "runtime/components/TestMe.vue.d.ts", + "runtime/components/TestMeSetup.d.vue.ts", + "runtime/components/TestMeSetup.vue", + "runtime/components/TestMeSetup.vue.d.ts", + "runtime/composables", + "runtime/composables/useAliasedApp.d.ts", + "runtime/composables/useAliasedApp.js", + "runtime/composables/useAppNuxt.d.ts", + "runtime/composables/useAppNuxt.js", + "runtime/composables/useWrappedFetch.d.ts", + "runtime/composables/useWrappedFetch.js", + "runtime/plugins", + "runtime/plugins/plugin.d.ts", + "runtime/plugins/plugin.js", + "types.d.mts", + "utils.d.mts", + "utils.mjs", + ] + `) + }) + + it('should reference `@nuxt/schema` rather than `nuxt/schema` in module declarations', async () => { + const types = await read(dist(), 'module.d.mts') + expect(types).toContain('import("@nuxt/schema")') + expect(types).not.toContain('import("nuxt/schema")') + }) + + it('should copy non-code files in the runtime directory', async () => { + expect(await read(dist(), 'runtime/components/TestMe.css')).toBe('.test-me{color:#639}') + }) + + it('should give every relative specifier in runtime declarations an extension that resolves', async () => { + expect(await unresolvedSpecifiers(dist())).toEqual([]) + }) + + it('should write types to output directory', async () => { + expect(await read(dist(), 'types.d.mts')).toMatchInlineSnapshot(` + "import type { ModuleHooks, ModuleRuntimeHooks, ModuleRuntimeConfig, ModulePublicRuntimeConfig } from './module.mjs' + + declare module '#app' { + interface RuntimeNuxtHooks extends ModuleRuntimeHooks {} + } + + declare module '@nuxt/schema' { + interface NuxtHooks extends ModuleHooks {} + interface RuntimeConfig extends ModuleRuntimeConfig {} + interface PublicRuntimeConfig extends ModulePublicRuntimeConfig {} + } + + export { type ModuleHooks, type ModuleOptions, type ModulePublicRuntimeConfig, type ModuleRuntimeConfig, type ModuleRuntimeHooks, default } from './module.mjs' + " + `) + }) + + it('should generate module metadata as separate JSON file', async () => { + const tsdownPkg = await readPackageJSON('tsdown') + expect(JSON.parse(await read(dist(), 'module.json'))).toMatchObject({ + builder: { '@nuxt/module-builder': version, 'tsdown': tsdownPkg.version }, + configKey: 'myModule', + name: 'my-module', + version: '1.0.0', + }) + }) + + it('should generate typed plugin', async () => { + const pluginDts = await read(dist(), 'runtime/plugins/plugin.d.ts') + const appAlias = `import\\("nuxt/app"\\)` + expect(pluginDts).toMatch(/^export type SharedTypeFromRuntime = 'shared-type';$/m) + expect(pluginDts).toMatch(new RegExp(`declare const _default: ${appAlias}\\.Plugin<\\{\\s*injection: "injected";\\s*\\}> & ${appAlias}\\.ObjectPlugin<\\{\\s*injection: "injected";\\s*\\}>;`)) + expect(pluginDts).toMatch(/^export default _default;$/m) + }) + + it('should resolve every shape of `#app` alias in runtime declarations, and leak none of them', async () => { + const declaration = await read(dist(), 'runtime/composables/useAliasedApp.d.ts') + expect(declaration).toMatch(/declare const useAppInstance: \(\) => import\("nuxt\/app"\)\.NuxtApp;/) + expect(declaration).toMatch(/declare const useAppRouter: \(\) => import\("vue-router"\)\./) + expect(declaration).toMatch(/declare const useAppCookie: \(name: string\) => import\("nuxt\/app"\)\.CookieRef import\("nuxt\/app"\)\.NuxtApp;/) + for (const file of (await listFiles(join(dist(), 'runtime'))).filter(file => /\.d\.[^/]*ts$/.test(file))) { + const contents = await read(dist(), 'runtime', file) + expect(contents, file).not.toMatch(/(["'])#app(?:\/[^"']*)?\1/) + expect(contents, file).not.toMatch(/import\("#app(?:\/[^"]*)?"\)/) + } + }) + + it('should correctly add extensions to imports from runtime/ directory', async () => { + const runtimeImport = findStaticImports(await read(dist(), 'module.d.mts')).find(i => i.specifier.includes('runtime')) + expect(runtimeImport!.code.trim()).toMatchInlineSnapshot(`"import { SharedTypeFromRuntime } from "./runtime/plugins/plugin.js";"`) + }) + + it('should generate components', async () => { + for (const file of ['TestMe.vue', 'TestMe.vue.d.ts', 'TestMeSetup.vue', 'TestMeSetup.vue.d.ts', 'TestMeSetup.d.vue.ts']) { + await expect((await read(dist(), 'runtime/components', file)).replace(/\r\n/g, '\n')).toMatchFileSnapshot(`__snapshots__/${file}`) + } + }) + + it('should generate wrapped composables', async () => { + const expectedErrorType = satisfies(nuxtVersion, '^3') ? 'null' : 'undefined' + const errorType = satisfies(nuxtVersion, '^3') + ? 'import\\("ofetch"\\)\\.FetchError' + : '(?:import\\("ofetch"\\)\\.FetchError|import\\("nuxt/app"\\)\\.NuxtError)' + expect(await read(dist(), 'runtime/composables/useWrappedFetch.d.ts')).toMatch(new RegExp(`^export declare const useWrappedFetch: \\(\\) => import\\("nuxt/app"\\)\\.AsyncData;$`, 'm')) + }) + + it('should preserve JSX in runtime files for the app to compile', async () => { + expect(exists(dist(), 'runtime/components/JsxComponent.js')).toBe(false) + await expect(await read(dist(), 'runtime/components/JsxComponent.jsx')).toMatchFileSnapshot('__snapshots__/JsxComponent.jsx') + await expect(await read(dist(), 'runtime/components/JsxComponent.d.ts')).toMatchFileSnapshot('__snapshots__/JsxComponent.d.ts') + }) + }) +}) diff --git a/test/deprecations.spec.ts b/test/deprecations.spec.ts deleted file mode 100644 index cccc9add..00000000 --- a/test/deprecations.spec.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { join } from 'pathe' -import ts from 'typescript' -import { describe, expect, it } from 'vitest' - -const repoRoot = fileURLToPath(new URL('..', import.meta.url)) - -function deprecations(source: string) { - const file = join(repoRoot, 'test/__deprecations__.ts') - const options: ts.CompilerOptions = { - allowImportingTsExtensions: true, - resolveJsonModule: true, - module: ts.ModuleKind.Preserve, - moduleResolution: ts.ModuleResolutionKind.Bundler, - target: ts.ScriptTarget.ES2024, - strict: true, - noEmit: true, - skipLibCheck: true, - } - const service = ts.createLanguageService({ - getScriptFileNames: () => [file], - getScriptVersion: () => '1', - getScriptSnapshot: name => name === file ? ts.ScriptSnapshot.fromString(source) : ts.sys.fileExists(name) ? ts.ScriptSnapshot.fromString(ts.sys.readFile(name)!) : undefined, - getCurrentDirectory: () => repoRoot, - getCompilationSettings: () => options, - getDefaultLibFileName: ts.getDefaultLibFilePath, - fileExists: name => name === file || ts.sys.fileExists(name), - readFile: name => name === file ? source : ts.sys.readFile(name), - }) - expect(service.getSemanticDiagnostics(file).map(diagnostic => ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'))).toEqual([]) - return service.getSuggestionDiagnostics(file) - .filter(diagnostic => diagnostic.reportsDeprecated) - .map(diagnostic => ({ - name: source.slice(diagnostic.start, diagnostic.start! + diagnostic.length!), - advice: ts.displayPartsToString(service.getQuickInfoAtPosition(file, diagnostic.start!)?.tags?.find(tag => tag.name === 'deprecated')?.text), - })) -} - -describe('deprecations in the editor', () => { - it('should mark `defineBuildConfig()`', () => { - expect(deprecations([ - `import { defineBuildConfig } from '../src/index.ts'`, - `defineBuildConfig({ entries: ['./src/utils'] })`, - ].join('\n'))).toEqual(Array.from({ length: 2 }, () => ({ - name: 'defineBuildConfig', - advice: expect.stringMatching(/`builder\(\)` from `@nuxt\/module-builder\/tsdown`, in `tsdown\.config\.ts`/), - }))) - }) -}) diff --git a/test/legacy.spec.ts b/test/legacy.spec.ts new file mode 100644 index 00000000..d663b1aa --- /dev/null +++ b/test/legacy.spec.ts @@ -0,0 +1,546 @@ +import { createHash } from 'node:crypto' +import { mkdir, mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { fileURLToPath } from 'node:url' +import { consola } from 'consola' +import { findStaticImports } from 'mlly' +import { join, relative } from 'pathe' +import ts from 'typescript' +import { beforeAll, describe, expect, it, vi } from 'vitest' + +import { assertNoLegacyBuildConfig, bundledEntries, entryName, formatUnsupportedOptions, loadBuildConfig, translateBuildConfig, warnDeprecatedBuildConfig } from '../src/build/build-config.ts' +import { guide } from '../src/build/guide.ts' +import type { FixtureOptions, Result } from './utils.ts' +import { cli, exists, fixture, listFiles, read, repoRoot, tsdown } from './utils.ts' + +const exampleDir = fileURLToPath(new URL('../example', import.meta.url)) + +describe('translateBuildConfig', () => { + const cwd = exampleDir + const outDir = join(cwd, 'dist') + const translate = (...configs: unknown[]) => translateBuildConfig(configs.map((config, index) => ({ name: `config${index}`, config })), { cwd, outDir }) + + it('should name entries the way unbuild did', () => { + expect(entryName('src/vite', cwd)).toBe('vite') + expect(entryName('./src/runtime/server/index.ts', cwd)).toBe('runtime/server/index') + expect(entryName(join(cwd, 'src/cli.mts'), cwd)).toBe('cli') + expect(entryName('lib/other', cwd)).toBe('lib/other') + }) + + it('should resolve entry inputs to their source file, without duplicating the module entry', () => { + expect(translate({ entries: ['src/utils', { input: './src/utils.ts', name: 'helpers' }] }).entries).toEqual({ + utils: './src/utils.ts', + helpers: './src/utils.ts', + }) + expect(bundledEntries(cwd, translate({ entries: ['src/module'] }))).toEqual({ module: './src/module.ts' }) + }) + + it('should skip a directory entry for `src/runtime` and keep others', () => { + const { directories, unsupported } = translate({ entries: [{ input: 'src/runtime/', outDir: 'dist/runtime' }, { input: 'src/shared/', builder: 'mkdist', outDir: 'dist/shared' }, { input: 'src/features/', outDir: 'dist/features', ext: 'js' }, { input: 'src/other/', outDir: 'lib' }] }) + expect(directories).toEqual([ + { srcDir: join(cwd, 'src/shared'), outDir: join(outDir, 'shared'), ext: 'mjs' }, + { srcDir: join(cwd, 'src/features'), outDir: join(outDir, 'features'), ext: 'js' }, + ]) + expect(unsupported).toEqual(['config0: entries[3].outDir']) + }) + + it('should match string externals by package name', () => { + const [pkg, alias] = translate({ externals: ['fake-pkg', '#alias'] }).neverBundle + expect(['fake-pkg', 'fake-pkg/sub'].every(id => pkg!.test(id))).toBe(true) + expect(pkg!.test('fake-pkg-other')).toBe(false) + expect(alias!.test('#alias/config')).toBe(true) + }) + + it('should merge replacements with earlier configs taking precedence', () => { + expect(translate( + { replace: { __A__: '"a"' }, rollup: { replace: { delimiters: ['', ''], values: { __B__: '"b"' } } } }, + { replace: { __A__: '"overridden"', __C__: '"c"' } }, + ).replace).toEqual({ values: { __A__: '"a"', __B__: '"b"', __C__: '"c"' }, delimiters: ['', ''], preventAssignment: true }) + expect(translate({ replace: { __A__: '"a"' }, rollup: { replace: false } }).replace).toBeUndefined() + }) + + it('should accept options without an effect on the output', () => { + expect(translate({ + declaration: 'node16', + failOnWarn: false, + name: 'my-module', + rootDir: '.', + outDir: 'dist', + clean: true, + entries: [{ input: 'src/features/', outDir: 'dist/features', ext: 'mjs', addRelativeDeclarationExtensions: true }], + rollup: { emitCJS: false, cjsBridge: false, output: { exports: 'named' } }, + }).unsupported).toEqual([]) + }) + + it('should keep supported hooks, ignore mkdist hooks and reject the rest', () => { + const before = () => {} + const done = () => {} + const { hooks, ignoredHooks, unsupported } = translate({ hooks: { 'build:before': before, 'rollup:done': done, 'mkdist:entry:options': () => {}, 'rollup:options': () => {} } }) + expect(hooks).toEqual({ 'build:before': [before], 'rollup:done': [done], 'build:done': [] }) + expect(ignoredHooks).toEqual(['config0: hooks[\'mkdist:entry:options\']']) + expect(unsupported).toEqual(['config0: hooks[\'rollup:options\']']) + }) + + it('should collect every option without an equivalent', () => { + expect(translate( + { hooks: { 'build:prepare': () => {} }, rollup: { emitCJS: true, output: { format: 'cjs' } }, stubOptions: {} }, + { externals: [42], replace: { __FN__: () => '' } }, + ).unsupported).toEqual([ + 'config0: hooks[\'build:prepare\']', + 'config0: rollup.emitCJS: true', + 'config0: rollup.output', + 'config0: stubOptions', + 'config1: externals[0]', + 'config1: replace[\'__FN__\']', + ]) + }) + + it('should point each unsupported option at its section of the upgrade guide', () => { + const message = formatUnsupportedOptions(['build.config.ts: hooks[\'rollup:options\']', 'build.config.ts: rollup.emitCJS: true', 'build.config.ts: rollup.alias', 'build.config.ts: entries[0].esbuild', 'build.config.ts: stubOptions']) + expect(message.split('\n')).toEqual([ + 'The build config uses options that `@nuxt/module-builder` v2 does not support:', + ` - build.config.ts: hooks['rollup:options'] (${guide('hooks')})`, + ` - build.config.ts: rollup.emitCJS: true (${guide('commonjs-output')})`, + ` - build.config.ts: rollup.alias (${guide('rollup-options')})`, + ` - build.config.ts: entries[0].esbuild (${guide('mkdist-options')})`, + ` - build.config.ts: stubOptions (${guide('other-options')})`, + `Remove each of them from the file named. ${guide('unsupported-build-options')}`, + ]) + }) + + it('should warn about a deprecated config file and ignored hooks in CI too', () => { + vi.stubEnv('CI', 'true') + const warn = vi.spyOn(consola, 'warn').mockImplementation(() => {}) + try { + const config = { ...translate({}), file: 'build.config.ts', importsUnbuild: true, ignoredHooks: ['build.config.ts: hooks[\'mkdist:entry:options\']'] } + warnDeprecatedBuildConfig(config) + warnDeprecatedBuildConfig({ ...config, importsUnbuild: false, ignoredHooks: [], field: 'unbuild' }) + expect(warn.mock.calls.map(([message]) => message)).toEqual([ + expect.stringMatching(new RegExp(`^Ignoring build\\.config\\.ts: hooks\\['mkdist:entry:options'\\]: .*Remove the hook\\. ${guide('hooks')}$`)), + expect.stringMatching(new RegExp(`^\`build\\.config\\.ts\` is deprecated\\. .*instead of \`unbuild\`\\. Move them into \`builder\\(\\)\` in \`tsdown\\.config\\.ts\`\\. ${guide('moving-from-buildconfigts')}$`)), + `\`build.config.ts\` is deprecated. Its options are still applied. Move them into \`builder()\` in \`tsdown.config.ts\`. ${guide('moving-from-buildconfigts')}`, + expect.stringMatching(new RegExp(`^The \`unbuild\` field of \`package\\.json\` is deprecated\\. .*Rename the field to \`build\`\\. ${guide('build-configuration')}$`)), + ]) + } + finally { + warn.mockRestore() + vi.unstubAllEnvs() + } + }) +}) + +describe('loadBuildConfig', () => { + let dir: string + + beforeAll(async () => { + dir = await mkdtemp(join(tmpdir(), 'module-builder-')) + return () => rm(dir, { recursive: true, force: true }) + }) + + it('should load a config file, then `package.json`', async () => { + await writeFile(join(dir, 'build.config.mjs'), `export default [{ externals: ['a'] }, false]\n`) + const config = await loadBuildConfig(dir, { build: { externals: ['b'] } }, join(dir, 'dist')) + expect(config.file).toBe('build.config.mjs') + expect(config.importsUnbuild).toBe(false) + expect(config.field).toBe('build') + expect(config.neverBundle.map(String)).toEqual(['/^a(?:\\/|$)/', '/^b(?:\\/|$)/']) + expect(config.unsupported).toEqual([]) + + await rm(join(dir, 'build.config.mjs')) + await mkdir(join(dir, 'node_modules/unbuild'), { recursive: true }) + await writeFile(join(dir, 'node_modules/unbuild/package.json'), JSON.stringify({ name: 'unbuild', type: 'module', exports: './index.js' })) + await writeFile(join(dir, 'node_modules/unbuild/index.js'), 'export const defineBuildConfig = config => config\n') + await writeFile(join(dir, 'build.config.js'), `import { defineBuildConfig } from 'unbuild'\nexport default [defineBuildConfig({ externals: ['a'] }), { entries: ['src/utils'] }]\n`) + expect(await loadBuildConfig(dir, {}, join(dir, 'dist'))).toMatchObject({ importsUnbuild: true, field: undefined, unsupported: ['build.config.js: an array of 2 configs'] }) + + await rm(join(dir, 'build.config.js')) + await writeFile(join(dir, 'build.config.mts'), 'export default () => ({})\n') + await expect(loadBuildConfig(dir, {}, join(dir, 'dist'))).rejects.toThrow(`not a function. Replace the function with the object it returns. ${guide('other-options')}`) + await rm(join(dir, 'build.config.mts')) + + expect(await loadBuildConfig(dir, {}, join(dir, 'dist'))).toMatchObject({ file: undefined, unsupported: [] }) + const fromPkg = await loadBuildConfig(dir, { unbuild: { externals: ['u'] }, build: { externals: ['b'] } }, join(dir, 'dist')) + expect(fromPkg.neverBundle.map(String)).toEqual(['/^u(?:\\/|$)/']) + + const inferred = (await loadBuildConfig(dir, { name: '@nuxt/image', imports: { '#image/*': './src/*.ts' } }, join(dir, 'dist'))).neverBundle + expect(inferred).toHaveLength(1) + expect(['@nuxt/image', '@nuxt/image/utils'].every(id => inferred[0]!.test(id))).toBe(true) + expect(inferred[0]!.test('@nuxt/image/runtime/providers/ipx')).toBe(false) + }) + + it('should list the imports of a config file and of the module code that Node cannot resolve', async () => { + const root = join(dir, 'extensions') + await mkdir(join(root, 'src/lib'), { recursive: true }) + await writeFile(join(root, 'options.ts'), `export default { externals: ['o'] }\n`) + await writeFile(join(root, 'build.config.ts'), `import options from './options'\nexport default options\n`) + await writeFile(join(root, 'src/module.ts'), `import { helper } from './helper'\nexport { shared } from './lib'\nexport default helper\n`) + await writeFile(join(root, 'src/helper.ts'), `export const helper = 1\n`) + await writeFile(join(root, 'src/lib/index.ts'), `import { shared } from '../../options'\nexport { shared }\n`) + await expect(loadBuildConfig(root, { build: { entries: ['src/lib/index'] } }, join(root, 'dist'))).rejects.toThrow([ + 'Module code has to load with Node, which strips types and resolves imports as written:', + ' - build.config.ts:1:21: `./options` (use `./options.ts`)', + ' - src/lib/index.ts:1:24: `../../options` (use `../../options.ts`)', + ' - src/module.ts:1:24: `./helper` (use `./helper.ts`)', + ' - src/module.ts:2:24: `./lib` (use `./lib/index.ts`)', + `Change each one as suggested. ${guide('module-code-loads-with-node')}`, + ].join('\n')) + await writeFile(join(root, 'build.config.ts'), `import options from './options.ts'\nexport default options\n`) + expect((await loadBuildConfig(root, {}, join(root, 'dist'))).neverBundle.map(String)).toEqual(['/^o(?:\\/|$)/']) + }) +}) + +describe('assertNoLegacyBuildConfig', () => { + it('should refuse a `build` or `unbuild` field of `package.json` alongside `builder()`', () => { + expect(() => assertNoLegacyBuildConfig(exampleDir, { build: {} })).toThrow(`The \`build\` field of \`package.json\` configures the build, and so does \`builder()\` in the tsdown config. Move its options into \`builder()\` and remove the field. ${guide('moving-from-buildconfigts')}`) + expect(() => assertNoLegacyBuildConfig(exampleDir, { unbuild: {} })).toThrow('The `unbuild` field of `package.json`') + expect(() => assertNoLegacyBuildConfig(exampleDir, {})).not.toThrow() + }) +}) + +describe('deprecations in the editor', () => { + it('should mark `defineBuildConfig()`', () => { + const file = join(repoRoot, 'test/__deprecations__.ts') + const source = [ + `import { defineBuildConfig } from '../src/index.ts'`, + `defineBuildConfig({ entries: ['./src/utils'] })`, + ].join('\n') + const options: ts.CompilerOptions = { + allowImportingTsExtensions: true, + resolveJsonModule: true, + module: ts.ModuleKind.Preserve, + moduleResolution: ts.ModuleResolutionKind.Bundler, + target: ts.ScriptTarget.ES2024, + strict: true, + noEmit: true, + skipLibCheck: true, + } + const service = ts.createLanguageService({ + getScriptFileNames: () => [file], + getScriptVersion: () => '1', + getScriptSnapshot: name => name === file ? ts.ScriptSnapshot.fromString(source) : ts.sys.fileExists(name) ? ts.ScriptSnapshot.fromString(ts.sys.readFile(name)!) : undefined, + getCurrentDirectory: () => repoRoot, + getCompilationSettings: () => options, + getDefaultLibFileName: ts.getDefaultLibFilePath, + fileExists: name => name === file || ts.sys.fileExists(name), + readFile: name => name === file ? source : ts.sys.readFile(name), + }) + expect(service.getSemanticDiagnostics(file).map(diagnostic => ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'))).toEqual([]) + const deprecated = service.getSuggestionDiagnostics(file) + .filter(diagnostic => diagnostic.reportsDeprecated) + .map(diagnostic => ({ + name: source.slice(diagnostic.start, diagnostic.start! + diagnostic.length!), + advice: ts.displayPartsToString(service.getQuickInfoAtPosition(file, diagnostic.start!)?.tags?.find(tag => tag.name === 'deprecated')?.text), + })) + expect(deprecated).toEqual(Array.from({ length: 2 }, () => ({ + name: 'defineBuildConfig', + advice: expect.stringMatching(/`builder\(\)` from `@nuxt\/module-builder\/tsdown`, in `tsdown\.config\.ts`/), + }))) + }) +}) + +describe('nuxt-module-build build without a tsdown config', () => { + const LEGACY_TSCONFIG = { extends: './.nuxt/tsconfig.json', exclude: ['dist', 'node_modules', 'playground'] } + const dirs: Record = {} + const results: Record = {} + const step = async (name: string, result: Promise) => { + results[name] = await result + return results[name] + } + const expectBuilt = (name: string) => { + expect(results[name]!.exitCode, results[name]!.output).toBe(0) + return results[name]!.output + } + const expectFailed = (name: string) => { + expect(results[name]!.exitCode, results[name]!.output).not.toBe(0) + return results[name]!.output + } + const hashes = async (dir: string) => { + const files = (await readdir(dir, { recursive: true, withFileTypes: true })).filter(file => file.isFile()) + return Object.fromEntries(await Promise.all(files.map(async (file) => { + const path = join(file.parentPath, file.name) + return [relative(dir, path), createHash('sha256').update(await readFile(path)).digest('hex')] as const + }))) + } + + const withoutBuildConfig = ({ 'build.config.ts': _, ...files }: NonNullable) => files + + beforeAll(async () => { + const base = await fixture('.temp-legacy/base', { config: false, files: { 'tsconfig.json': JSON.stringify(LEGACY_TSCONFIG) } }) + const prepared = await cli(['prepare', base]) + expect(prepared.exitCode, prepared.output).toBe(0) + + const buildConfig: FixtureOptions = { + from: base, + config: false, + pkg: pkg => ({ + ...pkg, + imports: { '#content-alias/*': './src/alias/*.ts' }, + publishConfig: { imports: { '#content-alias/*': './dist/alias/*.mjs' } }, + build: { entries: [{ input: 'src/features/', outDir: 'dist/features', ext: 'js' }] }, + }), + files: { + 'build.config.ts': `import { appendFileSync, existsSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' +import { defineBuildConfig } from '@nuxt/module-builder' +import { externals } from './build/externals.ts' + +const record = hook => ctx => appendFileSync(join(ctx.options.rootDir, 'hooks.log'), JSON.stringify({ + hook, + stub: ctx.options.stub, + meta: existsSync(join(ctx.options.outDir, 'module.json')), + entries: ctx.options.entries.map(entry => entry.name).sort(), +}) + '\\n') + +export default defineBuildConfig({ + hooks: { + 'build:before'(ctx) { + record('build:before')(ctx) + writeFileSync(join(ctx.options.rootDir, 'src/generated.ts'), 'export const generated = "from build:before"\\n') + }, + 'rollup:done': record('rollup:done'), + 'build:done': record('build:done'), + }, + declaration: true, + entries: [ + 'src/utils', + './src/vite.ts', + { input: 'src/content', name: 'content' }, + 'src/nested/helper', + { input: 'src/shared/', outDir: 'dist/shared' }, + ], + externals, + replace: { + __MODULE_VERSION__: JSON.stringify('1.2.3'), + }, + rollup: { + emitCJS: false, + }, +}) +`, + 'build/externals.ts': `export const externals = ['fake-pkg', '#content-alias', /^regex-pkg$/]\n`, + 'node_modules/fake-pkg/package.json': JSON.stringify({ name: 'fake-pkg', type: 'module', exports: { './sub': './sub.js' } }), + 'node_modules/fake-pkg/sub.js': `export const plugin = 'bundled-fake-pkg'\n`, + 'node_modules/regex-pkg/package.json': JSON.stringify({ name: 'regex-pkg', type: 'module', exports: './index.js' }), + 'node_modules/regex-pkg/index.js': `export default 'bundled-regex-pkg'\n`, + 'src/alias/config.ts': `export default 'bundled-alias'\n`, + 'src/vite.ts': `// @ts-ignore untyped\nimport { plugin } from 'fake-pkg/sub'\n// @ts-ignore untyped\nimport virtual from 'regex-pkg'\n\nimport { generated } from './generated.ts'\n\ndeclare const __MODULE_VERSION__: string\n\nexport const version: string = __MODULE_VERSION__\nexport const refs: unknown[] = [plugin, virtual, generated]\n`, + 'src/content.ts': `// @ts-ignore build-time alias\nimport config from '#content-alias/config'\n\nexport const content: unknown = config\n`, + 'src/nested/helper.ts': `import plugin from '../runtime/plugins/plugin.ts'\n\nexport const helper = (): unknown => plugin\nexport const lazy = (): Promise => import('../runtime/composables/useWrappedFetch.ts')\n`, + 'src/shared/format.ts': `export const format = (value: string): string => value.trim()\n`, + 'src/features/flag.ts': `export const flag: boolean = true\n`, + }, + } + dirs.buildConfig = await fixture('.temp-legacy/build-config', buildConfig) + dirs.buildConfigEjected = await fixture('.temp-legacy/build-config-ejected', { + ...buildConfig, + config: `import { writeFileSync } from 'node:fs' +import { join } from 'node:path' +import { externals } from './build/externals.ts' + +export default { + hooks: { + 'build:prepare'(ctx) { + writeFileSync(join(ctx.options.cwd, 'src/generated.ts'), 'export const generated = "from build:before"\\n') + }, + }, + plugins: [builder({ + entries: ['src/utils', './src/vite.ts', { input: 'src/content', name: 'content' }, 'src/nested/helper', { input: 'src/shared/', outDir: 'dist/shared' }, { input: 'src/features/', outDir: 'dist/features', ext: 'js' }], + externals, + replace: { __MODULE_VERSION__: JSON.stringify('1.2.3') }, + })], +} +`, + pkg: pkg => ({ ...buildConfig.pkg!(pkg), build: undefined }), + files: withoutBuildConfig(buildConfig.files!), + }) + + const replace: FixtureOptions = { + from: base, + config: false, + module: source => [ + `import type { NuxtModule } from '@nuxt/schema'`, + source.replace(/export default defineNuxtModule()?\(\{/, (_, options = '') => `const module: NuxtModule${options} = defineNuxtModule${options}({`), + 'export default module', + ].join('\n'), + pkg: pkg => ({ ...pkg, unbuild: { externals: ['ext-pkg'] } }), + files: { + 'tsconfig.json': JSON.stringify({ ...LEGACY_TSCONFIG, compilerOptions: { isolatedDeclarations: true } }), + 'src/utils.ts': 'export const myModuleUtils = (): void => {}\n', + 'build.config.ts': `import { defineBuildConfig } from 'unbuild' + +export default defineBuildConfig({ + entries: ['./src/unplugin'], + externals: ['#build/ui'], + hooks: { + 'mkdist:entry:options'(ctx, entry, options) { + options.addRelativeDeclarationExtensions = false + }, + }, + rollup: { + replace: { + delimiters: ['', ''], + values: { + "process.argv.includes('--uiDev')": 'false', + }, + }, + }, +}) +`, + 'src/unplugin.ts': `// @ts-ignore untyped\nimport ext from 'ext-pkg'\n\ndeclare const process: { argv: string[] }\n\nexport const isDev: boolean = process.argv.includes('--uiDev')\nexport const extRef: unknown = ext\n`, + 'node_modules/ext-pkg/package.json': JSON.stringify({ name: 'ext-pkg', type: 'module', exports: './index.js' }), + 'node_modules/ext-pkg/index.js': `export default 'bundled-ext-pkg'\n`, + }, + } + dirs.replace = await fixture('.temp-legacy/replace', replace) + dirs.replaceEjected = await fixture('.temp-legacy/replace-ejected', { + ...replace, + config: `export default {\n plugins: [builder({\n entries: ['./src/unplugin'],\n externals: ['#build/ui', 'ext-pkg'],\n replace: { delimiters: ['', ''], values: { "process.argv.includes('--uiDev')": 'false' } },\n })],\n}\n`, + pkg: undefined, + files: withoutBuildConfig(replace.files!), + }) + + dirs.unsupported = await fixture('.temp-legacy/unsupported', { + from: base, + config: false, + files: { + 'build.config.ts': `import { defineBuildConfig } from 'unbuild' + +export default defineBuildConfig({ + entries: [ + { input: 'src/runtime/', ext: 'cjs' }, + { input: 'src/schema', builder: 'untyped' }, + ], + hooks: { + 'build:prepare'() {}, + 'rollup:options'() {}, + 'mkdist:entry:options'() {}, + }, + rollup: { + emitCJS: true, + alias: {}, + }, + stub: true, + unknownOption: 1, +}) +`, + }, + }) + + dirs.example = await fixture('.temp-legacy/example', { config: false }) + dirs.exampleEjected = await fixture('.temp-legacy/example-ejected') + dirs.withField = await fixture('.temp-legacy/with-field', { config: 'export default {\n plugins: [builder()],\n}\n', pkg: pkg => ({ ...pkg, build: { entries: ['./src/utils'] } }) }) + dirs.withFile = await fixture('.temp-legacy/with-file', { config: 'export default {\n plugins: [builder()],\n}\n', files: { 'build.config.ts': 'export default {}\n' } }) + + await Promise.all([ + step('buildConfig', cli(['build', dirs.buildConfig], { CI: '' })), + step('buildConfigEjected', tsdown(dirs.buildConfigEjected)), + step('replace', cli(['build', dirs.replace])), + step('replaceEjected', tsdown(dirs.replaceEjected)), + step('unsupported', cli(['build', dirs.unsupported])), + step('example', cli(['build', dirs.example])), + step('exampleEjected', tsdown(dirs.exampleEjected)), + step('withField', cli(['build', dirs.withField])), + step('withField:prepare', cli(['prepare', dirs.withField])), + step('withFile', tsdown(dirs.withFile)), + ]) + }, 300_000) + + it('should build `build.config.ts` entries under the names unbuild gave them, alongside the `build` field of `package.json`', async () => { + expectBuilt('buildConfig') + expect((await listFiles(join(dirs.buildConfig!, 'dist'))).filter(file => !file.startsWith('runtime'))).toMatchInlineSnapshot(` + [ + "content.d.mts", + "content.mjs", + "features", + "features/flag.d.ts", + "features/flag.js", + "module.d.mts", + "module.json", + "module.mjs", + "nested", + "nested/helper.d.mts", + "nested/helper.mjs", + "shared", + "shared/format.d.mts", + "shared/format.mjs", + "types.d.mts", + "utils.d.mts", + "utils.mjs", + "vite.d.mts", + "vite.mjs", + ] + `) + }) + + it('should import runtime code relative to nested entries', async () => { + const helper = await read(dirs.buildConfig!, 'dist/nested/helper.mjs') + expect(findStaticImports(helper).map(i => i.specifier)).toEqual(['../runtime/plugins/plugin.js']) + expect(helper).toContain('import("../runtime/composables/useWrappedFetch.js")') + expect(helper).not.toContain(dirs.buildConfig) + }) + + it('should run `build.config.ts` hooks in order with the build context', async () => { + const log = (await read(dirs.buildConfig!, 'hooks.log')).trim().split('\n').map(line => JSON.parse(line)) + expect(log.slice(0, 3)).toEqual([ + expect.objectContaining({ hook: 'build:before', stub: false }), + expect.objectContaining({ hook: 'rollup:done', stub: false, meta: true }), + expect.objectContaining({ hook: 'build:done', stub: false, meta: true }), + ]) + expect(log[0].entries).toEqual(['content', 'features', 'module', 'nested/helper', 'runtime', 'shared', 'utils', 'vite']) + expect(await read(dirs.buildConfig!, 'dist/vite.mjs')).toContain('from build:before') + }) + + it('should keep `build.config.ts` externals external and apply its replacements', async () => { + const vite = await read(dirs.buildConfig!, 'dist/vite.mjs') + expect(vite).toContain('from "fake-pkg/sub"') + expect(vite).toContain('from "regex-pkg"') + expect(vite).toContain('"1.2.3"') + expect(vite).not.toContain('__MODULE_VERSION__') + const content = await read(dirs.buildConfig!, 'dist/content.mjs') + expect(content).toContain('from "#content-alias/config"') + expect(vite + content).not.toContain('bundled-') + }) + + it('should warn that `build.config.ts` is deprecated', () => { + const output = expectBuilt('buildConfig') + expect(output).toMatch(new RegExp(`\`?build\\.config\\.ts\`? is deprecated\\. Its options are still applied\\. Move them into \`?builder\\(\\)\`? in \`?tsdown\\.config\\.ts\`?\\. ${guide('moving-from-buildconfigts')}`)) + expect(output).not.toMatch(/`?unbuild`? field/) + }) + + it('should read the `unbuild` field of `package.json` in preference to `build`, with the replacements of `rollup.replace`', async () => { + expectBuilt('replace') + const unplugin = await read(dirs.replace!, 'dist/unplugin.mjs') + expect(unplugin).toContain('from "ext-pkg"') + expect(unplugin).not.toContain('bundled-ext-pkg') + expect(unplugin).not.toContain('--uiDev') + expect(unplugin).toMatch(/isDev = false/) + expect(exists(dirs.replace!, 'dist/utils.mjs')).toBe(false) + }) + + it('should fail on every `build.config.ts` option without an equivalent', () => { + const output = expectFailed('unsupported') + for (const option of ['entries[0].ext', 'entries[1].builder: \'untyped\'', 'hooks[\'build:prepare\']', 'hooks[\'rollup:options\']', 'rollup.emitCJS: true', 'rollup.alias', 'stub', 'unknownOption']) { + expect(output).toContain(`build.config.ts: ${option}`) + } + expect(output).not.toContain('build.config.ts: hooks[\'mkdist:entry:options\']') + expect(output).toContain(`build.config.ts: rollup.emitCJS: true (${guide('commonjs-output')})`) + expect(output).toContain(guide('unsupported-build-options')) + }) + + it('should build the same `dist` as `tsdown` with `builder()` and the same options', async () => { + for (const [legacy, ejected] of [['example', 'exampleEjected'], ['buildConfig', 'buildConfigEjected'], ['replace', 'replaceEjected']] as const) { + expectBuilt(legacy) + expectBuilt(ejected) + const built = await hashes(join(dirs[legacy]!, 'dist')) + expect(Object.keys(built), legacy).toContain('module.json') + expect(await hashes(join(dirs[ejected]!, 'dist')), legacy).toEqual(built) + } + }) + + it('should fail when `package.json` or `build.config.ts` configures the build alongside `builder()`', () => { + for (const name of ['withField', 'withField:prepare']) { + expect(expectFailed(name), name).toContain('The `build` field of `package.json` configures the build, and so does `builder()` in the tsdown config.') + } + expect(expectFailed('withFile')).toContain(`\`build.config.ts\` configures the build, and so does \`builder()\` in the tsdown config. Move its options into \`builder()\` and delete the file. ${guide('moving-from-buildconfigts')}`) + }) +}) diff --git a/test/setup.ts b/test/setup.ts new file mode 100644 index 00000000..0fa88708 --- /dev/null +++ b/test/setup.ts @@ -0,0 +1,12 @@ +import { rm } from 'node:fs/promises' +import { fileURLToPath } from 'node:url' + +const slotsDir = fileURLToPath(new URL('../.temp-slots', import.meta.url)) + +export async function setup() { + await rm(slotsDir, { recursive: true, force: true }) +} + +export async function teardown() { + await rm(slotsDir, { recursive: true, force: true }) +} diff --git a/test/rolldown.spec.ts b/test/transpile-dir.spec.ts similarity index 88% rename from test/rolldown.spec.ts rename to test/transpile-dir.spec.ts index 7959497b..f9d3ef87 100644 --- a/test/rolldown.spec.ts +++ b/test/transpile-dir.spec.ts @@ -8,7 +8,7 @@ import { afterAll, beforeAll, describe, expect, it } from 'vitest' import { emptyEntry, transpileDir } from '../src/rolldown/index.ts' import type { ExternalImport } from '../src/rolldown/index.ts' -const root = fileURLToPath(new URL('../.temp-rolldown-plugin', import.meta.url)) +const root = fileURLToPath(new URL('../.temp-transpile-dir', import.meta.url)) const cwd = join(root, 'project') const dist = join(cwd, 'dist') const listFiles = async (dir: string) => (await readdir(dir, { recursive: true })).map(file => file.replaceAll('\\', '/')) @@ -89,31 +89,48 @@ describe('transpileDir', () => { await mkdir(join(root, file, '..'), { recursive: true }) await writeFile(join(root, file), contents) } - const options = { cwd, config: false, entry: ['src/index.ts'], format: 'esm', dts: false, report: false } satisfies Parameters[0] - await build({ - ...options, - outDir: dist, - plugins: [transpileDir({ - srcDir: 'src/lib', - outBase: 'lib', - resolveExternal(specifier, _importer, { kind, file }) { - externals.push([specifier, kind, file.slice(root.length)]) - return { mirror: kind } - }, - })], - }) - await build({ - ...options, - entry: emptyEntry, - outDir: join(cwd, 'dist-raw'), - plugins: [transpileDir({ - srcDir: 'src/lib', - exclude: ['**/*.spec.ts', '**/Other.vue'], - declaration: false, - stylesheets: false, - })], - }) - }, 120_000) + const options = { cwd, config: false, entry: emptyEntry, format: 'esm', dts: false, report: false } satisfies Parameters[0] + const automatic = { runtime: 'automatic', importSource: 'vue' } as const + await Promise.all([ + build({ + ...options, + entry: ['src/index.ts'], + outDir: dist, + plugins: [transpileDir({ + srcDir: 'src/lib', + outBase: 'lib', + resolveExternal(specifier, _importer, { kind, file }) { + externals.push([specifier, kind, file.slice(root.length)]) + return { mirror: kind } + }, + })], + }), + build({ + ...options, + outDir: join(cwd, 'dist-raw'), + plugins: [transpileDir({ + srcDir: 'src/lib', + exclude: ['**/*.spec.ts', '**/Other.vue'], + declaration: false, + stylesheets: false, + })], + }), + build({ + ...options, + outDir: join(cwd, 'dist-jsx'), + plugins: [ + transpileDir({ srcDir: 'src/lib', outBase: 'preserved', include: ['components/Button.tsx'], extension: 'mjs' }), + transpileDir({ srcDir: 'src/lib', outBase: 'compiled', include: ['components/Button.tsx'], declaration: false, jsx: automatic }), + transpileDir({ srcDir: 'src/lib', outBase: 'mixed', include: ['index.ts', 'components/*.tsx'], declaration: false, jsx: file => file.endsWith('Button.tsx') ? automatic : 'preserve' }), + ], + }), + build({ + ...options, + outDir: join(cwd, 'dist-maps'), + plugins: [transpileDir({ srcDir: 'src/lib', outBase: 'lib', include: ['lazy.ts'], declaration: false, sourcemap: true })], + }), + ]) + }) afterAll(async () => { await rm(root, { recursive: true, force: true }) @@ -262,21 +279,6 @@ describe('transpileDir', () => { it('should compile JSX with the `jsx` option, per file when it is a function', async () => { const outDir = join(cwd, 'dist-jsx') - const automatic = { runtime: 'automatic', importSource: 'vue' } as const - await build({ - cwd, - config: false, - entry: emptyEntry, - format: 'esm', - dts: false, - report: false, - outDir, - plugins: [ - transpileDir({ srcDir: 'src/lib', outBase: 'preserved', include: ['components/Button.tsx'], extension: 'mjs' }), - transpileDir({ srcDir: 'src/lib', outBase: 'compiled', include: ['components/Button.tsx'], declaration: false, jsx: automatic }), - transpileDir({ srcDir: 'src/lib', outBase: 'mixed', include: ['index.ts', 'components/*.tsx'], declaration: false, jsx: file => file.endsWith('Button.tsx') ? automatic : 'preserve' }), - ], - }) expect((await listFiles(outDir)).filter(file => file.includes('.')).sort()).toEqual([ 'compiled/components/Button.js', 'mixed/components/Button.js', @@ -293,16 +295,6 @@ describe('transpileDir', () => { it('should emit a source map next to each script that links back to its source', async () => { const outDir = join(cwd, 'dist-maps') - await build({ - cwd, - config: false, - entry: emptyEntry, - format: 'esm', - dts: false, - report: false, - outDir, - plugins: [transpileDir({ srcDir: 'src/lib', outBase: 'lib', include: ['lazy.ts'], declaration: false, sourcemap: true })], - }) const code = await readFile(join(outDir, 'lib/lazy.js'), 'utf8') expect(code.trimEnd().split('\n').at(-1)).toBe('//# sourceMappingURL=lazy.js.map') const map = JSON.parse(await readFile(join(outDir, 'lib/lazy.js.map'), 'utf8')) diff --git a/test/tsdown-cli.spec.ts b/test/tsdown-cli.spec.ts deleted file mode 100644 index e68d7215..00000000 --- a/test/tsdown-cli.spec.ts +++ /dev/null @@ -1,157 +0,0 @@ -import { existsSync } from 'node:fs' -import { appendFile, mkdir, readFile, rm, writeFile } from 'node:fs/promises' -import { pathToFileURL } from 'node:url' -import { join } from 'pathe' -import { exec } from 'tinyexec' -import { describe, expect, it } from 'vitest' - -import { guide } from '../src/build/guide.ts' -import { builderImport, copyExample, repoRoot } from './utils.ts' - -describe('builder', () => { - describe('with `nuxt-module-build`', () => { - const cli = (args: string[]) => exec('pnpm', ['nuxt-module-build', ...args], { nodeOptions: { cwd: repoRoot, env: { ...process.env, NUXT_TELEMETRY_DISABLED: '1' } } }) - const options = (outDir: string) => `{ entries: [{ input: './src/utils', name: 'helpers' }, { input: 'src/shared/', outDir: '${outDir}/shared' }] }` - const exportShapes = { - object: `export default {\n plugins: [builder(${options('dist')})],\n}\n`, - array: `export default [\n { entry: { cli: 'src/cli.ts' }, outDir: 'dist-cli', dts: false },\n { plugins: [builder(${options('out')})], outDir: 'out' },\n]\n`, - function: `export default (_, { watch: { restart } }) => ({\n plugins: [Promise.resolve(builder(${options('dist')}))],\n})\n`, - } - const outDirs = { object: 'dist', array: 'out', function: 'dist' } - - const copyWithShape = async (shape: keyof typeof exportShapes) => { - const dir = await copyExample(`.temp-tsdown-${shape}-export`, exportShapes[shape]) - await rm(join(dir, '.nuxt'), { recursive: true, force: true }) - await mkdir(join(dir, 'src/shared'), { recursive: true }) - await writeFile(join(dir, 'src/shared/value.ts'), `export { other } from './other.ts'\n`) - await writeFile(join(dir, 'src/shared/other.ts'), `export const other: string = 'other'\n`) - await writeFile(join(dir, 'src/cli.ts'), `export const cli: string = 'cli'\n`) - await appendFile(join(dir, 'src/module.ts'), `export { other } from './shared/value.ts'\n`) - return dir - } - - it.each(Object.keys(exportShapes) as Array)('should prepare and build a module whose tsdown config exports %s', async (shape) => { - const dir = await copyWithShape(shape) - const outDir = join(dir, outDirs[shape]) - - const prepared = await cli(['prepare', dir]) - expect(prepared.stdout + prepared.stderr).not.toContain('ERROR') - expect(prepared.exitCode).toBe(0) - expect(existsSync(join(dir, '.nuxt/tsconfig.json'))).toBe(true) - expect(existsSync(join(dir, '.nuxt/module-builder/types.d.mts'))).toBe(true) - - const built = await cli(['build', dir]) - expect(built.exitCode).toBe(0) - expect(await readFile(join(outDir, 'shared/value.mjs'), 'utf-8')).toContain(`from "./other.mjs"`) - expect(existsSync(join(outDir, 'helpers.mjs'))).toBe(true) - expect(existsSync(join(outDir, 'types.d.mts'))).toBe(true) - expect(JSON.parse(await readFile(join(outDir, 'module.json'), 'utf-8'))).toMatchObject({ name: 'my-module' }) - if (shape === 'array') { - expect(await readFile(join(dir, 'dist-cli/cli.mjs'), 'utf-8')).toContain(`const cli = "cli"`) - } - }) - - it('should build with the tsdown config\'s `outDir` and `sourcemap` unless `--outDir` and `--sourcemap` override them', async () => { - const dir = await copyExample('.temp-tsdown-build-flags', `export default {\n outDir: 'out',\n sourcemap: true,\n plugins: [builder()],\n}\n`) - expect((await cli(['build', dir])).exitCode).toBe(0) - expect(existsSync(join(dir, 'out/module.mjs.map'))).toBe(true) - expect(existsSync(join(dir, 'out/runtime/plugins/plugin.js.map'))).toBe(true) - expect(existsSync(join(dir, 'dist'))).toBe(false) - - expect((await cli(['build', '--outDir', 'custom', '--no-sourcemap', dir])).exitCode).toBe(0) - expect(existsSync(join(dir, 'custom/module.json'))).toBe(true) - expect(existsSync(join(dir, 'custom/module.mjs.map'))).toBe(false) - expect(existsSync(join(dir, 'custom/runtime/plugins/plugin.js.map'))).toBe(false) - }) - - it('should refuse `hooks` in `builder()` and point at tsdown\'s own', async () => { - const dir = await copyExample('.temp-tsdown-builder-hooks', `export default {\n plugins: [builder({ hooks: { 'build:before': () => {} } })],\n}\n`) - for (const args of [['build'], ['prepare']]) { - const { exitCode, stdout, stderr } = await cli([...args, dir]) - expect(exitCode, args.join(' ')).not.toBe(0) - expect(stdout + stderr, args.join(' ')).toContain(`\`builder()\` does not take \`hooks\`. Use tsdown's own \`hooks\` in the tsdown config, or a plugin that emits extra files. ${guide('hooks-in-a-tsdown-config')}`) - } - }) - - it('should load the package root without tsdown, and point at installing it to build', async () => { - const dir = await copyExample('.temp-tsdown-without-tsdown', `export default {\n plugins: [builder({ entries: [{ input: './src/utils', name: 'helpers' }] })],\n}\n`) - const hook = join(dir, 'no-tsdown.mjs') - await writeFile(hook, `import { registerHooks } from 'node:module'\n\nregisterHooks({\n resolve(specifier, context, nextResolve) {\n if (/^(?:tsdown|rolldown)(?:\\/|$)/.test(specifier)) {\n throw Object.assign(new Error(\`Cannot find package '\${specifier}'\`), { code: 'ERR_MODULE_NOT_FOUND' })\n }\n return nextResolve(specifier, context)\n },\n})\n`) - const node = (args: string[]) => exec('node', ['--import', pathToFileURL(hook).href, ...args], { nodeOptions: { cwd: dir } }) - - const root = await node(['--input-type=module', '-e', `await import('tsdown').then(() => console.log('tsdown found'), () => {})\nconst root = await import(${JSON.stringify(pathToFileURL(join(repoRoot, 'src/index.ts')).href)})\nconsole.log(Object.keys(root).sort().join(','))`]) - expect(root.stdout.trim()).toBe('build,defineBuildConfig,prepare') - - const built = await node([join(repoRoot, 'src/cli.ts'), 'build', dir]) - expect(built.exitCode).not.toBe(0) - expect(built.stdout + built.stderr).toContain(guide('install-tsdown')) - }) - - it('should fail on `--stub` and point at what replaces it', async () => { - const dir = await copyExample('.temp-tsdown-stub-flag', `export default {\n plugins: [builder()],\n}\n`) - for (const command of ['build', 'prepare']) { - const { exitCode, stdout, stderr } = await cli([command, '--stub', dir]) - expect(exitCode, command).not.toBe(0) - expect(stdout + stderr, command).toContain(`\`nuxt-module-build ${command} --stub\` has been removed. With pnpm or Yarn 4, point \`package.json\` at the module's sources. Otherwise, build \`dist\` with \`tsdown\` and rebuild it with \`tsdown --watch\`. ${guide('stub-builds')}`) - } - expect(existsSync(join(dir, 'dist'))).toBe(false) - }) - - it('should fail to prepare with a tsdown config whose `cwd` is another directory', async () => { - const dir = await copyExample('.temp-tsdown-config-cwd', `export default {\n cwd: './elsewhere',\n plugins: [builder()],\n}\n`) - const { exitCode, stdout, stderr } = await cli(['prepare', dir]) - expect(exitCode).not.toBe(0) - expect(stdout + stderr).toContain('`tsdown.config.ts` sets `cwd`, but `prepare` reads the module in the directory of the tsdown config.') - await writeFile(join(dir, 'tsdown.config.ts'), `${builderImport}\nexport default {\n cwd: '.',\n plugins: [builder()],\n}\n`) - expect((await cli(['prepare', dir])).exitCode).toBe(0) - }) - - it('should fail on a tsdown config that Node cannot load', async () => { - const dir = await copyExample('.temp-tsdown-config-enum', `enum Mode { Build }\nexport default {\n define: { __MODE__: String(Mode.Build) },\n plugins: [builder()],\n}\n`) - for (const args of [['build'], ['prepare']]) { - const { exitCode, stdout, stderr } = await cli([...args, dir]) - expect(exitCode, args.join(' ')).not.toBe(0) - expect(stdout + stderr, args.join(' ')).toContain('tsdown.config.ts:2:1: `enum` (use an `as const` object and a union type of its values)') - expect(stdout + stderr, args.join(' ')).toContain(guide('module-code-loads-with-node')) - } - }) - - it('should fail on a tsdown config without `builder()` and show how to add it', async () => { - const dir = await copyExample('.temp-tsdown-without-plugin', `export default {}\n`) - for (const args of [['build'], ['prepare']]) { - const { exitCode, stdout, stderr } = await cli([...args, dir]) - expect(exitCode, args.join(' ')).not.toBe(0) - expect(stdout + stderr, args.join(' ')).toContain([ - '`tsdown.config.ts` does not build the module with `builder()`. Add the plugin:', - '', - ` import { builder } from '@nuxt/module-builder/tsdown'`, - ` import { defineConfig } from 'tsdown'`, - '', - ` export default defineConfig({`, - ` plugins: [builder()],`, - ` })`, - ].join('\n')) - expect(stdout + stderr, args.join(' ')).toContain(guide('tsdown-config')) - } - }) - - it('should fail when no config of the tsdown config uses `builder()`', async () => { - const dir = await copyExample('.temp-tsdown-entries-only', `export default [{ entry: { utils: 'src/utils.ts' }, dts: false }]\n`) - const { exitCode, stdout, stderr } = await cli(['build', dir]) - expect(exitCode).not.toBe(0) - expect(stdout + stderr).toContain('`tsdown.config.ts` does not build the module with `builder()`.') - expect(existsSync(join(dir, 'dist'))).toBe(false) - }) - - it('should fail when `package.json` configures the build too', async () => { - const dir = await copyExample('.temp-tsdown-legacy-field', `export default {\n plugins: [builder()],\n}\n`) - const pkgPath = join(dir, 'package.json') - await writeFile(pkgPath, JSON.stringify({ ...JSON.parse(await readFile(pkgPath, 'utf-8')), build: { entries: ['./src/utils'] } })) - for (const args of [['build'], ['prepare']]) { - const { exitCode, stdout, stderr } = await cli([...args, dir]) - expect(exitCode, args.join(' ')).not.toBe(0) - expect(stdout + stderr, args.join(' ')).toContain('The `build` field of `package.json` configures the build, and so does `builder()` in the tsdown config.') - } - }) - }) -}) diff --git a/test/tsdown-references.spec.ts b/test/tsdown-references.spec.ts deleted file mode 100644 index 4ff64c22..00000000 --- a/test/tsdown-references.spec.ts +++ /dev/null @@ -1,305 +0,0 @@ -import { existsSync } from 'node:fs' -import { appendFile, mkdir, readFile, rm, symlink, writeFile } from 'node:fs/promises' -import { dirname, join } from 'pathe' -import { exec } from 'tinyexec' -import { describe, expect, it } from 'vitest' - -import { builderImport, copyExample, exampleDir, repoRoot, tsdown } from './utils.ts' - -describe('with a root tsconfig that only lists references', () => { - const references = (node: string) => ({ - files: [], - exclude: ['dist', 'node_modules', 'playground'], - references: [node, './.nuxt/tsconfig.app.json', './.nuxt/tsconfig.server.json', './.nuxt/tsconfig.shared.json'].map(path => ({ path })), - }) - - it('should generate tsconfigs for the module entry, without the playground or the workspace, and with app aliases for module code', async () => { - const dir = await copyExample('.temp-tsdown-references-prepare', 'export default { plugins: [builder()] }\n') - await writeFile(join(dir, 'tsconfig.json'), JSON.stringify({ extends: './tsconfig.options.json', files: [], references: [{ path: './tsconfig.module.json' }] })) - await writeFile(join(dir, 'tsconfig.options.json'), JSON.stringify({ compilerOptions: { types: ['vitest/importMeta'] }, exclude: ['dist', 'node_modules', 'playground'] })) - await writeFile(join(dir, 'tsconfig.module.json'), JSON.stringify({ extends: './tsconfig.base.json' })) - await writeFile(join(dir, 'tsconfig.base.json'), JSON.stringify({ extends: './.nuxt/tsconfig.node' })) - await rm(join(dir, '.nuxt'), { recursive: true, force: true }) - expect((await exec('node', [join(repoRoot, 'src/cli.ts'), 'prepare', dir], { nodeOptions: { env: { ...process.env, NUXT_TELEMETRY_DISABLED: '1' } } })).exitCode).toBe(0) - const generated = async (name: string) => JSON.parse(await readFile(join(dir, `.nuxt/tsconfig.${name}.json`), 'utf-8')) - const [node, app] = [await generated('node'), await generated('app')] - expect(node.include).toContain('../src/*.ts') - expect(node.compilerOptions.paths['#app']).toBeDefined() - expect(node.compilerOptions.types).toContain('vitest/importMeta') - expect(node.compilerOptions.paths['#components']).toBeDefined() - expect(app.exclude).toContain('../playground') - expect(app.include).not.toContain('../../**/*') - expect(app.include).toContain('../src/runtime') - for (const name of ['app', 'node', 'server', 'shared']) { - const { include, exclude } = await generated(name) - expect([...include, ...exclude].filter((pattern: string) => pattern.startsWith('../src/dist')), name).toEqual([]) - } - await rm(dir, { recursive: true, force: true }) - }) - - it('should type runtime components with their own context and pass the type check', async () => { - const dir = await copyExample('.temp-tsdown-references-contexts', 'export default { plugins: [builder()] }\n') - const moduleSrc = join(dir, 'src/module.ts') - await writeFile(moduleSrc, (await readFile(moduleSrc, 'utf-8')) - .replace('import { defineNuxtModule, addPlugin, createResolver } from \'@nuxt/kit\'', 'import { defineNuxtModule, addPlugin, addImports, addTemplate, addTypeTemplate, createResolver } from \'@nuxt/kit\'\nimport { moduleHelper } from \'./helpers/name.ts\'') - .replace(' addPlugin(resolver.resolve(\'./runtime/plugins/plugin\'))', ' addPlugin(resolver.resolve(\'./runtime/plugins/plugin\'))\n _nuxt.options.alias[\'#my-types\'] = resolver.resolve(\'./runtime/types\')\n addImports({ name: \'useThing\', from: resolver.resolve(\'./runtime/composables/useThing\') })\n addTypeTemplate({ filename: \'module/my-module-names.d.ts\', getContents: () => \'declare module "#my-module/names" {\\n export const names: string[]\\n}\\n\' }, { nuxt: false })\n _nuxt.hook(\'prepare:types\', ({ tsConfig }) => { tsConfig.include?.push(\'./module/my-module-names.d.ts\') })\n addTemplate({ filename: \'my-module-virtual.mjs\', getContents: () => \'export default 1\\n\' })\n moduleHelper()')) - await mkdir(join(dir, 'src/helpers'), { recursive: true }) - await mkdir(join(dir, 'src/runtime/types'), { recursive: true }) - await mkdir(join(dir, 'src/runtime/server'), { recursive: true }) - await mkdir(join(dir, 'test/fixture'), { recursive: true }) - await mkdir(join(dir, 'types'), { recursive: true }) - await Promise.all([ - writeFile(join(dir, 'types/virtual.d.ts'), `declare module '#my-root-virtual' {\n export const rootValue: string\n}\n`), - writeFile(join(dir, 'content.d.ts'), `export * from './dist/content'\n`), - writeFile(join(dir, 'src/helpers/name.ts'), `import { useNuxt } from '@nuxt/kit'\n\nexport type { Linked } from '../runtime/linked.ts'\nexport type Jsx = typeof import('../runtime/components/JsxComponent.tsx').default\nexport type Names = ReturnType\n\nexport function moduleHelper(): unknown {\n return import.meta.vitest ? undefined : useNuxt().options.myModule\n}\n\nexport const callInit = (): unknown => useNuxt().callHook('my-module:init', 'shared-type')\n`), - writeFile(join(dir, 'src/runtime/composables/useVirtual.ts'), `import value from '#build/my-module-virtual'\n\nexport const useVirtual = (): unknown => value\n`), - writeFile(join(dir, 'src/runtime/composables/useNames.ts'), `import { names } from '#my-module/names'\n\nexport const useNames = (): string[] => names\n`), - writeFile(join(dir, 'src/runtime/linked.ts'), `import type { NuxtLink } from '#components'\n\nexport type Linked = typeof NuxtLink\n`), - writeFile(join(dir, 'src/env.d.ts'), `declare const __MY_MODULE_FLAG__: boolean\n`), - writeFile(join(dir, 'ambient.d.ts'), `declare module '#my-virtual' {\n export const virtualValue: string\n}\n`), - writeFile(join(dir, 'src/runtime/server/virtual.ts'), `import { virtualValue } from '#my-virtual'\nimport { rootValue } from '#my-root-virtual'\n\nexport const value: string = import.meta.vitest ? '' : virtualValue + rootValue\n`), - writeFile(join(dir, 'src/augments.d.ts'), `declare module '#app' {\n interface NuxtApp {\n $thing: 'thing'\n }\n}\n\nexport {}\n`), - writeFile(join(dir, 'src/runtime/composables/useAppThing.ts'), `import { useNuxtApp } from '#app'\n\nexport const useAppThing = (): 'thing' | undefined => import.meta.vitest ? undefined : useNuxtApp().$thing\n`), - writeFile(join(dir, 'src/runtime/types/index.ts'), `export type Trigger = 'onNuxtReady' | string[] | boolean\n`), - writeFile(join(dir, 'src/runtime/composables/useThing.ts'), `export function useThing() {\n return { loggedIn: __MY_MODULE_FLAG__, user: null as { name: string } | null }\n}\n`), - writeFile(join(dir, 'src/runtime/components/Triggered.vue'), `\n\n\n`), - writeFile(join(dir, 'src/runtime/components/ThingState.vue'), `\n\n\n`), - writeFile(join(dir, 'test/fixture/nuxt.config.ts'), `export default defineNuxtConfig({})\n`), - writeFile(join(dir, 'tsconfig.json'), JSON.stringify({ - files: [], - compilerOptions: { types: ['vitest/importMeta'] }, - exclude: ['dist', 'node_modules', 'playground'], - references: ['./.nuxt/tsconfig.app.json', './.nuxt/tsconfig.server.json', './.nuxt/tsconfig.shared.json', './.nuxt/tsconfig.node.json'].map(path => ({ path })), - })), - ]) - await rm(join(dir, '.nuxt'), { recursive: true, force: true }) - const built = await tsdown(dir) - expect(built.exitCode, built.stdout + built.stderr).toBe(0) - expect(built.stdout + built.stderr).not.toContain('type error') - expect(await readFile(join(dir, 'dist/runtime/components/ThingState.d.vue.ts'), 'utf-8')).toMatch(/loggedIn: boolean;\s+user: \{\s+name: string;\s+\} \| null;/) - expect(await readFile(join(dir, 'dist/runtime/components/Triggered.vue'), 'utf-8')).toMatch(/type: \[\s*String,\s*Array,\s*Boolean\s*\]/) - const generated = async (name: string) => JSON.parse(await readFile(join(dir, `.nuxt/tsconfig.${name}.json`), 'utf-8')) - for (const name of ['app', 'node', 'server', 'shared']) { - const config = await generated(name) - expect(config.files, name).toEqual(expect.arrayContaining([join(dir, 'src/env.d.ts'), join(dir, 'ambient.d.ts'), join(dir, 'types/virtual.d.ts')])) - expect(config.files, name).not.toContain(join(dir, 'src/augments.d.ts')) - expect(config.compilerOptions.types, name).toContain('vitest/importMeta') - } - for (const name of ['nuxt', 'nuxt.node']) { - expect(await readFile(join(dir, `.nuxt/${name}.d.ts`), 'utf-8'), name).toContain('/// ') - } - expect(await readFile(join(dir, '.nuxt/nuxt.shared.d.ts'), 'utf-8')).not.toContain('augments.d.ts') - expect(await readFile(join(dir, '.nuxt/nuxt.node.d.ts'), 'utf-8')).toContain('/// ') - const buildTypes = (await readFile(join(dir, '.nuxt/types/build.d.ts'), 'utf-8')).split('\n') - expect(buildTypes).toContain('declare module "#build/my-module-virtual";') - expect(buildTypes).not.toContain('declare module "#build/my-module-virtual.mjs";') - const app = await generated('app') - expect(app.include).not.toContain('../**/*') - const typecheck = await exec(join(repoRoot, 'node_modules/.bin/vue-tsc'), ['-b', '--noEmit'], { nodeOptions: { cwd: dir } }) - expect(typecheck.stdout + typecheck.stderr).toBe('') - await rm(dir, { recursive: true, force: true }) - }, 240 * 1000) - - it('should give tsdown the project that includes the module entry, unless the config sets `tsconfig`', async () => { - const dir = await copyExample('.temp-tsdown-references', 'export default { plugins: [builder()] }\n') - await writeFile(join(dir, 'tsconfig.module.json'), JSON.stringify({ extends: './.nuxt/tsconfig.node.json', compilerOptions: { erasableSyntaxOnly: true, useDefineForClassFields: false } })) - await writeFile(join(dir, 'tsconfig.override.json'), JSON.stringify({ extends: './.nuxt/tsconfig.node.json', compilerOptions: { useDefineForClassFields: true } })) - await writeFile(join(dir, 'tsconfig.json'), JSON.stringify(references('./tsconfig.module.json'))) - await appendFile(join(dir, 'src/module.ts'), `\nclass Fields { value!: string }\nexport const ownsField: boolean = Object.hasOwn(new Fields(), 'value')\n`) - const ownsField = async () => (await readFile(join(dir, 'dist/module.mjs'), 'utf-8')).includes('\tvalue;') - const result = await tsdown(dir, [], { CI: '' }) - expect(result.exitCode, result.stdout + result.stderr).toBe(0) - expect(result.stdout).toContain('tsconfig: tsconfig.module.json') - expect(result.stdout).toMatch(/Set `?isolatedDeclarations: true`? in `?tsconfig\.module\.json`?/) - expect(await ownsField()).toBe(false) - const referencesDist = await readFile(join(dir, 'dist/module.d.mts'), 'utf-8') - - await writeFile(join(dir, 'tsdown.config.ts'), `${builderImport}\nexport default { tsconfig: 'tsconfig.override.json', plugins: [builder()] }\n`) - expect((await tsdown(dir)).stdout).toContain('tsconfig: tsconfig.override.json') - expect(await ownsField()).toBe(true) - - await writeFile(join(dir, 'tsdown.config.ts'), `${builderImport}\nexport default { plugins: [builder()] }\n`) - await writeFile(join(dir, 'tsconfig.json'), JSON.stringify({ extends: './.nuxt/tsconfig.json', exclude: ['dist', 'node_modules', 'playground'] })) - const legacy = await tsdown(dir) - expect(legacy.exitCode).toBe(0) - expect(legacy.stdout).toContain('tsconfig: tsconfig.json') - expect(await readFile(join(dir, 'dist/module.d.mts'), 'utf-8')).toBe(referencesDist) - await rm(dir, { recursive: true, force: true }) - }) - - it('should resolve the module\'s own package to declarations of module code in its app, server and shared tsconfigs', async () => { - const dir = await copyExample('.temp-tsdown-references-own-package', 'export default { plugins: [builder()] }\n') - const { exports, main, types, publishConfig } = JSON.parse(await readFile(join(exampleDir, 'package.json'), 'utf-8')) - const pkg = JSON.parse(await readFile(join(dir, 'package.json'), 'utf-8')) - await writeFile(join(dir, 'package.json'), JSON.stringify({ ...pkg, exports, main, types, publishConfig, imports: { '#my-helpers': './src/helpers.ts' } })) - await writeFile(join(dir, 'src/helpers.ts'), `export interface Helper {\n name: string\n}\n`) - await writeFile(join(dir, 'src/extra.d.ts'), `export interface Extra {\n id: string\n}\n`) - const moduleSrc = join(dir, 'src/module.ts') - await writeFile(moduleSrc, (await readFile(moduleSrc, 'utf-8')) - .replace('import { defineNuxtModule, addPlugin, createResolver } from \'@nuxt/kit\'', 'import { defineNuxtModule, addPlugin, addTypeTemplate, createResolver } from \'@nuxt/kit\'\n\nexport type { Helper } from \'#my-helpers\'\nexport type { Extra } from \'./extra\'') - .replace(' addPlugin(resolver.resolve(\'./runtime/plugins/plugin\'))', ' addPlugin(resolver.resolve(\'./runtime/plugins/plugin\'))\n addTypeTemplate({ filename: \'types/my-module.d.ts\', getContents: () => \'import type { ModuleOptions } from "my-module"\\ndeclare module "#app" {\\n interface NuxtApp {\\n $myModuleOptions: ModuleOptions\\n }\\n}\\nexport {}\\n\' })\n const configured: unknown = _nuxt.options.myModule\n void configured')) - await mkdir(join(dir, 'src/runtime/server'), { recursive: true }) - await mkdir(join(dir, 'shared'), { recursive: true }) - await writeFile(join(dir, 'shared/options.ts'), `import type { Extra, ModuleOptions } from 'my-module'\n\nexport const sharedApiKey = (options: ModuleOptions, extra: Extra): string => options.apiKey + extra.id\n// @ts-expect-error a string is not a number\nexport const extraId = (extra: Extra): number => extra.id\n`) - await writeFile(join(dir, 'src/runtime/composables/useUtils.ts'), `import { myModuleUtils } from 'my-module/utils'\n\nexport const useUtils = (): () => void => myModuleUtils\n`) - await writeFile(join(dir, 'src/runtime/server/options.ts'), `import type { ModuleOptions } from 'my-module'\n\nexport const apiKey = (options: ModuleOptions): string => options.apiKey\n`) - await writeFile(join(dir, 'tsconfig.json'), JSON.stringify(references('./.nuxt/tsconfig.node.json'))) - await rm(join(dir, '.nuxt'), { recursive: true, force: true }) - const prepared = await exec('node', [join(repoRoot, 'src/cli.ts'), 'prepare', dir], { nodeOptions: { env: { ...process.env, NUXT_TELEMETRY_DISABLED: '1' } } }) - expect(prepared.exitCode, prepared.stdout + prepared.stderr).toBe(0) - const typecheck = await exec(join(repoRoot, 'node_modules/.bin/vue-tsc'), ['-b', '--noEmit'], { nodeOptions: { cwd: dir } }) - expect(typecheck.stdout + typecheck.stderr).toBe('') - for (const name of ['app', 'server', 'shared']) { - const listed = await exec(join(repoRoot, 'node_modules/.bin/vue-tsc'), ['-p', `.nuxt/tsconfig.${name}.json`, '--noEmit', '--listFilesOnly'], { nodeOptions: { cwd: dir } }) - const files = listed.stdout.split('\n').map(file => file.trim()) - expect(files, name).not.toContain(join(dir, 'src/module.ts')) - expect(files, name).not.toContain(join(dir, 'src/utils.ts')) - expect(files, name).not.toContain(join(dir, 'src/helpers.ts')) - expect(files, name).toContain(join(dir, '.nuxt/module-builder/declarations/src/module.d.ts')) - } - const app = (await exec(join(repoRoot, 'node_modules/.bin/vue-tsc'), ['-p', '.nuxt/tsconfig.app.json', '--noEmit', '--listFilesOnly'], { nodeOptions: { cwd: dir } })).stdout - expect(app).toContain(join(dir, '.nuxt/module-builder/declarations/src/utils.d.ts')) - await rm(dir, { recursive: true, force: true }) - }) - - it('should write the declarations of module code with oxc when its tsconfig sets `isolatedDeclarations`', async () => { - const dir = await copyExample('.temp-tsdown-references-own-package-isolated', 'export default { plugins: [builder()] }\n') - await mkdir(join(dir, 'src/nested'), { recursive: true }) - await writeFile(join(dir, 'src/nested/payload.ts'), `export interface Payload {\n value: string\n}\n`) - await writeFile(join(dir, 'src/nested/shape.ts'), `export interface Shape {\n sides: number\n}\n`) - await writeFile(join(dir, 'src/utils.ts'), `export const myModuleUtils = (): void => {}\n`) - const pkg = JSON.parse(await readFile(join(dir, 'package.json'), 'utf-8')) - await writeFile(join(dir, 'package.json'), JSON.stringify({ ...pkg, imports: { '#payload': './src/nested/payload.ts' } })) - await writeFile(join(dir, 'src/module.ts'), [ - `import { defineNuxtModule } from '@nuxt/kit'`, - `import type { NuxtModule } from '@nuxt/schema'`, - `import type { Payload } from '#payload'`, - `import type { Shape } from './nested/shape.ts'`, - ``, - `export interface ModuleOptions {\n payload?: Payload\n shape?: Shape\n}`, - ``, - `const module: NuxtModule = defineNuxtModule({ meta: { name: 'my-module', configKey: 'myModule' } })`, - ``, - `export default module`, - ``, - ].join('\n')) - await writeFile(join(dir, 'src/runtime/composables/usePayload.ts'), `import type { ModuleOptions } from 'my-module'\n\nexport const usePayload = (options: ModuleOptions): string | undefined => options.payload?.value\n`) - await writeFile(join(dir, 'tsconfig.module.json'), JSON.stringify({ extends: './.nuxt/tsconfig.node.json', compilerOptions: { isolatedDeclarations: true, declaration: true, allowJs: false } })) - await writeFile(join(dir, 'tsconfig.json'), JSON.stringify(references('./tsconfig.module.json'))) - await rm(join(dir, '.nuxt'), { recursive: true, force: true }) - const prepared = await exec('node', [join(repoRoot, 'src/cli.ts'), 'prepare', dir], { nodeOptions: { env: { ...process.env, NUXT_TELEMETRY_DISABLED: '1' } } }) - expect(prepared.exitCode, prepared.stdout + prepared.stderr).toBe(0) - expect(prepared.stdout + prepared.stderr).not.toContain('The build reports the same errors') - expect(await readFile(join(dir, '.nuxt/module-builder/declarations/src/nested/payload.d.ts'), 'utf-8')).toContain('interface Payload') - const moduleDeclaration = await readFile(join(dir, '.nuxt/module-builder/declarations/src/module.d.ts'), 'utf-8') - expect(moduleDeclaration).toContain('from "./nested/payload.js"') - expect(moduleDeclaration).toContain('from "./nested/shape.js"') - const typecheck = await exec(join(repoRoot, 'node_modules/.bin/vue-tsc'), ['-b', '--noEmit'], { nodeOptions: { cwd: dir } }) - expect(typecheck.stdout + typecheck.stderr).toBe('') - const listed = await exec(join(repoRoot, 'node_modules/.bin/vue-tsc'), ['-p', '.nuxt/tsconfig.app.json', '--noEmit', '--listFilesOnly'], { nodeOptions: { cwd: dir } }) - expect(listed.stdout).toContain(join(dir, '.nuxt/module-builder/declarations/src/nested/payload.d.ts')) - expect(listed.stdout).not.toContain(join(dir, 'src/nested/payload.ts')) - expect(listed.stdout).not.toContain(join(dir, 'src/nested/shape.ts')) - await rm(dir, { recursive: true, force: true }) - }) - - it('should warn about a declaration error in module code at prepare, and write the other declarations', async () => { - const dir = await copyExample('.temp-tsdown-references-own-package-error', 'export default { plugins: [builder()] }\n') - const store = (name: string) => `node_modules/.pnpm/${name}@1.0.0/node_modules/${name}` - const files = { - [`${store('fake-logger')}/package.json`]: JSON.stringify({ name: 'fake-logger', type: 'module', exports: { '.': { types: './index.d.ts', default: './index.js' } } }), - [`${store('fake-logger')}/index.d.ts`]: `export interface LoggerInstance { log: (message: string) => void }\nexport declare function createLogger(): LoggerInstance\n`, - [`${store('fake-shared')}/package.json`]: JSON.stringify({ name: 'fake-shared', type: 'module', exports: { '.': { types: './index.d.ts', default: './index.js' } } }), - [`${store('fake-shared')}/index.d.ts`]: `import { createLogger } from 'fake-logger'\nexport declare function createModuleLogger(name: string): ReturnType\n`, - 'src/logger.ts': `import { createModuleLogger } from 'fake-shared'\n\nexport const logger = createModuleLogger('my-module')\n`, - } - for (const [file, contents] of Object.entries(files)) { - await mkdir(dirname(join(dir, file)), { recursive: true }) - await writeFile(join(dir, file), contents) - } - await symlink(join(dir, store('fake-logger')), join(dir, 'node_modules/.pnpm/fake-shared@1.0.0/node_modules/fake-logger')) - await symlink(join(dir, store('fake-shared')), join(dir, 'node_modules/fake-shared')) - await writeFile(join(dir, 'tsconfig.json'), JSON.stringify(references('./.nuxt/tsconfig.node.json'))) - const prepared = await exec('node', [join(repoRoot, 'src/cli.ts'), 'prepare', dir], { nodeOptions: { env: { ...process.env, NUXT_TELEMETRY_DISABLED: '1' } } }) - expect(prepared.exitCode, prepared.stdout + prepared.stderr).toBe(0) - expect(prepared.stdout + prepared.stderr).toContain('The build reports the same errors') - expect(prepared.stdout + prepared.stderr).toContain('src/logger.ts(3,14): error TS2883') - expect(existsSync(join(dir, '.nuxt/module-builder/declarations/src/module.d.ts'))).toBe(true) - expect(existsSync(join(dir, '.nuxt/module-builder/declarations/types.d.mts'))).toBe(true) - await rm(dir, { recursive: true, force: true }) - }) - - it('should keep `.nuxt/tsconfig.json` one program over the module\'s sources, with the generated tsconfigs adapted', async () => { - const dir = await copyExample('.temp-tsdown-references-legacy-prepare', 'export default { plugins: [builder()] }\n') - const moduleSrc = join(dir, 'src/module.ts') - await writeFile(moduleSrc, (await readFile(moduleSrc, 'utf-8')) - .replace('import { defineNuxtModule, addPlugin, createResolver } from \'@nuxt/kit\'', 'import { defineNuxtModule, addPlugin, addTypeTemplate, createResolver } from \'@nuxt/kit\'') - .replace(' addPlugin(resolver.resolve(\'./runtime/plugins/plugin\'))', ' addPlugin(resolver.resolve(\'./runtime/plugins/plugin\'))\n addTypeTemplate({ filename: \'types/my-module.d.ts\', getContents: () => \'import type { ModuleOptions } from "my-module"\\ndeclare module "#app" {\\n interface NuxtApp {\\n $myModuleOptions: ModuleOptions\\n }\\n}\\nexport {}\\n\' })\n const configured: unknown = _nuxt.options.myModule\n void configured\n void _nuxt.callHook(\'my-module:init\', \'shared-type\')')) - await mkdir(join(dir, 'src/runtime/server'), { recursive: true }) - await writeFile(join(dir, 'src/runtime/server/options.ts'), `export const apiKey = (options: { apiKey: string }): string => options.apiKey\n`) - await writeFile(join(dir, 'tsconfig.json'), JSON.stringify({ extends: './.nuxt/tsconfig.json', exclude: ['dist', 'node_modules', 'playground', 'tsdown.config.ts', 'nuxt.config.ts'] })) - await writeFile(join(dir, 'nuxt.config.ts'), `export default { buildDir: '.nuxt-custom' }\n`) - await rm(join(dir, '.nuxt'), { recursive: true, force: true }) - const prepared = await exec('node', [join(repoRoot, 'src/cli.ts'), 'prepare', dir], { nodeOptions: { env: { ...process.env, NUXT_TELEMETRY_DISABLED: '1' } } }) - expect(prepared.exitCode, prepared.stdout + prepared.stderr).toBe(0) - const generated = async (name: string) => JSON.parse(await readFile(join(dir, `.nuxt/${name}.json`), 'utf-8')) - expect((await generated('tsconfig.app')).compilerOptions.paths['my-module']).toEqual(['./module-builder/declarations/types.d.mts']) - const legacy = await generated('tsconfig') - expect(legacy.compilerOptions.paths['my-module']).toBeUndefined() - expect(legacy.include).not.toContain('./module-builder/declarations/types.d.mts') - expect(legacy.exclude).not.toContain('../src/runtime/server') - const typecheck = await exec(join(repoRoot, 'node_modules/.bin/vue-tsc'), ['--noEmit'], { nodeOptions: { cwd: dir } }) - expect(typecheck.stdout).not.toMatch(/error TS5\d{3}/) - expect(typecheck.stdout.split('\n').filter(line => /^(?:src|\.nuxt)\//.test(line))).toEqual([]) - const listed = await exec(join(repoRoot, 'node_modules/.bin/vue-tsc'), ['--noEmit', '--listFilesOnly'], { nodeOptions: { cwd: dir } }) - expect(listed.stdout).toContain(join(dir, 'src/module.ts')) - expect(listed.stdout).toContain(join(dir, 'src/runtime/server/options.ts')) - expect(listed.stdout).not.toContain(join(dir, '.nuxt/module-builder/declarations/src/module.d.ts')) - await rm(dir, { recursive: true, force: true }) - }) - - it('should name a dependency in runtime declarations by its package when only another part of the module imports it', async () => { - const dir = await copyExample('.temp-tsdown-references-portable', 'export default { plugins: [builder()] }\n') - const store = (name: string) => `node_modules/.pnpm/${name}@1.0.0/node_modules/${name}` - const files = { - [`${store('fake-logger')}/package.json`]: JSON.stringify({ name: 'fake-logger', type: 'module', exports: { '.': { types: './index.d.ts', default: './index.js' } } }), - [`${store('fake-logger')}/index.d.ts`]: `export interface LoggerInstance { log: (message: string) => void }\nexport declare function createLogger(): LoggerInstance\n`, - [`${store('fake-logger')}/index.js`]: `export const createLogger = () => ({ log: console.log })\n`, - [`${store('fake-shared')}/package.json`]: JSON.stringify({ name: 'fake-shared', type: 'module', exports: { '.': { types: './index.d.ts', default: './index.js' } } }), - [`${store('fake-shared')}/index.d.ts`]: `import { createLogger } from 'fake-logger'\nexport declare function createModuleLogger(name: string): ReturnType\n`, - [`${store('fake-shared')}/index.js`]: `import { createLogger } from 'fake-logger'\nexport const createModuleLogger = () => createLogger()\n`, - 'src/runtime/logger.ts': `import { createModuleLogger } from 'fake-shared'\n\nexport const logger = createModuleLogger('my-module')\n`, - 'src/runtime/server/log.ts': `import { createLogger } from 'fake-logger'\n\nexport const serverLogger = createLogger()\n`, - } - for (const [file, contents] of Object.entries(files)) { - await mkdir(dirname(join(dir, file)), { recursive: true }) - await writeFile(join(dir, file), contents) - } - await symlink(join(dir, store('fake-logger')), join(dir, 'node_modules/.pnpm/fake-shared@1.0.0/node_modules/fake-logger')) - for (const name of ['fake-logger', 'fake-shared']) { - await symlink(join(dir, store(name)), join(dir, 'node_modules', name)) - } - const pkg = JSON.parse(await readFile(join(dir, 'package.json'), 'utf-8')) - await writeFile(join(dir, 'package.json'), JSON.stringify({ ...pkg, dependencies: { ...pkg.dependencies, 'fake-logger': '1.0.0', 'fake-shared': '1.0.0' } })) - await writeFile(join(dir, 'tsconfig.json'), JSON.stringify(references('./.nuxt/tsconfig.node.json'))) - const built = await tsdown(dir) - expect(built.exitCode, built.stdout + built.stderr).toBe(0) - expect(await readFile(join(dir, 'dist/runtime/logger.d.ts'), 'utf-8')).toContain('import("fake-logger").LoggerInstance') - await rm(dir, { recursive: true, force: true }) - }) - - it('should transform each runtime file with the referenced project that includes it', async () => { - const dir = await copyExample('.temp-tsdown-references-transforms', 'export default { plugins: [builder()] }\n') - await mkdir(join(dir, 'src/runtime/server'), { recursive: true }) - const source = `class Fields { value!: string }\nexport const ownsField: boolean = Object.hasOwn(new Fields(), 'value')\n` - await writeFile(join(dir, 'src/runtime/fields.ts'), source) - await writeFile(join(dir, 'src/runtime/server/fields.ts'), source) - await writeFile(join(dir, 'tsconfig.server.json'), JSON.stringify({ extends: './.nuxt/tsconfig.server.json', compilerOptions: { useDefineForClassFields: false } })) - await writeFile(join(dir, 'tsconfig.json'), JSON.stringify(references('./.nuxt/tsconfig.node.json')).replace('./.nuxt/tsconfig.server.json', './tsconfig.server.json')) - const built = await tsdown(dir) - expect(built.exitCode, built.stdout + built.stderr).toBe(0) - expect(await readFile(join(dir, 'dist/runtime/fields.js'), 'utf-8')).toContain('\tvalue;') - expect(await readFile(join(dir, 'dist/runtime/server/fields.js'), 'utf-8')).not.toContain('value;') - await rm(dir, { recursive: true, force: true }) - }) -}) diff --git a/test/tsdown-watch.spec.ts b/test/tsdown-watch.spec.ts deleted file mode 100644 index 2648bff6..00000000 --- a/test/tsdown-watch.spec.ts +++ /dev/null @@ -1,316 +0,0 @@ -import { createHash } from 'node:crypto' -import { existsSync } from 'node:fs' -import { appendFile, 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 { exec } from 'tinyexec' -import { describe, expect, it } from 'vitest' - -import { builderImport, copyExample, repoRoot, tsdown, tsdownBin, waitFor, watch } from './utils.ts' - -describe('builder', () => { - it('should not keep more memory with each watched rebuild', async () => { - const dir = await copyExample('.temp-tsdown-watch-memory', '') - await rm(join(dir, 'tsdown.config.ts')) - const file = join(dir, 'src/runtime/composables/useWrappedFetch.ts') - await mkdir(join(dir, 'src/shared'), { recursive: true }) - await writeFile(join(dir, 'src/shared/format.ts'), `export const format = (value: string): string => value.trim()\n`) - await writeFile(join(dir, 'watch.mjs'), [ - `import { readFileSync, writeFileSync } from 'node:fs'`, - `import { build } from ${JSON.stringify(pathToFileURL(join(repoRoot, 'node_modules/tsdown/dist/index.mjs')).href)}`, - builderImport, - `const source = readFileSync(${JSON.stringify(file)}, 'utf8')`, - `let built, idle, started`, - `const settled = { name: 'settled', buildStart() { started = true; clearTimeout(idle) }, writeBundle: { order: 'post', handler() { idle = setTimeout(() => started && built(), 250) } } }`, - `const handle = await build({ cwd: ${JSON.stringify(dir)}, config: false, watch: true, logLevel: 'silent', plugins: [builder({ entries: [{ input: 'src/shared/', outDir: 'dist/shared' }] }), settled] })`, - `const heap = []`, - `for (let round = 0; round < 6; round++) {`, - ` await new Promise(resolve => { built = resolve; started = false; writeFileSync(${JSON.stringify(file)}, source + 'export const round = ' + round + '\\n') })`, - ` globalThis.gc()`, - ` heap.push(process.memoryUsage().heapUsed)`, - `}`, - `await handle.watch.close()`, - `console.log(JSON.stringify(heap))`, - `process.exit(0)`, - '', - ].join('\n')) - const { stdout, exitCode } = await exec('node', ['--expose-gc', 'watch.mjs'], { nodeOptions: { cwd: dir, env: { ...process.env, NODE_ENV: '', TEST: '' } } }) - expect(exitCode).toBe(0) - const heap = JSON.parse(stdout.trim().split('\n').at(-1)!) as number[] - expect(heap.at(-1)! - heap[2]!).toBeLessThan(64 * 1024 * 1024) - }) - - it('should rewrite `module.json` when a file the module entry imports changes while watching', async () => { - const dir = await copyExample('.temp-tsdown-watch-imports', '') - await rm(join(dir, 'tsdown.config.ts')) - await writeFile(join(dir, 'src/runtime/name.ts'), `export const moduleName: string = 'from-runtime'\n`) - const source = await readFile(join(dir, 'src/module.ts'), 'utf-8') - await writeFile(join(dir, 'src/module.ts'), `import { moduleName } from './runtime/name.ts'\n${source.replace(`name: 'my-module'`, 'name: moduleName')}`) - await writeFile(join(dir, 'watch.mjs'), [ - `import { build } from ${JSON.stringify(pathToFileURL(join(repoRoot, 'node_modules/tsdown/dist/index.mjs')).href)}`, - builderImport, - `await build({ cwd: ${JSON.stringify(dir)}, config: false, watch: true, plugins: [builder()] })`, - '', - ].join('\n')) - const meta = join(dir, 'dist/module.json') - const watcher = watch(dir, ['watch.mjs']) - try { - await waitFor(async () => existsSync(meta) && JSON.parse(await readFile(meta, 'utf-8')).name === 'from-runtime') - await writeFile(join(dir, 'src/runtime/name.ts'), `export const moduleName: string = 'changed-runtime'\n`) - await waitFor(async () => JSON.parse(await readFile(meta, 'utf-8')).name === 'changed-runtime') - } - finally { - await watcher.stop() - } - }) - - it.each([['an existing', 'existing'], ['a missing', 'missing']])('should rebuild when a file is added to %s runtime directory while watching', async (_, state) => { - const dir = await copyExample(`.temp-tsdown-watch-added-${state}`, `export default {\n plugins: [builder()],\n}\n`) - if (state === 'missing') { - await rm(join(dir, 'src/runtime'), { recursive: true, force: true }) - await writeFile(join(dir, 'src/module.ts'), `import { defineNuxtModule } from '@nuxt/kit'\n\nexport default defineNuxtModule({ meta: { name: 'my-module' } })\n`) - } - const watcher = watch(dir, [tsdownBin, '--watch']) - try { - await waitFor(async () => existsSync(join(dir, 'dist/module.json'))) - await mkdir(join(dir, 'src/runtime/utils/nested'), { recursive: true }) - await writeFile(join(dir, 'src/runtime/utils/nested/added.ts'), `export const added: string = 'added'\n`) - await waitFor(async () => existsSync(join(dir, 'dist/runtime/utils/nested/added.js')) && existsSync(join(dir, 'dist/runtime/utils/nested/added.d.ts'))) - } - finally { - await watcher.stop() - } - }) - - it('should write current metadata from each build session in the same process', async () => { - const dir = await copyExample('.temp-tsdown-meta-sessions', '') - await rm(join(dir, 'tsdown.config.ts')) - await writeFile(join(dir, 'sessions.mjs'), [ - `import { readFile, writeFile } from 'node:fs/promises'`, - `import { build } from ${JSON.stringify(pathToFileURL(join(repoRoot, 'node_modules/tsdown/dist/index.mjs')).href)}`, - builderImport, - `const cwd = ${JSON.stringify(dir)}`, - `const source = await readFile(cwd + '/src/module.ts', 'utf8')`, - `const names = []`, - `for (const name of ['first-session', 'second-session']) {`, - ` await writeFile(cwd + '/src/module.ts', source.replace("name: 'my-module'", 'name: ' + JSON.stringify(name)))`, - ` await build({ cwd, config: false, logLevel: 'silent', plugins: [builder()] })`, - ` names.push(JSON.parse(await readFile(cwd + '/dist/module.json', 'utf8')).name)`, - `}`, - `console.log(JSON.stringify(names))`, - '', - ].join('\n')) - const { stdout, stderr, exitCode } = await exec('node', ['sessions.mjs'], { nodeOptions: { cwd: dir, env: { ...process.env, NODE_ENV: '', TEST: '' } } }) - expect(exitCode, stdout + stderr).toBe(0) - expect(JSON.parse(stdout.trim().split('\n').at(-1)!)).toEqual(['first-session', 'second-session']) - }) - - it('should compile JSX in a server runtime file added while watching', async () => { - const dir = await copyExample('.temp-tsdown-watch-jsx', `export default {\n plugins: [builder()],\n}\n`) - const watcher = watch(dir, [tsdownBin, '--watch']) - try { - await waitFor(async () => existsSync(join(dir, 'dist/module.json'))) - await mkdir(join(dir, 'src/runtime/server'), { recursive: true }) - await writeFile(join(dir, 'src/runtime/server/render.tsx'), `export const render = (): unknown =>

hi

\n`) - await waitFor(async () => existsSync(join(dir, 'dist/runtime/server/render.js')) || existsSync(join(dir, 'dist/runtime/server/render.jsx'))) - expect(existsSync(join(dir, 'dist/runtime/server/render.jsx'))).toBe(false) - expect(await readFile(join(dir, 'dist/runtime/server/render.js'), 'utf-8')).toContain('vue/jsx-runtime') - } - finally { - await watcher.stop() - } - }) - - it('should rebuild when a file outside the runtime directory that a runtime file imports changes while watching', async () => { - const dir = await copyExample('.temp-tsdown-watch-outside', `export default {\n plugins: [builder()],\n}\n`) - await writeFile(join(dir, 'src/shared.ts'), `export const shared: string = 'first'\n`) - await writeFile(join(dir, 'src/runtime/use.ts'), `import { shared } from '../shared'\n\nexport const useShared = (): string => shared\n`) - const output = join(dir, 'dist/shared.js') - const watcher = watch(dir, [tsdownBin, '--watch']) - try { - await waitFor(async () => existsSync(output) && (await readFile(output, 'utf-8')).includes('first')) - await writeFile(join(dir, 'src/shared.ts'), `export const shared: string = 'second'\n`) - await waitFor(async () => (await readFile(output, 'utf-8')).includes('second')) - } - finally { - await watcher.stop() - } - }) - - it('should remove the output of a runtime file deleted while watching', async () => { - const dir = await copyExample('.temp-tsdown-watch-deleted', `export default {\n plugins: [builder()],\n}\n`) - await writeFile(join(dir, 'src/runtime/removed.ts'), `export const removed: string = 'removed'\n`) - const outputs = ['dist/runtime/removed.js', 'dist/runtime/removed.d.ts'].map(output => join(dir, output)) - const watcher = watch(dir, [tsdownBin, '--watch']) - try { - await waitFor(async () => existsSync(join(dir, 'dist/module.json')) && outputs.every(output => existsSync(output))) - await rm(join(dir, 'src/runtime/removed.ts')) - await waitFor(async () => outputs.every(output => !existsSync(output))) - expect(existsSync(join(dir, 'dist/runtime/plugins/plugin.js'))).toBe(true) - } - finally { - await watcher.stop() - } - }) - - it.each([ - ['the module entry', 'module', 'src/module.ts', 'types.d.mts'], - ['a runtime file', 'runtime', 'src/runtime/plugins/plugin.ts', 'runtime/plugins/plugin.js'], - ])('should keep the previous output when a watched rebuild of %s fails, and recover on the next good save', async (_, name, file, recovered) => { - const dir = await copyExample(`.temp-tsdown-watch-failure-${name}`, `export default {\n plugins: [builder()],\n}\n`) - const files = ['module.mjs', 'module.d.mts', 'module.json', 'types.d.mts', 'runtime/plugins/plugin.js'].map(output => join(dir, 'dist', output)) - const source = await readFile(join(dir, file), 'utf-8') - const watcher = watch(dir, [tsdownBin, '--watch']) - try { - await waitFor(async () => files.every(output => existsSync(output))) - const before = await Promise.all(files.map(output => readFile(output, 'utf-8'))) - const seen = watcher.output().length - await writeFile(join(dir, file), `${source}\nexport const broken = (\n`) - await waitFor(async () => /error/i.test(watcher.output().slice(seen))) - await delay(1000) - expect(await Promise.all(files.map(output => readFile(output, 'utf-8')))).toEqual(before) - await writeFile(join(dir, file), `${source}\nexport const recoveredMarker: string = 'recovered'\n`) - await waitFor(async () => (await readFile(join(dir, 'dist', recovered), 'utf-8')).includes('recoveredMarker')) - } - finally { - await watcher.stop() - } - }) - - it('should keep `dist` while a watched build starts, and empty it before a one-off build', async () => { - const dir = await copyExample('.temp-tsdown-watch-kept', `export default {\n plugins: [builder()],\n}\n`) - const distDir = join(dir, 'dist') - const stale = ['stale.txt', 'runtime/components/Removed.vue'] - const addStale = () => Promise.all(stale.map(file => writeFile(join(distDir, file), 'stale\n'))) - const snapshot = async () => { - const files = (await readdir(distDir, { recursive: true, withFileTypes: true })).filter(file => file.isFile()) - return new Map(await Promise.all(files.map(async (file) => { - const path = join(file.parentPath, file.name) - return [relative(distDir, path), (await stat(path, { bigint: true })).mtimeNs] as const - }))) - } - - expect((await tsdown(dir)).exitCode).toBe(0) - await addStale() - expect((await tsdown(dir)).exitCode).toBe(0) - expect(stale.filter(file => existsSync(join(distDir, file)))).toEqual([]) - - await addStale() - const before = await snapshot() - const watcher = watch(dir, [tsdownBin, '--watch']) - let missing = false - try { - await waitFor(async () => { - missing ||= !existsSync(join(distDir, 'module.mjs')) || !existsSync(join(distDir, 'runtime/plugins/plugin.js')) - return /Rebuilt in/.test(watcher.output()) - }) - const after = await snapshot() - expect(missing).toBe(false) - expect([...before.keys()].filter(file => !after.has(file)).sort()).toEqual([...stale].sort()) - expect([...after.keys()].filter(file => before.get(file) !== after.get(file) && !file.endsWith('.d.ts'))).toEqual([]) - } - finally { - await watcher.stop() - } - }) - - it('should only write the outputs whose content changes when a watched build rebuilds', async () => { - const dir = await copyExample('.temp-tsdown-watch-unchanged', `export default {\n plugins: [\n builder({ entries: ['./src/utils'] }),\n { name: 'user-asset', generateBundle() { this.emitFile({ type: 'asset', fileName: 'user.txt', source: 'user asset\\n' }) } },\n ],\n}\n`) - const distDir = join(dir, 'dist') - const snapshot = async () => { - const files = (await readdir(distDir, { recursive: true, withFileTypes: true })).filter(file => file.isFile()) - return new Map(await Promise.all(files.map(async (file) => { - const path = join(file.parentPath, file.name) - return [relative(distDir, path), { mtime: (await stat(path, { bigint: true })).mtimeNs, hash: createHash('sha256').update(await readFile(path)).digest('hex') }] as const - }))) - } - const changes = (before: Awaited>, after: Awaited>) => ({ - changed: [...after.keys()].filter(file => before.has(file) && before.get(file)!.mtime !== after.get(file)!.mtime).sort(), - added: [...after.keys()].filter(file => !before.has(file)).sort(), - removed: [...before.keys()].filter(file => !after.has(file)).sort(), - }) - const watcher = watch(dir, [tsdownBin, '--watch']) - const rebuilds = () => watcher.output().match(/Rebuilt in/g)?.length ?? 0 - const rebuild = async (change: () => Promise) => { - const before = await snapshot() - const count = rebuilds() - await change() - await waitFor(async () => rebuilds() > count) - return changes(before, await snapshot()) - } - const edit = async (file: string, from: string, to: string) => writeFile(join(dir, file), (await readFile(join(dir, file), 'utf-8')).replace(from, to)) - try { - await waitFor(async () => rebuilds() > 0 && existsSync(join(distDir, 'module.json')) && existsSync(join(distDir, 'types.d.mts'))) - expect(await readFile(join(distDir, 'user.txt'), 'utf-8')).toBe('user asset\n') - - await rm(join(distDir, 'runtime/plugins/plugin.js')) - expect(await rebuild(() => edit('src/runtime/components/TestMe.vue', '', ''))).toEqual({ changed: [], added: ['runtime/plugins/plugin.js'], removed: [] }) - - expect(await rebuild(() => edit('src/runtime/components/TestMe.vue', '{{ count }}', 'count: {{ count }}'))).toEqual({ changed: ['runtime/components/TestMe.vue'], added: [], removed: [] }) - expect(await rebuild(() => edit('src/runtime/components/TestMe.vue', '', ''))).toEqual({ changed: [], added: [], removed: [] }) - expect(await rebuild(() => edit('src/module.ts', `name: 'my-module'`, `name: 'my-renamed-module'`))).toEqual({ changed: ['module.json', 'module.mjs'], added: [], removed: [] }) - expect(await rebuild(() => rm(join(dir, 'src/runtime/composables/useAppNuxt.ts')))).toEqual({ changed: [], added: [], removed: ['runtime/composables/useAppNuxt.d.ts', 'runtime/composables/useAppNuxt.js'] }) - - const before = await snapshot() - const plugin = await readFile(join(dir, 'src/runtime/plugins/plugin.ts'), 'utf-8') - const failures = () => watcher.output().match(/Failed to transpile/g)?.length ?? 0 - const failed = failures() - await writeFile(join(dir, 'src/runtime/plugins/plugin.ts'), `${plugin}\nexport const broken: = 1\n`) - await waitFor(async () => failures() > failed) - expect(changes(before, await snapshot())).toEqual({ changed: [], added: [], removed: [] }) - expect(await rebuild(() => writeFile(join(dir, 'src/runtime/plugins/plugin.ts'), plugin))).toEqual({ changed: [], added: [], removed: [] }) - expect([...(await snapshot()).entries()].map(([file, { hash }]) => [file, hash])).toEqual([...before.entries()].map(([file, { hash }]) => [file, hash])) - } - finally { - await watcher.stop() - } - }) - - it('should rewrite `types.d.mts` and `module.json` when a watched build rebuilds', async () => { - const dir = await copyExample('.temp-tsdown-watch', `export default {\n plugins: [builder({ entries: ['./src/utils'] })],\n}\n`) - const types = join(dir, 'dist/types.d.mts') - const watcher = tsdown(dir, ['--watch']) - try { - await waitFor(async () => existsSync(types) && existsSync(join(dir, 'dist/module.json'))) - expect(await readFile(types, 'utf-8')).not.toContain('rebuiltMarker') - await writeFile(join(dir, 'src/runtime/composables/added.d.ts'), `import type { NuxtApp } from '#app'\nexport type Added = NuxtApp\n`) - const source = await readFile(join(dir, 'src/module.ts'), 'utf-8') - await writeFile(join(dir, 'src/module.ts'), `${source.replace(`name: 'my-module'`, `name: 'my-rebuilt-module'`)}\nexport const rebuiltMarker: string = 'rebuilt'\n`) - await waitFor(async () => existsSync(types) && (await readFile(types, 'utf-8')).includes('rebuiltMarker')) - await waitFor(async () => JSON.parse(await readFile(join(dir, 'dist/module.json'), 'utf-8')).name === 'my-rebuilt-module') - expect(await readFile(join(dir, 'dist/runtime/composables/added.d.ts'), 'utf-8')).toContain(`from 'nuxt/app'`) - } - finally { - watcher.kill() - } - }) - - it('should break the size report down by entry and runtime directory only when it is a summary', async () => { - const rows = (output: string) => [...output.matchAll(/(dist\/(?:module\.mjs|runtime\/))\s[^\n]*types/g)].map(match => match[1]).sort() - const breakdown = ['dist/module.mjs', 'dist/runtime/'] - for (const [report, expected] of [[undefined, breakdown], ['{ summary: true }', breakdown], ['{ summary: false }', []], ['false', []]] as const) { - const dir = await copyExample(`.temp-tsdown-report-${String(report).replace(/\W/g, '')}`, `export default {\n ${report === undefined ? '' : `report: ${report},`}\n plugins: [builder()],\n}\n`) - const built = await tsdown(dir) - expect(built.exitCode, String(report)).toBe(0) - expect(rows(built.stdout + built.stderr), String(report)).toEqual(expected) - if (report === undefined) { - const watcher = watch(dir, [tsdownBin, '--watch']) - const types = join(dir, 'dist/types.d.mts') - try { - await waitFor(async () => rows(watcher.output()).length >= 2 && existsSync(types)) - await delay(1000) - expect(rows(watcher.output())).toEqual(breakdown) - const seen = watcher.output().length - await appendFile(join(dir, 'src/module.ts'), '\nexport const reportRebuild: string = "rebuilt"\n') - await waitFor(async () => rows(watcher.output().slice(seen)).length >= 2 && (await readFile(types, 'utf-8')).includes('reportRebuild')) - await delay(1000) - expect(rows(watcher.output().slice(seen))).toEqual(breakdown) - } - finally { - await watcher.stop() - } - } - } - }) -}) diff --git a/test/tsdown.spec.ts b/test/tsdown.spec.ts deleted file mode 100644 index 355c3af3..00000000 --- a/test/tsdown.spec.ts +++ /dev/null @@ -1,346 +0,0 @@ -import { existsSync } from 'node:fs' -import { appendFile, mkdir, readFile, rm, symlink, writeFile } from 'node:fs/promises' -import { dirname, join, relative } from 'pathe' -import { exec } from 'tinyexec' -import ts from 'typescript' -import { beforeAll, describe, expect, it } from 'vitest' - -import { guide } from '../src/build/guide.ts' -import { npmPackFromPnpmScript, packProbeArgs, packProbeContext } from './pack-env.ts' -import { copyExample, repoRoot, tsdown, tsdownBin } from './utils.ts' - -describe('builder', () => { - let hooksDir: string - - beforeAll(async () => { - hooksDir = await copyExample('.temp-tsdown-hooks', `import { appendFileSync, existsSync, mkdirSync, writeFileSync } from 'node:fs' -import { join } from 'node:path' - -const log = line => appendFileSync(join(import.meta.dirname, 'hooks.log'), line + '\\n') - -export default { - hooks: { - 'build:prepare'(ctx) { - writeFileSync(join(ctx.options.cwd, 'src/generated.ts'), "export const generated: string = 'from build:prepare'\\n") - mkdirSync(ctx.options.outDir, { recursive: true }) - writeFileSync(join(ctx.options.outDir, 'stale.txt'), '') - log('build:prepare') - }, - 'build:done'(ctx) { - log(\`build:done \${existsSync(join(ctx.options.outDir, 'module.json'))} \${existsSync(join(ctx.options.outDir, 'types.d.mts'))}\`) - }, - }, - format: 'esm', - dts: true, - fixedExtension: true, - platform: 'node', - deps: { neverBundle: ['fake-ext'] }, - inputOptions(options) { - log('inputOptions') - return options - }, - plugins: [ - { - name: 'user', - transform(code, id) { - return id.replaceAll('\\\\', '/').endsWith('src/module.ts') ? code.replace('__USER__', 'replaced by a user plugin') : undefined - }, - }, - builder({ entries: ['./src/utils'] }), - ], -} -`) - await mkdir(join(hooksDir, 'node_modules/fake-ext'), { recursive: true }) - await writeFile(join(hooksDir, 'node_modules/fake-ext/package.json'), JSON.stringify({ name: 'fake-ext', type: 'module', exports: { '.': { types: './index.d.ts', default: './index.js' } } })) - await writeFile(join(hooksDir, 'node_modules/fake-ext/index.js'), `export const ext = 'bundled-fake-ext'\n`) - await writeFile(join(hooksDir, 'node_modules/fake-ext/index.d.ts'), `export declare const ext: string\n`) - await mkdir(join(hooksDir, 'src/runtime/utils'), { recursive: true }) - await writeFile(join(hooksDir, 'src/runtime/utils/answer.ts'), `export const answer: number = 42\n`) - await appendFile(join(hooksDir, 'src/module.ts'), [ - `import { generated } from './generated.ts'`, - `import { ext } from 'fake-ext'`, - `import { answer } from './runtime/utils/answer.ts'`, - `export const refs: unknown[] = [generated, ext, answer, '__USER__']`, - '', - ].join('\n')) - }) - - it('should run the config\'s hooks before its own, so `build:prepare` can generate sources, and compose with its plugins and options', async () => { - const { exitCode, stdout, stderr } = await tsdown(hooksDir) - expect(stdout + stderr).not.toContain('Error') - expect(exitCode).toBe(0) - expect((await readFile(join(hooksDir, 'hooks.log'), 'utf-8')).trim().split('\n')).toEqual(['build:prepare', 'inputOptions', 'build:done true true']) - expect(existsSync(join(hooksDir, 'dist/stale.txt'))).toBe(false) - const module = await readFile(join(hooksDir, 'dist/module.mjs'), 'utf-8') - expect(module).toContain('from build:prepare') - expect(module).toContain('replaced by a user plugin') - expect(module).toContain('from "fake-ext"') - expect(module).not.toContain('bundled-fake-ext') - expect(module).toContain('from "./runtime/utils/answer.js"') - expect(JSON.parse(await readFile(join(hooksDir, 'dist/module.json'), 'utf-8'))).toMatchObject({ name: 'my-module', configKey: 'myModule' }) - }) - - it('should write files a plugin emits before checking the paths of `package.json`', async () => { - const dir = await copyExample('.temp-tsdown-emitted', `export default {\n plugins: [\n builder(),\n { name: 'config', generateBundle() { this.emitFile({ type: 'asset', fileName: 'config.cjs', source: 'module.exports = {}\\n' }) } },\n ],\n}\n`) - const pkgPath = join(dir, 'package.json') - const { typesVersions: _, ...pkg } = JSON.parse(await readFile(pkgPath, 'utf-8')) - await writeFile(pkgPath, JSON.stringify({ ...pkg, exports: { '.': { types: './dist/types.d.mts', default: './dist/module.mjs' }, './config': './dist/config.cjs' } }, null, 2)) - const { exitCode, stdout, stderr } = await tsdown(dir) - expect(exitCode).toBe(0) - expect(stdout + stderr).not.toContain('do not exist after the build') - expect(await readFile(join(dir, 'dist/config.cjs'), 'utf-8')).toBe('module.exports = {}\n') - }) - - it('should refuse to build when a published path points at a TypeScript source or at a file the pack leaves out', async () => { - const dir = await copyExample('.temp-tsdown-unpublishable', `export default {\n plugins: [builder()],\n}\n`) - const pkgPath = join(dir, 'package.json') - const pkg = JSON.parse(await readFile(pkgPath, 'utf-8')) - const cases: Array<[Record, string]> = [ - [{ '.': './src/module.ts' }, 'Pointing at TypeScript sources, which Node does not load from `node_modules`: `exports` (`./src/module.ts`).'], - [{ '.': './lib/module.mjs' }, 'Pointing at paths that the pack leaves out: `exports` (`./lib/module.mjs`).'], - ] - for (const [exports, message] of cases) { - await writeFile(pkgPath, JSON.stringify({ ...pkg, exports }, null, 2)) - for (const args of [[tsdownBin], [join(repoRoot, 'src/cli.ts'), 'build']]) { - const { exitCode, stdout, stderr } = await exec('node', args, { nodeOptions: { cwd: dir, env: { ...process.env, NODE_ENV: '', TEST: '' } } }) - expect(exitCode, args.join(' ')).not.toBe(0) - expect(stdout + stderr, args.join(' ')).toContain(message) - expect(existsSync(join(dir, 'dist'))).toBe(false) - } - } - }) - - it('should augment the same interfaces from the types `prepare` writes as from `dist`, through star re-exports', async () => { - const dir = await copyExample('.temp-tsdown-star-exports', `export default {\n plugins: [builder()],\n}\n`) - const files: Record = { - 'src/module.ts': `import { defineNuxtModule } from '@nuxt/kit'\nimport type { ModuleOptions } from './types/index.ts'\n\nexport * from './types/index.ts'\nexport type * from './types/runtime.ts'\n\nexport default defineNuxtModule({\n meta: { name: 'my-module', configKey: 'myModule' },\n defaults: { apiKey: '' },\n})\n`, - 'src/types/index.ts': `export * from './hooks.ts'\n\nexport interface ModuleOptions {\n apiKey: string\n}\n`, - 'src/types/hooks.ts': `export interface ModuleHooks {\n 'my-module:init': () => void\n}\n`, - 'src/types/runtime.ts': `export interface ModuleRuntimeHooks {\n 'my-module:runtime-hook': () => void\n}\n\nexport interface ModulePublicRuntimeConfig {\n NAME: string\n}\n`, - } - for (const [file, contents] of Object.entries(files)) { - await mkdir(dirname(join(dir, file)), { recursive: true }) - await writeFile(join(dir, file), contents) - } - const env = { ...process.env, NODE_ENV: '', TEST: '', NUXT_TELEMETRY_DISABLED: '1' } - const prepared = await exec('node', [join(repoRoot, 'src/cli.ts'), 'prepare'], { nodeOptions: { cwd: dir, env } }) - expect(prepared.exitCode, prepared.stdout + prepared.stderr).toBe(0) - const built = await tsdown(dir) - expect(built.exitCode, built.stdout + built.stderr).toBe(0) - - const shims = async (file: string) => (await readFile(join(dir, file), 'utf-8')).match(/^declare module '[^']+' \{\n[\s\S]*?\n\}$/gm) - const sourceShims = await shims('.nuxt/module-builder/types.d.mts') - expect(sourceShims).toEqual(await shims('dist/types.d.mts')) - expect(sourceShims).toEqual([ - `declare module '#app' {\n interface RuntimeNuxtHooks extends ModuleRuntimeHooks {}\n}`, - `declare module '@nuxt/schema' {\n interface NuxtHooks extends ModuleHooks {}\n interface PublicRuntimeConfig extends ModulePublicRuntimeConfig {}\n}`, - ]) - - const { config } = ts.readConfigFile(join(dir, '.nuxt/tsconfig.json'), ts.sys.readFile) - const { options } = ts.parseJsonConfigFileContent(config, ts.sys, join(dir, '.nuxt')) - for (const types of ['./.nuxt/module-builder/types.mjs', './dist/types.mjs']) { - const probe = join(dir, 'probe.ts') - await writeFile(probe, `import type {} from '${types}'\nimport type { RuntimeNuxtHooks } from '#app'\nimport type { NuxtHooks, PublicRuntimeConfig } from '@nuxt/schema'\n\nexport type Augmented = [NuxtHooks['my-module:init'], RuntimeNuxtHooks['my-module:runtime-hook'], PublicRuntimeConfig['NAME']]\n`) - const program = ts.createProgram([probe], { ...options, noEmit: true, skipLibCheck: false }) - const diagnostics = ts.getPreEmitDiagnostics(program).filter(diagnostic => diagnostic.file && /^(?:src|dist|\.nuxt\/module-builder)\/|^probe\.ts$/.test(relative(dir, diagnostic.file.fileName))) - expect(diagnostics.map(diagnostic => `${relative(dir, diagnostic.file!.fileName)}: ${ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')}`), types).toEqual([]) - } - }) - - it('should refuse package `imports` that the output imports and that would not work once installed', async () => { - const dir = await copyExample('.temp-tsdown-package-imports', `export default {\n plugins: [builder({ externals: [/^#ext\\//] })],\n}\n`) - const pkgPath = join(dir, 'package.json') - const pkg = { ...JSON.parse(await readFile(pkgPath, 'utf-8')), imports: { '#ext/*': './src/ext/*.ts', '#internal/*': './src/internal/*.ts' } } - await writeFile(pkgPath, JSON.stringify(pkg, null, 2)) - await mkdir(join(dir, 'src/ext'), { recursive: true }) - await mkdir(join(dir, 'src/internal'), { recursive: true }) - await writeFile(join(dir, 'src/ext/value.ts'), `export const ext: string = 'ext'\n`) - await writeFile(join(dir, 'src/internal/value.ts'), `export const internal: string = 'internal'\n`) - await appendFile(join(dir, 'src/module.ts'), `export { ext } from '#ext/value'\nexport { internal } from '#internal/value'\nexport const label: string = '#internal/label'\n`) - - const refused = await tsdown(dir) - expect(refused.exitCode).not.toBe(0) - expect(refused.stdout + refused.stderr).toContain(`The build output imports these \`imports\` of \`package.json\`, which would not work once installed. Pointing at TypeScript sources, which Node does not load from \`node_modules\`: \`#ext/*\` (\`./src/ext/*.ts\`).`) - expect(await readFile(join(dir, 'dist/module.mjs'), 'utf-8')).toContain('"#ext/value"') - - await writeFile(pkgPath, JSON.stringify({ ...pkg, publishConfig: { imports: { '#ext/*': './dist/ext/*.mjs' } } }, null, 2)) - const built = await tsdown(dir) - expect(built.exitCode, built.stdout + built.stderr).toBe(0) - }) - - it('should be published at `@nuxt/module-builder/tsdown`, not at the package root', async () => { - const built = await exec('node', [tsdownBin], { nodeOptions: { cwd: repoRoot } }) - expect(built.exitCode, built.stdout + built.stderr).toBe(0) - const loaded = await exec('node', ['--input-type=module', '-e', `const root = await import('@nuxt/module-builder')\nconst { builder } = await import('@nuxt/module-builder/tsdown')\nconsole.log(JSON.stringify(['builder' in root, builder().name]))`], { nodeOptions: { cwd: repoRoot } }) - expect(JSON.parse(loaded.stdout)).toEqual([false, 'nuxt-module-builder']) - }) - - it('should prepare a module without `.nuxt` before building it', async () => { - const dir = await copyExample('.temp-tsdown-auto-prepare', `export default {\n plugins: [builder()],\n}\n`) - await rm(join(dir, '.nuxt'), { recursive: true, force: true }) - const { exitCode, stdout, stderr } = await exec('node', [tsdownBin], { nodeOptions: { cwd: dir, env: { ...process.env, NODE_ENV: '', TEST: '', NUXT_TELEMETRY_DISABLED: '1' } } }) - expect(exitCode).toBe(0) - expect(stdout + stderr).toContain(guide('preparing-nuxt')) - expect(existsSync(join(dir, '.nuxt/tsconfig.json'))).toBe(true) - expect(await readFile(join(dir, 'dist/runtime/composables/useAliasedApp.d.ts'), 'utf-8')).toMatch(/import\("nuxt\/app"\)\.NuxtApp/) - }) - - it('should prepare a module that lists its own package in `.nuxtrc` and `nuxt.config`, with or without `dist`', async () => { - const dir = await copyExample('.temp-tsdown-self-listed', `export default {\n plugins: [builder()],\n}\n`) - const pkgPath = join(dir, 'package.json') - const pkg = JSON.parse(await readFile(pkgPath, 'utf-8')) - await writeFile(pkgPath, JSON.stringify({ ...pkg, name: 'self-listed-module' }, null, 2)) - await appendFile(join(dir, '.nuxtrc'), '\nmodules[]=self-listed-module\n') - await writeFile(join(dir, 'nuxt.config.ts'), `export default { modules: [['self-listed-module', { apiKey: 'from-config' }]] }\n`) - await writeFile(join(dir, 'src/module.ts'), (await readFile(join(dir, 'src/module.ts'), 'utf-8')).replace('setup(_options, _nuxt) {', 'setup(_options, _nuxt) {\n console.log(`[setup] ${_options.apiKey}`)')) - const env = { ...process.env, NODE_ENV: '', TEST: '', NUXT_TELEMETRY_DISABLED: '1' } - const references = async () => (await readFile(join(dir, '.nuxt/nuxt.node.d.ts'), 'utf-8')).split('\n').filter(line => line.includes('types="self-listed-module"') || line === '/// ') - - await rm(join(dir, '.nuxt'), { recursive: true, force: true }) - const built = await exec('node', [tsdownBin], { nodeOptions: { cwd: dir, env } }) - expect(built.exitCode, built.stdout + built.stderr).toBe(0) - expect(built.stdout.match(/\[setup\] .*/g)).toEqual(['[setup] from-config']) - expect(await references()).toEqual(['/// ']) - - await writeFile(pkgPath, JSON.stringify({ ...pkg, name: 'self-listed-module', exports: { '.': './src/module.ts' }, main: './src/module.ts' }, null, 2)) - await rm(join(dir, '.nuxt'), { recursive: true, force: true }) - const prepared = await exec('node', [join(repoRoot, 'src/cli.ts'), 'prepare'], { nodeOptions: { cwd: dir, env } }) - expect(prepared.exitCode, prepared.stdout + prepared.stderr).toBe(0) - expect(prepared.stdout.match(/\[setup\] .*/g)).toEqual(['[setup] from-config']) - expect(await references()).toEqual(['/// ']) - }) - - it('should reject one plugin instance shared by two configs', async () => { - const dir = await copyExample('.temp-tsdown-shared', `const plugin = builder()\n\nexport default [\n { plugins: [plugin] },\n { plugins: [plugin], outDir: 'dist-other' },\n]\n`) - const { exitCode, stdout, stderr } = await tsdown(dir) - expect(exitCode).not.toBe(0) - expect(stdout + stderr).toContain('The same `builder()` plugin is used in more than one tsdown config.') - }) - - it.each([ - ['format', `{ format: 'cjs' }`], - ['entry', `{ entry: { module: 'src/utils.ts' } }`], - ['platform', `{ platform: 'browser' }`], - ])('should fail when another plugin changes `%s`, which it sets', async (option, override) => { - const dir = await copyExample(`.temp-tsdown-overridden-${option}`, `export default {\n plugins: [builder(), { name: 'override', tsdownConfig: () => (${override}) }],\n}\n`) - const { exitCode, stdout, stderr } = await tsdown(dir) - expect(exitCode).not.toBe(0) - expect(stdout + stderr).toMatch(new RegExp(`Another tsdown plugin changed \`${option}\`.*, which \`builder\\(\\)\` sets\\. ${guide('options-builder-sets')}`)) - expect(existsSync(join(dir, 'dist'))).toBe(false) - }) - - it('should fail when `outputOptions` changes the file names of the bundled entries', async () => { - const dir = await copyExample('.temp-tsdown-entry-file-names', `export default {\n outputOptions: { entryFileNames: '[name].js' },\n plugins: [builder({ entries: ['./src/utils'] })],\n}\n`) - const { exitCode, stdout, stderr } = await tsdown(dir) - expect(exitCode).not.toBe(0) - expect(stdout + stderr).toMatch(/The build did not emit `(module|utils)\.mjs`, `(module|utils)\.mjs`\./) - expect(existsSync(join(dir, 'dist'))).toBe(false) - }) - - describe('with `package.json` pointing at the sources and `publishConfig` at `dist`', () => { - let dir: string - - beforeAll(async () => { - dir = await copyExample('.temp-tsdown-source-exports', `export default {\n publint: true,\n plugins: [builder({ entries: ['./src/utils'] })],\n}\n`) - const pkgPath = join(dir, 'package.json') - const { typesVersions: _, ...pkg } = JSON.parse(await readFile(pkgPath, 'utf-8')) - await writeFile(pkgPath, JSON.stringify({ - ...pkg, - exports: { '.': { types: './.nuxt/module-builder/types.d.mts', default: './src/module.ts' }, './utils': './src/utils.ts' }, - main: './src/module.ts', - types: './.nuxt/module-builder/types.d.mts', - scripts: { prepack: 'node ../node_modules/tsdown/dist/run.mjs' }, - publishConfig: { - exports: { '.': { types: './dist/types.d.mts', default: './dist/module.mjs' }, './utils': { types: './dist/utils.d.mts', default: './dist/utils.mjs' } }, - main: './dist/module.mjs', - types: './dist/types.d.mts', - typesVersions: { '*': { utils: ['./dist/utils.d.mts'] } }, - }, - }, null, 2)) - await rm(join(dir, 'playground/node_modules/my-module'), { force: true }) - await symlink(dir, join(dir, 'playground/node_modules/my-module')) - for (const nuxtDir of ['.nuxt', 'playground/.nuxt']) { - await rm(join(dir, nuxtDir), { recursive: true, force: true }) - } - await writeFile(join(dir, 'src/module.ts'), (await readFile(join(dir, 'src/module.ts'), 'utf-8')).replace(`import type { SharedTypeFromRuntime } from './runtime/plugins/plugin'`, `type SharedTypeFromRuntime = 'shared-type'`)) - }) - - const nuxtEnv = { ...process.env, NUXT_TELEMETRY_DISABLED: '1' } - const typecheckPlayground = (context: string) => exec(join(repoRoot, 'node_modules/.bin/vue-tsc'), ['--noEmit', '-p', join(dir, `playground/.nuxt/tsconfig.${context}.json`)], { nodeOptions: { cwd: dir } }) - - it('should let the playground load the module and its type augmentations from its sources, without `dist`', async () => { - const prepared = await exec('node', [join(repoRoot, 'src/cli.ts'), 'prepare'], { nodeOptions: { cwd: dir, env: nuxtEnv } }) - expect(prepared.exitCode, prepared.stdout + prepared.stderr).toBe(0) - const { exitCode, stdout, stderr } = await exec('node', [join(repoRoot, 'node_modules/nuxt/bin/nuxt.mjs'), 'prepare', 'playground'], { nodeOptions: { cwd: dir, env: nuxtEnv } }) - expect(exitCode, stdout + stderr).toBe(0) - expect(existsSync(join(dir, 'dist'))).toBe(false) - expect(await readFile(join(dir, 'playground/.nuxt/types/plugins.d.ts'), 'utf-8')).toContain('src/runtime/plugins/plugin') - - for (const context of ['app', 'node']) { - const typecheck = await typecheckPlayground(context) - expect(typecheck.stdout + typecheck.stderr, context).toBe('') - expect(typecheck.exitCode, context).toBe(0) - } - - const pkgPath = join(dir, 'package.json') - const pkg = await readFile(pkgPath, 'utf-8') - await writeFile(pkgPath, pkg.replaceAll('./.nuxt/module-builder/types.d.mts', './src/module.ts')) - try { - const [app, node] = await Promise.all(['app', 'node'].map(typecheckPlayground)) - expect(app!.stdout).toContain(`'"my-module:runtime-hook"' is not assignable`) - expect(node!.stdout).toContain(`''my-module:init'' does not exist`) - } - finally { - await writeFile(pkgPath, pkg) - } - }) - - it('should refuse to build for a pack by npm, which publishes the source paths', async () => { - const { exitCode, stdout, stderr } = await exec('node', [...packProbeArgs, tsdownBin], { nodeOptions: { cwd: dir, env: { ...npmPackFromPnpmScript(), NODE_ENV: '', TEST: '' } } }) - expect(exitCode, `${packProbeContext()}\n${stdout}${stderr}`).not.toBe(0) - expect(stdout + stderr).toMatch(/`npm(?:@[\d.]+)?` packs these fields of `package\.json` as written, and they point at TypeScript sources or paths that `files` leaves out: `exports`, `main`, `types` \(`\.\/\.nuxt\/module-builder\/types\.d\.mts`, `\.\/src\/module\.ts`, `\.\/src\/utils\.ts`\)\./) - expect(stdout + stderr).toContain(guide('publishing-source-exports')) - }) - - it('should check the published paths of `package.json` after a build', async () => { - const { exitCode, stdout, stderr } = await tsdown(dir) - expect(exitCode).toBe(0) - expect(stdout + stderr).not.toContain('package.json') - expect(stdout + stderr).toContain('[publint] No issues found') - - const pkgPath = join(dir, 'package.json') - const pkg = await readFile(pkgPath, 'utf-8') - await writeFile(pkgPath, pkg.replace('"./dist/utils.mjs"', '"./dist/missing.mjs"')) - try { - const broken = await tsdown(dir) - expect(broken.stdout + broken.stderr).toMatch(/do not exist after the build.*\.\/dist\/missing\.mjs/) - } - finally { - await writeFile(pkgPath, pkg) - } - }) - - it('should pack `dist` paths that attw accepts', async () => { - const destination = join(dir, '.pack') - const packed = await exec('pnpm', ['pack', '--pack-destination', destination], { nodeOptions: { cwd: dir } }) - expect(packed.exitCode, packed.stdout + packed.stderr).toBe(0) - const tarball = join(destination, 'my-module-1.0.0.tgz') - await exec('tar', ['-xzf', tarball, '-C', destination, 'package/package.json'], { throwOnError: true }) - expect(JSON.parse(await readFile(join(destination, 'package/package.json'), 'utf-8'))).toMatchObject({ - exports: { '.': { types: './dist/types.d.mts', default: './dist/module.mjs' } }, - main: './dist/module.mjs', - types: './dist/types.d.mts', - }) - const attw = await exec(join(repoRoot, 'node_modules/.bin/attw'), [tarball, '--ignore-rules', 'cjs-resolves-to-esm'], { nodeOptions: { cwd: dir } }) - expect(attw.exitCode, attw.stdout + attw.stderr).toBe(0) - }) - }) - - it('should fail when `build.config.ts` configures the build too', async () => { - const dir = await copyExample('.temp-tsdown-legacy', `export default {\n plugins: [builder()],\n}\n`) - await writeFile(join(dir, 'build.config.ts'), `export default {}\n`) - const { exitCode, stdout, stderr } = await tsdown(dir) - expect(exitCode).not.toBe(0) - expect(stdout + stderr).toContain(`\`build.config.ts\` configures the build, and so does \`builder()\` in the tsdown config. Move its options into \`builder()\` and delete the file. ${guide('moving-from-buildconfigts')}`) - }) -}) diff --git a/test/unit.spec.ts b/test/unit.spec.ts index dc5ffd86..e63882e0 100644 --- a/test/unit.spec.ts +++ b/test/unit.spec.ts @@ -9,7 +9,7 @@ import { version as nuxtVersion } from 'nuxt/package.json' import { consola } from 'consola' import { basename, dirname, join, resolve } from 'pathe' import { parseTsconfig } from 'get-tsconfig' -import { assertNoLegacyBuildConfig, bundledEntries, entryName, formatUnsupportedOptions, loadBuildConfig, resolveModuleOptions, resolveOutDir, translateBuildConfig, warnDeprecatedBuildConfig } from '../src/build/build-config.ts' +import { resolveModuleOptions, resolveOutDir } from '../src/build/build-config.ts' import { setupBuilder } from '../src/tsdown/setup.ts' import { defaultReport, reportsSummary, sizeBreakdown } from '../src/tsdown/report.ts' import { unchangedOutputs } from '../src/tsdown/unchanged.ts' @@ -50,18 +50,19 @@ function createResolver(packageName?: string) { } describe('runtimeExternals', () => { - it('should rewrite relative runtime imports to their built extension', async () => { + it('should point relative runtime imports at their output, keeping the name of `.vue` and non-code files', async () => { await expect(createResolver()('./runtime/plugins/plugin')).resolves.toEqual({ id: '/dist/runtime/plugins/plugin.js', external: true, }) - }) - - it('should leave `.vue` specifiers untouched', async () => { await expect(createResolver()('./runtime/components/TestMe.vue')).resolves.toEqual({ id: '/dist/runtime/components/TestMe.vue', external: true, }) + await expect(createResolver()('./runtime/assets/config.json')).resolves.toEqual({ + id: '/dist/runtime/assets/config.json', + external: true, + }) }) it('should point runtime JSX imports at their `.jsx` output unless their JSX is compiled', async () => { @@ -80,38 +81,15 @@ describe('runtimeExternals', () => { }) }) - it('should keep the name of non-code runtime files', async () => { - await expect(createResolver()('./runtime/assets/config.json')).resolves.toEqual({ - id: '/dist/runtime/assets/config.json', - external: true, - }) - }) - - it('should rewrite self-referencing runtime imports', async () => { + it('should point self-referencing runtime imports at their output, treating a `.client` suffix as part of the name and a directory as its index', async () => { await expect(createResolver('my-module')('my-module/runtime/plugins/plugin')).resolves.toEqual({ id: '/dist/runtime/plugins/plugin.js', external: true, }) - }) - - it('should treat a `.client` suffix in a self-referencing import as part of the name', async () => { await expect(createResolver('my-module')('my-module/runtime/plugins/plugin.client')).resolves.toEqual({ id: '/dist/runtime/plugins/plugin.client.js', external: true, }) - }) - - it('should ignore specifiers outside the runtime tree', async () => { - await expect(createResolver('my-module')('@nuxt/kit')).resolves.toBeUndefined() - }) - - it('should ignore files that resolve outside the runtime tree', async () => { - const resolveId = runtimeExternals(directories()).resolveId as (this: unknown, id: string, importer?: string) => Promise - const context = { resolve: async () => ({ id: join(runtimeSrcDir, '../utils.ts'), external: false }) } - await expect(resolveId.call(context, './utils', importer)).resolves.toBeUndefined() - }) - - it('should point self-referencing directory imports at their index file', async () => { const dir = await mkdtemp(join(tmpdir(), 'module-builder-')) try { await mkdir(join(dir, 'utils')) @@ -127,6 +105,13 @@ describe('runtimeExternals', () => { } }) + it('should ignore specifiers and files outside the runtime tree', async () => { + await expect(createResolver('my-module')('@nuxt/kit')).resolves.toBeUndefined() + const resolveId = runtimeExternals(directories()).resolveId as (this: unknown, id: string, importer?: string) => Promise + const context = { resolve: async () => ({ id: join(runtimeSrcDir, '../utils.ts'), external: false }) } + await expect(resolveId.call(context, './utils', importer)).resolves.toBeUndefined() + }) + it('should import runtime files relative to the chunk that imports them', () => { const renderChunk = runtimeExternals(directories()).renderChunk as (code: string, chunk: { fileName: string, imports: string[], dynamicImports: string[] }, options: { dir?: string }) => { code: string } | undefined const code = 'import plugin from "/dist/runtime/plugins/plugin.js";\nconst lazy = () => import("/dist/runtime/lazy.js");\nconst path = "/dist/runtime/plugins/plugin.js/other";\n' @@ -138,177 +123,6 @@ describe('runtimeExternals', () => { }) }) -describe('translateBuildConfig', () => { - const cwd = fileURLToPath(new URL('../example', import.meta.url)) - const outDir = join(cwd, 'dist') - const translate = (...configs: unknown[]) => translateBuildConfig(configs.map((config, index) => ({ name: `config${index}`, config })), { cwd, outDir }) - - it('should name entries the way unbuild did', () => { - expect(entryName('src/vite', cwd)).toBe('vite') - expect(entryName('./src/runtime/server/index.ts', cwd)).toBe('runtime/server/index') - expect(entryName(join(cwd, 'src/cli.mts'), cwd)).toBe('cli') - expect(entryName('lib/other', cwd)).toBe('lib/other') - }) - - it('should resolve entry inputs to their source file', () => { - expect(translate({ entries: ['src/utils', { input: './src/utils.ts', name: 'helpers' }] }).entries).toEqual({ - utils: './src/utils.ts', - helpers: './src/utils.ts', - }) - }) - - it('should skip a directory entry for `src/runtime` and keep others', () => { - const { directories, unsupported } = translate({ entries: [{ input: 'src/runtime/', outDir: 'dist/runtime' }, { input: 'src/shared/', builder: 'mkdist', outDir: 'dist/shared' }, { input: 'src/features/', outDir: 'dist/features', ext: 'js' }, { input: 'src/other/', outDir: 'lib' }] }) - expect(directories).toEqual([ - { srcDir: join(cwd, 'src/shared'), outDir: join(outDir, 'shared'), ext: 'mjs' }, - { srcDir: join(cwd, 'src/features'), outDir: join(outDir, 'features'), ext: 'js' }, - ]) - expect(unsupported).toEqual(['config0: entries[3].outDir']) - }) - - it('should match string externals by package name', () => { - const [pkg, alias] = translate({ externals: ['fake-pkg', '#alias'] }).neverBundle - expect(['fake-pkg', 'fake-pkg/sub'].every(id => pkg!.test(id))).toBe(true) - expect(pkg!.test('fake-pkg-other')).toBe(false) - expect(alias!.test('#alias/config')).toBe(true) - }) - - it('should merge replacements with earlier configs taking precedence', () => { - expect(translate( - { replace: { __A__: '"a"' }, rollup: { replace: { delimiters: ['', ''], values: { __B__: '"b"' } } } }, - { replace: { __A__: '"overridden"', __C__: '"c"' } }, - ).replace).toEqual({ values: { __A__: '"a"', __B__: '"b"', __C__: '"c"' }, delimiters: ['', ''], preventAssignment: true }) - expect(translate({ replace: { __A__: '"a"' }, rollup: { replace: false } }).replace).toBeUndefined() - }) - - it('should accept options without an effect on the output', () => { - expect(translate({ - declaration: 'node16', - failOnWarn: false, - name: 'my-module', - rootDir: '.', - outDir: 'dist', - clean: true, - entries: [{ input: 'src/features/', outDir: 'dist/features', ext: 'mjs', addRelativeDeclarationExtensions: true }], - rollup: { emitCJS: false, cjsBridge: false, output: { exports: 'named' } }, - }).unsupported).toEqual([]) - }) - - it('should keep supported hooks, ignore mkdist hooks and reject the rest', () => { - const before = () => {} - const done = () => {} - const { hooks, ignoredHooks, unsupported } = translate({ hooks: { 'build:before': before, 'rollup:done': done, 'mkdist:entry:options': () => {}, 'rollup:options': () => {} } }) - expect(hooks).toEqual({ 'build:before': [before], 'rollup:done': [done], 'build:done': [] }) - expect(ignoredHooks).toEqual(['config0: hooks[\'mkdist:entry:options\']']) - expect(unsupported).toEqual(['config0: hooks[\'rollup:options\']']) - }) - - it('should not duplicate the default module entry', () => { - expect(bundledEntries(cwd, translate({ entries: ['src/module'] }))).toEqual({ module: './src/module.ts' }) - }) - - it('should load a config file, then `package.json`', async () => { - const dir = await mkdtemp(join(tmpdir(), 'module-builder-')) - try { - await writeFile(join(dir, 'build.config.mjs'), `export default [{ externals: ['a'] }, false]\n`) - const config = await loadBuildConfig(dir, { build: { externals: ['b'] } }, join(dir, 'dist')) - expect(config.file).toBe('build.config.mjs') - expect(config.importsUnbuild).toBe(false) - expect(config.field).toBe('build') - expect(config.neverBundle.map(String)).toEqual(['/^a(?:\\/|$)/', '/^b(?:\\/|$)/']) - expect(config.unsupported).toEqual([]) - - await rm(join(dir, 'build.config.mjs')) - await mkdir(join(dir, 'node_modules/unbuild'), { recursive: true }) - await writeFile(join(dir, 'node_modules/unbuild/package.json'), JSON.stringify({ name: 'unbuild', type: 'module', exports: './index.js' })) - await writeFile(join(dir, 'node_modules/unbuild/index.js'), 'export const defineBuildConfig = config => config\n') - await writeFile(join(dir, 'build.config.js'), `import { defineBuildConfig } from 'unbuild'\nexport default [defineBuildConfig({ externals: ['a'] }), { entries: ['src/utils'] }]\n`) - expect(await loadBuildConfig(dir, {}, join(dir, 'dist'))).toMatchObject({ importsUnbuild: true, field: undefined, unsupported: ['build.config.js: an array of 2 configs'] }) - - await rm(join(dir, 'build.config.js')) - await writeFile(join(dir, 'build.config.mts'), 'export default () => ({})\n') - await expect(loadBuildConfig(dir, {}, join(dir, 'dist'))).rejects.toThrow(`not a function. Replace the function with the object it returns. ${guide('other-options')}`) - - await rm(join(dir, 'build.config.mts')) - await mkdir(join(dir, 'extensions/src/lib'), { recursive: true }) - await writeFile(join(dir, 'extensions/options.ts'), `export default { externals: ['o'] }\n`) - await writeFile(join(dir, 'extensions/build.config.ts'), `import options from './options'\nexport default options\n`) - await writeFile(join(dir, 'extensions/src/module.ts'), `import { helper } from './helper'\nexport { shared } from './lib'\nexport default helper\n`) - await writeFile(join(dir, 'extensions/src/helper.ts'), `export const helper = 1\n`) - await writeFile(join(dir, 'extensions/src/lib/index.ts'), `import { shared } from '../../options'\nexport { shared }\n`) - await expect(loadBuildConfig(join(dir, 'extensions'), { build: { entries: ['src/lib/index'] } }, join(dir, 'dist'))).rejects.toThrow([ - 'Module code has to load with Node, which strips types and resolves imports as written:', - ' - build.config.ts:1:21: `./options` (use `./options.ts`)', - ' - src/lib/index.ts:1:24: `../../options` (use `../../options.ts`)', - ' - src/module.ts:1:24: `./helper` (use `./helper.ts`)', - ' - src/module.ts:2:24: `./lib` (use `./lib/index.ts`)', - `Change each one as suggested. ${guide('module-code-loads-with-node')}`, - ].join('\n')) - await writeFile(join(dir, 'extensions/build.config.ts'), `import options from './options.ts'\nexport default options\n`) - expect((await loadBuildConfig(join(dir, 'extensions'), {}, join(dir, 'dist'))).neverBundle.map(String)).toEqual(['/^o(?:\\/|$)/']) - - expect(await loadBuildConfig(dir, {}, join(dir, 'dist'))).toMatchObject({ file: undefined, unsupported: [] }) - const fromPkg = await loadBuildConfig(dir, { unbuild: { externals: ['u'] }, build: { externals: ['b'] } }, join(dir, 'dist')) - expect(fromPkg.neverBundle.map(String)).toEqual(['/^u(?:\\/|$)/']) - - const inferred = (await loadBuildConfig(dir, { name: '@nuxt/image', imports: { '#image/*': './src/*.ts' } }, join(dir, 'dist'))).neverBundle - expect(inferred).toHaveLength(1) - expect(['@nuxt/image', '@nuxt/image/utils'].every(id => inferred[0]!.test(id))).toBe(true) - expect(inferred[0]!.test('@nuxt/image/runtime/providers/ipx')).toBe(false) - } - finally { - await rm(dir, { recursive: true, force: true }) - } - }) - - it('should collect every option without an equivalent', () => { - expect(translate( - { hooks: { 'build:prepare': () => {} }, rollup: { emitCJS: true, output: { format: 'cjs' } }, stubOptions: {} }, - { externals: [42], replace: { __FN__: () => '' } }, - ).unsupported).toEqual([ - 'config0: hooks[\'build:prepare\']', - 'config0: rollup.emitCJS: true', - 'config0: rollup.output', - 'config0: stubOptions', - 'config1: externals[0]', - 'config1: replace[\'__FN__\']', - ]) - }) - - it('should point each unsupported option at its section of the upgrade guide', () => { - const message = formatUnsupportedOptions(['build.config.ts: hooks[\'rollup:options\']', 'build.config.ts: rollup.emitCJS: true', 'build.config.ts: rollup.alias', 'build.config.ts: entries[0].esbuild', 'build.config.ts: stubOptions']) - expect(message.split('\n')).toEqual([ - 'The build config uses options that `@nuxt/module-builder` v2 does not support:', - ` - build.config.ts: hooks['rollup:options'] (${guide('hooks')})`, - ` - build.config.ts: rollup.emitCJS: true (${guide('commonjs-output')})`, - ` - build.config.ts: rollup.alias (${guide('rollup-options')})`, - ` - build.config.ts: entries[0].esbuild (${guide('mkdist-options')})`, - ` - build.config.ts: stubOptions (${guide('other-options')})`, - `Remove each of them from the file named. ${guide('unsupported-build-options')}`, - ]) - }) - - it('should warn about a deprecated config file and ignored hooks in CI too', () => { - vi.stubEnv('CI', 'true') - const warn = vi.spyOn(consola, 'warn').mockImplementation(() => {}) - try { - const config = { ...translate({}), file: 'build.config.ts', importsUnbuild: true, ignoredHooks: ['build.config.ts: hooks[\'mkdist:entry:options\']'] } - warnDeprecatedBuildConfig(config) - warnDeprecatedBuildConfig({ ...config, importsUnbuild: false, ignoredHooks: [], field: 'unbuild' }) - expect(warn.mock.calls.map(([message]) => message)).toEqual([ - expect.stringMatching(new RegExp(`^Ignoring build\\.config\\.ts: hooks\\['mkdist:entry:options'\\]: .*Remove the hook\\. ${guide('hooks')}$`)), - expect.stringMatching(new RegExp(`^\`build\\.config\\.ts\` is deprecated\\. .*instead of \`unbuild\`\\. Move them into \`builder\\(\\)\` in \`tsdown\\.config\\.ts\`\\. ${guide('moving-from-buildconfigts')}$`)), - `\`build.config.ts\` is deprecated. Its options are still applied. Move them into \`builder()\` in \`tsdown.config.ts\`. ${guide('moving-from-buildconfigts')}`, - expect.stringMatching(new RegExp(`^The \`unbuild\` field of \`package\\.json\` is deprecated\\. .*Rename the field to \`build\`\\. ${guide('build-configuration')}$`)), - ]) - } - finally { - warn.mockRestore() - vi.unstubAllEnvs() - } - }) -}) - describe('upgrade guide', () => { it('should have a heading for every section that build messages link to', async () => { const markdown = await readFile(new URL('../docs/upgrade-v2.md', import.meta.url), 'utf8') @@ -991,12 +805,6 @@ describe('builder options', () => { expect(() => resolveModuleOptions(cwd, {}, outDir, { hooks: { 'build:before': () => {} } } as never)).toThrow(`\`builder()\` does not take \`hooks\`. Use tsdown's own \`hooks\` in the tsdown config, or a plugin that emits extra files. ${guide('hooks-in-a-tsdown-config')}`) }) - it('should refuse a `build` or `unbuild` field of `package.json` alongside it', () => { - expect(() => assertNoLegacyBuildConfig(cwd, { build: {} })).toThrow(`The \`build\` field of \`package.json\` configures the build, and so does \`builder()\` in the tsdown config. Move its options into \`builder()\` and remove the field. ${guide('moving-from-buildconfigts')}`) - expect(() => assertNoLegacyBuildConfig(cwd, { unbuild: {} })).toThrow('The `unbuild` field of `package.json`') - expect(() => assertNoLegacyBuildConfig(cwd, {})).not.toThrow() - }) - it('should list every tsdown option it sets that the config sets too', async () => { const config: UserConfig = { entry: 'src/index.ts', diff --git a/test/utils.ts b/test/utils.ts index e86b5c37..2d0bfb92 100644 --- a/test/utils.ts +++ b/test/utils.ts @@ -1,8 +1,11 @@ -import { cp, readFile, rm, writeFile } from 'node:fs/promises' +import { existsSync } from 'node:fs' +import { cp, mkdir, readdir, readFile, rm, symlink, writeFile } from 'node:fs/promises' +import { availableParallelism } from 'node:os' import { setTimeout as delay } from 'node:timers/promises' import { fileURLToPath, pathToFileURL } from 'node:url' -import { join } from 'pathe' +import { dirname, join } from 'pathe' import { exec } from 'tinyexec' +import type { PackageJson } from 'pkg-types' import { onTestFailed } from 'vitest' import { publishedPackage } from '../src/build/package.ts' @@ -10,26 +13,165 @@ import { publishedPackage } from '../src/build/package.ts' export const repoRoot = fileURLToPath(new URL('..', import.meta.url)) 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') +export const bin = (name: string) => join(repoRoot, 'node_modules/.bin', name) export const builderImport = `import { builder } from ${JSON.stringify(pathToFileURL(join(repoRoot, 'src/tsdown/index.ts')).href)}` +const buildEnv = { NODE_ENV: '', TEST: '', NUXT_TELEMETRY_DISABLED: '1' } -export async function copyExample(name: string, config: string) { - const dir = join(repoRoot, name) - await rm(dir, { recursive: true, force: true }) - await cp(exampleDir, dir, { recursive: true }) - await rm(join(dir, 'dist'), { recursive: true, force: true }) - const pkgPath = join(dir, 'package.json') - const { build: _, publishConfig: __, ...pkg } = publishedPackage(JSON.parse(await readFile(pkgPath, 'utf-8'))) - await writeFile(pkgPath, JSON.stringify(pkg, null, 2)) - await writeFile(join(dir, 'tsdown.config.ts'), `${builderImport}\n${config}`) - return dir +export interface Result { + output: string + stdout: string + exitCode: number | undefined } -export const tsdown = (cwd: string, args: string[] = [], env: Record = {}) => exec('node', [tsdownBin, ...args], { nodeOptions: { cwd, env: { ...process.env, NODE_ENV: '', TEST: '', ...env } } }) +/** Directories that hold one slot each of the processes that every spec file runs at once. */ +const slotsDir = join(repoRoot, '.temp-slots') -export function watch(cwd: string, args: string[]) { - const result = exec('node', args, { nodeOptions: { cwd, env: { ...process.env, NODE_ENV: '', TEST: '' } } }) +async function acquireSlot(): Promise { + for (;;) { + for (let index = 0; index < availableParallelism(); index++) { + const slot = join(slotsDir, String(index)) + try { + await mkdir(slot) + return slot + } + catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') { + await mkdir(slotsDir, { recursive: true }) + } + } + } + await delay(50 + Math.random() * 50) + } +} + +/** + * Runs a command with at most one process per CPU at a time across spec files, and resolves + * with its combined output. + */ +export async function run(command: string, args: string[], { cwd = repoRoot, env = {} }: { cwd?: string, env?: Record } = {}): Promise { + const slot = await acquireSlot() + try { + const result = await exec(command, args, { nodeOptions: { cwd, env: { ...process.env, ...buildEnv, ...env } } }) + return { output: result.stdout + result.stderr, stdout: result.stdout, exitCode: result.exitCode } + } + finally { + await rm(slot, { recursive: true, force: true }) + } +} + +export const cli = (args: string[], env?: Record) => run('node', [cliBin, ...args], { env }) + +export const tsdown = (cwd: string, args: string[] = [], env?: Record) => run('node', [tsdownBin, ...args], { cwd, env }) + +export async function succeed(result: Promise | Result): Promise { + const { output, exitCode } = await result + if (exitCode !== 0) { + throw new Error(`Exited with ${exitCode}:\n${output}`) + } + return output +} + +type Contents = string | ((source: string) => string) + +export interface FixtureOptions { + /** The directory to copy, `example` by default. */ + from?: string + /** + * The tsdown config, after an import of `builder`. `false` leaves the module without one and + * keeps the `build` field of `package.json`. + */ + config?: string | false + /** The source of `src/module.ts`, or a transform of it. */ + module?: Contents + /** Files to write, relative to the fixture, as contents or a transform of the existing file. */ + files?: Record + /** Files and directories to remove, before `files` are written. */ + remove?: string[] + /** A transform of `package.json`. */ + pkg?: (pkg: PackageJson) => PackageJson + /** `paths` to merge into `.nuxt/tsconfig.json`. */ + paths?: Record + /** Symlinks to create, as link to target, relative to the fixture. */ + links?: Record +} + +const DEFAULT_CONFIG = `export default {\n plugins: [builder({ entries: ['./src/utils'] })],\n}\n` + +/** + * Copies `example` to `dir` under the repository, without `dist`, with `package.json` as it is + * published and a tsdown config that builds it with `builder()`. + */ +export async function fixture(dir: string, { from = exampleDir, config = DEFAULT_CONFIG, module, files = {}, remove = [], pkg, paths, links = {} }: FixtureOptions = {}): Promise { + const root = join(repoRoot, dir) + await rm(root, { recursive: true, force: true }) + await mkdir(dirname(root), { recursive: true }) + await cp(from, root, { recursive: true }) + await rm(join(root, 'dist'), { recursive: true, force: true }) + const pkgPath = join(root, 'package.json') + const { build, publishConfig: _, ...published } = publishedPackage(JSON.parse(await readFile(pkgPath, 'utf-8'))) + const copied = config === false ? { ...published, build } : published + await writeFile(pkgPath, JSON.stringify(pkg ? pkg(copied) : copied, null, 2)) + if (config !== false) { + await writeFile(join(root, 'tsdown.config.ts'), `${builderImport}\n${config}`) + } + for (const file of remove) { + await rm(join(root, file), { recursive: true, force: true }) + } + for (const [file, contents] of Object.entries({ ...module !== undefined && { 'src/module.ts': module }, ...files })) { + const path = join(root, file) + await mkdir(dirname(path), { recursive: true }) + await writeFile(path, typeof contents === 'function' ? contents(await readFile(path, 'utf-8')) : contents) + } + if (paths) { + const tsconfig = join(root, '.nuxt/tsconfig.json') + const config = JSON.parse(await readFile(tsconfig, 'utf-8')) + config.compilerOptions.paths = { ...config.compilerOptions.paths, ...paths } + await writeFile(tsconfig, JSON.stringify(config, null, 2)) + } + const playgroundLink = existsSync(join(root, 'playground/node_modules')) ? { 'playground/node_modules/my-module': '.' } : {} + for (const [link, target] of Object.entries({ ...playgroundLink, ...links })) { + await mkdir(dirname(join(root, link)), { recursive: true }) + await rm(join(root, link), { recursive: true, force: true }) + await symlink(join(root, target), join(root, link)) + } + return root +} + +export const listFiles = async (dir: string) => (await readdir(dir, { recursive: true })).map(file => file.replaceAll('\\', '/')).sort() + +export const read = (...segments: string[]) => readFile(join(...segments), 'utf-8') + +export const exists = (...segments: string[]) => existsSync(join(...segments)) + +export async function unresolvedSpecifiers(dir: string) { + const failures: string[] = [] + for (const entry of await listFiles(dir)) { + if (!/\.d\.[^/]*ts$/.test(entry)) { + continue + } + const file = join(dir, entry) + for (const [, specifier] of (await readFile(file, 'utf-8')).matchAll(/(?:\bfrom\s*|\bimport\s*\(\s*|\bimport\s+)['"](\.\.?\/[^'"]*)['"]/g)) { + const target = join(dirname(file), specifier!) + const candidates = /\.jsx?$/.test(specifier!) + ? [target.replace(/\.jsx?$/, '.d.ts')] + : specifier!.endsWith('.mjs') + ? [target.replace(/\.mjs$/, '.d.mts')] + : specifier!.endsWith('.vue') + ? [`${target}.d.ts`, target.replace(/\.vue$/, '.d.vue.ts')] + : specifier!.endsWith('.css') ? [target] : [] + if (!candidates.some(candidate => existsSync(candidate))) { + failures.push(`${entry}: ${specifier}`) + } + } + } + return failures +} + +export function watch(cwd: string, args: string[], onFailed: typeof onTestFailed = onTestFailed) { + const result = exec('node', args, { nodeOptions: { cwd, env: { ...process.env, ...buildEnv } } }) let output = '' - onTestFailed(() => { + onFailed(() => { console.error(`Output of \`node ${args.join(' ')}\`:\n${output.slice(-8000)}`) }) for (const stream of [result.process?.stdout, result.process?.stderr]) { @@ -46,7 +188,7 @@ export function watch(cwd: string, args: string[]) { } } -export async function waitFor(check: () => Promise, timeout = 60_000) { +export async function waitFor(check: () => Promise | boolean, timeout = 60_000) { const end = Date.now() + timeout while (!await check()) { if (Date.now() > end) { diff --git a/test/watch.spec.ts b/test/watch.spec.ts new file mode 100644 index 00000000..d8220f4c --- /dev/null +++ b/test/watch.spec.ts @@ -0,0 +1,290 @@ +import { createHash } from 'node:crypto' +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 { builderImport, exists, fixture, read, repoRoot, run, succeed, tsdown, tsdownBin, waitFor, watch } from './utils.ts' + +const PLUGIN = `export default {\n plugins: [builder()],\n}\n` +const tsdownApi = JSON.stringify(pathToFileURL(join(repoRoot, 'node_modules/tsdown/dist/index.mjs')).href) +const withoutConfig = { config: false, pkg: ({ build: _, ...pkg }: PackageJson) => pkg } as const +const sizeRows = (output: string) => [...output.matchAll(/(dist\/(?:module\.mjs|runtime\/))\s[^\n]*types/g)].map(match => match[1]).sort() + +async function outputs(dir: string) { + const files = (await readdir(dir, { recursive: true, withFileTypes: true })).filter(file => file.isFile()) + return new Map(await Promise.all(files.map(async (file) => { + const path = join(file.parentPath, file.name) + return [relative(dir, path), { mtime: (await stat(path, { bigint: true })).mtimeNs, hash: createHash('sha256').update(await readFile(path)).digest('hex') }] as const + }))) +} + +describe.concurrent('tsdown --watch', () => { + describe('with a module whose entry imports runtime code', () => { + let dir: string + let watcher: ReturnType + const dist = (file: string) => join(dir, 'dist', file) + let previous = Promise.resolve() + const finished: Array<() => void> = [] + const inOrder = (test: () => Promise) => { + const prior = previous + let done!: () => void + previous = new Promise((resolve) => { + done = resolve + }) + finished.push(done) + return ({ task }: TestContext) => { + task.suite!.tasks.forEach((sibling, index) => { + if (sibling.mode === 'skip' || sibling.mode === 'todo') { + finished[index]!() + } + }) + return prior.then(test).finally(done) + } + } + + beforeAll(async () => { + dir = await fixture('.temp-watch/module', { + config: PLUGIN, + module: source => `import { moduleName } from './runtime/name.ts'\n${source.replace(`name: 'my-module'`, 'name: moduleName')}`, + files: { + 'src/runtime/name.ts': `export const moduleName: string = 'from-runtime'\n`, + 'src/runtime/removed.ts': `export const removed: string = 'removed'\n`, + 'src/shared.ts': `export const shared: string = 'first'\n`, + 'src/runtime/use.ts': `import { shared } from '../shared'\n\nexport const useShared = (): string => shared\n`, + }, + }) + watcher = watch(dir, [tsdownBin, '--watch'], () => {}) + await waitFor(() => exists(dist('module.json')) && exists(dist('types.d.mts'))) + }) + + afterAll(() => watcher?.stop()) + + afterEach(({ task }) => { + if (task.result?.state === 'fail') { + console.error(`Output of \`tsdown --watch\`:\n${watcher.output().slice(-8000)}`) + } + }) + + it('should report the size of each entry and runtime directory once', inOrder(async () => { + await waitFor(async () => sizeRows(watcher.output()).length >= 2 && exists(dist('types.d.mts')) && exists(dist('module.json'))) + await delay(1000) + expect(sizeRows(watcher.output())).toEqual(['dist/module.mjs', 'dist/runtime/']) + expect(JSON.parse(await read(dist('module.json'))).name).toBe('from-runtime') + })) + + it('should rewrite `module.json` when a file the module entry imports changes', inOrder(async () => { + await writeFile(join(dir, 'src/runtime/name.ts'), `export const moduleName: string = 'changed-runtime'\n`) + await waitFor(async () => JSON.parse(await read(dist('module.json'))).name === 'changed-runtime') + })) + + it('should rebuild when a file is added to the runtime directory', inOrder(async () => { + await mkdir(join(dir, 'src/runtime/utils/nested'), { recursive: true }) + await writeFile(join(dir, 'src/runtime/utils/nested/added.ts'), `export const added: string = 'added'\n`) + await waitFor(() => exists(dist('runtime/utils/nested/added.js')) && exists(dist('runtime/utils/nested/added.d.ts'))) + })) + + it('should compile JSX in a server runtime file added', inOrder(async () => { + await mkdir(join(dir, 'src/runtime/server'), { recursive: true }) + await writeFile(join(dir, 'src/runtime/server/render.tsx'), `export const render = (): unknown =>

hi

\n`) + await waitFor(() => exists(dist('runtime/server/render.js')) || exists(dist('runtime/server/render.jsx'))) + expect(exists(dist('runtime/server/render.jsx'))).toBe(false) + expect(await read(dist('runtime/server/render.js'))).toContain('vue/jsx-runtime') + })) + + it('should rebuild when a file outside the runtime directory that a runtime file imports changes', inOrder(async () => { + await waitFor(async () => (await read(dist('shared.js'))).includes('first')) + await writeFile(join(dir, 'src/shared.ts'), `export const shared: string = 'second'\n`) + await waitFor(async () => (await read(dist('shared.js'))).includes('second')) + })) + + it('should remove the output of a deleted runtime file', inOrder(async () => { + expect(exists(dist('runtime/removed.js'))).toBe(true) + await rm(join(dir, 'src/runtime/removed.ts')) + await waitFor(() => !exists(dist('runtime/removed.js')) && !exists(dist('runtime/removed.d.ts'))) + expect(exists(dist('runtime/plugins/plugin.js'))).toBe(true) + })) + + it('should rewrite `#app` in an added declaration file', inOrder(async () => { + await writeFile(join(dir, 'src/runtime/composables/added.d.ts'), `import type { NuxtApp } from '#app'\nexport type Added = NuxtApp\n`) + await waitFor(async () => exists(dist('runtime/composables/added.d.ts')) && (await read(dist('runtime/composables/added.d.ts'))).includes(`from 'nuxt/app'`)) + })) + + it('should rewrite `types.d.mts` and report sizes once when the module entry changes', inOrder(async () => { + const seen = watcher.output().length + await writeFile(join(dir, 'src/module.ts'), `${await read(dir, 'src/module.ts')}\nexport const rebuiltMarker: string = 'rebuilt'\n`) + await waitFor(async () => (await read(dist('types.d.mts'))).includes('rebuiltMarker') && sizeRows(watcher.output().slice(seen)).length >= 2) + await delay(1000) + expect(sizeRows(watcher.output().slice(seen))).toEqual(['dist/module.mjs', 'dist/runtime/']) + expect(JSON.parse(await read(dist('module.json'))).name).toBe('changed-runtime') + })) + + for (const [target, file, recovered] of [ + ['the module entry', 'src/module.ts', 'types.d.mts'], + ['a runtime file', 'src/runtime/plugins/plugin.ts', 'runtime/plugins/plugin.js'], + ] as const) { + it(`should keep the previous output when a rebuild of ${target} fails, and recover on the next good save`, inOrder(async () => { + const files = ['module.mjs', 'module.d.mts', 'module.json', 'types.d.mts', 'runtime/plugins/plugin.js'].map(dist) + const source = await read(dir, file) + const before = await Promise.all(files.map(output => read(output))) + const seen = watcher.output().length + await writeFile(join(dir, file), `${source}\nexport const broken = (\n`) + await waitFor(() => /error/i.test(watcher.output().slice(seen))) + await delay(1000) + expect(await Promise.all(files.map(output => read(output)))).toEqual(before) + await writeFile(join(dir, file), `${source}\nexport const recoveredMarker: string = 'recovered'\n`) + await waitFor(async () => (await read(dist(recovered))).includes('recoveredMarker')) + })) + } + }) + + it('should rebuild when a file is added to a missing runtime directory', async ({ onTestFailed }) => { + const dir = await fixture('.temp-watch/without-runtime', { + config: PLUGIN, + remove: ['src/runtime'], + module: `import { defineNuxtModule } from '@nuxt/kit'\n\nexport default defineNuxtModule({ meta: { name: 'my-module' } })\n`, + }) + const watcher = watch(dir, [tsdownBin, '--watch'], onTestFailed) + try { + await waitFor(() => exists(dir, 'dist/module.json')) + await mkdir(join(dir, 'src/runtime/utils'), { recursive: true }) + await writeFile(join(dir, 'src/runtime/utils/added.ts'), `export const added: string = 'added'\n`) + await waitFor(() => exists(dir, 'dist/runtime/utils/added.js') && exists(dir, 'dist/runtime/utils/added.d.ts')) + } + finally { + await watcher.stop() + } + }) + + it('should keep `dist` while a watched build starts, and empty it before a one-off build', async ({ onTestFailed }) => { + const dir = await fixture('.temp-watch/kept', { config: PLUGIN }) + const distDir = join(dir, 'dist') + const stale = ['stale.txt', 'runtime/components/Removed.vue'] + const addStale = () => Promise.all(stale.map(file => writeFile(join(distDir, file), 'stale\n'))) + + await succeed(tsdown(dir)) + await addStale() + await succeed(tsdown(dir)) + expect(stale.filter(file => exists(distDir, file))).toEqual([]) + + await addStale() + const before = await outputs(distDir) + const watcher = watch(dir, [tsdownBin, '--watch'], onTestFailed) + let missing = false + try { + await waitFor(async () => { + missing ||= !exists(distDir, 'module.mjs') || !exists(distDir, 'runtime/plugins/plugin.js') + return /Rebuilt in/.test(watcher.output()) + }) + const after = await outputs(distDir) + expect(missing).toBe(false) + expect([...before.keys()].filter(file => !after.has(file)).sort()).toEqual([...stale].sort()) + expect([...after.keys()].filter(file => before.get(file)!.mtime !== after.get(file)!.mtime && !file.endsWith('.d.ts'))).toEqual([]) + } + finally { + await watcher.stop() + } + }) + + it('should only write the outputs whose content changes', async ({ onTestFailed }) => { + const dir = await fixture('.temp-watch/unchanged', { + config: `export default {\n plugins: [\n builder({ entries: ['./src/utils'] }),\n { name: 'user-asset', generateBundle() { this.emitFile({ type: 'asset', fileName: 'user.txt', source: 'user asset\\n' }) } },\n ],\n}\n`, + }) + const distDir = join(dir, 'dist') + const changes = (before: Awaited>, after: Awaited>) => ({ + changed: [...after.keys()].filter(file => before.has(file) && before.get(file)!.mtime !== after.get(file)!.mtime).sort(), + added: [...after.keys()].filter(file => !before.has(file)).sort(), + removed: [...before.keys()].filter(file => !after.has(file)).sort(), + }) + const watcher = watch(dir, [tsdownBin, '--watch'], onTestFailed) + const rebuilds = () => watcher.output().match(/Rebuilt in/g)?.length ?? 0 + const rebuild = async (change: () => Promise) => { + const before = await outputs(distDir) + const count = rebuilds() + await change() + await waitFor(() => rebuilds() > count) + return changes(before, await outputs(distDir)) + } + const edit = async (file: string, from: string, to: string) => writeFile(join(dir, file), (await read(dir, file)).replace(from, to)) + try { + await waitFor(() => rebuilds() > 0 && exists(distDir, 'module.json') && exists(distDir, 'types.d.mts')) + expect(await read(distDir, 'user.txt')).toBe('user asset\n') + + await rm(join(distDir, 'runtime/plugins/plugin.js')) + expect(await rebuild(() => edit('src/runtime/components/TestMe.vue', '', ''))).toEqual({ changed: [], added: ['runtime/plugins/plugin.js'], removed: [] }) + + expect(await rebuild(() => edit('src/runtime/components/TestMe.vue', '{{ count }}', 'count: {{ count }}'))).toEqual({ changed: ['runtime/components/TestMe.vue'], added: [], removed: [] }) + expect(await rebuild(() => edit('src/runtime/components/TestMe.vue', '', ''))).toEqual({ changed: [], added: [], removed: [] }) + expect(await rebuild(() => edit('src/module.ts', `name: 'my-module'`, `name: 'my-renamed-module'`))).toEqual({ changed: ['module.json', 'module.mjs'], added: [], removed: [] }) + expect(await rebuild(() => rm(join(dir, 'src/runtime/composables/useAppNuxt.ts')))).toEqual({ changed: [], added: [], removed: ['runtime/composables/useAppNuxt.d.ts', 'runtime/composables/useAppNuxt.js'] }) + + const before = await outputs(distDir) + const plugin = await read(dir, 'src/runtime/plugins/plugin.ts') + const failures = () => watcher.output().match(/Failed to transpile/g)?.length ?? 0 + const failed = failures() + await writeFile(join(dir, 'src/runtime/plugins/plugin.ts'), `${plugin}\nexport const broken: = 1\n`) + await waitFor(() => failures() > failed) + expect(changes(before, await outputs(distDir))).toEqual({ changed: [], added: [], removed: [] }) + expect(await rebuild(() => writeFile(join(dir, 'src/runtime/plugins/plugin.ts'), plugin))).toEqual({ changed: [], added: [], removed: [] }) + expect([...(await outputs(distDir)).entries()].map(([file, { hash }]) => [file, hash])).toEqual([...before.entries()].map(([file, { hash }]) => [file, hash])) + } + finally { + await watcher.stop() + } + }) + + it('should not keep more memory with each rebuild', async () => { + const dir = await fixture('.temp-watch/memory', withoutConfig) + const file = join(dir, 'src/runtime/composables/useWrappedFetch.ts') + await mkdir(join(dir, 'src/shared'), { recursive: true }) + await writeFile(join(dir, 'src/shared/format.ts'), `export const format = (value: string): string => value.trim()\n`) + await writeFile(join(dir, 'watch.mjs'), [ + `import { readFileSync, writeFileSync } from 'node:fs'`, + `import { build } from ${tsdownApi}`, + builderImport, + `const source = readFileSync(${JSON.stringify(file)}, 'utf8')`, + `let built, idle, started`, + `const settled = { name: 'settled', buildStart() { started = true; clearTimeout(idle) }, writeBundle: { order: 'post', handler() { idle = setTimeout(() => started && built(), 250) } } }`, + `const handle = await build({ cwd: ${JSON.stringify(dir)}, config: false, watch: true, logLevel: 'silent', plugins: [builder({ entries: [{ input: 'src/shared/', outDir: 'dist/shared' }] }), settled] })`, + `const heap = []`, + `for (let round = 0; round < 6; round++) {`, + ` await new Promise(resolve => { built = resolve; started = false; writeFileSync(${JSON.stringify(file)}, source + 'export const round = ' + round + '\\n') })`, + ` globalThis.gc()`, + ` heap.push(process.memoryUsage().heapUsed)`, + `}`, + `await handle.watch.close()`, + `console.log(JSON.stringify(heap))`, + `process.exit(0)`, + '', + ].join('\n')) + const { stdout, exitCode, output } = await run('node', ['--expose-gc', 'watch.mjs'], { cwd: dir }) + expect(exitCode, output).toBe(0) + const heap = JSON.parse(stdout.trim().split('\n').at(-1)!) as number[] + expect(heap.at(-1)! - heap[2]!).toBeLessThan(64 * 1024 * 1024) + }) + + it('should write current metadata from each build session in the same process', async () => { + const dir = await fixture('.temp-watch/sessions', withoutConfig) + await writeFile(join(dir, 'sessions.mjs'), [ + `import { readFile, writeFile } from 'node:fs/promises'`, + `import { build } from ${tsdownApi}`, + builderImport, + `const cwd = ${JSON.stringify(dir)}`, + `const source = await readFile(cwd + '/src/module.ts', 'utf8')`, + `const names = []`, + `for (const name of ['first-session', 'second-session']) {`, + ` await writeFile(cwd + '/src/module.ts', source.replace("name: 'my-module'", 'name: ' + JSON.stringify(name)))`, + ` await build({ cwd, config: false, logLevel: 'silent', plugins: [builder()] })`, + ` names.push(JSON.parse(await readFile(cwd + '/dist/module.json', 'utf8')).name)`, + `}`, + `console.log(JSON.stringify(names))`, + '', + ].join('\n')) + const { stdout, exitCode, output } = await run('node', ['sessions.mjs'], { cwd: dir }) + expect(exitCode, output).toBe(0) + expect(JSON.parse(stdout.trim().split('\n').at(-1)!)).toEqual(['first-session', 'second-session']) + }) +}) diff --git a/vitest.config.mts b/vitest.config.mts index ed24f31f..c5a2ab17 100644 --- a/vitest.config.mts +++ b/vitest.config.mts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' const config: ReturnType = defineConfig({ test: { coverage: {}, + globalSetup: ['./test/setup.ts'], testTimeout: 180_000, hookTimeout: 180_000, }, From 06e99d710f331ffe950b9bfbb1753b068599472c Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Tue, 17 Nov 2026 07:24:52 +0000 Subject: [PATCH 02/21] fix: address audit findings in the build, loader and docs --- README.md | 3 +- docs/index.md | 2 +- docs/upgrade-v2.md | 6 +- package.json | 4 +- src/build/aliases.ts | 23 +++-- src/build/build-config.ts | 16 ++-- src/build/build.ts | 56 ++++++----- src/build/define.ts | 4 +- src/build/deprecations.ts | 2 +- src/build/guide.ts | 1 - src/build/loader.ts | 17 +--- src/build/module-declarations.ts | 3 +- src/build/tsconfig.ts | 11 ++- src/commands/_shared.ts | 5 +- src/commands/prepare.ts | 2 +- src/rolldown/declarations.ts | 8 +- src/rolldown/resolve.ts | 22 +++-- src/rolldown/transpile-dir.ts | 3 +- src/tsdown/externals.ts | 11 ++- src/tsdown/setup.ts | 7 +- src/utils.ts | 22 +++++ test/cli.spec.ts | 4 +- test/regressions.spec.ts | 153 +++++++++++++++++++++++++++++++ test/unit.spec.ts | 3 +- 24 files changed, 290 insertions(+), 98 deletions(-) create mode 100644 src/utils.ts create mode 100644 test/regressions.spec.ts diff --git a/README.md b/README.md index f3ee94d8..8c59b8a0 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ Create a module from the [module starter](https://github.com/nuxt/starter/tree/m npm create nuxt -- -t module my-module ``` -Building a module requires Node `^22.18.0 || >=24.0.0`, with `tsdown` and `typescript` installed alongside `@nuxt/module-builder`. Apps that install a built module need Nuxt 3 or later. +Building a module requires Node `^22.18.0 || ^24.11.0 || >=26.0.0`, with `tsdown` and `typescript` installed alongside `@nuxt/module-builder`. Apps that install a built module need Nuxt 3 or later. ## Documentation @@ -43,7 +43,6 @@ For writing the module itself, read the [Nuxt Module Author Guide](https://nuxt. ## πŸ’» Development - Clone repository -- Enable [Corepack](https://github.com/nodejs/corepack) using `corepack enable` - Install dependencies using `pnpm install` - Try building [example module](./example) using `pnpm example:build` diff --git a/docs/index.md b/docs/index.md index 169cced6..a18229ee 100644 --- a/docs/index.md +++ b/docs/index.md @@ -13,7 +13,7 @@ navigation: To build a module, you need: -- Node `^22.18.0 || >=24.0.0`. +- Node `^22.18.0 || ^24.11.0 || >=26.0.0`. - `tsdown` and `typescript` (`^5.9.3 || ^6.0.0`), which are peer dependencies of `@nuxt/module-builder`. - `nuxt`, which provides the `@nuxt/cli` that `nuxt-module-build prepare` runs. diff --git a/docs/upgrade-v2.md b/docs/upgrade-v2.md index 1ae9d6d1..12c4c75b 100644 --- a/docs/upgrade-v2.md +++ b/docs/upgrade-v2.md @@ -9,7 +9,7 @@ Most modules upgrade by running the build and following its output. Every messag ## Node engines -v2 requires Node `^22.18.0 || >=24.0.0`. Use Node 22.18+ or 24+ locally and in CI: +v2 requires Node `^22.18.0 || ^24.11.0 || >=26.0.0`. Use Node 22.18+, 24.11+, or 26+ locally and in CI: ```yaml # .github/workflows/ci.yml @@ -611,7 +611,7 @@ Each file under `src/runtime` is still emitted under `dist/runtime` with its nam ## Output directory -A one-off build empties `--outDir` (`dist` by default) before it writes to it. `tsdown --watch` removes the files in it that the build doesn't emit any more. The directory must therefore be inside your module. An `--outDir` of `.`, or of a directory that contains the module, fails the build. +A one-off build empties `--outDir` (`dist` by default) before it writes to it. `tsdown --watch` removes the files in it that the build doesn't emit any more. The directory must therefore be inside your module. An `--outDir` outside the module, such as `../dist`, or the module root itself, fails the build. ## Module tsconfig @@ -872,7 +872,7 @@ pnpm remove unbuild Follow these steps in order to upgrade a module. Each step is mechanical until the build runs. Where a step says `pnpm`, use your module's own package manager. -1. Use Node 22.18+ or 24+ locally and in CI. +1. Use Node 22.18+, 24.11+, or 26+ locally and in CI. 2. Install v2 and tsdown, before step 3: - Run `pnpm add -D @nuxt/module-builder@^2.0.0 tsdown@^0.23.7`. - Run `pnpm remove unbuild`. Also remove `mkdist` and `jiti`, if they only served the builder. diff --git a/package.json b/package.json index 4f68736f..b661c0ad 100644 --- a/package.json +++ b/package.json @@ -43,7 +43,7 @@ "prepack": "pnpm build", "test": "pnpm vitest", "test:pack": "pnpm -C example pack --out ../.temp-pack/example.tgz && attw .temp-pack/example.tgz && publint .temp-pack/example.tgz", - "test:engines": "pnpm exec installed-check -d -i tsdown --no-workspaces --ignore @nuxt/cli", + "test:engines": "pnpm exec installed-check -d --no-workspaces --ignore @nuxt/cli", "test:knip": "knip --exclude unresolved", "test:types": "vue-tsc --noEmit && pnpm -r test:types" }, @@ -108,6 +108,6 @@ "vue-tsc": "^3.3.14" }, "engines": { - "node": "^22.18.0 || >=24.0.0" + "node": "^22.18.0 || ^24.11.0 || >=26.0.0" } } diff --git a/src/build/aliases.ts b/src/build/aliases.ts index e45e6a75..48f36a5d 100644 --- a/src/build/aliases.ts +++ b/src/build/aliases.ts @@ -1,6 +1,7 @@ import { existsSync, promises as fsp } from 'node:fs' import { dirname, join, resolve } from 'pathe' +const APP_ALIAS_RE = /(\bfrom\s*|\bimport\s*\(\s*)(['"])#app(?:\/[^'"]*)?\2/g const RELATIVE_SPECIFIER_RE = /(\bfrom\s*|\bimport\s*\(\s*|\bimport\s+)(['"])(\.\.?\/[^'"]*)\2/g const DECLARATION_TARGETS = [ ['.d.ts', '.js'], @@ -15,20 +16,16 @@ const DECLARATION_TARGETS = [ * * - Relative specifiers without an extension get the one of the file they resolve to in * `outDir`, so they resolve under `node16` and `nodenext` module resolution. - * - `#app` aliases, which tsc prints whenever the real path is not reachable through - * `node_modules` and which only resolve inside a Nuxt app, become `nuxt/app`. + * - `#app` aliases become `nuxt/app`, see {@link rewriteAppAliases}. */ export async function rewriteRuntimeDeclarations(outDir: string, outputs: string[]): Promise { const files = outputs.flatMap(output => declarationsOf(join(outDir, output))).filter(file => existsSync(file)) await Promise.all(files.map(async (file) => { const contents = await fsp.readFile(file, 'utf8') - const rewritten = contents - .replace(RELATIVE_SPECIFIER_RE, (match, prefix: string, quote: string, specifier: string) => { - const resolved = resolveDeclarationSpecifier(dirname(file), specifier) ?? specifier - return resolved === specifier ? match : `${prefix}${quote}${resolved}${quote}` - }) - .replace(/import\("#app(?:\/[^"]*)?"\)/g, 'import("nuxt/app")') - .replace(/(\bfrom\s*)(['"])#app(?:\/[^'"]*)?\2/g, '$1$2nuxt/app$2') + const rewritten = rewriteAppAliases(contents.replace(RELATIVE_SPECIFIER_RE, (match, prefix: string, quote: string, specifier: string) => { + const resolved = resolveDeclarationSpecifier(dirname(file), specifier) ?? specifier + return resolved === specifier ? match : `${prefix}${quote}${resolved}${quote}` + })) if (rewritten !== contents) { await fsp.writeFile(file, rewritten, 'utf8') @@ -36,6 +33,14 @@ export async function rewriteRuntimeDeclarations(outDir: string, outputs: string })) } +/** + * `code` with `#app` aliases, which tsc prints whenever the real path is not reachable through + * `node_modules` and which only resolve inside a Nuxt app, written as `nuxt/app`. + */ +export function rewriteAppAliases(code: string): string { + return code.replace(APP_ALIAS_RE, '$1$2nuxt/app$2') +} + /** * The paths, relative to `outDir`, whose presence decides how {@link rewriteRuntimeDeclarations} * rewrites the relative specifiers in `code`, the declaration emitted as `fileName`. diff --git a/src/build/build-config.ts b/src/build/build-config.ts index 6824d2da..aef16b5b 100644 --- a/src/build/build-config.ts +++ b/src/build/build-config.ts @@ -4,6 +4,7 @@ import { isAbsolute, normalize, relative, resolve } from 'pathe' import { consola } from 'consola' import type { PackageJson } from 'pkg-types' +import { isInside } from '../utils.ts' import type { BuildContext, BuildHook } from './define.ts' import { guide } from './guide.ts' import type { GuideSection } from './guide.ts' @@ -82,7 +83,7 @@ export function translateBuildConfig(sources: BuildConfigSource[], options: Tran ignoredHooks: [], unsupported: [], } - const replace: ReplaceOptions = { values: {}, preventAssignment: true } + const replace: ReplaceOptions = { values: {} } let replaceDisabled = false const runtime = { srcDir: resolve(cwd, 'src/runtime'), outDir: resolve(outDir, 'runtime') } @@ -212,6 +213,9 @@ export function translateBuildConfig(sources: BuildConfigSource[], options: Tran } const name = typeof normalised.name === 'string' ? normalised.name : entryName(input, cwd) + if (name === 'types') { + throw new Error(`\`${source}\` has a bundled entry named \`types\`, whose declarations would replace the generated \`types.d.mts\`. Give \`${input}\` another \`name\`.`) + } const file = probe(resolve(cwd, input)) ?? resolve(cwd, `${input}.ts`) result.entries[name] = `./${relative(cwd, file)}` } @@ -262,7 +266,7 @@ export function translateBuildConfig(sources: BuildConfigSource[], options: Tran } } else if (key === 'preventAssignment' || key === 'objectGuards') { - replace[key] = value === true + replace[key] ??= value === true } } } @@ -284,7 +288,7 @@ export function translateBuildConfig(sources: BuildConfigSource[], options: Tran } if (!replaceDisabled && Object.keys(replace.values).length) { - result.replace = replace + result.replace = { ...replace, preventAssignment: replace.preventAssignment ?? true } } return result @@ -310,11 +314,11 @@ export interface LoadedBuildConfig extends TranslatedBuildConfig { const UNBUILD_IMPORT_RE = /\bfrom\s*['"]unbuild['"]/ -/** Resolves `outDir` against `cwd`, refusing a directory the build would empty the module root with. */ +/** Resolves `outDir` against `cwd`, refusing a directory outside the module, which the build would empty. */ export function resolveOutDir(cwd: string, outDir: string, label: string = `--outDir ${outDir}`): string { const resolved = resolve(cwd, outDir) - if (!relative(resolved, cwd).startsWith('..')) { - throw new Error(`\`${label}\` resolves to \`${resolved}\`, which contains the module root; the build empties the output directory first. Use a directory inside the module such as \`dist\`. ${guide('output-directory')}`) + if (resolved === cwd || !isInside(cwd, resolved)) { + throw new Error(`\`${label}\` resolves to \`${resolved}\`, which is not inside the module root; the build empties the output directory first. Use a directory inside the module such as \`dist\`. ${guide('output-directory')}`) } return resolved } diff --git a/src/build/build.ts b/src/build/build.ts index 79ba695a..6c35465b 100644 --- a/src/build/build.ts +++ b/src/build/build.ts @@ -8,10 +8,11 @@ import type { PackageJson } from 'pkg-types' import { glob, globSync } from 'tinyglobby' import builderPkg from '../../package.json' with { type: 'json' } -import { probe as probeSource, scriptExtension, valueSpecifiers } from '../rolldown/resolve.ts' +import { DECLARATION_RE, probe as probeSource, scriptExtension, valueSpecifiers } from '../rolldown/resolve.ts' import { DEFAULT_EXCLUDE } from '../rolldown/transpile-dir.ts' import type { ResolveExternal } from '../rolldown/transpile-dir.ts' import { createTsconfigResolver, declarationPaths, findPackageDir, namedCachePath, tsconfigPaths, writeDependencyImports, writeDerivedTsconfig, writeServerRoutesStub } from '../rolldown/tsconfig.ts' +import { relativeSpecifier } from '../utils.ts' import { shouldAdvise } from './advice.ts' import { rewriteRuntimeDeclarations } from './aliases.ts' import { bundledEntries, callBuildHook, createBuildContext, formatUnsupportedOptions, warnDeprecatedBuildConfig } from './build-config.ts' @@ -90,8 +91,6 @@ export interface BuildPlan { generatedTypesHash: string /** Set by {@link prepareBuild}. */ prepared?: PreparedBuild - /** Whether {@link finishBuild} writes `types.d.mts`, rather than a bundled entry named `types`. */ - writesTypes?: boolean } export interface PreparedBuild { @@ -110,8 +109,6 @@ export async function resolveBuild({ cwd, pkg, outDir, sourcemap, loadConfig }: const advice = path.startsWith('..') ? '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')}`) } - const selfPaths = selfReferencePaths(cwd, pkg, outDir) - const config = await loadConfig() if (config.unsupported.length) { throw new Error(formatUnsupportedOptions(config.unsupported)) @@ -122,8 +119,9 @@ export async function resolveBuild({ cwd, pkg, outDir, sourcemap, loadConfig }: const resolvedSourcemap = sourcemap || config.sourcemap const ctx = createBuildContext({ cwd, outDir, pkg, config, directories, sourcemap: resolvedSourcemap }) const entries = bundledEntries(cwd, config) + const selfPaths = selfReferencePaths(cwd, pkg, outDir, entries) - const moduleTsconfig = tsconfigs.resolve(resolve(cwd, entries.module ?? Object.values(entries)[0]!)) + const moduleTsconfig = tsconfigs.resolve(resolve(cwd, entries.module)) const nuxtDir = findPackageDir('nuxt', cwd) return { @@ -249,13 +247,15 @@ export interface FinishBuildOptions { outputs: string[] /** Versions recorded as `builder` in `module.json`, besides this package's. */ builder: Record + /** Keeps the output when the built module cannot be loaded, as a watcher goes on serving it. */ + keepOutput?: boolean } // Counted per process, as a restarted watcher imports the same files again with a new plan. let metaImports = 0 /** Writes `module.json` and `types.d.mts`, finalises declarations and runs the checks and remaining hooks. */ -export async function finishBuild(plan: BuildPlan, { outputs, builder }: FinishBuildOptions): Promise { +export async function finishBuild(plan: BuildPlan, { outputs, builder, keepOutput }: FinishBuildOptions): Promise { const { cwd, outDir, pkg } = plan const duration = Date.now() - (plan.prepared?.startedAt ?? Date.now()) const version = metaImports++ || undefined @@ -265,15 +265,13 @@ export async function finishBuild(plan: BuildPlan, { outputs, builder }: FinishB pkg, builder: { [builderPkg.name]: builderPkg.version, ...builder }, version, - }).catch((error) => { - consola.error(error) - consola.error('Cannot load module. Please check dist:', resolve(outDir, 'module.mjs')) + }).catch(async (error) => { + if (!keepOutput) { + await rm(outDir, { recursive: true, force: true }) + } + throw new Error(`Cannot load \`${relative(cwd, resolve(outDir, 'module.mjs'))}\` to write \`module.json\`: ${error instanceof Error ? error.message : String(error)}`, { cause: error }) }) - const typesFile = join(outDir, 'types.d.mts') - plan.writesTypes ??= !existsSync(typesFile) - if (plan.writesTypes) { - await writeTypes(outDir) - } + await writeTypes(outDir) await callBuildHook(plan.config, 'rollup:done', plan.ctx) await rewriteRuntimeDeclarations(outDir, outputs) @@ -307,7 +305,8 @@ function importedFrom(dir: string, keys: string[]): (key: string) => boolean { function valueImports(roots: string[]) { const transform = loadOxc()?.transformSync - const queue = roots.filter(file => SCRIPT_RE.test(file)) + const isScript = (file: string) => SCRIPT_RE.test(file) && !DECLARATION_RE.test(file) + const queue = roots.filter(isScript) const found = new Set() while (queue.length) { const file = queue.pop()! @@ -321,7 +320,7 @@ function valueImports(roots: string[]) { : source for (const specifier of valueSpecifiers(code)) { const target = probeSource(resolve(dirname(file), specifier)) - if (target && SCRIPT_RE.test(target)) { + if (target && isScript(target)) { queue.push(normalize(target)) } } @@ -334,20 +333,27 @@ function isDirectoryError(error: unknown) { return Array.isArray(errors) && errors.some(nested => nested.plugin === 'transpile-dir') } -function relativeSpecifier(from: string, to: string) { - const path = relative(dirname(from), to) - return path.startsWith('.') ? path : `./${path}` -} +const LOCKFILES = ['pnpm-lock.yaml', 'package-lock.json', 'yarn.lock', 'bun.lock', 'bun.lockb'] /** - * A hash of the types Nuxt generates in `.nuxt/`, which augment what single-file - * component declarations refer to without being visible to the declaration cache. + * A hash of the types Nuxt generates in `.nuxt/` and of the nearest lockfile, which change + * what single-file component declarations refer to without being visible to the declaration cache. */ -async function hashGeneratedTypes(cwd: string) { +export async function hashGeneratedTypes(cwd: string): Promise { const files = await glob(['tsconfig.json', '**/*.d.ts'], { cwd: join(cwd, '.nuxt'), absolute: true, onlyFiles: true }) + const lockfile = nearestLockfile(cwd) const hash = createHash('sha256') - for (const file of files.sort()) { + for (const file of [...files.sort(), ...lockfile ? [lockfile] : []]) { hash.update(relative(cwd, file)).update(await readFile(file)) } return hash.digest('hex').slice(0, 12) } + +function nearestLockfile(cwd: string) { + for (let dir = cwd; ; dir = dirname(dir)) { + const file = LOCKFILES.map(name => join(dir, name)).find(file => existsSync(file)) + if (file || dirname(dir) === dir) { + return file + } + } +} diff --git a/src/build/define.ts b/src/build/define.ts index 1fe5171e..97dc4788 100644 --- a/src/build/define.ts +++ b/src/build/define.ts @@ -43,8 +43,8 @@ export interface BuildConfig { /** * Type helper for a legacy `build.config.ts`, which `nuxt-module-build` still reads. - * Supported options are `entries`, `externals`, `replace`, `rollup.replace` and the - * `build:before`, `rollup:done` and `build:done` hooks. + * Supported options are `entries`, `externals`, `replace`, `rollup.replace`, `sourcemap` and + * the `build:before`, `rollup:done` and `build:done` hooks. * * @deprecated `build.config.ts` will stop being read in a future major. Move `entries`, `externals` * and `replace` into `builder()` from `@nuxt/module-builder/tsdown`, in `tsdown.config.ts`, and diff --git a/src/build/deprecations.ts b/src/build/deprecations.ts index 51e1fea6..0673e745 100644 --- a/src/build/deprecations.ts +++ b/src/build/deprecations.ts @@ -27,7 +27,7 @@ export async function checkDeprecatedPackageFields(cwd: string): Promise { type PackageJSON = Awaited> const DECLARATION_RE = /(?:^|\/)(?:module|types)\.d\.ts$/ -const CJS_MODULE_RE = /module\.cjs$/ +const CJS_MODULE_RE = /(?:^|\/)module\.cjs$/ export function checkLegacyDeclarationPaths(cwd: string, pkg: PackageJSON): boolean { if (!missingPaths(cwd, pkg).some(path => DECLARATION_RE.test(path))) { diff --git a/src/build/guide.ts b/src/build/guide.ts index 2fdfabf4..a6370abb 100644 --- a/src/build/guide.ts +++ b/src/build/guide.ts @@ -2,7 +2,6 @@ const GUIDE_URL = 'https://github.com/nuxt/module-builder/blob/main/docs/upgrade /** The sections of the upgrade guide that build messages link to, by heading anchor. */ export const GUIDE_SECTIONS = [ - 'node-engines', 'install-tsdown', 'build-configuration', 'tsdown-config', diff --git a/src/build/loader.ts b/src/build/loader.ts index 336a220d..721cb7f6 100644 --- a/src/build/loader.ts +++ b/src/build/loader.ts @@ -1,12 +1,13 @@ import { existsSync, readFileSync, statSync } from 'node:fs' import { createRequire, registerHooks } from 'node:module' import { fileURLToPath, pathToFileURL } from 'node:url' -import { dirname, isAbsolute, relative, resolve } from 'pathe' +import { dirname, relative, resolve } from 'pathe' import { resolvePathSync } from 'mlly' import { createPathsMatcher, getTsconfig } from 'get-tsconfig' import type ts from 'typescript' import type { Transform } from '../rolldown/transpile-dir.ts' +import { isInside, relativeSpecifier } from '../utils.ts' import { guide } from './guide.ts' const VIRTUAL_ALIAS_RE = /^#(?:app|imports|build)(?:\/|$)/ @@ -147,7 +148,7 @@ export function findModuleCodeIssues(cwd: string, entries: string[], runtimeDirs issue(location, `\`${specifier}\` is ${resolution.file.endsWith('.vue') ? 'a single-file component' : 'JSX'}, which Node cannot load (move the value the module needs into a \`.ts\` file, or use \`import type\`)`) continue } - const suggestion = relativeSpecifier(dirname(file), resolution.file) + const suggestion = relativeSpecifier(file, resolution.file) if (resolution.via === 'relative' && resolution.file !== resolve(dirname(file), specifier)) { issue(location, `\`${specifier}\` (use \`${suggestion}\`)`) } @@ -162,7 +163,7 @@ export function findModuleCodeIssues(cwd: string, entries: string[], runtimeDirs } for (const { specifier, typeOnly, json: _, resolution, ...location } of analysis.imports) { if (!typeOnly && resolution?.via === 'relative' && resolution.file !== resolve(dirname(file), specifier)) { - found.push({ file: relative(cwd, file), ...location, message: `\`${specifier}\` (use \`${relativeSpecifier(dirname(file), resolution.file)}\`)` }) + found.push({ file: relative(cwd, file), ...location, message: `\`${specifier}\` (use \`${relativeSpecifier(file, resolution.file)}\`)` }) } } }) @@ -240,16 +241,6 @@ function resolvesAsPackage(specifier: string, parentDir: string) { } } -function relativeSpecifier(from: string, to: string) { - const path = relative(from, to) - return path.startsWith('.') ? path : `./${path}` -} - -function isInside(dir: string, path: string) { - const subpath = relative(dir, path) - return !subpath.startsWith('..') && !isAbsolute(subpath) -} - /** * 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 diff --git a/src/build/module-declarations.ts b/src/build/module-declarations.ts index 74af841a..25de18dd 100644 --- a/src/build/module-declarations.ts +++ b/src/build/module-declarations.ts @@ -3,9 +3,10 @@ import { consola } from 'consola' import type { TsConfigResult } from 'get-tsconfig' import { dirname, join, normalize, relative, resolve } from 'pathe' -import { createDeclarationProgram, relativeSpecifier } from '../rolldown/declarations.ts' +import { createDeclarationProgram } from '../rolldown/declarations.ts' import { DECLARATION_RE, probe, RELATIVE_RE, rewriteSpecifiers, SCRIPT_RE } from '../rolldown/resolve.ts' import { isModuleFile } from '../rolldown/tsconfig.ts' +import { relativeSpecifier } from '../utils.ts' import { loadOxc } from './loader.ts' import { hasIsolatedDeclarations } from './tsconfig.ts' import { writeSourceTypes } from './types.ts' diff --git a/src/build/tsconfig.ts b/src/build/tsconfig.ts index 0dcf4597..8e07a298 100644 --- a/src/build/tsconfig.ts +++ b/src/build/tsconfig.ts @@ -1,14 +1,15 @@ import type { TsConfigResult } from 'get-tsconfig' -import { relative, resolve } from 'pathe' +import { join, relative, resolve } from 'pathe' import type { PackageJson } from 'pkg-types' import { publishedPackage } from './package.ts' /** * `paths` pointing the package's own name and `exports` subpaths at its sources, so - * self-referencing imports type-check before `dist` exists. + * self-referencing imports type-check before `dist` exists. A subpath that points at a + * bundled entry of `entries`, keyed by output name, maps to that entry's input. */ -export function selfReferencePaths(cwd: string, pkg: PackageJson, outDir: string): Record { +export function selfReferencePaths(cwd: string, pkg: PackageJson, outDir: string, entries: Record = {}): Record { if (!pkg.name) { return {} } @@ -24,7 +25,9 @@ export function selfReferencePaths(cwd: string, pkg: PackageJson, outDir: string } const distPath = relative(outDir, resolve(cwd, file)) if (!distPath.startsWith('..')) { - paths[`${pkg.name}/${subpath.slice(2)}`] = [resolve(cwd, 'src', distPath.replace(/(?:\.d)?\.[cm]?[jt]s$/, ''))] + const name = distPath.replace(/(?:\.d)?\.[cm]?[jt]s$/, '') + const input = Object.hasOwn(entries, name) ? entries[name]!.replace(/\.[cm]?[jt]sx?$/, '') : join('src', name) + paths[`${pkg.name}/${subpath.slice(2)}`] = [resolve(cwd, input)] } } return paths diff --git a/src/commands/_shared.ts b/src/commands/_shared.ts index 49e65573..8349f078 100644 --- a/src/commands/_shared.ts +++ b/src/commands/_shared.ts @@ -1,6 +1,5 @@ -import { resolve } from 'pathe' - import { guide } from '../build/guide.ts' +import { realpath } from '../utils.ts' import { findTsdownConfig, loadBuilderConfig } from './config-file.ts' import type { BuilderConfig } from './config-file.ts' @@ -20,7 +19,7 @@ export const sharedArgs = { }, } as const -export const resolveCwdArg = (args: { cwd?: string, rootDir?: string }): string => resolve(args.cwd || args.rootDir || '.') +export const resolveCwdArg = (args: { cwd?: string, rootDir?: string }): string => realpath(args.cwd || args.rootDir || '.') export function assertNoStubArg(command: 'build' | 'prepare', args: Record): void { if (args.stub) { diff --git a/src/commands/prepare.ts b/src/commands/prepare.ts index 4ec2038d..c14f2bbe 100644 --- a/src/commands/prepare.ts +++ b/src/commands/prepare.ts @@ -73,7 +73,7 @@ export async function prepareModule(cwd: string, buildConfig?: { config: Transla const entryPath = resolve(cwd, entries.module) const rootConfig = await rootTsconfig(cwd) const ambient = await ambientDeclarations(cwd, runtimeDirs, [...rootConfig.exclude ?? [], outDir]) - const selfPaths = selfReferencePaths(cwd, pkg, outDir) + const selfPaths = selfReferencePaths(cwd, pkg, outDir, entries) const declarationsDir = join(sourceTypesDir(cwd), 'declarations') const ownTypes = join(declarationsDir, 'types.d.mts') const ownPaths = name ? moduleDeclarationPaths(cwd, declarationsDir, name, selfPaths, runtimeDirs) : {} diff --git a/src/rolldown/declarations.ts b/src/rolldown/declarations.ts index 719c85f6..063369f8 100644 --- a/src/rolldown/declarations.ts +++ b/src/rolldown/declarations.ts @@ -1,5 +1,5 @@ import type { TsConfigResult } from 'get-tsconfig' -import { dirname, relative } from 'pathe' +import { relative } from 'pathe' import type ts from 'typescript' import { declarationPaths, projectFiles, tsconfigPaths, writeAmbientModules, writeServerRoutesStub } from './tsconfig.ts' @@ -166,9 +166,3 @@ export function declarationError(diagnostics: string[]): DeclarationError { : [], ].join('\n'), diagnostics) } - -/** The relative specifier from the directory of `from` to `to`. */ -export function relativeSpecifier(from: string, to: string): string { - const path = relative(dirname(from), to) - return path.startsWith('.') ? path : `./${path}` -} diff --git a/src/rolldown/resolve.ts b/src/rolldown/resolve.ts index 01b4a018..c7b9ed65 100644 --- a/src/rolldown/resolve.ts +++ b/src/rolldown/resolve.ts @@ -46,13 +46,21 @@ export interface Specifier { end: number } +const DYNAMIC_IMPORT_RE = /^\s*(?:\/\*[\s\S]*?\*\/\s*)*(?:(['"])([^'"\n]+)\1|`([^`$]+)`)\s*(?:,[\s\S]*)?$/ + +/** The specifier of an `import()` whose first argument is a string literal. */ +function dynamicImportSpecifier(expression: string) { + const match = expression.match(DYNAMIC_IMPORT_RE) + return match ? match[2] ?? match[3] : undefined +} + const TYPE_STAR_EXPORT_RE = /\bexport\s+type\s*\*(?:\s*as\s+[\w$]+)?\s*from\s*(['"])([^'"\n]+)\1/g /** Every string-literal module specifier in `code`: static imports, re-exports (type-only ones included) and `import()` calls. */ export function moduleSpecifiers(code: string): Specifier[] { const found = new Map() const locate = (statement: { code: string, start: number }, specifier: string) => { - const index = Math.max(statement.code.indexOf(`'${specifier}'`), statement.code.indexOf(`"${specifier}"`)) + const index = Math.max(...['\'', '"', '`'].map(quote => statement.code.indexOf(`${quote}${specifier}${quote}`))) if (index !== -1) { const start = statement.start + index found.set(start, { specifier, start, end: start + specifier.length + 2 }) @@ -70,9 +78,9 @@ export function moduleSpecifiers(code: string): Specifier[] { locate({ code: match[0], start: match.index }, match[2]!) } for (const statement of findDynamicImports(code)) { - const literal = statement.expression.match(/^\s*(['"])([^'"]+)\1\s*$/) - if (literal) { - locate(statement, literal[2]!) + const specifier = dynamicImportSpecifier(statement.expression) + if (specifier) { + locate(statement, specifier) } } return [...found.values()].sort((a, b) => a.start - b.start) @@ -104,9 +112,9 @@ export function valueSpecifiers(code: string): Set { } } for (const statement of findDynamicImports(code)) { - const literal = statement.expression.match(/^\s*(['"])(\.\.?\/[^'"]*)\1\s*$/) - if (literal) { - values.add(literal[2]!) + const specifier = dynamicImportSpecifier(statement.expression) + if (specifier && RELATIVE_RE.test(specifier)) { + values.add(specifier) } } return values diff --git a/src/rolldown/transpile-dir.ts b/src/rolldown/transpile-dir.ts index f1e1426d..0a8d78f2 100644 --- a/src/rolldown/transpile-dir.ts +++ b/src/rolldown/transpile-dir.ts @@ -6,7 +6,8 @@ import type { Rolldown } from 'tsdown' import type { Transform as VueTransform } from 'vue-sfc-transformer/core' -import { createDeclarationProgram, DeclarationError, declarationError, relativeSpecifier } from './declarations.ts' +import { relativeSpecifier } from '../utils.ts' +import { createDeclarationProgram, DeclarationError, declarationError } from './declarations.ts' import type { DeclarationProgram } from './declarations.ts' import { DECLARATION_RE, moduleSpecifiers, probe, RELATIVE_RE, rewriteSpecifiers, SCRIPT_RE, scriptExtension, valueSpecifiers } from './resolve.ts' import { compileSass, SASS_RE, transformCss } from './stylesheets.ts' diff --git a/src/tsdown/externals.ts b/src/tsdown/externals.ts index 0b72b920..91f24aa4 100644 --- a/src/tsdown/externals.ts +++ b/src/tsdown/externals.ts @@ -1,12 +1,15 @@ import { isAbsolute } from 'pathe' import type { Rolldown } from 'tsdown' +import { rewriteAppAliases } from '../build/aliases.ts' + const DECLARATION_RE = /\.d\.[cm]?ts$/ const NODE_MODULES_RE = /[\\/]node_modules[\\/]/ /** * Keeps declaration imports of installed packages external, whether or not the package - * is a dependency. Aliases that resolve into the module's own source are bundled. + * is a dependency. Aliases that resolve into the module's own source are bundled, and + * `#app` aliases are written as `nuxt/app`. */ export function externalDependencyDeclarations(): Rolldown.Plugin { return { @@ -26,5 +29,11 @@ export function externalDependencyDeclarations(): Rolldown.Plugin { } }, }, + renderChunk(code, chunk) { + if (DECLARATION_RE.test(chunk.fileName)) { + const rewritten = rewriteAppAliases(code) + return rewritten === code ? undefined : { code: rewritten, map: null } + } + }, } } diff --git a/src/tsdown/setup.ts b/src/tsdown/setup.ts index 06155524..0958be22 100644 --- a/src/tsdown/setup.ts +++ b/src/tsdown/setup.ts @@ -18,6 +18,7 @@ import { externalDependencyDeclarations } from './externals.ts' import { replacePlugin } from './replace.ts' import { defaultReport, reportsSummary, sizeBreakdown } from './report.ts' import { runtimeExternals } from './runtime-externals.ts' +import { realpath } from '../utils.ts' import { unchangedOutputs } from './unchanged.ts' export interface SetupOptions { @@ -76,7 +77,7 @@ export async function setupBuilder(config: UserConfig, inline: InlineConfig, opt ].join('\n')) } - const cwd = resolve(config.cwd ?? process.cwd()) + const cwd = realpath(config.cwd ?? process.cwd()) const pkg = await readPackageJSON(cwd) const packageError = sourcePathsPackError(cwd, pkg) ?? unpublishablePathsError(cwd, pkg) if (packageError) { @@ -253,12 +254,10 @@ export async function setupBuilder(config: UserConfig, inline: InlineConfig, opt } } const outputs = await Promise.all(directoryPlugins.map(plugin => plugin.api.outputs)) - if (keptOutput) { - plan.writesTypes ??= !Object.hasOwn(bundle, 'types.d.mts') - } await finishBuild(plan, { outputs: outputs.flatMap(map => [...map.values()]), builder: { tsdown: await readPackageJSON('tsdown', { from: import.meta.url }).then(r => r.version || 'unknown').catch(() => 'unknown') }, + keepOutput: watch, }) }, } diff --git a/src/utils.ts b/src/utils.ts new file mode 100644 index 00000000..6e7bc509 --- /dev/null +++ b/src/utils.ts @@ -0,0 +1,22 @@ +import { existsSync, realpathSync } from 'node:fs' +import { dirname, isAbsolute, relative, resolve } from 'pathe' + +/** `path` resolved, with symlinks followed when it exists, as module ids are. */ +export function realpath(path: string): string { + const resolved = resolve(path) + return existsSync(resolved) ? resolve(realpathSync(resolved)) : resolved +} + +/** Whether `path` is `dir` or inside it. */ +export function isInside(dir: string, path: string): boolean { + const subpath = relative(dir, path) + return subpath !== '..' && !subpath.startsWith('../') && !isAbsolute(subpath) +} + +export const RELATIVE_RE: RegExp = /^\.\.?(?:\/|$)/ + +/** The relative specifier from the directory of `from` to `to`. */ +export function relativeSpecifier(from: string, to: string): string { + const path = relative(dirname(from), to) + return RELATIVE_RE.test(path) ? path : `./${path}` +} diff --git a/test/cli.spec.ts b/test/cli.spec.ts index 57cf0f89..80921139 100644 --- a/test/cli.spec.ts +++ b/test/cli.spec.ts @@ -888,8 +888,8 @@ describe('a module without a runtime directory', () => { `) }) - it('should refuse an `outDir` that contains the module root', () => { - expect(expectFailed('minimal:outDir')).toContain(`\`--outDir ..\` resolves to \`${resolve(dirs.minimal!, '..')}\`, which contains the module root; the build empties the output directory first. Use a directory inside the module such as \`dist\`. ${guide('output-directory')}`) + it('should refuse an `outDir` outside the module root', () => { + expect(expectFailed('minimal:outDir')).toContain(`\`--outDir ..\` resolves to \`${resolve(dirs.minimal!, '..')}\`, which is not inside the module root; the build empties the output directory first. Use a directory inside the module such as \`dist\`. ${guide('output-directory')}`) expect(exists(dirs.minimal!, 'package.json')).toBe(true) }) diff --git a/test/regressions.spec.ts b/test/regressions.spec.ts new file mode 100644 index 00000000..16d79362 --- /dev/null +++ b/test/regressions.spec.ts @@ -0,0 +1,153 @@ +import { existsSync } from 'node:fs' +import { appendFile, mkdir, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { consola } from 'consola' +import { join } from 'pathe' +import { exec } from 'tinyexec' +import { afterAll, describe, expect, it, vi } from 'vitest' + +import { analyseSources, hashGeneratedTypes } from '../src/build/build.ts' +import type { BuildPlan } from '../src/build/build.ts' +import { resolveModuleOptions, resolveOutDir, translateBuildConfig } from '../src/build/build-config.ts' +import { checkLegacyCJSPaths } from '../src/build/deprecations.ts' +import { selfReferencePaths } from '../src/build/tsconfig.ts' +import { resolveCwdArg } from '../src/commands/_shared.ts' +import { moduleSpecifiers, valueSpecifiers } from '../src/rolldown/resolve.ts' +import { relativeSpecifier } from '../src/utils.ts' +import { copyExample, repoRoot } from './utils.ts' + +const temp: string[] = [] +const tempDir = async () => { + const dir = await mkdtemp(join(tmpdir(), 'module-builder-regressions-')) + temp.push(dir) + return dir +} + +afterAll(async () => { + await Promise.all(temp.map(dir => rm(dir, { recursive: true, force: true }))) +}) + +describe('regressions', () => { + it('should resolve a module root reached through a symlink to its real path', async () => { + const dir = await tempDir() + await mkdir(join(dir, 'real')) + await symlink(join(dir, 'real'), join(dir, 'link')) + expect(resolveCwdArg({ rootDir: join(dir, 'link') })).toBe(resolveCwdArg({ rootDir: join(dir, 'real') })) + expect(resolveCwdArg({ cwd: join(dir, 'missing') })).toBe(join(dir, 'missing')) + }) + + it('should change the declaration cache key with the nearest lockfile', async () => { + const dir = await tempDir() + await mkdir(join(dir, 'module/.nuxt'), { recursive: true }) + await writeFile(join(dir, 'module/.nuxt/tsconfig.json'), '{}') + await writeFile(join(dir, 'pnpm-lock.yaml'), 'lockfileVersion: 9\n') + const before = await hashGeneratedTypes(join(dir, 'module')) + expect(await hashGeneratedTypes(join(dir, 'module'))).toBe(before) + await writeFile(join(dir, 'pnpm-lock.yaml'), 'lockfileVersion: 9\npackages: {}\n') + expect(await hashGeneratedTypes(join(dir, 'module'))).not.toBe(before) + }) + + it('should refuse a bundled entry named `types`', () => { + const cwd = join(repoRoot, 'example') + for (const entries of [[{ input: './src/utils', name: 'types' }], ['./src/types']]) { + expect(() => resolveModuleOptions(cwd, {}, join(cwd, 'dist'), { entries })).toThrow('named `types`, whose declarations would replace the generated `types.d.mts`') + } + }) + + it('should find literal dynamic imports with comments, template literals and options', () => { + const code = [ + `import(/* @vite-ignore */ './a')`, + 'import(`./b`)', + `import('./c', { with: { type: 'json' } })`, + 'import(`./${name}`)', + ].join('\n') + expect(moduleSpecifiers(code).map(({ specifier }) => specifier)).toEqual(['./a', './b', './c']) + expect([...valueSpecifiers(code)]).toEqual(['./a', './b', './c']) + }) + + it('should refuse an output directory outside the module', () => { + for (const outDir of ['../sibling', '/elsewhere/dist', '.']) { + expect(() => resolveOutDir('/repo/mod', outDir)).toThrow('which is not inside the module root') + } + expect(resolveOutDir('/repo/mod', '..dist')).toBe('/repo/mod/..dist') + }) + + it('should map a self-referencing subpath to the input of the entry with that name', () => { + const pkg = { name: 'my-module', exports: { './vite': './dist/vite.mjs', './utils': './dist/utils.mjs' } } + expect(selfReferencePaths('/mod', pkg, '/mod/dist', { module: './src/module.ts', vite: './src/lib/vite.ts' })).toEqual({ + 'my-module': ['/mod/src/module'], + 'my-module/vite': ['/mod/src/lib/vite'], + 'my-module/utils': ['/mod/src/utils'], + }) + }) + + it('should treat a dot-prefixed name as a path inside the directory', () => { + expect(relativeSpecifier('/mod/src/module.ts', '/mod/src/.generated/types.ts')).toBe('./.generated/types.ts') + expect(relativeSpecifier('/mod/src/module.ts', '/mod/shared.ts')).toBe('../shared.ts') + }) + + it('should let the first config set every replace option', () => { + const cwd = join(repoRoot, 'example') + const translate = (...configs: unknown[]) => translateBuildConfig(configs.map((config, index) => ({ name: `config${index}`, config })), { cwd, outDir: join(cwd, 'dist') }).replace + expect(translate( + { rollup: { replace: { values: { A: 'a' }, preventAssignment: false, objectGuards: true } } }, + { rollup: { replace: { preventAssignment: true, objectGuards: false } } }, + )).toEqual({ values: { A: 'a' }, preventAssignment: false, objectGuards: true }) + expect(translate({ replace: { A: 'a' } })).toEqual({ values: { A: 'a' }, preventAssignment: true }) + }) + + it('should only advise about `module.cjs` itself', () => { + const warn = vi.spyOn(consola, 'warn').mockImplementation(() => {}) + expect(checkLegacyCJSPaths(repoRoot, { main: './dist/submodule.cjs' })).toBe(false) + expect(checkLegacyCJSPaths(repoRoot, { main: './dist/module.cjs' })).toBe(true) + warn.mockRestore() + }) + + 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 }) + await writeFile(join(cwd, 'src/module.ts'), 'export default {}\n') + await writeFile(join(cwd, 'src/runtime/server/types.d.ts'), `export { default } from '../Button'\n`) + await writeFile(join(cwd, 'src/runtime/server/handler.ts'), `export default 'handler'\n`) + await writeFile(join(cwd, 'src/runtime/Button.tsx'), `export default () => \n}\n`, + 'project/src/jsx/components/Toolbar.tsx': `import Button from './Button.js'\n\nexport default function Toolbar() {\n return \n}\n`, + 'project/src/maps/lazy.ts': `export const lazy = true\n`, 'project/node_modules/side-effect-package/package.json': JSON.stringify({ name: 'side-effect-package', type: 'module', exports: './index.js' }), 'project/node_modules/side-effect-package/index.js': `globalThis.sideEffect = true\n`, 'project/node_modules/side-effect-package/index.d.ts': `export {}\n`, @@ -82,6 +87,8 @@ const files: Record = { const externals: Array<[string, ExternalImport['kind'], string]> = [] +const plugin = (options: Partial) => transpileDir({ cwd, srcDir: join(cwd, 'src/lib'), outBase: '', extension: 'js', paths: {}, jsx: () => 'preserve', transform: loadOxc()!.transform, sourcemap: false, cacheVersion: '', resolveExternal: () => undefined, ...options }) + describe('transpileDir', () => { beforeAll(async () => { await rm(root, { recursive: true, force: true }) @@ -89,15 +96,14 @@ describe('transpileDir', () => { await mkdir(join(root, file, '..'), { recursive: true }) await writeFile(join(root, file), contents) } - const options = { cwd, config: false, entry: emptyEntry, format: 'esm', dts: false, report: false } satisfies Parameters[0] + const options = { cwd, config: false, entry: ['src/index.ts'], format: 'esm', dts: false, report: false } satisfies Parameters[0] const automatic = { runtime: 'automatic', importSource: 'vue' } as const + const jsxDir = join(cwd, 'src/jsx') await Promise.all([ build({ ...options, - entry: ['src/index.ts'], outDir: dist, - plugins: [transpileDir({ - srcDir: 'src/lib', + plugins: [plugin({ outBase: 'lib', resolveExternal(specifier, _importer, { kind, file }) { externals.push([specifier, kind, file.slice(root.length)]) @@ -105,29 +111,19 @@ describe('transpileDir', () => { }, })], }), - build({ - ...options, - outDir: join(cwd, 'dist-raw'), - plugins: [transpileDir({ - srcDir: 'src/lib', - exclude: ['**/*.spec.ts', '**/Other.vue'], - declaration: false, - stylesheets: false, - })], - }), build({ ...options, outDir: join(cwd, 'dist-jsx'), plugins: [ - transpileDir({ srcDir: 'src/lib', outBase: 'preserved', include: ['components/Button.tsx'], extension: 'mjs' }), - transpileDir({ srcDir: 'src/lib', outBase: 'compiled', include: ['components/Button.tsx'], declaration: false, jsx: automatic }), - transpileDir({ srcDir: 'src/lib', outBase: 'mixed', include: ['index.ts', 'components/*.tsx'], declaration: false, jsx: file => file.endsWith('Button.tsx') ? automatic : 'preserve' }), + plugin({ srcDir: jsxDir, outBase: 'preserved', extension: 'mjs' }), + plugin({ srcDir: jsxDir, outBase: 'compiled', jsx: () => automatic }), + plugin({ srcDir: jsxDir, outBase: 'mixed', jsx: file => file.endsWith('Button.tsx') ? automatic : 'preserve' }), ], }), build({ ...options, outDir: join(cwd, 'dist-maps'), - plugins: [transpileDir({ srcDir: 'src/lib', outBase: 'lib', include: ['lazy.ts'], declaration: false, sourcemap: true })], + plugins: [plugin({ srcDir: join(cwd, 'src/maps'), outBase: 'lib', sourcemap: true })], }), ]) }) @@ -264,29 +260,20 @@ describe('transpileDir', () => { expect(existsSync(join(dist, 'lib/lib.spec.js'))).toBe(false) }) - it('should leave out declarations, stylesheet processing and excluded components when asked', async () => { - const raw = join(cwd, 'dist-raw') - const emitted = (await listFiles(raw)).filter(file => file.includes('.')).sort() - expect(emitted.filter(file => /\.d\.|\.vue|\.mjs$|styles\//.test(file))).toEqual([ - 'components/Hello.vue', - 'styles/_tokens.scss', - 'styles/main.css', - 'styles/theme.scss', - ]) - expect(await readFile(join(raw, 'styles/theme.scss'), 'utf8')).toBe(files['project/src/lib/styles/theme.scss']) - expect(await readFile(join(raw, 'components/Hello.vue'), 'utf8')).toContain('defineProps') - }) - - it('should compile JSX with the `jsx` option, per file when it is a function', async () => { + it('should compile JSX with the `jsx` option, per file', async () => { const outDir = join(cwd, 'dist-jsx') - expect((await listFiles(outDir)).filter(file => file.includes('.')).sort()).toEqual([ + expect((await listFiles(outDir)).filter(file => file.includes('/') && file.includes('.') && !/\.d\.m?ts$/.test(file)).sort()).toEqual([ 'compiled/components/Button.js', + 'compiled/components/Toolbar.js', + 'compiled/index.js', 'mixed/components/Button.js', 'mixed/components/Toolbar.jsx', 'mixed/index.js', - 'preserved/components/Button.d.ts', 'preserved/components/Button.jsx', + 'preserved/components/Toolbar.jsx', + 'preserved/index.mjs', ]) + expect(existsSync(join(outDir, 'preserved/components/Button.d.ts'))).toBe(true) expect(await readFile(join(outDir, 'compiled/components/Button.js'), 'utf8')).toContain(`import { jsx as _jsx } from "vue/jsx-runtime";`) expect(await readFile(join(outDir, 'mixed/components/Button.js'), 'utf8')).toContain(`import { jsx as _jsx } from "vue/jsx-runtime";`) expect(await readFile(join(outDir, 'mixed/components/Toolbar.jsx'), 'utf8')).toBe(`import Button from "./Button.js";\nexport default function Toolbar() {\n\treturn ;\n}\n`) @@ -299,8 +286,8 @@ describe('transpileDir', () => { expect(code.trimEnd().split('\n').at(-1)).toBe('//# sourceMappingURL=lazy.js.map') const map = JSON.parse(await readFile(join(outDir, 'lib/lazy.js.map'), 'utf8')) expect(map.file).toBe('lazy.js') - expect(map.sources).toEqual(['../../src/lib/lazy.ts']) + expect(map.sources).toEqual(['../../src/maps/lazy.ts']) expect(map.mappings).not.toBe('') - expect(await readFile(join(outDir, 'lib', map.sources[0]), 'utf8')).toBe(files['project/src/lib/lazy.ts']) + expect(await readFile(join(outDir, 'lib', map.sources[0]), 'utf8')).toBe(files['project/src/maps/lazy.ts']) }) }) diff --git a/test/unit.spec.ts b/test/unit.spec.ts index cb34247e..159a0c11 100644 --- a/test/unit.spec.ts +++ b/test/unit.spec.ts @@ -17,8 +17,8 @@ import type { Rolldown, UserConfig } from 'tsdown' import { exec } from 'tinyexec' import { runtimeExternals } from '../src/tsdown/runtime-externals.ts' import { selfReferencePaths } from '../src/build/tsconfig.ts' -import { SERVER_ROUTES_STUB, createTsconfigResolver, declarationPaths, rootTsconfig, tsconfigPaths, writeDerivedTsconfig, writeServerRoutesStub } from '../src/rolldown/tsconfig.ts' -import { transformCss } from '../src/rolldown/stylesheets.ts' +import { SERVER_ROUTES_STUB, createTsconfigResolver, declarationPaths, rootTsconfig, tsconfigPaths, writeDerivedTsconfig, writeServerRoutesStub } from '../src/transpile/tsconfig.ts' +import { transformCss } from '../src/transpile/stylesheets.ts' import { declarationTargets, rewriteRuntimeDeclarations } from '../src/build/aliases.ts' import { checkMissingPaths, checkNode10DeclarationPaths, checkStaleTypesField } from '../src/build/deprecations.ts' import { checkLegacyCJSPaths, checkLegacyDeclarationPaths } from '../src/legacy/package-paths.ts' diff --git a/tsdown.config.ts b/tsdown.config.ts index 36f10c70..c631bf58 100644 --- a/tsdown.config.ts +++ b/tsdown.config.ts @@ -1,7 +1,7 @@ import { defineConfig } from 'tsdown' export default defineConfig({ - entry: { cli: './src/cli.ts', index: './src/index.ts', rolldown: './src/rolldown/index.ts', tsdown: './src/tsdown/index.ts' }, + entry: { cli: './src/cli.ts', index: './src/index.ts', tsdown: './src/tsdown/index.ts' }, format: 'esm', dts: true, publint: { level: 'error' }, From 2c2e379623bb6330756940fc26a165a1c5b29f77 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Tue, 17 Nov 2026 07:37:40 +0000 Subject: [PATCH 05/21] feat!: remove the implicit default `build` command --- docs/2.commands.md | 2 +- docs/cli/build-module/index.md | 2 +- docs/upgrade-v2.md | 4 ++++ src/cli.ts | 9 --------- 4 files changed, 6 insertions(+), 11 deletions(-) diff --git a/docs/2.commands.md b/docs/2.commands.md index 6649a6b1..87471992 100644 --- a/docs/2.commands.md +++ b/docs/2.commands.md @@ -13,7 +13,7 @@ You build a module with `tsdown`, which reads the [`builder()` plugin](/docs/gui - `build` builds the module, with or without a `tsdown.config.ts`. - `prepare` generates the `.nuxt` directory that types the module. -Name the subcommand every time. `nuxt-module-build` without a subcommand runs `build` and prints a warning. +Name the subcommand every time: `nuxt-module-build` without one prints its usage. The Nuxt CLI runs the same subcommands as [`nuxt build-module`](/docs/api/commands/build-module), so `nuxt build-module build` is the same as `nuxt-module-build build`. To see how a module's scripts combine these commands, read [Develop and Publish](/docs/guide/modules/module-builder/develop-and-publish). diff --git a/docs/cli/build-module/index.md b/docs/cli/build-module/index.md index 886f07a0..5481dcac 100644 --- a/docs/cli/build-module/index.md +++ b/docs/cli/build-module/index.md @@ -13,7 +13,7 @@ npx nuxt build-module build [ROOTDIR] [--cwd=] [--outDir=] npx nuxt build-module prepare [ROOTDIR] [--cwd=] ``` -The `build-module` command runs the `nuxt-build-module` binary that [`@nuxt/module-builder`](/docs/guide/modules/module-builder) installs in your module. It's the same CLI as `nuxt-module-build`, with two subcommands. Without a subcommand, it runs `build` and prints a warning. +The `build-module` command runs the `nuxt-build-module` binary that [`@nuxt/module-builder`](/docs/guide/modules/module-builder) installs in your module. It's the same CLI as `nuxt-module-build`, with two subcommands. Without a subcommand, it prints its usage. ## `build` diff --git a/docs/upgrade-v2.md b/docs/upgrade-v2.md index 12c4c75b..80331ee9 100644 --- a/docs/upgrade-v2.md +++ b/docs/upgrade-v2.md @@ -369,6 +369,10 @@ TypeScript resolves `typesVersions` entries with `node10` rules. A path without Any other path in `exports`, `main`, `module`, `types`, or `typesVersions` that doesn't exist after the build is listed in a warning. Either add the entry that produces it (see [Build configuration](#build-configuration)), or remove the path. +## Commands + +`nuxt-module-build` and `nuxt build-module` need a subcommand. Without one they print their usage, so a script such as `"prepack": "nuxt-module-build"` becomes `"prepack": "tsdown"`, or `nuxt-module-build build`. + ## Stub builds `nuxt-module-build build --stub` and `nuxt-module-build prepare --stub` have been removed, and fail with a link to this section. Replace the scripts that use them as described in [Developing a module](#developing-a-module): diff --git a/src/cli.ts b/src/cli.ts index 0a7656c8..1de49893 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -1,7 +1,6 @@ #!/usr/bin/env node import { defineCommand, runMain } from 'citty' import type { CommandDef } from 'citty' -import { consola } from 'consola' import pkg from '../package.json' with { type: 'json' } const { name, description, version } = pkg @@ -18,14 +17,6 @@ const main = defineCommand({ prepare: () => import('./commands/prepare.ts').then(_rDefault), build: () => import('./commands/build.ts').then(_rDefault), }, - setup(context) { - // TODO: support 'default command' in citty? - const firstArg = context.rawArgs[0] - if (context.cmd.subCommands && !(firstArg && firstArg in context.cmd.subCommands)) { - consola.warn('Please specify the `build` command explicitly. In a future version of `@nuxt/module-builder`, the implicit default build command will be removed.') - context.rawArgs.unshift('build') - } - }, }) runMain(main) From 3c68dfb96470dd527855d213969f276e0f79e680 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Tue, 17 Nov 2026 07:42:34 +0000 Subject: [PATCH 06/21] refactor: share helpers in `src/utils.ts` and merge single-purpose modules --- src/build/advice.ts | 10 -- src/build/aliases.ts | 4 +- src/build/build.ts | 55 ++++---- src/build/deprecations.ts | 101 -------------- src/build/loader.ts | 39 +----- src/build/meta.ts | 26 ---- src/build/module-declarations.ts | 9 +- src/build/options.ts | 3 +- src/build/package.ts | 145 ++++++++++++++++++-- src/build/tsconfig.ts | 48 ------- src/build/types.ts | 3 +- src/build/write.ts | 8 -- src/commands/_shared.ts | 8 -- src/commands/config-file.ts | 8 +- src/commands/prepare.ts | 13 +- src/legacy/package-paths.ts | 2 +- src/transpile/declarations.ts | 3 - src/transpile/{resolve.ts => specifiers.ts} | 33 +---- src/transpile/transpile-dir.ts | 27 +--- src/transpile/tsconfig.ts | 28 ++-- src/tsdown/externals.ts | 84 +++++++++++- src/tsdown/replace.ts | 16 --- src/tsdown/report.ts | 5 +- src/tsdown/runtime-externals.ts | 84 ------------ src/tsdown/setup.ts | 24 ++-- src/tsdown/unchanged.ts | 5 +- src/utils.ts | 76 ++++++++-- test/regressions.spec.ts | 4 +- test/unit.spec.ts | 11 +- 29 files changed, 383 insertions(+), 499 deletions(-) delete mode 100644 src/build/advice.ts delete mode 100644 src/build/deprecations.ts delete mode 100644 src/build/meta.ts delete mode 100644 src/build/tsconfig.ts delete mode 100644 src/build/write.ts rename src/transpile/{resolve.ts => specifiers.ts} (77%) delete mode 100644 src/tsdown/replace.ts delete mode 100644 src/tsdown/runtime-externals.ts diff --git a/src/build/advice.ts b/src/build/advice.ts deleted file mode 100644 index 043a2607..00000000 --- a/src/build/advice.ts +++ /dev/null @@ -1,10 +0,0 @@ -const shown = new Set() - -/** Advice is shown at most once per process, and never in CI. */ -export function shouldAdvise(key: string): boolean { - if (process.env.CI || shown.has(key)) { - return false - } - shown.add(key) - return true -} diff --git a/src/build/aliases.ts b/src/build/aliases.ts index 48f36a5d..4a0d6ca6 100644 --- a/src/build/aliases.ts +++ b/src/build/aliases.ts @@ -1,6 +1,8 @@ import { existsSync, promises as fsp } from 'node:fs' import { dirname, join, resolve } from 'pathe' +import { DECLARATION_RE } from '../utils.ts' + const APP_ALIAS_RE = /(\bfrom\s*|\bimport\s*\(\s*)(['"])#app(?:\/[^'"]*)?\2/g const RELATIVE_SPECIFIER_RE = /(\bfrom\s*|\bimport\s*\(\s*|\bimport\s+)(['"])(\.\.?\/[^'"]*)\2/g const DECLARATION_TARGETS = [ @@ -54,7 +56,7 @@ export function declarationTargets(fileName: string, code: string): string[] { } function declarationsOf(output: string) { - if (/\.d\.[cm]?ts$/.test(output)) { + if (DECLARATION_RE.test(output)) { return [output] } if (output.endsWith('.vue')) { diff --git a/src/build/build.ts b/src/build/build.ts index bb649466..2c841933 100644 --- a/src/build/build.ts +++ b/src/build/build.ts @@ -3,26 +3,23 @@ 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' } -import { DECLARATION_RE, probe as probeSource, scriptExtension, valueSpecifiers } from '../transpile/resolve.ts' +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, findPackageDir, namedCachePath, tsconfigPaths, writeDependencyImports, writeDerivedTsconfig, writeServerRoutesStub } from '../transpile/tsconfig.ts' -import { relativeSpecifier } from '../utils.ts' -import { shouldAdvise } from './advice.ts' +import { createTsconfigResolver, declarationPaths, hasIsolatedDeclarations, namedCachePath, tsconfigPaths, writeDependencyImports, writeDerivedTsconfig, writeServerRoutesStub } from '../transpile/tsconfig.ts' +import { DECLARATION_RE, findPackageDir, isInside, probe, relativeSpecifier, SCRIPT_RE, writeIfChanged } from '../utils.ts' import { rewriteRuntimeDeclarations } from './aliases.ts' -import { checkDeprecatedPackageFields } from './deprecations.ts' import { guide } from './guide.ts' -import { assertLoadableModuleCode, loadOxc, probe } from './loader.ts' -import { writeModuleMeta } from './meta.ts' +import { assertLoadableModuleCode, importModule, loadOxc } from './loader.ts' import { bundledEntries, NUXT_EXTERNALS } from './options.ts' import type { DirectoryEntry, ModuleConfig } from './options.ts' -import { importsKeyFor, publishedPackage, unpublishableImportsError } from './package.ts' -import { hasIsolatedDeclarations, selfReferencePaths } from './tsconfig.ts' +import { checkPublishedPaths, importsKeyFor, publishedPackage, selfReferencePaths, unpublishableImportsError } from './package.ts' import { writeTypes } from './types.ts' const ISOLATED_DECLARATIONS_HINT = [ @@ -41,11 +38,17 @@ const TYPE_ERROR_HINT = [ `If \`.nuxt\` is out of date, run \`nuxt-module-build prepare\` and build again. ${guide('declaration-errors')}`, ].join('\n') -const SCRIPT_RE = /\.[cm]?[jt]sx?$/ const SERVER_DIR_RE = /(?:^|\/)server\// +let nudged = false + +/** Whether to suggest `isolatedDeclarations`, which happens once per process and never in CI. */ export function shouldNudge(isolatedDeclarations: boolean): boolean { - return !isolatedDeclarations && shouldAdvise('isolated-declarations') + if (isolatedDeclarations || nudged || process.env.CI) { + return false + } + nudged = true + return true } export interface ResolveBuildOptions { @@ -102,7 +105,7 @@ export async function resolveBuild({ cwd, pkg, outDir, sourcemap, config }: Reso const tsconfigs = await createTsconfigResolver(cwd) if (tsconfigs.replaced) { const path = relative(cwd, tsconfigs.replaced) - const advice = path.startsWith('..') ? 'Add a `tsconfig.json` in the module directory that extends `./.nuxt/tsconfig.json`.' : 'Extend `./.nuxt/tsconfig.json` in the module\'s tsconfig.' + 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')}`) } @@ -199,7 +202,7 @@ export function resolveDirectoryExternal(plan: BuildPlan, directory: DirectoryEn if (bundled) { return relativeSpecifier(from, bundled) } - const other = directories.find(directory => !relative(directory.srcDir, file).startsWith('..')) + const other = directories.find(directory => isInside(directory.srcDir, file)) if (other) { return relativeSpecifier(from, join(relative(outDir, other.outDir), relative(other.srcDir, file).replace(SCRIPT_RE, scriptExtension(file, `.${other.ext}`, preservesJsx(plan, file))))) } @@ -247,19 +250,17 @@ let metaImports = 0 export async function finishBuild(plan: BuildPlan, { outputs, builder, keepOutput }: FinishBuildOptions): Promise { const { cwd, outDir, pkg } = plan const duration = Date.now() - (plan.prepared?.startedAt ?? Date.now()) - const version = metaImports++ || undefined - await writeModuleMeta({ - cwd, - outDir, - pkg, - builder: { [builderPkg.name]: builderPkg.version, ...builder }, - version, - }).catch(async (error) => { + const moduleFile = resolve(outDir, 'module.mjs') + const meta = await readModuleMeta(moduleFile, cwd).catch(async (error) => { if (!keepOutput) { await rm(outDir, { recursive: true, force: true }) } - throw new Error(`Cannot load \`${relative(cwd, resolve(outDir, 'module.mjs'))}\` to write \`module.json\`: ${error instanceof Error ? error.message : String(error)}`, { cause: error }) + throw new Error(`Cannot load \`${relative(cwd, moduleFile)}\` to write \`module.json\`: ${error instanceof Error ? error.message : String(error)}`, { cause: error }) }) + meta.name ||= pkg.name + meta.version ||= pkg.version + meta.builder = { [builderPkg.name]: builderPkg.version, ...builder } + await writeIfChanged(resolve(outDir, 'module.json'), JSON.stringify(meta, null, 2)) await writeTypes(outDir) await plan.config.callHook?.('rollup:done', plan) await rewriteRuntimeDeclarations(outDir, outputs) @@ -270,7 +271,7 @@ export async function finishBuild(plan: BuildPlan, { outputs, builder, keepOutpu consola.info(`Built in ${duration}ms. Set \`isolatedDeclarations: true\` in ${where} to use the faster oxc declaration generator. ${guide('isolated-declarations')}`) } - await checkDeprecatedPackageFields(cwd) + await checkPublishedPaths(cwd) const importsError = unpublishableImportsError(cwd, pkg, importedFrom(outDir, Object.keys(publishedPackage(pkg).imports ?? {}))) if (importsError) { throw new Error(importsError) @@ -278,6 +279,12 @@ export async function finishBuild(plan: BuildPlan, { outputs, builder, keepOutpu await plan.config.callHook?.('build:done', plan) } +async function readModuleMeta(file: string, cwd: string) { + const exports = await importModule(file, { cwd, version: metaImports++ || undefined }) + const nuxtModule = (exports.default ?? exports) as NuxtModule> + return await nuxtModule.getMeta?.() || {} +} + const OUTPUT_TEXT_RE = /\.(?:[cm]?[jt]sx?|vue|css)$/ const PACKAGE_IMPORT_RE = /(?:\bfrom|\bimport(?:\s+url)?|\brequire)\s*(?:\(\s*)?(["'`])(#[^"'`]+)\1/g @@ -308,7 +315,7 @@ function valueImports(roots: string[]) { ? (transform(file, source, { lang: file.match(/\.[cm]?([jt]sx?)$/)![1], jsx: 'preserve', typescript: { onlyRemoveTypeImports: false } })).code : source for (const specifier of valueSpecifiers(code)) { - const target = probeSource(resolve(dirname(file), specifier)) + const target = probe(resolve(dirname(file), specifier)) if (target && isScript(target)) { queue.push(normalize(target)) } diff --git a/src/build/deprecations.ts b/src/build/deprecations.ts deleted file mode 100644 index 55128979..00000000 --- a/src/build/deprecations.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { existsSync, statSync } from 'node:fs' -import { relative, resolve } from 'pathe' -import { consola } from 'consola' -import { readPackageJSON } from 'pkg-types' - -import { checkLegacyCJSPaths, checkLegacyDeclarationPaths, isLegacyPath } from '../legacy/package-paths.ts' -import { guide } from './guide.ts' -import { collectStrings, publishedPackage } from './package.ts' - -/** - * Warn about `package.json` fields that point at output this builder no longer produces. - * The paths are read as published, with `publishConfig` applied. - */ -export async function checkDeprecatedPackageFields(cwd: string): Promise { - const read = await readPackageJSON(cwd).catch(() => undefined) - const pkg = read && publishedPackage(read) - if (!pkg) { - return - } - - checkLegacyDeclarationPaths(cwd, pkg) - checkLegacyCJSPaths(cwd, pkg) - checkStaleTypesField(cwd, pkg) - checkNode10DeclarationPaths(cwd, pkg) - checkMissingPaths(cwd, pkg) -} - -type PackageJSON = Awaited> - -export function checkStaleTypesField(cwd: string, pkg: PackageJSON): boolean { - if (!pkg.types || resolvesForTypeScript(cwd, pkg.types)) { - return false - } - consola.warn(`\`types\` in \`package.json\` points at \`${pkg.types}\`, which the build does not produce. Set it to \`./dist/types.d.mts\`, which node10 module resolution reads, or remove it: bundler module resolution reads \`exports\` instead. ${guide('the-types-field')}`) - return true -} - -/** - * Warn about `typesVersions` paths that TypeScript's node10 resolution cannot find because - * they rely on probing for `.d.ts`, where the build now produces `.d.mts`. - */ -export function checkNode10DeclarationPaths(cwd: string, pkg: PackageJSON): boolean { - const entries = typesVersionsPaths(pkg).flatMap((path) => { - const replacement = node10Replacement(cwd, path) - return replacement ? [`\`${path}\` (use \`${replacement}\`)`] : [] - }) - if (!entries.length) { - return false - } - consola.warn(`These \`typesVersions\` paths in \`package.json\` do not resolve under TypeScript's node10 module resolution, which probes for \`.d.ts\` but not for \`.d.mts\`: ${entries.join(', ')}. Write each path with its extension. ${guide('typesversions-paths')}`) - return true -} - -/** Warn about paths in `package.json` that the build did not produce, other than those the checks above explain. */ -export function checkMissingPaths(cwd: string, pkg: PackageJSON): boolean { - const paths = [...new Set(missingPaths(cwd, pkg))] - .filter(path => !path.includes('*') && !isLegacyPath(path) && path !== pkg.types && !node10Replacement(cwd, path)) - if (!paths.length) { - return false - } - consola.warn(`These paths in \`package.json\` do not exist after the build, so imports that resolve to them will fail: ${list(paths)}. Add the entry that produces each one, or remove the path. ${guide('paths-the-build-does-not-produce')}`) - return true -} - -export function list(paths: string[]): string { - return [...new Set(paths)].map(path => `\`${path}\``).join(', ') -} - -const TS_PROBES = ['', '.ts', '.tsx', '.d.ts', '/index.ts', '/index.tsx', '/index.d.ts'] -const TS_MODULE_PROBES = ['.d.mts', '.d.cts', '/index.d.mts', '/index.d.cts'] - -function isFile(path: string) { - return existsSync(path) && statSync(path).isFile() -} - -/** Whether TypeScript's node10 resolution finds a file for `path`: as written, or with a `.ts`, `.tsx`, `.d.ts` or `/index` suffix. */ -function resolvesForTypeScript(cwd: string, path: string) { - return TS_PROBES.some(suffix => isFile(resolve(cwd, path + suffix))) -} - -/** The `.d.mts` or `.d.cts` file an unresolvable `path` was meant to reach, as a `./` path. */ -function node10Replacement(cwd: string, path: string) { - if (resolvesForTypeScript(cwd, path)) { - return - } - const suffix = TS_MODULE_PROBES.find(suffix => isFile(resolve(cwd, path + suffix))) - return suffix === undefined ? undefined : `./${relative(cwd, resolve(cwd, path + suffix))}` -} - -function typesVersionsPaths(pkg: PackageJSON) { - return collectStrings(pkg.typesVersions).filter(path => !path.includes('*')) -} - -export function missingPaths(cwd: string, pkg: PackageJSON): string[] { - const typesVersions = new Set(typesVersionsPaths(pkg)) - return referencedPaths(pkg).filter(path => !path.startsWith('/') && !(typesVersions.has(path) ? resolvesForTypeScript(cwd, path) : existsSync(resolve(cwd, path)))) -} - -function referencedPaths(pkg: PackageJSON): string[] { - return [...[pkg.exports, pkg.typesVersions, pkg.types, pkg.main, pkg.module].flatMap(collectStrings), ...collectStrings(pkg.imports).filter(path => path.startsWith('./'))] -} diff --git a/src/build/loader.ts b/src/build/loader.ts index 933c02ec..bdb4183c 100644 --- a/src/build/loader.ts +++ b/src/build/loader.ts @@ -1,4 +1,4 @@ -import { existsSync, readFileSync, statSync } from 'node:fs' +import { existsSync, readFileSync } from 'node:fs' import { createRequire, registerHooks } from 'node:module' import { fileURLToPath, pathToFileURL } from 'node:url' import { dirname, relative, resolve } from 'pathe' @@ -7,21 +7,17 @@ import { createPathsMatcher, getTsconfig } from 'get-tsconfig' import type ts from 'typescript' import type { Transform } from '../transpile/transpile-dir.ts' -import { isInside, relativeSpecifier } from '../utils.ts' +import { isInside, NODE_MODULES_RE, probe, relativeSpecifier, SCRIPT_RE, TYPESCRIPT_RE } from '../utils.ts' import { guide } from './guide.ts' const VIRTUAL_ALIAS_RE = /^#(?:app|imports|build)(?:\/|$)/ const ALIAS_SHAPED_RE = /^(?:#|~|@\/)/ -const NODE_MODULES_RE = /[\\/]node_modules[\\/]/ const JSON_RE = /\.json$/ const UNLOADABLE_RE = /\.(?:vue|[jt]sx)$/ -const EXTENSIONS = ['.ts', '.mts', '.cts', '.tsx', '.js', '.mjs', '.cjs', '.jsx'] export interface ImportModuleOptions { /** Module root, inside which `version` applies. */ cwd?: string - /** The build's output directory, inside which `version` also applies. */ - outDir?: string /** Source code to serve in place of these bare specifiers. */ stubs?: Record /** @@ -46,7 +42,7 @@ export async function importModule(path: string, options: ImportModuleOptions = return { url: `data:text/javascript,${encodeURIComponent(stubs[specifier]!)}`, shortCircuit: true } } const resolved = nextResolve(specifier, context) - if (!options.version || !resolved.url.startsWith('file:') || ![cwd, options.outDir ?? cwd].some(root => isInside(root, fileURLToPath(resolved.url))) || NODE_MODULES_RE.test(resolved.url)) { + if (!options.version || !resolved.url.startsWith('file:') || !isInside(cwd, fileURLToPath(resolved.url)) || NODE_MODULES_RE.test(resolved.url)) { return resolved } const url = new URL(resolved.url) @@ -67,9 +63,6 @@ export async function importModule(path: string, options: ImportModuleOptions = } } -const TYPESCRIPT_RE = /\.[cm]?tsx?$/ -const SOURCE_RE = /\.[cm]?[jt]sx?$/ - interface Oxc { transform: Transform transformSync: (...args: Parameters) => Awaited> @@ -210,7 +203,7 @@ function walkSources(cwd: string, entries: string[], visit: (file: string, analy const queue: Array<{ file: string, importer?: Importer }> = entries.map(entry => ({ file: resolve(cwd, entry) })) while (queue.length) { const { file, importer } = queue.shift()! - if (seen.has(file) || !SOURCE_RE.test(file) || !existsSync(file)) { + if (seen.has(file) || !SCRIPT_RE.test(file) || !existsSync(file)) { continue } seen.add(file) @@ -387,27 +380,3 @@ function pathsMatcher(cwd: string) { return undefined } } - -/** - * Find the source file a specifier refers to, trying the path as written, its - * TypeScript counterpart, each source extension, then an `index` file. - */ -export function probe(path: string): string | undefined { - if (existsSync(path) && statSync(path).isFile()) { - return path - } - const source = path.replace(/\.([cm]?)js(x?)$/, '.$1ts$2') - if (source !== path && existsSync(source)) { - return source - } - for (const extension of EXTENSIONS) { - if (existsSync(path + extension)) { - return path + extension - } - } - for (const extension of EXTENSIONS) { - if (existsSync(resolve(path, `index${extension}`))) { - return resolve(path, `index${extension}`) - } - } -} diff --git a/src/build/meta.ts b/src/build/meta.ts deleted file mode 100644 index 8d5c37ad..00000000 --- a/src/build/meta.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { resolve } from 'pathe' -import type { NuxtModule } from '@nuxt/schema' - -import { importModule } from './loader.ts' -import { writeIfChanged } from './write.ts' - -export interface WriteModuleMetaOptions { - cwd: string - outDir: string - pkg: { name?: string, version?: string } - builder: Record - /** Set on rebuilds, so the rebuilt module is imported rather than the cached one. */ - version?: number -} - -export async function writeModuleMeta({ cwd, outDir, pkg, builder, version }: WriteModuleMetaOptions): Promise { - const moduleExports = await importModule(resolve(outDir, 'module.mjs'), { cwd, outDir, version }) - const moduleFn = (moduleExports.default ?? moduleExports) as NuxtModule> - - const moduleMeta = await moduleFn.getMeta?.() || {} - moduleMeta.name ||= pkg.name - moduleMeta.version ||= pkg.version - moduleMeta.builder = builder - - await writeIfChanged(resolve(outDir, 'module.json'), JSON.stringify(moduleMeta, null, 2)) -} diff --git a/src/build/module-declarations.ts b/src/build/module-declarations.ts index 296f7dbd..2767aba0 100644 --- a/src/build/module-declarations.ts +++ b/src/build/module-declarations.ts @@ -4,11 +4,10 @@ import type { TsConfigResult } from 'get-tsconfig' import { dirname, join, normalize, relative, resolve } from 'pathe' import { createDeclarationProgram } from '../transpile/declarations.ts' -import { DECLARATION_RE, probe, RELATIVE_RE, rewriteSpecifiers, SCRIPT_RE } from '../transpile/resolve.ts' -import { isModuleFile } from '../transpile/tsconfig.ts' -import { relativeSpecifier } from '../utils.ts' +import { rewriteSpecifiers } from '../transpile/specifiers.ts' +import { hasIsolatedDeclarations, isModuleFile } from '../transpile/tsconfig.ts' +import { DECLARATION_RE, isInside, probe, RELATIVE_RE, relativeSpecifier, SCRIPT_RE } from '../utils.ts' import { loadOxc } from './loader.ts' -import { hasIsolatedDeclarations } from './tsconfig.ts' import { writeSourceTypes } from './types.ts' const NUXT_DIR_RE = /^\.nuxt(?:\/|$)/ @@ -26,7 +25,7 @@ export function moduleDeclarationPaths(cwd: string, dir: string, name: string, s const paths: Record = { [name]: [join(dir, 'types.d.mts')] } for (const [alias, [target]] of Object.entries(selfPaths)) { const file = target && !alias.includes('*') && alias !== name ? probe(target) : undefined - if (file && SCRIPT_RE.test(file) && !runtimeDirs.some(runtimeDir => !relative(runtimeDir, file).startsWith('..'))) { + if (file && SCRIPT_RE.test(file) && !runtimeDirs.some(runtimeDir => isInside(runtimeDir, file))) { paths[alias] = [declarationFile(cwd, dir, file)] } } diff --git a/src/build/options.ts b/src/build/options.ts index d3b4e3c7..b34046bb 100644 --- a/src/build/options.ts +++ b/src/build/options.ts @@ -2,10 +2,9 @@ import { isAbsolute, normalize, relative, resolve } from 'pathe' import type { PackageJson } from 'pkg-types' import { assertNoLegacyBuildConfig } from '../legacy/build-config.ts' -import { escapeRegExp, isInside, isPlainObject } from '../utils.ts' +import { escapeRegExp, isInside, isPlainObject, probe } from '../utils.ts' import type { BuildPlan } from './build.ts' import { guide } from './guide.ts' -import { probe } from './loader.ts' export const NUXT_EXTERNALS: (string | RegExp)[] = [ '@nuxt/schema', diff --git a/src/build/package.ts b/src/build/package.ts index 0ae1469e..95b3b423 100644 --- a/src/build/package.ts +++ b/src/build/package.ts @@ -1,6 +1,11 @@ -import { basename, relative, resolve } from 'pathe' +import { existsSync, statSync } 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, isInside, TYPESCRIPT_RE } from '../utils.ts' import { guide } from './guide.ts' const PUBLISH_CONFIG_FIELDS = ['bin', 'browser', 'exports', 'imports', 'main', 'module', 'types', 'typings', 'typesVersions'] as const @@ -18,9 +23,7 @@ const YARN_PUBLISH_CONFIG_FIELDS: Record = { const PACK_EVENTS = new Set(['prepack', 'prepublishOnly']) -const TS_SOURCE_RE = /\.[cm]?tsx?$/ const UNPUBLISHABLE = 'TypeScript sources or paths that `files` leaves out' -const DECLARATION_RE = /\.d\.[cm]?ts$/ /** `pkg` as pnpm publishes it, with the paths in `publishConfig` replacing their top-level fields. */ export function publishedPackage(pkg: PackageJson): PackageJson { @@ -53,7 +56,7 @@ export function unpublishablePaths(cwd: string, pkg: PackageJson, files: string[ ? Object.entries((pkg.imports ?? {}) as Record).flatMap(([key, value]) => collectStrings(value).filter(path => path.startsWith('./')).map(path => ({ path, key }))) : collectStrings(pkg[field]).map(path => ({ path })) return PATH_FIELDS.flatMap(field => targets(field).flatMap(({ path, key }): UnpublishablePath[] => { - if (TS_SOURCE_RE.test(path) && !DECLARATION_RE.test(path)) { + if (TYPESCRIPT_RE.test(path) && !DECLARATION_RE.test(path)) { return [{ field, path, reason: 'source', key }] } return !packed(cwd, path, files, alwaysPacked) ? [{ field, path, reason: 'files', key }] : [] @@ -61,8 +64,9 @@ export function unpublishablePaths(cwd: string, pkg: PackageJson, files: string[ } function packed(cwd: string, path: string, files: string[] | undefined, alwaysPacked: Set): boolean { - const file = relative(cwd, resolve(cwd, path.split('*')[0]!)) - if (!file || file.startsWith('..')) { + const target = resolve(cwd, path.split('*')[0]!) + const file = relative(cwd, target) + if (!file || !isInside(cwd, target)) { return !file } if (!path.includes('*') && alwaysPacked.has(file)) { @@ -204,11 +208,11 @@ function publishConfigFields(name: string, version: string | undefined): readonl return [] } -function list(values: string[]) { +export function list(values: string[]): string { return [...new Set(values)].map(value => `\`${value}\``).join(', ') } -export function collectStrings(value: unknown): string[] { +function collectStrings(value: unknown): string[] { if (typeof value === 'string') { return [value] } @@ -220,3 +224,128 @@ export function collectStrings(value: unknown): string[] { } return [] } + +/** + * `paths` pointing the package's own name and `exports` subpaths at its sources, so + * self-referencing imports type-check before `dist` exists. A subpath that points at a + * bundled entry of `entries`, keyed by output name, maps to that entry's input. + */ +export function selfReferencePaths(cwd: string, pkg: PackageJson, outDir: string, entries: Record = {}): Record { + if (!pkg.name) { + return {} + } + const paths: Record = { [pkg.name]: [resolve(cwd, 'src/module')] } + const { exports } = publishedPackage(pkg) + if (!exports || typeof exports !== 'object' || Array.isArray(exports)) { + return paths + } + for (const [subpath, target] of Object.entries(exports)) { + const file = exportTarget(target) + if (!subpath.startsWith('./') || !file) { + continue + } + if (isInside(outDir, resolve(cwd, file))) { + const name = relative(outDir, resolve(cwd, file)).replace(/(?:\.d)?\.[cm]?[jt]s$/, '') + const input = Object.hasOwn(entries, name) ? entries[name]!.replace(/\.[cm]?[jt]sx?$/, '') : join('src', name) + paths[`${pkg.name}/${subpath.slice(2)}`] = [resolve(cwd, input)] + } + } + return paths +} + +function exportTarget(target: unknown): string | undefined { + if (typeof target === 'string') { + return target + } + if (target && typeof target === 'object' && !Array.isArray(target)) { + const conditions = target as Record + return exportTarget(conditions.import ?? conditions.default ?? conditions.types) + } +} + +/** + * Warn about `package.json` fields that point at output this builder no longer produces. + * The paths are read as published, with `publishConfig` applied. + */ +export async function checkPublishedPaths(cwd: string): Promise { + const read = await readPackageJSON(cwd).catch(() => undefined) + const pkg = read && publishedPackage(read) + if (!pkg) { + return + } + + checkLegacyDeclarationPaths(cwd, pkg) + checkLegacyCJSPaths(cwd, pkg) + checkStaleTypesField(cwd, pkg) + checkNode10DeclarationPaths(cwd, pkg) + checkMissingPaths(cwd, pkg) +} + +export function checkStaleTypesField(cwd: string, pkg: PackageJson): boolean { + if (!pkg.types || resolvesForTypeScript(cwd, pkg.types)) { + return false + } + consola.warn(`\`types\` in \`package.json\` points at \`${pkg.types}\`, which the build does not produce. Set it to \`./dist/types.d.mts\`, which node10 module resolution reads, or remove it: bundler module resolution reads \`exports\` instead. ${guide('the-types-field')}`) + return true +} + +/** + * Warn about `typesVersions` paths that TypeScript's node10 resolution cannot find because + * they rely on probing for `.d.ts`, where the build now produces `.d.mts`. + */ +export function checkNode10DeclarationPaths(cwd: string, pkg: PackageJson): boolean { + const entries = typesVersionsPaths(pkg).flatMap((path) => { + const replacement = node10Replacement(cwd, path) + return replacement ? [`\`${path}\` (use \`${replacement}\`)`] : [] + }) + if (!entries.length) { + return false + } + consola.warn(`These \`typesVersions\` paths in \`package.json\` do not resolve under TypeScript's node10 module resolution, which probes for \`.d.ts\` but not for \`.d.mts\`: ${entries.join(', ')}. Write each path with its extension. ${guide('typesversions-paths')}`) + return true +} + +/** Warn about paths in `package.json` that the build did not produce, other than those the checks above explain. */ +export function checkMissingPaths(cwd: string, pkg: PackageJson): boolean { + const paths = [...new Set(missingPaths(cwd, pkg))] + .filter(path => !path.includes('*') && !isLegacyPath(path) && path !== pkg.types && !node10Replacement(cwd, path)) + if (!paths.length) { + return false + } + consola.warn(`These paths in \`package.json\` do not exist after the build, so imports that resolve to them will fail: ${list(paths)}. Add the entry that produces each one, or remove the path. ${guide('paths-the-build-does-not-produce')}`) + return true +} + +const TS_PROBES = ['', '.ts', '.tsx', '.d.ts', '/index.ts', '/index.tsx', '/index.d.ts'] +const TS_MODULE_PROBES = ['.d.mts', '.d.cts', '/index.d.mts', '/index.d.cts'] + +function isFile(path: string) { + return existsSync(path) && statSync(path).isFile() +} + +/** Whether TypeScript's node10 resolution finds a file for `path`: as written, or with a `.ts`, `.tsx`, `.d.ts` or `/index` suffix. */ +function resolvesForTypeScript(cwd: string, path: string) { + return TS_PROBES.some(suffix => isFile(resolve(cwd, path + suffix))) +} + +/** The `.d.mts` or `.d.cts` file an unresolvable `path` was meant to reach, as a `./` path. */ +function node10Replacement(cwd: string, path: string) { + if (resolvesForTypeScript(cwd, path)) { + return + } + const suffix = TS_MODULE_PROBES.find(suffix => isFile(resolve(cwd, path + suffix))) + return suffix === undefined ? undefined : `./${relative(cwd, resolve(cwd, path + suffix))}` +} + +function typesVersionsPaths(pkg: PackageJson) { + return collectStrings(pkg.typesVersions).filter(path => !path.includes('*')) +} + +export function missingPaths(cwd: string, pkg: PackageJson): string[] { + const typesVersions = new Set(typesVersionsPaths(pkg)) + return referencedPaths(pkg).filter(path => !path.startsWith('/') && !(typesVersions.has(path) ? resolvesForTypeScript(cwd, path) : existsSync(resolve(cwd, path)))) +} + +function referencedPaths(pkg: PackageJson): string[] { + return [...[pkg.exports, pkg.typesVersions, pkg.types, pkg.main, pkg.module].flatMap(collectStrings), ...collectStrings(pkg.imports).filter(path => path.startsWith('./'))] +} diff --git a/src/build/tsconfig.ts b/src/build/tsconfig.ts deleted file mode 100644 index 8e07a298..00000000 --- a/src/build/tsconfig.ts +++ /dev/null @@ -1,48 +0,0 @@ -import type { TsConfigResult } from 'get-tsconfig' -import { join, relative, resolve } from 'pathe' -import type { PackageJson } from 'pkg-types' - -import { publishedPackage } from './package.ts' - -/** - * `paths` pointing the package's own name and `exports` subpaths at its sources, so - * self-referencing imports type-check before `dist` exists. A subpath that points at a - * bundled entry of `entries`, keyed by output name, maps to that entry's input. - */ -export function selfReferencePaths(cwd: string, pkg: PackageJson, outDir: string, entries: Record = {}): Record { - if (!pkg.name) { - return {} - } - const paths: Record = { [pkg.name]: [resolve(cwd, 'src/module')] } - const { exports } = publishedPackage(pkg) - if (!exports || typeof exports !== 'object' || Array.isArray(exports)) { - return paths - } - for (const [subpath, target] of Object.entries(exports)) { - const file = exportTarget(target) - if (!subpath.startsWith('./') || !file) { - continue - } - const distPath = relative(outDir, resolve(cwd, file)) - if (!distPath.startsWith('..')) { - const name = distPath.replace(/(?:\.d)?\.[cm]?[jt]s$/, '') - const input = Object.hasOwn(entries, name) ? entries[name]!.replace(/\.[cm]?[jt]sx?$/, '') : join('src', name) - paths[`${pkg.name}/${subpath.slice(2)}`] = [resolve(cwd, input)] - } - } - return paths -} - -function exportTarget(target: unknown): string | undefined { - if (typeof target === 'string') { - return target - } - if (target && typeof target === 'object' && !Array.isArray(target)) { - const conditions = target as Record - return exportTarget(conditions.import ?? conditions.default ?? conditions.types) - } -} - -export function hasIsolatedDeclarations(tsconfig: TsConfigResult | undefined): boolean { - return tsconfig?.config.compilerOptions?.isolatedDeclarations === true -} diff --git a/src/build/types.ts b/src/build/types.ts index 74a12ecc..1d079652 100644 --- a/src/build/types.ts +++ b/src/build/types.ts @@ -3,8 +3,7 @@ import { dirname, relative, resolve } from 'pathe' import { findExports, findTypeExports } from 'mlly' import type { ESMExport } from 'mlly' -import { probe } from './loader.ts' -import { writeIfChanged } from './write.ts' +import { probe, writeIfChanged } from '../utils.ts' const TYPE_ONLY_DECLARATIONS = new Set(['interface', 'type']) const DECLARATION_SUFFIXES: Record = { diff --git a/src/build/write.ts b/src/build/write.ts deleted file mode 100644 index d4f5cae0..00000000 --- a/src/build/write.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { readFile, writeFile } from 'node:fs/promises' - -/** Writes `contents` to `file` unless it already holds them, so its modification time only changes with its content. */ -export async function writeIfChanged(file: string, contents: string): Promise { - if (await readFile(file, 'utf8').catch(() => undefined) !== contents) { - await writeFile(file, contents, 'utf8') - } -} diff --git a/src/commands/_shared.ts b/src/commands/_shared.ts index 8349f078..02b442be 100644 --- a/src/commands/_shared.ts +++ b/src/commands/_shared.ts @@ -1,7 +1,5 @@ import { guide } from '../build/guide.ts' import { realpath } from '../utils.ts' -import { findTsdownConfig, loadBuilderConfig } from './config-file.ts' -import type { BuilderConfig } from './config-file.ts' export const sharedArgs = { // cwd falls back to rootDir's default (indirect default) @@ -26,9 +24,3 @@ export function assertNoStubArg(command: 'build' | 'prepare', args: Record { - const file = findTsdownConfig(cwd) - return file ? loadBuilderConfig(cwd, file) : undefined -} diff --git a/src/commands/config-file.ts b/src/commands/config-file.ts index 7d450a22..99142ebe 100644 --- a/src/commands/config-file.ts +++ b/src/commands/config-file.ts @@ -40,7 +40,7 @@ export interface BuilderConfig { * Finds the options of the `builder()` plugin in a tsdown config file, which may export * a config, an array of configs, or a function returning either. */ -export async function loadBuilderConfig(cwd: string, file: string): Promise { +async function loadBuilderConfig(cwd: string, file: string): Promise { if (!file.endsWith('.json')) { assertLoadableModuleCode(cwd, [file], []) } @@ -72,6 +72,12 @@ export async function loadBuilderConfig(cwd: string, file: string): Promise { + const file = findTsdownConfig(cwd) + return file ? loadBuilderConfig(cwd, file) : undefined +} + /** Whether `plugins`, in any of the shapes a tsdown config accepts, contain `builder()`. */ export async function hasBuilder(plugins: unknown): Promise { return (await flattenPlugins(plugins)).some(plugin => !!plugin && typeof plugin === 'object' && BUILDER_OPTIONS in plugin) diff --git a/src/commands/prepare.ts b/src/commands/prepare.ts index 6e66f273..a3ff6b00 100644 --- a/src/commands/prepare.ts +++ b/src/commands/prepare.ts @@ -12,12 +12,13 @@ import { assertLoadableModuleCode, importModule } from '../build/loader.ts' import { moduleDeclarationPaths, writeModuleDeclarations } from '../build/module-declarations.ts' import { bundledEntries, resolveModuleOptions } from '../build/options.ts' import type { ModuleConfig } from '../build/options.ts' -import { selfReferencePaths } from '../build/tsconfig.ts' +import { selfReferencePaths } from '../build/package.ts' import { writeSourceTypes } from '../build/types.ts' import { loadBuildConfig } from '../legacy/build-config.ts' -import { probe } from '../transpile/resolve.ts' import { createTsconfigResolver, isModuleFile, rootTsconfig } from '../transpile/tsconfig.ts' -import { assertNoStubArg, loadModuleConfig, resolveCwdArg, sharedArgs } from './_shared.ts' +import { isInside, probe } from '../utils.ts' +import { assertNoStubArg, resolveCwdArg, sharedArgs } from './_shared.ts' +import { loadModuleConfig } from './config-file.ts' const BUILD_DECLARATION_RE = /^declare module "#build\/(.+)";$/ const PATH_OPTIONS = new Set(['paths', 'baseUrl', 'rootDir', 'rootDirs', 'outDir', 'outFile', 'declarationDir', 'typeRoots', 'tsBuildInfoFile']) @@ -178,7 +179,7 @@ export async function prepareModule(cwd: string, buildConfig?: { config: ModuleC list.push(...ambient.augmentations.map(path => ({ path }))) } // Module code can import types from runtime sources, which rely on the app's aliases, declarations and JSX options. - const appDeclarations = (tsConfig.include ?? []).filter(pattern => !relative(nuxt.options.buildDir, resolve(nuxt.options.buildDir, pattern)).startsWith('..')) + const appDeclarations = (tsConfig.include ?? []).filter(pattern => isInside(nuxt.options.buildDir, resolve(nuxt.options.buildDir, pattern))) nodeTsConfig.include = [...new Set([...nodeTsConfig.include ?? [], ...appDeclarations])] // A type reference does not resolve the module's own package name. const ownReference = nodeReferences.findIndex(isOwnTypes) @@ -207,7 +208,7 @@ export async function prepareModule(cwd: string, buildConfig?: { config: ModuleC await writeSourceTypes(sourceTypesDir(cwd), entryPath) await writeCompatibilityTsconfig(resolve(cwd, '.nuxt/tsconfig.json'), cwd, { ownPaths, ownTypes, entryPath, ambient: ambient.globals }) if (name && perContext) { - const roots = Object.values(entries).flatMap(input => probe(resolve(cwd, input)) ?? []).filter(file => !runtimeDirs.some(dir => !relative(dir, file).startsWith('..'))) + const roots = Object.values(entries).flatMap(input => probe(resolve(cwd, input)) ?? []).filter(file => !runtimeDirs.some(dir => isInside(dir, file))) const tsconfigs = await createTsconfigResolver(cwd) const project = tsconfigs.resolve(entryPath) const nodeTsconfig = resolve(cwd, '.nuxt/tsconfig.node.json') @@ -242,7 +243,7 @@ async function writeCompatibilityTsconfig(file: string, cwd: string, { ownPaths, const entryDir = dirname(entryPath) const isDerived = (pattern: string) => { const path = resolve(dirname(file), pattern) - const inEntryDist = entryDir !== cwd && !relative(join(entryDir, 'dist'), path).startsWith('..') + const inEntryDist = entryDir !== cwd && isInside(join(entryDir, 'dist'), path) return path === ownTypes || path === join(entryDir, 'runtime/server') || inEntryDist } config.include = config.include?.filter(pattern => !isDerived(pattern)) diff --git a/src/legacy/package-paths.ts b/src/legacy/package-paths.ts index 1d03f962..764637be 100644 --- a/src/legacy/package-paths.ts +++ b/src/legacy/package-paths.ts @@ -6,7 +6,7 @@ import { consola } from 'consola' import type { PackageJson } from 'pkg-types' import { guide } from '../build/guide.ts' -import { list, missingPaths } from '../build/deprecations.ts' +import { list, missingPaths } from '../build/package.ts' const DECLARATION_RE = /(?:^|\/)(?:module|types)\.d\.ts$/ const CJS_MODULE_RE = /(?:^|\/)module\.cjs$/ diff --git a/src/transpile/declarations.ts b/src/transpile/declarations.ts index 063369f8..28e86541 100644 --- a/src/transpile/declarations.ts +++ b/src/transpile/declarations.ts @@ -3,7 +3,6 @@ import { relative } from 'pathe' import type ts from 'typescript' import { declarationPaths, projectFiles, tsconfigPaths, writeAmbientModules, writeServerRoutesStub } from './tsconfig.ts' -import type { DeclarationPaths } from './tsconfig.ts' export interface DeclarationProgramOptions { cwd: string @@ -22,7 +21,6 @@ interface DeclarationEmit { } export interface DeclarationProgram { - paths: DeclarationPaths emit: (files: string[]) => Promise /** The program's source files other than declaration files. */ sources: () => string[] @@ -65,7 +63,6 @@ export async function createDeclarationProgram({ cwd, tsconfig, paths }: Declara const createProgram = () => program ??= ts.createProgram({ rootNames: [...rootNames], options, projectReferences: parsed?.projectReferences }) return { - paths: declaration, sources: () => createProgram().getSourceFiles().filter(source => !source.isDeclarationFile).map(source => source.fileName), resolve: (specifier, importer) => ts.resolveModuleName(specifier, importer, options, ts.sys).resolvedModule?.resolvedFileName, async emit(files) { diff --git a/src/transpile/resolve.ts b/src/transpile/specifiers.ts similarity index 77% rename from src/transpile/resolve.ts rename to src/transpile/specifiers.ts index c7b9ed65..559bff35 100644 --- a/src/transpile/resolve.ts +++ b/src/transpile/specifiers.ts @@ -1,10 +1,7 @@ -import { existsSync, statSync } from 'node:fs' import { findDynamicImports, findExports, findStaticImports, findTypeExports } from 'mlly' -import { resolve } from 'pathe' -export const SCRIPT_RE: RegExp = /\.[cm]?[jt]sx?$/ -export const DECLARATION_RE: RegExp = /\.d\.[cm]?ts$/ -export const RELATIVE_RE: RegExp = /^\.\.?(?:\/|$)/ +import { RELATIVE_RE } from '../utils.ts' + const JSX_RE = /\.[jt]sx$/ /** The extension `file` is emitted with: `.jsx` for a JSX source when JSX is preserved, `extension` otherwise. */ @@ -12,32 +9,6 @@ export function scriptExtension(file: string, extension: string, preserveJsx: bo return preserveJsx && JSX_RE.test(file) ? '.jsx' : extension } -const EXTENSIONS = ['.ts', '.mts', '.cts', '.tsx', '.js', '.mjs', '.cjs', '.jsx'] - -/** The file an extensionless or `.js`-suffixed specifier for a TypeScript source resolves to. */ -export function probe(path: string): string | undefined { - if (existsSync(path) && statSync(path).isFile()) { - return path - } - const source = path.replace(/\.([cm]?)js(x?)$/, '.$1ts$2') - if (source !== path && existsSync(source)) { - return source - } - if (path.endsWith('.js') && existsSync(`${source}x`)) { - return `${source}x` - } - for (const extension of EXTENSIONS) { - if (existsSync(path + extension)) { - return path + extension - } - } - for (const extension of EXTENSIONS) { - if (existsSync(resolve(path, `index${extension}`))) { - return resolve(path, `index${extension}`) - } - } -} - export interface Specifier { specifier: string /** Offset of the opening quote. */ diff --git a/src/transpile/transpile-dir.ts b/src/transpile/transpile-dir.ts index 471dea91..dd54f943 100644 --- a/src/transpile/transpile-dir.ts +++ b/src/transpile/transpile-dir.ts @@ -6,10 +6,10 @@ import type { Rolldown } from 'tsdown' import type { Transform as VueTransform } from 'vue-sfc-transformer/core' -import { relativeSpecifier } from '../utils.ts' +import { DECLARATION_RE, probe, RELATIVE_RE, relativeSpecifier, SCRIPT_RE, TYPESCRIPT_RE } from '../utils.ts' import { createDeclarationProgram, DeclarationError, declarationError } from './declarations.ts' import type { DeclarationProgram } from './declarations.ts' -import { DECLARATION_RE, moduleSpecifiers, probe, RELATIVE_RE, rewriteSpecifiers, SCRIPT_RE, scriptExtension, valueSpecifiers } from './resolve.ts' +import { moduleSpecifiers, rewriteSpecifiers, scriptExtension, valueSpecifiers } from './specifiers.ts' import { compileSass, SASS_RE, transformCss } from './stylesheets.ts' import { createTsconfigResolver, writeDependencyImports, writeDerivedTsconfig } from './tsconfig.ts' import type { TsconfigResolver } from './tsconfig.ts' @@ -113,7 +113,6 @@ const EMPTY_IMPORT_RE = /^[ \t]*import\s*\{\s*\}\s*from\s*(['"])[^'"\n]+\1\s*;?/ export const EXCLUDE: string[] = ['**/*.{stories,spec,test}.{js,jsx,ts,tsx,mjs,cjs,mts,cts}', '**/node_modules/**'] const STYLESHEET_RE = /\.(?:css|s[ac]ss)$/ const VUE_DECLARATION_RE = /\.(?:d\.vue\.ts|vue\.d\.ts)$/ -const TYPESCRIPT_RE = /\.(?:[cm]?ts|tsx)$/ interface Emitter { /** Rewritten declarations keyed by source path. */ @@ -129,14 +128,6 @@ interface Emitter { * files are copied, and declarations come from one TypeScript program over the directory. */ export function transpileDir(options: TranspileDirOptions): Rolldown.Plugin & { api: TranspileDirApi } { - let resolveOutputs: (outputs: Map) => void - let rejectOutputs: (error: unknown) => void - const outputs = new Promise>((resolve, reject) => { - resolveOutputs = resolve - rejectOutputs = reject - }) - outputs.catch(() => {}) - let latestOutputs = outputs let work: Promise<{ build: DirectoryBuild, files: Emitted[] } | { error: unknown }> | undefined let latestBuild: DirectoryBuild | undefined @@ -144,7 +135,7 @@ export function transpileDir(options: TranspileDirOptions): Rolldown.Plugin & { name: 'transpile-dir', api: { get outputs() { - return latestOutputs + return work!.then(result => 'error' in result ? Promise.reject(result.error) : result.build.outputs) }, }, async buildStart() { @@ -153,17 +144,7 @@ export function transpileDir(options: TranspileDirOptions): Rolldown.Plugin & { this.addWatchFile(file) } const build = latestBuild = new DirectoryBuild(options, files.map(file => normalize(file)).sort()) - work = build.run() - .then((files) => { - resolveOutputs(build.outputs) - return { build, files } - }) - .catch((error) => { - rejectOutputs(error) - return { error } - }) - latestOutputs = work.then(result => 'error' in result ? Promise.reject(result.error) : result.build.outputs) - latestOutputs.catch(() => {}) + work = build.run().then(files => ({ build, files }), (error: unknown) => ({ error })) }, async buildEnd() { await work diff --git a/src/transpile/tsconfig.ts b/src/transpile/tsconfig.ts index dc8e6f77..e8eb77b8 100644 --- a/src/transpile/tsconfig.ts +++ b/src/transpile/tsconfig.ts @@ -3,10 +3,11 @@ import { existsSync } from 'node:fs' import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises' import { createFilesMatcher, createPathsMatcher, getTsconfig, parseTsconfig } from 'get-tsconfig' import type { TsConfigResult } from 'get-tsconfig' -import { dirname, isAbsolute, join, relative, resolve } from 'pathe' +import { dirname, join, relative, resolve } from 'pathe' import type ts from 'typescript' -import { moduleSpecifiers } from './resolve.ts' +import { findPackageDir, isInside, NODE_MODULES_RE } from '../utils.ts' +import { moduleSpecifiers } from './specifiers.ts' export interface TsconfigResolver { /** The nearest tsconfig, which may delegate files to `references`. */ @@ -50,7 +51,7 @@ function usesForeignBuildDir(tsconfig: TsConfigResult, dir: string) { } function isOwnBuildFile(file: string, dir: string) { - return !relative(join(dir, '.nuxt'), file).startsWith('..') + return isInside(join(dir, '.nuxt'), file) } function isForeignBuildFile(file: string, dir: string) { @@ -174,8 +175,7 @@ export function projectFiles(parsed: ts.ParsedCommandLine | undefined, dir: stri /** Whether `file` belongs to the module in `dir`, as {@link projectFiles} decides. */ export function isModuleFile(file: string, dir: string): boolean { - const path = relative(dir, file) - if (path.startsWith('..') || isAbsolute(path) || FOREIGN_DIR_RE.test(path.split('/')[0]!) || NODE_MODULES_RE.test(file)) { + if (!isInside(dir, file) || FOREIGN_DIR_RE.test(relative(dir, file).split('/')[0]!) || NODE_MODULES_RE.test(file)) { return false } return !NUXT_BUILD_DIR_RE.test(file) || isOwnBuildFile(file, dir) @@ -210,6 +210,10 @@ function allReferencedProjects(tsconfig: TsConfigResult | undefined, seen = new }).sort((a, b) => projectRank(a.path) - projectRank(b.path)) } +export function hasIsolatedDeclarations(tsconfig: TsConfigResult | undefined): boolean { + return tsconfig?.config.compilerOptions?.isolatedDeclarations === true +} + /** The tsconfig's `paths` made absolute. */ export function tsconfigPaths(tsconfig: TsConfigResult | undefined): Record { const paths = tsconfig?.config.compilerOptions?.paths @@ -223,7 +227,6 @@ export function tsconfigPaths(tsconfig: TsConfigResult | undefined): Record, cwd: string) { } } -/** The directory of an installed package, found the way Node looks up `node_modules`. */ -export function findPackageDir(name: string, cwd: string): string | undefined { - for (let dir = cwd; ; dir = dirname(dir)) { - const packageDir = join(dir, 'node_modules', name) - if (existsSync(join(packageDir, 'package.json'))) { - return packageDir - } - if (dirname(dir) === dir) { - return - } - } -} - const cacheDir = (cwd: string) => join(cwd, 'node_modules/.cache/transpile-dir') function cachedPath(cwd: string, extension: string, contents: string) { diff --git a/src/tsdown/externals.ts b/src/tsdown/externals.ts index 91f24aa4..050ab80b 100644 --- a/src/tsdown/externals.ts +++ b/src/tsdown/externals.ts @@ -1,10 +1,9 @@ -import { isAbsolute } from 'pathe' +import { dirname, isAbsolute, join, normalize, relative } from 'pathe' import type { Rolldown } from 'tsdown' import { rewriteAppAliases } from '../build/aliases.ts' - -const DECLARATION_RE = /\.d\.[cm]?ts$/ -const NODE_MODULES_RE = /[\\/]node_modules[\\/]/ +import { scriptExtension } from '../transpile/specifiers.ts' +import { DECLARATION_RE, isInside, NODE_MODULES_RE, probe, SCRIPT_RE } from '../utils.ts' /** * Keeps declaration imports of installed packages external, whether or not the package @@ -37,3 +36,80 @@ export function externalDependencyDeclarations(): Rolldown.Plugin { }, } } + +export interface RuntimeExternalsOptions { + /** Absolute path of the build's output directory. */ + outDir: string + /** The directories transpiled file by file, with their absolute source and output paths. */ + directories: Array<{ srcDir: string, outDir: string, ext: 'js' | 'mjs' }> + /** The module's own package name, so self-referencing imports are caught. */ + packageName?: string + /** Whether a JSX source is emitted with its JSX preserved, as `.jsx`. Defaults to always. */ + preserveJsx?: (file: string) => boolean +} + +/** + * Rewrites imports of the module's runtime tree to the absolute paths they will occupy + * in `dist/`, and marks them external so the runtime tree is never inlined into the + * bundled module entry. The build has to set `makeAbsoluteExternalsRelative: false`: + * the specifiers are made relative to each chunk's own location when it is rendered. + * + * `this.resolve()` is used rather than pattern-matching the specifier so that + * tsconfig path aliases resolving into `src/runtime/` are handled too. + */ +export function runtimeExternals({ outDir, directories, packageName, preserveJsx = () => true }: RuntimeExternalsOptions): Rolldown.Plugin { + const selfPrefix = packageName ? `${packageName}/` : undefined + const distSubpath = (subpath: string, { srcDir, ext }: { srcDir: string, ext: string }) => { + const source = probe(join(srcDir, subpath)) + if (source && SCRIPT_RE.test(source)) { + return relative(srcDir, source).replace(SCRIPT_RE, scriptExtension(source, `.${ext}`, preserveJsx(source))) + } + if (source || subpath.endsWith('.vue')) { + return subpath + } + return `${subpath.replace(SCRIPT_RE, '')}.${ext}` + } + + return { + name: 'nuxt-module-builder:runtime-externals', + async resolveId(id, importer) { + if (selfPrefix && id.startsWith(selfPrefix)) { + const target = join(outDir, id.slice(selfPrefix.length)) + const directory = directories.find(directory => target !== directory.outDir && isInside(directory.outDir, target)) + if (directory) { + return { id: join(directory.outDir, distSubpath(relative(directory.outDir, target), directory)), external: true } + } + } + + if (!importer) { + return + } + + const resolved = await this.resolve(id, importer, { skipSelf: true }) + if (!resolved || resolved.external) { + return + } + + const file = normalize(resolved.id) + const directory = directories.find(directory => file !== directory.srcDir && isInside(directory.srcDir, file)) + if (directory) { + return { id: join(directory.outDir, distSubpath(relative(directory.srcDir, file), directory)), external: true } + } + }, + renderChunk(code, chunk, { dir }) { + if (!dir) { + return + } + const chunkDir = dirname(join(dir, chunk.fileName)) + let result = code + for (const id of new Set([...chunk.imports, ...chunk.dynamicImports])) { + if (!directories.some(directory => id.startsWith(`${directory.outDir}/`))) { + continue + } + const specifier = relative(chunkDir, id) + result = result.replaceAll(JSON.stringify(id), JSON.stringify(specifier.startsWith('.') ? specifier : `./${specifier}`)) + } + return result === code ? undefined : { code: result, map: null } + }, + } +} diff --git a/src/tsdown/replace.ts b/src/tsdown/replace.ts deleted file mode 100644 index 5c3e441f..00000000 --- a/src/tsdown/replace.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { pathToFileURL } from 'node:url' -import { resolvePath } from 'mlly' -import type { Rolldown } from 'tsdown' - -import type { ReplaceOptions } from '../build/options.ts' - -/** - * rolldown's built-in replace plugin. It is loaded from the copy of rolldown that - * tsdown runs, because built-in plugins only work with the binding that created them. - */ -export async function replacePlugin({ values, ...options }: ReplaceOptions): Promise { - const tsdown = await resolvePath('tsdown', { url: import.meta.url }) - const plugins = await resolvePath('rolldown/plugins', { url: tsdown }) - const { replacePlugin } = await import(pathToFileURL(plugins).href) as { replacePlugin: (values: Record, options: Omit) => Rolldown.RolldownPluginOption } - return replacePlugin(values, options) -} diff --git a/src/tsdown/report.ts b/src/tsdown/report.ts index 23f89ecf..62fb1340 100644 --- a/src/tsdown/report.ts +++ b/src/tsdown/report.ts @@ -2,8 +2,7 @@ import { relative } from 'pathe' import type { Rolldown, UserConfig } from 'tsdown' import type { DirectoryEntry } from '../build/options.ts' - -const DECLARATION_RE = /\.d\.(?:[^/]+\.)?[cm]?ts$/ +import { ANY_DECLARATION_RE } from '../utils.ts' /** * tsdown's size report, unless the config sets `report`: a summary when the build has @@ -47,7 +46,7 @@ export function sizeBreakdown(bundle: Rolldown.OutputBundle, { cwd, outDir, entr for (const prefix of prefixes) { const files = sizes.filter(output => output.asset && !entryFiles.has(output.fileName) && owner(output.fileName) === prefix) if (files.length) { - const total = (declarations: boolean) => files.filter(output => DECLARATION_RE.test(output.fileName) === declarations).reduce((sum, output) => sum + output.size, 0) + const total = (declarations: boolean) => files.filter(output => ANY_DECLARATION_RE.test(output.fileName) === declarations).reduce((sum, output) => sum + output.size, 0) rows.push([`${base}/${prefix}`, `${formatSize(total(false))} Β· types ${formatSize(total(true))} Β· ${files.length} files`]) } } diff --git a/src/tsdown/runtime-externals.ts b/src/tsdown/runtime-externals.ts deleted file mode 100644 index 68afaa71..00000000 --- a/src/tsdown/runtime-externals.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { dirname, isAbsolute, join, normalize, relative } from 'pathe' -import type { Rolldown } from 'tsdown' - -import { probe, SCRIPT_RE, scriptExtension } from '../transpile/resolve.ts' - -export interface RuntimeExternalsOptions { - /** Absolute path of the build's output directory. */ - outDir: string - /** The directories transpiled file by file, with their absolute source and output paths. */ - directories: Array<{ srcDir: string, outDir: string, ext: 'js' | 'mjs' }> - /** The module's own package name, so self-referencing imports are caught. */ - packageName?: string - /** Whether a JSX source is emitted with its JSX preserved, as `.jsx`. Defaults to always. */ - preserveJsx?: (file: string) => boolean -} - -/** - * Rewrites imports of the module's runtime tree to the absolute paths they will occupy - * in `dist/`, and marks them external so the runtime tree is never inlined into the - * bundled module entry. The build has to set `makeAbsoluteExternalsRelative: false`: - * the specifiers are made relative to each chunk's own location when it is rendered. - * - * `this.resolve()` is used rather than pattern-matching the specifier so that - * tsconfig path aliases resolving into `src/runtime/` are handled too. - */ -export function runtimeExternals({ outDir, directories, packageName, preserveJsx = () => true }: RuntimeExternalsOptions): Rolldown.Plugin { - const selfPrefix = packageName ? `${packageName}/` : undefined - const distSubpath = (subpath: string, { srcDir, ext }: { srcDir: string, ext: string }) => { - const source = probe(join(srcDir, subpath)) - if (source && SCRIPT_RE.test(source)) { - return relative(srcDir, source).replace(SCRIPT_RE, scriptExtension(source, `.${ext}`, preserveJsx(source))) - } - if (source || subpath.endsWith('.vue')) { - return subpath - } - return `${subpath.replace(SCRIPT_RE, '')}.${ext}` - } - - return { - name: 'nuxt-module-builder:runtime-externals', - async resolveId(id, importer) { - if (selfPrefix && id.startsWith(selfPrefix)) { - const target = join(outDir, id.slice(selfPrefix.length)) - for (const directory of directories) { - const subpath = relative(directory.outDir, target) - if (subpath && !subpath.startsWith('..') && !isAbsolute(subpath)) { - return { id: join(directory.outDir, distSubpath(subpath, directory)), external: true } - } - } - } - - if (!importer) { - return - } - - const resolved = await this.resolve(id, importer, { skipSelf: true }) - if (!resolved || resolved.external) { - return - } - - for (const directory of directories) { - const subpath = relative(directory.srcDir, normalize(resolved.id)) - if (subpath && !subpath.startsWith('..') && !isAbsolute(subpath)) { - return { id: join(directory.outDir, distSubpath(subpath, directory)), external: true } - } - } - }, - renderChunk(code, chunk, { dir }) { - if (!dir) { - return - } - const chunkDir = dirname(join(dir, chunk.fileName)) - let result = code - for (const id of new Set([...chunk.imports, ...chunk.dynamicImports])) { - if (!directories.some(directory => id.startsWith(`${directory.outDir}/`))) { - continue - } - const specifier = relative(chunkDir, id) - result = result.replaceAll(JSON.stringify(id), JSON.stringify(specifier.startsWith('.') ? specifier : `./${specifier}`)) - } - return result === code ? undefined : { code: result, map: null } - }, - } -} diff --git a/src/tsdown/setup.ts b/src/tsdown/setup.ts index 37c15ca7..f9e43e71 100644 --- a/src/tsdown/setup.ts +++ b/src/tsdown/setup.ts @@ -1,25 +1,24 @@ import { existsSync, readdirSync } from 'node:fs' import { rm } from 'node:fs/promises' +import { pathToFileURL } from 'node:url' import { dirname, relative, resolve } from 'pathe' import { consola } from 'consola' +import { resolvePath } from 'mlly' import { readPackageJSON } from 'pkg-types' import type { PackageJson } from 'pkg-types' import type { InlineConfig, ResolvedConfig, Rolldown, UserConfig } from 'tsdown' import { analyseSources, finishBuild, onBuildError, prepareBuild, preservesJsx, resolveBuild, resolveDirectoryExternal } from '../build/build.ts' -import type { BuildPlan } from '../build/build.ts' import { guide } from '../build/guide.ts' import { loadOxc } from '../build/loader.ts' import { resolveModuleOptions, resolveOutDir } from '../build/options.ts' -import type { BuilderOptions, ModuleConfig } from '../build/options.ts' +import type { BuilderOptions, ModuleConfig, ReplaceOptions } from '../build/options.ts' import { sourcePathsPackError, unpublishablePathsError } from '../build/package.ts' import { prepareModule } from '../commands/prepare.ts' import { transpileDir, TYPE_ERRORS_WARNING } from '../transpile/transpile-dir.ts' -import { externalDependencyDeclarations } from './externals.ts' -import { replacePlugin } from './replace.ts' -import { defaultReport, reportsSummary, sizeBreakdown } from './report.ts' -import { runtimeExternals } from './runtime-externals.ts' import { realpath } from '../utils.ts' +import { externalDependencyDeclarations, runtimeExternals } from './externals.ts' +import { defaultReport, reportsSummary, sizeBreakdown } from './report.ts' import { unchangedOutputs } from './unchanged.ts' export interface SetupOptions { @@ -28,7 +27,6 @@ export interface SetupOptions { } export interface BuilderSession { - plan: BuildPlan /** Whether a build has started with this session. */ started: boolean /** Directories a watcher watches as a whole, so new files in them trigger a rebuild. */ @@ -192,7 +190,6 @@ export async function setupBuilder(config: UserConfig, inline: InlineConfig, opt } satisfies UserConfig) const session: BuilderSession = { - plan, started: false, watchDirs: [...new Set(plan.runtimeDirs.map(dir => existingAncestor(dir, cwd)))], checkResolved(resolved) { @@ -262,6 +259,17 @@ export async function setupBuilder(config: UserConfig, inline: InlineConfig, opt return session } +/** + * rolldown's built-in replace plugin. It is loaded from the copy of rolldown that + * tsdown runs, because built-in plugins only work with the binding that created them. + */ +async function replacePlugin({ values, ...options }: ReplaceOptions): Promise { + const tsdown = await resolvePath('tsdown', { url: import.meta.url }) + const plugins = await resolvePath('rolldown/plugins', { url: tsdown }) + const { replacePlugin } = await import(pathToFileURL(plugins).href) as { replacePlugin: (values: Record, options: Omit) => Rolldown.RolldownPluginOption } + return replacePlugin(values, options) +} + /** The files that `finishBuild` writes after the bundle. */ const FINISHED_FILES = new Set(['module.json', 'types.d.mts']) diff --git a/src/tsdown/unchanged.ts b/src/tsdown/unchanged.ts index 848a210d..4a3346a1 100644 --- a/src/tsdown/unchanged.ts +++ b/src/tsdown/unchanged.ts @@ -4,8 +4,7 @@ import { join } from 'pathe' import type { Rolldown } from 'tsdown' import { declarationTargets } from '../build/aliases.ts' - -const DECLARATION_RE = /\.d\.(?:[^/]+\.)?[cm]?ts$/ +import { ANY_DECLARATION_RE } from '../utils.ts' export interface UnchangedOutputs { /** @@ -73,7 +72,7 @@ function contentHash(output: Rolldown.OutputChunk | Rolldown.OutputAsset, bundle if (output.type === 'chunk' && output.map) { hash.update(output.map.toString()) } - if (DECLARATION_RE.test(output.fileName)) { + if (ANY_DECLARATION_RE.test(output.fileName)) { const text = typeof code === 'string' ? code : Buffer.from(code).toString('utf8') hash.update('\0').update(declarationTargets(output.fileName, text).filter(target => Object.hasOwn(bundle, target)).join('\0')) } diff --git a/src/utils.ts b/src/utils.ts index b09c4176..904bd95d 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1,5 +1,43 @@ -import { existsSync, realpathSync } from 'node:fs' -import { dirname, isAbsolute, relative, resolve } from 'pathe' +import { existsSync, realpathSync, statSync } from 'node:fs' +import { readFile, writeFile } from 'node:fs/promises' +import { dirname, isAbsolute, join, relative, resolve } from 'pathe' + +export const SCRIPT_RE: RegExp = /\.[cm]?[jt]sx?$/ +export const TYPESCRIPT_RE: RegExp = /\.[cm]?tsx?$/ +export const DECLARATION_RE: RegExp = /\.d\.[cm]?ts$/ +/** Declarations of scripts and of single-file components, such as `Foo.d.vue.ts`. */ +export const ANY_DECLARATION_RE: RegExp = /\.d\.(?:[^/]+\.)?[cm]?ts$/ +export const RELATIVE_RE: RegExp = /^\.\.?(?:\/|$)/ +export const NODE_MODULES_RE: RegExp = /[\\/]node_modules[\\/]/ + +const EXTENSIONS = ['.ts', '.mts', '.cts', '.tsx', '.js', '.mjs', '.cjs', '.jsx'] + +/** + * The source file a specifier refers to: the path as written, its TypeScript counterpart for + * a `.js`-suffixed path, the path with each source extension, then an `index` file. + */ +export function probe(path: string): string | undefined { + if (existsSync(path) && statSync(path).isFile()) { + return path + } + const source = path.replace(/\.([cm]?)js(x?)$/, '.$1ts$2') + if (source !== path && existsSync(source)) { + return source + } + if (path.endsWith('.js') && existsSync(`${source}x`)) { + return `${source}x` + } + for (const extension of EXTENSIONS) { + if (existsSync(path + extension)) { + return path + extension + } + } + for (const extension of EXTENSIONS) { + if (existsSync(resolve(path, `index${extension}`))) { + return resolve(path, `index${extension}`) + } + } +} /** `path` resolved, with symlinks followed when it exists, as module ids are. */ export function realpath(path: string): string { @@ -13,6 +51,32 @@ export function isInside(dir: string, path: string): boolean { return subpath !== '..' && !subpath.startsWith('../') && !isAbsolute(subpath) } +/** The relative specifier from the directory of `from` to `to`. */ +export function relativeSpecifier(from: string, to: string): string { + const path = relative(dirname(from), to) + return RELATIVE_RE.test(path) ? path : `./${path}` +} + +/** The directory of an installed package, found the way Node looks up `node_modules`. */ +export function findPackageDir(name: string, cwd: string): string | undefined { + for (let dir = cwd; ; dir = dirname(dir)) { + const packageDir = join(dir, 'node_modules', name) + if (existsSync(join(packageDir, 'package.json'))) { + return packageDir + } + if (dirname(dir) === dir) { + return + } + } +} + +/** Writes `contents` to `file` unless it already holds them, so its modification time only changes with its content. */ +export async function writeIfChanged(file: string, contents: string): Promise { + if (await readFile(file, 'utf8').catch(() => undefined) !== contents) { + await writeFile(file, contents, 'utf8') + } +} + export function isPlainObject(value: unknown): value is Record { return !!value && typeof value === 'object' && !Array.isArray(value) && !(value instanceof RegExp) } @@ -20,11 +84,3 @@ export function isPlainObject(value: unknown): value is Record export function escapeRegExp(value: string): string { return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') } - -export const RELATIVE_RE: RegExp = /^\.\.?(?:\/|$)/ - -/** The relative specifier from the directory of `from` to `to`. */ -export function relativeSpecifier(from: string, to: string): string { - const path = relative(dirname(from), to) - return RELATIVE_RE.test(path) ? path : `./${path}` -} diff --git a/test/regressions.spec.ts b/test/regressions.spec.ts index 427c132c..a55b0b2b 100644 --- a/test/regressions.spec.ts +++ b/test/regressions.spec.ts @@ -9,11 +9,11 @@ import { afterAll, describe, expect, it, vi } from 'vitest' import { analyseSources, hashGeneratedTypes } from '../src/build/build.ts' import type { BuildPlan } from '../src/build/build.ts' import { resolveModuleOptions, resolveOutDir } from '../src/build/options.ts' -import { selfReferencePaths } from '../src/build/tsconfig.ts' +import { selfReferencePaths } from '../src/build/package.ts' import { resolveCwdArg } from '../src/commands/_shared.ts' import { translateBuildConfig } from '../src/legacy/build-config.ts' import { checkLegacyCJSPaths } from '../src/legacy/package-paths.ts' -import { moduleSpecifiers, valueSpecifiers } from '../src/transpile/resolve.ts' +import { moduleSpecifiers, valueSpecifiers } from '../src/transpile/specifiers.ts' import { relativeSpecifier } from '../src/utils.ts' import { copyExample, repoRoot } from './utils.ts' diff --git a/test/unit.spec.ts b/test/unit.spec.ts index 159a0c11..3b638965 100644 --- a/test/unit.spec.ts +++ b/test/unit.spec.ts @@ -15,14 +15,12 @@ import { defaultReport, reportsSummary, sizeBreakdown } from '../src/tsdown/repo import { unchangedOutputs } from '../src/tsdown/unchanged.ts' import type { Rolldown, UserConfig } from 'tsdown' import { exec } from 'tinyexec' -import { runtimeExternals } from '../src/tsdown/runtime-externals.ts' -import { selfReferencePaths } from '../src/build/tsconfig.ts' +import { runtimeExternals } from '../src/tsdown/externals.ts' import { SERVER_ROUTES_STUB, createTsconfigResolver, declarationPaths, rootTsconfig, tsconfigPaths, writeDerivedTsconfig, writeServerRoutesStub } from '../src/transpile/tsconfig.ts' import { transformCss } from '../src/transpile/stylesheets.ts' import { declarationTargets, rewriteRuntimeDeclarations } from '../src/build/aliases.ts' -import { checkMissingPaths, checkNode10DeclarationPaths, checkStaleTypesField } from '../src/build/deprecations.ts' import { checkLegacyCJSPaths, checkLegacyDeclarationPaths } from '../src/legacy/package-paths.ts' -import { importsKeyFor, publishedPackage, sourcePathsPackError, unpublishableImportsError, unpublishablePathsError } from '../src/build/package.ts' +import { checkMissingPaths, checkNode10DeclarationPaths, checkStaleTypesField, importsKeyFor, publishedPackage, selfReferencePaths, sourcePathsPackError, unpublishableImportsError, unpublishablePathsError } from '../src/build/package.ts' import { writeSourceTypes } from '../src/build/types.ts' import ts from 'typescript' import { GUIDE_SECTIONS, guide } from '../src/build/guide.ts' @@ -701,14 +699,13 @@ describe('selfReferencePaths', () => { }) describe('importModule', () => { - it('should import files in an output directory outside the module afresh for each version', async () => { + it('should import files in the output directory afresh for each version', async () => { const root = await mkdtemp(join(tmpdir(), 'module-builder-versions-')) - await mkdir(join(root, 'module')) await mkdir(join(root, 'out/runtime'), { recursive: true }) await writeFile(join(root, 'out/module.mjs'), `export { name } from './runtime/name.js'\n`) await writeFile(join(root, 'out/runtime/name.js'), `export const name = 'one'\n`) const loader = fileURLToPath(new URL('../src/build/loader.ts', import.meta.url)) - const options = JSON.stringify({ cwd: join(root, 'module'), outDir: join(root, 'out') }) + const options = JSON.stringify({ cwd: root }) const script = [ `const { importModule } = await import(${JSON.stringify(pathToFileURL(loader).href)})`, `const { writeFile } = await import('node:fs/promises')`, From e7858b6597ae28de323e17dbbc2d406ca533c0f6 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Tue, 17 Nov 2026 07:47:44 +0000 Subject: [PATCH 07/21] fix: refuse a directory entry that would replace `types.d.mts` --- docs/4.configuration.md | 2 +- src/build/build.ts | 3 +++ test/regressions.spec.ts | 7 ++++++- 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/docs/4.configuration.md b/docs/4.configuration.md index e748c809..62ba5a92 100644 --- a/docs/4.configuration.md +++ b/docs/4.configuration.md @@ -54,7 +54,7 @@ An entry is either bundled into one file, like `src/module.ts`, or transpiled fi | Option | Description | |---|---| | `input` | The entry file, relative to the module root. You can leave out the extension. | -| `name` | The output name. Defaults to `input` without `src/` and without its extension. | +| `name` | The output name. Defaults to `input` without `src/` and without its extension. It can't be `types`, as the build writes `dist/types.d.mts` itself. | The build writes each bundled entry to `dist/.mjs`, with its declarations in `dist/.d.mts`. The entries in the example above produce `dist/utils.mjs` and `dist/kit.mjs`. Add each one to the `exports` of `package.json`, as described in [Exports](/docs/guide/modules/module-builder/exports#bundled-entries). diff --git a/src/build/build.ts b/src/build/build.ts index 2c841933..36742ccc 100644 --- a/src/build/build.ts +++ b/src/build/build.ts @@ -250,6 +250,9 @@ let metaImports = 0 export async function finishBuild(plan: BuildPlan, { outputs, builder, keepOutput }: FinishBuildOptions): Promise { const { cwd, outDir, pkg } = plan const duration = Date.now() - (plan.prepared?.startedAt ?? Date.now()) + if (outputs.includes('types.mjs')) { + throw new Error(`A directory entry emits \`types.mjs\` at the root of \`${relative(cwd, outDir)}\`, whose declarations would replace the generated \`types.d.mts\`. Rename the file, or give the directory entry another \`outDir\`.`) + } const moduleFile = resolve(outDir, 'module.mjs') const meta = await readModuleMeta(moduleFile, cwd).catch(async (error) => { if (!keepOutput) { diff --git a/test/regressions.spec.ts b/test/regressions.spec.ts index a55b0b2b..4aa5a9fa 100644 --- a/test/regressions.spec.ts +++ b/test/regressions.spec.ts @@ -6,7 +6,7 @@ import { join } from 'pathe' import { exec } from 'tinyexec' import { afterAll, describe, expect, it, vi } from 'vitest' -import { analyseSources, hashGeneratedTypes } from '../src/build/build.ts' +import { analyseSources, finishBuild, hashGeneratedTypes } from '../src/build/build.ts' import type { BuildPlan } from '../src/build/build.ts' import { resolveModuleOptions, resolveOutDir } from '../src/build/options.ts' import { selfReferencePaths } from '../src/build/package.ts' @@ -55,6 +55,11 @@ describe('regressions', () => { } }) + it('should refuse a directory entry that emits `types.mjs` at the root of the output', async () => { + const plan = { cwd: '/mod', outDir: '/mod/dist' } as BuildPlan + await expect(finishBuild(plan, { outputs: ['types.mjs', 'types.d.mts'], builder: {} })).rejects.toThrow('emits `types.mjs` at the root of `dist`, whose declarations would replace the generated `types.d.mts`') + }) + it('should find literal dynamic imports with comments, template literals and options', () => { const code = [ `import(/* @vite-ignore */ './a')`, From d7047d94c103d805848b36381f6186de3067f9e6 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Tue, 17 Nov 2026 10:29:16 +0000 Subject: [PATCH 08/21] fix: remove the output when a check after the bundle fails --- src/build/build.ts | 21 ++++-- test/builder.spec.ts | 2 +- test/regressions.spec.ts | 159 --------------------------------------- 3 files changed, 16 insertions(+), 166 deletions(-) delete mode 100644 test/regressions.spec.ts diff --git a/src/build/build.ts b/src/build/build.ts index 36742ccc..e708c870 100644 --- a/src/build/build.ts +++ b/src/build/build.ts @@ -239,7 +239,7 @@ export interface FinishBuildOptions { outputs: string[] /** Versions recorded as `builder` in `module.json`, besides this package's. */ builder: Record - /** Keeps the output when the built module cannot be loaded, as a watcher goes on serving it. */ + /** Keeps the output when a step or check fails, as a watcher goes on serving it. */ keepOutput?: boolean } @@ -247,17 +247,26 @@ export interface FinishBuildOptions { let metaImports = 0 /** Writes `module.json` and `types.d.mts`, finalises declarations and runs the checks and remaining hooks. */ -export async function finishBuild(plan: BuildPlan, { outputs, builder, keepOutput }: FinishBuildOptions): Promise { +export async function finishBuild(plan: BuildPlan, { keepOutput, ...options }: FinishBuildOptions): Promise { + try { + await finish(plan, options) + } + catch (error) { + if (!keepOutput) { + await rm(plan.outDir, { recursive: true, force: true }) + } + throw error + } +} + +async function finish(plan: BuildPlan, { outputs, builder }: Omit) { const { cwd, outDir, pkg } = plan const duration = Date.now() - (plan.prepared?.startedAt ?? Date.now()) if (outputs.includes('types.mjs')) { throw new Error(`A directory entry emits \`types.mjs\` at the root of \`${relative(cwd, outDir)}\`, whose declarations would replace the generated \`types.d.mts\`. Rename the file, or give the directory entry another \`outDir\`.`) } const moduleFile = resolve(outDir, 'module.mjs') - const meta = await readModuleMeta(moduleFile, cwd).catch(async (error) => { - if (!keepOutput) { - await rm(outDir, { recursive: true, force: true }) - } + const meta = await readModuleMeta(moduleFile, cwd).catch((error) => { throw new Error(`Cannot load \`${relative(cwd, moduleFile)}\` to write \`module.json\`: ${error instanceof Error ? error.message : String(error)}`, { cause: error }) }) meta.name ||= pkg.name diff --git a/test/builder.spec.ts b/test/builder.spec.ts index 290a5c5a..8ac00a4a 100644 --- a/test/builder.spec.ts +++ b/test/builder.spec.ts @@ -217,7 +217,7 @@ describe('builder', () => { it('should refuse package `imports` that the output imports and that would not work once installed', async () => { expect(expectFailed('packageImports')).toContain(`The build output imports these \`imports\` of \`package.json\`, which would not work once installed. Pointing at TypeScript sources, which Node does not load from \`node_modules\`: \`#ext/*\` (\`./src/ext/*.ts\`).`) - expect(await read(dirs.packageImports!, 'dist/module.mjs')).toContain('"#ext/value"') + expect(exists(dirs.packageImports!, 'dist')).toBe(false) const module = await read(dirs.compose!, 'dist/module.mjs') expect(module).toContain('"#ext/value"') expect(module).toContain('through imports') diff --git a/test/regressions.spec.ts b/test/regressions.spec.ts deleted file mode 100644 index 4aa5a9fa..00000000 --- a/test/regressions.spec.ts +++ /dev/null @@ -1,159 +0,0 @@ -import { existsSync } from 'node:fs' -import { appendFile, mkdir, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { consola } from 'consola' -import { join } from 'pathe' -import { exec } from 'tinyexec' -import { afterAll, describe, expect, it, vi } from 'vitest' - -import { analyseSources, finishBuild, hashGeneratedTypes } from '../src/build/build.ts' -import type { BuildPlan } from '../src/build/build.ts' -import { resolveModuleOptions, resolveOutDir } from '../src/build/options.ts' -import { selfReferencePaths } from '../src/build/package.ts' -import { resolveCwdArg } from '../src/commands/_shared.ts' -import { translateBuildConfig } from '../src/legacy/build-config.ts' -import { checkLegacyCJSPaths } from '../src/legacy/package-paths.ts' -import { moduleSpecifiers, valueSpecifiers } from '../src/transpile/specifiers.ts' -import { relativeSpecifier } from '../src/utils.ts' -import { copyExample, repoRoot } from './utils.ts' - -const temp: string[] = [] -const tempDir = async () => { - const dir = await mkdtemp(join(tmpdir(), 'module-builder-regressions-')) - temp.push(dir) - return dir -} - -afterAll(async () => { - await Promise.all(temp.map(dir => rm(dir, { recursive: true, force: true }))) -}) - -describe('regressions', () => { - it('should resolve a module root reached through a symlink to its real path', async () => { - const dir = await tempDir() - await mkdir(join(dir, 'real')) - await symlink(join(dir, 'real'), join(dir, 'link')) - expect(resolveCwdArg({ rootDir: join(dir, 'link') })).toBe(resolveCwdArg({ rootDir: join(dir, 'real') })) - expect(resolveCwdArg({ cwd: join(dir, 'missing') })).toBe(join(dir, 'missing')) - }) - - it('should change the declaration cache key with the nearest lockfile', async () => { - const dir = await tempDir() - await mkdir(join(dir, 'module/.nuxt'), { recursive: true }) - await writeFile(join(dir, 'module/.nuxt/tsconfig.json'), '{}') - await writeFile(join(dir, 'pnpm-lock.yaml'), 'lockfileVersion: 9\n') - const before = await hashGeneratedTypes(join(dir, 'module')) - expect(await hashGeneratedTypes(join(dir, 'module'))).toBe(before) - await writeFile(join(dir, 'pnpm-lock.yaml'), 'lockfileVersion: 9\npackages: {}\n') - expect(await hashGeneratedTypes(join(dir, 'module'))).not.toBe(before) - }) - - it('should refuse a bundled entry named `types`', () => { - const cwd = join(repoRoot, 'example') - for (const entries of [[{ input: './src/utils', name: 'types' }], ['./src/types']]) { - expect(() => resolveModuleOptions(cwd, {}, join(cwd, 'dist'), { entries })).toThrow('named `types`, whose declarations would replace the generated `types.d.mts`') - } - }) - - it('should refuse a directory entry that emits `types.mjs` at the root of the output', async () => { - const plan = { cwd: '/mod', outDir: '/mod/dist' } as BuildPlan - await expect(finishBuild(plan, { outputs: ['types.mjs', 'types.d.mts'], builder: {} })).rejects.toThrow('emits `types.mjs` at the root of `dist`, whose declarations would replace the generated `types.d.mts`') - }) - - it('should find literal dynamic imports with comments, template literals and options', () => { - const code = [ - `import(/* @vite-ignore */ './a')`, - 'import(`./b`)', - `import('./c', { with: { type: 'json' } })`, - 'import(`./${name}`)', - ].join('\n') - expect(moduleSpecifiers(code).map(({ specifier }) => specifier)).toEqual(['./a', './b', './c']) - expect([...valueSpecifiers(code)]).toEqual(['./a', './b', './c']) - }) - - it('should refuse an output directory outside the module', () => { - for (const outDir of ['../sibling', '/elsewhere/dist', '.']) { - expect(() => resolveOutDir('/repo/mod', outDir)).toThrow('which is not inside the module root') - } - expect(resolveOutDir('/repo/mod', '..dist')).toBe('/repo/mod/..dist') - }) - - it('should map a self-referencing subpath to the input of the entry with that name', () => { - const pkg = { name: 'my-module', exports: { './vite': './dist/vite.mjs', './utils': './dist/utils.mjs' } } - expect(selfReferencePaths('/mod', pkg, '/mod/dist', { module: './src/module.ts', vite: './src/lib/vite.ts' })).toEqual({ - 'my-module': ['/mod/src/module'], - 'my-module/vite': ['/mod/src/lib/vite'], - 'my-module/utils': ['/mod/src/utils'], - }) - }) - - it('should treat a dot-prefixed name as a path inside the directory', () => { - expect(relativeSpecifier('/mod/src/module.ts', '/mod/src/.generated/types.ts')).toBe('./.generated/types.ts') - expect(relativeSpecifier('/mod/src/module.ts', '/mod/shared.ts')).toBe('../shared.ts') - }) - - it('should let the first config set every replace option', () => { - const cwd = join(repoRoot, 'example') - const translate = (...configs: unknown[]) => translateBuildConfig(configs.map((config, index) => ({ name: `config${index}`, config })), { cwd, outDir: join(cwd, 'dist') }).replace - expect(translate( - { rollup: { replace: { values: { A: 'a' }, preventAssignment: false, objectGuards: true } } }, - { rollup: { replace: { preventAssignment: true, objectGuards: false } } }, - )).toEqual({ values: { A: 'a' }, preventAssignment: false, objectGuards: true }) - expect(translate({ replace: { A: 'a' } })).toEqual({ values: { A: 'a' }, preventAssignment: true }) - }) - - it('should only advise about `module.cjs` itself', () => { - const warn = vi.spyOn(consola, 'warn').mockImplementation(() => {}) - expect(checkLegacyCJSPaths(repoRoot, { main: './dist/submodule.cjs' })).toBe(false) - expect(checkLegacyCJSPaths(repoRoot, { main: './dist/module.cjs' })).toBe(true) - warn.mockRestore() - }) - - 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 }) - await writeFile(join(cwd, 'src/module.ts'), 'export default {}\n') - await writeFile(join(cwd, 'src/runtime/server/types.d.ts'), `export { default } from '../Button'\n`) - await writeFile(join(cwd, 'src/runtime/server/handler.ts'), `export default 'handler'\n`) - await writeFile(join(cwd, 'src/runtime/Button.tsx'), `export default () =>