From ea3b74d232595c3b5e24f8ba2efdd3ca2f22794e Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Sun, 22 Nov 2026 23:47:05 +0000 Subject: [PATCH] fix: run vue and dts declarations on the builder's typescript --- docs/4.configuration.md | 4 ++- package.json | 2 +- pnpm-lock.yaml | 10 +++---- pnpm-workspace.yaml | 2 +- src/diagnostics.ts | 2 +- src/transpile/typescript.ts | 4 ++- src/transpile/vue.ts | 7 +++-- src/tsdown/dts.ts | 19 +++++++++---- test/engines.spec.ts | 57 ++++++++++++++++++++++++++++++------- 9 files changed, 78 insertions(+), 29 deletions(-) diff --git a/docs/4.configuration.md b/docs/4.configuration.md index 52369111..197cdcf3 100644 --- a/docs/4.configuration.md +++ b/docs/4.configuration.md @@ -157,6 +157,8 @@ The build generates the declarations of TypeScript sources (the bundled entries, 3. tsrs, oxc's Rust port of TypeScript 7.1. 4. Otherwise, the JavaScript API of the module's own TypeScript 5.9 or 6. +Installing one of these packages selects it, unless `declarations.engine` or `NUXT_MODULE_BUILDER_DECLARATION_ENGINE` selects another (see [Selecting an engine](#selecting-an-engine)). + The native compilers are several times faster, and run in one process for the whole build, which `tsdown --watch` keeps between rebuilds. As the module's own `typescript` stays on 5.9 or 6 for `vue-tsc`, install TypeScript 7 next to it, under an alias that only the TypeScript team can publish: ```bash [Terminal] @@ -169,7 +171,7 @@ To make TypeScript 7 the module's `tsc` too, install `@typescript/typescript6` a pnpm add -D typescript@npm:@typescript/typescript6 @typescript/typescript7@npm:typescript@beta ``` -The build checks that the package it finds is `typescript` 7.1 or later before it runs anything from it. Declarations of `.vue` files always come from `@vue/language-core`, the tooling that `vue-tsc` uses. +The build checks that the package it finds is `typescript` 7.1 or later before it runs anything from it. Declarations of `.vue` files, and of the scripts in a directory entry that has them, always come from `@vue/language-core`, the tooling that `vue-tsc` uses, with the JavaScript API of TypeScript that the build uses: the module's own `typescript` 5.9 or 6, or else `@typescript/typescript6`. TypeScript 7 prints some types differently from TypeScript 6, such as string literal types with the quotes of the source, and reports some declaration errors with other codes, such as TS2883 instead of TS2742. They fail the build in the same way. See [Declarations](/docs/api/module-builder/typescript#declarations). diff --git a/package.json b/package.json index 371073d7..beca8f7f 100644 --- a/package.json +++ b/package.json @@ -65,7 +65,7 @@ "nostics": "^1.4.0", "pathe": "^2.0.3", "tinyglobby": "^0.2.17", - "vue-sfc-transformer": "^0.3.5" + "vue-sfc-transformer": "^0.3.6" }, "peerDependencies": { "@nuxt/cli": "^3.37.0 || ^4.0.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 0c424742..dc76d48a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -203,8 +203,8 @@ importers: specifier: ^0.2.17 version: 0.2.17 vue-sfc-transformer: - specifier: ^0.3.5 - version: 0.3.5(@volar/typescript@2.4.30(typescript@6.0.3))(@vue/compiler-core@3.5.45)(@vue/language-core@3.3.14)(esbuild@0.28.2)(rolldown@1.2.19)(typescript@6.0.3)(vue@3.5.45(typescript@6.0.3)) + specifier: ^0.3.6 + version: 0.3.6(@volar/typescript@2.4.30(typescript@6.0.3))(@vue/compiler-core@3.5.45)(@vue/language-core@3.3.14)(esbuild@0.28.2)(rolldown@1.2.19)(typescript@6.0.3)(vue@3.5.45(typescript@6.0.3)) devDependencies: '@arethetypeswrong/cli': specifier: ^0.18.5 @@ -5330,8 +5330,8 @@ packages: vite: optional: true - vue-sfc-transformer@0.3.5: - resolution: {integrity: sha512-bdobiOcFNETn0VIO5JagLfC/DwUdk35MkJHU6s0v4ycW5b5W7ke6HWrlimhDpSv9RMu+F3H93ZdkwBtKJGIHJg==} + vue-sfc-transformer@0.3.6: + resolution: {integrity: sha512-xugkDM5IgnKvFg/dB0nlQUqebtYxHWQSfD7UCnQLFYrK7lglDf1eiEtK2XTF3WZkXA9ZzVVBe8+b6/eNHMbqGg==} engines: {node: '>=18.0.0'} peerDependencies: '@volar/typescript': ^2.4.0 @@ -10582,7 +10582,7 @@ snapshots: - unloader - webpack - vue-sfc-transformer@0.3.5(@volar/typescript@2.4.30(typescript@6.0.3))(@vue/compiler-core@3.5.45)(@vue/language-core@3.3.14)(esbuild@0.28.2)(rolldown@1.2.19)(typescript@6.0.3)(vue@3.5.45(typescript@6.0.3)): + vue-sfc-transformer@0.3.6(@volar/typescript@2.4.30(typescript@6.0.3))(@vue/compiler-core@3.5.45)(@vue/language-core@3.3.14)(esbuild@0.28.2)(rolldown@1.2.19)(typescript@6.0.3)(vue@3.5.45(typescript@6.0.3)): dependencies: '@vue/compiler-core': 3.5.45 tinyglobby: 0.2.17 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 85b0bfae..a3998be3 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -24,4 +24,4 @@ minimumReleaseAgeExclude: - '@nuxt/*' - vue - '@vue/*' - - vue-sfc-transformer@0.3.5 + - vue-sfc-transformer@0.3.6 diff --git a/src/diagnostics.ts b/src/diagnostics.ts index dac60779..d523273d 100644 --- a/src/diagnostics.ts +++ b/src/diagnostics.ts @@ -77,7 +77,7 @@ export const errorCodes = { docs: '#bundled-packages', }, NUXT_MB_B0005: { - why: (p: { found?: string, fallback?: string }): string => `\`@nuxt/module-builder\` uses the JavaScript API of TypeScript, from the module's \`typescript\` (\`${pkg.peerDependencies.typescript}\`) or else from \`@typescript/typescript6\`. ${p.found ? `The module has \`${p.found}\`, which has no JavaScript API` : 'The module has no `typescript`'}, and ${p.fallback ? `\`@typescript/typescript6\` resolves to \`${p.fallback}\`, which is not \`@typescript/typescript6@^6.0.0\`` : '`@typescript/typescript6` is not installed'}.`, + why: (p: { found?: string, fallback?: string }): string => `\`@nuxt/module-builder\` uses the JavaScript API of TypeScript, from the module's \`typescript\` (\`${pkg.peerDependencies.typescript}\`) or else from \`@typescript/typescript6\`. ${p.found ? `\`typescript\` resolves to \`${p.found}\`, which has no JavaScript API` : 'The module has no `typescript`'}, and ${p.fallback ? `\`@typescript/typescript6\` resolves to \`${p.fallback}\`, which is not \`@typescript/typescript6@^6.0.0\`` : '`@typescript/typescript6` is not installed'}.`, fix: (p: { install: string }): string => `Install the JavaScript API of TypeScript 6 next to TypeScript 7 with \`${p.install}\`, or install TypeScript 6 as the module's \`typescript\` with \`pnpm add -D typescript@^6.0.0\`.`, docs: false, }, diff --git a/src/transpile/typescript.ts b/src/transpile/typescript.ts index 54b057df..066ed998 100644 --- a/src/transpile/typescript.ts +++ b/src/transpile/typescript.ts @@ -17,6 +17,8 @@ export interface TypescriptApi { version: string /** The file the API is loaded from. */ file: string + /** The directory of the package the API is loaded from. */ + dir: string } /** Why neither `typescript` nor `@typescript/typescript6` provides the JavaScript API of TypeScript 6. */ @@ -57,7 +59,7 @@ function withApi({ base, installedAs, version }: InstalledPackage): TypescriptAp const require = createRequire(join(base, 'index.js')) const file = normalize(require.resolve(installedAs)) const ts = require(file) as Partial - return typeof ts.createProgram === 'function' ? { ts: ts as typeof import('typescript'), version, file } : undefined + return typeof ts.createProgram === 'function' ? { ts: ts as typeof import('typescript'), version, file, dir: join(base, 'node_modules', installedAs) } : undefined } /** diff --git a/src/transpile/vue.ts b/src/transpile/vue.ts index 28143f35..4c4940bd 100644 --- a/src/transpile/vue.ts +++ b/src/transpile/vue.ts @@ -3,6 +3,7 @@ import { relative } from 'pathe' import type { DeclarationDiagnostic, Transform, VueDeclarationSession } from 'vue-sfc-transformer/core' import type { TypeResolutionFs } from './tsconfig.ts' +import { loadTypescript } from './typescript.ts' interface VueDeclarationOptions { cwd: string @@ -48,8 +49,9 @@ export async function createDeclarationSession(): Promise /** * Emits declarations for `.vue` files and TypeScript sources from one program over - * `tsconfig`, so scripts can import types from single-file components. The program doesn't type - * check: only syntax and declaration emit errors are reported. + * `tsconfig`, so scripts can import types from single-file components, with the TypeScript of + * `loadTypescript`. The program doesn't type check: only syntax and declaration emit errors are + * reported. */ export async function emitDeclarations(files: string[], options: VueDeclarationOptions): Promise { const { emitVueDeclarations, isDeclarationEmitDiagnostic } = await import('vue-sfc-transformer/core') @@ -61,6 +63,7 @@ export async function emitDeclarations(files: string[], options: VueDeclarationO emitLegacyDeclarationAlias: true, session: options.session, typeCheck: false, + typescript: loadTypescript().ts, }) const format = (diagnostic: DeclarationDiagnostic): DeclarationMessage => ({ file: diagnostic.file, message: formatDiagnostic(diagnostic, options.cwd) }) return { diff --git a/src/tsdown/dts.ts b/src/tsdown/dts.ts index 0fe81381..62feb015 100644 --- a/src/tsdown/dts.ts +++ b/src/tsdown/dts.ts @@ -12,7 +12,7 @@ import { createDeclarationProgram, declarationError, restoreImports } from '../t import type { DeclarationProgram } from '../transpile/declarations.ts' import type { DeclarationEngine } from '../transpile/engine.ts' import { loadTypescript } from '../transpile/typescript.ts' -import { DECLARATION_RE, resolveFrom } from '../utils.ts' +import { DECLARATION_RE } from '../utils.ts' /** The `Generator` interface of rolldown-plugin-dts. */ export type DeclarationGenerator = Required['generator']>, object>, 'addFile'>> @@ -34,15 +34,22 @@ export interface EntryDeclarationOptions { type Request = { type: 'emit', file: string } | { type: 'invalidate', file: string } | { type: 'inputs' } -type WorkerModules = Record<'dts' | 'tsc' | 'context' | 'typescript', string> +type WorkerModules = Record<'dts' | 'tsc' | 'context' | 'typescript' | 'typescriptDir', string> // Every file of the tsconfig is passed as `entries`, resolved as the program's roots are (with the // platform's separators), so that one program has them all as roots and // emits every declaration: ambient declarations such as `.nuxt/nuxt.d.ts` apply, and inferred types // can be named by their package. The tsconfig is read again after a file changes, as a rebuild -// rewrites it. +// rewrites it. `typescript` resolves to the JavaScript API that the builder uses, in place of the +// `typescript` that rolldown-plugin-dts resolves, which can be TypeScript 7. const WORKER = ` +import { registerHooks } from 'node:module' import { parentPort, workerData } from 'node:worker_threads' +registerHooks({ + resolve: (specifier, context, nextResolve) => specifier === 'typescript' + ? { url: workerData.typescript, shortCircuit: true } + : specifier.startsWith('typescript/') ? nextResolve(workerData.typescriptDir + specifier.slice('typescript'.length), context) : nextResolve(specifier, context), +}) const [{ resolveOptions }, { tscEmit }, { createContext, invalidateContextFile }, { default: ts }, { dirname }] = await Promise.all([import(workerData.dts), import(workerData.tsc), import(workerData.context), import(workerData.typescript), import('node:path')]) const context = createContext() let base @@ -177,20 +184,20 @@ function workerModules(): WorkerModules { tsc: pathToFileURL(require.resolve('rolldown-plugin-dts/tsc')).href, context: pathToFileURL(require.resolve('rolldown-plugin-dts/tsc-context')).href, typescript: pathToFileURL(loadTypescript().file).href, + typescriptDir: pathToFileURL(loadTypescript().dir).href, } } /** What the declarations depend on besides the files the program reads. */ async function cacheKey(modules: WorkerModules, dtsOptions: Record, cacheVersion: string) { const { resolveOptions } = await import(modules.dts) as { resolveOptions: (options: object) => { tsconfig?: string, tsconfigRaw: unknown, sourcemap: boolean } } - // The `tsc` generator needs the JavaScript API of the `typescript` rolldown-plugin-dts resolves, and the options read here do not depend on the generator. + // The `tsc` generator loads TypeScript, and the options read here do not depend on the generator. const resolved = resolveOptions({ ...dtsOptions, generator: 'oxc' }) const require = createRequire(new URL(modules.dts)) - const emitter = resolveFrom(new URL(modules.dts), 'typescript/package.json') return { builder: builderPkg.version, dts: (require('rolldown-plugin-dts/package.json') as { version: string }).version, - typescript: emitter ? (require(emitter) as { version: string }).version : loadTypescript().version, + typescript: loadTypescript().version, tsconfig: resolved.tsconfig, tsconfigRaw: resolved.tsconfigRaw, sourcemap: resolved.sourcemap, diff --git a/test/engines.spec.ts b/test/engines.spec.ts index 92100833..438360e4 100644 --- a/test/engines.spec.ts +++ b/test/engines.spec.ts @@ -1,5 +1,6 @@ import { realpathSync } from 'node:fs' -import { cp, mkdir, readFile, rm, symlink, writeFile } from 'node:fs/promises' +import { cp, mkdir, readdir, readFile, rm, symlink, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' import { pathToFileURL } from 'node:url' import { join } from 'pathe' import { beforeAll, describe, expect, it } from 'vitest' @@ -46,20 +47,36 @@ const PORTABILITY_LINKS = { 'node_modules/fake-shared': store('fake-shared'), } -async function ownTypescript7Fixture() { - const dir = await fixture('.temp-engines/own-typescript7', { remove: ['src/runtime/components/TestMe.vue', 'src/runtime/components/TestMeSetup.vue'], files: EXTRA }) +/** A module with a copy of the builder and `links` to packages of the repository. With `outside`, it is moved there, out of reach of the repository's own TypeScript packages. */ +async function typescriptFixture(name: string, links: Record, outside?: string) { + let dir = await fixture(`.temp-engines/${name}`, { files: EXTRA }) + if (outside) { + await rm(outside, { recursive: true, force: true }) + await cp(dir, outside, { recursive: true }) + await rm(dir, { recursive: true }) + dir = outside + for (const entry of await readdir(join(repoRoot, 'node_modules'))) { + const children = entry.startsWith('@') ? (await readdir(join(repoRoot, 'node_modules', entry))).map(child => `${entry}/${child}`) : [entry] + for (const child of children.filter(child => !child.startsWith('.') && !/^(?:typescript|@typescript\/.*)$/.test(child) && !exists(dir, 'node_modules', child))) { + await mkdir(join(dir, 'node_modules', child, '..'), { recursive: true }) + await symlink(realpathSync(join(repoRoot, 'node_modules', child)), join(dir, 'node_modules', child)) + } + } + } const builder = join(dir, 'builder') await cp(join(repoRoot, 'src'), join(builder, 'src'), { recursive: true }) await cp(join(repoRoot, 'package.json'), join(builder, 'package.json')) await writeFile(join(dir, 'tsdown.config.ts'), `import { builder } from ${JSON.stringify(pathToFileURL(join(builder, 'src/tsdown/index.ts')).href)}\nexport default {\n plugins: [builder({ entries: ['./src/utils', './src/kit/index.ts', { input: './src/extra/', outDir: 'dist/extra' }] })],\n}\n`) - for (const [name, installed] of [['typescript', '@typescript/typescript7'], ['@typescript/typescript6', '@typescript/typescript6']]) { - await mkdir(join(dir, 'node_modules', name, '..'), { recursive: true }) - await rm(join(dir, 'node_modules', name), { recursive: true, force: true }) - await symlink(realpathSync(join(repoRoot, 'node_modules', installed!)), join(dir, 'node_modules', name)) + for (const [link, installed] of Object.entries(links)) { + await mkdir(join(dir, link, '..'), { recursive: true }) + await rm(join(dir, link), { recursive: true, force: true }) + await symlink(realpathSync(join(repoRoot, 'node_modules', installed)), join(dir, link)) } return dir } +const typescriptFrom = (dir: string) => ({ NODE_DEBUG: 'nuxt-module-builder', NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --require=${JSON.stringify(join(repoRoot, 'test/typescript-from.cjs'))}`, TYPESCRIPT_FROM: join(dir, 'package.json') }) + const declarationsOf = async (dir: string, sub: string) => { const files = (await listFiles(join(dir, sub))).filter(file => /\.d\.[cm]?ts$/.test(file)) return Object.fromEntries(await Promise.all(files.map(async file => [file, await read(dir, sub, file)] as const))) @@ -95,7 +112,9 @@ beforeAll(async () => { dirs.fallback = await fixture('.temp-engines/fallback', { config: config('tsrs'), files: EXTRA }) dirs.installed = await fixture('.temp-engines/installed', { files: EXTRA }) if (!reasons.typescript7) { - dirs.ownTypescript7 = await ownTypescript7Fixture() + dirs.ownTypescript7 = await typescriptFixture('own-typescript7', { 'node_modules/typescript': '@typescript/typescript7', 'node_modules/@typescript/typescript6': '@typescript/typescript6' }) + dirs.onlyTypescript7 = await typescriptFixture('only-typescript7', { 'node_modules/typescript': '@typescript/typescript7' }, join(realpathSync(tmpdir()), 'nuxt-module-builder-only-typescript7')) + dirs.peerTypescript7 = await typescriptFixture('peer-typescript7', { 'node_modules/@typescript/typescript7': '@typescript/typescript7', 'node_modules/@typescript/typescript6': '@typescript/typescript6', 'peers/node_modules/typescript': '@typescript/typescript7' }, join(realpathSync(tmpdir()), 'nuxt-module-builder-peer-typescript7')) } dirs.declarationMap = await fixture('.temp-engines/declaration-map', { files: { @@ -133,10 +152,10 @@ beforeAll(async () => { step('installed', cli(['prepare', dirs.installed!])), ...dirs.ownTypescript7 ? [(async () => { - const env = { NODE_DEBUG: 'nuxt-module-builder', NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --require=${JSON.stringify(join(repoRoot, 'test/typescript-from.cjs'))}`, TYPESCRIPT_FROM: join(dirs.ownTypescript7!, 'package.json') } + const env = typescriptFrom(dirs.ownTypescript7!) await step('ownTypescript7', tsdown(dirs.ownTypescript7!, [], env)) await step('ownTypescript7:prepare', run('node', [join(dirs.ownTypescript7!, 'builder/src/cli.ts'), 'prepare', dirs.ownTypescript7!], { env })) - })()] + })(), step('onlyTypescript7', tsdown(dirs.onlyTypescript7!, [], typescriptFrom(dirs.onlyTypescript7!))), step('peerTypescript7', tsdown(dirs.peerTypescript7!, [], { ...typescriptFrom(join(dirs.peerTypescript7!, 'peers')), NUXT_MODULE_BUILDER_DECLARATION_ENGINE: 'typescript' }))] : [], step('declarationMap', tsdown(dirs.declarationMap!)), step('isolated', tsdown(dirs.isolated!)).then(() => step('isolated:prepare', cli(['prepare', dirs.isolated!]))).then(() => step('isolated:typecheck', run(bin('vue-tsc'), ['-b', '--noEmit'], { cwd: dirs.isolated }))), @@ -243,11 +262,27 @@ it.skipIf(reasons.typescript7)('should build and prepare a module whose own `typ const quotes = (text: string | undefined) => text?.replaceAll('\'', '"') const own = Object.fromEntries(Object.entries(await declarationsOf(dirs.ownTypescript7!, sub)).map(([file, text]) => [file, quotes(text)])) const typescript = await declarationsOf(dirs.typescript!, sub) - expect(Object.keys(own)).toContain(sub === 'dist' ? 'extra/math.d.mts' : 'src/runtime/plugins/plugin.d.ts') + expect(Object.keys(own)).toEqual(expect.arrayContaining(sub === 'dist' ? ['extra/math.d.mts', 'runtime/components/TestMe.vue.d.ts'] : ['src/runtime/plugins/plugin.d.ts'])) expect(own).toEqual(Object.fromEntries(Object.keys(own).map(file => [file, quotes(typescript[file])]))) } }) +it.skipIf(reasons.typescript7)('should generate declarations with `@typescript/typescript6` when every other package resolves `typescript` to TypeScript 7', async () => { + expectBuilt('peerTypescript7') + const files = ['utils.d.mts', 'kit/index.d.mts', 'extra/math.d.mts', 'runtime/components/TestMe.vue.d.ts'] + const peer = await declarationsOf(dirs.peerTypescript7!, 'dist') + const typescript = await declarationsOf(dirs.typescript!, 'dist') + expect(files.filter(file => !peer[file])).toEqual([]) + expect(Object.fromEntries(files.map(file => [file, peer[file]]))).toEqual(Object.fromEntries(files.map(file => [file, typescript[file]]))) +}) + +it.skipIf(reasons.typescript7)('should refuse a module with `.vue` files whose only `typescript` is TypeScript 7, naming it and the package to install', () => { + const output = expectFailed('onlyTypescript7') + expect(output).toMatch(/NUXT_MB_B0005\b[^\n]*`typescript` resolves to `typescript@7\.1\.[^`]+`, which has no JavaScript API, and `@typescript\/typescript6` is not installed/) + expect(output).toContain('pnpm add -D @typescript/typescript6') + expect(output).not.toContain('TypeError') +}) + it('should report an inferred type that cannot be named with TypeScript 6', () => { expect(expectFailed('typescript-portability')).toMatch(/src\/logger\.ts\(3,14\): error TS(2742|2883)/) })