|
| 1 | +import { type Input, toDeferResolve, toDependency } from '../../util/input.ts'; |
| 2 | +import type { Manifest } from '../../util/package-json.ts'; |
| 3 | +import { isInternal } from '../../util/path.ts'; |
| 4 | + |
| 5 | +const getCandidates = (prefix: string, identifier: string): string[] => { |
| 6 | + if (isInternal(identifier)) return [identifier]; |
| 7 | + |
| 8 | + if (identifier.startsWith('@')) { |
| 9 | + const [scope, name, ...rest] = identifier.split('/'); |
| 10 | + if (rest.length > 0) return [identifier]; |
| 11 | + if (scope) { |
| 12 | + if (!name) return [[scope, prefix].join('/')]; |
| 13 | + if (name.startsWith(prefix)) return [identifier]; |
| 14 | + return [[scope, prefix + name].join('/'), identifier]; |
| 15 | + } |
| 16 | + } |
| 17 | + |
| 18 | + const [name, ...rest] = identifier.split('/'); |
| 19 | + if (rest.length > 0) return [identifier]; |
| 20 | + if (name.startsWith(prefix)) return [identifier]; |
| 21 | + return [prefix + name, name]; |
| 22 | +}; |
| 23 | + |
| 24 | +const getDeclaredDependencies = (manifest: Manifest) => |
| 25 | + new Set([ |
| 26 | + ...Object.keys(manifest.dependencies ?? {}), |
| 27 | + ...Object.keys(manifest.devDependencies ?? {}), |
| 28 | + ...Object.keys(manifest.optionalDependencies ?? {}), |
| 29 | + ...Object.keys(manifest.peerDependencies ?? {}), |
| 30 | + ]); |
| 31 | + |
| 32 | +const pickCandidate = (prefix: string, identifier: string, manifest: Manifest) => { |
| 33 | + const candidates = getCandidates(prefix, identifier); |
| 34 | + if (candidates.length === 1 || isInternal(candidates[0])) return candidates[0]; |
| 35 | + |
| 36 | + const dependencies = getDeclaredDependencies(manifest); |
| 37 | + return candidates.find(candidate => dependencies.has(candidate)) ?? candidates[0]; |
| 38 | +}; |
| 39 | + |
| 40 | +// Resolve plugins for https://github.com/wooorm/load-plugin |
| 41 | +export const resolveLoadPluginStylePluginName = (prefix: string, identifier: string, manifest: Manifest): Input => { |
| 42 | + // https://github.com/wooorm/load-plugin/blob/4a1b7231e20f64be52625ff3469bbf111dda5949/lib/index.js#L104 |
| 43 | + prefix = prefix + (prefix.at(-1) === '-' ? '' : '-'); |
| 44 | + |
| 45 | + const candidate = pickCandidate(prefix, identifier, manifest); |
| 46 | + |
| 47 | + return isInternal(candidate) ? toDeferResolve(candidate) : toDependency(candidate); |
| 48 | +}; |
0 commit comments