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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/4.configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ An entry is either bundled into one file, like `src/module.ts`, or transpiled fi

The build writes each bundled entry to `dist/<name>.mjs`, with its declarations in `dist/<name>.d.mts`. The entries in the example above produce `dist/utils.mjs` and `dist/kit.mjs`. Add each one to the `exports` of `package.json`, as described in [Exports](/docs/api/module-builder/exports#bundled-entries).

Relative imports in a bundled entry carry the imported file's extension, as in module code. [Source exports](/docs/api/module-builder/develop-and-publish#source-exports) point at the entry as it is, so the entry has to load as written:
Relative imports in a bundled entry carry the imported file's extension, as in module code. [Source exports](/docs/api/module-builder/develop-and-publish#source-exports) point at the entry as it is, so when `exports` or `imports` point at it, the entry and the files that it imports follow every rule of [module code](/docs/api/module-builder/typescript#module-code):

```ts [src/utils.ts]
import { normalizeOptions } from './options.ts'
Expand Down
3 changes: 2 additions & 1 deletion docs/5.typescript.md
Original file line number Diff line number Diff line change
Expand Up @@ -165,8 +165,9 @@ Each part is type-checked on its own, with the files that it imports and the typ
- `src/module.ts`.
- Every file that `src/module.ts` imports by value, including runtime files.
- `tsdown.config.ts`.
- With [source exports](/docs/api/module-builder/develop-and-publish#source-exports), each [bundled entry](/docs/api/module-builder/configuration#bundled-entries) that `exports` or `imports` points at, and every file that it imports by value.

Node strips types and resolves imports as written. Module code therefore follows the rules in the following sections. `prepare`, `tsdown`, and `nuxt-module-build build` stop with a list of every import and every piece of syntax that breaks them. Each entry has its file, line, column, and fix, and an entry in a runtime file also names the module code that imports it. An import that the check can't follow, such as one of a file that doesn't exist yet, ends the list: the files behind it are checked once it resolves. Until the list is empty, `prepare` doesn't generate `.nuxt`.
Node strips types and resolves imports as written. Module code therefore follows the rules in the following sections. `prepare`, `tsdown`, and `nuxt-module-build build` stop with a list of every import and every piece of syntax that breaks them. Each entry has its file, line, column, and fix, and an entry in a runtime file also names the module code that imports it. A problem in a bundled entry, or in a file that it imports, names the key of `exports` or `imports` that points at the bundled entry. An import that the check can't follow, such as one of a file that doesn't exist yet, ends the list: the files behind it are checked once it resolves. Until the list is empty, `prepare` doesn't generate `.nuxt`.

### Relative imports carry their extension

Expand Down
2 changes: 1 addition & 1 deletion docs/upgrade-v2.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ After each build, a warning lists any other path in these fields that the build

### Step 4: Make module code load with Node

`nuxt-module-build prepare` and the build load module code with Node, as Nuxt 5 does. Module code is `src/module.ts`, every file that it imports by value (runtime files included), and `tsdown.config.ts`. In these files:
`nuxt-module-build prepare` and the build load module code with Node, as Nuxt 5 does. Module code is `src/module.ts`, every file that it imports by value (runtime files included), and `tsdown.config.ts`. With the source exports of step 6, it also includes each bundled entry that `exports` or `imports` points at, and the files that it imports by value. In these files:

- Add the file's extension to every relative import, type-only imports included: `./utils` becomes `./utils.ts`, and `./dir` becomes `./dir/index.ts`.
- Replace imports through tsconfig `paths` aliases with relative imports, or with entries in the `imports` field of `package.json`.
Expand Down
2 changes: 1 addition & 1 deletion src/build/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ function reportReplacedPaths(cwd: string, tsconfigs: TsconfigResolver) {
export async function prepareBuild(plan: BuildPlan, { keepOutput }: { keepOutput: boolean }): Promise<void> {
const { cwd, outDir, entries, runtimeDirs } = plan
await plan.config.callHook?.('build:before', plan)
assertLoadableModuleCode(cwd, [entries.module], runtimeDirs, Object.values(entries))
assertLoadableModuleCode(cwd, [entries.module], runtimeDirs, { entries, pkg: plan.pkg, outDir })
if (!keepOutput) {
await rm(outDir, { recursive: true, force: true })
}
Expand Down
80 changes: 60 additions & 20 deletions src/build/loader.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { existsSync, readFileSync } from 'node:fs'
import { registerHooks } from 'node:module'
import { fileURLToPath, pathToFileURL } from 'node:url'
import { dirname, join, relative, resolve } from 'pathe'
import { basename, dirname, join, relative, resolve } from 'pathe'
import { createPathsMatcher, getTsconfig } from 'get-tsconfig'
import type { Diagnostic } from 'nostics'
import type { Expression, ImportDeclaration, ObjectExpression, TSGlobalDeclaration, TSModuleDeclaration } from '@oxc-project/types'
Expand All @@ -12,7 +12,7 @@ import { packageName } from '../transpile/tsconfig.ts'
import { findPackageDir, findUp, isFile, isInside, isPlainObject, NODE_MODULES_RE, probe, relativeSpecifier, resolveFrom, SCRIPT_RE } from '../utils.ts'
import type { PackageJson } from '../utils.ts'
import { errors } from '../diagnostics.ts'
import { importsKeyFor } from './package.ts'
import { importsKeyFor, sourceLoadedEntries } from './package.ts'

const VIRTUAL_ALIAS_RE = /^#(?:app|imports|build)(?:\/|$)/
const PATH_ALIAS_RE = /^(?:~|@\/)/
Expand Down Expand Up @@ -71,6 +71,8 @@ export interface ModuleCodeIssue {
column: number
/** For a file in a runtime directory, the module code that imports it, as `file:line`. */
importedBy?: string
/** For a bundled entry loaded from source and the files it imports, the key of `package.json` that loads it, such as `` `./utils` in `exports` ``. */
loadedBy?: string
/** What Node cannot load, and what to write instead. */
message: string
/** Whether the issue is an import that the check cannot follow, so the files it imports are not checked. */
Expand All @@ -87,23 +89,31 @@ const NON_ERASABLE: Array<[message: string, matches: (node: Node, parent: Node |
['decorator (call the decorator as a function)', node => node.type === 'Decorator'],
]

export interface BundledEntries {
/** Bundled entries keyed by output name, as paths relative to the module root. */
entries: Record<string, string>
/** `package.json` as it is on disk. */
pkg: PackageJson
outDir: string
}

/**
* Everything in `entries` and the sources they import by value, which Node loads with
* them, that Node cannot load as written: TypeScript syntax that stripping types does not
* remove, relative specifiers without the file's extension, tsconfig `paths` aliases and
* the aliases only a Nuxt app provides. Type-only imports are erased before Node sees
* them. Files in `runtimeDirs` that are not imported this way are left to the build.
*
* `otherEntries`, bundled entries that source exports point at as they are, only need the
* extensions of their relative imports outside `runtimeDirs`.
* The `bundled` entries that `exports` or `imports` load from source are checked in the same
* way, and an entry that is itself a `.tsx` or `.vue` file is reported, as Node loads neither. The others are loaded from `outDir`, once built, so they only need the extensions of
* their relative imports outside `runtimeDirs`.
*/
export function findModuleCodeIssues(cwd: string, entries: string[], runtimeDirs: string[], otherEntries: string[] = []): ModuleCodeIssue[] {
export function findModuleCodeIssues(cwd: string, entries: string[], runtimeDirs: string[], bundled?: BundledEntries): ModuleCodeIssue[] {
const found: ModuleCodeIssue[] = []
const checked = new Set<string>()
walkSources(cwd, entries, (file, analysis, importer) => {
checked.add(file)
const visit = (loadedBy?: string) => (file: string, analysis: SourceAnalysis, importer?: Importer) => {
const importedBy = importer && runtimeDirs.some(dir => isInside(dir, file)) ? `${relative(cwd, importer.file)}:${importer.line}` : undefined
const issue = (location: { line: number, column: number }, message: string) => found.push({ file: relative(cwd, file), ...location, ...importedBy && { importedBy }, message })
const context = { ...importedBy && { importedBy }, ...loadedBy && { loadedBy } }
const issue = (location: { line: number, column: number }, message: string) => found.push({ file: relative(cwd, file), ...location, ...context, message })
for (const { message, ...location } of analysis.nonErasable) {
issue(location, message)
}
Expand All @@ -112,14 +122,16 @@ export function findModuleCodeIssues(cwd: string, entries: string[], runtimeDirs
continue
}
if (typeof resolution === 'string' && resolution !== EXTERNAL) {
found.push({ file: relative(cwd, file), ...location, ...importedBy && { importedBy }, message: `\`${specifier}\` ${resolution}`, unfollowed: true })
found.push({ file: relative(cwd, file), ...location, ...context, message: `\`${specifier}\` ${resolution}`, unfollowed: true })
continue
}
if (VIRTUAL_ALIAS_RE.test(specifier)) {
issue(location, `\`${specifier}\` only exists in a Nuxt app (move the code that uses it into a runtime file the module adds, or import types only)`)
}
if (JSON_RE.test(typeof resolution === 'object' ? resolution.file : specifier) && !json) {
issue(location, `\`${specifier}\` is JSON (use \`import pkg from '${specifier}' with { type: 'json' }\` and read \`pkg.version\`; destructuring \`pkg\` bundles the whole file)`)
const target = typeof resolution === 'object' ? resolution.file : specifier
if (JSON_RE.test(target) && !json) {
const [name, read] = basename(target) === 'package.json' ? ['pkg', '`pkg.version`'] : ['data', 'properties from `data`']
issue(location, `\`${specifier}\` is JSON (use \`import ${name} from '${specifier}' with { type: 'json' }\` and read ${read}; destructuring \`${name}\` bundles the whole file)`)
}
if (typeof resolution !== 'object') {
continue
Expand All @@ -136,17 +148,37 @@ export function findModuleCodeIssues(cwd: string, entries: string[], runtimeDirs
issue(location, `\`${specifier}\` is a tsconfig \`paths\` alias (use \`${suggestion}\`, or an entry in the \`imports\` of \`package.json\`)`)
}
}
})
}
const walked = walkState(cwd)
const roots = new Set<string>()
const reportUnloadableRoot = (file: string, loadedBy?: string) => {
if (roots.has(file) || !UNLOADABLE_RE.test(file) || !existsSync(file)) {
return
}
roots.add(file)
const kind = file.endsWith('.vue') ? 'a single-file component' : 'JSX'
found.push({ file: relative(cwd, file), line: 1, column: 1, ...loadedBy && { loadedBy }, message: `\`${relative(cwd, file)}\` is ${kind}, which Node cannot load (write it as \`.ts\`)` })
}
for (const entry of entries) {
reportUnloadableRoot(resolve(cwd, entry))
}
walkSources(cwd, entries, visit(), walked)
const otherEntries = Object.values(bundled?.entries ?? {})
const sourceLoaded = bundled ? sourceLoadedEntries(cwd, bundled.pkg, bundled.outDir, bundled.entries) : new Map<string, string>()
for (const [file, loadedBy] of sourceLoaded) {
reportUnloadableRoot(file, loadedBy)
walkSources(cwd, [file], visit(loadedBy), walked)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
walkSources(cwd, otherEntries, (file, analysis) => {
if (checked.has(file) || runtimeDirs.some(dir => isInside(dir, file))) {
if (runtimeDirs.some(dir => isInside(dir, file))) {
return
}
for (const { specifier, typeOnly, json: _, resolution, ...location } of analysis.imports) {
if (!typeOnly && typeof resolution === 'object' && resolution.via === 'relative' && resolution.file !== resolve(dirname(file), specifier)) {
found.push({ file: relative(cwd, file), ...location, message: `\`${specifier}\` (use \`${relativeSpecifier(file, resolution.file)}\`)` })
}
}
})
}, walked)
return found.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.column - b.column)
}

