Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion docs/4.configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand All @@ -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).

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
10 changes: 5 additions & 5 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion pnpm-workspace.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,4 @@ minimumReleaseAgeExclude:
- '@nuxt/*'
- vue
- '@vue/*'
- vue-sfc-transformer@0.3.5
- vue-sfc-transformer@0.3.6
2 changes: 1 addition & 1 deletion src/diagnostics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
},
Expand Down
4 changes: 3 additions & 1 deletion src/transpile/typescript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down Expand Up @@ -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<typeof import('typescript')>
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
}

/**
Expand Down
7 changes: 5 additions & 2 deletions src/transpile/vue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -48,8 +49,9 @@ export async function createDeclarationSession(): Promise<VueDeclarationSession>

/**
* 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<VueDeclarations> {
const { emitVueDeclarations, isDeclarationEmitDiagnostic } = await import('vue-sfc-transformer/core')
Expand All @@ -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 {
Expand Down
19 changes: 13 additions & 6 deletions src/tsdown/dts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Omit<Extract<NonNullable<Extract<UserConfig['dts'], object>['generator']>, object>, 'addFile'>>
Expand All @@ -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
Expand Down Expand Up @@ -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<string, unknown>, 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,
Expand Down
57 changes: 46 additions & 11 deletions test/engines.spec.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -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<string, string>, 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)))
Expand Down Expand Up @@ -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: {
Expand Down Expand Up @@ -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 }))),
Expand Down Expand Up @@ -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)/)
})
Expand Down
Loading