// ██████╗ ██████╗ ███╗ ███╗██████╗ ██╗██╗ █████╗ ████████╗██╗ ██████╗ ███╗ ██╗ // ██╔════╝██╔═══██╗████╗ ████║██╔══██╗██║██║ ██╔══██╗╚══██╔══╝██║██╔═══██╗████╗ ██║ // ██║ ██║ ██║██╔████╔██║██████╔╝██║██║ ███████║ ██║ ██║██║ ██║██╔██╗ ██║ // ██║ ██║ ██║██║╚██╔╝██║██╔═══╝ ██║██║ ██╔══██║ ██║ ██║██║ ██║██║╚██╗██║ // ╚██████╗╚██████╔╝██║ ╚═╝ ██║██║ ██║███████╗██║ ██║ ██║ ██║╚██████╔╝██║ ╚████║ // ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ // MIT License (c) 2020–present Cezar Augusto & the Extension.js authors, presence implies inheritance import * as fs from 'node:fs' import * as path from 'node:path' import type {Compilation, Compiler} from '@rspack/core' import {projectConfigCandidatePaths} from '../lib/config-loader' import * as messages from './compilation-lib/messages' const ANSI = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`, 'g') const SUBPATH_NOT_EXPORTED = /Package subpath '(\.\/[^'?]+)' is not defined by "exports" in (.+?package\.json)/ const LEADING_MARK = /^\s*×\s*/ type BuildError = Error & { module?: {identifier?: () => string} loc?: {start?: {line?: number; column?: number}} file?: string } // The bundler lists its errors in an order that changes between runs. // Read by importing file and line, two runs print the same text. function inSourceOrder(a: BuildError, b: BuildError): number { const fileOf = (error: BuildError) => String(error.module?.identifier?.() || error.file || '') return ( fileOf(a).localeCompare(fileOf(b)) || (a.loc?.start?.line ?? 0) - (b.loc?.start?.line ?? 0) || (a.loc?.start?.column ?? 0) - (b.loc?.start?.column ?? 0) ) } // The conditions an import statement in a browser bundle is resolved with. const IMPORT_CONDITIONS = new Set([ 'import', 'module', 'browser', 'worker', 'webpack', 'production', 'development', 'default' ]) // The file an exports target gives an import, the way Node walks it: the // first condition that applies wins, and a `require` branch never does. function importTarget(target: unknown): string | undefined { if (typeof target === 'string') return target if (Array.isArray(target)) { for (const item of target) { const found = importTarget(item) if (found) return found } return undefined } if (target && typeof target === 'object') { for (const [condition, value] of Object.entries(target)) { if (!IMPORT_CONDITIONS.has(condition)) continue const found = importTarget(value) if (found) return found } } return undefined } // The names an import reaches the hidden file under, read from the exports // map. A pattern key is skipped, its name cannot be spelled from the file. export function exportedNamesOf( packageJson: {name?: unknown; exports?: unknown}, subpath: string ): string[] { const name = String(packageJson.name || '') const map = packageJson.exports if (!name || !map || typeof map !== 'object' || Array.isArray(map)) return [] const wanted = path.posix.normalize(subpath) return Object.entries(map) .filter(([key]) => key.startsWith('.') && !key.includes('*')) .filter(([, target]) => { const file = importTarget(target) return file !== undefined && path.posix.normalize(file) === wanted }) .map(([key]) => path.posix.join(name, key)) } interface ConfigFileShape { name: string dir: string esm: boolean // Whether the file is on disk, and whether it already has a config hook. exists: boolean hasHook: boolean } const CONFIG_HOOK = /(?:^|[\s,{])config\s*(?:\(|:)/m // The config file the alias goes in, and whether it is read as a module. // With none on disk the answer is the file the project would create. export function configFileShape(projectPath: string): ConfigFileShape { const candidates = projectPath ? projectConfigCandidatePaths(projectPath) : [] const found = candidates.find((candidate) => fs.existsSync(candidate)) const file = found || path.join(projectPath, 'extension.config.js') const dir = path.dirname(file) const name = path.basename(file) const text = found ? readText(found) : '' const shape = { name, dir, exists: Boolean(found), hasHook: CONFIG_HOOK.test(text) } if (name.endsWith('.mjs')) return {...shape, esm: true} if (name.endsWith('.cjs')) return {...shape, esm: false} const ownType = readPackageJson(path.join(dir, 'package.json')).type const type = ownType ?? readPackageJson(path.join(projectPath, 'package.json')).type return {...shape, esm: type === 'module'} } function readText(file: string): string { try { return fs.readFileSync(file, 'utf8') } catch { return '' } } function readPackageJson(file: string): { name?: unknown exports?: unknown type?: unknown } { try { return JSON.parse(fs.readFileSync(file, 'utf8')) } catch { return {} } } // The resolver's refusal stops at the exports field. The answer is the name // the package exports the file under, or an alias in the config file. export class HiddenPackageSubpathPlugin { public static readonly name: string = 'plugin-compilation:hidden-package-subpath' public apply(compiler: Compiler): void { // The refusal names the file and drops the query the import carried. const queries = new Map() if (typeof compiler.hooks?.normalModuleFactory?.tap === 'function') { compiler.hooks.normalModuleFactory.tap( HiddenPackageSubpathPlugin.name, (factory) => { factory.hooks.beforeResolve.tap( HiddenPackageSubpathPlugin.name, (data: {request?: unknown}) => { const request = String(data?.request || '') const queryAt = request.indexOf('?') if (queryAt > 0 && !request.includes('!')) { queries.set(request.slice(0, queryAt), request.slice(queryAt)) } } ) } ) } compiler.hooks.afterCompile.tap( HiddenPackageSubpathPlugin.name, (compilation: Compilation) => { const ErrorCtor = compiler.rspack?.WebpackError || Error const errors = compilation.errors as unknown as BuildError[] const config = configFileShape(String(compiler.options.context || '')) const found = errors.flatMap((error, index) => { const upstream = String(error?.message || '') const match = SUBPATH_NOT_EXPORTED.exec(upstream.replace(ANSI, '')) if (!match) return [] const [, subpath, packageJsonPath] = match const packageJson = readPackageJson(packageJsonPath) const name = String(packageJson.name || '') || path.basename(path.dirname(packageJsonPath)) const request = path.posix.join(name, subpath) const query = queries.get(request) || '' return [ { index, error, // The printer adds its own mark, a second one would stand beside it. upstream: upstream.replace(LEADING_MARK, ''), request, exportedAs: exportedNamesOf(packageJson, subpath).map( (exported) => `${exported}${query}` ), fileFromConfig: path .relative( config.dir, path.join(path.dirname(packageJsonPath), subpath) ) .split(path.sep) .join('/') } ] }) // Each refusal takes a place a refusal already had, in source order. const places = found.map((refusal) => refusal.index) const refusals = [...found] .sort((a, b) => inSourceOrder(a.error, b.error)) .map((refusal, at) => ({...refusal, index: places[at]})) // One build can refuse several files, and two whole configs cannot // both be pasted, so the first refusal carries every alias. const aliased = refusals.filter( (refusal) => refusal.exportedAs.length === 0 ) const aliases = [ ...new Map( aliased.map((refusal) => [refusal.request, refusal.fileFromConfig]) ) ].map(([request, fileFromConfig]) => ({request, fileFromConfig})) for (const refusal of refusals) { const {error} = refusal const next = new ErrorCtor( refusal.exportedAs.length > 0 ? messages.packageSubpathIsExportedAs( refusal.upstream, refusal.exportedAs ) : refusal === aliased[0] ? messages.packageSubpathNeedsAlias( refusal.upstream, config, aliases ) : messages.packageSubpathAliasIsAbove( refusal.upstream, config.name, aliased[0].request ) ) as BuildError next.name = error.name if (error.module) next.module = error.module if (error.loc) next.loc = error.loc if (error.file) next.file = error.file errors.splice(refusal.index, 1, next) } queries.clear() } ) } }