|
1 | | -import { isAbsolute, join, resolve } from 'path'; |
| 1 | +import { isAbsolute, join, resolve, sep } from 'path'; |
2 | 2 | import { existsSync, lstatSync } from 'fs'; |
3 | 3 | import type { CompilerOptions } from 'typescript'; |
4 | 4 | import type { Package } from '@manypkg/get-packages'; |
@@ -63,6 +63,36 @@ function getTsConfigMapping(packages: Package[]) { |
63 | 63 | return result; |
64 | 64 | } |
65 | 65 |
|
| 66 | +function getMatchedIndex(sourcePath: string, targetPath: string) { |
| 67 | + const sourcePathArray = sourcePath.split(sep); |
| 68 | + const targetPathArray = targetPath.split(sep); |
| 69 | + let matchedIndex = -1; |
| 70 | + |
| 71 | + for (let i = 0; i < Math.min(sourcePathArray.length, targetPathArray.length); i++) { |
| 72 | + if (sourcePathArray[i] === targetPathArray[i]) { |
| 73 | + matchedIndex = Math.max(i, matchedIndex); |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + return matchedIndex; |
| 78 | +} |
| 79 | + |
| 80 | +function getExactMatchedPackage(packages: Package[], importer: string): Package | null { |
| 81 | + let matchedIndex = -1; |
| 82 | + let result = null; |
| 83 | + |
| 84 | + packages.forEach((pkg) => { |
| 85 | + const matchedIndexForPackage = getMatchedIndex(importer, pkg.dir); |
| 86 | + |
| 87 | + if (matchedIndexForPackage > matchedIndex && importer.includes(pkg.dir)) { |
| 88 | + matchedIndex = matchedIndexForPackage; |
| 89 | + result = pkg; |
| 90 | + } |
| 91 | + }); |
| 92 | + |
| 93 | + return result; |
| 94 | +} |
| 95 | + |
66 | 96 | const defaultOptions = { |
67 | 97 | alias: {}, |
68 | 98 | ignorePackages: undefined, |
@@ -130,7 +160,7 @@ export default async function tsMonoAlias(options: TsMonoAliasOption = defaultOp |
130 | 160 | } |
131 | 161 |
|
132 | 162 | const resolvedImporter = resolve(importer); |
133 | | - const importedFromPackage = packages.find((pkg) => resolvedImporter.includes(pkg.dir)); |
| 163 | + const importedFromPackage = getExactMatchedPackage(packages, resolvedImporter); |
134 | 164 |
|
135 | 165 | if (!importedFromPackage) { |
136 | 166 | return null; |
|
0 commit comments