// ██████╗ ██████╗ ███╗ ███╗██████╗ ██╗██╗ █████╗ ████████╗██╗ ██████╗ ███╗ ██╗ // ██╔════╝██╔═══██╗████╗ ████║██╔══██╗██║██║ ██╔══██╗╚══██╔══╝██║██╔═══██╗████╗ ██║ // ██║ ██║ ██║██╔████╔██║██████╔╝██║██║ ███████║ ██║ ██║██║ ██║██╔██╗ ██║ // ██║ ██║ ██║██║╚██╔╝██║██╔═══╝ ██║██║ ██╔══██║ ██║ ██║██║ ██║██║╚██╗██║ // ╚██████╗╚██████╔╝██║ ╚═╝ ██║██║ ██║███████╗██║ ██║ ██║ ██║╚██████╔╝██║ ╚████║ // ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ // MIT License (c) 2020–present Cezar Augusto & the Extension.js authors, presence implies inheritance import type {Compiler} from '@rspack/core' interface ResolveRequest { context?: unknown request?: unknown dependencyType?: unknown } type ResolveSync = (context: string, request: string) => string | false // A package name alone, scoped or not, followed by a query. const PACKAGE_ROOT_WITH_QUERY = /^((?:@[^/?#!:\\]+\/)?[^/?#!:\\.@][^/?#!:\\]*)(\?[^#!]*)$/ // Returns the file the package root stands for with the query kept, or nothing // when the request is not a bare package root carrying a query. export function placePackageRootQuery( request: string, context: string, resolve: ResolveSync ): string | undefined { const match = PACKAGE_ROOT_WITH_QUERY.exec(request) if (!match) return undefined try { const file = resolve(context, match[1]) return file ? `${file}${match[2]}` : undefined } catch { return undefined } } // The resolver reads `pkg?url` against an exports map as the subpath // `./?url` and refuses it, where `pkg/sub?url` resolves. export class PackageRootQueryPlugin { public static readonly name: string = 'plugin-compilation:package-root-query' public apply(compiler: Compiler): void { // A stand-in compiler without a module factory resolves nothing. if (typeof compiler.hooks?.normalModuleFactory?.tap !== 'function') return compiler.hooks.normalModuleFactory.tap( PackageRootQueryPlugin.name, (nmf) => { nmf.hooks.beforeResolve.tap( PackageRootQueryPlugin.name, (data: ResolveRequest) => { const dependencyType = String(data?.dependencyType || 'esm') const placed = placePackageRootQuery( String(data?.request || ''), String(data?.context || ''), (context, request) => nmf .getResolver('normal', {dependencyType}) .resolveSync({}, context, request) ) if (placed) data.request = placed } ) } ) } }