diff --git a/docs/1.project-structure.md b/docs/1.project-structure.md index 70d7d8e9..665c1638 100644 --- a/docs/1.project-structure.md +++ b/docs/1.project-structure.md @@ -14,7 +14,8 @@ my-module/ │ └── server/ # server routes, middleware, and Nitro plugins ├── playground/ # a Nuxt app that installs the module ├── package.json -├── tsconfig.json +├── tsconfig.json # references the tsconfigs in .nuxt +├── tsconfig.module.json └── tsdown.config.ts # the build configuration ``` @@ -225,16 +226,22 @@ To publish more entry points, such as `my-module/utils` or `my-module/components ## `tsconfig.json` -Your module's own `tsconfig.json` extends the `.nuxt/tsconfig.json` that `prepare` generates in the module root: +Your module's own `tsconfig.json` references the tsconfigs that `prepare` generates in the module's `.nuxt`, one for each part of the module, with `tsconfig.module.json` in place of the one for module code: ```json [tsconfig.json] { - "extends": "./.nuxt/tsconfig.json", - "exclude": ["dist", "node_modules", "playground"] + "files": [], + "exclude": ["dist", "node_modules", "playground"], + "references": [ + { "path": "./tsconfig.module.json" }, + { "path": "./.nuxt/tsconfig.app.json" }, + { "path": "./.nuxt/tsconfig.server.json" }, + { "path": "./.nuxt/tsconfig.shared.json" } + ] } ``` -[TypeScript](/docs/guide/modules/module-builder/typescript) describes this setup. +[TypeScript](/docs/guide/modules/module-builder/typescript) describes this setup, and `tsconfig.module.json`. ## `tsdown.config.ts` diff --git a/docs/2.commands.md b/docs/2.commands.md index 8db0ab03..6649a6b1 100644 --- a/docs/2.commands.md +++ b/docs/2.commands.md @@ -66,7 +66,7 @@ npx nuxt-module-build build [ROOTDIR] [--cwd=] [--outDir=] 4. Empty the output directory. 5. Bundle `src/module.ts` and any other [bundled entry](/docs/guide/modules/module-builder/configuration#bundled-entries) with tsdown. 6. Transpile `src/runtime/` and any other [directory entry](/docs/guide/modules/module-builder/configuration#directory-entries) file by file. -7. Generate the declarations of every entry and runtime file, with the [module's `tsconfig.json`](/docs/guide/modules/module-builder/typescript). +7. Generate the declarations of every entry and runtime file, each with the project of the [module's `tsconfig.json`](/docs/guide/modules/module-builder/typescript) that includes it. 8. Print the [size of the output](/docs/guide/modules/module-builder/output#size-report). 9. Load the built module to write `dist/module.json`, and write `dist/types.d.mts`. 10. Compare the paths in `package.json` with the files that the build produced. @@ -95,13 +95,15 @@ npx nuxt-module-build prepare [ROOTDIR] [--cwd=] `prepare` generates `.nuxt` in the module root. It runs `nuxt prepare` on the module root, as a Nuxt app with your module as its only module and with auto-imports disabled. It writes nothing to `dist`. -Your module's `tsconfig.json` extends the `.nuxt/tsconfig.json` that `prepare` generates. Your editor, your type check, and the declarations that the build generates then see the same types: +Your module's `tsconfig.json` references the tsconfigs that `prepare` generates, one for each part of the module. Your editor, your type check, and the declarations that the build generates then see the same types: - `@nuxt/schema`. - The `#app`, `#imports`, and `#build` aliases. - Anything your module adds, such as its templates and its server routes. -`prepare` also writes `.nuxt/module-builder/types.d.mts`. This file re-exports `src/module.ts`, and adds the same [type augmentations](/docs/guide/modules/module-builder/project-structure#srcmodulets) as `dist/types.d.mts`. With [source exports](/docs/guide/modules/module-builder/develop-and-publish#source-exports), the root export's `types` condition points at it. +`prepare` also writes `.nuxt/module-builder/types.d.mts`. This file re-exports `src/module.ts`, and adds the same [type augmentations](/docs/guide/modules/module-builder/project-structure#srcmodulets) as `dist/types.d.mts`. With [source exports](/docs/guide/modules/module-builder/develop-and-publish#source-exports), the root export's `types` condition points at it, and the tsconfig for module code includes it. + +In the app, server and shared tsconfigs, `prepare` resolves your module's own package name to declarations of module code, which it writes into `.nuxt/module-builder/declarations`. A declaration error there is a warning, which the build reports as an error. ### How `prepare` loads your module diff --git a/docs/3.develop-and-publish.md b/docs/3.develop-and-publish.md index 8f72c451..356afc20 100644 --- a/docs/3.develop-and-publish.md +++ b/docs/3.develop-and-publish.md @@ -16,7 +16,7 @@ The [playground](/docs/guide/modules/module-builder/project-structure#playground | pnpm, Yarn 4 | Your sources, with the `dist` paths in `publishConfig` | The playground runs your sources. See [Source exports](#source-exports). | | npm, Yarn 3 and earlier, bun | `dist` | `tsdown --watch` rebuilds `dist`. See [Developing against `dist`](#developing-against-dist). | -Run `dev:prepare` after you install dependencies. Run it again when the types that it generates are out of date, such as after the module registers a new template or server route. +Run `dev:prepare` after you install dependencies. Run it again when the types that it generates are out of date, such as after the module registers a new template or server route. The module's own app, server and shared type checks see the types of module code as of the last `prepare`. The build runs `prepare` on its own when `.nuxt` is missing. Keep `prepare` in `dev:prepare` anyway, so the module's types are in place before your editor or your type check needs them. diff --git a/docs/5.typescript.md b/docs/5.typescript.md index 7596e750..50423ade 100644 --- a/docs/5.typescript.md +++ b/docs/5.typescript.md @@ -7,26 +7,45 @@ A module has two TypeScript setups: one for the module itself, and one for its p ## The module's `tsconfig.json` -The module root has a `tsconfig.json` of its own. It extends the `.nuxt/tsconfig.json` that [`nuxt-module-build prepare`](/docs/guide/modules/module-builder/commands#prepare) generates there: +[`nuxt-module-build prepare`](/docs/guide/modules/module-builder/commands#prepare) generates a `.nuxt` in the module root, with one tsconfig for each part of the module: `tsconfig.node.json` for `src/module.ts` and the files next to it, `tsconfig.app.json` for `src/runtime/`, `tsconfig.server.json` for `src/runtime/server/`, and `tsconfig.shared.json` for code that both the app and the server use. The module's own `tsconfig.json` references them, with a `tsconfig.module.json` of yours in place of the one for module code: ```json [tsconfig.json] { - "extends": "./.nuxt/tsconfig.json", + "files": [], + "exclude": ["dist", "node_modules", "playground"], + "references": [ + { "path": "./tsconfig.module.json" }, + { "path": "./.nuxt/tsconfig.app.json" }, + { "path": "./.nuxt/tsconfig.server.json" }, + { "path": "./.nuxt/tsconfig.shared.json" } + ] +} +``` + +```json [tsconfig.module.json] +{ + "extends": "./.nuxt/tsconfig.node.json", "compilerOptions": { - "erasableSyntaxOnly": true - }, - "exclude": ["dist", "node_modules", "playground"] + "erasableSyntaxOnly": true, + "tsBuildInfoFile": "./.nuxt/tsconfig.module.tsbuildinfo" + } } ``` -This tsconfig covers both `src/module.ts` and `src/runtime/`. Your editor, your type check, and the declarations that the build generates all read it, so they see the same types. +Type-check the module with `vue-tsc -b --noEmit`. Each part is checked with the types it has in an app that installs the module, and the build generates each file's declarations with the project that includes it, so your editor, your type check, and `dist` see the same types. The `.nuxt` in the module root types the module as Nuxt sees it when the module is installed alone. It uses the module's default options, and disables auto-imports. It's separate from the playground's `.nuxt`, which reflects the playground's configuration and any other modules that it installs. - `erasableSyntaxOnly` makes the type check report the syntax that Node can't run in [module code](#module-code). +- `tsBuildInfoFile` keeps the build info that `vue-tsc -b` writes in `.nuxt`, next to that of the generated tsconfigs. - `exclude` leaves out `playground`, so the playground's own tsconfig types its files. Add any other directory that isn't part of the module, such as `docs`. +- Options in the root's `compilerOptions`, such as `"types": ["youtube"]`, apply to every part. Keep `./.nuxt/tsconfig.app.json` itself in `references`. + +`prepare` adapts the generated tsconfigs to a module. [Module tsconfig](/docs/guide/modules/module-builder/upgrade-v2#module-tsconfig) in the upgrade guide describes what it changes, and the errors that checking each part can report. + +The generated tsconfigs set `allowImportingTsExtensions`, so relative imports with a `.ts` extension type-check without further settings. -The generated `.nuxt/tsconfig.json` sets `allowImportingTsExtensions`, so relative imports with a `.ts` extension type-check without further settings. +A `tsconfig.json` that extends `./.nuxt/tsconfig.json` also works, type-checked with `vue-tsc --noEmit`, but checks less. See [Extending .nuxt/tsconfig.json](/docs/guide/modules/module-builder/upgrade-v2#extending-nuxttsconfigjson). ## Module code @@ -134,7 +153,7 @@ To type-check the module and the playground, run the type check once in each: ```json [package.json] { "scripts": { - "test:types": "vue-tsc --noEmit && cd playground && vue-tsc --noEmit" + "test:types": "vue-tsc -b --noEmit && cd playground && vue-tsc --noEmit" } } ``` @@ -158,13 +177,13 @@ The type check can report these errors: ## Monorepos -In a monorepo, give the module its own `tsconfig.json`, as shown above. Don't rely on a root tsconfig or on an app's `.nuxt` for it. Move any `compilerOptions` that the module relies on into it, such as `"types": ["youtube"]` for a global namespace. They then apply to the module's own type check and to its declarations. +In a monorepo, give the module its own `tsconfig.json` and `tsconfig.module.json`, as shown above. Don't rely on a root tsconfig or on an app's `.nuxt` for it. Copy into its `compilerOptions` the entries of the repository root's `types` that the module's `src` relies on, such as `"youtube"` for a global namespace, and leave out those only tests or other packages use, such as `"vitest/globals"`. They then apply to the module's own type check and to its declarations. The tsconfig that covers your module might extend or reference another app's `.nuxt/tsconfig.json` instead. In that case, the build generates declarations with the module's `./.nuxt/tsconfig.json`, plus that tsconfig's own `compilerOptions`, and prints a note. See [Module tsconfig](/docs/guide/modules/module-builder/upgrade-v2#module-tsconfig) in the upgrade guide. ## Declarations -The build generates declarations from your module's own files, with the module's tsconfig: +The build generates declarations from your module's own files, each with the project that includes it: - The module entry and every other bundled entry, with TypeScript. With `isolatedDeclarations`, it uses oxc instead. - Every script in the runtime directory and in other directory entries, with TypeScript. @@ -196,7 +215,7 @@ Build-time aliases, such as `#build/*`, `#internal/*`, and other paths into `.nu ### `isolatedDeclarations` -With `isolatedDeclarations: true` in the module's tsconfig, the module entry's declarations come from oxc. oxc is faster than TypeScript, but every export then needs an explicit type, including the module definition: +With `isolatedDeclarations: true` in the tsconfig for module code, the module entry's declarations come from oxc. oxc is faster than TypeScript, but every export then needs an explicit type, including the module definition: ```ts [src/module.ts] import { defineNuxtModule } from '@nuxt/kit' diff --git a/docs/8.transpile-dir.md b/docs/8.transpile-dir.md index 63677bc1..9b684e07 100644 --- a/docs/8.transpile-dir.md +++ b/docs/8.transpile-dir.md @@ -24,7 +24,7 @@ The plugin emits every file under `srcDir` under `outBase` in the build's output - Sass files compile to `.css`. - Test and story files are left out by default. -Scripts are transpiled with oxc, and keep their imports as written. Relative imports are the exception: they get the emitted extension. `.vue` files are transpiled with `vue-sfc-transformer`, stylesheets are processed as described in [Build Output](/docs/guide/modules/module-builder/output#runtime-files), and other files are copied. Declarations come from one TypeScript program that uses the nearest `tsconfig.json`. +Scripts are transpiled with oxc, and keep their imports as written. Relative imports are the exception: they get the emitted extension. `.vue` files are transpiled with `vue-sfc-transformer`, stylesheets are processed as described in [Build Output](/docs/guide/modules/module-builder/output#runtime-files), and other files are copied. Declarations come from one TypeScript program per tsconfig project: the nearest `tsconfig.json`, or the project in its `references` that includes the file. By default, the plugin transpiles scripts with the `transform` from `rolldown/utils`. `rolldown` is an optional peer dependency of `@nuxt/module-builder`, so install it in your project, or pass a `transform` of your own. `builder()` passes the `transform` of the `rolldown` that `tsdown` installs, so a module that builds with `builder()` needs neither. diff --git a/docs/cli/build-module/index.md b/docs/cli/build-module/index.md index 0b9f320d..886f07a0 100644 --- a/docs/cli/build-module/index.md +++ b/docs/cli/build-module/index.md @@ -35,7 +35,7 @@ Builds the module into `dist` for publishing. When the module has a `tsdown.conf ## `prepare` -Generates `.nuxt` in the module root, which the module's `tsconfig.json` extends. It also writes the declarations that the root export's `types` condition points at while `package.json` points at the module's sources. See [`prepare`](/docs/guide/modules/module-builder/commands#prepare). +Generates `.nuxt` in the module root, whose tsconfigs the module's `tsconfig.json` references. It also writes the declarations that the root export's `types` condition points at while `package.json` points at the module's sources. See [`prepare`](/docs/guide/modules/module-builder/commands#prepare). ### Arguments diff --git a/docs/index.md b/docs/index.md index d5399dba..169cced6 100644 --- a/docs/index.md +++ b/docs/index.md @@ -91,7 +91,7 @@ To add `@nuxt/module-builder` to an existing module, follow these steps: ``` 4. Point the `exports` of `package.json` at your module, as described in [Project Structure](/docs/guide/modules/module-builder/project-structure#packagejson). -5. Create a `tsconfig.json` that extends `.nuxt/tsconfig.json`, as described in [TypeScript](/docs/guide/modules/module-builder/typescript). +5. Create a `tsconfig.json` that references the tsconfigs in `.nuxt`, and a `tsconfig.module.json` for module code, as described in [TypeScript](/docs/guide/modules/module-builder/typescript). The `dev:prepare` script in step 3 is for a module that you publish with pnpm or Yarn 4. If you publish with npm, Yarn 3 or earlier, or bun, add `tsdown` before `nuxt prepare playground`. [Develop and Publish](/docs/guide/modules/module-builder/develop-and-publish#preparing-a-checkout) explains the difference. diff --git a/docs/upgrade-v2.md b/docs/upgrade-v2.md index 7e9ed561..1ae9d6d1 100644 --- a/docs/upgrade-v2.md +++ b/docs/upgrade-v2.md @@ -384,17 +384,18 @@ Both scripts start with `nuxt-module-build prepare`, also where the old one had The module's build-time code has to load with Node as it is, because Nuxt 5 loads modules with Node itself. That covers `src/module.ts`, every file it imports by value (runtime files included), `build.config.ts`, and `tsdown.config.ts`. Node strips types and resolves imports as written, so `nuxt-module-build build`, `tsdown`, and `nuxt-module-build prepare` stop with a list of everything it can't load, each with its file, line, column, and fix. A runtime file in the list also names the module code that imports it. Node never loads type-only imports, so they don't stop the module loading. A type check that resolves imports like Node still requires their extensions, such as the playground's check of its `nuxt.config.ts` context when the playground sets `future.compatibilityVersion: 5`: write them with extensions too. Runtime files that module code doesn't import keep extensionless imports, as they're emitted with the extension added. -Set `erasableSyntaxOnly` so your editor and type check report the syntax as well: +Set `erasableSyntaxOnly` in the tsconfig for module code, `tsconfig.module.json` in [Module tsconfig](#module-tsconfig), so your editor and type check report the syntax as well: ```json { + "extends": "./.nuxt/tsconfig.node.json", "compilerOptions": { "erasableSyntaxOnly": true } } ``` -Relative imports carry the imported file's extension: `./utils.ts`, not `./utils`, `./utils.js`, or `./dir`. The generated `.nuxt/tsconfig.json` sets `allowImportingTsExtensions`, so the `.ts` form type checks: +Relative imports carry the imported file's extension: `./utils.ts`, not `./utils`, `./utils.js`, or `./dir`. The generated tsconfigs set `allowImportingTsExtensions`, so the `.ts` form type checks: ```ts // before @@ -488,7 +489,7 @@ Fix the list before you run `prepare` or `dev:prepare`. Until it's empty, `prepa ## Declaration errors -Declarations for the module entry and for `src/runtime` are generated with TypeScript, using your module's own `tsconfig.json`. Run `nuxt-module-build prepare` first, as described in [Preparing .nuxt](#preparing-nuxt). Errors that would leave the declarations missing or wrong fail the build. Every other type error, in `.ts` and `.vue` files alike, is reported as a warning. +Declarations for the module entry and for `src/runtime` are generated with TypeScript, using the tsconfig project that includes each file, as described in [Module tsconfig](#module-tsconfig). Run `nuxt-module-build prepare` first, as described in [Preparing .nuxt](#preparing-nuxt). Errors that would leave the declarations missing or wrong fail the build. Every other type error, in `.ts` and `.vue` files alike, is reported as a warning. ### Portability errors @@ -521,7 +522,7 @@ Type errors that don't change the declarations, such as a wrong argument type or ```bash nuxt typecheck # or -vue-tsc --noEmit +vue-tsc -b --noEmit ``` If the type check reports the same errors, fix them there. If it passes, the warning is safe to ignore. @@ -561,7 +562,7 @@ export const fetchItems = () => $fetch('/api/items') ### Isolated declarations -With `isolatedDeclarations: true` in `tsconfig.json`, the module entry's declarations come from oxc. This is faster than TypeScript but requires an explicit type on every export. Write the module entry as follows: +With `isolatedDeclarations: true` in the tsconfig that includes `src/module.ts`, the module entry's declarations come from oxc. This is faster than TypeScript but requires an explicit type on every export. Write the module entry as follows: ```ts import type { NuxtModule } from '@nuxt/schema' @@ -614,24 +615,92 @@ A one-off build empties `--outDir` (`dist` by default) before it writes to it. ` ## Module tsconfig -Declarations are generated with your module's own `.nuxt`, which `nuxt-module-build prepare` writes from a Nuxt instance that runs the module alone. Extend it from the module's `tsconfig.json`, and leave the playground to its own `tsconfig.json`: +`nuxt-module-build prepare` writes the module's own `.nuxt` from a Nuxt instance that runs the module alone. It has one tsconfig for each part of the module: `tsconfig.node.json` for `src/module.ts` and the files next to it, `tsconfig.app.json` for `src/runtime`, `tsconfig.server.json` for `src/runtime/server`, and `tsconfig.shared.json` for code that both the app and the server use. Reference them from the module's `tsconfig.json`, and leave the playground to its own `tsconfig.json`: + +```json +{ + "files": [], + "exclude": ["dist", "node_modules", "playground"], + "references": [ + { "path": "./tsconfig.module.json" }, + { "path": "./.nuxt/tsconfig.app.json" }, + { "path": "./.nuxt/tsconfig.server.json" }, + { "path": "./.nuxt/tsconfig.shared.json" } + ] +} +``` + +To change the options of one part, reference a tsconfig of your own that extends the generated one, in its place. Here `tsconfig.module.json` takes the place of `./.nuxt/tsconfig.node.json` for module code: + +```json +{ + "extends": "./.nuxt/tsconfig.node.json", + "compilerOptions": { + "erasableSyntaxOnly": true, + "tsBuildInfoFile": "./.nuxt/tsconfig.module.tsbuildinfo" + } +} +``` + +`vue-tsc -b` writes a `.tsbuildinfo` file for each project, next to its tsconfig unless `tsBuildInfoFile` says otherwise. Those of the generated tsconfigs go in `.nuxt`, and `tsBuildInfoFile` puts this one there too. + +Keep `./.nuxt/tsconfig.app.json` itself in `references`, and put options for the runtime in the root's `compilerOptions`, as described in [Generated tsconfigs](#generated-tsconfigs). The build infers the runtime types of single-file component props, such as a prop typed through one of the module's aliases, through the generated app tsconfig itself. + +Type check with `vue-tsc -b --noEmit`. It checks each part as its own program, so it takes longer than `vue-tsc --noEmit` with a single tsconfig: between about 1.1 and 2.4 times as long, for the modules it was measured on. The build generates each file's declarations with the project that includes it, trying the module's own tsconfigs before the generated ones and the app's last. tsdown reads the project that includes `src/module.ts`, unless the tsdown config sets `tsconfig`. + +Auto-imports are off in the module's own `.nuxt`, so runtime code imports what it uses, such as `defineEventHandler` from `h3` or `useNuxtApp` from `#imports`. + +### Generated tsconfigs + +`prepare` adapts the generated tsconfigs to a module: + +- The app's tsconfig covers `src/runtime` and the module's other runtime directories rather than the whole module root, less the root's `exclude`. +- The root's `compilerOptions`, with those of the tsconfigs it extends, are copied into all four, apart from path options such as `paths` and `rootDir`. Its `types` are added to those Nuxt sets. Put options that every part needs there, such as `"types": ["youtube"]` for a global namespace. +- The module's `.d.ts` files are added as well, apart from those in the runtime directories, in the output directory (`dist` by default), in the root's `exclude`, and in the `playground*`, `docs`, `test`, `tests`, `fixtures`, `example` and `examples` directories. Those that only declare globals and ambient modules, with no top-level `import` or `export`, go to all four. Module augmentations, with a top-level `import` or `export` and a `declare module` or `declare global`, go to the app and to module code, the parts that Nuxt gives an installed module's types. Other `.d.ts` modules only apply to the files that import them. +- Module code gets the app's aliases, declarations (with the type templates that the app's tsconfig includes) and JSX options, for the runtime files it imports. +- Module code also gets `.nuxt/module-builder/types.d.mts`, so the augmentations for the `ModuleHooks`, `ModuleRuntimeHooks`, `ModuleRuntimeConfig` and `ModulePublicRuntimeConfig` that `src/module.ts` exports apply to it, as they do in an app that installs the module. +- In the app, server and shared tsconfigs, the module's own package name resolves to declarations of module code that `prepare` writes into `.nuxt/module-builder/declarations`, with a `types.d.mts` that has the same augmentations, and the subpath of each other bundled entry resolves to that entry's declarations. A type template or a runtime file that imports from the module's own name then gets the types an app that installs the module gets, without type checking module code in that part. A declaration error there, such as an export whose type can't be named, is a warning: the build reports it as an error. + +Other files, such as most tests and fixtures, are in none of them. Reference a tsconfig of your own to type check them. + +### Type checking each part + +Each part is type checked on its own, with the files it imports and the types that part has in an app. A `tsconfig.json` that extends `./.nuxt/tsconfig.json` checks the whole module root as one program with the app's types, so it doesn't report some of the errors below. Each entry gives the error, what it means and the fix: + +- **Missing `types` in module code** (TS2304, TS2503, such as `Cannot find namespace 'YT'`). Runtime files that module code imports are type checked with module code too. The root's `types` apply to it, but a `types` list in `tsconfig.module.json` replaces them, so repeat them there, such as `"types": ["youtube", "google.maps"]`. +- **An augmentation that only another file brings in** (TS2322, TS2339, TS2353). Module code that relies on a type augmentation that only a test or a config file loads needs it in its own tsconfig. A Vite plugin that returns `test` from its `config` hook needs Vitest's augmentation of the Vite config: add `"types": ["vitest/config"]` to `tsconfig.module.json`, or `/// ` to that file. +- **`erasableSyntaxOnly` outside the Node entry** (TS1294). `erasableSyntaxOnly` in `tsconfig.module.json` also applies to other bundled entries next to `src/module.ts`, such as a `src/vite.ts` or `src/unplugin.ts`, and to every file module code imports, runtime files included, which don't have to load with Node. Rewrite the syntax there too. A bundled entry that module code doesn't import can instead be left out of its `include`; a file that module code imports stays in its program either way. +- **App code in the server part** (TS2307 for `#app`, TS2305 and TS2724 for app composables in `#imports`, TS2304 and TS2584 for `window` and `document`, TS2724 for typed routes such as `RouteMapI18n`). A server file that imports an app runtime file or module code gets that file type checked with the server's types, which have no `#app`, no app composables in `#imports`, no DOM globals, and none of the app's typed routes. Move what both parts use into files that only depend on what both have. Code in a server file that runs in a browser, such as a function passed to Playwright's `page.evaluate`, needs `/// ` in that file. +- **A runtime config type declared twice** (TS2322, TS2345, TS2339). A runtime config key whose type the module declares, through `ModulePublicRuntimeConfig` or its own augmentation of `RuntimeConfig` or `PublicRuntimeConfig`, is also typed by Nuxt from the value the module sets. When the two types differ, TypeScript uses the declaration it reads first, or merges the two into a type that lacks properties of either, and the result differs between the layouts. Make the two types agree, or declare the full type. +- **`default` refers to itself** (TS7022 on the default export, TS7023 on a function in it, such as `moduleDependencies`). The module's own `.nuxt/types/modules.d.ts` types its options key and its entry in `ModuleDependencies` from `typeof import('../../src/module').default`. A `moduleDependencies` function without a return type is inferred from that same export. Give it one: `moduleDependencies(nuxt): ModuleDependencies`, with `ModuleDependencies` from `@nuxt/schema`. +- **An ambient module declared twice** (TS2554, TS2748, or a wrong type for an export). A `.d.ts` in the module that declares an ambient module a type template also declares, such as `declare module '#my-module/bindings'` in both, applies to each part along with the template, and the two declarations merge. Keep one of them. +- **Errors in code that relies on `.nuxt`'s declarations**. A `tsconfig.json` whose own `include` replaces the one it extends, such as `"include": ["src"]`, leaves out `.nuxt/nuxt.d.ts` and the declarations it references, such as the module's runtime config, typed routes and type templates. Each part here has them, so code that relies on them is checked against them. Fix what they report. + +### Extending .nuxt/tsconfig.json + +`prepare` also writes `.nuxt/tsconfig.json`, for a `tsconfig.json` that extends it. It type checks the whole module root as one program with the app's types, so it doesn't report the errors in [Type checking each part](#type-checking-each-part), and in it the module's own package name resolves through `package.json` rather than to declarations of module code. Set `erasableSyntaxOnly` in its own `compilerOptions`, and type check with `vue-tsc --noEmit`: ```json { "extends": "./.nuxt/tsconfig.json", + "compilerOptions": { + "erasableSyntaxOnly": true + }, "exclude": ["dist", "node_modules", "playground"] } ``` +### Other tsconfig layouts + The tsconfig that covers your module might extend or reference a playground's `.nuxt/tsconfig.json` instead. This can be the module's own tsconfig or a monorepo root's, such as `../../tsconfig.json`. In that case, the build generates declarations with `./.nuxt/tsconfig.json` plus that tsconfig's own `compilerOptions`, and prints a note saying so. `types` and `paths` are included, apart from paths into the playground's `.nuxt`. -In a monorepo, give the module a `tsconfig.json` of its own as shown above. Move any `compilerOptions.types` the module relies on into it, such as `"types": ["youtube"]` for a global namespace. They then apply to the module's own type check as well as to the build. +In a monorepo, give the module a `tsconfig.json` and a `tsconfig.module.json` of its own as shown above, in the module's directory. Copy into its `compilerOptions` the entries of the repository root's `compilerOptions.types` that the module's `src` relies on, such as `"youtube"` and `"google.maps"` for global namespaces, and leave out those only tests or other packages use, such as `"vitest/globals"`. They then apply to the module's own type check as well as to the build. The declaration program starts from your module's own files only. Files the tsconfig includes outside the module root (a workspace, with `typescript.includeWorkspace`) are left out. So are files under the module's `playground*`, `docs`, `test`, `tests`, `fixtures`, `example`, and `examples` directories. Their routes and type augmentations therefore don't end up in `dist`. Files that your module's sources import are still followed, wherever they are. ## Preparing .nuxt -Declarations are generated against `.nuxt/tsconfig.json`, so a build runs `nuxt-module-build prepare` first when `.nuxt` is missing. `prepare` loads `src/module.ts` with Node, so the rules in [Module code loads with Node](#module-code-loads-with-node) are checked there too. Keep `prepare` first in your module's `dev:prepare` script, as in [Developing a module](#developing-a-module), so the build doesn't have to: +Declarations are generated against the tsconfigs in `.nuxt`, so a build runs `nuxt-module-build prepare` first when `.nuxt` is missing. `prepare` loads `src/module.ts` with Node, so the rules in [Module code loads with Node](#module-code-loads-with-node) are checked there too. Keep `prepare` first in your module's `dev:prepare` script, as in [Developing a module](#developing-a-module), so the build doesn't have to: ```json { @@ -649,7 +718,7 @@ The playground installs the module by its package name, so it loads whatever `pa - With pnpm or Yarn 4, `package.json` points at the module's sources, and `publishConfig` holds the `dist` paths that are published. See [Source exports](#source-exports). - With npm, Yarn 3 or earlier, or bun, `package.json` points at `dist`, and `tsdown --watch` rebuilds it while you develop. See [Developing against dist](#developing-against-dist). -Run `dev:prepare` after you install dependencies, and again when the module registers something new for types, such as a template or a server route. +Run `dev:prepare` after you install dependencies, and again when the module registers something new for types, such as a template or a server route. With the tsconfigs in [Module tsconfig](#module-tsconfig), the module's own app, server and shared type checks see the types of module code as of the last `prepare`. ### Source exports @@ -816,7 +885,16 @@ Follow these steps in order to upgrade a module. Each step is mechanical until t - Replace `module.cjs` with `module.mjs`, and remove `.cjs` entries. - Remove the top-level `types` field and `typesVersions`, unless your module supports `node10` consumers. - If it does, set `types` to `./dist/types.d.mts`, in `publishConfig` with source exports (see step 8). Give every `typesVersions` path its full file name: `./dist/util.d.mts`, not `dist/util`. -5. Add `"erasableSyntaxOnly": true` to `tsconfig.json`. Rewrite any `enum`, `namespace`, parameter property, or `value` assertion that the type check reports. +5. Move the module to the tsconfigs in [Module tsconfig](#module-tsconfig): + - Replace `tsconfig.json` with the root shown there: `"files": []`, the `references` to `./tsconfig.module.json` and to `./.nuxt/tsconfig.app.json`, `tsconfig.server.json` and `tsconfig.shared.json`, and the old `exclude`. + - Keep the old `compilerOptions` in the root, `types` included: `prepare` copies them into every part. Path options such as `paths` and `baseUrl` aren't copied: move an alias from `paths` into the `imports` of `package.json`, as described in [Source exports](#source-exports). Move `erasableSyntaxOnly` and any other option for module code only into `tsconfig.module.json`. + - Create `tsconfig.module.json` as shown there, with `"erasableSyntaxOnly": true` and `tsBuildInfoFile`. + - Drop the old `include`. The generated tsconfigs cover `src`, and the module's `.d.ts` files are added to them, as described in [Generated tsconfigs](#generated-tsconfigs). A `.d.ts` that an `include` named in an excluded directory, such as `test/`, applies to none of them: move it into `src` or the module root. + - In a monorepo whose module has no tsconfig of its own, create both files in the module's directory, as described in [Other tsconfig layouts](#other-tsconfig-layouts). + - Set the type-check script to `vue-tsc -b --noEmit`. + - Run `nuxt-module-build prepare` and the type check. It checks each part with the types that part has in an app, so it can report errors that a single-program check didn't. [Type checking each part](#type-checking-each-part) lists them, with their fixes. Rewrite any `enum`, `namespace`, parameter property, or `value` assertion it reports. + + To keep a `tsconfig.json` that extends `./.nuxt/tsconfig.json`, set `erasableSyntaxOnly` in it instead, as described in [Extending .nuxt/tsconfig.json](#extending-nuxttsconfigjson). 6. Make module code load with Node, before step 8. `prepare` lists each problem, and doesn't generate `.nuxt` until you fix them all. See [Module code loads with Node](#module-code-loads-with-node): - Add the `.ts` extension to relative imports in `src/module.ts` and the files that it imports by value, runtime files included. `./utils` becomes `./utils.ts`, and `./dir` becomes `./dir/index.ts`. - Replace value imports through tsconfig `paths` aliases. @@ -828,7 +906,7 @@ Follow these steps in order to upgrade a module. Each step is mechanical until t - With npm, Yarn 3 or earlier, or bun, set `dev:prepare` to `nuxt-module-build prepare && tsdown && nuxt prepare playground`. See [Developing against dist](#developing-against-dist). - Run `nuxt-module-build prepare`, then `tsdown`. - Fix what the build reports. Remove each unsupported build option, and annotate each export in a portability error. Build again until the build passes. -9. Run your module's own type check, such as `nuxt typecheck` or `vue-tsc --noEmit`, and fix what it reports: +9. Run your module's own type check, `vue-tsc -b --noEmit` (or `vue-tsc --noEmit` with a `tsconfig.json` that extends `./.nuxt/tsconfig.json`), and fix what it reports, as described in [Type checking each part](#type-checking-each-part): - You can ignore a build warning about type errors that the type check doesn't reproduce. - Annotate exports whose type is inferred through a `#build/*` alias. Otherwise, `dist` declares them as `any`. 10. Check the package: diff --git a/example/package.json b/example/package.json index 0c6f6531..6a137c6e 100644 --- a/example/package.json +++ b/example/package.json @@ -36,7 +36,7 @@ "dev": "nuxt dev playground", "dev:build": "nuxt build playground", "dev:prepare": "node ../src/cli.ts prepare && nuxt prepare playground", - "test:types": "vue-tsc --noEmit" + "test:types": "vue-tsc -b --noEmit" }, "dependencies": { "@nuxt/kit": "^4.6.4" diff --git a/example/tsconfig.json b/example/tsconfig.json index b54b3240..71a636d6 100644 --- a/example/tsconfig.json +++ b/example/tsconfig.json @@ -1,9 +1,14 @@ { - "extends": "./.nuxt/tsconfig.json", + "files": [], "exclude": [ "dist", "node_modules", - "playground", - "../src" + "playground" + ], + "references": [ + { "path": "./.nuxt/tsconfig.node.json" }, + { "path": "./.nuxt/tsconfig.app.json" }, + { "path": "./.nuxt/tsconfig.server.json" }, + { "path": "./.nuxt/tsconfig.shared.json" } ] } diff --git a/package.json b/package.json index e4eba492..57931bad 100644 --- a/package.json +++ b/package.json @@ -74,7 +74,7 @@ }, "peerDependencies": { "@nuxt/cli": "^3.37.0 || ^4.0.0", - "rolldown": "^1.0.0", + "rolldown": "^1.2.6", "tsdown": "^0.23.7", "typescript": "^5.9.3 || ^6.0.0" }, diff --git a/src/build/build.ts b/src/build/build.ts index a468efb5..79ba695a 100644 --- a/src/build/build.ts +++ b/src/build/build.ts @@ -11,7 +11,7 @@ import builderPkg from '../../package.json' with { type: 'json' } import { probe as probeSource, scriptExtension, valueSpecifiers } from '../rolldown/resolve.ts' import { DEFAULT_EXCLUDE } from '../rolldown/transpile-dir.ts' import type { ResolveExternal } from '../rolldown/transpile-dir.ts' -import { createTsconfigResolver, declarationPaths, findPackageDir, namedCachePath, tsconfigPaths, writeDerivedTsconfig, writeServerRoutesStub } from '../rolldown/tsconfig.ts' +import { createTsconfigResolver, declarationPaths, findPackageDir, namedCachePath, tsconfigPaths, writeDependencyImports, writeDerivedTsconfig, writeServerRoutesStub } from '../rolldown/tsconfig.ts' import { shouldAdvise } from './advice.ts' import { rewriteRuntimeDeclarations } from './aliases.ts' import { bundledEntries, callBuildHook, createBuildContext, formatUnsupportedOptions, warnDeprecatedBuildConfig } from './build-config.ts' @@ -74,6 +74,10 @@ export interface BuildPlan { ctx: BuildContext neverBundle: (string | RegExp)[] moduleTsconfig: TsConfigResult | undefined + /** The nearest tsconfig, which may delegate files to `references`. */ + rootTsconfig: TsConfigResult | undefined + /** The referenced project that includes the module entry, which the bundler reads in place of a root tsconfig that only lists references. */ + moduleProject?: string isolatedDeclarations: boolean selfPaths: Record /** The tsconfig the module entry's declarations are generated with, written by {@link prepareBuild}, or `false` for none. */ @@ -134,6 +138,8 @@ export async function resolveBuild({ cwd, pkg, outDir, sourcemap, loadConfig }: ctx, neverBundle: [...NUXT_EXTERNALS, ...config.neverBundle], moduleTsconfig, + rootTsconfig: tsconfigs.root, + ...moduleTsconfig && moduleTsconfig.path !== tsconfigs.root?.path && !tsconfigs.replaced && { moduleProject: moduleTsconfig.path }, isolatedDeclarations: hasIsolatedDeclarations(moduleTsconfig), selfPaths, declarationTsconfig: moduleTsconfig ? namedCachePath(cwd, `declarations-${createHash('sha256').update(outDir).digest('hex').slice(0, 12)}.json`) : false, @@ -159,7 +165,8 @@ export async function prepareBuild(plan: BuildPlan, { keepOutput = false }: { ke await writeServerRoutesStub(cwd) if (plan.moduleTsconfig && plan.declarationTsconfig) { - await writeDerivedTsconfig(cwd, plan.moduleTsconfig, plan.selfPaths, plan.declarationTsconfig) + const imports = plan.moduleProject ? await writeDependencyImports(cwd, plan.rootTsconfig) : undefined + await writeDerivedTsconfig(cwd, plan.moduleTsconfig, plan.selfPaths, { file: plan.declarationTsconfig, imports }) } plan.prepared = analyseSources(plan) @@ -271,7 +278,9 @@ export async function finishBuild(plan: BuildPlan, { outputs, builder }: FinishB await rewriteRuntimeDeclarations(outDir, outputs) if (shouldNudge(plan.isolatedDeclarations)) { - consola.info(`Built in ${duration}ms. Set \`isolatedDeclarations: true\` in your \`tsconfig.json\` to use the faster oxc declaration generator. ${guide('isolated-declarations')}`) + const project = plan.moduleProject && relative(cwd, plan.moduleProject) + const where = !project ? 'your `tsconfig.json`' : project.startsWith('.nuxt') ? 'a `tsconfig.module.json` that extends `./.nuxt/tsconfig.node.json`' : `\`${project}\`` + consola.info(`Built in ${duration}ms. Set \`isolatedDeclarations: true\` in ${where} to use the faster oxc declaration generator. ${guide('isolated-declarations')}`) } await checkDeprecatedPackageFields(cwd) diff --git a/src/build/module-declarations.ts b/src/build/module-declarations.ts new file mode 100644 index 00000000..74af841a --- /dev/null +++ b/src/build/module-declarations.ts @@ -0,0 +1,95 @@ +import { mkdir, readFile, writeFile } from 'node:fs/promises' +import { consola } from 'consola' +import type { TsConfigResult } from 'get-tsconfig' +import { dirname, join, normalize, relative, resolve } from 'pathe' + +import { createDeclarationProgram, relativeSpecifier } from '../rolldown/declarations.ts' +import { DECLARATION_RE, probe, RELATIVE_RE, rewriteSpecifiers, SCRIPT_RE } from '../rolldown/resolve.ts' +import { isModuleFile } from '../rolldown/tsconfig.ts' +import { loadOxc } from './loader.ts' +import { hasIsolatedDeclarations } from './tsconfig.ts' +import { writeSourceTypes } from './types.ts' + +const NUXT_DIR_RE = /^\.nuxt(?:\/|$)/ + +function declarationFile(cwd: string, dir: string, file: string) { + return join(dir, relative(cwd, file)).replace(/\.([cm]?)[jt]sx?$/, (_, format: string) => `.d.${format}ts`) +} + +/** + * The `paths` that resolve the module's own package name to `types.d.mts` in `dir`, and the + * subpaths of its other bundled entries to their declarations there. Subpaths into a runtime + * directory, or with a wildcard, are left out. + */ +export function moduleDeclarationPaths(cwd: string, dir: string, name: string, selfPaths: Record, runtimeDirs: string[]): Record { + const paths: Record = { [name]: [join(dir, 'types.d.mts')] } + for (const [alias, [target]] of Object.entries(selfPaths)) { + const file = target && !alias.includes('*') && alias !== name ? probe(target) : undefined + if (file && SCRIPT_RE.test(file) && !runtimeDirs.some(runtimeDir => !relative(runtimeDir, file).startsWith('..'))) { + paths[alias] = [declarationFile(cwd, dir, file)] + } + } + return paths +} + +export interface ModuleDeclarationOptions { + /** The project that includes the module entry. */ + tsconfig: TsConfigResult | undefined + entry: string + /** The bundled entries, the module entry included. */ + roots: string[] + /** `paths` added to the tsconfig's. */ + paths: Record +} + +/** + * Writes into `dir` the declarations of the module code that `roots` reach, and a + * `types.d.mts` over them with the module's type augmentations. Declaration errors are + * reported as a warning, and the other declarations are written. + */ +export async function writeModuleDeclarations(cwd: string, dir: string, { tsconfig, entry, roots, paths }: ModuleDeclarationOptions): Promise { + await writeSourceTypes(dir, entry, join(dir, relative(cwd, entry))) + const isModuleCode = (file: string) => SCRIPT_RE.test(file) && !DECLARATION_RE.test(file) && isModuleFile(file, cwd) && !NUXT_DIR_RE.test(relative(cwd, file)) + const program = await createDeclarationProgram({ cwd, tsconfig, paths }, roots) + const sources = program.sources().filter(isModuleCode) + const { declarations, errors } = (hasIsolatedDeclarations(tsconfig) && await isolatedDeclarations(sources, cwd)) + || await program.emit(sources) + const emitted = new Map([...declarations.keys()].map(source => [normalize(source), declarationFile(cwd, dir, source)])) + await Promise.all([...declarations].map(async ([source, text]) => { + const output = emitted.get(normalize(source))! + const code = rewriteSpecifiers(text, (specifier) => { + const isRelative = RELATIVE_RE.test(specifier) + const target = (isRelative ? probe(resolve(dirname(source), specifier)) : undefined) ?? program.resolve(specifier, source) + const declaration = target && emitted.get(normalize(target)) + if (declaration) { + return relativeSpecifier(output, declaration).replace(/\.d\.([cm]?)ts$/, '.$1js') + } + return isRelative && target ? relativeSpecifier(output, target).replace(/\.d\.([cm]?)ts$/, '.$1js') : undefined + }) + await mkdir(dirname(output), { recursive: true }) + await writeFile(output, code) + })) + if (errors.length) { + consola.warn([ + `Declarations of module code for the module's own app, server and shared type checks could not be generated for every file. The build reports the same errors:`, + ...errors, + ].join('\n')) + } +} + +async function isolatedDeclarations(files: string[], cwd: string) { + const oxc = loadOxc() + if (!oxc) { + return + } + const declarations = new Map() + const errors: string[] = [] + for (const file of files) { + const result = await oxc.transform(file, await readFile(file, 'utf8'), { typescript: { declaration: {} } } as never) as { declaration?: string, errors: Array<{ message: string }> } + if (result.declaration !== undefined) { + declarations.set(file, result.declaration) + } + errors.push(...result.errors.map(error => `${relative(cwd, file)}: ${error.message}`)) + } + return { declarations, errors } +} diff --git a/src/build/types.ts b/src/build/types.ts index 778c78b9..74a12ecc 100644 --- a/src/build/types.ts +++ b/src/build/types.ts @@ -17,13 +17,15 @@ const VALUE_DECLARATION_RE = /\bexport\s+declare\s+(?:async\s+function|function| /** * Writes `module.d.mts`, which re-exports `entry`, and the `types.d.mts` that adds its type - * augmentations, into `dir`. + * augmentations, into `dir`. With `reExported`, `module.d.mts` re-exports that path instead, + * such as where the declarations of `entry` are written. */ -export async function writeSourceTypes(dir: string, entry: string): Promise { +export async function writeSourceTypes(dir: string, entry: string, reExported: string = entry): Promise { const source = await fsp.readFile(entry, 'utf8') const hasDefaultExport = findExports(source).some(e => e.type === 'default' || e.names?.includes('default')) - // TypeScript resolves the `.js` specifier to the `.ts` source without `allowImportingTsExtensions`. - const specifier = relative(dir, entry).replace(/\.([cm]?)tsx?$/, '.$1js') + // TypeScript resolves the `.js` specifier to the `.ts` source, or to its declaration, without `allowImportingTsExtensions`. + const path = relative(dir, reExported).replace(/\.([cm]?)tsx?$/, '.$1js') + const specifier = path.startsWith('.') ? path : `./${path}` await fsp.rm(dir, { recursive: true, force: true }) await fsp.mkdir(dir, { recursive: true }) await fsp.writeFile(resolve(dir, 'module.d.mts'), [ diff --git a/src/commands/prepare.ts b/src/commands/prepare.ts index 48ebb7f5..4ec2038d 100644 --- a/src/commands/prepare.ts +++ b/src/commands/prepare.ts @@ -2,41 +2,94 @@ import { pathToFileURL } from 'node:url' import type { Nuxt, NuxtConfig, NuxtModule } from '@nuxt/schema' import { defineCommand } from 'citty' import type { CommandDef } from 'citty' +import { readFile, writeFile } from 'node:fs/promises' +import { parseTsconfig } from 'get-tsconfig' import { resolvePathSync } from 'mlly' -import { resolve } from 'pathe' +import { dirname, join, relative, resolve } from 'pathe' import { readPackageJSON } from 'pkg-types' +import { glob } from 'tinyglobby' import { assertNoLegacyBuildConfig, bundledEntries, loadBuildConfig, resolveModuleOptions } from '../build/build-config.ts' import type { TranslatedBuildConfig } from '../build/build-config.ts' import { assertLoadableModuleCode, importModule } from '../build/loader.ts' +import { moduleDeclarationPaths, writeModuleDeclarations } from '../build/module-declarations.ts' +import { selfReferencePaths } from '../build/tsconfig.ts' import { writeSourceTypes } from '../build/types.ts' +import { probe } from '../rolldown/resolve.ts' +import { createTsconfigResolver, isModuleFile, rootTsconfig } from '../rolldown/tsconfig.ts' import { assertNoStubArg, loadModuleConfig, resolveCwdArg, sharedArgs } from './_shared.ts' -async function loadPrepareConfig(cwd: string): Promise { +const BUILD_DECLARATION_RE = /^declare module "#build\/(.+)";$/ +const PATH_OPTIONS = new Set(['paths', 'baseUrl', 'rootDir', 'rootDirs', 'outDir', 'outFile', 'declarationDir', 'typeRoots', 'tsBuildInfoFile']) + +async function loadPrepareConfig(cwd: string): Promise<{ config: TranslatedBuildConfig, outDir: string }> { const pkg = await readPackageJSON(cwd) const moduleConfig = await loadModuleConfig(cwd) const outDir = resolve(cwd, moduleConfig?.outDir ?? 'dist') if (!moduleConfig) { - return loadBuildConfig(cwd, pkg, outDir) + return { config: await loadBuildConfig(cwd, pkg, outDir), outDir } } assertNoLegacyBuildConfig(cwd, pkg) - return resolveModuleOptions(cwd, pkg, outDir, moduleConfig.options) + return { config: resolveModuleOptions(cwd, pkg, outDir, moduleConfig.options), outDir } } -export async function prepareModule(cwd: string, buildConfig?: TranslatedBuildConfig): Promise<{ result: unknown }> { +/** + * The module's `.d.ts` files outside the runtime directories and `exclude`, split + * into those that only declare globals and ambient modules, and module augmentations. Other + * modules, which only declare types for files that import them, are left out. + */ +async function ambientDeclarations(cwd: string, runtimeDirs: string[], exclude: string[]) { + const { default: ts } = await import('typescript') + const ignore = [...runtimeDirs, ...exclude].flatMap((pattern) => { + const path = relative(cwd, pattern) + return [path, `${path}/**`] + }) + const files = await glob(['**/*.d.ts'], { cwd, absolute: true, ignore: [...ignore, '**/node_modules/**'] }) + const globals: string[] = [] + const augmentations: string[] = [] + for (const file of files.filter(file => isModuleFile(file, cwd)).sort()) { + const source = ts.createSourceFile(file, await readFile(file, 'utf8'), ts.ScriptTarget.Latest) + if (!ts.isExternalModule(source)) { + globals.push(file) + } + else if (source.statements.some(statement => ts.isModuleDeclaration(statement))) { + augmentations.push(file) + } + } + return { globals, augmentations } +} + +export async function prepareModule(cwd: string, buildConfig?: { config: TranslatedBuildConfig, outDir: string }): Promise<{ result: unknown }> { const { runCommand } = await import('@nuxt/cli') - const config = buildConfig ?? await loadPrepareConfig(cwd) + const { config, outDir } = buildConfig ?? await loadPrepareConfig(cwd) const runtimeDirs = [resolve(cwd, 'src/runtime'), ...config.directories.map(directory => directory.srcDir)] const entries = bundledEntries(cwd, config) assertLoadableModuleCode(cwd, [entries.module], runtimeDirs, Object.values(entries)) const moduleExports = await importModule(resolve(cwd, entries.module), { cwd }) const nuxtModule = (moduleExports.default ?? moduleExports) as NuxtModule - const entryPath = resolve(cwd, './src/module') - const { name } = await readPackageJSON(cwd) + const pkg = await readPackageJSON(cwd) + const { name } = pkg const useNuxt = name ? await loadUseNuxt(cwd) : undefined + const entryPath = resolve(cwd, entries.module) + const rootConfig = await rootTsconfig(cwd) + const ambient = await ambientDeclarations(cwd, runtimeDirs, [...rootConfig.exclude ?? [], outDir]) + const selfPaths = selfReferencePaths(cwd, pkg, outDir) + const declarationsDir = join(sourceTypesDir(cwd), 'declarations') + const ownTypes = join(declarationsDir, 'types.d.mts') + const ownPaths = name ? moduleDeclarationPaths(cwd, declarationsDir, name, selfPaths, runtimeDirs) : {} + let perContext = false + const isOwnTypes = (reference: { path: string } | { types: string }) => 'types' in reference && (reference.types === name || reference.types === entryPath) + const compilerOptions = Object.fromEntries(Object.entries(rootConfig.compilerOptions).filter(([key]) => !PATH_OPTIONS.has(key))) + const withRootOptions = (options: Record = {}) => ({ + ...options, + ...compilerOptions, + ...compilerOptions.types !== undefined && { types: [...new Set([...options.types as string[] ?? [], ...compilerOptions.types as string[]])] }, + }) const result = await runCommand('prepare', [cwd], { overrides: { + buildDir: resolve(cwd, '.nuxt'), + typesDir: resolve(cwd, '.nuxt'), compatibilityDate: '2024-04-03', hooks: { 'modules:before': () => { @@ -48,7 +101,9 @@ export async function prepareModule(cwd: string, buildConfig?: TranslatedBuildCo }, typescript: { builder: 'shared', + tsConfig: { exclude: rootConfig.exclude ?? [] }, }, + nitro: { typescript: { tsConfig: { ...ambient.globals.length && { files: ambient.globals }, compilerOptions: withRootOptions() } } }, imports: { autoImport: false, }, @@ -65,18 +120,141 @@ export async function prepareModule(cwd: string, buildConfig?: TranslatedBuildCo nuxt.options.modules[index] = entryPath } nuxt.hooks.hook('app:templates', (app) => { + const virtual = new Set(app.templates.filter(template => !template.write).map(template => template.filename)) for (const template of app.templates) { template.write = true } + // `types/build.d.ts` only declares templates kept in memory; of those written here, it keeps the specifiers TypeScript does not resolve. + const buildTypes = app.templates.find(template => template.filename === 'types/build.d.ts') + const getContents = buildTypes?.getContents + if (buildTypes && getContents) { + buildTypes.getContents = async (data) => { + const written = new Set(data.app.templates.map(template => template.filename)) + const resolves = (path: string) => ['', '.ts', '.tsx', '.d.ts', '.js', '.jsx'].some(extension => written.has(path + extension)) + const contents = await getContents({ ...data, app: { ...data.app, templates: data.app.templates.map(template => virtual.has(template.filename) ? { ...template, write: false } : template) } }) + return contents.split('\n').filter(line => !resolves(line.match(BUILD_DECLARATION_RE)?.[1] ?? '')).join('\n') + } + } + }) + // Nuxt adds `dist` paths in the directory of each module's entry, the package root of an installed module. + const entryDist = dirname(entryPath) === cwd ? undefined : join(relative(nuxt.options.buildDir, dirname(entryPath)), 'dist') + const outsideEntryDist = (pattern: string) => entryDist === undefined || (pattern !== entryDist && !pattern.startsWith(`${entryDist}/`)) + // Nuxt 3 generates a single tsconfig, which is left as it is. + nuxt.hooks.hook('prepare:types', ({ nodeTsConfig }) => { + perContext = nodeTsConfig !== undefined + }) + nuxt.hooks.hook('nitro:init', (nitro) => { + nitro.hooks.hook('types:extend', ({ tsConfig }: { tsConfig?: { include?: string[], exclude?: string[], compilerOptions?: { paths?: Record } } }) => { + if (tsConfig) { + tsConfig.include &&= tsConfig.include.filter(outsideEntryDist) + tsConfig.exclude &&= tsConfig.exclude.filter(outsideEntryDist) + } + if (tsConfig && perContext) { + tsConfig.compilerOptions = { ...tsConfig.compilerOptions, paths: { ...tsConfig.compilerOptions?.paths, ...ownPaths } } + } + }) + }) + // Registered once every module is set up, so that it sees the aliases and options they add. + nuxt.hooks.hook('modules:done', () => { + nuxt.hooks.hook('prepare:types', ({ references, nodeReferences = [], tsConfig, nodeTsConfig, serverTsConfig, sharedTsConfig }) => { + if (!nodeTsConfig) { + return + } + // The app's tsconfig covers the module root as a Nuxt app's source directory, and the workspace, so it is narrowed to the runtime directories. + const rootGlobs = new Set([cwd, nuxt.options.workspaceDir].flatMap((dir) => { + const root = relative(nuxt.options.buildDir, dir) || '.' + return [join(root, '**/*'), join(root, '**/*.vue')] + })) + tsConfig.include = [...(tsConfig.include ?? []).filter(pattern => !rootGlobs.has(pattern)), ...runtimeDirs.filter(dir => !dir.startsWith(`${runtimeDirs[0]}/`))] + tsConfig.exclude = [...tsConfig.exclude ?? [], resolve(cwd, '**/nuxt.config.*')] + for (const context of [tsConfig, nodeTsConfig, serverTsConfig, sharedTsConfig].filter(context => context !== undefined)) { + context.include &&= context.include.filter(outsideEntryDist) + context.exclude &&= context.exclude.filter(outsideEntryDist) + context.compilerOptions = withRootOptions(context.compilerOptions) + if (ambient.globals.length) { + context.files = [...context.files ?? [], ...ambient.globals] + } + } + // Referenced from the declaration entries, so that the augmentations follow Nuxt's own declarations. + for (const list of [references, nodeReferences]) { + list.push(...ambient.augmentations.map(path => ({ path }))) + } + // Module code can import types from runtime sources, which rely on the app's aliases, declarations and JSX options. + const appDeclarations = (tsConfig.include ?? []).filter(pattern => !relative(nuxt.options.buildDir, resolve(nuxt.options.buildDir, pattern)).startsWith('..')) + nodeTsConfig.include = [...new Set([...nodeTsConfig.include ?? [], ...appDeclarations])] + // A type reference does not resolve the module's own package name. + const ownReference = nodeReferences.findIndex(isOwnTypes) + nodeReferences.splice(ownReference === -1 ? nodeReferences.length : ownReference, ownReference === -1 ? 0 : 1, { path: join(sourceTypesDir(cwd), 'types.d.mts') }) + const { jsx, jsxImportSource } = tsConfig.compilerOptions ?? {} + nodeTsConfig.compilerOptions = { jsx, jsxImportSource, ...nodeTsConfig.compilerOptions } + nodeTsConfig.compilerOptions.paths = { ...tsConfig.compilerOptions?.paths, ...nodeTsConfig.compilerOptions.paths } + // The module's own package resolves to declarations of module code here, so module code is not type checked in these parts. + // Included rather than referenced from `nuxt.d.ts`, which `.nuxt/tsconfig.json` also includes. + const appReference = references.findIndex(isOwnTypes) + if (appReference !== -1) { + references.splice(appReference, 1) + } + if (name) { + tsConfig.include = [...tsConfig.include ?? [], ownTypes] + } + for (const context of [tsConfig, serverTsConfig, sharedTsConfig].filter(context => context !== undefined)) { + context.compilerOptions = { ...context.compilerOptions, paths: { ...context.compilerOptions?.paths, ...ownPaths } } + } + }) }) }, ], } satisfies NuxtConfig, }) - await writeSourceTypes(resolve(cwd, '.nuxt/module-builder'), resolve(cwd, entries.module)) + await writeSourceTypes(sourceTypesDir(cwd), entryPath) + await writeCompatibilityTsconfig(resolve(cwd, '.nuxt/tsconfig.json'), cwd, { ownPaths, ownTypes, entryPath, ambient: ambient.globals }) + if (name && perContext) { + const roots = Object.values(entries).flatMap(input => probe(resolve(cwd, input)) ?? []).filter(file => !runtimeDirs.some(dir => !relative(dir, file).startsWith('..'))) + const tsconfigs = await createTsconfigResolver(cwd) + const project = tsconfigs.resolve(entryPath) + const nodeTsconfig = resolve(cwd, '.nuxt/tsconfig.node.json') + const tsconfig = project && project !== tsconfigs.root ? project : { path: nodeTsconfig, config: parseTsconfig(nodeTsconfig) } + await writeModuleDeclarations(cwd, declarationsDir, { tsconfig, entry: entryPath, roots, paths: selfPaths }) + } return result } +const sourceTypesDir = (cwd: string) => resolve(cwd, '.nuxt/module-builder') + +interface CompatibilityOptions { + ownPaths: Record + ownTypes: string + entryPath: string + /** The module's ambient declarations, which the program's `include` already covers. */ + ambient: string[] +} + +/** + * Rewrites `.nuxt/tsconfig.json`, one program over the module root, without the app's mapping of + * the module's own package to declarations of module code, as that program has its sources, and + * without the paths Nuxt derives from the directory of the module's entry, which exclude its + * server runtime. + */ +async function writeCompatibilityTsconfig(file: string, cwd: string, { ownPaths, ownTypes, entryPath, ambient }: CompatibilityOptions) { + const config = JSON.parse(await readFile(file, 'utf8')) as { include?: string[], exclude?: string[], files?: string[], compilerOptions?: { paths?: Record } } + config.files = config.files?.filter(path => !ambient.includes(resolve(dirname(file), path))) + if (!config.files?.length) { + delete config.files + } + const entryDir = dirname(entryPath) + const isDerived = (pattern: string) => { + const path = resolve(dirname(file), pattern) + const inEntryDist = entryDir !== cwd && !relative(join(entryDir, 'dist'), path).startsWith('..') + return path === ownTypes || path === join(entryDir, 'runtime/server') || inEntryDist + } + config.include = config.include?.filter(pattern => !isDerived(pattern)) + config.exclude = config.exclude?.filter(pattern => !isDerived(pattern)) + for (const alias of Object.keys(ownPaths)) { + delete config.compilerOptions?.paths?.[alias] + } + await writeFile(file, JSON.stringify(config, null, 2)) +} + /** * Replaces the entries of `modules` that install the package `name` with `nuxtModule`, keeping * their options, so the module is installed once from its sources whether or not `dist` exists. diff --git a/src/rolldown/declarations.ts b/src/rolldown/declarations.ts index a20e9ff7..719c85f6 100644 --- a/src/rolldown/declarations.ts +++ b/src/rolldown/declarations.ts @@ -24,6 +24,10 @@ interface DeclarationEmit { export interface DeclarationProgram { paths: DeclarationPaths emit: (files: string[]) => Promise + /** The program's source files other than declaration files. */ + sources: () => string[] + /** The file `specifier` resolves to from `importer`, with the program's options. */ + resolve: (specifier: string, importer: string) => string | undefined } /** @@ -58,11 +62,14 @@ export async function createDeclarationProgram({ cwd, tsconfig, paths }: Declara declarationDir: undefined, } let program: ts.Program | undefined + const createProgram = () => program ??= ts.createProgram({ rootNames: [...rootNames], options, projectReferences: parsed?.projectReferences }) return { paths: declaration, + sources: () => createProgram().getSourceFiles().filter(source => !source.isDeclarationFile).map(source => source.fileName), + resolve: (specifier, importer) => ts.resolveModuleName(specifier, importer, options, ts.sys).resolvedModule?.resolvedFileName, async emit(files) { - program ??= ts.createProgram({ rootNames: [...rootNames], options, projectReferences: parsed?.projectReferences }) + const program = createProgram() const { isDeclarationEmitDiagnostic } = await classifier const declarations = new Map() const errors: ts.Diagnostic[] = [] diff --git a/src/rolldown/transpile-dir.ts b/src/rolldown/transpile-dir.ts index 7fc9e5a8..f1e1426d 100644 --- a/src/rolldown/transpile-dir.ts +++ b/src/rolldown/transpile-dir.ts @@ -10,7 +10,7 @@ import { createDeclarationProgram, DeclarationError, declarationError, relativeS import type { DeclarationProgram } from './declarations.ts' import { DECLARATION_RE, moduleSpecifiers, probe, RELATIVE_RE, rewriteSpecifiers, SCRIPT_RE, scriptExtension, valueSpecifiers } from './resolve.ts' import { compileSass, SASS_RE, transformCss } from './stylesheets.ts' -import { createTsconfigResolver, writeDerivedTsconfig } from './tsconfig.ts' +import { createTsconfigResolver, writeDependencyImports, writeDerivedTsconfig } from './tsconfig.ts' import { declarationPath, emitDeclarations, transformVueRuntime } from './vue.ts' import type { VueDeclarations, VueOptions } from './vue.ts' @@ -25,6 +25,7 @@ export interface TransformOptions { sourcemap?: boolean jsx?: 'preserve' | { runtime?: 'automatic' | 'classic', importSource?: string } typescript?: { onlyRemoveTypeImports?: boolean } + tsconfig?: string } /** The shape of `transform` from `rolldown/utils`. */ @@ -237,6 +238,7 @@ class DirectoryBuild { private resolutions = new Map>() private references = new Map>() private transform: Promise | undefined + private resolver: ReturnType | undefined private extension: string private dtsExtension: string private outBase: string @@ -423,11 +425,14 @@ class DirectoryBuild { private async transpileSource(file: string, source: string, sourcemap = false) { const transform = await this.loadTransform() + const resolver = await (this.resolver ??= this.tsconfigs()) + const project = resolver?.resolve(file) const result = await transform(file, /\.[cm]?tsx?$/.test(file) ? source.replace(EMPTY_IMPORT_RE, match => ' '.repeat(match.length)) : source, { lang: file.match(/\.[cm]?([jt]sx?)$/)![1], sourcemap, jsx: this.jsx(file), typescript: { onlyRemoveTypeImports: false }, + ...project && project !== resolver?.root && { tsconfig: project.path }, }) if (result.errors.length) { throw new Error(`Failed to transpile ${relative(this.options.cwd, file)}:\n${result.errors.map(error => error.message).join('\n')}`) @@ -540,11 +545,12 @@ class DirectoryBuild { */ private async createEmitter(): Promise { const resolver = await this.tsconfigs() + const imports = await writeDependencyImports(this.options.cwd, resolver?.root) const programs = new Map>() const programFor = (tsconfig: TsConfigResult | undefined) => { let program = programs.get(tsconfig?.path) if (!program) { - program = createDeclarationProgram({ cwd: this.options.cwd, tsconfig, paths: this.options.paths ?? {} }, [...this.scripts, ...this.outside.keys()]) + program = createDeclarationProgram({ cwd: this.options.cwd, tsconfig, paths: this.options.paths ?? {} }, [...this.scripts, ...this.outside.keys(), ...imports ? [imports] : []]) programs.set(tsconfig?.path, program) } return program @@ -556,7 +562,7 @@ class DirectoryBuild { return emitDeclarations([...this.vue, ...[...this.scripts, ...this.outside.keys()].filter(file => TYPESCRIPT_RE.test(file))], { ...this.options.vue || {}, cwd: this.options.cwd, - tsconfig: tsconfig && await writeDerivedTsconfig(this.options.cwd, tsconfig, this.options.paths ?? {}), + tsconfig: tsconfig && await writeDerivedTsconfig(this.options.cwd, tsconfig, this.options.paths ?? {}, { vue: true, imports }), }) })() : undefined diff --git a/src/rolldown/tsconfig.ts b/src/rolldown/tsconfig.ts index 29059a70..859749a3 100644 --- a/src/rolldown/tsconfig.ts +++ b/src/rolldown/tsconfig.ts @@ -1,12 +1,13 @@ import { createHash, randomUUID } from 'node:crypto' -import { existsSync, statSync } from 'node:fs' -import { createRequire } from 'node:module' -import { mkdir, rename, rm, writeFile } from 'node:fs/promises' +import { existsSync } from 'node:fs' +import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises' import { createFilesMatcher, createPathsMatcher, getTsconfig, parseTsconfig } from 'get-tsconfig' import type { TsConfigResult } from 'get-tsconfig' import { dirname, isAbsolute, join, relative, resolve } from 'pathe' import type ts from 'typescript' +import { moduleSpecifiers } from './resolve.ts' + export interface TsconfigResolver { /** The nearest tsconfig, which may delegate files to `references`. */ root: TsConfigResult | undefined @@ -32,7 +33,7 @@ export async function createTsconfigResolver(dir: string, file?: string): Promis replaced = root.path root = await rebaseOnOwnBuildDir(root.path, own, dir) } - const projects = referencedProjects(root).map(project => ({ project, matches: createFilesMatcher(project) })) + const projects = allReferencedProjects(root).map(project => ({ project, matches: createFilesMatcher(project) })) const scriptPath = (file: string) => file.endsWith('.vue') ? `${file}.ts` : file @@ -45,7 +46,7 @@ export async function createTsconfigResolver(dir: string, file?: string): Promis function usesForeignBuildDir(tsconfig: TsConfigResult, dir: string) { const targets = Object.values(tsconfigPaths(tsconfig)).flat() - const projects = referencedProjects(tsconfig).map(project => project.path) + const projects = allReferencedProjects(tsconfig).map(project => project.path) return [...targets, ...projects].some(file => NUXT_BUILD_DIR_RE.test(file) && !isOwnBuildFile(file, dir)) } @@ -69,17 +70,9 @@ const PATH_LIST_OPTIONS = ['rootDirs', 'typeRoots'] as const async function rebaseOnOwnBuildDir(tsconfig: string, own: string, dir: string): Promise { const { default: ts } = await import('typescript') const read = (file: string) => ts.readConfigFile(file, ts.sys.readFile).config as RawTsconfig | undefined - const layerOptions = (file: string): Record => { - const raw = read(file) - const base = (Array.isArray(raw?.extends) ? raw.extends : raw?.extends ? [raw.extends] : []) - .map(target => resolveExtends(target, dirname(file))) - .filter(target => target !== undefined && !isForeignBuildFile(target, dir)) - .map(target => layerOptions(target!)) - return Object.assign({}, ...base, absoluteOptions(raw?.compilerOptions ?? {}, dirname(file), dirname(tsconfig))) - } const ownConfig = parseTsconfig(own) const ownPaths = tsconfigPaths({ path: own, config: ownConfig }) - const { paths, types, ...options } = layerOptions(tsconfig) + const { paths, types, ...options } = (await inheritedTsconfig(tsconfig, target => isForeignBuildFile(target, dir))).compilerOptions const ownTypes = ownConfig.compilerOptions?.types const config = { extends: own, @@ -99,26 +92,53 @@ async function rebaseOnOwnBuildDir(tsconfig: string, own: string, dir: string): interface RawTsconfig { extends?: string | string[] compilerOptions?: Record + exclude?: string[] references?: { path: string }[] } -function resolveExtends(target: string, from: string) { - if (target.startsWith('.') || isAbsolute(target)) { - const path = resolve(from, target) - return [path, `${path}.json`, join(path, 'tsconfig.json')].find(candidate => existsSync(candidate) && statSync(candidate).isFile()) - } - const require = createRequire(join(from, 'tsconfig.json')) - for (const candidate of [target, `${target}.json`, `${target}/tsconfig.json`]) { - try { - return require.resolve(candidate) - } - catch { - continue +interface InheritedTsconfig { + compilerOptions: Record + /** Absolute patterns. */ + exclude?: string[] +} + +/** The `compilerOptions` and `exclude` of `dir/tsconfig.json`, see {@link inheritedTsconfig}, apart from those of tsconfigs in a `.nuxt`. */ +export function rootTsconfig(dir: string): Promise { + return inheritedTsconfig(join(dir, 'tsconfig.json'), file => NUXT_BUILD_DIR_RE.test(file)) +} + +/** + * The `compilerOptions` and `exclude` of `file` and of the tsconfigs it extends, apart from + * those `skip` matches, merged as TypeScript merges them, with paths made absolute. + */ +async function inheritedTsconfig(file: string, skip: (file: string) => boolean): Promise { + const { default: ts } = await import('typescript') + const configDir = dirname(file) + const layer = (path: string, ancestors: string[]): InheritedTsconfig => { + const raw = ts.readConfigFile(path, ts.sys.readFile).config as RawTsconfig | undefined + const bases = [raw?.extends ?? []].flat() + .map(target => resolveExtends(ts, target, dirname(path))) + .filter((target): target is string => target !== undefined && !ancestors.includes(target) && !skip(target)) + .map(target => layer(target, [...ancestors, path])) + return { + compilerOptions: Object.assign({}, ...bases.map(base => base.compilerOptions), absoluteOptions(raw?.compilerOptions ?? {}, dirname(path), configDir)), + exclude: raw?.exclude?.map(pattern => resolve(dirname(path), pattern.replace('${configDir}', configDir))) ?? bases.findLast(base => base.exclude)?.exclude, } } + return layer(file, []) +} + +const RELATIVE_RE = /^\.\.?[\\/]/ + +/** The existing tsconfig that an `extends` entry in a tsconfig in `from` names, resolved by TypeScript. */ +function resolveExtends(ts: typeof import('typescript'), target: string, from: string) { + const file = join(from, 'tsconfig.json') + const source = ts.readJsonConfigFile(file, () => JSON.stringify({ extends: target, files: [], include: [] })) + ts.parseJsonSourceFileConfigFileContent(source, { ...ts.sys, readDirectory: () => [] }, from, undefined, file) + return source.extendedSourceFiles?.[0] } -/** Path options resolved against `from`, the layer's directory; `${configDir}` is the leaf tsconfig's. */ +/** Path options resolved against `from`, the layer's directory; `${configDir}` and relative `types` are the leaf tsconfig's. */ function absoluteOptions(options: Record, from: string, configDir: string) { const dir = (value: string) => resolve(from, value.replace('${configDir}', configDir)) const result = { ...options } @@ -132,6 +152,9 @@ function absoluteOptions(options: Record, from: string, configD result[key] = result[key].map(value => dir(value as string)) } } + if (Array.isArray(result.types)) { + result.types = result.types.map(value => typeof value === 'string' && (RELATIVE_RE.test(value) || value.includes('${configDir}')) ? resolve(configDir, value.replace('${configDir}', configDir)) : value) + } if (result.paths && typeof result.paths === 'object') { const base = typeof options.baseUrl === 'string' ? dir(options.baseUrl) : from result.paths = Object.fromEntries(Object.entries(result.paths as Record).map(([alias, targets]) => [alias, targets.map(target => resolve(base, target.replace('${configDir}', configDir)))])) @@ -147,21 +170,45 @@ const FOREIGN_DIR_RE = /^(?:playgrounds?(?:-.*)?|docs|tests?|fixtures|examples?| * another app. */ export function projectFiles(parsed: ts.ParsedCommandLine | undefined, dir: string): string[] { - return (parsed?.fileNames ?? []).filter((file) => { - const path = relative(dir, file) - if (path.startsWith('..') || isAbsolute(path) || FOREIGN_DIR_RE.test(path.split('/')[0]!) || NODE_MODULES_RE.test(file)) { - return false - } - return !NUXT_BUILD_DIR_RE.test(file) || isOwnBuildFile(file, dir) - }) + return (parsed?.fileNames ?? []).filter(file => isModuleFile(file, dir)) +} + +/** Whether `file` belongs to the module in `dir`, as {@link projectFiles} decides. */ +export function isModuleFile(file: string, dir: string): boolean { + const path = relative(dir, file) + if (path.startsWith('..') || isAbsolute(path) || FOREIGN_DIR_RE.test(path.split('/')[0]!) || NODE_MODULES_RE.test(file)) { + return false + } + return !NUXT_BUILD_DIR_RE.test(file) || isOwnBuildFile(file, dir) } +/** + * The projects `tsconfig` references, with the module's own tsconfigs before those Nuxt + * generates and, of those, the app's last, as its files include the others'. + */ function referencedProjects(tsconfig: TsConfigResult | undefined): TsConfigResult[] { return (tsconfig?.config.references ?? []).flatMap((reference) => { const path = resolve(dirname(tsconfig!.path), reference.path) const config = path.endsWith('.json') ? path : join(path, 'tsconfig.json') return existsSync(config) ? [{ path: config, config: parseTsconfig(config) }] : [] - }) + }).sort((a, b) => projectRank(a.path) - projectRank(b.path)) +} + +function projectRank(path: string) { + if (!NUXT_BUILD_DIR_RE.test(path)) { + return 0 + } + return /[\\/]tsconfig(?:\.app)?\.json$/.test(path) ? 2 : 1 +} + +function allReferencedProjects(tsconfig: TsConfigResult | undefined, seen = new Set()): TsConfigResult[] { + return referencedProjects(tsconfig).flatMap((project) => { + if (seen.has(project.path)) { + return [] + } + seen.add(project.path) + return [project, ...allReferencedProjects(project, seen)] + }).sort((a, b) => projectRank(a.path) - projectRank(b.path)) } /** The tsconfig's `paths` made absolute. */ @@ -316,6 +363,34 @@ export function writeServerRoutesStub(cwd: string): Promise { return writeCached(cwd, '.d.ts', SERVER_ROUTES_STUB) } +/** + * Writes a declaration file that imports each installed package the files of the projects + * `tsconfig` references import, one specifier per package, or returns `undefined` when it has + * no references. A program over one of those projects that lists it resolves the module's + * dependencies from the module root, so their types are named by package in declarations. + */ +export async function writeDependencyImports(cwd: string, tsconfig: TsConfigResult | undefined): Promise { + const projects = allReferencedProjects(tsconfig) + if (!projects.length) { + return + } + const { default: ts } = await import('typescript') + const extraFileExtensions = [{ extension: 'vue', isMixedContent: true, scriptKind: ts.ScriptKind.Deferred }] + const host = { ...ts.sys, onUnRecoverableConfigFileDiagnostic: () => {} } + const files = new Set(projects.flatMap(project => projectFiles(ts.getParsedCommandLineOfConfigFile(project.path, {}, host, undefined, undefined, extraFileExtensions), cwd))) + const sources = await Promise.all([...files].sort().map(file => readFile(file, 'utf8').catch(() => ''))) + const specifiers = new Map() + for (const source of sources) { + for (const { specifier } of moduleSpecifiers(source)) { + const name = /^[#~@]\//.test(specifier) || specifier.startsWith('#') || specifier.includes(':') ? undefined : specifier.match(PACKAGE_NAME_RE)?.[0] + if (name && !specifiers.has(name) && findPackageDir(name, cwd)) { + specifiers.set(name, specifier) + } + } + } + return writeCached(cwd, '.d.ts', [...[...specifiers.values()].map(specifier => `import type {} from '${specifier}'\n`), 'export {}\n'].join('')) +} + /** * Writes a tsconfig extending `tsconfig`, for tools that take a tsconfig file. Its `paths` * are the tsconfig's plus `paths`, less what {@link declarationPaths} drops; the aliases @@ -323,8 +398,10 @@ export function writeServerRoutesStub(cwd: string): Promise { * inferred, so `isolatedDeclarations` is off. The files are listed rather than inherited, * less those of a playground (see {@link projectFiles}). Each project in `references` is * derived the same way. It is written to `file`, or by default to a content-addressed path. + * With `vue`, single-file components are listed too. `imports` (see {@link writeDependencyImports}) + * is listed in each derived tsconfig that lists files of its own. */ -export async function writeDerivedTsconfig(cwd: string, tsconfig: TsConfigResult | undefined, paths: Record, file?: string): Promise { +export async function writeDerivedTsconfig(cwd: string, tsconfig: TsConfigResult | undefined, paths: Record, { file, vue, imports }: { file?: string, vue?: boolean, imports?: string } = {}): Promise { const declaration = declarationPaths({ ...tsconfigPaths(tsconfig), ...paths }, cwd) await writeServerRoutesStub(cwd) const compilerOptions: Record = { paths: declaration.paths, isolatedDeclarations: false } @@ -334,12 +411,14 @@ export async function writeDerivedTsconfig(cwd: string, tsconfig: TsConfigResult await writeAmbientModules(cwd, declaration.ambient), ] } - const references = await Promise.all(referencedProjects(tsconfig).map(async project => ({ path: await writeDerivedTsconfig(cwd, project, paths) }))) + const references = await Promise.all(referencedProjects(tsconfig).map(async project => ({ path: await writeDerivedTsconfig(cwd, project, paths, { vue, imports }) }))) const { default: ts } = await import('typescript') - const parsed = tsconfig && ts.getParsedCommandLineOfConfigFile(tsconfig.path, {}, { ...ts.sys, onUnRecoverableConfigFileDiagnostic: () => {} }) + const extraFileExtensions = vue ? [{ extension: 'vue', isMixedContent: true, scriptKind: ts.ScriptKind.Deferred }] : undefined + const parsed = tsconfig && ts.getParsedCommandLineOfConfigFile(tsconfig.path, {}, { ...ts.sys, onUnRecoverableConfigFileDiagnostic: () => {} }, undefined, undefined, extraFileExtensions) + const files = projectFiles(parsed, cwd) const contents = JSON.stringify({ ...tsconfig && { extends: tsconfig.path }, - ...tsconfig && { files: projectFiles(parsed, cwd).map(file => relative(cacheDir(cwd), file)), include: [] }, + ...tsconfig && { files: [...files, ...imports && files.length ? [imports] : []].map(file => relative(cacheDir(cwd), file)), include: [] }, compilerOptions, ...references.length && { references }, }) diff --git a/src/tsdown/setup.ts b/src/tsdown/setup.ts index a0e73358..06155524 100644 --- a/src/tsdown/setup.ts +++ b/src/tsdown/setup.ts @@ -91,7 +91,7 @@ export async function setupBuilder(config: UserConfig, inline: InlineConfig, opt if (!existsSync(resolve(cwd, '.nuxt/tsconfig.json'))) { consola.info(`\`.nuxt\` not found, running \`nuxt-module-build prepare\` first. Add it to the module's \`dev:prepare\` script to skip this step. ${guide('preparing-nuxt')}`) - await prepareModule(cwd, buildConfig) + await prepareModule(cwd, { config: buildConfig, outDir }) } const plan = await resolveBuild({ cwd, pkg, outDir, sourcemap: !!config.sourcemap, loadConfig: async () => buildConfig }) @@ -148,6 +148,7 @@ export async function setupBuilder(config: UserConfig, inline: InlineConfig, opt Object.assign(config, { entry: plan.entries, + ...config.tsconfig === undefined && plan.moduleProject && { tsconfig: plan.moduleProject }, format: 'esm', outDir, clean: false, diff --git a/test/build.spec.ts b/test/build.spec.ts index 9126fbcf..3e1083d9 100644 --- a/test/build.spec.ts +++ b/test/build.spec.ts @@ -53,6 +53,8 @@ export type JsxComponentType = typeof JsxComponent export type { NuxtApp } from '#app' ` +const LEGACY_TSCONFIG = { extends: './.nuxt/tsconfig.json', exclude: ['dist', 'node_modules', 'playground', '../src'] } + describe('module builder', () => { const repoRoot = fileURLToPath(new URL('..', import.meta.url)) const rootDir = fileURLToPath(new URL('../example', import.meta.url)) @@ -112,10 +114,16 @@ describe('module builder', () => { const flowOutput = new Map() beforeAll(async () => { + const legacyRootDir = rootDir.replace('example', '.temp-example-legacy-tsconfig') + await rm(legacyRootDir, { force: true, recursive: true }) + await cp(rootDir, legacyRootDir, { recursive: true }) + await writeFile(join(legacyRootDir, 'tsconfig.json'), JSON.stringify(LEGACY_TSCONFIG, null, 2)) + await exec('pnpm', ['nuxt-module-build', 'prepare', legacyRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true }) + const copyExample = async (target: string, transform: (contents: string) => string) => { await mkdir(dirname(target), { recursive: true }) await rm(target, { force: true, recursive: true }) - await cp(rootDir, target, { recursive: true }) + await cp(legacyRootDir, target, { recursive: true }) const pkgPath = join(target, 'package.json') const { publishConfig: _, ...pkg } = publishedPackage(JSON.parse(await readFile(pkgPath, 'utf-8'))) await writeFile(pkgPath, JSON.stringify(pkg, null, 2)) @@ -868,7 +876,7 @@ export const defineOptions = (options: Options) => ({ options, helper }) const { stderr, exitCode } = await exec('pnpm', ['nuxt-module-build', 'prepare', prepareLoaderRootDir], { nodeOptions: { cwd: repoRoot, env: { ...process.env, NUXT_TELEMETRY_DISABLED: '1' } } }) expect(stderr).not.toContain('ERR_INTERNAL_ASSERTION') expect(exitCode).toBe(0) - expect(await readFile(join(prepareLoaderRootDir, '.nuxt/nuxt.d.ts'), 'utf-8')).toContain('/// ') + expect(await readFile(join(prepareLoaderRootDir, '.nuxt/nuxt.node.d.ts'), 'utf-8')).toContain('/// ') const modulesDts = await readFile(join(prepareLoaderRootDir, '.nuxt/types/modules.d.ts'), 'utf-8') expect(modulesDts).toContain(`typeof import(${JSON.stringify(join(prepareLoaderRootDir, 'src/module'))}).default`) }, 120 * 1000) diff --git a/test/tsdown.spec.ts b/test/tsdown.spec.ts index 302cb73c..d9e62581 100644 --- a/test/tsdown.spec.ts +++ b/test/tsdown.spec.ts @@ -29,7 +29,7 @@ async function copyExample(name: string, config: string) { return dir } -const tsdown = (cwd: string, args: string[] = []) => exec('node', [tsdownBin, ...args], { nodeOptions: { cwd, env: { ...process.env, NODE_ENV: '', TEST: '' } } }) +const tsdown = (cwd: string, args: string[] = [], env: Record = {}) => exec('node', [tsdownBin, ...args], { nodeOptions: { cwd, env: { ...process.env, NODE_ENV: '', TEST: '', ...env } } }) function watch(cwd: string, args: string[]) { const result = exec('node', args, { nodeOptions: { cwd, env: { ...process.env, NODE_ENV: '', TEST: '' } } }) @@ -549,20 +549,20 @@ export default { await writeFile(join(dir, 'nuxt.config.ts'), `export default { modules: [['self-listed-module', { apiKey: 'from-config' }]] }\n`) await writeFile(join(dir, 'src/module.ts'), (await readFile(join(dir, 'src/module.ts'), 'utf-8')).replace('setup(_options, _nuxt) {', 'setup(_options, _nuxt) {\n console.log(`[setup] ${_options.apiKey}`)')) const env = { ...process.env, NODE_ENV: '', TEST: '', NUXT_TELEMETRY_DISABLED: '1' } - const references = async () => (await readFile(join(dir, '.nuxt/nuxt.d.ts'), 'utf-8')).split('\n').filter(line => line.includes('types="self-listed-module"')) + const references = async () => (await readFile(join(dir, '.nuxt/nuxt.node.d.ts'), 'utf-8')).split('\n').filter(line => line.includes('types="self-listed-module"') || line === '/// ') await rm(join(dir, '.nuxt'), { recursive: true, force: true }) const built = await exec('node', [tsdownBin], { nodeOptions: { cwd: dir, env } }) expect(built.exitCode, built.stdout + built.stderr).toBe(0) expect(built.stdout.match(/\[setup\] .*/g)).toEqual(['[setup] from-config']) - expect(await references()).toHaveLength(1) + expect(await references()).toEqual(['/// ']) await writeFile(pkgPath, JSON.stringify({ ...pkg, name: 'self-listed-module', exports: { '.': './src/module.ts' }, main: './src/module.ts' }, null, 2)) await rm(join(dir, '.nuxt'), { recursive: true, force: true }) const prepared = await exec('node', [join(repoRoot, 'src/cli.ts'), 'prepare'], { nodeOptions: { cwd: dir, env } }) expect(prepared.exitCode, prepared.stdout + prepared.stderr).toBe(0) expect(prepared.stdout.match(/\[setup\] .*/g)).toEqual(['[setup] from-config']) - expect(await references()).toHaveLength(1) + expect(await references()).toEqual(['/// ']) }, 120 * 1000) it('should reject one plugin instance shared by two configs', async () => { @@ -845,3 +845,301 @@ export default { expect(stdout + stderr).toContain(`\`build.config.ts\` configures the build, and so does \`builder()\` in the tsdown config. Move its options into \`builder()\` and delete the file. ${guide('moving-from-buildconfigts')}`) }, 60 * 1000) }) + +describe('with a root tsconfig that only lists references', () => { + const references = (node: string) => ({ + files: [], + exclude: ['dist', 'node_modules', 'playground'], + references: [node, './.nuxt/tsconfig.app.json', './.nuxt/tsconfig.server.json', './.nuxt/tsconfig.shared.json'].map(path => ({ path })), + }) + + it('should generate tsconfigs for the module entry, without the playground or the workspace, and with app aliases for module code', async () => { + const dir = await copyExample('.temp-tsdown-references-prepare', 'export default { plugins: [builder()] }\n') + await writeFile(join(dir, 'tsconfig.json'), JSON.stringify({ extends: './tsconfig.options.json', files: [], references: [{ path: './tsconfig.module.json' }] })) + await writeFile(join(dir, 'tsconfig.options.json'), JSON.stringify({ compilerOptions: { types: ['vitest/importMeta'] }, exclude: ['dist', 'node_modules', 'playground'] })) + await writeFile(join(dir, 'tsconfig.module.json'), JSON.stringify({ extends: './tsconfig.base.json' })) + await writeFile(join(dir, 'tsconfig.base.json'), JSON.stringify({ extends: './.nuxt/tsconfig.node' })) + await rm(join(dir, '.nuxt'), { recursive: true, force: true }) + expect((await exec('node', [join(repoRoot, 'src/cli.ts'), 'prepare', dir], { nodeOptions: { env: { ...process.env, NUXT_TELEMETRY_DISABLED: '1' } } })).exitCode).toBe(0) + const generated = async (name: string) => JSON.parse(await readFile(join(dir, `.nuxt/tsconfig.${name}.json`), 'utf-8')) + const [node, app] = [await generated('node'), await generated('app')] + expect(node.include).toContain('../src/*.ts') + expect(node.compilerOptions.paths['#app']).toBeDefined() + expect(node.compilerOptions.types).toContain('vitest/importMeta') + expect(node.compilerOptions.paths['#components']).toBeDefined() + expect(app.exclude).toContain('../playground') + expect(app.include).not.toContain('../../**/*') + expect(app.include).toContain('../src/runtime') + for (const name of ['app', 'node', 'server', 'shared']) { + const { include, exclude } = await generated(name) + expect([...include, ...exclude].filter((pattern: string) => pattern.startsWith('../src/dist')), name).toEqual([]) + } + await rm(dir, { recursive: true, force: true }) + }, 120 * 1000) + + it('should type runtime components with their own context and pass the type check', async () => { + const dir = await copyExample('.temp-tsdown-references-contexts', 'export default { plugins: [builder()] }\n') + const moduleSrc = join(dir, 'src/module.ts') + await writeFile(moduleSrc, (await readFile(moduleSrc, 'utf-8')) + .replace('import { defineNuxtModule, addPlugin, createResolver } from \'@nuxt/kit\'', 'import { defineNuxtModule, addPlugin, addImports, addTemplate, addTypeTemplate, createResolver } from \'@nuxt/kit\'\nimport { moduleHelper } from \'./helpers/name.ts\'') + .replace(' addPlugin(resolver.resolve(\'./runtime/plugins/plugin\'))', ' addPlugin(resolver.resolve(\'./runtime/plugins/plugin\'))\n _nuxt.options.alias[\'#my-types\'] = resolver.resolve(\'./runtime/types\')\n addImports({ name: \'useThing\', from: resolver.resolve(\'./runtime/composables/useThing\') })\n addTypeTemplate({ filename: \'module/my-module-names.d.ts\', getContents: () => \'declare module "#my-module/names" {\\n export const names: string[]\\n}\\n\' }, { nuxt: false })\n _nuxt.hook(\'prepare:types\', ({ tsConfig }) => { tsConfig.include?.push(\'./module/my-module-names.d.ts\') })\n addTemplate({ filename: \'my-module-virtual.mjs\', getContents: () => \'export default 1\\n\' })\n moduleHelper()')) + await mkdir(join(dir, 'src/helpers'), { recursive: true }) + await mkdir(join(dir, 'src/runtime/types'), { recursive: true }) + await mkdir(join(dir, 'src/runtime/server'), { recursive: true }) + await mkdir(join(dir, 'test/fixture'), { recursive: true }) + await mkdir(join(dir, 'types'), { recursive: true }) + await Promise.all([ + writeFile(join(dir, 'types/virtual.d.ts'), `declare module '#my-root-virtual' {\n export const rootValue: string\n}\n`), + writeFile(join(dir, 'content.d.ts'), `export * from './dist/content'\n`), + writeFile(join(dir, 'src/helpers/name.ts'), `import { useNuxt } from '@nuxt/kit'\n\nexport type { Linked } from '../runtime/linked.ts'\nexport type Jsx = typeof import('../runtime/components/JsxComponent.tsx').default\nexport type Names = ReturnType\n\nexport function moduleHelper(): unknown {\n return import.meta.vitest ? undefined : useNuxt().options.myModule\n}\n\nexport const callInit = (): unknown => useNuxt().callHook('my-module:init', 'shared-type')\n`), + writeFile(join(dir, 'src/runtime/composables/useVirtual.ts'), `import value from '#build/my-module-virtual'\n\nexport const useVirtual = (): unknown => value\n`), + writeFile(join(dir, 'src/runtime/composables/useNames.ts'), `import { names } from '#my-module/names'\n\nexport const useNames = (): string[] => names\n`), + writeFile(join(dir, 'src/runtime/linked.ts'), `import type { NuxtLink } from '#components'\n\nexport type Linked = typeof NuxtLink\n`), + writeFile(join(dir, 'src/env.d.ts'), `declare const __MY_MODULE_FLAG__: boolean\n`), + writeFile(join(dir, 'ambient.d.ts'), `declare module '#my-virtual' {\n export const virtualValue: string\n}\n`), + writeFile(join(dir, 'src/runtime/server/virtual.ts'), `import { virtualValue } from '#my-virtual'\nimport { rootValue } from '#my-root-virtual'\n\nexport const value: string = import.meta.vitest ? '' : virtualValue + rootValue\n`), + writeFile(join(dir, 'src/augments.d.ts'), `declare module '#app' {\n interface NuxtApp {\n $thing: 'thing'\n }\n}\n\nexport {}\n`), + writeFile(join(dir, 'src/runtime/composables/useAppThing.ts'), `import { useNuxtApp } from '#app'\n\nexport const useAppThing = (): 'thing' | undefined => import.meta.vitest ? undefined : useNuxtApp().$thing\n`), + writeFile(join(dir, 'src/runtime/types/index.ts'), `export type Trigger = 'onNuxtReady' | string[] | boolean\n`), + writeFile(join(dir, 'src/runtime/composables/useThing.ts'), `export function useThing() {\n return { loggedIn: __MY_MODULE_FLAG__, user: null as { name: string } | null }\n}\n`), + writeFile(join(dir, 'src/runtime/components/Triggered.vue'), `\n\n\n`), + writeFile(join(dir, 'src/runtime/components/ThingState.vue'), `\n\n\n`), + writeFile(join(dir, 'test/fixture/nuxt.config.ts'), `export default defineNuxtConfig({})\n`), + writeFile(join(dir, 'tsconfig.json'), JSON.stringify({ + files: [], + compilerOptions: { types: ['vitest/importMeta'] }, + exclude: ['dist', 'node_modules', 'playground'], + references: ['./.nuxt/tsconfig.app.json', './.nuxt/tsconfig.server.json', './.nuxt/tsconfig.shared.json', './.nuxt/tsconfig.node.json'].map(path => ({ path })), + })), + ]) + await rm(join(dir, '.nuxt'), { recursive: true, force: true }) + const built = await tsdown(dir) + expect(built.exitCode, built.stdout + built.stderr).toBe(0) + expect(built.stdout + built.stderr).not.toContain('type error') + expect(await readFile(join(dir, 'dist/runtime/components/ThingState.d.vue.ts'), 'utf-8')).toMatch(/loggedIn: boolean;\s+user: \{\s+name: string;\s+\} \| null;/) + expect(await readFile(join(dir, 'dist/runtime/components/Triggered.vue'), 'utf-8')).toMatch(/type: \[\s*String,\s*Array,\s*Boolean\s*\]/) + const generated = async (name: string) => JSON.parse(await readFile(join(dir, `.nuxt/tsconfig.${name}.json`), 'utf-8')) + for (const name of ['app', 'node', 'server', 'shared']) { + const config = await generated(name) + expect(config.files, name).toEqual(expect.arrayContaining([join(dir, 'src/env.d.ts'), join(dir, 'ambient.d.ts'), join(dir, 'types/virtual.d.ts')])) + expect(config.files, name).not.toContain(join(dir, 'src/augments.d.ts')) + expect(config.compilerOptions.types, name).toContain('vitest/importMeta') + } + for (const name of ['nuxt', 'nuxt.node']) { + expect(await readFile(join(dir, `.nuxt/${name}.d.ts`), 'utf-8'), name).toContain('/// ') + } + expect(await readFile(join(dir, '.nuxt/nuxt.shared.d.ts'), 'utf-8')).not.toContain('augments.d.ts') + expect(await readFile(join(dir, '.nuxt/nuxt.node.d.ts'), 'utf-8')).toContain('/// ') + const buildTypes = (await readFile(join(dir, '.nuxt/types/build.d.ts'), 'utf-8')).split('\n') + expect(buildTypes).toContain('declare module "#build/my-module-virtual";') + expect(buildTypes).not.toContain('declare module "#build/my-module-virtual.mjs";') + const app = await generated('app') + expect(app.include).not.toContain('../**/*') + const typecheck = await exec(join(repoRoot, 'node_modules/.bin/vue-tsc'), ['-b', '--noEmit'], { nodeOptions: { cwd: dir } }) + expect(typecheck.stdout + typecheck.stderr).toBe('') + await rm(dir, { recursive: true, force: true }) + }, 240 * 1000) + + it('should give tsdown the project that includes the module entry, unless the config sets `tsconfig`', async () => { + const dir = await copyExample('.temp-tsdown-references', 'export default { plugins: [builder()] }\n') + await writeFile(join(dir, 'tsconfig.module.json'), JSON.stringify({ extends: './.nuxt/tsconfig.node.json', compilerOptions: { erasableSyntaxOnly: true, useDefineForClassFields: false } })) + await writeFile(join(dir, 'tsconfig.override.json'), JSON.stringify({ extends: './.nuxt/tsconfig.node.json', compilerOptions: { useDefineForClassFields: true } })) + await writeFile(join(dir, 'tsconfig.json'), JSON.stringify(references('./tsconfig.module.json'))) + await appendFile(join(dir, 'src/module.ts'), `\nclass Fields { value!: string }\nexport const ownsField: boolean = Object.hasOwn(new Fields(), 'value')\n`) + const ownsField = async () => (await readFile(join(dir, 'dist/module.mjs'), 'utf-8')).includes('\tvalue;') + const result = await tsdown(dir, [], { CI: '' }) + expect(result.exitCode, result.stdout + result.stderr).toBe(0) + expect(result.stdout).toContain('tsconfig: tsconfig.module.json') + expect(result.stdout).toMatch(/Set `?isolatedDeclarations: true`? in `?tsconfig\.module\.json`?/) + expect(await ownsField()).toBe(false) + const referencesDist = await readFile(join(dir, 'dist/module.d.mts'), 'utf-8') + + await writeFile(join(dir, 'tsdown.config.ts'), `${builderImport}\nexport default { tsconfig: 'tsconfig.override.json', plugins: [builder()] }\n`) + expect((await tsdown(dir)).stdout).toContain('tsconfig: tsconfig.override.json') + expect(await ownsField()).toBe(true) + + await writeFile(join(dir, 'tsdown.config.ts'), `${builderImport}\nexport default { plugins: [builder()] }\n`) + await writeFile(join(dir, 'tsconfig.json'), JSON.stringify({ extends: './.nuxt/tsconfig.json', exclude: ['dist', 'node_modules', 'playground'] })) + const legacy = await tsdown(dir) + expect(legacy.exitCode).toBe(0) + expect(legacy.stdout).toContain('tsconfig: tsconfig.json') + expect(await readFile(join(dir, 'dist/module.d.mts'), 'utf-8')).toBe(referencesDist) + await rm(dir, { recursive: true, force: true }) + }, 180 * 1000) + + it('should resolve the module\'s own package to declarations of module code in its app, server and shared tsconfigs', async () => { + const dir = await copyExample('.temp-tsdown-references-own-package', 'export default { plugins: [builder()] }\n') + const { exports, main, types, publishConfig } = JSON.parse(await readFile(join(exampleDir, 'package.json'), 'utf-8')) + const pkg = JSON.parse(await readFile(join(dir, 'package.json'), 'utf-8')) + await writeFile(join(dir, 'package.json'), JSON.stringify({ ...pkg, exports, main, types, publishConfig, imports: { '#my-helpers': './src/helpers.ts' } })) + await writeFile(join(dir, 'src/helpers.ts'), `export interface Helper {\n name: string\n}\n`) + await writeFile(join(dir, 'src/extra.d.ts'), `export interface Extra {\n id: string\n}\n`) + const moduleSrc = join(dir, 'src/module.ts') + await writeFile(moduleSrc, (await readFile(moduleSrc, 'utf-8')) + .replace('import { defineNuxtModule, addPlugin, createResolver } from \'@nuxt/kit\'', 'import { defineNuxtModule, addPlugin, addTypeTemplate, createResolver } from \'@nuxt/kit\'\n\nexport type { Helper } from \'#my-helpers\'\nexport type { Extra } from \'./extra\'') + .replace(' addPlugin(resolver.resolve(\'./runtime/plugins/plugin\'))', ' addPlugin(resolver.resolve(\'./runtime/plugins/plugin\'))\n addTypeTemplate({ filename: \'types/my-module.d.ts\', getContents: () => \'import type { ModuleOptions } from "my-module"\\ndeclare module "#app" {\\n interface NuxtApp {\\n $myModuleOptions: ModuleOptions\\n }\\n}\\nexport {}\\n\' })\n const configured: unknown = _nuxt.options.myModule\n void configured')) + await mkdir(join(dir, 'src/runtime/server'), { recursive: true }) + await mkdir(join(dir, 'shared'), { recursive: true }) + await writeFile(join(dir, 'shared/options.ts'), `import type { Extra, ModuleOptions } from 'my-module'\n\nexport const sharedApiKey = (options: ModuleOptions, extra: Extra): string => options.apiKey + extra.id\n// @ts-expect-error a string is not a number\nexport const extraId = (extra: Extra): number => extra.id\n`) + await writeFile(join(dir, 'src/runtime/composables/useUtils.ts'), `import { myModuleUtils } from 'my-module/utils'\n\nexport const useUtils = (): () => void => myModuleUtils\n`) + await writeFile(join(dir, 'src/runtime/server/options.ts'), `import type { ModuleOptions } from 'my-module'\n\nexport const apiKey = (options: ModuleOptions): string => options.apiKey\n`) + await writeFile(join(dir, 'tsconfig.json'), JSON.stringify(references('./.nuxt/tsconfig.node.json'))) + await rm(join(dir, '.nuxt'), { recursive: true, force: true }) + const prepared = await exec('node', [join(repoRoot, 'src/cli.ts'), 'prepare', dir], { nodeOptions: { env: { ...process.env, NUXT_TELEMETRY_DISABLED: '1' } } }) + expect(prepared.exitCode, prepared.stdout + prepared.stderr).toBe(0) + const typecheck = await exec(join(repoRoot, 'node_modules/.bin/vue-tsc'), ['-b', '--noEmit'], { nodeOptions: { cwd: dir } }) + expect(typecheck.stdout + typecheck.stderr).toBe('') + for (const name of ['app', 'server', 'shared']) { + const listed = await exec(join(repoRoot, 'node_modules/.bin/vue-tsc'), ['-p', `.nuxt/tsconfig.${name}.json`, '--noEmit', '--listFilesOnly'], { nodeOptions: { cwd: dir } }) + const files = listed.stdout.split('\n').map(file => file.trim()) + expect(files, name).not.toContain(join(dir, 'src/module.ts')) + expect(files, name).not.toContain(join(dir, 'src/utils.ts')) + expect(files, name).not.toContain(join(dir, 'src/helpers.ts')) + expect(files, name).toContain(join(dir, '.nuxt/module-builder/declarations/src/module.d.ts')) + } + const app = (await exec(join(repoRoot, 'node_modules/.bin/vue-tsc'), ['-p', '.nuxt/tsconfig.app.json', '--noEmit', '--listFilesOnly'], { nodeOptions: { cwd: dir } })).stdout + expect(app).toContain(join(dir, '.nuxt/module-builder/declarations/src/utils.d.ts')) + await rm(dir, { recursive: true, force: true }) + }, 180 * 1000) + + it('should write the declarations of module code with oxc when its tsconfig sets `isolatedDeclarations`', async () => { + const dir = await copyExample('.temp-tsdown-references-own-package-isolated', 'export default { plugins: [builder()] }\n') + await mkdir(join(dir, 'src/nested'), { recursive: true }) + await writeFile(join(dir, 'src/nested/payload.ts'), `export interface Payload {\n value: string\n}\n`) + await writeFile(join(dir, 'src/nested/shape.ts'), `export interface Shape {\n sides: number\n}\n`) + await writeFile(join(dir, 'src/utils.ts'), `export const myModuleUtils = (): void => {}\n`) + const pkg = JSON.parse(await readFile(join(dir, 'package.json'), 'utf-8')) + await writeFile(join(dir, 'package.json'), JSON.stringify({ ...pkg, imports: { '#payload': './src/nested/payload.ts' } })) + await writeFile(join(dir, 'src/module.ts'), [ + `import { defineNuxtModule } from '@nuxt/kit'`, + `import type { NuxtModule } from '@nuxt/schema'`, + `import type { Payload } from '#payload'`, + `import type { Shape } from './nested/shape.ts'`, + ``, + `export interface ModuleOptions {\n payload?: Payload\n shape?: Shape\n}`, + ``, + `const module: NuxtModule = defineNuxtModule({ meta: { name: 'my-module', configKey: 'myModule' } })`, + ``, + `export default module`, + ``, + ].join('\n')) + await writeFile(join(dir, 'src/runtime/composables/usePayload.ts'), `import type { ModuleOptions } from 'my-module'\n\nexport const usePayload = (options: ModuleOptions): string | undefined => options.payload?.value\n`) + await writeFile(join(dir, 'tsconfig.module.json'), JSON.stringify({ extends: './.nuxt/tsconfig.node.json', compilerOptions: { isolatedDeclarations: true, declaration: true, allowJs: false } })) + await writeFile(join(dir, 'tsconfig.json'), JSON.stringify(references('./tsconfig.module.json'))) + await rm(join(dir, '.nuxt'), { recursive: true, force: true }) + const prepared = await exec('node', [join(repoRoot, 'src/cli.ts'), 'prepare', dir], { nodeOptions: { env: { ...process.env, NUXT_TELEMETRY_DISABLED: '1' } } }) + expect(prepared.exitCode, prepared.stdout + prepared.stderr).toBe(0) + expect(prepared.stdout + prepared.stderr).not.toContain('The build reports the same errors') + expect(await readFile(join(dir, '.nuxt/module-builder/declarations/src/nested/payload.d.ts'), 'utf-8')).toContain('interface Payload') + const moduleDeclaration = await readFile(join(dir, '.nuxt/module-builder/declarations/src/module.d.ts'), 'utf-8') + expect(moduleDeclaration).toContain('from "./nested/payload.js"') + expect(moduleDeclaration).toContain('from "./nested/shape.js"') + const typecheck = await exec(join(repoRoot, 'node_modules/.bin/vue-tsc'), ['-b', '--noEmit'], { nodeOptions: { cwd: dir } }) + expect(typecheck.stdout + typecheck.stderr).toBe('') + const listed = await exec(join(repoRoot, 'node_modules/.bin/vue-tsc'), ['-p', '.nuxt/tsconfig.app.json', '--noEmit', '--listFilesOnly'], { nodeOptions: { cwd: dir } }) + expect(listed.stdout).toContain(join(dir, '.nuxt/module-builder/declarations/src/nested/payload.d.ts')) + expect(listed.stdout).not.toContain(join(dir, 'src/nested/payload.ts')) + expect(listed.stdout).not.toContain(join(dir, 'src/nested/shape.ts')) + await rm(dir, { recursive: true, force: true }) + }, 180 * 1000) + + it('should warn about a declaration error in module code at prepare, and write the other declarations', async () => { + const dir = await copyExample('.temp-tsdown-references-own-package-error', 'export default { plugins: [builder()] }\n') + const store = (name: string) => `node_modules/.pnpm/${name}@1.0.0/node_modules/${name}` + const files = { + [`${store('fake-logger')}/package.json`]: JSON.stringify({ name: 'fake-logger', type: 'module', exports: { '.': { types: './index.d.ts', default: './index.js' } } }), + [`${store('fake-logger')}/index.d.ts`]: `export interface LoggerInstance { log: (message: string) => void }\nexport declare function createLogger(): LoggerInstance\n`, + [`${store('fake-shared')}/package.json`]: JSON.stringify({ name: 'fake-shared', type: 'module', exports: { '.': { types: './index.d.ts', default: './index.js' } } }), + [`${store('fake-shared')}/index.d.ts`]: `import { createLogger } from 'fake-logger'\nexport declare function createModuleLogger(name: string): ReturnType\n`, + 'src/logger.ts': `import { createModuleLogger } from 'fake-shared'\n\nexport const logger = createModuleLogger('my-module')\n`, + } + for (const [file, contents] of Object.entries(files)) { + await mkdir(dirname(join(dir, file)), { recursive: true }) + await writeFile(join(dir, file), contents) + } + await symlink(join(dir, store('fake-logger')), join(dir, 'node_modules/.pnpm/fake-shared@1.0.0/node_modules/fake-logger')) + await symlink(join(dir, store('fake-shared')), join(dir, 'node_modules/fake-shared')) + await writeFile(join(dir, 'tsconfig.json'), JSON.stringify(references('./.nuxt/tsconfig.node.json'))) + const prepared = await exec('node', [join(repoRoot, 'src/cli.ts'), 'prepare', dir], { nodeOptions: { env: { ...process.env, NUXT_TELEMETRY_DISABLED: '1' } } }) + expect(prepared.exitCode, prepared.stdout + prepared.stderr).toBe(0) + expect(prepared.stdout + prepared.stderr).toContain('The build reports the same errors') + expect(prepared.stdout + prepared.stderr).toContain('src/logger.ts(3,14): error TS2883') + expect(existsSync(join(dir, '.nuxt/module-builder/declarations/src/module.d.ts'))).toBe(true) + expect(existsSync(join(dir, '.nuxt/module-builder/declarations/types.d.mts'))).toBe(true) + await rm(dir, { recursive: true, force: true }) + }, 120 * 1000) + + it('should keep `.nuxt/tsconfig.json` one program over the module\'s sources, with the generated tsconfigs adapted', async () => { + const dir = await copyExample('.temp-tsdown-references-legacy-prepare', 'export default { plugins: [builder()] }\n') + const moduleSrc = join(dir, 'src/module.ts') + await writeFile(moduleSrc, (await readFile(moduleSrc, 'utf-8')) + .replace('import { defineNuxtModule, addPlugin, createResolver } from \'@nuxt/kit\'', 'import { defineNuxtModule, addPlugin, addTypeTemplate, createResolver } from \'@nuxt/kit\'') + .replace(' addPlugin(resolver.resolve(\'./runtime/plugins/plugin\'))', ' addPlugin(resolver.resolve(\'./runtime/plugins/plugin\'))\n addTypeTemplate({ filename: \'types/my-module.d.ts\', getContents: () => \'import type { ModuleOptions } from "my-module"\\ndeclare module "#app" {\\n interface NuxtApp {\\n $myModuleOptions: ModuleOptions\\n }\\n}\\nexport {}\\n\' })\n const configured: unknown = _nuxt.options.myModule\n void configured\n void _nuxt.callHook(\'my-module:init\', \'shared-type\')')) + await mkdir(join(dir, 'src/runtime/server'), { recursive: true }) + await writeFile(join(dir, 'src/runtime/server/options.ts'), `export const apiKey = (options: { apiKey: string }): string => options.apiKey\n`) + await writeFile(join(dir, 'tsconfig.json'), JSON.stringify({ extends: './.nuxt/tsconfig.json', exclude: ['dist', 'node_modules', 'playground', 'tsdown.config.ts', 'nuxt.config.ts'] })) + await writeFile(join(dir, 'nuxt.config.ts'), `export default { buildDir: '.nuxt-custom' }\n`) + await rm(join(dir, '.nuxt'), { recursive: true, force: true }) + const prepared = await exec('node', [join(repoRoot, 'src/cli.ts'), 'prepare', dir], { nodeOptions: { env: { ...process.env, NUXT_TELEMETRY_DISABLED: '1' } } }) + expect(prepared.exitCode, prepared.stdout + prepared.stderr).toBe(0) + const generated = async (name: string) => JSON.parse(await readFile(join(dir, `.nuxt/${name}.json`), 'utf-8')) + expect((await generated('tsconfig.app')).compilerOptions.paths['my-module']).toEqual(['./module-builder/declarations/types.d.mts']) + const legacy = await generated('tsconfig') + expect(legacy.compilerOptions.paths['my-module']).toBeUndefined() + expect(legacy.include).not.toContain('./module-builder/declarations/types.d.mts') + expect(legacy.exclude).not.toContain('../src/runtime/server') + const typecheck = await exec(join(repoRoot, 'node_modules/.bin/vue-tsc'), ['--noEmit'], { nodeOptions: { cwd: dir } }) + expect(typecheck.stdout).not.toMatch(/error TS5\d{3}/) + expect(typecheck.stdout.split('\n').filter(line => /^(?:src|\.nuxt)\//.test(line))).toEqual([]) + const listed = await exec(join(repoRoot, 'node_modules/.bin/vue-tsc'), ['--noEmit', '--listFilesOnly'], { nodeOptions: { cwd: dir } }) + expect(listed.stdout).toContain(join(dir, 'src/module.ts')) + expect(listed.stdout).toContain(join(dir, 'src/runtime/server/options.ts')) + expect(listed.stdout).not.toContain(join(dir, '.nuxt/module-builder/declarations/src/module.d.ts')) + await rm(dir, { recursive: true, force: true }) + }, 120 * 1000) + + it('should name a dependency in runtime declarations by its package when only another part of the module imports it', async () => { + const dir = await copyExample('.temp-tsdown-references-portable', 'export default { plugins: [builder()] }\n') + const store = (name: string) => `node_modules/.pnpm/${name}@1.0.0/node_modules/${name}` + const files = { + [`${store('fake-logger')}/package.json`]: JSON.stringify({ name: 'fake-logger', type: 'module', exports: { '.': { types: './index.d.ts', default: './index.js' } } }), + [`${store('fake-logger')}/index.d.ts`]: `export interface LoggerInstance { log: (message: string) => void }\nexport declare function createLogger(): LoggerInstance\n`, + [`${store('fake-logger')}/index.js`]: `export const createLogger = () => ({ log: console.log })\n`, + [`${store('fake-shared')}/package.json`]: JSON.stringify({ name: 'fake-shared', type: 'module', exports: { '.': { types: './index.d.ts', default: './index.js' } } }), + [`${store('fake-shared')}/index.d.ts`]: `import { createLogger } from 'fake-logger'\nexport declare function createModuleLogger(name: string): ReturnType\n`, + [`${store('fake-shared')}/index.js`]: `import { createLogger } from 'fake-logger'\nexport const createModuleLogger = () => createLogger()\n`, + 'src/runtime/logger.ts': `import { createModuleLogger } from 'fake-shared'\n\nexport const logger = createModuleLogger('my-module')\n`, + 'src/runtime/server/log.ts': `import { createLogger } from 'fake-logger'\n\nexport const serverLogger = createLogger()\n`, + } + for (const [file, contents] of Object.entries(files)) { + await mkdir(dirname(join(dir, file)), { recursive: true }) + await writeFile(join(dir, file), contents) + } + await symlink(join(dir, store('fake-logger')), join(dir, 'node_modules/.pnpm/fake-shared@1.0.0/node_modules/fake-logger')) + for (const name of ['fake-logger', 'fake-shared']) { + await symlink(join(dir, store(name)), join(dir, 'node_modules', name)) + } + const pkg = JSON.parse(await readFile(join(dir, 'package.json'), 'utf-8')) + await writeFile(join(dir, 'package.json'), JSON.stringify({ ...pkg, dependencies: { ...pkg.dependencies, 'fake-logger': '1.0.0', 'fake-shared': '1.0.0' } })) + await writeFile(join(dir, 'tsconfig.json'), JSON.stringify(references('./.nuxt/tsconfig.node.json'))) + const built = await tsdown(dir) + expect(built.exitCode, built.stdout + built.stderr).toBe(0) + expect(await readFile(join(dir, 'dist/runtime/logger.d.ts'), 'utf-8')).toContain('import("fake-logger").LoggerInstance') + await rm(dir, { recursive: true, force: true }) + }, 180 * 1000) + + it('should transform each runtime file with the referenced project that includes it', async () => { + const dir = await copyExample('.temp-tsdown-references-transforms', 'export default { plugins: [builder()] }\n') + await mkdir(join(dir, 'src/runtime/server'), { recursive: true }) + const source = `class Fields { value!: string }\nexport const ownsField: boolean = Object.hasOwn(new Fields(), 'value')\n` + await writeFile(join(dir, 'src/runtime/fields.ts'), source) + await writeFile(join(dir, 'src/runtime/server/fields.ts'), source) + await writeFile(join(dir, 'tsconfig.server.json'), JSON.stringify({ extends: './.nuxt/tsconfig.server.json', compilerOptions: { useDefineForClassFields: false } })) + await writeFile(join(dir, 'tsconfig.json'), JSON.stringify(references('./.nuxt/tsconfig.node.json')).replace('./.nuxt/tsconfig.server.json', './tsconfig.server.json')) + const built = await tsdown(dir) + expect(built.exitCode, built.stdout + built.stderr).toBe(0) + expect(await readFile(join(dir, 'dist/runtime/fields.js'), 'utf-8')).toContain('\tvalue;') + expect(await readFile(join(dir, 'dist/runtime/server/fields.js'), 'utf-8')).not.toContain('value;') + await rm(dir, { recursive: true, force: true }) + }, 180 * 1000) +}) diff --git a/test/unit.spec.ts b/test/unit.spec.ts index fa17db71..6419edf6 100644 --- a/test/unit.spec.ts +++ b/test/unit.spec.ts @@ -17,7 +17,7 @@ import type { Rolldown, UserConfig } from 'tsdown' import { exec } from 'tinyexec' import { runtimeExternals } from '../src/tsdown/runtime-externals.ts' import { selfReferencePaths } from '../src/build/tsconfig.ts' -import { SERVER_ROUTES_STUB, createTsconfigResolver, declarationPaths, tsconfigPaths, writeDerivedTsconfig, writeServerRoutesStub } from '../src/rolldown/tsconfig.ts' +import { SERVER_ROUTES_STUB, createTsconfigResolver, declarationPaths, rootTsconfig, tsconfigPaths, writeDerivedTsconfig, writeServerRoutesStub } from '../src/rolldown/tsconfig.ts' import { transformCss } from '../src/rolldown/stylesheets.ts' import { declarationTargets, rewriteRuntimeDeclarations } from '../src/build/aliases.ts' import { checkLegacyCJSPaths, checkLegacyDeclarationPaths, checkMissingPaths, checkNode10DeclarationPaths, checkStaleTypesField } from '../src/build/deprecations.ts' @@ -1184,6 +1184,47 @@ describe('createTsconfigResolver', () => { await rm(cwd, { recursive: true, force: true }) }) + it('should resolve each file to the referenced project that includes it, preferring the module\'s own tsconfigs and leaving the app\'s last', async () => { + const cwd = await mkdtemp(join(tmpdir(), 'module-builder-references-')) + await mkdir(join(cwd, '.nuxt')) + const write = (file: string, config: object) => writeFile(join(cwd, file), JSON.stringify(config)) + await write('.nuxt/tsconfig.app.json', { include: ['../src/runtime'] }) + await write('.nuxt/tsconfig.server.json', { include: ['../src/runtime/server'] }) + await write('.nuxt/tsconfig.node.json', { include: ['../src/*.ts'] }) + await write('tsconfig.module.json', { extends: './.nuxt/tsconfig.node.json', references: [{ path: './tsconfig.extra.json' }] }) + await write('tsconfig.extra.json', { include: ['extra'] }) + await write('tsconfig.json', { files: [], references: [{ path: './.nuxt/tsconfig.app.json' }, { path: './.nuxt/tsconfig.server.json' }, { path: './tsconfig.module.json' }] }) + const { resolve: projectOf } = await createTsconfigResolver(cwd) + expect(projectOf(join(cwd, 'src/module.ts'))?.path).toBe(join(cwd, 'tsconfig.module.json')) + expect(projectOf(join(cwd, 'extra/helper.ts'))?.path).toBe(join(cwd, 'tsconfig.extra.json')) + expect(projectOf(join(cwd, 'src/runtime/server/api.ts'))?.path).toBe(join(cwd, '.nuxt/tsconfig.server.json')) + expect(projectOf(join(cwd, 'src/runtime/plugin.ts'))?.path).toBe(join(cwd, '.nuxt/tsconfig.app.json')) + + await write('tsconfig.runtime.json', { extends: './.nuxt/tsconfig.app.json' }) + await write('tsconfig.json', { files: [], references: [{ path: './.nuxt/tsconfig.app.json' }, { path: './.nuxt/tsconfig.server.json' }, { path: './tsconfig.runtime.json' }] }) + expect((await createTsconfigResolver(cwd)).resolve(join(cwd, 'src/runtime/plugin.ts'))?.path).toBe(join(cwd, 'tsconfig.runtime.json')) + await rm(cwd, { recursive: true, force: true }) + }) + + it('should read the root `compilerOptions` and `exclude` through `extends`, apart from tsconfigs in `.nuxt`', async () => { + const cwd = await mkdtemp(join(tmpdir(), 'module-builder-root-')) + await mkdir(join(cwd, '.nuxt')) + await mkdir(join(cwd, 'config')) + const write = (file: string, config: object) => writeFile(join(cwd, file), JSON.stringify(config)) + await write('.nuxt/tsconfig.node.json', { compilerOptions: { types: ['generated'] }, exclude: ['../generated'] }) + await write('config/base.json', { compilerOptions: { types: ['vitest/config', './types/globals.d.ts'], strict: true }, exclude: ['../test'] }) + await write('tsconfig.json', { extends: ['./config/base', './.nuxt/tsconfig.node.json'], files: [], compilerOptions: { strict: false } }) + expect(await rootTsconfig(cwd)).toEqual({ compilerOptions: { types: ['vitest/config', join(cwd, 'types/globals.d.ts')], strict: false }, exclude: [join(cwd, 'test')] }) + await write('tsconfig.json', { extends: './config/base.json', exclude: ['dist'] }) + expect((await rootTsconfig(cwd)).exclude).toEqual([join(cwd, 'dist')]) + await mkdir(join(cwd, 'node_modules/shared-config'), { recursive: true }) + await write('node_modules/shared-config/package.json', { name: 'shared-config', tsconfig: 'base.json' }) + await write('node_modules/shared-config/base.json', { compilerOptions: { types: ['youtube'] } }) + await write('tsconfig.json', { extends: 'shared-config', files: [] }) + expect((await rootTsconfig(cwd)).compilerOptions).toEqual({ types: ['youtube'] }) + await rm(cwd, { recursive: true, force: true }) + }) + it('should keep a tsconfig that takes its types from the module\'s own `.nuxt`', async () => { const cwd = await mkdtemp(join(tmpdir(), 'module-builder-own-')) await mkdir(join(cwd, '.nuxt'))