Expand All @@ -156,8 +188,8 @@ export function hasLoadIssues(found: ModuleCodeIssue[]): boolean {
}

/** Fails for {@link findModuleCodeIssues} findings. */
export function assertLoadableModuleCode(cwd: string, entries: string[], runtimeDirs: string[], otherEntries: string[] = []): void {
const found = findModuleCodeIssues(cwd, entries, runtimeDirs, otherEntries)
export function assertLoadableModuleCode(cwd: string, entries: string[], runtimeDirs: string[], bundled?: BundledEntries): void {
const found = findModuleCodeIssues(cwd, entries, runtimeDirs, bundled)
if (hasLoadIssues(found)) {
throw moduleCodeError(cwd, found)
}
Expand Down Expand Up @@ -191,9 +223,17 @@ interface Importer {
line: number
}

function walkSources(cwd: string, entries: string[], visit: (file: string, analysis: SourceAnalysis, importer?: Importer) => void) {
const paths = pathsMatcher(cwd)
const seen = new Set<string>()
/** What every walk of these sources shares, so that a file reached from several entries is analysed once. */
interface WalkState {
seen: Set<string>
paths: PathsMatcher
}

function walkState(cwd: string): WalkState {
return { seen: new Set(), paths: pathsMatcher(cwd) }
}

function walkSources(cwd: string, entries: string[], visit: (file: string, analysis: SourceAnalysis, importer?: Importer) => void, { seen, paths }: WalkState = walkState(cwd)) {
const queue: Array<{ file: string, importer?: Importer }> = entries.map(entry => ({ file: resolve(cwd, entry) }))
while (queue.length) {
const { file, importer } = queue.shift()!
Expand Down
Loading
Loading