From d333162d8cf44f3bba80dcd9b2ab7db55ba3903c Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Sun, 22 Nov 2026 16:58:06 +0000 Subject: [PATCH 1/7] feat: fall back to `@typescript/typescript6` for the TypeScript JavaScript API --- CONTRIBUTING.md | 2 +- knip.json | 4 +- package.json | 5 ++ pnpm-lock.yaml | 11 +++++ src/build/directives.ts | 3 +- src/build/engine.ts | 14 ++++-- src/build/loader.ts | 5 +- src/build/unchecked.ts | 3 +- src/commands/prepare.ts | 3 +- src/diagnostics.ts | 4 +- src/transpile/declarations.ts | 3 +- src/transpile/engine.ts | 7 +-- src/transpile/specifiers.ts | 6 +-- src/transpile/tsconfig.ts | 13 +++--- src/transpile/typescript.ts | 88 +++++++++++++++++++++++++++++++++++ src/tsdown/dts.ts | 8 ++-- test/engines.spec.ts | 43 ++++++++++++++++- test/typescript-from.cjs | 24 ++++++++++ test/unit.spec.ts | 50 ++++++++++++++++++-- 19 files changed, 260 insertions(+), 36 deletions(-) create mode 100644 src/transpile/typescript.ts create mode 100644 test/typescript-from.cjs diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 59afc942..ae7fb73f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -36,7 +36,7 @@ The package has three entry points: | `src/commands/` | The CLI subcommands, plus `config-file.ts`, which finds the module's tsdown config and reads the `builder()` options from it. | | `src/tsdown/` | The `builder()` plugin. `plugin.ts` creates it, and `setup.ts` turns the tsdown config into a build. It adds the plugins, hooks into tsdown's lifecycle, and handles watch mode. `externals.ts`, `unchanged.ts` and `report.ts` are the plugins and helpers that `setup.ts` uses, and `dts.ts` generates the declarations of the bundled entries. `build.ts` runs tsdown for `nuxt-module-build build`. | | `src/build/` | The build itself, independent of tsdown's plugin API:
`options.ts` resolves `builder()` options.
`build.ts` resolves a `BuildPlan` and runs the steps before and after the bundle.
`loader.ts` imports module code and checks that Node can load it.
`package.ts` holds the `package.json` checks.
`types.ts` and `module-declarations.ts` write `types.d.mts` and the declarations `prepare` generates.
`aliases.ts` rewrites `#app` in declarations.
`directives.ts` wraps the oxc transform of runtime files so that TypeScript directive comments are left out.
`unchecked.ts` finds the TypeScript files that no tsconfig the module references includes, for `prepare`'s note.
`engine.ts` loads the declaration engine that `declarations.engine` selects, with its diagnostics. | -| `src/transpile/` | `transpileDir()`, the internal rolldown plugin that transpiles a directory file by file. It transforms scripts with oxc and `.vue` files with `vue.ts`, compiles stylesheets with `stylesheets.ts`, emits declarations with `declarations.ts` (reused from `node_modules/.cache` while their inputs are unchanged, see `cache.ts`) through a declaration engine (`engine.ts` for the module's own TypeScript, `native.ts` for TypeScript 7 and tsrs), rewrites import specifiers with `specifiers.ts`, and resolves the tsconfig of each file with `tsconfig.ts`. It imports nothing outside the directory but `src/utils.ts`, so it can be extracted later. | +| `src/transpile/` | `transpileDir()`, the internal rolldown plugin that transpiles a directory file by file. It transforms scripts with oxc and `.vue` files with `vue.ts`, compiles stylesheets with `stylesheets.ts`, emits declarations with `declarations.ts` (reused from `node_modules/.cache` while their inputs are unchanged, see `cache.ts`) through a declaration engine (`engine.ts` for the module's own TypeScript, `native.ts` for TypeScript 7 and tsrs), rewrites import specifiers with `specifiers.ts`, resolves the tsconfig of each file with `tsconfig.ts`, and loads the JavaScript API of TypeScript that the whole package uses with `typescript.ts` (the module's own `typescript` when it has one, or else `@typescript/typescript6`). It imports nothing outside the directory but `src/utils.ts`, so it can be extracted later. | | `src/legacy/` | Compatibility with v1 and unbuild (see [Legacy code](#legacy-code)). | | `src/diagnostics.ts` | The codes of every error and warning the builder reports (see [Diagnostics](#diagnostics)). | | `src/utils.ts` | Path, file and regex helpers shared across directories, and `logger`, which prints diagnostics outside a tsdown build. | diff --git a/knip.json b/knip.json index fed466aa..3773f17d 100644 --- a/knip.json +++ b/knip.json @@ -1,9 +1,11 @@ { "$schema": "https://unpkg.com/knip@5/schema.json", "ignore": [ - "test/__snapshots__/**" + "test/__snapshots__/**", + "test/typescript-from.cjs" ], "ignoreDependencies": [ + "@typescript/typescript6", "@typescript/typescript7", "rolldown-plugin-dts", "tsrs" diff --git a/package.json b/package.json index 8a80944c..c61b73ef 100644 --- a/package.json +++ b/package.json @@ -69,12 +69,16 @@ }, "peerDependencies": { "@nuxt/cli": "^3.37.0 || ^4.0.0", + "@typescript/typescript6": "^6.0.0", "@typescript/typescript7": "npm:typescript@>=7.1.0-beta", "tsdown": "^0.23.7", "tsrs": ">=7.1.0-beta.tsrs3", "typescript": "^5.9.3 || ^6.0.0" }, "peerDependenciesMeta": { + "@typescript/typescript6": { + "optional": true + }, "@typescript/typescript7": { "optional": true }, @@ -89,6 +93,7 @@ "@nuxt/eslint-config": "^1.17.0", "@nuxt/schema": "~4.6.4", "@types/node": "^26.6.6", + "@typescript/typescript6": "6.0.2", "@typescript/typescript7": "npm:typescript@7.1.0-beta", "@vitest/coverage-v8": "^5.1.0", "eslint": "^10.14.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 2c207f25..144547f6 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -224,6 +224,9 @@ importers: '@types/node': specifier: ^26.6.6 version: 26.6.6 + '@typescript/typescript6': + specifier: 6.0.2 + version: 6.0.2 '@typescript/typescript7': specifier: npm:typescript@7.1.0-beta version: typescript@7.1.0-beta @@ -2061,6 +2064,10 @@ packages: cpu: [x64] os: [win32] + '@typescript/typescript6@6.0.2': + resolution: {integrity: sha512-mbCddXd+jm7hfx7w2YU64/Av4/NqqeG3GoRZgxPcgoTxYjhrcfJRw9ULch71SS4G+Q3bOXFhRvPqjguN0Hyp5w==} + hasBin: true + '@unhead/bundler@3.4.3': resolution: {integrity: sha512-noUTzazRB4fMgO/nluoirrZJXngNbNb3sQzIslA805tKkwakRv2fib4Xe4EdiTuNB7V5XmpUFvfQkKRdBQ9qAA==} peerDependencies: @@ -7141,6 +7148,10 @@ snapshots: '@typescript/typescript-win32-x64@7.1.0-beta': optional: true + '@typescript/typescript6@6.0.2': + dependencies: + '@typescript/old': typescript@6.0.3 + '@unhead/bundler@3.4.3(@oxc-project/types@0.157.0)(esbuild@0.28.2)(lightningcss@1.33.0)(oxc-parser@0.156.0)(rolldown@1.2.18)(rollup@4.68.2)(unhead@3.4.3(esbuild@0.28.2)(rolldown@1.2.18)(rollup@4.68.2)(vite@8.3.7(@types/node@26.6.6)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.1)(terser@5.51.2)(yaml@2.9.1)))(vite@8.3.7(@types/node@26.6.6)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.1)(terser@5.51.2)(yaml@2.9.1))': dependencies: magic-string: 1.4.5 diff --git a/src/build/directives.ts b/src/build/directives.ts index c260b273..1435d958 100644 --- a/src/build/directives.ts +++ b/src/build/directives.ts @@ -1,6 +1,7 @@ import type ts from 'typescript' import type { Transform } from '../transpile/transpile-dir.ts' +import { loadTypescript } from '../transpile/typescript.ts' const DIRECTIVE_RE = /@ts-(?:expect-error|ignore|nocheck|check)\b/g const LINE_DIRECTIVE_RE = /^\/\/\/?[\t ]*@ts-(?:expect-error|ignore|nocheck|check)\b/ @@ -20,7 +21,7 @@ export function withoutDirectiveComments(transform: Transform): Transform { } async function blankDirectiveComments(source: string, lang: string) { - const { default: ts } = await import('typescript') + const { ts } = loadTypescript() const sourceFile = ts.createSourceFile(`source.${lang}`, source, ts.ScriptTarget.Latest, false, ts.ScriptKind[SCRIPT_KINDS[lang] ?? 'TS']) const comments = new Map() for (const { index } of source.matchAll(DIRECTIVE_RE)) { diff --git a/src/build/engine.ts b/src/build/engine.ts index bc324ffa..c7e68842 100644 --- a/src/build/engine.ts +++ b/src/build/engine.ts @@ -3,6 +3,7 @@ import { ENGINES } from '../transpile/engine.ts' import type { DeclarationEngine, DeclarationEngineName } from '../transpile/engine.ts' import { createNativeEngine, hasNativeTypescript, installedNativeEngine, NativeEngineError } from '../transpile/native.ts' import type { NativeEngineName } from '../transpile/native.ts' +import { loadTypescript, TYPESCRIPT6, TypescriptApiError } from '../transpile/typescript.ts' import { isDeclarationEngine } from './options.ts' import type { ModuleConfig } from './options.ts' @@ -26,11 +27,16 @@ function selectedEngine(config: Pick): { engi return config.declarationEngine && { engine: config.declarationEngine, setting: '`declarations.engine`' } } -/** Fails when the module's own `typescript` has no JavaScript API, as TypeScript 7 has none. */ +/** Fails when neither the module's own `typescript` nor `@typescript/typescript6` has the JavaScript API of TypeScript 6, see `loadTypescript`. */ export async function assertSupportedTypescript(): Promise { - const ts = (await import('typescript')).default as Partial & { version: string } - if (typeof ts.createProgram !== 'function') { - throw errors.NUXT_MB_B0005({ version: ts.version, install: INSTALL[ENGINES.typescript7] }) + try { + loadTypescript() + } + catch (error) { + if (error instanceof TypescriptApiError) { + throw errors.NUXT_MB_B0005({ found: error.found, fallback: error.fallback, install: `pnpm add -D ${TYPESCRIPT6}` }) + } + throw error } } diff --git a/src/build/loader.ts b/src/build/loader.ts index ab774180..56714a83 100644 --- a/src/build/loader.ts +++ b/src/build/loader.ts @@ -8,6 +8,7 @@ import type ts from 'typescript' import type { Transform } from '../transpile/transpile-dir.ts' import { packageName } from '../transpile/tsconfig.ts' +import { loadTypescript } from '../transpile/typescript.ts' import { findPackageDir, findUp, isFile, isInside, isPlainObject, NODE_MODULES_RE, probe, relativeSpecifier, resolveFrom, SCRIPT_RE, TYPESCRIPT_RE } from '../utils.ts' import type { PackageJson } from '../utils.ts' import { errors } from '../diagnostics.ts' @@ -319,8 +320,6 @@ function importTarget(target: unknown, match: string | undefined): string | unde } } -let typescript: typeof ts | undefined - function scriptKind(ts: typeof import('typescript'), filename: string) { if (TYPESCRIPT_RE.test(filename)) { return filename.endsWith('x') ? ts.ScriptKind.TSX : ts.ScriptKind.TS @@ -344,7 +343,7 @@ function hasRuntimeCode(ts: typeof import('typescript'), node: ts.ModuleDeclarat } function analyseSource(filename: string, source: string): SourceAnalysis { - const ts = typescript ??= createRequire(import.meta.url)('typescript') as typeof import('typescript') + const { ts } = loadTypescript() const { SyntaxKind } = ts const sourceFile = ts.createSourceFile(filename, source, ts.ScriptTarget.Latest, true, scriptKind(ts, filename)) const found: SourceAnalysis = { nonErasable: [], imports: [] } diff --git a/src/build/unchecked.ts b/src/build/unchecked.ts index 96720159..8b88fa8f 100644 --- a/src/build/unchecked.ts +++ b/src/build/unchecked.ts @@ -4,6 +4,7 @@ import { glob } from 'tinyglobby' import { warnings } from '../diagnostics.ts' import type { TsconfigResolver } from '../transpile/tsconfig.ts' +import { loadTypescript } from '../transpile/typescript.ts' import { moduleTsconfigs } from './build.ts' const NUXT_BUILD_DIR_RE = /[\\/]\.nuxt(?:[\\/]|$)/ @@ -30,7 +31,7 @@ async function uncheckedFiles(cwd: string, tsconfigs: TsconfigResolver, { outDir if (!root?.config.references?.length || tsconfigs.replaced) { return groups } - const { default: ts } = await import('typescript') + const { ts } = loadTypescript() const ownExcludes = root.config.references.flatMap(({ path }) => { const file = resolve(dirname(root.path), path) const config = file.endsWith('.json') ? file : join(file, 'tsconfig.json') diff --git a/src/commands/prepare.ts b/src/commands/prepare.ts index 4fca71bf..f5248739 100644 --- a/src/commands/prepare.ts +++ b/src/commands/prepare.ts @@ -17,6 +17,7 @@ import { augmentsNuxtTypes, writeSourceTypes } from '../build/types.ts' import { noteUncheckedFiles } from '../build/unchecked.ts' import { loadBuildConfig } from '../legacy/build-config.ts' import { hasIsolatedDeclarations, isModuleFile, rootTsconfig, writeDependencyImports } from '../transpile/tsconfig.ts' +import { loadTypescript } from '../transpile/typescript.ts' import { isInside, probe, readPackageJson, resolveFrom } from '../utils.ts' import type { PackageJson } from '../utils.ts' import { assertNoStubArg, resolveCwdArg, sharedArgs } from './_shared.ts' @@ -55,7 +56,7 @@ async function declaresModules(cwd: string, runtimeDirs: string[], entries: stri } async function ambientDeclarations(cwd: string, runtimeDirs: string[], exclude: string[]) { - const { default: ts } = await import('typescript') + const { ts } = loadTypescript() const ignore = [...runtimeDirs, ...exclude].flatMap((pattern) => { const path = relative(cwd, pattern) return [path, `${path}/**`] diff --git a/src/diagnostics.ts b/src/diagnostics.ts index ea744370..b8c10864 100644 --- a/src/diagnostics.ts +++ b/src/diagnostics.ts @@ -73,8 +73,8 @@ export const errorCodes = { docs: '#bundled-packages', }, NUXT_MB_B0005: { - why: (p: { version: string }): string => `\`@nuxt/module-builder\` uses the JavaScript API of the module's \`typescript\`, which needs \`${pkg.peerDependencies.typescript}\`, and the module has \`typescript@${p.version}\`, which has no JavaScript API.`, - fix: (p: { install: string }): string => `Install TypeScript 6 as the module's \`typescript\` with \`pnpm add -D typescript@^6.0.0\`. To generate declarations with TypeScript 7, install it next to TypeScript 6 with \`${p.install}\`.`, + 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'}.`, + 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/declarations.ts b/src/transpile/declarations.ts index 01727fba..56a5d783 100644 --- a/src/transpile/declarations.ts +++ b/src/transpile/declarations.ts @@ -7,6 +7,7 @@ import { contentCache } from './cache.ts' import { createTscEngine } from './engine.ts' import type { DeclarationEngine, DeclarationProject, EngineDiagnostic, ProjectOptions, SourceFileCache } from './engine.ts' import { isModuleFile, writeDeclarationPaths } from './tsconfig.ts' +import { loadTypescript } from './typescript.ts' export type { SourceFileCache } from './engine.ts' @@ -173,7 +174,7 @@ const SFC_SCRIPT_RE = /"']|"[^"]*"|'[^']*')*>([\s\S]*?)<\/script\ * the module resolves the alias. */ export async function restoreImports(declaration: string, source: string, code: string): Promise { - const { default: ts } = await import('typescript') + const { ts } = loadTypescript() const script = source.endsWith('.vue') ? [...code.matchAll(SFC_SCRIPT_RE)].map(([, content]) => content).join('\n') : code const emitted = ts.createSourceFile('declaration.d.ts', declaration, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS) const referenced: Array<[name: string, node: ts.Node]> = [] diff --git a/src/transpile/engine.ts b/src/transpile/engine.ts index 2907d4ee..8c66fafc 100644 --- a/src/transpile/engine.ts +++ b/src/transpile/engine.ts @@ -1,6 +1,7 @@ -import { createRequire } from 'node:module' import type ts from 'typescript' +import { loadTypescript } from './typescript.ts' + /** The values of `declarations.engine`. */ export const ENGINES = { /** The module's own `typescript`: its JavaScript API up to 6, its native API from 7.1. */ @@ -92,10 +93,10 @@ export function createTscEngine({ sourceFiles }: TscEngineOptions = {}): TscEngi return { name: ENGINES.typescript, get version() { - return (createRequire(import.meta.url)('typescript/package.json') as { version: string }).version + return loadTypescript().version }, async open({ tsconfig, include, roots, compilerOptions }) { - const { default: ts } = await import('typescript') + const { ts } = loadTypescript() const parsed = tsconfig ? ts.getParsedCommandLineOfConfigFile(tsconfig, {}, configHost(ts)) : undefined const rootNames = [...new Set([...(parsed?.fileNames ?? []).filter(include), ...roots])] const options: ts.CompilerOptions = { ...parsed?.options, ...compilerOptions as ts.CompilerOptions } diff --git a/src/transpile/specifiers.ts b/src/transpile/specifiers.ts index f1a8abc3..83feb814 100644 --- a/src/transpile/specifiers.ts +++ b/src/transpile/specifiers.ts @@ -1,7 +1,7 @@ -import { createRequire } from 'node:module' import type ts from 'typescript' import { RELATIVE_RE } from '../utils.ts' +import { loadTypescript } from './typescript.ts' const JSX_RE = /\.[jt]sx$/ const DYNAMIC_IMPORT_RE = /\bimport\s*(?:\(|\/[*/])/ @@ -26,11 +26,9 @@ interface Reference extends Specifier { typeOnly: boolean } -let typescript: typeof import('typescript') | undefined - /** `code` parsed by TypeScript, as the language that the extension of `filename` implies. */ export function parseModule(code: string, filename: string): { ts: typeof import('typescript'), sourceFile: ts.SourceFile } { - const ts = typescript ??= createRequire(import.meta.url)('typescript') as typeof import('typescript') + const { ts } = loadTypescript() const sourceFile = ts.createSourceFile(filename, code, { languageVersion: ts.ScriptTarget.Latest, jsDocParsingMode: ts.JSDocParsingMode.ParseNone }) return { ts, sourceFile } } diff --git a/src/transpile/tsconfig.ts b/src/transpile/tsconfig.ts index 28e75f7a..5644dac3 100644 --- a/src/transpile/tsconfig.ts +++ b/src/transpile/tsconfig.ts @@ -8,6 +8,7 @@ import type ts from 'typescript' import { findPackageDir, findUp, getOrCreate, isInside, NODE_MODULES_RE } from '../utils.ts' import { moduleSpecifiers } from './specifiers.ts' +import { loadTypescript } from './typescript.ts' export interface TsconfigResolver { /** The nearest tsconfig, which may delegate files to `references`. */ @@ -64,7 +65,7 @@ const presented = new Map() * that one are hidden. */ export async function typeResolutionFs(files: string[], project: (file: string) => TsConfigResult | undefined): Promise> { - const { default: ts } = await import('typescript') + const { ts } = loadTypescript() const configs = new Map>() const owners = new Map() const result = new Map() @@ -142,7 +143,7 @@ const PATH_LIST_OPTIONS = ['rootDirs', 'typeRoots'] as const * `references` into another `.nuxt` are dropped. */ async function rebaseOnOwnBuildDir(tsconfig: string, own: string, dir: string): Promise { - const { default: ts } = await import('typescript') + const { ts } = loadTypescript() const ownConfig = parseTsconfig(own) const ownPaths = tsconfigPaths({ path: own, config: ownConfig }) const { paths, types, ...options } = (await inheritedTsconfig(tsconfig, target => isForeignBuildFile(target, dir))).compilerOptions @@ -179,7 +180,7 @@ interface InheritedTsconfig { /** The `compilerOptions` and `exclude` of `dir/tsconfig.json`, see {@link inheritedTsconfig}, apart from those of tsconfigs in a `.nuxt`, and whether it has `references`. */ export async function rootTsconfig(dir: string): Promise { - const { default: ts } = await import('typescript') + const { ts } = loadTypescript() const file = join(dir, 'tsconfig.json') const raw = ts.readConfigFile(file, ts.sys.readFile).config as RawTsconfig | undefined return { ...await inheritedTsconfig(file, target => NUXT_BUILD_DIR_RE.test(target)), references: !!raw?.references?.length } @@ -191,7 +192,7 @@ export async function rootTsconfig(dir: string): Promise { * resolve against the merged `baseUrl`, or else the directory of the tsconfig that sets them. */ async function inheritedTsconfig(file: string, skip: (file: string) => boolean): Promise { - const { default: ts } = await import('typescript') + const { ts } = loadTypescript() const configDir = dirname(file) const layer = (path: string, ancestors: string[]): InheritedTsconfig & { pathsBase?: string } => { const raw = ts.readConfigFile(path, ts.sys.readFile).config as RawTsconfig | undefined @@ -452,7 +453,7 @@ export async function writeDependencyImports(cwd: string, tsconfig: TsConfigResu if (!projects.length) { return } - const { default: ts } = await import('typescript') + const { ts } = loadTypescript() const files = new Set(projects.flatMap(project => projectFiles(parseProject(ts, project.path, true), cwd))) const sources = await Promise.all([...files].sort().map(async file => ({ file, source: await readFile(file, 'utf8').catch(() => '') }))) const specifiers = new Map() @@ -478,7 +479,7 @@ export async function writeDependencyImports(cwd: string, tsconfig: TsConfigResu * is listed in each derived tsconfig that lists files of its own. */ export async function writeDerivedTsconfig(cwd: string, tsconfig: TsConfigResult, paths: Record, { file, vue = false, imports }: { file?: string, vue?: boolean, imports?: string } = {}): Promise { - const { default: ts } = await import('typescript') + const { ts } = loadTypescript() const declaration = await writeDeclarationPaths(cwd, tsconfig, paths) const compilerOptions: Record = { paths: declaration.paths, isolatedDeclarations: false } if (declaration.ambient) { diff --git a/src/transpile/typescript.ts b/src/transpile/typescript.ts new file mode 100644 index 00000000..cbe149eb --- /dev/null +++ b/src/transpile/typescript.ts @@ -0,0 +1,88 @@ +import { existsSync, readFileSync } from 'node:fs' +import { createRequire } from 'node:module' +import { fileURLToPath } from 'node:url' +import { debuglog } from 'node:util' +import { dirname, join } from 'pathe' + +import { findUp } from '../utils.ts' + +/** The package that provides the JavaScript API of TypeScript 6 next to TypeScript 7. */ +export const TYPESCRIPT6 = '@typescript/typescript6' + +const debug = debuglog('nuxt-module-builder') + +export interface TypescriptApi { + ts: typeof import('typescript') + /** The version of the package the API is loaded from. */ + version: string + /** The file the API is loaded from. */ + file: string +} + +/** Why neither `typescript` nor `@typescript/typescript6` provides the JavaScript API of TypeScript 6. */ +export class TypescriptApiError extends Error { + /** The package and version `typescript` resolves to, such as `typescript@7.0.2`, if it is installed. */ + readonly found?: string + /** The package and version `@typescript/typescript6` resolves to, if it is installed. */ + readonly fallback?: string + constructor(found: string | undefined, fallback: string | undefined) { + super(`${found ? `\`typescript\` resolves to \`${found}\`, which has no JavaScript API` : '`typescript` is not installed'}, and ${fallback ? `\`${TYPESCRIPT6}\` resolves to \`${fallback}\`` : `\`${TYPESCRIPT6}\` is not installed`}.`) + this.found = found + this.fallback = fallback + } +} + +interface InstalledPackage { + /** The directory whose `node_modules` holds the package. */ + base: string + installedAs: string + name?: string + version: string + /** The package and version, such as `typescript@6.0.3`. */ + found: string +} + +/** The package installed as `name` in `node_modules` of `from` or a directory above it, leaving out `NODE_PATH` and global folders. */ +function installedPackage(name: string, from: string): InstalledPackage | undefined { + const base = findUp(from, dir => existsSync(join(dir, 'node_modules', name, 'package.json')) ? dir : undefined) + if (!base) { + return + } + const pkg = JSON.parse(readFileSync(join(base, 'node_modules', name, 'package.json'), 'utf8')) as { name?: string, version?: string } + const version = pkg.version ?? '' + return { base, installedAs: name, name: pkg.name, version, found: `${pkg.name ?? name}@${version}` } +} + +function withApi({ base, installedAs, version }: InstalledPackage): TypescriptApi | undefined { + const require = createRequire(join(base, 'index.js')) + const file = require.resolve(installedAs) + const ts = require(file) as Partial + return typeof ts.createProgram === 'function' ? { ts: ts as typeof import('typescript'), version, file } : undefined +} + +/** + * The JavaScript API of TypeScript that `from` resolves: `typescript` when it has one, as + * TypeScript 5.9 and 6 do, or else `@typescript/typescript6` at 6.x. Throws a + * {@link TypescriptApiError} when neither does. + */ +export function findTypescript(from: string): TypescriptApi { + const own = installedPackage('typescript', from) + const api = own && withApi(own) + if (api) { + return api + } + const fallback = installedPackage(TYPESCRIPT6, from) + const fallbackApi = fallback?.name === TYPESCRIPT6 && fallback.version.split('.')[0] === '6' ? withApi(fallback) : undefined + if (!fallbackApi) { + throw new TypescriptApiError(own?.found, fallback?.found) + } + debug('the TypeScript JavaScript API is %s, as `typescript` is %s', fallback!.found, own?.found ?? 'not installed') + return fallbackApi +} + +let loaded: TypescriptApi | undefined + +/** The JavaScript API of TypeScript that `@nuxt/module-builder` resolves, see {@link findTypescript}. */ +export function loadTypescript(): TypescriptApi { + return loaded ??= findTypescript(dirname(fileURLToPath(import.meta.url))) +} diff --git a/src/tsdown/dts.ts b/src/tsdown/dts.ts index e2b5e997..12f3d1c6 100644 --- a/src/tsdown/dts.ts +++ b/src/tsdown/dts.ts @@ -11,6 +11,7 @@ import type { ContentCache } from '../transpile/cache.ts' import { createDeclarationProgram, declarationError, restoreImports } from '../transpile/declarations.ts' import type { DeclarationProgram } from '../transpile/declarations.ts' import type { DeclarationEngine } from '../transpile/engine.ts' +import { loadTypescript } from '../transpile/typescript.ts' import { DECLARATION_RE } from '../utils.ts' /** The `Generator` interface of rolldown-plugin-dts. */ @@ -175,19 +176,20 @@ function workerModules(): WorkerModules { dts: pathToFileURL(dts).href, tsc: pathToFileURL(require.resolve('rolldown-plugin-dts/tsc')).href, context: pathToFileURL(require.resolve('rolldown-plugin-dts/tsc-context')).href, - typescript: pathToFileURL(createRequire(dts).resolve('typescript')).href, + typescript: pathToFileURL(loadTypescript().file).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 } } - const resolved = resolveOptions(dtsOptions) + // 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. + const resolved = resolveOptions({ ...dtsOptions, generator: 'oxc' }) const require = createRequire(new URL(modules.dts)) return { builder: builderPkg.version, dts: (require('rolldown-plugin-dts/package.json') as { version: string }).version, - typescript: (require('typescript/package.json') as { version: string }).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 22e46384..6882a0a8 100644 --- a/test/engines.spec.ts +++ b/test/engines.spec.ts @@ -1,4 +1,6 @@ -import { mkdir, readFile, rm, writeFile } from 'node:fs/promises' +import { realpathSync } from 'node:fs' +import { cp, mkdir, readFile, rm, symlink, writeFile } from 'node:fs/promises' +import { pathToFileURL } from 'node:url' import { join } from 'pathe' import { beforeAll, describe, expect, it } from 'vitest' @@ -44,6 +46,20 @@ 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 }) + 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)) + } + return dir +} + 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))) @@ -78,6 +94,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.declarationMap = await fixture('.temp-engines/declaration-map', { files: { 'tsconfig.module.json': JSON.stringify({ extends: './.nuxt/tsconfig.node.json', compilerOptions: { declarationMap: true } }), @@ -112,6 +131,13 @@ beforeAll(async () => { ...['typescript', ...native].map(engine => step(`${engine}-portability`, tsdown(dirs[`${engine}-portability`]!)).then(() => step(`${engine}-portability:prepare`, cli(['prepare', dirs[`${engine}-portability`]!])))), step('fallback', tsdown(dirs.fallback!, [], { TSRS_BINARY: join(dirs.fallback!, 'missing-tsrs') })), step('installed', cli(['prepare', dirs.installed!])), + ...dirs.ownTypescript7 + ? [(async () => { + const env = { NODE_DEBUG: 'nuxt-module-builder', NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --require=${join(repoRoot, 'test/typescript-from.cjs')}`, TYPESCRIPT_FROM: join(dirs.ownTypescript7!, 'package.json') } + 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('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 }))), step('isolatedMissing', tsdown(dirs.isolatedMissing!)).then(() => step('isolatedMissing:prepare', cli(['prepare', dirs.isolatedMissing!]))), @@ -207,6 +233,21 @@ it.skipIf(reasons.typescript7)('should generate declarations with the engine the expect(await read(dirs.installed!, '.nuxt/module-builder/declarations/src/runtime/plugins/plugin.d.ts')).toContain('injection: \'injected\'') }) +it.skipIf(reasons.typescript7)('should build and prepare a module whose own `typescript` is TypeScript 7.1 with `@typescript/typescript6`, generating the declarations TypeScript 6 generates with TypeScript 7', async () => { + for (const name of ['ownTypescript7', 'ownTypescript7:prepare']) { + const output = expectBuilt(name) + expect(output).toMatch(/the TypeScript JavaScript API is @typescript\/typescript6@6\.\d+\.\d+, as `typescript` is typescript@7\.1\./) + expect(output).toMatch(/the typescript declaration engine uses typescript@7\.1\.\S+, installed as typescript\n/) + } + for (const sub of ['dist', '.nuxt/module-builder/declarations']) { + const quotes = (text: string | undefined) => sub === 'dist' ? text : 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(own).toEqual(Object.fromEntries(Object.keys(own).map(file => [file, quotes(typescript[file])]))) + } +}) + 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)/) }) diff --git a/test/typescript-from.cjs b/test/typescript-from.cjs new file mode 100644 index 00000000..98dbf250 --- /dev/null +++ b/test/typescript-from.cjs @@ -0,0 +1,24 @@ +// Preloaded with `--require`, so that it also applies in worker threads: resolves `typescript` +// and its subpaths for every importer from `TYPESCRIPT_FROM`, as a module's own `typescript` is +// the one its dependencies resolve. +const { createRequire, registerHooks } = require('node:module') +const { pathToFileURL } = require('node:url') + +const resolver = createRequire(process.env.TYPESCRIPT_FROM) +const TYPESCRIPT_RE = /^typescript(?:\/|$)/ +let resolving = false + +registerHooks({ + resolve(specifier, context, nextResolve) { + if (resolving || !TYPESCRIPT_RE.test(specifier)) { + return nextResolve(specifier, context) + } + resolving = true + try { + return { url: pathToFileURL(resolver.resolve(specifier)).href, shortCircuit: true } + } + finally { + resolving = false + } + }, +}) diff --git a/test/unit.spec.ts b/test/unit.spec.ts index 66a12fc5..ff001bad 100644 --- a/test/unit.spec.ts +++ b/test/unit.spec.ts @@ -28,6 +28,7 @@ import { contentCache } from '../src/transpile/cache.ts' import { createDeclarationProgram, declarationDiagnosticClass, declarationError, REMAPPED_CODES, restoreImports } from '../src/transpile/declarations.ts' import type { DeclarationEngine } from '../src/transpile/engine.ts' import { createNativeEngine, installedNativeEngine, platformProblem } from '../src/transpile/native.ts' +import { findTypescript, loadTypescript } from '../src/transpile/typescript.ts' import { assertSupportedTypescript, loadDeclarationEngine } from '../src/build/engine.ts' import { declarationTargets, rewriteRuntimeDeclarations } from '../src/build/aliases.ts' import { checkLegacyCJSPaths, checkLegacyDeclarationPaths } from '../src/legacy/package-paths.ts' @@ -2166,16 +2167,57 @@ describe('declaration engines', () => { await expect(createNativeEngine(unspawnable, 'typescript7')).rejects.toThrow(expect.objectContaining({ reason: 'platform', message: expect.stringContaining('its binary does not start') })) }) - it('should refuse a module whose own `typescript` has no JavaScript API, and say which versions work', async () => { + const ownTypescript = (version: string) => version.startsWith('7.') + ? { + 'node_modules/typescript/package.json': JSON.stringify({ name: 'typescript', version, type: 'module', exports: { '.': './lib/version.cjs', './package.json': './package.json' } }), + 'node_modules/typescript/lib/version.cjs': `module.exports = { version: '${version}', versionMajorMinor: '${version.slice(0, 3)}' }\n`, + } + : { + 'node_modules/typescript/package.json': JSON.stringify({ name: 'typescript', version, main: './lib/typescript.js' }), + 'node_modules/typescript/lib/typescript.js': `module.exports = { version: '${version}', createProgram() {} }\n`, + } + const typescript6 = (manifest: Record, main = `module.exports = { version: '${manifest.version}', createProgram() {} }\n`) => ({ + 'node_modules/@typescript/typescript6/package.json': JSON.stringify({ main: './lib/typescript.js', ...manifest }), + 'node_modules/@typescript/typescript6/lib/typescript.js': main, + }) + + it('should load the JavaScript API of the module\'s own `typescript` when it has one', async () => { + expect(loadTypescript().ts).toBe(ts) + expect(loadTypescript().version).toBe(ts.version) + const own = await fakePackage({ ...ownTypescript('5.9.3'), ...typescript6({ name: '@typescript/typescript6', version: '6.0.2' }) }) + expect(findTypescript(own)).toMatchObject({ version: '5.9.3', file: join(own, 'node_modules/typescript/lib/typescript.js') }) + }) + + it('should load `@typescript/typescript6` when the module\'s own `typescript` has no JavaScript API', async () => { + const cwd = await fakePackage({ ...ownTypescript('7.1.0'), ...typescript6({ name: '@typescript/typescript6', version: '6.0.2' }) }) + expect(findTypescript(cwd)).toMatchObject({ version: '6.0.2', file: join(cwd, 'node_modules/@typescript/typescript6/lib/typescript.js') }) + expect(findTypescript(await fakePackage(typescript6({ name: '@typescript/typescript6', version: '6.0.2' })))).toMatchObject({ version: '6.0.2' }) + }) + + it('should not import a `@typescript/typescript6` that is another package or version', async () => { + const unused = `throw new Error('imported')\n` + const aliased = await fakePackage({ ...ownTypescript('7.1.0'), ...typescript6({ name: 'typescript', version: '6.0.3' }, unused) }) + expect(() => findTypescript(aliased)).toThrow(expect.objectContaining({ found: 'typescript@7.1.0', fallback: 'typescript@6.0.3' })) + const seven = await fakePackage({ ...ownTypescript('7.1.0'), ...typescript6({ name: '@typescript/typescript6', version: '7.0.0' }, unused) }) + expect(() => findTypescript(seven)).toThrow(expect.objectContaining({ fallback: '@typescript/typescript6@7.0.0' })) + const none = await fakePackage({}) + expect(() => findTypescript(none)).toThrow(expect.objectContaining({ found: undefined, fallback: undefined })) + }) + + it('should refuse a module with no JavaScript API of TypeScript 6, and say to install `@typescript/typescript6`', async () => { await expect(assertSupportedTypescript()).resolves.toBeUndefined() + const cwd = await fakePackage(ownTypescript('7.0.2')) vi.resetModules() - vi.doMock('typescript', () => ({ default: { version: '7.0.2', versionMajorMinor: '7.0' } })) + vi.doMock('../src/transpile/typescript.ts', async (importOriginal) => { + const original = await importOriginal() + return { ...original, loadTypescript: () => original.findTypescript(cwd) } + }) onTestFinished(() => { - vi.doUnmock('typescript') + vi.doUnmock('../src/transpile/typescript.ts') vi.resetModules() }) const { assertSupportedTypescript: assertWithTypescript7 } = await import('../src/build/engine.ts') - await expect(assertWithTypescript7()).rejects.toThrow(expect.objectContaining({ code: 'NUXT_MB_B0005', message: expect.stringContaining('`typescript@7.0.2`'), fix: expect.stringContaining('typescript@^6.0.0') })) + await expect(assertWithTypescript7()).rejects.toThrow(expect.objectContaining({ code: 'NUXT_MB_B0005', message: expect.stringContaining('`typescript@7.0.2`'), fix: expect.stringContaining('pnpm add -D @typescript/typescript6') })) }) it('should warn rather than fail when the engine the module has installed is too old', async () => { From 049b5242d4583969cea9dd41472d5423750d6d5c Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Sun, 22 Nov 2026 17:21:56 +0000 Subject: [PATCH 2/7] refactor: parse scripts with oxc rather than TypeScript --- CONTRIBUTING.md | 2 +- package.json | 1 + pnpm-lock.yaml | 3 + src/build/build.ts | 3 +- src/build/directives.ts | 69 ++---------- src/build/loader.ts | 153 ++++++++++++-------------- src/build/module-declarations.ts | 2 +- src/build/types.ts | 65 ++++++------ src/commands/prepare.ts | 22 +++- src/transpile/declarations.ts | 177 +++++++++++++++++++++++-------- src/transpile/oxc.ts | 81 ++++++++++++++ src/transpile/specifiers.ts | 57 +++++----- src/tsdown/setup.ts | 2 +- test/transpile-dir.spec.ts | 2 +- test/unit.spec.ts | 11 +- 15 files changed, 383 insertions(+), 267 deletions(-) create mode 100644 src/transpile/oxc.ts diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ae7fb73f..f01d006e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -36,7 +36,7 @@ The package has three entry points: | `src/commands/` | The CLI subcommands, plus `config-file.ts`, which finds the module's tsdown config and reads the `builder()` options from it. | | `src/tsdown/` | The `builder()` plugin. `plugin.ts` creates it, and `setup.ts` turns the tsdown config into a build. It adds the plugins, hooks into tsdown's lifecycle, and handles watch mode. `externals.ts`, `unchanged.ts` and `report.ts` are the plugins and helpers that `setup.ts` uses, and `dts.ts` generates the declarations of the bundled entries. `build.ts` runs tsdown for `nuxt-module-build build`. | | `src/build/` | The build itself, independent of tsdown's plugin API:
`options.ts` resolves `builder()` options.
`build.ts` resolves a `BuildPlan` and runs the steps before and after the bundle.
`loader.ts` imports module code and checks that Node can load it.
`package.ts` holds the `package.json` checks.
`types.ts` and `module-declarations.ts` write `types.d.mts` and the declarations `prepare` generates.
`aliases.ts` rewrites `#app` in declarations.
`directives.ts` wraps the oxc transform of runtime files so that TypeScript directive comments are left out.
`unchecked.ts` finds the TypeScript files that no tsconfig the module references includes, for `prepare`'s note.
`engine.ts` loads the declaration engine that `declarations.engine` selects, with its diagnostics. | -| `src/transpile/` | `transpileDir()`, the internal rolldown plugin that transpiles a directory file by file. It transforms scripts with oxc and `.vue` files with `vue.ts`, compiles stylesheets with `stylesheets.ts`, emits declarations with `declarations.ts` (reused from `node_modules/.cache` while their inputs are unchanged, see `cache.ts`) through a declaration engine (`engine.ts` for the module's own TypeScript, `native.ts` for TypeScript 7 and tsrs), rewrites import specifiers with `specifiers.ts`, resolves the tsconfig of each file with `tsconfig.ts`, and loads the JavaScript API of TypeScript that the whole package uses with `typescript.ts` (the module's own `typescript` when it has one, or else `@typescript/typescript6`). It imports nothing outside the directory but `src/utils.ts`, so it can be extracted later. | +| `src/transpile/` | `transpileDir()`, the internal rolldown plugin that transpiles a directory file by file. It transforms scripts with oxc and `.vue` files with `vue.ts`, compiles stylesheets with `stylesheets.ts`, emits declarations with `declarations.ts` (reused from `node_modules/.cache` while their inputs are unchanged, see `cache.ts`) through a declaration engine (`engine.ts` for the module's own TypeScript, `native.ts` for TypeScript 7 and tsrs), rewrites import specifiers with `specifiers.ts`, resolves the tsconfig of each file with `tsconfig.ts`. `oxc.ts` loads the oxc bindings of the `rolldown` that `tsdown` depends on, whose parser the whole package parses scripts with, and `typescript.ts` loads the JavaScript API of TypeScript that the whole package uses (the module's own `typescript` when it has one, or else `@typescript/typescript6`). The directory imports nothing outside it but `src/utils.ts`, so it can be extracted later. | | `src/legacy/` | Compatibility with v1 and unbuild (see [Legacy code](#legacy-code)). | | `src/diagnostics.ts` | The codes of every error and warning the builder reports (see [Diagnostics](#diagnostics)). | | `src/utils.ts` | Path, file and regex helpers shared across directories, and `logger`, which prints diagnostics outside a tsdown build. | diff --git a/package.json b/package.json index c61b73ef..32fe0171 100644 --- a/package.json +++ b/package.json @@ -92,6 +92,7 @@ "@nuxt/cli": "^4.0.3", "@nuxt/eslint-config": "^1.17.0", "@nuxt/schema": "~4.6.4", + "@oxc-project/types": "^0.157.0", "@types/node": "^26.6.6", "@typescript/typescript6": "6.0.2", "@typescript/typescript7": "npm:typescript@7.1.0-beta", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 144547f6..7e04b710 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -221,6 +221,9 @@ importers: '@nuxt/schema': specifier: ~4.6.4 version: 4.6.4 + '@oxc-project/types': + specifier: ^0.157.0 + version: 0.157.0 '@types/node': specifier: ^26.6.6 version: 26.6.6 diff --git a/src/build/build.ts b/src/build/build.ts index 77195852..dcc11f59 100644 --- a/src/build/build.ts +++ b/src/build/build.ts @@ -9,6 +9,7 @@ import { glob, globSync } from 'tinyglobby' import builderPkg from '../../package.json' with { type: 'json' } import { scriptExtension, valueSpecifiers } from '../transpile/specifiers.ts' +import { loadOxc } from '../transpile/oxc.ts' import { EXCLUDE } from '../transpile/transpile-dir.ts' import type { ResolveExternal } from '../transpile/transpile-dir.ts' import { createTsconfigResolver, declarationPaths, hasIsolatedDeclarations, namedCachePath, TsconfigError, tsconfigPaths, writeDependencyImports, writeDerivedTsconfig, writeServerRoutesStub } from '../transpile/tsconfig.ts' @@ -17,7 +18,7 @@ import { errors, warnings } from '../diagnostics.ts' import { findPackageDir, findUp, isInside, isSourceScript, probe, relativeSpecifier, SCRIPT_RE, writeIfChanged } from '../utils.ts' import type { PackageJson } from '../utils.ts' import { rewriteRuntimeDeclarations } from './aliases.ts' -import { assertLoadableModuleCode, importModule, loadOxc } from './loader.ts' +import { assertLoadableModuleCode, importModule } from './loader.ts' import { bundledEntries, NUXT_EXTERNALS } from './options.ts' import type { DirectoryEntry, ModuleConfig } from './options.ts' import { checkPublishedPaths, importsKeyFor, publishedPackage, selfReferencePaths, unpublishableImportsError } from './package.ts' diff --git a/src/build/directives.ts b/src/build/directives.ts index 1435d958..5818f022 100644 --- a/src/build/directives.ts +++ b/src/build/directives.ts @@ -1,38 +1,28 @@ -import type ts from 'typescript' - +import { parseModule } from '../transpile/oxc.ts' import type { Transform } from '../transpile/transpile-dir.ts' -import { loadTypescript } from '../transpile/typescript.ts' -const DIRECTIVE_RE = /@ts-(?:expect-error|ignore|nocheck|check)\b/g +const DIRECTIVE_RE = /@ts-(?:expect-error|ignore|nocheck|check)\b/ const LINE_DIRECTIVE_RE = /^\/\/\/?[\t ]*@ts-(?:expect-error|ignore|nocheck|check)\b/ const BLOCK_DIRECTIVE_RE = /^[\t /*]*@ts-(?:expect-error|ignore)\b/ const LINE_TERMINATOR_RE = /\r\n?|[\n\u2028\u2029]/ const NOT_LINE_TERMINATOR_RE = /[^\n\r\u2028\u2029]/g -const SCRIPT_KINDS: Record = { js: 'JS', jsx: 'JSX', ts: 'TS', tsx: 'TSX' } - /** * `transform` with the TypeScript directive comments of the source, such as `// @ts-ignore` * and `// @ts-expect-error`, replaced by spaces, so that the output leaves them out and its * source map still matches the source. Other comments are kept. */ export function withoutDirectiveComments(transform: Transform): Transform { - return async (filename, source, options) => transform(filename, source.search(DIRECTIVE_RE) === -1 ? source : await blankDirectiveComments(source, options?.lang ?? 'ts'), options) + return async (filename, source, options) => transform(filename, source.search(DIRECTIVE_RE) === -1 ? source : blankDirectiveComments(source, options?.lang ?? 'ts'), options) } -async function blankDirectiveComments(source: string, lang: string) { - const { ts } = loadTypescript() - const sourceFile = ts.createSourceFile(`source.${lang}`, source, ts.ScriptTarget.Latest, false, ts.ScriptKind[SCRIPT_KINDS[lang] ?? 'TS']) - const comments = new Map() - for (const { index } of source.matchAll(DIRECTIVE_RE)) { - const comment = commentAt(ts, sourceFile, index) - if (comment && isDirective(source.slice(comment.pos, comment.end))) { - comments.set(comment.pos, comment.end) - } - } +function blankDirectiveComments(source: string, lang: string) { let result = source - for (const [pos, end] of comments) { - result = result.slice(0, pos) + source.slice(pos, end).replace(NOT_LINE_TERMINATOR_RE, ' ') + result.slice(end) + for (const { start, end } of parseModule(source, `source.${lang}`).comments) { + const comment = source.slice(start, end) + if (isDirective(comment)) { + result = result.slice(0, start) + comment.replace(NOT_LINE_TERMINATOR_RE, ' ') + result.slice(end) + } } return result } @@ -41,44 +31,3 @@ async function blankDirectiveComments(source: string, lang: string) { function isDirective(comment: string) { return comment.startsWith('/*') ? BLOCK_DIRECTIVE_RE.test(comment.split(LINE_TERMINATOR_RE).at(-1)!) : LINE_DIRECTIVE_RE.test(comment) } - -/** - * The comment that holds `offset`, or `undefined` when `offset` is not in a comment, such as in - * a string, a template or JSX text. - */ -function commentAt(ts: typeof import('typescript'), sourceFile: ts.SourceFile, offset: number) { - const text = sourceFile.text - const holding = (pos: number) => [...ts.getTrailingCommentRanges(text, pos) ?? [], ...ts.getLeadingCommentRanges(text, pos) ?? []].find(range => range.pos <= offset && offset < range.end) - let node: ts.Node = sourceFile - for (;;) { - let containing: ts.Node | undefined - let before: ts.Node | undefined - ts.forEachChild(node, (child) => { - if (child.end <= offset) { - before = child - return - } - if (child.pos <= offset) { - containing = child - } - return true - }) - if (!containing) { - if (!before && node.kind < ts.SyntaxKind.FirstNode) { - return - } - // Between its children, a node holds only punctuation, keywords and trivia. - const scanner = ts.createScanner(ts.ScriptTarget.Latest, false, sourceFile.languageVariant, text, undefined, before ? before.end : node.getStart(sourceFile)) - for (let kind = scanner.scan(); kind !== ts.SyntaxKind.EndOfFileToken && scanner.getTokenStart() <= offset; kind = scanner.scan()) { - if ((kind === ts.SyntaxKind.SingleLineCommentTrivia || kind === ts.SyntaxKind.MultiLineCommentTrivia) && offset < scanner.getTokenEnd()) { - return { pos: scanner.getTokenStart(), end: scanner.getTokenEnd() } - } - } - return - } - if (offset < containing.getStart(sourceFile)) { - return holding(containing.pos) - } - node = containing - } -} diff --git a/src/build/loader.ts b/src/build/loader.ts index 56714a83..30c0bc93 100644 --- a/src/build/loader.ts +++ b/src/build/loader.ts @@ -1,15 +1,15 @@ import { existsSync, readFileSync } from 'node:fs' -import { createRequire, registerHooks } from 'node:module' +import { registerHooks } from 'node:module' import { fileURLToPath, pathToFileURL } from 'node:url' import { dirname, join, relative, resolve } from 'pathe' import { createPathsMatcher, getTsconfig } from 'get-tsconfig' import type { Diagnostic } from 'nostics' -import type ts from 'typescript' +import type { Expression, ImportDeclaration, ObjectExpression, TSGlobalDeclaration, TSModuleDeclaration } from '@oxc-project/types' -import type { Transform } from '../transpile/transpile-dir.ts' +import { literalText, parseModule, walk } from '../transpile/oxc.ts' +import type { Node } from '../transpile/oxc.ts' import { packageName } from '../transpile/tsconfig.ts' -import { loadTypescript } from '../transpile/typescript.ts' -import { findPackageDir, findUp, isFile, isInside, isPlainObject, NODE_MODULES_RE, probe, relativeSpecifier, resolveFrom, SCRIPT_RE, TYPESCRIPT_RE } from '../utils.ts' +import { findPackageDir, findUp, isFile, isInside, isPlainObject, NODE_MODULES_RE, probe, relativeSpecifier, resolveFrom, SCRIPT_RE } from '../utils.ts' import type { PackageJson } from '../utils.ts' import { errors } from '../diagnostics.ts' import { importsKeyFor } from './package.ts' @@ -64,26 +64,6 @@ export async function importModule(path: string, { cwd, stubs = {}, version }: I } } -interface Oxc { - transform: Transform - transformSync: (...args: Parameters) => Awaited> -} - -let oxc: Oxc | null | undefined - -/** The oxc bindings of the `rolldown` that `tsdown` depends on, or `null` when `tsdown` is not installed. */ -export function loadOxc(): Oxc | null { - if (oxc === undefined) { - try { - oxc = createRequire(import.meta.resolve('tsdown'))('rolldown/utils') as Oxc - } - catch { - oxc = null - } - } - return oxc -} - export interface ModuleCodeIssue { /** Path relative to the module root. */ file: string @@ -97,14 +77,14 @@ export interface ModuleCodeIssue { unfollowed?: true } -const NON_ERASABLE: Array<[message: string, matches: (ts: typeof import('typescript'), node: ts.Node) => boolean]> = [ - ['`enum` (use an `as const` object and a union type of its values)', (ts, node) => ts.isEnumDeclaration(node)], - ['`namespace` (use plain exports or an object)', (ts, node) => ts.isModuleDeclaration(node) && ts.isIdentifier(node.name) && !(node.flags & (ts.NodeFlags.NestedNamespace | ts.NodeFlags.GlobalAugmentation)) && hasRuntimeCode(ts, node)], - ['angle-bracket type assertion (write `value as Type`)', (ts, node) => ts.isTypeAssertionExpression(node)], - ['parameter property (declare the field and assign it in the constructor)', (ts, node) => ts.isParameter(node) && ts.isParameterPropertyDeclaration(node, node.parent)], - ['`import =` (use `import`, or `createRequire` for CommonJS)', (ts, node) => ts.isImportEqualsDeclaration(node) && !node.isTypeOnly], - ['`export =` (use `export default`)', (ts, node) => ts.isExportAssignment(node) && !!node.isExportEquals], - ['decorator (call the decorator as a function)', (ts, node) => ts.isDecorator(node)], +const NON_ERASABLE: Array<[message: string, matches: (node: Node, parent: Node | undefined, grandparent: Node | undefined) => boolean]> = [ + ['`enum` (use an `as const` object and a union type of its values)', node => node.type === 'TSEnumDeclaration'], + ['`namespace` (use plain exports or an object)', node => node.type === 'TSModuleDeclaration' && node.id.type !== 'Literal' && node.kind !== 'global' && hasRuntimeCode(node)], + ['angle-bracket type assertion (write `value as Type`)', node => node.type === 'TSTypeAssertion'], + ['parameter property (declare the field and assign it in the constructor)', (node, _, method) => node.type === 'TSParameterProperty' && method?.type === 'MethodDefinition' && method.kind === 'constructor'], + ['`import =` (use `import`, or `createRequire` for CommonJS)', node => node.type === 'TSImportEqualsDeclaration' && node.importKind !== 'type'], + ['`export =` (use `export default`)', node => node.type === 'TSExportAssignment'], + ['decorator (call the decorator as a function)', node => node.type === 'Decorator'], ] /** @@ -320,88 +300,95 @@ function importTarget(target: unknown, match: string | undefined): string | unde } } -function scriptKind(ts: typeof import('typescript'), filename: string) { - if (TYPESCRIPT_RE.test(filename)) { - return filename.endsWith('x') ? ts.ScriptKind.TSX : ts.ScriptKind.TS - } - return filename.endsWith('x') ? ts.ScriptKind.JSX : ts.ScriptKind.JS +function hasRuntimeCode(node: TSModuleDeclaration | TSGlobalDeclaration): boolean { + return !!node.body?.body.some((statement) => { + const declaration = statement.type === 'ExportNamedDeclaration' && statement.declaration ? statement.declaration : statement + return !(declaration.type === 'TSInterfaceDeclaration' || declaration.type === 'TSTypeAliasDeclaration' || (declaration.type === 'TSModuleDeclaration' && !hasRuntimeCode(declaration))) + }) } -function hasRuntimeCode(ts: typeof import('typescript'), node: ts.ModuleDeclaration): boolean { - const { body } = node - if (!body) { - return false - } - if (ts.isModuleDeclaration(body)) { - return hasRuntimeCode(ts, body) +const LINE_BREAK_RE = /\r\n?|[\n\u2028\u2029]/g + +/** The 1-based line and column of each offset of `source`, in UTF-16 code units. */ +function lineColumns(source: string) { + const starts = [0, ...[...source.matchAll(LINE_BREAK_RE)].map(({ index, 0: lineBreak }) => index + lineBreak.length)] + return (offset: number) => { + let low = 0 + let high = starts.length - 1 + while (low < high) { + const middle = (low + high + 1) >> 1 + if (starts[middle]! <= offset) { + low = middle + } + else { + high = middle - 1 + } + } + return { line: low + 1, column: offset - starts[low]! + 1 } } - return ts.isModuleBlock(body) && body.statements.some(statement => !( - ts.isInterfaceDeclaration(statement) - || ts.isTypeAliasDeclaration(statement) - || (ts.isModuleDeclaration(statement) && !hasRuntimeCode(ts, statement)) - )) } +type ImportAttributes = ImportDeclaration['attributes'] + function analyseSource(filename: string, source: string): SourceAnalysis { - const { ts } = loadTypescript() - const { SyntaxKind } = ts - const sourceFile = ts.createSourceFile(filename, source, ts.ScriptTarget.Latest, true, scriptKind(ts, filename)) + const position = lineColumns(source) const found: SourceAnalysis = { nonErasable: [], imports: [] } - const position = (node: ts.Node) => { - const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)) - return { line: line + 1, column: character + 1 } - } - const isJson = (attributes: ts.ImportAttributes | undefined) => !!attributes?.elements.some(element => element.name.text === 'type' && ts.isStringLiteral(element.value) && element.value.text === 'json') + const isJson = (attributes: ImportAttributes) => attributes.some(({ key, value }) => (key.type === 'Literal' ? key.value : key.name) === 'type' && value.value === 'json') // `true` when the value is not known statically. - const property = (object: ts.ObjectLiteralExpression, name: string): ts.Expression | true | undefined => { + const property = (object: ObjectExpression, name: string): Expression | true | undefined => { for (const property of [...object.properties].reverse()) { - if (ts.isPropertyAssignment(property) && (ts.isIdentifier(property.name) || ts.isStringLiteral(property.name))) { - if (property.name.text === name) { - return property.initializer + const key = property.type === 'Property' && !property.computed ? property.key : undefined + const keyName = key?.type === 'Identifier' ? key.name : key?.type === 'Literal' && typeof key.value === 'string' ? key.value : undefined + if (property.type === 'Property' && property.kind === 'init' && !property.method && !property.shorthand && keyName !== undefined) { + if (keyName === name) { + return property.value as Expression } } - else if (!ts.isShorthandPropertyAssignment(property) || property.name.text === name) { + else if (!(property.type === 'Property' && property.shorthand) || keyName === name) { return true } } } - const isJsonOptions = (options: ts.Expression | undefined) => { - if (!options || !ts.isObjectLiteralExpression(options)) { + const isJsonOptions = (options: Expression | null) => { + if (options?.type !== 'ObjectExpression') { return !!options } const attributes = property(options, 'with') - if (!attributes || attributes === true || !ts.isObjectLiteralExpression(attributes)) { + if (!attributes || attributes === true || attributes.type !== 'ObjectExpression') { return !!attributes } const type = property(attributes, 'type') - return !!type && (type === true || !ts.isStringLiteralLike(type) || type.text === 'json') + return !!type && (type === true || literalText(type) === undefined || literalText(type) === 'json') } - const specifierOf = (node: ts.Node) => { - if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) { - return { specifier: node.moduleSpecifier, typeOnly: node.importClause?.isTypeOnly ?? false, json: isJson(node.attributes) } + const specifierOf = (node: Node) => { + if (node.type === 'ImportDeclaration') { + return { specifier: node.source, typeOnly: node.importKind === 'type', json: isJson(node.attributes) } } - if (ts.isExportDeclaration(node) && node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) { - return { specifier: node.moduleSpecifier, typeOnly: node.isTypeOnly, json: isJson(node.attributes) } + if ((node.type === 'ExportNamedDeclaration' || node.type === 'ExportAllDeclaration') && node.source) { + return { specifier: node.source, typeOnly: node.exportKind === 'type', json: isJson(node.attributes) } } - if (ts.isCallExpression(node) && node.expression.kind === SyntaxKind.ImportKeyword && node.arguments[0] && ts.isStringLiteralLike(node.arguments[0])) { - return { specifier: node.arguments[0], typeOnly: false, json: isJsonOptions(node.arguments[1]) } + if (node.type === 'ImportExpression' && literalText(node.source) !== undefined) { + return { specifier: node.source, typeOnly: false, json: isJsonOptions(node.options) } } } - const visit = (node: ts.Node) => { - if (ts.canHaveModifiers(node) && ts.getModifiers(node)?.some(modifier => modifier.kind === SyntaxKind.DeclareKeyword)) { - return + const parents = new Map() + walk(parseModule(source, filename).program, (node, parent) => { + if ('declare' in node && node.declare) { + return false + } + if (parent) { + parents.set(node, parent) } - const nonErasable = NON_ERASABLE.find(([, matches]) => matches(ts, node)) + const nonErasable = NON_ERASABLE.find(([, matches]) => matches(node, parent, parent && parents.get(parent))) if (nonErasable) { - found.nonErasable.push({ ...position(node), message: nonErasable[0] }) + found.nonErasable.push({ ...position(parent?.type === 'ExportNamedDeclaration' ? parent.start : node.start), message: nonErasable[0] }) } const imported = specifierOf(node) if (imported) { - found.imports.push({ specifier: imported.specifier.text, typeOnly: imported.typeOnly, json: imported.json, ...position(imported.specifier) }) + found.imports.push({ specifier: literalText(imported.specifier)!, typeOnly: imported.typeOnly, json: imported.json, ...position(imported.specifier.start) }) } - ts.forEachChild(node, visit) - } - visit(sourceFile) + }) + found.imports.sort((a, b) => a.line - b.line || a.column - b.column) return found } diff --git a/src/build/module-declarations.ts b/src/build/module-declarations.ts index f3a794d1..2d3ac34e 100644 --- a/src/build/module-declarations.ts +++ b/src/build/module-declarations.ts @@ -5,10 +5,10 @@ import { dirname, join, normalize, relative, resolve } from 'pathe' import { warnings } from '../diagnostics.ts' import { createDeclarationProgram } from '../transpile/declarations.ts' import type { DeclarationEngine } from '../transpile/engine.ts' +import { loadOxc } from '../transpile/oxc.ts' import { moduleSpecifiers, rewriteSpecifiers } from '../transpile/specifiers.ts' import { hasIsolatedDeclarations, isModuleFile } from '../transpile/tsconfig.ts' import { isInside, isSourceScript, probe, RELATIVE_RE, relativeSpecifier, SCRIPT_RE } from '../utils.ts' -import { loadOxc } from './loader.ts' import { writeSourceTypes } from './types.ts' const NUXT_DIR_RE = /^\.nuxt(?:\/|$)/ diff --git a/src/build/types.ts b/src/build/types.ts index 13c5026b..175bddbf 100644 --- a/src/build/types.ts +++ b/src/build/types.ts @@ -1,8 +1,8 @@ import { existsSync, promises as fsp, readFileSync } from 'node:fs' import { dirname, relative, resolve } from 'pathe' -import type ts from 'typescript' +import type { BindingPattern, Declaration, ModuleExportName, TSTypeName } from '@oxc-project/types' -import { parseModule } from '../transpile/specifiers.ts' +import { parseModule } from '../transpile/oxc.ts' import { probe, writeIfChanged } from '../utils.ts' interface ExportedName { @@ -155,47 +155,50 @@ function probeWithDeclarations(path: string) { } function parseExports(code: string, filename: string): ModuleExport[] { - const { ts, sourceFile } = parseModule(code, filename) const exports: ModuleExport[] = [] - const hasModifier = (node: ts.Node, kind: ts.SyntaxKind) => ts.canHaveModifiers(node) && !!ts.getModifiers(node)?.some(modifier => modifier.kind === kind) - for (const statement of sourceFile.statements) { - if (ts.isExportDeclaration(statement)) { - const specifier = statement.moduleSpecifier && ts.isStringLiteral(statement.moduleSpecifier) ? statement.moduleSpecifier.text : undefined - const clause = statement.exportClause - if (clause && ts.isNamedExports(clause)) { - exports.push({ specifier, names: clause.elements.map(element => ({ name: element.name.text, typeOnly: statement.isTypeOnly || element.isTypeOnly })) }) - } - else if (specifier) { - exports.push({ specifier, star: { typeOnly: statement.isTypeOnly }, names: clause ? [{ name: clause.name.text, typeOnly: statement.isTypeOnly }] : [] }) - } + for (const statement of parseModule(code, filename).program.body) { + if (statement.type === 'ExportNamedDeclaration' && statement.declaration) { + const { declaration } = statement + const typeOnly = declaration.type === 'TSInterfaceDeclaration' || declaration.type === 'TSTypeAliasDeclaration' + exports.push({ names: declaredNames(declaration).map(name => ({ name, typeOnly })) }) } - else if (ts.isExportAssignment(statement)) { - if (!statement.isExportEquals) { - exports.push({ names: [{ name: 'default', typeOnly: false }] }) - } + else if (statement.type === 'ExportNamedDeclaration') { + exports.push({ specifier: statement.source?.value, names: statement.specifiers.map(element => ({ name: moduleExportName(element.exported), typeOnly: statement.exportKind === 'type' || element.exportKind === 'type' })) }) } - else if (hasModifier(statement, ts.SyntaxKind.ExportKeyword)) { - const typeOnly = ts.isInterfaceDeclaration(statement) || ts.isTypeAliasDeclaration(statement) - const names = hasModifier(statement, ts.SyntaxKind.DefaultKeyword) ? ['default'] : declaredNames(ts, statement) - exports.push({ names: names.map(name => ({ name, typeOnly })) }) + else if (statement.type === 'ExportAllDeclaration') { + const typeOnly = statement.exportKind === 'type' + exports.push({ specifier: statement.source.value, star: { typeOnly }, names: statement.exported ? [{ name: moduleExportName(statement.exported), typeOnly }] : [] }) + } + else if (statement.type === 'ExportDefaultDeclaration') { + exports.push({ names: [{ name: 'default', typeOnly: statement.declaration.type === 'TSInterfaceDeclaration' }] }) } } return exports } -function declaredNames(ts: typeof import('typescript'), statement: ts.Statement): string[] { - if (ts.isVariableStatement(statement)) { - return statement.declarationList.declarations.flatMap(declaration => bindingNames(ts, declaration.name)) +const moduleExportName = (name: ModuleExportName) => name.type === 'Literal' ? name.value : name.name + +const leftmost = (name: TSTypeName): TSTypeName => name.type === 'TSQualifiedName' ? leftmost(name.left) : name + +function declaredNames(declaration: Declaration): string[] { + if (declaration.type === 'VariableDeclaration') { + return declaration.declarations.flatMap(declarator => bindingNames(declarator.id)) } - const name = (statement as ts.DeclarationStatement).name - return name && ts.isIdentifier(name) ? [name.text] : [] + const id = 'id' in declaration && declaration.id ? declaration.id.type === 'TSQualifiedName' ? leftmost(declaration.id) : declaration.id : undefined + return id?.type === 'Identifier' ? [id.name] : [] } -function bindingNames(ts: typeof import('typescript'), name: ts.BindingName): string[] { - if (ts.isIdentifier(name)) { - return [name.text] +function bindingNames(pattern: BindingPattern): string[] { + switch (pattern.type) { + case 'Identifier': + return [pattern.name] + case 'AssignmentPattern': + return bindingNames(pattern.left) + case 'ObjectPattern': + return pattern.properties.flatMap(property => bindingNames(property.type === 'RestElement' ? property.argument : property.value)) + case 'ArrayPattern': + return pattern.elements.flatMap(element => !element ? [] : bindingNames(element.type === 'RestElement' ? element.argument : element)) } - return name.elements.flatMap(element => ts.isBindingElement(element) ? bindingNames(ts, element.name) : []) } /** The names that `exports` declare or re-export by name, sorted with `default` last. */ diff --git a/src/commands/prepare.ts b/src/commands/prepare.ts index f5248739..3aa93073 100644 --- a/src/commands/prepare.ts +++ b/src/commands/prepare.ts @@ -17,7 +17,8 @@ import { augmentsNuxtTypes, writeSourceTypes } from '../build/types.ts' import { noteUncheckedFiles } from '../build/unchecked.ts' import { loadBuildConfig } from '../legacy/build-config.ts' import { hasIsolatedDeclarations, isModuleFile, rootTsconfig, writeDependencyImports } from '../transpile/tsconfig.ts' -import { loadTypescript } from '../transpile/typescript.ts' +import { parseModule, walk } from '../transpile/oxc.ts' +import type { Program } from '../transpile/oxc.ts' import { isInside, probe, readPackageJson, resolveFrom } from '../utils.ts' import type { PackageJson } from '../utils.ts' import { assertNoStubArg, resolveCwdArg, sharedArgs } from './_shared.ts' @@ -55,8 +56,19 @@ async function declaresModules(cwd: string, runtimeDirs: string[], entries: stri return sources.some(source => DECLARE_RE.test(source)) } +const MODULE_STATEMENTS = new Set(['ImportDeclaration', 'ExportNamedDeclaration', 'ExportDefaultDeclaration', 'ExportAllDeclaration', 'TSExportAssignment']) + +/** Whether TypeScript reads `program` as a module, rather than as a script that declares globals. */ +function isExternalModule(program: Program) { + let importMeta = false + walk(program, (node) => { + importMeta ||= node.type === 'MetaProperty' && node.meta.name === 'import' + return !importMeta + }) + return importMeta || program.body.some(statement => MODULE_STATEMENTS.has(statement.type) || (statement.type === 'TSImportEqualsDeclaration' && statement.moduleReference.type === 'TSExternalModuleReference')) +} + async function ambientDeclarations(cwd: string, runtimeDirs: string[], exclude: string[]) { - const { ts } = loadTypescript() const ignore = [...runtimeDirs, ...exclude].flatMap((pattern) => { const path = relative(cwd, pattern) return [path, `${path}/**`] @@ -65,11 +77,11 @@ async function ambientDeclarations(cwd: string, runtimeDirs: string[], exclude: const globals: string[] = [] const augmentations: string[] = [] for (const file of files.filter(file => isModuleFile(file, cwd)).sort()) { - const source = ts.createSourceFile(file, await readFile(file, 'utf8'), ts.ScriptTarget.Latest) - if (!ts.isExternalModule(source)) { + const { program } = parseModule(await readFile(file, 'utf8'), file) + if (!isExternalModule(program)) { globals.push(file) } - else if (source.statements.some(statement => ts.isModuleDeclaration(statement))) { + else if (program.body.some(statement => (statement.type === 'ExportNamedDeclaration' ? statement.declaration : statement)?.type === 'TSModuleDeclaration')) { augmentations.push(file) } } diff --git a/src/transpile/declarations.ts b/src/transpile/declarations.ts index 56a5d783..07ae6bf7 100644 --- a/src/transpile/declarations.ts +++ b/src/transpile/declarations.ts @@ -1,13 +1,14 @@ import { readFile } from 'node:fs/promises' import type { TsConfigResult } from 'get-tsconfig' import { relative } from 'pathe' -import type ts from 'typescript' +import type { ImportDeclaration, ImportSpecifier, ModuleExportName, TSQualifiedName } from '@oxc-project/types' import { contentCache } from './cache.ts' import { createTscEngine } from './engine.ts' import type { DeclarationEngine, DeclarationProject, EngineDiagnostic, ProjectOptions, SourceFileCache } from './engine.ts' +import { parseModule, walk } from './oxc.ts' +import type { Node } from './oxc.ts' import { isModuleFile, writeDeclarationPaths } from './tsconfig.ts' -import { loadTypescript } from './typescript.ts' export type { SourceFileCache } from './engine.ts' @@ -165,7 +166,122 @@ function formatDiagnostic(diagnostic: EngineDiagnostic, cwd: string): string { return diagnostic.file && diagnostic.line !== undefined ? `${relative(cwd, diagnostic.file)}(${diagnostic.line},${diagnostic.column}): ${prefix}` : prefix } -const SFC_SCRIPT_RE = /"']|"[^"]*"|'[^']*')*>([\s\S]*?)<\/script\b[^>]*>/gi +const SFC_SCRIPT_RE = /("']|"[^"]*"|'[^']*')*>)([\s\S]*?)<\/script\b[^>]*>/gi +const SFC_LANG_RE = /\blang\s*=\s*["']?(\w+)/ + +/** The leftmost identifier of a qualified name or a property access, if it starts with one. */ +function leftmostIdentifier(node: Node | null | undefined): string | undefined { + while (node?.type === 'TSQualifiedName' || (node?.type === 'MemberExpression' && !node.computed)) { + node = node.type === 'TSQualifiedName' ? node.left : node.object + } + return node?.type === 'Identifier' ? node.name : undefined +} + +const moduleExportName = (name: ModuleExportName) => name.type === 'Literal' ? name.value : name.name + +const DECLARED_TYPES = new Set(['TSInterfaceDeclaration', 'TSTypeAliasDeclaration', 'ClassDeclaration', 'TSEnumDeclaration', 'FunctionDeclaration', 'TSDeclareFunction', 'VariableDeclarator']) + +/** The names that `declaration` refers to without declaring or importing them where it refers to them. */ +function unboundNames(declaration: string): string[] { + const parents = new Map() + const referenced: Array<[name: string, node: Node]> = [] + const declared: Array<[name: string, scope: Node, outside?: Node]> = [] + const reference = (name: string | undefined, node: Node) => { + if (name !== undefined) { + referenced.push([name, node]) + } + } + const ancestor = (node: Node, matches: (node: Node) => boolean) => { + for (let current = parents.get(node); current; current = parents.get(current)) { + if (matches(current)) { + return current + } + } + } + const block = (node: Node) => ancestor(node, ({ type }) => type === 'TSModuleBlock' || type === 'Program')! + walk(parseModule(declaration, 'declaration.d.ts').program, (node, parent) => { + if (parent) { + parents.set(node, parent) + } + switch (node.type) { + case 'TSTypeReference': + reference(leftmostIdentifier(node.typeName), node) + break + case 'TSTypeQuery': + reference(leftmostIdentifier(node.exprName), node) + break + case 'TSClassImplements': + case 'TSInterfaceHeritage': + case 'TSInstantiationExpression': + reference(leftmostIdentifier(node.expression), node) + break + case 'ClassDeclaration': + case 'ClassExpression': + if (node.superClass) { + reference(leftmostIdentifier(node.superClass), node.superClass) + } + break + case 'ExportNamedDeclaration': + if (!node.source) { + for (const specifier of node.specifiers) { + reference(moduleExportName(specifier.local), specifier) + } + } + break + case 'ExportDefaultDeclaration': + if (node.declaration.type === 'Identifier') { + reference(node.declaration.name, node) + } + break + case 'TSExportAssignment': + if (node.expression.type === 'Identifier') { + reference(node.expression.name, node) + } + break + case 'TSTypeParameter': + if (parent?.type === 'TSInferType') { + const conditional = ancestor(parent, ({ type }) => type === 'TSConditionalType') + declared.push(conditional?.type === 'TSConditionalType' ? [node.name.name, conditional, conditional.falseType] : [node.name.name, parent]) + } + else { + declared.push([node.name.name, parents.get(parent!)!]) + } + break + case 'TSMappedType': + declared.push([node.key.name, node]) + break + case 'ImportSpecifier': + case 'ImportDefaultSpecifier': + case 'ImportNamespaceSpecifier': + declared.push([node.local.name, block(node)]) + break + case 'TSModuleDeclaration': + for (let id: Node = node.id; ; id = (id as TSQualifiedName).left) { + const name = id.type === 'TSQualifiedName' ? id.right : id + if (name.type === 'Identifier') { + declared.push([name.name, block(node)]) + } + if (id.type !== 'TSQualifiedName') { + break + } + } + break + } + if (DECLARED_TYPES.has(node.type) && 'id' in node && node.id?.type === 'Identifier') { + declared.push([node.id.name, block(node)]) + } + }) + const within = (node: Node, scope: Node) => node === scope || ancestor(node, current => current === scope) !== undefined + return [...new Set(referenced.filter(([name, node]) => !declared.some(([local, scope, outside]) => local === name && within(node, scope) && !(outside && within(node, outside)))).map(([name]) => name))] +} + +/** The import declarations of `code`, the contents of `source`, or of the scripts of a single-file component. */ +function importDeclarations(source: string, code: string): ImportDeclaration[] { + const scripts = source.endsWith('.vue') + ? [...code.matchAll(SFC_SCRIPT_RE)].map(({ 1: tag, 2: content }) => ({ filename: `${source}.${tag!.match(SFC_LANG_RE)?.[1] ?? 'ts'}`, content: content! })) + : [{ filename: source, content: code }] + return scripts.flatMap(({ filename, content }) => parseModule(content, filename).program.body.filter(statement => statement.type === 'ImportDeclaration')) +} /** * `declaration` with the imports of `source` (`code`, the file's contents) that it refers to by @@ -174,60 +290,27 @@ const SFC_SCRIPT_RE = /"']|"[^"]*"|'[^']*')*>([\s\S]*?)<\/script\ * the module resolves the alias. */ export async function restoreImports(declaration: string, source: string, code: string): Promise { - const { ts } = loadTypescript() - const script = source.endsWith('.vue') ? [...code.matchAll(SFC_SCRIPT_RE)].map(([, content]) => content).join('\n') : code - const emitted = ts.createSourceFile('declaration.d.ts', declaration, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS) - const referenced: Array<[name: string, node: ts.Node]> = [] - const declared: Array<[name: string, scope: ts.Node, outside?: ts.Node]> = [] - const visit = (node: ts.Node) => { - if ((ts.isTypeReferenceNode(node) || ts.isTypeQueryNode(node) || ts.isExpressionWithTypeArguments(node)) && !ts.isImportTypeNode(node)) { - let name: ts.Node = ts.isTypeReferenceNode(node) ? node.typeName : ts.isTypeQueryNode(node) ? node.exprName : node.expression - while (ts.isQualifiedName(name) || ts.isPropertyAccessExpression(name)) { - name = ts.isQualifiedName(name) ? name.left : name.expression - } - if (ts.isIdentifier(name)) { - referenced.push([name.text, node]) - } - } - if (ts.isExportSpecifier(node) && !node.parent.parent.moduleSpecifier) { - referenced.push([(node.propertyName ?? node.name).text, node]) - } - if (ts.isExportAssignment(node) && ts.isIdentifier(node.expression)) { - referenced.push([node.expression.text, node]) - } - if (ts.isTypeParameterDeclaration(node)) { - const conditional = ts.isInferTypeNode(node.parent) ? ts.findAncestor(node.parent, ts.isConditionalTypeNode) : undefined - declared.push(conditional ? [node.name.text, conditional, conditional.falseType] : [node.name.text, node.parent]) - } - if ((ts.isImportSpecifier(node) || ts.isImportClause(node) || ts.isNamespaceImport(node) || ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node) || ts.isClassDeclaration(node) || ts.isEnumDeclaration(node) || ts.isModuleDeclaration(node) || ts.isFunctionDeclaration(node) || ts.isVariableDeclaration(node)) && node.name && ts.isIdentifier(node.name)) { - declared.push([node.name.text, ts.findAncestor(node.parent, ancestor => ts.isModuleBlock(ancestor) || ts.isSourceFile(ancestor))!]) - } - ts.forEachChild(node, visit) - } - visit(emitted) - const within = (node: ts.Node, scope: ts.Node) => !!ts.findAncestor(node, ancestor => ancestor === scope) - const missing = [...new Set(referenced.filter(([name, node]) => !declared.some(([local, scope, outside]) => local === name && within(node, scope) && !(outside && within(node, outside)))).map(([name]) => name))] + const missing = unboundNames(declaration) if (!missing.length) { return declaration } const pending = new Set(missing) const imports: string[] = [] - for (const statement of ts.createSourceFile(source, script, ts.ScriptTarget.Latest, false, ts.ScriptKind.TS).statements) { - if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier) || !statement.importClause) { + for (const statement of importDeclarations(source, code)) { + if (!statement.specifiers.length) { continue } - const clause = statement.importClause - const specifier = `'${statement.moduleSpecifier.text.replaceAll('\'', '\\\'')}'` - const bindings = clause.namedBindings - if (clause.name && pending.delete(clause.name.text)) { - imports.push(`import type ${clause.name.text} from ${specifier};`) + const specifier = `'${statement.source.value.replaceAll('\'', '\\\'')}'` + const bound = (type: string) => statement.specifiers.flatMap(element => element.type === type && pending.delete(element.local.name) ? [element] : []) + for (const element of bound('ImportDefaultSpecifier')) { + imports.push(`import type ${element.local.name} from ${specifier};`) } - if (bindings && ts.isNamespaceImport(bindings) && pending.delete(bindings.name.text)) { - imports.push(`import type * as ${bindings.name.text} from ${specifier};`) + for (const element of bound('ImportNamespaceSpecifier')) { + imports.push(`import type * as ${element.local.name} from ${specifier};`) } - const named = bindings && ts.isNamedImports(bindings) ? bindings.elements.filter(element => pending.delete(element.name.text)) : [] + const named = bound('ImportSpecifier') as ImportSpecifier[] if (named.length) { - imports.push(`import type { ${named.map(element => element.propertyName ? `${ts.isStringLiteral(element.propertyName) ? JSON.stringify(element.propertyName.text) : element.propertyName.text} as ${element.name.text}` : element.name.text).join(', ')} } from ${specifier};`) + imports.push(`import type { ${named.map(element => element.imported.start === element.local.start ? element.local.name : `${element.imported.type === 'Literal' ? JSON.stringify(element.imported.value) : element.imported.name} as ${element.local.name}`).join(', ')} } from ${specifier};`) } } return imports.length ? `${imports.join('\n')}\n${declaration}` : declaration diff --git a/src/transpile/oxc.ts b/src/transpile/oxc.ts new file mode 100644 index 00000000..d2210920 --- /dev/null +++ b/src/transpile/oxc.ts @@ -0,0 +1,81 @@ +import { createRequire } from 'node:module' +import type { Expression, Node, Program } from '@oxc-project/types' + +import type { Transform } from './transpile-dir.ts' + +export type { Node, Program } from '@oxc-project/types' + +type Lang = 'js' | 'jsx' | 'ts' | 'tsx' | 'dts' + +interface Comment { + type: 'Line' | 'Block' + value: string + start: number + end: number +} + +interface ParseResult { + program: Program + comments: Comment[] + errors: Array<{ message: string }> +} + +interface Oxc { + transform: Transform + transformSync: (...args: Parameters) => Awaited> + parseSync: (filename: string, code: string, options?: { lang?: Lang, sourceType?: 'module' }) => ParseResult +} + +let oxc: Oxc | null | undefined + +/** The oxc bindings of the `rolldown` that `tsdown` depends on, or `null` when `tsdown` is not installed. */ +export function loadOxc(): Oxc | null { + if (oxc === undefined) { + try { + oxc = createRequire(import.meta.resolve('tsdown'))('rolldown/utils') as Oxc + } + catch { + oxc = null + } + } + return oxc +} + +const DECLARATION_RE = /\.d\.(?:[^/]+\.)?[cm]?ts$/ +const LANGS: Record = { ts: 'ts', mts: 'ts', cts: 'ts', tsx: 'tsx', jsx: 'jsx', js: 'jsx', mjs: 'jsx', cjs: 'jsx' } + +/** + * `code` parsed by oxc as the language that the extension of `filename` implies, as TypeScript + * parses it: JSX is allowed in JavaScript, and any other extension is TypeScript. + */ +export function parseModule(code: string, filename: string): ParseResult { + const lang = DECLARATION_RE.test(filename) ? 'dts' : LANGS[filename.slice(filename.lastIndexOf('.') + 1)] ?? 'ts' + return loadOxc()!.parseSync(filename, code, { lang, sourceType: 'module' }) +} + +/** The text of a string literal, or of a template literal without substitutions. */ +export function literalText(node: Expression | null | undefined): string | undefined { + if (node?.type === 'Literal' && typeof node.value === 'string') { + return node.value + } + if (node?.type === 'TemplateLiteral' && !node.expressions.length) { + return node.quasis[0]!.value.cooked ?? undefined + } +} + +/** + * Calls `visit` on `node` and then on each node below it, depth first, with its parent. + * Returning `false` skips the nodes below. + */ +export function walk(node: Node, visit: (node: Node, parent: Node | undefined) => boolean | undefined, parent?: Node): void { + if (visit(node, parent) === false) { + return + } + for (const value of Object.values(node)) { + for (const child of Array.isArray(value) ? value : [value]) { + if (child && typeof child === 'object' && typeof (child as { type?: unknown }).type === 'string') { + walk(child as Node, visit, node) + } + } + } +} diff --git a/src/transpile/specifiers.ts b/src/transpile/specifiers.ts index 83feb814..63a6a2cc 100644 --- a/src/transpile/specifiers.ts +++ b/src/transpile/specifiers.ts @@ -1,7 +1,7 @@ -import type ts from 'typescript' +import type { Expression, Statement } from '@oxc-project/types' import { RELATIVE_RE } from '../utils.ts' -import { loadTypescript } from './typescript.ts' +import { literalText, parseModule, walk } from './oxc.ts' const JSX_RE = /\.[jt]sx$/ const DYNAMIC_IMPORT_RE = /\bimport\s*(?:\(|\/[*/])/ @@ -26,13 +26,6 @@ interface Reference extends Specifier { typeOnly: boolean } -/** `code` parsed by TypeScript, as the language that the extension of `filename` implies. */ -export function parseModule(code: string, filename: string): { ts: typeof import('typescript'), sourceFile: ts.SourceFile } { - const { ts } = loadTypescript() - const sourceFile = ts.createSourceFile(filename, code, { languageVersion: ts.ScriptTarget.Latest, jsDocParsingMode: ts.JSDocParsingMode.ParseNone }) - return { ts, sourceFile } -} - function references(code: string, filename: string): Reference[] { if (!filename.endsWith('.vue')) { return scriptReferences(code, filename, 0) @@ -44,39 +37,41 @@ function references(code: string, filename: string): Reference[] { } function scriptReferences(code: string, filename: string, offset: number): Reference[] { - const { ts, sourceFile } = parseModule(code, filename) + const { program } = parseModule(code, filename) const found: Reference[] = [] - const add = (node: ts.StringLiteralLike, typeOnly: boolean) => { - found.push({ specifier: node.text, start: offset + node.getStart(sourceFile), end: offset + node.end, typeOnly }) + const add = (node: Expression, typeOnly: boolean) => { + const specifier = literalText(node) + if (specifier !== undefined) { + found.push({ specifier, start: offset + node.start, end: offset + node.end, typeOnly }) + } } - const visitStatements = (statements: ts.NodeArray) => { - for (const statement of statements) { - if (ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier)) { - add(statement.moduleSpecifier, !!statement.importClause?.isTypeOnly) + const visitStatements = (statements: Statement[]) => { + for (const node of statements) { + const statement = node.type === 'ExportNamedDeclaration' && node.declaration ? node.declaration : node + if (statement.type === 'ImportDeclaration') { + add(statement.source, statement.importKind === 'type') } - else if (ts.isExportDeclaration(statement) && statement.moduleSpecifier && ts.isStringLiteral(statement.moduleSpecifier)) { - add(statement.moduleSpecifier, statement.isTypeOnly) + else if ((statement.type === 'ExportNamedDeclaration' || statement.type === 'ExportAllDeclaration') && statement.source) { + add(statement.source, statement.exportKind === 'type') } - else if (ts.isImportEqualsDeclaration(statement) && ts.isExternalModuleReference(statement.moduleReference) && ts.isStringLiteral(statement.moduleReference.expression)) { - add(statement.moduleReference.expression, statement.isTypeOnly) + else if (statement.type === 'TSImportEqualsDeclaration' && statement.moduleReference.type === 'TSExternalModuleReference') { + add(statement.moduleReference.expression, statement.importKind === 'type') } - else if (ts.isModuleDeclaration(statement) && statement.body && ts.isModuleBlock(statement.body)) { - visitStatements(statement.body.statements) + else if (statement.type === 'TSModuleDeclaration' && statement.id.type !== 'TSQualifiedName' && statement.body) { + visitStatements(statement.body.body) } } } - visitStatements(sourceFile.statements) + visitStatements(program.body) if (DYNAMIC_IMPORT_RE.test(code)) { - const visit = (node: ts.Node): void => { - if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword && node.arguments[0] && ts.isStringLiteralLike(node.arguments[0])) { - add(node.arguments[0], false) + walk(program, (node) => { + if (node.type === 'ImportExpression') { + add(node.source, false) } - else if (ts.isImportTypeNode(node) && ts.isLiteralTypeNode(node.argument) && ts.isStringLiteral(node.argument.literal)) { - add(node.argument.literal, true) + else if (node.type === 'TSImportType') { + add(node.source, true) } - ts.forEachChild(node, visit) - } - visit(sourceFile) + }) } return found.sort((a, b) => a.start - b.start) } diff --git a/src/tsdown/setup.ts b/src/tsdown/setup.ts index f963d3ad..b79ccd4b 100644 --- a/src/tsdown/setup.ts +++ b/src/tsdown/setup.ts @@ -9,12 +9,12 @@ import type { InlineConfig, ResolvedConfig, Rolldown, UserConfig } from 'tsdown' import { analyseSources, directoryPluginName, finishBuild, onBuildError, prepareBuild, preservesJsx, resolveBuild, resolveDirectoryExternal } from '../build/build.ts' import { withoutDirectiveComments } from '../build/directives.ts' import { assertSupportedTypescript, loadDeclarationEngine } from '../build/engine.ts' -import { loadOxc } from '../build/loader.ts' import { resolveModuleOptions, resolveOutDir } 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 { errors, unwrapBuildError, useBuildLogger, warnings } from '../diagnostics.ts' +import { loadOxc } from '../transpile/oxc.ts' import { transpileDir } from '../transpile/transpile-dir.ts' import { findUp, readPackageJson, realpath } from '../utils.ts' import type { PackageJson } from '../utils.ts' diff --git a/test/transpile-dir.spec.ts b/test/transpile-dir.spec.ts index 7a6f8d47..21a8f034 100644 --- a/test/transpile-dir.spec.ts +++ b/test/transpile-dir.spec.ts @@ -5,7 +5,7 @@ import { join } from 'pathe' import { build } from 'tsdown' import { afterAll, beforeAll, describe, expect, it } from 'vitest' -import { loadOxc } from '../src/build/loader.ts' +import { loadOxc } from '../src/transpile/oxc.ts' import { transpileDir } from '../src/transpile/transpile-dir.ts' import type { ExternalImport, TranspileDirOptions } from '../src/transpile/transpile-dir.ts' diff --git a/test/unit.spec.ts b/test/unit.spec.ts index ff001bad..185501d3 100644 --- a/test/unit.spec.ts +++ b/test/unit.spec.ts @@ -27,6 +27,7 @@ import { transformCss } from '../src/transpile/stylesheets.ts' import { contentCache } from '../src/transpile/cache.ts' import { createDeclarationProgram, declarationDiagnosticClass, declarationError, REMAPPED_CODES, restoreImports } from '../src/transpile/declarations.ts' import type { DeclarationEngine } from '../src/transpile/engine.ts' +import { loadOxc } from '../src/transpile/oxc.ts' import { createNativeEngine, installedNativeEngine, platformProblem } from '../src/transpile/native.ts' import { findTypescript, loadTypescript } from '../src/transpile/typescript.ts' import { assertSupportedTypescript, loadDeclarationEngine } from '../src/build/engine.ts' @@ -37,7 +38,7 @@ import { augmentsNuxtTypes, writeSourceTypes, writeTypes } from '../src/build/ty import ts from 'typescript' import { errorCodes, errors, GUIDE_URL, unwrapBuildError, useBuildLogger, warningCodes, warnings } from '../src/diagnostics.ts' import { withoutDirectiveComments } from '../src/build/directives.ts' -import { findModuleCodeIssues, hasLoadIssues, loadOxc, moduleCodeError } from '../src/build/loader.ts' +import { findModuleCodeIssues, hasLoadIssues, moduleCodeError } from '../src/build/loader.ts' import type { ModuleCodeIssue } from '../src/build/loader.ts' import buildCommand from '../src/commands/build.ts' import prepareCommand from '../src/commands/prepare.ts' @@ -1727,10 +1728,10 @@ describe('build plan', () => { `import('./c', { with: { type: 'json' } })`, 'import(`./${name}`)', `import(/* a */ /** b **/ './d')`, - `import(/*${'*//*'.repeat(40)}x)`, + `import(/*${'*//*'.repeat(40)}*/ './e')`, ].join('\n') - expect(moduleSpecifiers(code).map(({ specifier }) => specifier)).toEqual(['./a', './b', './c', './d']) - expect([...valueSpecifiers(code)]).toEqual(['./a', './b', './c', './d']) + expect(moduleSpecifiers(code).map(({ specifier }) => specifier)).toEqual(['./a', './b', './c', './d', './e']) + expect([...valueSpecifiers(code)]).toEqual(['./a', './b', './c', './d', './e']) expect(rewriteSpecifiers(`const load = () => import/* lazy */('./d')`, specifier => `${specifier}.js`)).toBe(`const load = () => import/* lazy */('./d.js')`) }) @@ -1882,7 +1883,7 @@ describe('createDeclarationProgram', () => { it('should restore an import that a type parameter or namespace member of the same name shadows only elsewhere', async () => { const source = `import type { Icon } from '#build/icons'\n` - const shadowed = `export declare function identity(icon: Icon): Icon;\nexport type Pick = T extends Array ? Icon : never;\n` + const shadowed = `export declare function identity(icon: Icon): Icon;\nexport type Pick = T extends Array ? Icon : never;\nexport type Keys = { [Icon in keyof T]: Icon };\n` expect(await restoreImports(shadowed, 'icon.ts', source)).toBe(shadowed) const unrelated = `${shadowed}export interface Props { icon: Icon; }\n` expect(await restoreImports(unrelated, 'icon.ts', source)).toBe(`import type { Icon } from '#build/icons';\n${unrelated}`) From 116c073258d68b68b2afd17139a605a10d9877db Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Sun, 22 Nov 2026 18:03:37 +0000 Subject: [PATCH 3/7] docs: describe installing `@typescript/typescript6` as `typescript` --- docs/4.configuration.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/4.configuration.md b/docs/4.configuration.md index dcdb1ea4..52369111 100644 --- a/docs/4.configuration.md +++ b/docs/4.configuration.md @@ -163,6 +163,12 @@ The native compilers are several times faster, and run in one process for the wh pnpm add -D @typescript/typescript7@npm:typescript@beta ``` +To make TypeScript 7 the module's `tsc` too, install `@typescript/typescript6` as its `typescript`. It provides the JavaScript API of TypeScript 6, which the build, `vue-tsc` 3.3.8 or later and other tools that import `typescript` use: + +```bash [Terminal] +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. 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). From 9343807c36218c3c8f88222e9ddd9fad08fe1c97 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Sun, 22 Nov 2026 20:06:55 +0000 Subject: [PATCH 4/7] fix: normalise the path of the loaded TypeScript API --- src/transpile/typescript.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/transpile/typescript.ts b/src/transpile/typescript.ts index cbe149eb..54b057df 100644 --- a/src/transpile/typescript.ts +++ b/src/transpile/typescript.ts @@ -2,7 +2,7 @@ import { existsSync, readFileSync } from 'node:fs' import { createRequire } from 'node:module' import { fileURLToPath } from 'node:url' import { debuglog } from 'node:util' -import { dirname, join } from 'pathe' +import { dirname, join, normalize } from 'pathe' import { findUp } from '../utils.ts' @@ -55,7 +55,7 @@ function installedPackage(name: string, from: string): InstalledPackage | undefi function withApi({ base, installedAs, version }: InstalledPackage): TypescriptApi | undefined { const require = createRequire(join(base, 'index.js')) - const file = require.resolve(installedAs) + 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 } From 544c9c4c232a1572910536e438fa481a921cc900 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Sun, 22 Nov 2026 20:13:42 +0000 Subject: [PATCH 5/7] fix: leave the checked type out of an `infer` binding's scope when restoring imports --- src/transpile/declarations.ts | 8 +++++--- test/unit.spec.ts | 4 ++++ 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/transpile/declarations.ts b/src/transpile/declarations.ts index 07ae6bf7..c195d8be 100644 --- a/src/transpile/declarations.ts +++ b/src/transpile/declarations.ts @@ -185,7 +185,7 @@ const DECLARED_TYPES = new Set(['TSInterfaceDeclaration', 'TSTypeAliasDeclaratio function unboundNames(declaration: string): string[] { const parents = new Map() const referenced: Array<[name: string, node: Node]> = [] - const declared: Array<[name: string, scope: Node, outside?: Node]> = [] + const declared: Array<[name: string, scope: Node]> = [] const reference = (name: string | undefined, node: Node) => { if (name !== undefined) { referenced.push([name, node]) @@ -241,7 +241,9 @@ function unboundNames(declaration: string): string[] { case 'TSTypeParameter': if (parent?.type === 'TSInferType') { const conditional = ancestor(parent, ({ type }) => type === 'TSConditionalType') - declared.push(conditional?.type === 'TSConditionalType' ? [node.name.name, conditional, conditional.falseType] : [node.name.name, parent]) + for (const scope of conditional?.type === 'TSConditionalType' ? [conditional.extendsType, conditional.trueType] : [parent]) { + declared.push([node.name.name, scope]) + } } else { declared.push([node.name.name, parents.get(parent!)!]) @@ -272,7 +274,7 @@ function unboundNames(declaration: string): string[] { } }) const within = (node: Node, scope: Node) => node === scope || ancestor(node, current => current === scope) !== undefined - return [...new Set(referenced.filter(([name, node]) => !declared.some(([local, scope, outside]) => local === name && within(node, scope) && !(outside && within(node, outside)))).map(([name]) => name))] + return [...new Set(referenced.filter(([name, node]) => !declared.some(([local, scope]) => local === name && within(node, scope))).map(([name]) => name))] } /** The import declarations of `code`, the contents of `source`, or of the scripts of a single-file component. */ diff --git a/test/unit.spec.ts b/test/unit.spec.ts index 185501d3..9a23864a 100644 --- a/test/unit.spec.ts +++ b/test/unit.spec.ts @@ -1893,6 +1893,10 @@ describe('createDeclarationProgram', () => { expect(await restoreImports(outsideNamespace, 'icon.ts', source)).toBe(`import type { Icon } from '#build/icons';\n${outsideNamespace}`) const falseBranch = `export type PickIcon = T extends { icon: infer Icon } ? Icon : Icon;\n` expect(await restoreImports(falseBranch, 'icon.ts', source)).toBe(`import type { Icon } from '#build/icons';\n${falseBranch}`) + const checked = `export type Copy = Icon extends infer Icon ? Icon : never;\n` + expect(await restoreImports(checked, 'icon.ts', source)).toBe(`import type { Icon } from '#build/icons';\n${checked}`) + const inferred = `export type Items = T extends [infer Icon, ...Icon[]] ? Icon : never;\n` + expect(await restoreImports(inferred, 'icon.ts', source)).toBe(inferred) }) it('should reuse the declarations of a cached emit until a file its program read changes', async () => { From bff24a67053ed6215220a6e74598c2bd4c33a514 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Sun, 22 Nov 2026 20:14:14 +0000 Subject: [PATCH 6/7] test: quote the preload path in `NODE_OPTIONS` --- test/engines.spec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/engines.spec.ts b/test/engines.spec.ts index 6882a0a8..f0968c57 100644 --- a/test/engines.spec.ts +++ b/test/engines.spec.ts @@ -133,7 +133,7 @@ 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=${join(repoRoot, 'test/typescript-from.cjs')}`, TYPESCRIPT_FROM: join(dirs.ownTypescript7!, 'package.json') } + 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') } await step('ownTypescript7', tsdown(dirs.ownTypescript7!, [], env)) await step('ownTypescript7:prepare', run('node', [join(dirs.ownTypescript7!, 'builder/src/cli.ts'), 'prepare', dirs.ownTypescript7!], { env })) })()] From 5610af9b49916a97aefbd8f53e826f3b1913a0ab Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Sun, 22 Nov 2026 20:15:14 +0000 Subject: [PATCH 7/7] fix: key the entry declarations by the `typescript` that rolldown-plugin-dts emits with --- src/tsdown/dts.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/tsdown/dts.ts b/src/tsdown/dts.ts index 12f3d1c6..0fe81381 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 } from '../utils.ts' +import { DECLARATION_RE, resolveFrom } from '../utils.ts' /** The `Generator` interface of rolldown-plugin-dts. */ export type DeclarationGenerator = Required['generator']>, object>, 'addFile'>> @@ -186,10 +186,11 @@ async function cacheKey(modules: WorkerModules, dtsOptions: Record