From 4cf7714cd8fcf68671ed6950ebc8cfdf37b7b2fb Mon Sep 17 00:00:00 2001 From: Kevin Deng Date: Wed, 21 Oct 2026 14:23:22 +0900 Subject: [PATCH] feat!: add tsgo API and VFS support (#290) --- README.md | 83 +++-- __snapshots__/tsnapi/index.snapshot.d.ts | 69 ++-- __snapshots__/tsnapi/tsc.snapshot.js | 2 +- package.json | 8 +- pnpm-lock.yaml | 197 +++++----- pnpm-workspace.yaml | 2 +- src/custom-language.ts | 5 +- src/generate.ts | 34 +- src/generator/index.ts | 43 ++- src/generator/tsc.ts | 37 +- src/generator/tsgo.ts | 340 +++++++++++------- src/index.ts | 9 +- src/options.ts | 271 ++++++++------ src/require.ts | 38 +- src/tsc/emit-compiler.ts | 4 +- src/tsc/vue.ts | 28 +- src/tsc/worker.ts | 16 +- src/tsgo.ts | 72 ++++ .../custom-language.test.ts.snap | 36 ++ tests/custom-language.test.ts | 55 +++ tests/fixtures/custom-language/tsconfig.json | 7 + .../tsconfig-no-declaration-map.json | 6 + tests/fixtures/tsgo-vfs/a.ts | 3 + tests/fixtures/tsgo-vfs/b.ts | 1 + tests/fixtures/tsgo-vfs/tsconfig.build.json | 6 + tests/fixtures/tsgo-vfs/tsconfig.json | 7 + tests/generator.test.ts | 340 +++++++++++++++--- tests/index.test.ts | 127 ++++++- tests/source-map.test.ts | 45 ++- tests/tsc.test.ts | 16 +- tests/tsgo.test.ts | 133 +++++++ 31 files changed, 1505 insertions(+), 535 deletions(-) create mode 100644 src/tsgo.ts create mode 100644 tests/fixtures/custom-language/tsconfig.json create mode 100644 tests/fixtures/source-map/tsconfig-no-declaration-map.json create mode 100644 tests/fixtures/tsgo-vfs/a.ts create mode 100644 tests/fixtures/tsgo-vfs/b.ts create mode 100644 tests/fixtures/tsgo-vfs/tsconfig.build.json create mode 100644 tests/fixtures/tsgo-vfs/tsconfig.json create mode 100644 tests/tsgo.test.ts diff --git a/README.md b/README.md index 928a757..81e8511 100644 --- a/README.md +++ b/README.md @@ -18,8 +18,8 @@ npm i -D rolldown-plugin-dts Install the compiler required by your generator: ```bash -npm i -D typescript@^6 # tsc -npm i -D @typescript/native-preview # tsgo, unless TypeScript 7 is installed +npm i -D typescript@^6 # tsc +npm i -D typescript@7.1.0-beta # tsgo API ``` Oxc is provided by Rolldown and needs no additional dependency. @@ -45,20 +45,23 @@ See [rolldown.config.ts](./rolldown.config.ts) for the project's own setup. ## Generators -| Generator | Use it for | Requirement | -| --------- | ------------------------------------------------------- | -------------------------------------------- | -| `tsc` | Full TypeScript compatibility, Vue, and Volar languages | TypeScript 5.x or 6.x | -| `oxc` | Fast generation for isolated declarations | Code compatible with `isolatedDeclarations` | -| `tsgo` | Experimental TypeScript 7 builds | TypeScript 7 or `@typescript/native-preview` | +| Generator | Use it for | Requirement | +| --------- | ------------------------------------------------- | ------------------------------------------- | +| `tsc` | Full TypeScript compatibility | TypeScript 5.x or 6.x | +| `oxc` | Fast generation for isolated declarations | Code compatible with `isolatedDeclarations` | +| `tsgo` | TypeScript Go's asynchronous declaration emit API | TypeScript 7.1 or later | When `generator` is omitted, the plugin selects: 1. `oxc` when `compilerOptions.isolatedDeclarations` is enabled. -2. `tsgo` when TypeScript 7 is installed as `typescript`. +2. `tsgo` when `typescript` exposes `Program.prototype.getDeclarationEmit`. 3. `tsc` otherwise. -Volar-based custom languages always require `tsc`. The `tsgo` generator does -not support custom languages. +Automatic selection only inspects `typescript`. When `tsgo` is selected +explicitly, a module without `getDeclarationEmit` reports an error. + +`generator` also accepts an object implementing the exported `Generator` +interface. ```ts dts({ @@ -72,7 +75,8 @@ dts({ | Option | Description | Default | | ----------------- | ----------------------------------------------------------------------------------------- | ----------------------- | -| `generator` | Declaration generator: `tsc`, `oxc`, or `tsgo`. | Inferred | +| `generator` | Built-in generator name or a custom `Generator` implementation. | Inferred | +| `tsc` | Options for the built-in `tsc` generator. | `{}` | | `entry` | Glob or globs selecting files to emit. Supports `!` negation and paths relative to `cwd`. | Rolldown entries | | `cwd` | Base directory for config discovery, globs, and relative paths. | `process.cwd()` | | `dtsInput` | Treat entry files as existing declarations. | `false` | @@ -86,6 +90,8 @@ dts({ | `sideEffects` | Mark declaration modules as having side effects. | `false` | | `logger` | Logger implementing `info`, `warn`, and `error`. | `console` | +`tsc.*`, `oxc.*`, and `tsgo.*` apply only to their respective generators. + `entry` may include files that are not Rolldown entry points: ```ts @@ -99,17 +105,17 @@ CommonJS-style declaration input. ### TypeScript (`tsc`) -| Option | Description | Default | -| ------------- | ------------------------------------------------------------- | ---------------------------------------- | -| `build` | Use TypeScript build mode and follow project references. | `false` | -| `incremental` | Persist build outputs, including `.tsbuildinfo`, to disk. | Enabled by the matching tsconfig options | -| `vue` | Register the built-in Vue integration using `vue-tsc`. | `false` | -| `parallel` | Run `tsc` or `vue-tsc` in a separate process. | `false` | -| `eager` | Load every file listed by `tsconfig.json`. | `false` | -| `newContext` | Use an isolated compiler cache instead of the shared context. | `false` | -| `emitJs` | Generate declarations for JavaScript files with JSDoc types. | `allowJs` or `checkJs` | - -`incremental` applies to build mode. When disabled, build outputs stay in +| Option | Description | Default | +| ----------------- | ------------------------------------------------------------- | ---------------------------------------- | +| `tsc.build` | Use TypeScript build mode and follow project references. | `false` | +| `tsc.incremental` | Persist build outputs, including `.tsbuildinfo`, to disk. | Enabled by the matching tsconfig options | +| `tsc.parallel` | Run `tsc` or `vue-tsc` in a separate process. | `false` | +| `tsc.eager` | Load every file listed by `tsconfig.json`. | `false` | +| `tsc.newContext` | Use an isolated compiler cache instead of the shared context. | `false` | +| `vue` | Register the built-in Vue integration using `vue-tsc`. | `false` | +| `emitJs` | Generate declarations for JavaScript files with JSDoc types. | `allowJs` or `checkJs` | + +`tsc.incremental` applies to build mode. When disabled, build outputs stay in memory. To invalidate a file in the shared compiler cache: @@ -134,13 +140,19 @@ This API is experimental and may change. ### Oxc -`oxc` accepts -[`IsolatedDeclarationsOptions`](https://oxc.rs/docs/guide/usage/transformer.html). -Use the top-level `sourcemap` option for declaration maps. +Oxc generates declarations from each source file independently. Your code must +be compatible with `isolatedDeclarations`, including explicit type annotations +where required for exported declarations. + +| Option | Description | Default | +| ------------------- | -------------------------------------------------------------------------------------------- | -------------------------------- | +| `oxc.stripInternal` | Omit declarations marked with `/** @internal */`. | `compilerOptions.stripInternal` | +| `sourcemap` | Generate `.d.ts.map` files so editors can navigate from declarations to the original source. | `compilerOptions.declarationMap` | ```ts dts({ generator: 'oxc', + sourcemap: true, oxc: { stripInternal: true, }, @@ -149,14 +161,29 @@ dts({ ### TypeScript Go -`tsgo` is experimental and requires a `tsconfig.json`. It reads compiler -options from that file, so `tsconfigRaw` and `compilerOptions` are ignored. +Experimental. Requires `typescript@7.1.0-beta` or a compatible version and a +`tsconfig.json`. + +| Option | Description | Default | +| ---------------- | ------------------------------------------------------------ | ----------------------------------- | +| `tsgo.moduleUrl` | File URL of the TypeScript package that provides the Go API. | `import.meta.resolve('typescript')` | +| `tsgo.path` | Custom API server executable, passed as `tsserverPath`. | Provided by the selected package | +| `tsgo.vfs` | Supply transformed source code through a virtual filesystem. | `false` | + +- The plugin's current `tsgo` implementation reads compiler settings from the + config file; `tsconfigRaw` and `compilerOptions` do not override them. +- Declaration maps require `compilerOptions.declarationMap: true` in the config + file; setting only the plugin's `sourcemap: true` produces a warning. +- With `tsgo.vfs: true`, source transforms must run before the dts transform hook. + Non-Volar custom languages also require a `toTsFilename` mapping; Vue and + Volar integrations require `tsc`. ```ts dts({ generator: 'tsgo', tsgo: { - path: '/path/to/tsgo', + moduleUrl: import.meta.resolve('typescript'), + vfs: true, }, }) ``` diff --git a/__snapshots__/tsnapi/index.snapshot.d.ts b/__snapshots__/tsnapi/index.snapshot.d.ts index 7bb57a3..8bb4dfe 100644 --- a/__snapshots__/tsnapi/index.snapshot.d.ts +++ b/__snapshots__/tsnapi/index.snapshot.d.ts @@ -9,28 +9,25 @@ export interface CustomLanguage { volarTypeScript?: typeof import("@volar/typescript"); createVolarPlugins?: Parameters<(typeof import("@volar/typescript"))["proxyCreateProgram"]>[2]; } +export interface Generator { + init?: () => void | Promise; + addFile?: (_: string, _: string) => void; + emit: (_: string, _: string) => GeneratorResult | Promise; + dispose?: () => void | Promise; + invalidate?: (_: string) => void; +} +export interface GeneratorResult { + code?: string; + map?: SourceMapInput; + error?: RollupError | string; +} export interface Logger { info: (..._: any[]) => void; warn: (..._: any[]) => void; error: (..._: any[]) => void; } -export interface Options extends GeneralOptions, TscOptions { - oxc?: Omit; - tsgo?: TsgoOptions; - customLanguages?: CustomLanguage[]; -} -// #endregion - -// #region Functions -export declare function createFakeJsPlugin({ sourcemap, cjsDefault, sideEffects }: Pick): Plugin; -export declare function createGeneratePlugin(_: Pick): Plugin; -export declare function dts(_?: Options): Plugin[]; -export declare function resolveOptions({ generator, entry, cwd, dtsInput, emitDtsOnly, tsconfig, tsconfigRaw: overriddenTsconfigRaw, compilerOptions, sourcemap, resolver, cjsDefault, sideEffects, logger, customLanguages, build, incremental, vue, parallel, eager, newContext, emitJs, oxc, tsgo }: Options): OptionsResolved; -// #endregion - -// #region Referenced (internal) -interface GeneralOptions { - generator?: "tsc" | "oxc" | "tsgo"; +export interface Options { + generator?: "tsc" | "oxc" | "tsgo" | Generator; entry?: string | string[]; cwd?: string; dtsInput?: boolean; @@ -43,25 +40,43 @@ interface GeneralOptions { cjsDefault?: boolean; sideEffects?: boolean; logger?: Logger; + vue?: boolean | VueLanguageOptions; + emitJs?: boolean; + tsc?: TscOptions; + oxc?: Omit; + tsgo?: TsgoOptions; + customLanguages?: CustomLanguage[]; } -type OptionsResolved = Overwrite>, { +export interface TscOptions { + build?: boolean; + incremental?: boolean; + parallel?: boolean; + eager?: boolean; + newContext?: boolean; +} +// #endregion + +// #region Functions +export declare function createFakeJsPlugin({ sourcemap, cjsDefault, sideEffects }: Pick): Plugin; +export declare function createGeneratePlugin(_: Pick): Plugin; +export declare function dts(_?: Options): Plugin[]; +export declare function resolveOptions({ generator, entry, cwd, dtsInput, emitDtsOnly, tsconfig, tsconfigRaw: overriddenTsconfigRaw, compilerOptions, sourcemap, resolver, cjsDefault, sideEffects, logger, customLanguages, tsc, vue, emitJs, oxc, tsgo }: Options): OptionsResolved; +// #endregion + +// #region Referenced (internal) +type OptionsResolved = Overwrite>, { entry?: string[]; tsconfig?: string; oxc: IsolatedDeclarationsOptions; tsconfigRaw: TsconfigJson; tsgo: TsgoOptions; languageContext: LanguageContext; + vue: false | VueLanguageOptions; + tsc: Required; }>; -interface TscOptions { - build?: boolean; - incremental?: boolean; - vue?: boolean | VueLanguageOptions; - parallel?: boolean; - eager?: boolean; - newContext?: boolean; - emitJs?: boolean; -} interface TsgoOptions { + moduleUrl?: string; path?: string; + vfs?: boolean; } // #endregion \ No newline at end of file diff --git a/__snapshots__/tsnapi/tsc.snapshot.js b/__snapshots__/tsnapi/tsc.snapshot.js index 45d4caf..05faec9 100644 --- a/__snapshots__/tsnapi/tsc.snapshot.js +++ b/__snapshots__/tsnapi/tsc.snapshot.js @@ -2,5 +2,5 @@ * Generated by tsnapi — public API snapshot of `rolldown-plugin-dts/tsc` */ // #region Re-exports -export { t as tscEmit } from "./tsc-CJA_TTZv.mjs"; +export { t as tscEmit } from "./tsc-DiWSn2Q-.mjs"; // #endregion \ No newline at end of file diff --git a/package.json b/package.json index 941f163..472cb83 100644 --- a/package.json +++ b/package.json @@ -62,17 +62,13 @@ "prepack": "pnpm run build" }, "peerDependencies": { - "@typescript/native-preview": "*", "@volar/typescript": "~2.4.0", "@vue/language-core": "~3.2.0 || ~3.3.0", "rolldown": "^1.2.0", - "typescript": "^5.0.0 || ^6.0.0 || ~7.0.0", + "typescript": "^5.0.0 || ^6.0.0 || ~7.0.0 || ~7.1.0-0", "vue-tsc": "~3.2.0 || ~3.3.0" }, "peerDependenciesMeta": { - "@typescript/native-preview": { - "optional": true - }, "@volar/typescript": { "optional": true }, @@ -103,7 +99,6 @@ "@ts-macro/language-plugin": "catalog:", "@ts-macro/tsc": "catalog:", "@types/node": "catalog:", - "@typescript/native-preview": "catalog:", "@volar/typescript": "catalog:", "@vue/language-core": "catalog:", "arktype": "catalog:", @@ -115,6 +110,7 @@ "tsdown": "catalog:", "tsnapi": "catalog:", "typescript": "catalog:", + "typescript-next": "catalog:", "vitest": "catalog:", "vue": "catalog:", "vue-tsc": "catalog:", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9ed2a2b..7736ae4 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -188,9 +188,6 @@ catalogs: '@types/node': specifier: ^26.6.5 version: 26.6.5 - '@typescript/native-preview': - specifier: npm:typescript@^7.0.2 - version: 7.0.2 '@volar/typescript': specifier: ^2.4.28 version: 2.4.28 @@ -221,6 +218,9 @@ catalogs: typescript: specifier: ^6.0.3 version: 6.0.3 + typescript-next: + specifier: npm:typescript@7.1.0-beta + version: 7.1.0-beta vitest: specifier: ^5.0.3 version: 5.0.3 @@ -303,9 +303,6 @@ importers: '@types/node': specifier: 'catalog:' version: 26.6.5 - '@typescript/native-preview': - specifier: 'catalog:' - version: typescript@7.0.2 '@volar/typescript': specifier: 'catalog:' version: 2.4.28(typescript@6.0.3) @@ -332,13 +329,16 @@ importers: version: 0.3.7 tsdown: specifier: 'catalog:' - version: 0.23.1(@volar/typescript@2.4.28(typescript@6.0.3))(@vue/language-core@3.3.13)(typescript@6.0.3)(typescript@7.0.2)(vue-tsc@3.3.13(typescript@6.0.3)) + version: 0.23.1(@volar/typescript@2.4.28(typescript@6.0.3))(@vue/language-core@3.3.13)(typescript@6.0.3)(vue-tsc@3.3.13(typescript@6.0.3)) tsnapi: specifier: 'catalog:' version: 1.5.0(srvx@1.0.5)(vitest@5.0.3(@types/node@26.6.5)(vite@8.3.4(@types/node@26.6.5)(jiti@2.7.0)(yaml@2.9.1))) typescript: specifier: 'catalog:' version: 6.0.3 + typescript-next: + specifier: 'catalog:' + version: typescript@7.1.0-beta vitest: specifier: 'catalog:' version: 5.0.3(@types/node@26.6.5)(vite@8.3.4(@types/node@26.6.5)(jiti@2.7.0)(yaml@2.9.1)) @@ -1109,122 +1109,128 @@ packages: resolution: {integrity: sha512-0GxiUGqMU0qXJt58cBsiG3DP8lUmBaFo2vChtUX+CT7PnR3v/VGLLrzVP4K9r1lNiZXjHYefMBbPunplr09v6w==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - '@typescript/typescript-aix-ppc64@7.0.2': - resolution: {integrity: sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==} + '@typescript/typescript-aix-ppc64@7.1.0-beta': + resolution: {integrity: sha512-DXDG+jIWxBHGdoO70tcHON33rCnSzsEZj9P13oyf/r/KEGIo6awsdSNVNjAw0uMwEpqRu75IrgCcW58YcVkZHg==} engines: {node: '>=16.20.0'} cpu: [ppc64] os: [aix] - '@typescript/typescript-darwin-arm64@7.0.2': - resolution: {integrity: sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==} + '@typescript/typescript-android-arm64@7.1.0-beta': + resolution: {integrity: sha512-UZx6PxoQavuvaVTrSf3aw0Oy/J/uJpRylipA0kzc038jMvZXh0UtE8vnQp20FqtdgD5bhXZ0aJrRJyoTSUO58Q==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [android] + + '@typescript/typescript-darwin-arm64@7.1.0-beta': + resolution: {integrity: sha512-q7mxblcyX0E7hXsY4k+Q6KWKK5mGmfVq+BDesdTgRVgjodk27aIxER77Zyj9+TgSTlCje8F7+JM6f6hl2BuNdw==} engines: {node: '>=16.20.0'} cpu: [arm64] os: [darwin] - '@typescript/typescript-darwin-x64@7.0.2': - resolution: {integrity: sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==} + '@typescript/typescript-darwin-x64@7.1.0-beta': + resolution: {integrity: sha512-D5EYqG5Wm/guw9+0j8+Mn1Jbr/gfS/VtFTuoH8PJtFbcqeDaQGMulc7SW8q51QG6Y3wGOGX3nbsTOw6fIKWWAA==} engines: {node: '>=16.20.0'} cpu: [x64] os: [darwin] - '@typescript/typescript-freebsd-arm64@7.0.2': - resolution: {integrity: sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==} + '@typescript/typescript-freebsd-arm64@7.1.0-beta': + resolution: {integrity: sha512-9A0XX0tcnH9qPdolSKKzSjTb93dlB0UEcAJbHYEsrFX2fkFNSum9+dvkQQJ9vLc+7vxHetDPujq9Qe6wx+Xhow==} engines: {node: '>=16.20.0'} cpu: [arm64] os: [freebsd] - '@typescript/typescript-freebsd-x64@7.0.2': - resolution: {integrity: sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==} + '@typescript/typescript-freebsd-x64@7.1.0-beta': + resolution: {integrity: sha512-EDf/dBHfY0TxX3NmUTek0hbffeyZlh3+ls6WQW3ICB8vYxwYLFnzg7wkgEUvl9eRlpiJ/nmc2S8arPMzINJ7rg==} engines: {node: '>=16.20.0'} cpu: [x64] os: [freebsd] - '@typescript/typescript-linux-arm64@7.0.2': - resolution: {integrity: sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==} + '@typescript/typescript-linux-arm64@7.1.0-beta': + resolution: {integrity: sha512-hNqQBgQ5b5oGqN76QqbAU6CwYhJZ6iOcWc2kPTUs2OentgpxZktETziH6KIyRFJPaiBncognwn2ZLu3DNhHiWw==} engines: {node: '>=16.20.0'} cpu: [arm64] os: [linux] - '@typescript/typescript-linux-arm@7.0.2': - resolution: {integrity: sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==} + '@typescript/typescript-linux-arm@7.1.0-beta': + resolution: {integrity: sha512-AvN9HmzOQh46G4312ooSgMHhbB7DtnLwg8D9mo324X49B7weMwtJrBG1MxT9IyI8kzDd7YRtW+1hWGun7WG7Qw==} engines: {node: '>=16.20.0'} cpu: [arm] os: [linux] - '@typescript/typescript-linux-loong64@7.0.2': - resolution: {integrity: sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==} + '@typescript/typescript-linux-loong64@7.1.0-beta': + resolution: {integrity: sha512-xbUustlBrFflt2pNEyG5ye+d4WGPc/rfr2xK29MXeobPSw297JqwuKRrvbKM5o3fE/eUM/c+urVm6jQ3IaMVTw==} engines: {node: '>=16.20.0'} cpu: [loong64] os: [linux] - '@typescript/typescript-linux-mips64el@7.0.2': - resolution: {integrity: sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==} + '@typescript/typescript-linux-mips64el@7.1.0-beta': + resolution: {integrity: sha512-fS4/G7/0bXZ3NSq3nBMAXyg65I3tO4S7j08VNQ2g1aNC/qq79gE7Qne1BNjVsjMFfHBVBFjQYoTQCjmVU2iFlg==} engines: {node: '>=16.20.0'} cpu: [mips64el] os: [linux] - '@typescript/typescript-linux-ppc64@7.0.2': - resolution: {integrity: sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==} + '@typescript/typescript-linux-ppc64@7.1.0-beta': + resolution: {integrity: sha512-0upCCxYPX8X6gOwkvfv+Ee7/ufyy7k97mTrGE0e5BxLlnUEa+w+rtgnv2dsKcxFdwdeZYVlZKCqgN/xCBV08+A==} engines: {node: '>=16.20.0'} cpu: [ppc64] os: [linux] - '@typescript/typescript-linux-riscv64@7.0.2': - resolution: {integrity: sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==} + '@typescript/typescript-linux-riscv64@7.1.0-beta': + resolution: {integrity: sha512-0jKU9YRgOPRgiy5V/UWv37kB53PaTpIbwGCbbOMUPPAkrjVRNOIAJaz7Wa7s3H7mdDebX1LopUEPEJR+7Xa7zg==} engines: {node: '>=16.20.0'} cpu: [riscv64] os: [linux] - '@typescript/typescript-linux-s390x@7.0.2': - resolution: {integrity: sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==} + '@typescript/typescript-linux-s390x@7.1.0-beta': + resolution: {integrity: sha512-j+d04s2kxaPQh6DLPb01sknAQfzsrdSZy15jBRHyLEZoaaQ19dVjbFRlkNVvYwUG7ZdP8+y5b/7RmPxdtHUKdQ==} engines: {node: '>=16.20.0'} cpu: [s390x] os: [linux] - '@typescript/typescript-linux-x64@7.0.2': - resolution: {integrity: sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==} + '@typescript/typescript-linux-x64@7.1.0-beta': + resolution: {integrity: sha512-kcD51ihf+pnI5KT4uQQYG04OpwznaZYBlIQhDhl8fflFd27NktxXsUeguxZyvUMyWfum7IF2bBS6Jv7ox0AgFQ==} engines: {node: '>=16.20.0'} cpu: [x64] os: [linux] - '@typescript/typescript-netbsd-arm64@7.0.2': - resolution: {integrity: sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==} + '@typescript/typescript-netbsd-arm64@7.1.0-beta': + resolution: {integrity: sha512-8W85YyoGK+rgGoSU9jJQUpELbrKcZcbdJk2jPNQ6UKDKI7ryPlPFTrV2jCE5RQuv4Tt96hMDTc33s4YfRrLFBA==} engines: {node: '>=16.20.0'} cpu: [arm64] os: [netbsd] - '@typescript/typescript-netbsd-x64@7.0.2': - resolution: {integrity: sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==} + '@typescript/typescript-netbsd-x64@7.1.0-beta': + resolution: {integrity: sha512-iGsTE0ve2PG0AcyZinwAR0LnGEZhu/y4dceS0hZsYCaKdYETvQtvtlNWlmYKempsBr6C7Il7dMXHVk+VFm9u0g==} engines: {node: '>=16.20.0'} cpu: [x64] os: [netbsd] - '@typescript/typescript-openbsd-arm64@7.0.2': - resolution: {integrity: sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==} + '@typescript/typescript-openbsd-arm64@7.1.0-beta': + resolution: {integrity: sha512-Z2FERdHB9fAKI+KGqdWn04O7uNlnB+VYiEm6INE1aZuzzLNd3KBqQ6IpKUJF2ny4GigGU6nVu75XD9tAUODPng==} engines: {node: '>=16.20.0'} cpu: [arm64] os: [openbsd] - '@typescript/typescript-openbsd-x64@7.0.2': - resolution: {integrity: sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==} + '@typescript/typescript-openbsd-x64@7.1.0-beta': + resolution: {integrity: sha512-NVG3qeyCq/rJEOhaRjR3LsWgjrjo5vJW25omVLeHAVnpKIG4pE4cenwwKGR06DiJ1s0QTOymcJeKXMEpsiNBVg==} engines: {node: '>=16.20.0'} cpu: [x64] os: [openbsd] - '@typescript/typescript-sunos-x64@7.0.2': - resolution: {integrity: sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==} + '@typescript/typescript-sunos-x64@7.1.0-beta': + resolution: {integrity: sha512-ovAdoWXEn2B5/fyWG69pLU3FWmQwPWOjQV5TFbcxtpnOv+R3g8ySGHl1NYRq7Lb/GYdFDvaGcZ+SiU7iKuiMsA==} engines: {node: '>=16.20.0'} cpu: [x64] os: [sunos] - '@typescript/typescript-win32-arm64@7.0.2': - resolution: {integrity: sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==} + '@typescript/typescript-win32-arm64@7.1.0-beta': + resolution: {integrity: sha512-lJbo71IEOfL7ZZIZnArRaOLqjn9BAfoSzyUQn0aSjfSpDZL4ru0afUsdBfo6PQEjD6ssdmi0n/RwaPADX6bsvQ==} engines: {node: '>=16.20.0'} cpu: [arm64] os: [win32] - '@typescript/typescript-win32-x64@7.0.2': - resolution: {integrity: sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==} + '@typescript/typescript-win32-x64@7.1.0-beta': + resolution: {integrity: sha512-UKcHvbybY2tDTvFW2b1vwiAvDlIRooo69lh8CXWVhOQejcvpM5+IgbiFW9EIwR5Wi5X/v+BdN7gdWbigBuJ3rw==} engines: {node: '>=16.20.0'} cpu: [x64] os: [win32] @@ -2709,8 +2715,8 @@ packages: engines: {node: '>=14.17'} hasBin: true - typescript@7.0.2: - resolution: {integrity: sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==} + typescript@7.1.0-beta: + resolution: {integrity: sha512-cjWjZAJDsmZzsNC5GwHNlW0YPM65jZa5oR0KyQcYX3KSVIfTvtBq//vewISyatKk4OLi5grZjHhIVE9fdrw1UQ==} engines: {node: '>=16.20.0'} hasBin: true @@ -3617,64 +3623,67 @@ snapshots: '@typescript-eslint/types': 8.71.1 eslint-visitor-keys: 5.0.1 - '@typescript/typescript-aix-ppc64@7.0.2': + '@typescript/typescript-aix-ppc64@7.1.0-beta': + optional: true + + '@typescript/typescript-android-arm64@7.1.0-beta': optional: true - '@typescript/typescript-darwin-arm64@7.0.2': + '@typescript/typescript-darwin-arm64@7.1.0-beta': optional: true - '@typescript/typescript-darwin-x64@7.0.2': + '@typescript/typescript-darwin-x64@7.1.0-beta': optional: true - '@typescript/typescript-freebsd-arm64@7.0.2': + '@typescript/typescript-freebsd-arm64@7.1.0-beta': optional: true - '@typescript/typescript-freebsd-x64@7.0.2': + '@typescript/typescript-freebsd-x64@7.1.0-beta': optional: true - '@typescript/typescript-linux-arm64@7.0.2': + '@typescript/typescript-linux-arm64@7.1.0-beta': optional: true - '@typescript/typescript-linux-arm@7.0.2': + '@typescript/typescript-linux-arm@7.1.0-beta': optional: true - '@typescript/typescript-linux-loong64@7.0.2': + '@typescript/typescript-linux-loong64@7.1.0-beta': optional: true - '@typescript/typescript-linux-mips64el@7.0.2': + '@typescript/typescript-linux-mips64el@7.1.0-beta': optional: true - '@typescript/typescript-linux-ppc64@7.0.2': + '@typescript/typescript-linux-ppc64@7.1.0-beta': optional: true - '@typescript/typescript-linux-riscv64@7.0.2': + '@typescript/typescript-linux-riscv64@7.1.0-beta': optional: true - '@typescript/typescript-linux-s390x@7.0.2': + '@typescript/typescript-linux-s390x@7.1.0-beta': optional: true - '@typescript/typescript-linux-x64@7.0.2': + '@typescript/typescript-linux-x64@7.1.0-beta': optional: true - '@typescript/typescript-netbsd-arm64@7.0.2': + '@typescript/typescript-netbsd-arm64@7.1.0-beta': optional: true - '@typescript/typescript-netbsd-x64@7.0.2': + '@typescript/typescript-netbsd-x64@7.1.0-beta': optional: true - '@typescript/typescript-openbsd-arm64@7.0.2': + '@typescript/typescript-openbsd-arm64@7.1.0-beta': optional: true - '@typescript/typescript-openbsd-x64@7.0.2': + '@typescript/typescript-openbsd-x64@7.1.0-beta': optional: true - '@typescript/typescript-sunos-x64@7.0.2': + '@typescript/typescript-sunos-x64@7.1.0-beta': optional: true - '@typescript/typescript-win32-arm64@7.0.2': + '@typescript/typescript-win32-arm64@7.1.0-beta': optional: true - '@typescript/typescript-win32-x64@7.0.2': + '@typescript/typescript-win32-x64@7.1.0-beta': optional: true '@ungap/structured-clone@1.4.0': {} @@ -5114,7 +5123,7 @@ snapshots: resolve-pkg-maps@1.0.0: {} - rolldown-plugin-dts@0.28.7(@volar/typescript@2.4.28(typescript@6.0.3))(@vue/language-core@3.3.13)(rolldown@1.2.13)(typescript@6.0.3)(typescript@7.0.2)(vue-tsc@3.3.13(typescript@6.0.3)): + rolldown-plugin-dts@0.28.7(@volar/typescript@2.4.28(typescript@6.0.3))(@vue/language-core@3.3.13)(rolldown@1.2.13)(typescript@6.0.3)(vue-tsc@3.3.13(typescript@6.0.3)): dependencies: dts-resolver: 3.0.0 get-tsconfig: 5.0.0-beta.6 @@ -5124,7 +5133,6 @@ snapshots: yuku-codegen: 0.18.1 yuku-parser: 0.18.1 optionalDependencies: - '@typescript/native-preview': typescript@7.0.2 '@volar/typescript': 2.4.28(typescript@6.0.3) '@vue/language-core': 3.3.13 typescript: 6.0.3 @@ -5245,7 +5253,7 @@ snapshots: dependencies: muggle-string: 0.4.1 - tsdown@0.23.1(@volar/typescript@2.4.28(typescript@6.0.3))(@vue/language-core@3.3.13)(typescript@6.0.3)(typescript@7.0.2)(vue-tsc@3.3.13(typescript@6.0.3)): + tsdown@0.23.1(@volar/typescript@2.4.28(typescript@6.0.3))(@vue/language-core@3.3.13)(typescript@6.0.3)(vue-tsc@3.3.13(typescript@6.0.3)): dependencies: cac: 7.0.1 defu: 6.1.7 @@ -5255,7 +5263,7 @@ snapshots: obug: 3.0.0 picomatch: 4.0.7 rolldown: 1.2.13 - rolldown-plugin-dts: 0.28.7(@volar/typescript@2.4.28(typescript@6.0.3))(@vue/language-core@3.3.13)(rolldown@1.2.13)(typescript@6.0.3)(typescript@7.0.2)(vue-tsc@3.3.13(typescript@6.0.3)) + rolldown-plugin-dts: 0.28.7(@volar/typescript@2.4.28(typescript@6.0.3))(@vue/language-core@3.3.13)(rolldown@1.2.13)(typescript@6.0.3)(vue-tsc@3.3.13(typescript@6.0.3)) tinyexec: 1.3.1 tinyglobby: 0.2.17 tree-kill: 1.2.2 @@ -5306,28 +5314,29 @@ snapshots: typescript@6.0.3: {} - typescript@7.0.2: + typescript@7.1.0-beta: optionalDependencies: - '@typescript/typescript-aix-ppc64': 7.0.2 - '@typescript/typescript-darwin-arm64': 7.0.2 - '@typescript/typescript-darwin-x64': 7.0.2 - '@typescript/typescript-freebsd-arm64': 7.0.2 - '@typescript/typescript-freebsd-x64': 7.0.2 - '@typescript/typescript-linux-arm': 7.0.2 - '@typescript/typescript-linux-arm64': 7.0.2 - '@typescript/typescript-linux-loong64': 7.0.2 - '@typescript/typescript-linux-mips64el': 7.0.2 - '@typescript/typescript-linux-ppc64': 7.0.2 - '@typescript/typescript-linux-riscv64': 7.0.2 - '@typescript/typescript-linux-s390x': 7.0.2 - '@typescript/typescript-linux-x64': 7.0.2 - '@typescript/typescript-netbsd-arm64': 7.0.2 - '@typescript/typescript-netbsd-x64': 7.0.2 - '@typescript/typescript-openbsd-arm64': 7.0.2 - '@typescript/typescript-openbsd-x64': 7.0.2 - '@typescript/typescript-sunos-x64': 7.0.2 - '@typescript/typescript-win32-arm64': 7.0.2 - '@typescript/typescript-win32-x64': 7.0.2 + '@typescript/typescript-aix-ppc64': 7.1.0-beta + '@typescript/typescript-android-arm64': 7.1.0-beta + '@typescript/typescript-darwin-arm64': 7.1.0-beta + '@typescript/typescript-darwin-x64': 7.1.0-beta + '@typescript/typescript-freebsd-arm64': 7.1.0-beta + '@typescript/typescript-freebsd-x64': 7.1.0-beta + '@typescript/typescript-linux-arm': 7.1.0-beta + '@typescript/typescript-linux-arm64': 7.1.0-beta + '@typescript/typescript-linux-loong64': 7.1.0-beta + '@typescript/typescript-linux-mips64el': 7.1.0-beta + '@typescript/typescript-linux-ppc64': 7.1.0-beta + '@typescript/typescript-linux-riscv64': 7.1.0-beta + '@typescript/typescript-linux-s390x': 7.1.0-beta + '@typescript/typescript-linux-x64': 7.1.0-beta + '@typescript/typescript-netbsd-arm64': 7.1.0-beta + '@typescript/typescript-netbsd-x64': 7.1.0-beta + '@typescript/typescript-openbsd-arm64': 7.1.0-beta + '@typescript/typescript-openbsd-x64': 7.1.0-beta + '@typescript/typescript-sunos-x64': 7.1.0-beta + '@typescript/typescript-win32-arm64': 7.1.0-beta + '@typescript/typescript-win32-x64': 7.1.0-beta ufo@1.6.4: {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 119b050..989c1cf 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -10,7 +10,6 @@ catalog: '@ts-macro/language-plugin': ^0.3.7 '@ts-macro/tsc': ^0.3.7 '@types/node': ^26.6.5 - '@typescript/native-preview': 'npm:typescript@^7.0.2' '@volar/typescript': ^2.4.28 '@vue/language-core': ^3.3.13 arktype: ^2.2.8 @@ -22,6 +21,7 @@ catalog: tsdown: ^0.23.1 tsnapi: ^1.5.0 typescript: ^6.0.3 + typescript-next: 'npm:typescript@7.1.0-beta' vitest: ^5.0.3 vue: ^3.5.43 vue-tsc: ^3.3.13 diff --git a/src/custom-language.ts b/src/custom-language.ts index 71b2906..8670747 100644 --- a/src/custom-language.ts +++ b/src/custom-language.ts @@ -16,7 +16,10 @@ export interface CustomLanguage { /** Extra file extensions passed to the TypeScript compiler. */ tsFileExtensionInfos?: FileExtensionInfo[] - /** Maps a source filename to the TypeScript filename used for declarations. */ + /** + * Maps a source filename to the TypeScript filename used for declarations. + * Required for custom file extensions. + */ toTsFilename?: (id: string) => string /** @ts-ignore - optional dep */ diff --git a/src/generate.ts b/src/generate.ts index b487c16..30395a4 100644 --- a/src/generate.ts +++ b/src/generate.ts @@ -15,7 +15,7 @@ import { } from './filename.ts' import { createGenerator } from './generator/index.ts' import type { OptionsResolved } from './options.ts' -import type { Plugin } from 'rolldown' +import type { Plugin, PluginContext } from 'rolldown' const debug = createDebug('rolldown-plugin-dts:generate') @@ -40,20 +40,17 @@ export function createGeneratePlugin( | 'cwd' | 'tsconfig' | 'tsconfigRaw' - | 'build' - | 'incremental' | 'oxc' | 'emitDtsOnly' | 'languageContext' - | 'parallel' - | 'eager' + | 'vue' + | 'tsc' | 'tsgo' - | 'newContext' | 'emitJs' | 'sourcemap' >, ): Plugin { - const { entry, cwd, emitDtsOnly, languageContext, eager, emitJs } = options + const { entry, cwd, emitDtsOnly, languageContext, tsc, emitJs } = options const entryIncludes = entry?.filter((p) => p[0] !== '!') const entryIgnores = entry?.filter((p) => p[0] === '!').map((p) => p.slice(1)) const entryMatcher = entry @@ -74,18 +71,28 @@ export function createGeneratePlugin( */ const inputAliasMap = new Map() - const declarationGenerator = createGenerator(options, () => - eager - ? undefined - : Array.from(dtsMap.values()) - .filter((module) => module.isEntry) - .map((module) => module.id), + let loadSource: PluginContext['load'] + const declarationGenerator = createGenerator( + options, + () => + tsc.eager + ? undefined + : Array.from(dtsMap.values()) + .filter((module) => module.isEntry) + .map((module) => module.id), + async (id) => { + await loadSource({ id, resolveDependencies: false }) + // Cached modules may not run their transform hooks again in watch mode. + const module = dtsMap.get(filename_to_dts(id, languageContext)) + if (module) declarationGenerator.addFile?.(module.code, module.id) + }, ) return { name: 'rolldown-plugin-dts:generate', async buildStart(options) { + loadSource = this.load.bind(this) await declarationGenerator.init?.() if (!Array.isArray(options.input)) { @@ -151,6 +158,7 @@ export function createGeneratePlugin( : !!mod?.isEntry const dtsId = filename_to_dts(id, languageContext) dtsMap.set(dtsId, { code, id, isEntry, jsFile }) + declarationGenerator.addFile?.(code, id) debug('register dts source: %s', id) if (isEntry) { diff --git a/src/generator/index.ts b/src/generator/index.ts index 35e83ef..47f6123 100644 --- a/src/generator/index.ts +++ b/src/generator/index.ts @@ -1,4 +1,3 @@ -import path from 'node:path' import { OxcGenerator } from './oxc.ts' import { TscGenerator } from './tsc.ts' import { TsgoGenerator } from './tsgo.ts' @@ -6,18 +5,28 @@ import type { OptionsResolved } from '../options.ts' import type { RollupError, SourceMapInput } from 'rolldown' export interface GeneratorResult { + /** Generated declaration code. */ code?: string + /** Source map for the generated declaration. */ map?: SourceMapInput + /** Error reported through Rolldown when declaration generation fails. */ error?: RollupError | string } +/** A declaration generator used by the dts plugin. */ export interface Generator { + /** Initializes resources at the start of each build. */ init?: () => void | Promise + /** Registers transformed source code before declaration generation. */ + addFile?: (code: string, fileName: string) => void + /** Generates a declaration for a source file. */ emit: ( code: string, fileName: string, ) => GeneratorResult | Promise + /** Releases resources at the end of each build. */ dispose?: () => void | Promise + /** Invalidates cached state for a changed file in watch mode. */ invalidate?: (fileName: string) => void } @@ -26,56 +35,58 @@ export function createGenerator( generator, tsconfig, tsconfigRaw, - build, - incremental, cwd, oxc, languageContext, - parallel, + vue, + tsc, tsgo, - newContext, sourcemap, }: Pick< OptionsResolved, | 'generator' | 'tsconfig' | 'tsconfigRaw' - | 'build' - | 'incremental' | 'cwd' | 'oxc' | 'languageContext' - | 'parallel' + | 'vue' + | 'tsc' | 'tsgo' - | 'newContext' | 'sourcemap' >, getEntries: () => string[] | undefined, + loadSource?: (fileName: string) => Promise, ): Generator { + if (typeof generator !== 'string') return generator + if (generator === 'oxc') { return new OxcGenerator(oxc, languageContext) } if (generator === 'tsgo') { return new TsgoGenerator({ - tsgoPath: tsgo.path!, - rootDir: tsconfig ? path.dirname(tsconfig) : cwd, + moduleUrl: tsgo.moduleUrl, + tsgoPath: tsgo.path, + cwd, tsconfig: tsconfig!, - sourcemap, + vfs: !!tsgo.vfs, languageContext, + loadSource, }) } return new TscGenerator({ tsconfig, tsconfigRaw, - build, - incremental, + build: tsc.build, + incremental: tsc.incremental, cwd, sourcemap, languageContext, - parallel, - newContext, + vue, + parallel: tsc.parallel, + newContext: tsc.newContext, getEntries, }) } diff --git a/src/generator/tsc.ts b/src/generator/tsc.ts index f21a08b..ce45053 100644 --- a/src/generator/tsc.ts +++ b/src/generator/tsc.ts @@ -9,19 +9,27 @@ import { type TscContext, } from '../tsc/context.ts' import type { TscOptions, TscResult } from '../tsc/index.ts' -import type { WorkerRequest, WorkerResponse } from '../tsc/worker.ts' +import type { VueLanguageOptions } from '../tsc/vue.ts' +import type { + WorkerRequest, + WorkerResponse, + WorkerTscOptions, +} from '../tsc/worker.ts' import type { Generator } from './index.ts' const WORKER_URL = import.meta.WORKER_URL || '../tsc/worker.ts' type TscGeneratorOptions = Omit & { + vue: false | VueLanguageOptions parallel: boolean newContext: boolean getEntries: () => string[] | undefined } export class TscGenerator implements Generator { - private options: Omit + private options: Omit + private languageContext: TscOptions['languageContext'] + private vue: false | VueLanguageOptions private parallel: boolean private newContext: boolean private getEntries: () => string[] | undefined @@ -33,9 +41,13 @@ export class TscGenerator implements Generator { parallel, newContext, getEntries, + languageContext, + vue, ...options }: TscGeneratorOptions) { this.options = options + this.languageContext = languageContext + this.vue = vue this.parallel = parallel this.newContext = newContext this.getEntries = getEntries @@ -43,7 +55,7 @@ export class TscGenerator implements Generator { async init(): Promise { if (this.parallel) { - this.worker = createTscWorker() + this.worker = createTscWorker(this.vue) return } @@ -54,11 +66,10 @@ export class TscGenerator implements Generator { } async emit(_code: string, fileName: string): Promise { - const options: TscOptions = { + const options: WorkerTscOptions = { ...this.options, entries: this.getEntries(), id: fileName, - context: this.context, } let result: TscResult @@ -71,7 +82,11 @@ export class TscGenerator implements Generator { if (!this.tscModule) { throw new Error('TscGenerator has not been initialized.') } - result = this.tscModule.tscEmit(options) + result = this.tscModule.tscEmit({ + ...options, + languageContext: this.languageContext, + context: this.context, + }) } if (result.code && RE_JSON.test(fileName)) { @@ -104,11 +119,11 @@ export class TscGenerator implements Generator { } interface TscWorker { - emit: (options: TscOptions) => Promise + emit: (options: WorkerTscOptions) => Promise kill: () => void } -function createTscWorker(): TscWorker { +function createTscWorker(vue: false | VueLanguageOptions): TscWorker { const childProcess = fork(new URL(WORKER_URL, import.meta.url), { stdio: 'inherit', serialization: 'advanced', @@ -146,7 +161,11 @@ function createTscWorker(): TscWorker { new Promise((resolve, reject) => { const id = nextId++ pending.set(id, { resolve, reject }) - childProcess.send({ id, options } satisfies WorkerRequest) + childProcess.send({ + id, + options, + vue: vue || undefined, + } satisfies WorkerRequest) }), kill: () => childProcess.kill(), } diff --git a/src/generator/tsgo.ts b/src/generator/tsgo.ts index bd6a692..982e8ff 100644 --- a/src/generator/tsgo.ts +++ b/src/generator/tsgo.ts @@ -1,174 +1,250 @@ -import { spawn } from 'node:child_process' -import { existsSync } from 'node:fs' -import { mkdtemp, readFile, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' import path from 'node:path' -import { styleText } from 'node:util' import { createDebug } from 'obug' -import { filename_to_dts } from '../filename.ts' -import { isTS70Installed, require, tryResolve } from '../require.ts' +import { RE_DTS, RE_NODE_MODULES } from '../filename.ts' +import { loadTsgoApi, loadTsgoFileSystem } from '../tsgo.ts' import type { LanguageContext } from '../custom-language.ts' -import type { Logger } from '../options.ts' import type { Generator, GeneratorResult } from './index.ts' import type { SourceMapInput } from 'rolldown' +import type * as TsgoApiModule from 'typescript-next/async' +import type { API, Snapshot } from 'typescript-next/async' +import type * as TsgoFsModule from 'typescript-next/fs' const debug = createDebug('rolldown-plugin-dts:tsgo') -const spawnAsync = (...args: Parameters) => - new Promise((resolve, reject) => { - const child = spawn(...args) - child.on('close', (code, signal) => { - if (code === 0) resolve() - else if (signal) - reject(new Error(`tsgo process terminated by signal ${signal}`)) - else reject(new Error(`tsgo process exited with code ${code}`)) - }) - child.on('error', (error) => reject(error)) - }) - -let tsgoPathCache: string | undefined - -export function resolveTsgoPath(logger: Logger): string { - if (tsgoPathCache) return tsgoPathCache - - const pkgName = isTS70Installed() - ? 'typescript' - : '@typescript/native-preview' - - const pkgJsonPath = tryResolve(`${pkgName}/package.json`) - if (!pkgJsonPath) { - throw new Error( - 'TypeScript Go is not installed. Please install the `typescript@7.0` or `@typescript/native-preview` package to use the `tsgo` generator.', - ) - } - - const { version } = require(pkgJsonPath) as { version: string } - logger.info( - `Emit types with ${styleText('underline', `${pkgName}@${version}`)}`, - ) - - const getExePath: any = require( - path.join(path.dirname(pkgJsonPath), 'lib/getExePath.js'), - ) - const tsgoPath = ( - typeof getExePath === 'function' ? getExePath : getExePath.default - )() - if (import.meta.TEST) { - return tsgoPath - } - return (tsgoPathCache = tsgoPath) -} - -export interface TsgoContext { - path: string - dispose: () => Promise -} - export interface TsgoGeneratorOptions { - tsgoPath: string - rootDir: string + moduleUrl?: string + tsgoPath?: string + cwd: string tsconfig: string - sourcemap?: boolean + vfs: boolean languageContext: LanguageContext + loadSource?: (fileName: string) => Promise } export class TsgoGenerator implements Generator { private options: TsgoGeneratorOptions - private context?: TsgoContext + private apiModule?: typeof TsgoApiModule + private fsModule?: typeof TsgoFsModule + private api?: API + private snapshot?: Snapshot + private pendingFiles = new Map() + private openedFiles = new Set() + private loadedSourceFiles = new Set() + private emitQueue: Promise = Promise.resolve() constructor(options: TsgoGeneratorOptions) { this.options = options } async init(): Promise { - const { tsgoPath, rootDir, tsconfig, sourcemap } = this.options - this.context = await runTsgo(tsgoPath, rootDir, tsconfig, sourcemap) + this.pendingFiles.clear() + this.openedFiles.clear() + this.loadedSourceFiles.clear() + this.emitQueue = Promise.resolve() + + this.apiModule = loadTsgoApi(this.options.moduleUrl) + this.fsModule = this.options.vfs + ? loadTsgoFileSystem(this.options.moduleUrl) + : undefined + const { tsgoPath, cwd, tsconfig } = this.options + this.api = new this.apiModule.API({ + cwd, + tsserverPath: tsgoPath, + }) + this.snapshot = await this.api.createSnapshot({ + openProjects: [tsconfig], + }) } - async emit(_code: string, fileName: string): Promise { - const { rootDir, languageContext } = this.options - if (languageContext.isCustomLanguageFile(fileName)) { - return { - error: `tsgo does not support ${path.extname(fileName)} files.`, + addFile(code: string, fileName: string): void { + if (!this.options.vfs) return + this.pendingFiles.set(this.toTsFilename(fileName), code) + } + + emit(code: string, fileName: string): Promise { + if (!this.options.vfs) { + return this.emitFromSnapshot(fileName) + } + + this.addFile(code, fileName) + const result = this.emitQueue.then(async () => { + await this.flushPendingFiles() + await this.loadSourceFiles() + return this.emitFromSnapshot(fileName) + }) + this.emitQueue = result.then( + () => {}, + () => {}, + ) + return result + } + + async dispose(): Promise { + await this.emitQueue + await this.api?.close() + this.api = this.snapshot = undefined + } + + private toTsFilename(fileName: string): string { + return path.resolve(this.options.languageContext.toTsFilename(fileName)) + } + + private async loadSourceFiles(): Promise { + const { loadSource } = this.options + if (!loadSource) return + + // Transforms may introduce new imports. Refresh the program until every + // local source it discovers has been loaded through Rolldown. + while (true) { + const sources = new Set() + for (const project of this.snapshot!.getProjects()) { + for (const name of await project.program.getSourceFileNames()) { + const fileName = path.resolve(name) + if ( + !RE_DTS.test(fileName) && + !RE_NODE_MODULES.test(fileName) && + !this.openedFiles.has(fileName) && + !this.loadedSourceFiles.has(fileName) + ) { + sources.add(fileName) + } + } } + if (!sources.size) return + await Promise.all( + [...sources].map(async (fileName) => { + await loadSource(fileName) + this.loadedSourceFiles.add(fileName) + }), + ) + await this.flushPendingFiles() } - if (!this.context) { + } + + private async flushPendingFiles(): Promise { + if (!this.pendingFiles.size) return + if (!this.fsModule || !this.snapshot) { throw new Error('TsgoGenerator has not been initialized.') } - const dtsPath = path.resolve( - this.context.path, - path.relative( - path.resolve(rootDir), - filename_to_dts(fileName, languageContext), - ), + const entries = [...this.pendingFiles] + this.pendingFiles.clear() + + const openFiles = entries + .map(([fileName]) => fileName) + .filter((fileName) => !this.openedFiles.has(fileName)) + + let nextSnapshot: Snapshot + try { + nextSnapshot = await this.snapshot.update({ + fileSystem: this.fsModule.createFileSystemLayer(entries), + // Filesystem layers mark projects dirty; rebuild them before emitting. + ensurePrograms: true, + ...(openFiles.length ? { openFiles } : undefined), + }) + } catch (error) { + for (const [fileName, code] of entries) { + if (!this.pendingFiles.has(fileName)) { + this.pendingFiles.set(fileName, code) + } + } + throw error + } + + for (const fileName of openFiles) this.openedFiles.add(fileName) + const oldSnapshot = this.snapshot + this.snapshot = nextSnapshot + if (oldSnapshot !== nextSnapshot) await oldSnapshot.dispose() + } + + private async emitFromSnapshot(fileName: string): Promise { + if (!this.apiModule || !this.api || !this.snapshot) { + throw new Error('TsgoGenerator has not been initialized.') + } + + const tsFileName = this.toTsFilename(fileName) + let project = await this.snapshot + .getDefaultProjectForFile(tsFileName) + .catch((error: unknown) => { + throw new Error(mapError(error, tsFileName, fileName), { + cause: error, + }) + }) + // Opening VFS files can select a nearby tsconfig instead of the requested one. + const configuredProject = this.snapshot.getConfiguredProject( + this.options.tsconfig, ) - if (!existsSync(dtsPath)) { - debug('[tsgo]', dtsPath, 'is missing') + if (configuredProject && configuredProject.id !== project?.id) { + const fileNames = await configuredProject.program.getSourceFileNames() + const canonicalFileName = this.api.getCanonicalFileName(tsFileName) + if ( + fileNames.some( + (name) => + this.api!.getCanonicalFileName(path.resolve(name)) === + canonicalFileName, + ) + ) { + project = configuredProject + } + } + if (!project) { return { - error: `tsgo did not generate dts file for ${fileName}, please check your tsconfig.`, + error: `No TypeScript Go project found for ${fileName}. Please check your tsconfig and custom language filename mapping.`, } } - const code = await readFile(dtsPath, 'utf8') + const output = await project.program + .getDeclarationEmit([tsFileName]) + .catch((error: unknown) => { + throw new Error(mapError(error, tsFileName, fileName), { + cause: error, + }) + }) + if (output.emitSkipped && output.diagnostics.length) { + return { + error: mapError( + this.apiModule.formatDiagnostics(output.diagnostics, this.api), + tsFileName, + fileName, + ), + } + } + + let code: string | undefined let map: SourceMapInput | undefined - const mapPath = `${dtsPath}.map` - if (existsSync(mapPath)) { - const mapRaw = await readFile(mapPath, 'utf8') - map = { - ...JSON.parse(mapRaw), - sources: [fileName], + for (const [outputFileName, outputFile] of output.outputFiles) { + if ( + outputFile.sourceFileName && + path.resolve(outputFile.sourceFileName) !== tsFileName + ) { + continue + } + + if (outputFileName.endsWith('.map')) { + map = { + ...JSON.parse(outputFile.text), + sources: [fileName], + } + } else { + code = outputFile.text } } - return { code, map } - } + if (!code) { + debug('[tsgo] declaration output is missing for', tsFileName) + return { + error: `tsgo did not generate a declaration file for ${fileName}. Please check your tsconfig.`, + } + } - async dispose(): Promise { - await this.context?.dispose() - this.context = undefined + return { code, map } } } -export async function runTsgo( - tsgoPath: string, - rootDir: string, - tsconfig: string, - sourcemap?: boolean, -): Promise { - debug('[tsgo] rootDir', rootDir) - debug('[tsgo] using tsgo binary', tsgoPath) - - const tsgoDist = await mkdtemp(path.join(tmpdir(), 'rolldown-plugin-dts-')) - debug('[tsgo] tsgoDist', tsgoDist) - - const args = [ - '--noEmit', - 'false', - '--declaration', - '--emitDeclarationOnly', - '-p', - tsconfig, - '--outDir', - tsgoDist, - '--rootDir', - rootDir, - '--noCheck', - ...(sourcemap ? ['--declarationMap'] : []), - ] - debug('[tsgo] args %o', args) - - await spawnAsync(tsgoPath, args, { stdio: 'inherit' }) - - return { - path: tsgoDist, - async dispose() { - if (debug.enabled) { - debug('[tsgo] skip cleanup of tsgoDist', tsgoDist) - } else { - debug('[tsgo] disposing tsgoDist', tsgoDist) - await rm(tsgoDist, { recursive: true, force: true }).catch(() => {}) - } - }, - } +function mapError( + error: unknown, + tsFileName: string, + fileName: string, +): string { + return String(error).replaceAll(tsFileName, fileName) } diff --git a/src/index.ts b/src/index.ts index e8e2dc9..70fab87 100644 --- a/src/index.ts +++ b/src/index.ts @@ -2,7 +2,12 @@ import { createDebug } from 'obug' import { createDtsInputPlugin } from './dts-input.ts' import { createFakeJsPlugin } from './fake-js/index.ts' import { createGeneratePlugin } from './generate.ts' -import { resolveOptions, type Logger, type Options } from './options.ts' +import { + resolveOptions, + type Logger, + type Options, + type TscOptions, +} from './options.ts' import { createDtsResolvePlugin } from './resolver.ts' import type { Plugin } from 'rolldown' @@ -29,5 +34,7 @@ export { resolveOptions, type Logger, type Options, + type TscOptions, } export type { CustomLanguage } from './custom-language.ts' +export type { Generator, GeneratorResult } from './generator/index.ts' diff --git a/src/options.ts b/src/options.ts index 6553249..4505fa1 100644 --- a/src/options.ts +++ b/src/options.ts @@ -8,9 +8,14 @@ import { } from 'get-tsconfig' import { createDebug } from 'obug' import { LanguageContext, type CustomLanguage } from './custom-language.ts' -import { resolveTsgoPath } from './generator/tsgo.ts' -import { isTS70Installed, requireTSApi } from './require.ts' -import { createVueLanguage, type VueLanguageOptions } from './tsc/vue.ts' +import { requireTSApi } from './require.ts' +import { + createVueLanguage, + createVueLanguageMetadata, + type VueLanguageOptions, +} from './tsc/vue.ts' +import { getDefaultTsgoModuleUrl, loadTsgoApi, tryLoadTsgoApi } from './tsgo.ts' +import type { Generator } from './generator/index.ts' import type { IsolatedDeclarationsOptions } from 'rolldown/experimental' const debug = createDebug('rolldown-plugin-dts:options') @@ -21,23 +26,23 @@ export interface Logger { error: (...args: any[]) => void } -//#region General Options -export interface GeneralOptions { +export interface Options { /** * The generator used to produce declaration files. * * - `'tsc'` supports the full TypeScript type system. * - `'oxc'` is faster but requires code compatible with * [`isolatedDeclarations`](https://www.typescriptlang.org/tsconfig/#isolatedDeclarations). - * - `'tsgo'` uses the experimental TypeScript Go compiler. + * - `'tsgo'` uses the experimental TypeScript Go API. + * - A custom {@link Generator} implementation can be provided directly. * * When omitted, the plugin selects `'oxc'` for `isolatedDeclarations`, - * `'tsgo'` for TypeScript 7, and `'tsc'` otherwise. Volar-based custom - * languages require `'tsc'`. + * `'tsgo'` when TypeScript exposes the declaration emit API, and `'tsc'` + * otherwise. Volar-based custom languages require `'tsc'`. * * @default Inferred from the TypeScript configuration and installed compiler. */ - generator?: 'tsc' | 'oxc' | 'tsgo' + generator?: 'tsc' | 'oxc' | 'tsgo' | Generator /** * Glob pattern(s) that select source files for declaration generation. @@ -77,20 +82,30 @@ export interface GeneralOptions { * A `tsconfig.json` path, resolved relative to {@link cwd}. * * When omitted or `true`, the nearest config is discovered from {@link cwd}. - * Set to `false` to disable config loading. + * Set to `false` to disable config loading. The `tsgo` generator requires a + * config file. */ tsconfig?: string | boolean - /** Raw `tsconfig.json` values merged over the loaded config. */ + /** + * Raw `tsconfig.json` values merged over the loaded config. + * The plugin's current `tsgo` implementation does not apply these overrides + * to the TypeScript program. + */ tsconfigRaw?: Omit /** * Compiler options merged over those loaded from `tsconfig.json`. + * In the plugin's current `tsgo` implementation, these affect plugin behavior + * but do not override the program's compiler options. Set those options in + * the config file instead. */ compilerOptions?: TsconfigJson.CompilerOptions /** * Emits declaration maps (`.d.ts.map`). + * With `tsgo`, source mappings also require `compilerOptions.declarationMap` + * to be enabled in the on-disk config; `sourcemap: true` alone is insufficient. * * @default The value of `compilerOptions.declarationMap`. */ @@ -127,9 +142,54 @@ export interface GeneralOptions { * @default console */ logger?: Logger + + /** + * Registers the built-in Vue language integration using `vue-tsc`. + * + * This is a shortcut for a preconfigured {@link Options.customLanguages} + * entry and requires the `tsc` generator. + * + * @default false + */ + vue?: boolean | VueLanguageOptions + + /** + * Generates declarations for JavaScript files with JSDoc types. + * + * @default Enabled when `allowJs` or `checkJs` is set. + */ + emitJs?: boolean + + /** Options for the built-in `tsc` generator. */ + tsc?: TscOptions + + /** + * Options for the `oxc` generator. + * + * The top-level {@link Options.sourcemap sourcemap} option controls + * declaration maps. + */ + oxc?: Omit + + /** + * **[Experimental]** Options for the TypeScript Go generator. + */ + tsgo?: TsgoOptions + + /** + * Registers non-standard source languages such as Vue or Astro. + * + * If a language is supported via {@link https://volarjs.dev Volar}, + * {@link CustomLanguage.volarTypeScript} and + * {@link CustomLanguage.createVolarPlugins} are both required. Volar + * languages require `tsc`. Non-Volar languages can use `tsgo` together + * with {@link TsgoOptions.vfs `tsgo.vfs`}. + * + * @experimental + */ + customLanguages?: CustomLanguage[] } -//#region tsc Options export interface TscOptions { /** * Uses TypeScript build mode (`tsc -b`) and follows project references. @@ -146,18 +206,10 @@ export interface TscOptions { */ incremental?: boolean - /** - * Registers the built-in Vue language integration using `vue-tsc`. - * - * This is a shortcut for a preconfigured {@link Options.customLanguages} - * entry and requires the `tsc` generator. - * - * @default false - */ - vue?: boolean | VueLanguageOptions - /** * Runs `tsc` or `vue-tsc` in a separate process. + * Custom languages supplied through {@link Options.customLanguages} are not + * supported in the worker process. * * @default false */ @@ -178,59 +230,39 @@ export interface TscOptions { * @default false */ newContext?: boolean - - /** - * Generates declarations for JavaScript files with JSDoc types. - * - * @default Enabled when `allowJs` or `checkJs` is set. - */ - emitJs?: boolean } -/** Configuration accepted by {@link dts}. */ -export interface Options extends GeneralOptions, TscOptions { - //#region Oxc - +export interface TsgoOptions { /** - * Options for the `oxc` generator. + * A `file://` URL of the TypeScript module that provides the TypeScript Go API. * - * The top-level {@link GeneralOptions.sourcemap sourcemap} option controls - * declaration maps. + * Use `import.meta.resolve()` to select an npm alias or another compatible + * TypeScript module. + * + * @default import.meta.resolve('typescript') */ - oxc?: Omit - - //#region TypeScript Go + moduleUrl?: string /** - * **[Experimental]** Options for the `tsgo` generator. - * - * Used when {@link GeneralOptions.generator generator} is `'tsgo'` or - * TypeScript 7 is detected. + * Path passed to the TypeScript Go API as `tsserverPath`. */ - tsgo?: TsgoOptions + path?: string /** - * Registers non-standard source languages such as Vue or Astro. - * - * If a language is supported via {@link https://volarjs.dev Volar}, - * {@link CustomLanguage.volarTypeScript} and - * {@link CustomLanguage.createVolarPlugins} are both required. Volar - * languages require `tsc`; `tsgo` does not support custom languages. + * Supplies Rolldown-transformed source code to the `tsgo` API through a + * virtual filesystem. * - * @experimental + * @default false */ - customLanguages?: CustomLanguage[] -} - -export interface TsgoOptions { - /** Path to a custom `tsgo` executable. */ - path?: string + vfs?: boolean } type Overwrite = Pick> & U export type OptionsResolved = Overwrite< - Required>, + Required< + Omit + >, { entry?: string[] tsconfig?: string @@ -238,6 +270,8 @@ export type OptionsResolved = Overwrite< tsconfigRaw: TsconfigJson tsgo: TsgoOptions languageContext: LanguageContext + vue: false | VueLanguageOptions + tsc: Required } > @@ -258,14 +292,9 @@ export function resolveOptions({ sideEffects = false, logger = console, customLanguages, + tsc, - // tsc - build = false, - incremental = false, vue = false, - parallel = false, - eager = false, - newContext = false, emitJs, oxc, @@ -288,8 +317,6 @@ export function resolveOptions({ ...compilerOptions, } - incremental ||= - compilerOptions.incremental || !!compilerOptions.tsBuildInfoFile sourcemap ??= !!compilerOptions.declarationMap compilerOptions.declarationMap = sourcemap @@ -299,50 +326,85 @@ export function resolveOptions({ compilerOptions, } - customLanguages ||= [] - if (vue) { - customLanguages.push(createVueLanguage(typeof vue === 'object' ? vue : {})) + const tscOptions: Required = { + build: tsc?.build ?? false, + incremental: + tsc?.incremental ?? + !!(compilerOptions.incremental || compilerOptions.tsBuildInfoFile), + parallel: tsc?.parallel ?? false, + eager: tsc?.eager ?? false, + newContext: tsc?.newContext ?? false, } - const languageContext = new LanguageContext(customLanguages) - if (customLanguages.length) { - // Custom languages that rely on Volar can only be handled by the `tsc` - // generator; Volar-free languages also work with `oxc`, but `tsgo` does not - // support custom languages at all. - if (languageContext.isUsingVolar()) { - requireTSApi( - 'custom languages', - '. Custom languages (including the `vue` option) require the TypeScript API.', + const hasCustomLanguages = !!customLanguages?.length + customLanguages = [...(customLanguages || [])] + const vueOptions: false | VueLanguageOptions = vue + ? typeof vue === 'object' + ? vue + : {} + : false + if (vueOptions) { + if (generator && generator !== 'tsc') { + throw new Error( + 'Volar-based custom languages (including the `vue` option) require the `tsc` generator.', ) + } + customLanguages.push( + tscOptions.parallel + ? createVueLanguageMetadata() + : createVueLanguage(vueOptions), + ) + } + + const languageContext = new LanguageContext(customLanguages) + const isUsingVolar = !!vueOptions || languageContext.isUsingVolar() + + oxc ||= {} + tsgo ||= {} + const defaultTsgoModuleUrl = getDefaultTsgoModuleUrl() + tsgo.moduleUrl ??= defaultTsgoModuleUrl + tsgo.vfs ??= false - if (generator && generator !== 'tsc') { - throw new Error( - 'Volar-based custom languages (including the `vue` option) require the `tsc` generator.', - ) - } - generator = 'tsc' - } else if (generator === 'tsgo') { - throw new Error('The `tsgo` generator does not support custom languages.') + if (isUsingVolar) { + if (generator && generator !== 'tsc') { + throw new Error( + 'Volar-based custom languages (including the `vue` option) require the `tsc` generator.', + ) } + generator = 'tsc' } if (!generator) { if (compilerOptions.isolatedDeclarations) { generator = 'oxc' - } else if (isTS70Installed()) { - if (customLanguages.length) { - throw new Error( - "TypeScript 7.0 is installed, but the `tsgo` generator does not support custom languages. Enable `isolatedDeclarations` or set `generator: 'oxc'` to use Oxc instead, or install TypeScript 6.0 or below.", - ) - } - generator = 'tsgo' } else { - generator = 'tsc' + generator = tryLoadTsgoApi(defaultTsgoModuleUrl) ? 'tsgo' : 'tsc' } } - oxc ||= {} - tsgo ||= {} + if (generator === 'tsc' && tscOptions.parallel && hasCustomLanguages) { + throw new Error( + 'The `tsc.parallel` option does not support `customLanguages`. Disable `tsc.parallel` or use the built-in `vue` option for Vue.', + ) + } + + if (isUsingVolar) { + requireTSApi( + vueOptions ? 'Vue' : 'custom languages', + vueOptions ? '.' : '. Custom languages require the TypeScript API.', + ) + } + + if ( + customLanguages.length && + !isUsingVolar && + generator === 'tsgo' && + !tsgo.vfs + ) { + throw new Error( + "The `tsgo` generator requires `tsgo.vfs: true` to process custom languages. Enable VFS, use `generator: 'oxc'`, or use a compatible `tsc` installation.", + ) + } if (generator === 'tsc') { requireTSApi( @@ -358,10 +420,15 @@ export function resolveOptions({ if (!warnedTsgo) { warnedTsgo = true logger.warn( - 'TypeScript 7.0 does not yet have a stable API and is experimental. Some options will be unavailable.', + 'TypeScript Go is experimental. Some options will be unavailable.', + ) + } + loadTsgoApi(tsgo.moduleUrl, logger) + if (sourcemap && !resolvedTsconfig?.compilerOptions?.declarationMap) { + logger.warn( + "The `tsgo` generator requires `compilerOptions.declarationMap: true` in your tsconfig file for source mappings. The plugin's `sourcemap` option does not override the tsconfig.", ) } - tsgo.path ??= resolveTsgoPath(logger) } oxc.stripInternal ??= !!compilerOptions.stripInternal // @ts-expect-error omitted in user options @@ -388,12 +455,8 @@ export function resolveOptions({ cjsDefault, sideEffects, - // tsc - build, - incremental, - parallel, - eager, - newContext, + vue: vueOptions, + tsc: tscOptions, emitJs, languageContext, diff --git a/src/require.ts b/src/require.ts index 72f0b2f..145e003 100644 --- a/src/require.ts +++ b/src/require.ts @@ -15,23 +15,42 @@ export const require: NodeJS.Require = import.meta.TEST const debug = createDebug('rolldown-plugin-dts:utils') -function tryRequire(moduleName: string): T | undefined { +export function tryRequire(moduleName: string): T | undefined { try { return require(moduleName) } catch {} } -export function tryResolve(id: string): string | undefined { +export function tryResolve( + id: string, + options?: { paths?: string[] }, +): string | undefined { try { - return require.resolve(id) + return require.resolve(id, options) } catch {} } let _ts: typeof import('typescript') | undefined -export function isTS70Installed(): boolean { - const tsPkg = tryRequire<{ version: string }>('typescript/package.json') - return tsPkg?.version.slice(0, 3) === '7.0' +export interface PackageInfo { + name: string + version: string + packageJsonPath: string +} + +export function getPackageInfo(name: string): PackageInfo | undefined { + const packageJsonPath = tryResolve(`${name}/package.json`) + if (!packageJsonPath) return + + const pkg = tryRequire<{ version?: string }>(packageJsonPath) + if (!pkg?.version) return + + return { name, version: pkg.version, packageJsonPath } +} + +export function isNativeTypeScriptVersion(version: string): boolean { + const major = +version.split('.', 1)[0] + return Number.isFinite(major) && major >= 7 } export function requireTSApi( @@ -40,9 +59,10 @@ export function requireTSApi( ): typeof import('typescript') { if (_ts) return _ts - if (isTS70Installed()) { + const tsPkg = getPackageInfo('typescript') + if (tsPkg && isNativeTypeScriptVersion(tsPkg.version)) { throw new Error( - `TypeScript 7.0 is not supported when using ${mode}. Please use TypeScript 6.0 or below${message}`, + `TypeScript ${tsPkg.version} does not provide the classic TypeScript API required by ${mode}. Please use TypeScript 6.0 or below${message}`, ) } @@ -51,7 +71,7 @@ export function requireTSApi( ts = require('typescript') } catch (cause) { throw new Error( - `TypeScript is not installed. Please install the \`typescript\` package (v7.0 is not yet supported)${ + `TypeScript is not installed. Please install the \`typescript\` package (v6.0 or below for the classic API)${ message }`, { cause }, diff --git a/src/tsc/emit-compiler.ts b/src/tsc/emit-compiler.ts index b747eaa..64740a6 100644 --- a/src/tsc/emit-compiler.ts +++ b/src/tsc/emit-compiler.ts @@ -139,7 +139,7 @@ function createTsProgramFromParsedConfig({ if (hasReferences) { throw new Error( - `[rolldown-plugin-dts] Unable to load ${id}; You have "references" in your tsconfig file. Perhaps you want to add \`dts: { build: true }\` in your config?`, + `[rolldown-plugin-dts] Unable to load ${id}; You have "references" in your tsconfig file. Perhaps you want to add \`dts: { tsc: { build: true } }\` in your config?`, ) } @@ -204,7 +204,7 @@ export function tscEmitCompiler(tscOptions: TscOptions): TscResult { dtsCode = file.getFullText() } else { console.warn( - '[rolldown-plugin-dts] Warning: Failed to emit declaration file. Please try to enable `eager` option (`dts.eager` for tsdown).', + '[rolldown-plugin-dts] Warning: Failed to emit declaration file. Please try to enable `tsc.eager` option (`dts.tsc.eager` for tsdown).', ) } } diff --git a/src/tsc/vue.ts b/src/tsc/vue.ts index 8640a2e..6b614af 100644 --- a/src/tsc/vue.ts +++ b/src/tsc/vue.ts @@ -11,6 +11,22 @@ export interface VueLanguageOptions { vueCompilerOptions?: Partial } +export function createVueLanguageMetadata(): CustomLanguage { + return { + extensionPatterns: [RE_VUE], + tsFileExtensionInfos: [ + { + extension: 'vue', + isMixedContent: true, + scriptKind: 7 satisfies ts.ScriptKind.Deferred, + }, + ], + toTsFilename(id: string): string { + return id.replace(RE_VUE, '.vue.ts') + }, + } +} + export function createVueLanguage( userOptions: VueLanguageOptions = {}, ): CustomLanguage { @@ -44,21 +60,11 @@ export function createVueLanguage( } return { - extensionPatterns: [RE_VUE], - tsFileExtensionInfos: [ - { - extension: 'vue', - isMixedContent: true, - scriptKind: 7 satisfies ts.ScriptKind.Deferred, - }, - ], + ...createVueLanguageMetadata(), volarTypeScript, createVolarPlugins(ts, options) { return [getLanguagePlugin(ts, options)] }, - toTsFilename(id: string): string { - return id.replace(RE_VUE, '.vue.ts') - }, } } diff --git a/src/tsc/worker.ts b/src/tsc/worker.ts index 5871017..53f42a3 100644 --- a/src/tsc/worker.ts +++ b/src/tsc/worker.ts @@ -1,10 +1,14 @@ import process from 'node:process' import { LanguageContext } from '../custom-language.ts' +import { createVueLanguage, type VueLanguageOptions } from './vue.ts' import { tscEmit, type TscOptions, type TscResult } from './index.ts' +export type WorkerTscOptions = Omit + export interface WorkerRequest { id: number - options: TscOptions + options: WorkerTscOptions + vue?: VueLanguageOptions } export interface WorkerResponse { @@ -13,15 +17,17 @@ export interface WorkerResponse { error?: unknown } +let languageContext: LanguageContext | undefined + process.on('message', (request: WorkerRequest) => { let response: WorkerResponse try { + languageContext ||= new LanguageContext( + request.vue ? [createVueLanguage(request.vue)] : [], + ) const options: TscOptions = { ...request.options, - // Structured clone preserves the data but not the class prototype. - languageContext: new LanguageContext( - request.options.languageContext.languages, - ), + languageContext, } response = { id: request.id, result: tscEmit(options) } } catch (error) { diff --git a/src/tsgo.ts b/src/tsgo.ts new file mode 100644 index 0000000..ec4a043 --- /dev/null +++ b/src/tsgo.ts @@ -0,0 +1,72 @@ +import path from 'node:path' +import { fileURLToPath, pathToFileURL } from 'node:url' +import { styleText } from 'node:util' +import { require, tryRequire, tryResolve } from './require.ts' +import type { Logger } from './options.ts' +import type * as TsgoApiModule from 'typescript-next/async' +import type * as TsgoFsModule from 'typescript-next/fs' + +export function getDefaultTsgoModuleUrl(): string | undefined { + try { + // Tests replace the CommonJS resolver to exercise different installations. + if (import.meta.TEST) { + const modulePath = tryResolve('typescript') + return modulePath && pathToFileURL(modulePath).href + } + return import.meta.resolve('typescript') + } catch {} +} + +export function tryLoadTsgoApi( + moduleUrl: string | undefined, +): typeof TsgoApiModule | undefined { + if (moduleUrl == null) return + + const modulePath = getTsgoModulePath(moduleUrl) + const apiPath = tryResolve('typescript/async', { + paths: [path.dirname(modulePath)], + }) + const api = apiPath ? tryRequire(apiPath) : undefined + return api?.Program?.prototype.getDeclarationEmit ? api : undefined +} + +export function loadTsgoApi( + moduleUrl: string | undefined = getDefaultTsgoModuleUrl(), + logger?: Logger, +): typeof TsgoApiModule { + const api = tryLoadTsgoApi(moduleUrl) + if (!api) { + throw new Error( + `The TypeScript module${moduleUrl ? ` at ${moduleUrl}` : ''} does not provide the tsgo \`getDeclarationEmit\` API. Please install \`typescript@7.1.0-beta\` or set \`tsgo.moduleUrl\` to a compatible module, for example \`import.meta.resolve('typescript-next')\`.`, + ) + } + + if (logger && moduleUrl) { + logger.info( + `Emit types with TypeScript Go from ${styleText('underline', moduleUrl)}`, + ) + } + return api +} + +export function loadTsgoFileSystem( + moduleUrl: string | undefined = getDefaultTsgoModuleUrl(), +): typeof TsgoFsModule { + if (moduleUrl == null) throw new Error('No TypeScript module found.') + const modulePath = getTsgoModulePath(moduleUrl) + return require( + require.resolve('typescript/fs', { paths: [path.dirname(modulePath)] }), + ) +} + +function getTsgoModulePath(moduleUrl: string): string { + try { + if (!moduleUrl.startsWith('file://')) throw new Error('Expected file://') + return fileURLToPath(moduleUrl) + } catch (cause) { + throw new Error( + "The `tsgo.moduleUrl` option must be a valid file:// URL. Use `import.meta.resolve('typescript')` or `import.meta.resolve('typescript-next')`.", + { cause }, + ) + } +} diff --git a/tests/__snapshots__/custom-language.test.ts.snap b/tests/__snapshots__/custom-language.test.ts.snap index e2f516c..f4b19cd 100644 --- a/tests/__snapshots__/custom-language.test.ts.snap +++ b/tests/__snapshots__/custom-language.test.ts.snap @@ -36,6 +36,25 @@ export { foo }; " `; +exports[`volar > custom without volar (tsgo vfs) 1`] = ` +"// main.d.ts +//#region tests/fixtures/custom-language/foo.custom.d.ts +export declare const foo: string; +//#endregion +//# sourceMappingURL=main.d.ts.map +// main.d.ts.map +{"version":3,"file":"main.d.ts","names":[],"sources":["../tests/fixtures/custom-language/foo.custom"],"mappings":";qBACa"} +// main.js +//#region tests/fixtures/custom-language/foo.custom +const foo = "bar"; +//#endregion +export { foo }; + +//# sourceMappingURL=main.js.map +// main.js.map +{"version":3,"file":"main.js","names":[],"sources":[],"mappings":""}" +`; + exports[`volar > ts-macro > ts-macro w/ ts-compiler 1`] = ` "// main.d.ts //#region tests/fixtures/ts-macro/main.d.ts @@ -85,6 +104,23 @@ declare const _default: typeof __VLS_export; export { _default as default };" `; +exports[`volar > vue > vue-sfc w/ parallel ts-compiler 1`] = ` +"// main.d.ts +//#region tests/fixtures/vue-sfc/App.vue.d.ts +type __VLS_Props = { + foo: string; +}; +declare global { + interface Window { + foo: string; + } +} +declare const __VLS_export: import("@vue/runtime-core").DefineComponent<__VLS_Props, {}, {}, {}, {}, import("@vue/runtime-core").ComponentOptionsMixin, import("@vue/runtime-core").ComponentOptionsMixin, {}, string, import("@vue/runtime-core").PublicProps, Readonly<__VLS_Props> & Readonly<{}>, {}, {}, {}, {}, string, import("@vue/runtime-core").ComponentProvideOptions, false, {}, any>; +declare const _default: typeof __VLS_export; +//#endregion +export { _default as App };" +`; + exports[`volar > vue > vue-sfc w/ ts-compiler 1`] = ` "// main.d.ts //#region tests/fixtures/vue-sfc/App.vue.d.ts diff --git a/tests/custom-language.test.ts b/tests/custom-language.test.ts index 3e7d6d3..39f8a54 100644 --- a/tests/custom-language.test.ts +++ b/tests/custom-language.test.ts @@ -8,6 +8,7 @@ import type { CustomLanguage } from '../src/custom-language.ts' const { dirname } = import.meta const require = createRequire(import.meta.url) +const tsgoModuleUrl = import.meta.resolve('typescript-next') const external = ['vue', /^@vue/] @@ -31,6 +32,27 @@ describe('volar', () => { expect(snapshot).toMatchSnapshot() }) + test('vue-sfc w/ parallel ts-compiler', async () => { + const root = path.resolve(dirname, 'fixtures/vue-sfc') + const { snapshot } = await rolldownBuild( + path.resolve(root, 'main.ts'), + [ + dts({ + emitDtsOnly: true, + vue: { + vueCompilerOptions: { fallthroughAttributes: false }, + }, + tsc: { parallel: true }, + compilerOptions: { + isolatedDeclarations: false, + }, + }), + ], + { external }, + ) + expect(snapshot).toMatchSnapshot() + }) + test('vue-sfc w/ ts-compiler w/ vueCompilerOptions in tsconfig', async () => { const root = path.resolve(dirname, 'fixtures/vue-sfc-fallthrough') const { snapshot } = await rolldownBuild( @@ -150,6 +172,39 @@ describe('volar', () => { expect(snapshot).toMatchSnapshot() }, ) + + test('custom without volar (tsgo vfs)', async () => { + const root = path.resolve(dirname, 'fixtures/custom-language') + const RE_CUSTOM = /\.custom$/ + const { snapshot } = await rolldownBuild(path.resolve(root, 'main.ts'), [ + { + name: 'convert-custom-to-ts', + transform: { + order: 'pre', + filter: { id: RE_CUSTOM }, + handler: (code) => ({ + code: code.replace('', ''), + moduleType: 'ts', + }), + }, + }, + dts({ + generator: 'tsgo', + tsconfig: path.resolve(root, 'tsconfig.json'), + sourcemap: true, + tsgo: { moduleUrl: tsgoModuleUrl, vfs: true }, + customLanguages: [ + { + extensionPatterns: [RE_CUSTOM], + toTsFilename: (id) => id.replace(RE_CUSTOM, '.custom.ts'), + }, + ], + }), + ]) + + expect(snapshot).toMatchSnapshot() + expect(snapshot).toContain('declare const foo: string') + }) }) function createTsMacroLanguage(): CustomLanguage { diff --git a/tests/fixtures/custom-language/tsconfig.json b/tests/fixtures/custom-language/tsconfig.json new file mode 100644 index 0000000..7a8efd6 --- /dev/null +++ b/tests/fixtures/custom-language/tsconfig.json @@ -0,0 +1,7 @@ +{ + "compilerOptions": { + "declaration": true, + "declarationMap": true + }, + "include": ["main.ts"] +} diff --git a/tests/fixtures/source-map/tsconfig-no-declaration-map.json b/tests/fixtures/source-map/tsconfig-no-declaration-map.json new file mode 100644 index 0000000..89b834a --- /dev/null +++ b/tests/fixtures/source-map/tsconfig-no-declaration-map.json @@ -0,0 +1,6 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "declarationMap": false + } +} diff --git a/tests/fixtures/tsgo-vfs/a.ts b/tests/fixtures/tsgo-vfs/a.ts new file mode 100644 index 0000000..f342cd4 --- /dev/null +++ b/tests/fixtures/tsgo-vfs/a.ts @@ -0,0 +1,3 @@ +import { valueB } from './b.ts' + +export const pair = { valueB } diff --git a/tests/fixtures/tsgo-vfs/b.ts b/tests/fixtures/tsgo-vfs/b.ts new file mode 100644 index 0000000..cc27e1a --- /dev/null +++ b/tests/fixtures/tsgo-vfs/b.ts @@ -0,0 +1 @@ +export const valueB: number = 1 diff --git a/tests/fixtures/tsgo-vfs/tsconfig.build.json b/tests/fixtures/tsgo-vfs/tsconfig.build.json new file mode 100644 index 0000000..da28e37 --- /dev/null +++ b/tests/fixtures/tsgo-vfs/tsconfig.build.json @@ -0,0 +1,6 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "stripInternal": true + } +} diff --git a/tests/fixtures/tsgo-vfs/tsconfig.json b/tests/fixtures/tsgo-vfs/tsconfig.json new file mode 100644 index 0000000..11efb61 --- /dev/null +++ b/tests/fixtures/tsgo-vfs/tsconfig.json @@ -0,0 +1,7 @@ +{ + "compilerOptions": { + "allowImportingTsExtensions": true, + "declaration": true + }, + "include": ["*.ts"] +} diff --git a/tests/generator.test.ts b/tests/generator.test.ts index e921bb5..b200abb 100644 --- a/tests/generator.test.ts +++ b/tests/generator.test.ts @@ -1,48 +1,109 @@ import { createRequire } from 'node:module' +import path from 'node:path' +import { pathToFileURL } from 'node:url' import { afterEach, describe, expect, test, vi } from 'vitest' import { resolveOptions, type Options } from '../src/options.ts' import { mockRequire } from '../src/require.ts' import type { CustomLanguage } from '../src/custom-language.ts' +import type { Generator } from '../src/index.ts' const realRequire = createRequire(import.meta.url) -const MOCK_TSGO_BIN = '/mock/bin/tsgo' -const TSGO_PKGS = ['typescript', '@typescript/native-preview'] +const MOCK_ROOT = path.join(path.parse(import.meta.dirname).root, 'mock') +const TYPESCRIPT_MODULE_PATH = path.join( + MOCK_ROOT, + 'typescript/lib/typescript.js', +) +const TYPESCRIPT_MODULE_URL = pathToFileURL(TYPESCRIPT_MODULE_PATH).href +const TYPESCRIPT_PACKAGE_JSON_PATH = path.join( + MOCK_ROOT, + 'typescript/package.json', +) +const TYPESCRIPT_API_PATH = path.join( + MOCK_ROOT, + 'typescript/dist/api/async/api.js', +) +const CUSTOM_MODULE_PATH = path.join(MOCK_ROOT, 'xxx/lib/index.js') +const CUSTOM_MODULE_URL = pathToFileURL(CUSTOM_MODULE_PATH).href +const CUSTOM_API_PATH = path.join(MOCK_ROOT, 'xxx/dist/api/async/api.js') -type Installed = [ts: 6 | 7 | false, tsgo: boolean] +function normalizePath(fileName: string): string { + return fileName.replaceAll('\\', '/') +} + +type PackageVersion = 6 | 7 | 'api' | 'next' | false +type Installed = [ts: PackageVersion, custom: PackageVersion] + +function getVersion(version: Exclude): string { + if (version === 6) return '6.0.0' + if (version === 7) return '7.0.2' + if (version === 'api') return '6.0.0' + return '7.1.0-dev.20260830.1' +} -function mockInstalled([ts, tsgo]: Installed) { +function mockInstalled([ts, custom]: Installed) { const fake = ((rawId: string) => { - // On Windows, `path.join` in `resolveTsgoPath` turns the fake `/mock/...` - // paths into backslash form; normalize for comparison only. - const id = rawId.replaceAll('\\', '/') + const id = normalizePath(rawId) switch (id) { case 'typescript': { if (!ts) throw new Error(`Cannot find module 'typescript'`) - return {} + return ts === 6 || ts === 'api' ? { createProgram() {} } : {} } + case normalizePath(TYPESCRIPT_MODULE_PATH): + if (!ts) throw new Error(`Cannot find module '${id}'`) + return ts === 6 || ts === 'api' ? { createProgram() {} } : {} + case normalizePath(CUSTOM_MODULE_PATH): + if (!custom) throw new Error(`Cannot find module '${id}'`) + return custom === 6 || custom === 'api' ? { createProgram() {} } : {} case 'typescript/package.json': - case '/mock/typescript/package.json': { + case normalizePath(TYPESCRIPT_PACKAGE_JSON_PATH): { if (!ts) throw new Error(`Cannot find module '${id}'`) - return { version: ts === 6 ? '6.0.0' : '7.0.0' } - } - case '@typescript/native-preview/package.json': - case '/mock/@typescript/native-preview/package.json': { - if (!tsgo) throw new Error(`Cannot find module '${id}'`) - return { version: '7.0.0-preview' } + return { version: getVersion(ts) } } } - if (TSGO_PKGS.some((pkg) => id === `/mock/${pkg}/lib/getExePath.js`)) { - return { default: () => MOCK_TSGO_BIN } + const apiSource = + id === normalizePath(TYPESCRIPT_API_PATH) + ? 'typescript' + : id === normalizePath(CUSTOM_API_PATH) + ? 'xxx' + : undefined + if (apiSource) { + const installed = apiSource === 'typescript' ? ts : custom + return { + API: class {}, + Program: + installed === 'api' || installed === 'next' + ? class { + getDeclarationEmit() {} + } + : class {}, + } } // vue / Volar related modules are loaded for real return realRequire(rawId) }) as NodeJS.Require fake.resolve = ((id: string, options?: { paths?: string[] }) => { - if (TSGO_PKGS.some((pkg) => id === `${pkg}/package.json`)) { - const installed = id.startsWith('typescript') ? ts : tsgo - if (!installed) throw new Error(`Cannot find module '${id}'`) - return `/mock/${id}` + if (id === 'typescript') { + if (!ts) throw new Error(`Cannot find module '${id}'`) + return TYPESCRIPT_MODULE_PATH + } + if (id === 'typescript/package.json') { + if (!ts) throw new Error(`Cannot find module '${id}'`) + return TYPESCRIPT_PACKAGE_JSON_PATH + } + if (id === 'typescript/async') { + const customRoot = normalizePath(path.join(MOCK_ROOT, 'xxx')) + const isCustom = options?.paths?.some((value) => { + const normalized = normalizePath(value) + return ( + normalized === customRoot || normalized.startsWith(`${customRoot}/`) + ) + }) + const installed = isCustom ? custom : ts + if (!installed || installed === 6) { + throw new Error(`Cannot find module '${id}'`) + } + return isCustom ? CUSTOM_API_PATH : TYPESCRIPT_API_PATH } return realRequire.resolve(id, options) }) as NodeJS.RequireResolve @@ -67,17 +128,19 @@ interface Fixture { isolatedDecl?: boolean oxc?: Options['oxc'] vue?: boolean + tsc?: Options['tsc'] customLanguages?: Options['customLanguages'] tsgo?: Options['tsgo'] generator?: Options['generator'] tsconfig?: string expected: string + selectedPackage?: string isThrow?: boolean } function formatTitle(fixture: Fixture): string { - const [ts, preview] = fixture.installed ?? [6, false] - const env = [ts ? `ts${ts}` : 'no-ts', preview && 'preview'] + const [ts, custom] = fixture.installed ?? [6, false] + const env = [ts ? `ts${ts}` : 'no-ts', custom && 'custom'] .filter(Boolean) .join('+') @@ -86,6 +149,8 @@ function formatTitle(fixture: Fixture): string { if (fixture.oxc !== undefined) parts.push(`oxc=${JSON.stringify(fixture.oxc)}`) if (fixture.vue) parts.push('vue') + if (fixture.tsc !== undefined) + parts.push(`tsc=${JSON.stringify(fixture.tsc)}`) if (fixture.customLanguages) parts.push( `langs=[${fixture.customLanguages @@ -104,14 +169,42 @@ function formatTitle(fixture: Fixture): string { } describe('resolve generator', () => { + test('preserves a custom generator without compiler inference', () => { + mockInstalled([false, false]) + const generator: Generator = { + emit: () => ({ code: '' }), + } + + expect(resolveOptions({ generator, tsconfig: false }).generator).toBe( + generator, + ) + }) + + test('resolves tsc.incremental from compiler options and allows overrides', () => { + mockInstalled([6, false]) + expect( + resolveOptions({ + tsconfig: false, + compilerOptions: { incremental: true }, + }).tsc.incremental, + ).toBe(true) + expect( + resolveOptions({ + tsconfig: false, + compilerOptions: { incremental: true }, + tsc: { incremental: false }, + }).tsc.incremental, + ).toBe(false) + }) + const fixtures: Fixture[] = [ //#region inference (no custom language) { expected: 'tsc' }, // TS 6 installed by default { installed: [6, false], expected: 'tsc' }, - // native-preview does not participate in inference - { installed: [6, true], expected: 'tsc' }, + // A custom module does not participate in inference. + { installed: [6, 'next'], expected: 'tsc' }, { - installed: [false, true], + installed: [false, 'next'], expected: 'TypeScript is not installed', isThrow: true, }, @@ -120,10 +213,29 @@ describe('resolve generator', () => { expected: 'TypeScript is not installed', isThrow: true, }, - { installed: [7, false], tsconfig: TSCONFIG, expected: 'tsgo' }, - { installed: [7, true], tsconfig: TSCONFIG, expected: 'tsgo' }, { installed: [7, false], + tsconfig: TSCONFIG, + expected: 'classic TypeScript API required by tsc', + isThrow: true, + }, + { + // A custom module is only used when configured through moduleUrl. + installed: [7, 'next'], + tsconfig: TSCONFIG, + expected: 'classic TypeScript API required by tsc', + isThrow: true, + }, + { installed: ['next', false], tsconfig: TSCONFIG, expected: 'tsgo' }, + // API capability, rather than the package version, selects tsgo. + { installed: ['api', false], tsconfig: TSCONFIG, expected: 'tsgo' }, + { + installed: [7, false], + expected: 'classic TypeScript API required by tsc', + isThrow: true, + }, + { + installed: ['next', false], expected: 'The `tsgo` generator requires a tsconfig file', isThrow: true, }, @@ -132,18 +244,35 @@ describe('resolve generator', () => { //#region isolatedDeclarations inference { installed: [false, false], isolatedDecl: true, expected: 'oxc' }, { isolatedDecl: true, expected: 'oxc' }, - // isolatedDeclarations takes priority over TS 7.0 tsgo inference - { installed: [7, true], isolatedDecl: true, expected: 'oxc' }, + // isolatedDeclarations takes priority over native compiler inference + { installed: ['next', 'next'], isolatedDecl: true, expected: 'oxc' }, //#endregion - //#region oxc / tsgo settings do not select the generator + //#region generator settings do not select the generator { oxc: {}, expected: 'tsc' }, { oxc: { stripInternal: true }, expected: 'tsc' }, { tsgo: {}, expected: 'tsc' }, { tsgo: { path: '/bin/tsgo' }, expected: 'tsc' }, + { tsgo: { vfs: true }, expected: 'tsc' }, + { + installed: [6, 'next'], + tsgo: { moduleUrl: CUSTOM_MODULE_URL }, + expected: 'tsc', + }, + { + installed: ['next', false], + tsc: { parallel: true }, + tsconfig: TSCONFIG, + expected: 'tsgo', + }, { oxc: {}, isolatedDecl: true, expected: 'oxc' }, - // TS 7.0 inference still applies with tsgo settings present - { installed: [7, false], tsgo: {}, tsconfig: TSCONFIG, expected: 'tsgo' }, + // Native compiler inference still applies with tsgo settings present. + { + installed: ['next', false], + tsgo: { path: '/bin/tsgo' }, + tsconfig: TSCONFIG, + expected: 'tsgo', + }, //#endregion //#region explicit generator @@ -157,57 +286,96 @@ describe('resolve generator', () => { { installed: [7, false], generator: 'tsc', - expected: 'TypeScript 7.0 is not supported when using tsc', + expected: 'does not provide the classic TypeScript API required by tsc', isThrow: true, }, // explicit generator takes priority over inference { generator: 'tsc', isolatedDecl: true, expected: 'tsc' }, + { + generator: 'tsc', + tsc: { + build: true, + incremental: true, + eager: true, + newContext: true, + }, + expected: 'tsc', + }, { installed: [false, false], generator: 'oxc', expected: 'oxc' }, { generator: 'oxc', expected: 'oxc' }, - { installed: [7, true], generator: 'oxc', expected: 'oxc' }, + { installed: [7, 'next'], generator: 'oxc', expected: 'oxc' }, { generator: 'oxc', oxc: { stripInternal: true }, expected: 'oxc' }, { - installed: [7, false], + installed: ['next', false], generator: 'tsgo', tsconfig: TSCONFIG, expected: 'tsgo', + selectedPackage: TYPESCRIPT_MODULE_URL, }, { - installed: [6, true], + installed: ['next', 'next'], generator: 'tsgo', tsconfig: TSCONFIG, expected: 'tsgo', + selectedPackage: TYPESCRIPT_MODULE_URL, }, { - installed: [6, true], + installed: [7, 'next'], generator: 'tsgo', - isolatedDecl: true, + tsgo: { moduleUrl: CUSTOM_MODULE_URL }, tsconfig: TSCONFIG, expected: 'tsgo', + selectedPackage: CUSTOM_MODULE_URL, }, - // tsgo binary is resolved at options-resolution time { + installed: [6, 'next'], generator: 'tsgo', + tsgo: { moduleUrl: CUSTOM_MODULE_URL }, tsconfig: TSCONFIG, - expected: 'TypeScript Go is not installed', + expected: 'tsgo', + selectedPackage: CUSTOM_MODULE_URL, + }, + { + installed: [6, 7], + generator: 'tsgo', + tsgo: { moduleUrl: CUSTOM_MODULE_URL }, + tsconfig: TSCONFIG, + expected: CUSTOM_MODULE_URL, isThrow: true, }, { - installed: [false, false], + installed: [7, false], generator: 'tsgo', tsconfig: TSCONFIG, - expected: 'TypeScript Go is not installed', + expected: 'install `typescript@7.1.0-beta`', isThrow: true, }, - // a custom tsgo path skips binary resolution { installed: [false, false], generator: 'tsgo', - tsgo: { path: '/bin/tsgo' }, + tsconfig: TSCONFIG, + expected: 'The TypeScript module does not provide', + isThrow: true, + }, + // A custom API server path still requires a package that provides the API. + { + installed: [6, 'next'], + generator: 'tsgo', + tsgo: { + moduleUrl: CUSTOM_MODULE_URL, + path: '/bin/custom-tsserver', + }, tsconfig: TSCONFIG, expected: 'tsgo', }, - // the tsconfig requirement is checked before binary resolution + { + installed: [false, false], + generator: 'tsgo', + tsgo: { path: '/bin/custom-tsserver' }, + tsconfig: TSCONFIG, + expected: 'The TypeScript module does not provide', + isThrow: true, + }, { generator: 'tsgo', expected: 'The `tsgo` generator requires a tsconfig file', @@ -226,7 +394,7 @@ describe('resolve generator', () => { { installed: [7, false], vue: true, - expected: 'TypeScript 7.0 is not supported when using Vue', + expected: 'does not provide the classic TypeScript API required by Vue', isThrow: true, }, { @@ -241,10 +409,18 @@ describe('resolve generator', () => { expected: 'require the `tsc` generator', isThrow: true, }, + { + installed: ['next', false], + vue: true, + generator: 'tsgo', + expected: 'require the `tsc` generator', + isThrow: true, + }, { vue: true, generator: 'tsc', expected: 'tsc' }, + { vue: true, tsc: { parallel: true }, expected: 'tsc' }, { vue: true, isolatedDecl: true, expected: 'tsc' }, // tsgo settings are ignored when tsc is selected - { installed: [6, true], vue: true, tsgo: {}, expected: 'tsc' }, + { installed: [6, 'next'], vue: true, tsgo: {}, expected: 'tsc' }, //#endregion //#region Volar-based custom language (requires tsc) @@ -258,7 +434,8 @@ describe('resolve generator', () => { { installed: [7, false], customLanguages: [volarLanguage], - expected: 'TypeScript 7.0 is not supported when using custom languages', + expected: + 'does not provide the classic TypeScript API required by custom languages', isThrow: true, }, { @@ -273,6 +450,12 @@ describe('resolve generator', () => { expected: 'require the `tsc` generator', isThrow: true, }, + { + customLanguages: [volarLanguage], + tsc: { parallel: true }, + expected: 'does not support `customLanguages`', + isThrow: true, + }, { customLanguages: [volarLanguage], isolatedDecl: true, expected: 'tsc' }, { customLanguages: [volarLanguage, plainLanguage], @@ -281,7 +464,7 @@ describe('resolve generator', () => { }, //#endregion - //#region non-Volar custom language (oxc allowed, tsgo not) + //#region non-Volar custom language { customLanguages: [plainLanguage], expected: 'tsc' }, { installed: [false, false], @@ -293,26 +476,48 @@ describe('resolve generator', () => { { installed: [7, false], customLanguages: [plainLanguage], - expected: - 'TypeScript 7.0 is installed, but the `tsgo` generator does not support custom languages', + tsconfig: TSCONFIG, + expected: 'classic TypeScript API required by tsc', + isThrow: true, + }, + { + installed: ['next', false], + customLanguages: [plainLanguage], + tsconfig: TSCONFIG, + expected: 'requires `tsgo.vfs: true`', isThrow: true, }, + { + installed: ['next', false], + customLanguages: [plainLanguage], + tsgo: { vfs: true }, + tsconfig: TSCONFIG, + expected: 'tsgo', + }, { customLanguages: [plainLanguage], generator: 'tsc', expected: 'tsc' }, + { + customLanguages: [plainLanguage], + generator: 'tsc', + tsc: { parallel: true }, + expected: 'does not support `customLanguages`', + isThrow: true, + }, { customLanguages: [plainLanguage], generator: 'oxc', expected: 'oxc' }, { customLanguages: [plainLanguage], generator: 'tsgo', - expected: 'The `tsgo` generator does not support custom languages', + expected: 'requires `tsgo.vfs: true`', isThrow: true, }, { + installed: [6, 'next'], customLanguages: [plainLanguage], generator: 'tsgo', - isolatedDecl: true, - expected: 'The `tsgo` generator does not support custom languages', - isThrow: true, + tsgo: { moduleUrl: CUSTOM_MODULE_URL, vfs: true }, + tsconfig: TSCONFIG, + expected: 'tsgo', }, - // tsgo settings are silently ignored with custom languages + // tsgo settings do not select a generator. { customLanguages: [plainLanguage], tsgo: {}, expected: 'tsc' }, //#endregion ] @@ -328,11 +533,13 @@ describe('resolve generator', () => { isolatedDecl, oxc, vue, + tsc, customLanguages, tsgo, generator, tsconfig, expected, + selectedPackage, isThrow, }, ) => { @@ -345,6 +552,7 @@ describe('resolve generator', () => { }, oxc, vue, + tsc: tsc && { ...tsc }, // resolveOptions may push into the array (e.g. vue), so avoid // sharing the same array between fixtures customLanguages: customLanguages && [...customLanguages], @@ -359,7 +567,23 @@ describe('resolve generator', () => { const resolved = resolveOptions(options) expect(resolved.generator).toBe(expected) if (expected === 'tsgo') { - expect(resolved.tsgo.path).toBe(tsgo?.path ?? MOCK_TSGO_BIN) + expect(resolved.tsgo.path).toBe(tsgo?.path) + } + expect(resolved.tsgo.moduleUrl).toBe( + tsgo?.moduleUrl ?? (installed[0] ? TYPESCRIPT_MODULE_URL : undefined), + ) + expect(resolved.tsgo.vfs).toBe(tsgo?.vfs ?? false) + expect(resolved.tsc).toStrictEqual({ + build: tsc?.build ?? false, + incremental: tsc?.incremental ?? false, + parallel: tsc?.parallel ?? false, + eager: tsc?.eager ?? false, + newContext: tsc?.newContext ?? false, + }) + if (selectedPackage) { + expect(logger.info.mock.calls.flat().join(' ')).toContain( + selectedPackage, + ) } }, ) diff --git a/tests/index.test.ts b/tests/index.test.ts index 6e40710..4831585 100644 --- a/tests/index.test.ts +++ b/tests/index.test.ts @@ -1,11 +1,13 @@ +import { createRequire } from 'node:module' import path from 'node:path' import { fileURLToPath } from 'node:url' import { normalizePath, rolldownBuild } from '@sxzz/test-utils' import { describe, expect, test } from 'vitest' -import { resolveTsgoPath } from '../src/generator/tsgo.ts' -import { dts } from '../src/index.ts' +import { dts, type Generator } from '../src/index.ts' const dirname = path.dirname(fileURLToPath(import.meta.url)) +const require = createRequire(import.meta.url) +const tsgoModuleUrl = import.meta.resolve('typescript-next') test('basic', async () => { const { snapshot } = await rolldownBuild( @@ -15,6 +17,38 @@ test('basic', async () => { expect(snapshot).toMatchSnapshot() }) +test('custom generator', async () => { + const calls: string[] = [] + const generator: Generator = { + init() { + calls.push('init') + }, + addFile(_code, fileName) { + calls.push(`addFile:${path.basename(fileName)}`) + }, + emit(_code, fileName) { + calls.push(`emit:${path.basename(fileName)}`) + return { code: 'export declare const custom: true' } + }, + dispose() { + calls.push('dispose') + }, + } + + const { snapshot } = await rolldownBuild( + path.resolve(dirname, 'fixtures/basic.ts'), + [dts({ generator, tsconfig: false, emitDtsOnly: true })], + ) + + expect(snapshot).toContain('declare const custom: true') + expect(calls).toStrictEqual([ + 'init', + 'addFile:basic.ts', + 'emit:basic.ts', + 'dispose', + ]) +}) + test('tsx', async () => { const { snapshot } = await rolldownBuild( path.resolve(dirname, 'fixtures/tsx.tsx'), @@ -669,17 +703,18 @@ test('infer false branch', async () => { }) test('tsgo with custom path', async () => { - const tsgoPath = resolveTsgoPath({ - info: () => {}, - warn: () => {}, - error: () => {}, - }) + const getExePath: any = require( + path.join(path.dirname(fileURLToPath(tsgoModuleUrl)), 'getExePath.js'), + ) + const tsserverPath = ( + typeof getExePath === 'function' ? getExePath : getExePath.default + )() const { snapshot } = await rolldownBuild( path.resolve(dirname, 'fixtures/basic.ts'), [ dts({ generator: 'tsgo', - tsgo: { path: tsgoPath }, + tsgo: { moduleUrl: tsgoModuleUrl, path: tsserverPath }, tsconfig: path.resolve(dirname, 'fixtures/basic.tsconfig.json'), }), ], @@ -687,6 +722,82 @@ test('tsgo with custom path', async () => { expect(snapshot).toMatchSnapshot() }) +test('tsgo vfs uses transformed source code', async () => { + const input = path.resolve(dirname, 'fixtures/basic.ts') + const tsconfig = path.resolve(dirname, 'fixtures/basic.tsconfig.json') + const transform = { + name: 'transform-before-dts', + transform: { + order: 'pre' as const, + handler(code: string, id: string) { + if (id !== input) return + return code.replace( + 'export const foo: number = 42', + "export const foo: 'transformed' = 'transformed'", + ) + }, + }, + } + + const disk = await rolldownBuild(input, [ + transform, + dts({ + generator: 'tsgo', + tsgo: { moduleUrl: tsgoModuleUrl }, + tsconfig, + emitDtsOnly: true, + }), + ]) + const virtual = await rolldownBuild(input, [ + transform, + dts({ + generator: 'tsgo', + tsconfig, + emitDtsOnly: true, + tsgo: { moduleUrl: tsgoModuleUrl, vfs: true }, + }), + ]) + + expect(disk.snapshot).toContain('foo: number') + expect(disk.snapshot).not.toContain("foo: 'transformed'") + expect(virtual.snapshot).toContain("foo: 'transformed'") +}) + +test.each([false, true])( + 'tsgo vfs infers types from transformed dependencies (circular: %s)', + async (circular) => { + const root = path.resolve(dirname, 'fixtures/tsgo-vfs') + const dependency = path.join(root, 'b.ts') + const { chunks } = await rolldownBuild(path.join(root, 'a.ts'), [ + { + name: 'transform-dependency-before-dts', + transform: { + order: 'pre', + handler(_code, id) { + if (id !== dependency) return + return ` + ${circular ? "import { pair } from './a.ts'; export function getPair() { return pair }" : ''} + export const valueB: string = 'transformed' + ` + }, + }, + }, + dts({ + generator: 'tsgo', + tsconfig: path.join(root, 'tsconfig.json'), + tsgo: { moduleUrl: tsgoModuleUrl, vfs: true }, + }), + ]) + + const declaration = chunks + .filter((chunk) => chunk.type === 'chunk') + .find((chunk) => chunk.fileName === 'a.d.ts') + expect(declaration).toBeDefined() + expect(declaration!.code).toContain('valueB: string') + expect(declaration!.code).not.toContain('valueB: number') + }, +) + // https://github.com/sxzz/rolldown-plugin-dts/issues/136 test('css.ts files', async () => { const root = path.resolve(dirname, 'fixtures/css-ts') diff --git a/tests/source-map.test.ts b/tests/source-map.test.ts index 58d50d3..b55f815 100644 --- a/tests/source-map.test.ts +++ b/tests/source-map.test.ts @@ -3,7 +3,7 @@ import path from 'node:path' import { SourceMapConsumer } from '@jridgewell/source-map' import { expectFilesSnapshot, rolldownBuild } from '@sxzz/test-utils' import { build } from 'rolldown' -import { beforeAll, expect, test } from 'vitest' +import { beforeAll, expect, test, vi } from 'vitest' import { dts } from '../src/index.ts' const tempDir = path.join(import.meta.dirname, 'temp') @@ -12,6 +12,7 @@ const tsconfig = path.resolve( import.meta.dirname, 'fixtures/source-map/tsconfig.json', ) +const tsgoModuleUrl = import.meta.resolve('typescript-next') beforeAll(async () => { await rm(tempDir, { recursive: true, force: true }) @@ -82,6 +83,7 @@ test('tsgo', async () => { plugins: [ dts({ generator: 'tsgo', + tsgo: { moduleUrl: tsgoModuleUrl }, tsconfig, sourcemap: true, emitDtsOnly: true, @@ -95,6 +97,47 @@ test('tsgo', async () => { validateSourceMap(sourcemap) }) +test.each([true, false])( + 'tsgo sourcemap with tsconfig declarationMap=%s', + async (declarationMap) => { + const dir = path.join(tempDir, `source-map-tsgo-${declarationMap}`) + const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() } + await build({ + input, + plugins: [ + dts({ + generator: 'tsgo', + tsgo: { moduleUrl: tsgoModuleUrl }, + tsconfig: declarationMap + ? tsconfig + : path.resolve( + import.meta.dirname, + 'fixtures/source-map/tsconfig-no-declaration-map.json', + ), + sourcemap: true, + emitDtsOnly: true, + logger, + }), + ], + output: { dir }, + write: true, + }) + + const warning = + "The `tsgo` generator requires `compilerOptions.declarationMap: true` in your tsconfig file for source mappings. The plugin's `sourcemap` option does not override the tsconfig." + if (declarationMap) { + expect(logger.warn).not.toHaveBeenCalledWith(warning) + const sourcemap = await readFile( + path.resolve(dir, 'index.d.ts.map'), + 'utf8', + ) + validateSourceMap(sourcemap) + } else { + expect(logger.warn).toHaveBeenCalledWith(warning) + } + }, +) + // https://github.com/rolldown/tsdown/issues/975 test('empty dts chunk does not break output sourcemap', async () => { const warnings: string[] = [] diff --git a/tests/tsc.test.ts b/tests/tsc.test.ts index 6df100f..ef948bb 100644 --- a/tests/tsc.test.ts +++ b/tests/tsc.test.ts @@ -33,7 +33,7 @@ describe('tsc', () => { test('parallel', async () => { const { snapshot } = await rolldownBuild( path.resolve(dirname, 'fixtures/basic.ts'), - [dts({ generator: 'tsc', parallel: true })], + [dts({ generator: 'tsc', tsc: { parallel: true } })], ) expect(snapshot).toContain('export declare const foo: number;') }) @@ -60,7 +60,7 @@ describe('tsc', () => { dts({ tsconfig: path.resolve(root, 'tsconfig.json'), compilerOptions: { isolatedDeclarations: false }, - build: true, + tsc: { build: true }, }), ], ) @@ -76,7 +76,7 @@ describe('tsc', () => { dts({ tsconfig: path.resolve(root, 'tsconfig.json'), sourcemap: true, - build: false, + tsc: { build: false }, }), ], {}, @@ -100,7 +100,7 @@ describe('tsc', () => { dts({ tsconfig: path.resolve(root, 'tsconfig.json'), sourcemap: true, - build: true, + tsc: { build: true }, }), ], {}, @@ -124,7 +124,7 @@ describe('tsc', () => { [ dts({ tsconfig: path.resolve(root, 'tsconfig.react.json'), - build: true, + tsc: { build: true }, sourcemap: true, emitDtsOnly: true, }), @@ -148,7 +148,7 @@ describe('tsc', () => { [ dts({ tsconfig: path.resolve(root, 'tsconfig.json'), - build: true, + tsc: { build: true }, sourcemap: true, emitDtsOnly: true, }), @@ -180,7 +180,7 @@ describe('tsc', () => { dts({ tsconfig: path.resolve(root, 'tsconfig.json'), compilerOptions: { isolatedDeclarations: false }, - build: true, + tsc: { build: true }, }), ], ) @@ -213,7 +213,7 @@ describe('tsc', () => { dts({ tsconfig: path.resolve(root, 'tsconfig.json'), compilerOptions: { isolatedDeclarations: false }, - build: true, + tsc: { build: true }, }), ], ) diff --git a/tests/tsgo.test.ts b/tests/tsgo.test.ts new file mode 100644 index 0000000..b216afc --- /dev/null +++ b/tests/tsgo.test.ts @@ -0,0 +1,133 @@ +import { readFile } from 'node:fs/promises' +import path from 'node:path' +import { fileURLToPath } from 'node:url' +import { afterEach, expect, test } from 'vitest' +import { LanguageContext } from '../src/custom-language.ts' +import { TsgoGenerator } from '../src/generator/tsgo.ts' +import { loadTsgoApi, loadTsgoFileSystem } from '../src/tsgo.ts' + +const root = path.resolve(import.meta.dirname, 'fixtures/tsgo-vfs') +const moduleUrl = import.meta.resolve('typescript-next') +const tsconfig = path.join(root, 'tsconfig.json') +const a = path.join(root, 'a.ts') +const b = path.join(root, 'b.ts') + +let generator: TsgoGenerator | undefined + +afterEach(async () => { + await generator?.dispose() + generator = undefined +}) + +function createGenerator(): TsgoGenerator { + return new TsgoGenerator({ + moduleUrl, + cwd: root, + tsconfig, + vfs: true, + languageContext: new LanguageContext([]), + }) +} + +test.each([ + '', + fileURLToPath(moduleUrl), + './node_modules/typescript-next/lib/version.cjs', + 'typescript-next', + 'https://example.com/typescript.js', + 'file:/typescript/lib/version.cjs', + 'file:///invalid%xx', +])('rejects invalid moduleUrl %j', async (invalidModuleUrl) => { + const message = 'The `tsgo.moduleUrl` option must be a valid file:// URL' + expect(() => loadTsgoApi(invalidModuleUrl)).toThrow(message) + expect(() => loadTsgoFileSystem(invalidModuleUrl)).toThrow(message) + await expect( + new TsgoGenerator({ + moduleUrl: invalidModuleUrl, + cwd: root, + tsconfig, + vfs: false, + languageContext: new LanguageContext([]), + }).init(), + ).rejects.toThrow(message) +}) + +test('vfs accumulates files, applies changes, and resets between builds', async () => { + const aCode = await readFile(a, 'utf8') + generator = createGenerator() + await generator.init() + + generator.addFile("export const valueB = 'virtual-b' as const\n", b) + const first = await generator.emit(aCode, a) + expect(first.error).toBeUndefined() + expect(first.code).toContain('valueB: "virtual-b"') + + await generator.emit("export const valueB = 'changed-b' as const\n", b) + const changed = await generator.emit(aCode, a) + expect(changed.error).toBeUndefined() + expect(changed.code).toContain('valueB: "changed-b"') + + const unchanged = await generator.emit(aCode, a) + expect(unchanged).toEqual(changed) + + await generator.dispose() + await generator.init() + + const rebuilt = await generator.emit(aCode, a) + expect(rebuilt.error).toBeUndefined() + expect(rebuilt.code).toContain('valueB: number') +}) + +test('vfs uses the specified tsconfig instead of the default project', async () => { + generator = new TsgoGenerator({ + moduleUrl, + cwd: root, + tsconfig: path.join(root, 'tsconfig.build.json'), + vfs: true, + languageContext: new LanguageContext([]), + }) + await generator.init() + + for (const value of [1, 2]) { + const output = await generator.emit( + `/** @internal */\nexport const internal = 0\nexport const visible = ${value}\n`, + a, + ) + expect(output.error).toBeUndefined() + expect(output.code).toContain(`visible = ${value}`) + expect(output.code).not.toContain('internal') + } +}) + +test('vfs resolves new files in virtual directories and retains them across updates', async () => { + const dependency = path.join(root, 'virtual/nested/dependency.ts') + const entryCode = "export { value } from './virtual/nested/dependency.ts'\n" + generator = createGenerator() + await generator.init() + + generator.addFile("export const value = 'virtual' as const\n", dependency) + const first = await generator.emit(entryCode, a) + expect(first.error).toBeUndefined() + expect(first.code).toContain( + "export { value } from './virtual/nested/dependency.ts'", + ) + + const output = await generator.emit( + "import { value } from './virtual/nested/dependency.ts'\nexport const copy = value\n", + a, + ) + expect(output.error).toBeUndefined() + expect(output.code).toContain('copy: "virtual"') + + const outputs = await Promise.all([ + generator.emit('export const value = 42 as const\n', dependency), + generator.emit( + "import { value } from './virtual/nested/dependency.ts'\nexport const copy = value\n", + a, + ), + ]) + expect(outputs[0].error).toBeUndefined() + expect(outputs[0].code).toContain('value: 42') + expect(outputs[1].error).toBeUndefined() + expect(outputs[1].code).toContain('copy: 42') +}) -- knotmirror 0.0.1