deps-conflict-resolver 1.1.0 → 1.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.en.md +321 -0
- package/README.md +62 -32
- package/dist/{config.types-FhZrFXHQ.d.cts → config.types-DPfKh8_B.d.cts} +6 -0
- package/dist/{config.types-FhZrFXHQ.d.ts → config.types-DPfKh8_B.d.ts} +6 -0
- package/dist/index.cjs +1333 -231
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1335 -233
- package/dist/index.js.map +1 -1
- package/dist/{resolver-BG2AVCds.d.cts → resolver-BBrA-8me.d.ts} +31 -1
- package/dist/{resolver-z_muBpc_.d.ts → resolver-Bres_MgX.d.cts} +31 -1
- package/dist/vite.cjs +1350 -251
- package/dist/vite.cjs.map +1 -1
- package/dist/vite.d.cts +1 -1
- package/dist/vite.d.ts +1 -1
- package/dist/vite.js +1352 -253
- package/dist/vite.js.map +1 -1
- package/dist/webpack.cjs +1440 -267
- package/dist/webpack.cjs.map +1 -1
- package/dist/webpack.d.cts +11 -2
- package/dist/webpack.d.ts +11 -2
- package/dist/webpack.js +1442 -269
- package/dist/webpack.js.map +1 -1
- package/package.json +73 -48
package/dist/index.cjs
CHANGED
|
@@ -238,7 +238,31 @@ function findPackagePath(packageName, baseDir) {
|
|
|
238
238
|
localRequire = module$1.createRequire(baseUrl);
|
|
239
239
|
requireCache.set(baseDir, localRequire);
|
|
240
240
|
}
|
|
241
|
-
const
|
|
241
|
+
const metadataRequest = `${packageName}/package.json`;
|
|
242
|
+
const lookupPaths = localRequire.resolve.paths?.(metadataRequest);
|
|
243
|
+
if (lookupPaths) {
|
|
244
|
+
let visible = findSelfPackagePath(packageName, baseDir);
|
|
245
|
+
if (!visible) {
|
|
246
|
+
for (const directory of lookupPaths) {
|
|
247
|
+
const candidate = path.join(directory, packageName);
|
|
248
|
+
if (fileExists(candidate)) {
|
|
249
|
+
visible = candidate;
|
|
250
|
+
break;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
let resolved2 = visible;
|
|
255
|
+
if (visible) {
|
|
256
|
+
try {
|
|
257
|
+
resolved2 = fs.realpathSync(visible);
|
|
258
|
+
} catch {
|
|
259
|
+
resolved2 = path.resolve(visible);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
packagePathCache.set(cacheKey, resolved2);
|
|
263
|
+
return resolved2;
|
|
264
|
+
}
|
|
265
|
+
const pkgJsonPath = localRequire.resolve(metadataRequest);
|
|
242
266
|
const resolved = path.dirname(pkgJsonPath);
|
|
243
267
|
packagePathCache.set(cacheKey, resolved);
|
|
244
268
|
return resolved;
|
|
@@ -248,6 +272,15 @@ function findPackagePath(packageName, baseDir) {
|
|
|
248
272
|
return resolved;
|
|
249
273
|
}
|
|
250
274
|
}
|
|
275
|
+
function findSelfPackagePath(packageName, baseDir) {
|
|
276
|
+
for (const directory of iterateParentDirs(path.resolve(baseDir))) {
|
|
277
|
+
if (path.basename(directory) === "node_modules") break;
|
|
278
|
+
const manifest = readPackageJsonCached(directory);
|
|
279
|
+
if (!manifest) continue;
|
|
280
|
+
return manifest.name === packageName && "exports" in manifest && manifest.exports != null ? directory : null;
|
|
281
|
+
}
|
|
282
|
+
return null;
|
|
283
|
+
}
|
|
251
284
|
function findPackagePathFallback(packageName, baseDir) {
|
|
252
285
|
for (const dir of iterateParentDirs(baseDir)) {
|
|
253
286
|
const candidatePath = path.join(dir, "node_modules", packageName);
|
|
@@ -499,7 +532,7 @@ function extractAliasesFromDeps(deps, targetPackage, definedIn, existingAliases)
|
|
|
499
532
|
if (typeof versionSpec !== "string") continue;
|
|
500
533
|
if (existingAliases.has(aliasName)) continue;
|
|
501
534
|
const parsed = parseNpmAlias(versionSpec);
|
|
502
|
-
if (parsed
|
|
535
|
+
if (parsed?.[0] === targetPackage) {
|
|
503
536
|
aliases.push({
|
|
504
537
|
aliasName,
|
|
505
538
|
targetPackage,
|
|
@@ -775,14 +808,6 @@ function findBestVersion(versions, ranges) {
|
|
|
775
808
|
}
|
|
776
809
|
return best;
|
|
777
810
|
}
|
|
778
|
-
function rangesIntersect(range1, range2) {
|
|
779
|
-
try {
|
|
780
|
-
const intersection = semver__default.default.intersects(range1, range2);
|
|
781
|
-
return intersection;
|
|
782
|
-
} catch {
|
|
783
|
-
return false;
|
|
784
|
-
}
|
|
785
|
-
}
|
|
786
811
|
function createAliasInstallSpec(alias, packageName, version) {
|
|
787
812
|
return `${alias}@npm:${packageName}@${version}`;
|
|
788
813
|
}
|
|
@@ -798,13 +823,13 @@ function generateAliasName(packageName, version) {
|
|
|
798
823
|
return `${cleanName}${major}`;
|
|
799
824
|
}
|
|
800
825
|
|
|
801
|
-
// src/core/
|
|
826
|
+
// src/core/registry-client.ts
|
|
802
827
|
var logger3 = createLogger("npm-registry");
|
|
803
828
|
var packageCache = /* @__PURE__ */ new Map();
|
|
804
829
|
function clearNpmRegistryCache() {
|
|
805
830
|
packageCache.clear();
|
|
806
831
|
}
|
|
807
|
-
async function fetchWithTimeout(url, options = {}, timeout = DEFAULT_NPM_REGISTRY_TIMEOUT_MS) {
|
|
832
|
+
async function fetchWithTimeout(url, options = {}, consumeResponse, timeout = DEFAULT_NPM_REGISTRY_TIMEOUT_MS) {
|
|
808
833
|
const controller = new AbortController();
|
|
809
834
|
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
|
810
835
|
try {
|
|
@@ -812,7 +837,7 @@ async function fetchWithTimeout(url, options = {}, timeout = DEFAULT_NPM_REGISTR
|
|
|
812
837
|
...options,
|
|
813
838
|
signal: controller.signal
|
|
814
839
|
});
|
|
815
|
-
return response;
|
|
840
|
+
return await consumeResponse(response);
|
|
816
841
|
} finally {
|
|
817
842
|
clearTimeout(timeoutId);
|
|
818
843
|
}
|
|
@@ -827,11 +852,23 @@ async function fetchPackageInfo(packageName, registry = DEFAULT_NPM_REGISTRY) {
|
|
|
827
852
|
const encodedName = packageName.startsWith("@") ? `@${encodeURIComponent(packageName.slice(1))}` : packageName;
|
|
828
853
|
const url = `${registry}/${encodedName}`;
|
|
829
854
|
logger3.debug(`Fetching package info from: ${url}`);
|
|
830
|
-
const response = await fetchWithTimeout(
|
|
831
|
-
|
|
832
|
-
|
|
855
|
+
const { response, data } = await fetchWithTimeout(
|
|
856
|
+
url,
|
|
857
|
+
{
|
|
858
|
+
headers: {
|
|
859
|
+
Accept: "application/vnd.npm.install-v1+json"
|
|
860
|
+
}
|
|
861
|
+
},
|
|
862
|
+
async (fetchedResponse) => {
|
|
863
|
+
if (!fetchedResponse.ok) {
|
|
864
|
+
return { response: fetchedResponse, data: null };
|
|
865
|
+
}
|
|
866
|
+
return {
|
|
867
|
+
response: fetchedResponse,
|
|
868
|
+
data: await fetchedResponse.json()
|
|
869
|
+
};
|
|
833
870
|
}
|
|
834
|
-
|
|
871
|
+
);
|
|
835
872
|
if (!response.ok) {
|
|
836
873
|
if (response.status === 404) {
|
|
837
874
|
logger3.warn(`Package not found: ${packageName}`);
|
|
@@ -839,7 +876,6 @@ async function fetchPackageInfo(packageName, registry = DEFAULT_NPM_REGISTRY) {
|
|
|
839
876
|
}
|
|
840
877
|
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
841
878
|
}
|
|
842
|
-
const data = await response.json();
|
|
843
879
|
const packageInfo = {
|
|
844
880
|
name: data.name,
|
|
845
881
|
versions: Object.keys(data.versions),
|
|
@@ -857,7 +893,8 @@ async function fetchPackageInfo(packageName, registry = DEFAULT_NPM_REGISTRY) {
|
|
|
857
893
|
} catch (error) {
|
|
858
894
|
if (error instanceof Error && error.name === "AbortError") {
|
|
859
895
|
logger3.error(
|
|
860
|
-
`Timeout fetching package info for ${packageName} (>${DEFAULT_NPM_REGISTRY_TIMEOUT_MS}ms)
|
|
896
|
+
`Timeout fetching package info for ${packageName} (>${DEFAULT_NPM_REGISTRY_TIMEOUT_MS}ms)`,
|
|
897
|
+
error
|
|
861
898
|
);
|
|
862
899
|
} else {
|
|
863
900
|
logger3.error(`Failed to fetch package info for ${packageName}:`, error);
|
|
@@ -865,9 +902,72 @@ async function fetchPackageInfo(packageName, registry = DEFAULT_NPM_REGISTRY) {
|
|
|
865
902
|
return null;
|
|
866
903
|
}
|
|
867
904
|
}
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
905
|
+
var npmRegistryClient = {
|
|
906
|
+
async fetchAllVersions(packageName, registry) {
|
|
907
|
+
const info = await fetchPackageInfo(packageName, registry);
|
|
908
|
+
return info?.versions ?? [];
|
|
909
|
+
}
|
|
910
|
+
};
|
|
911
|
+
function normalizePackagePath(packagePath) {
|
|
912
|
+
try {
|
|
913
|
+
return fs.realpathSync(packagePath);
|
|
914
|
+
} catch {
|
|
915
|
+
return path.resolve(packagePath);
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
function buildInstalledDependencyGraph(packageNames, projectRoot) {
|
|
919
|
+
const nodes = /* @__PURE__ */ new Map();
|
|
920
|
+
const roots = [];
|
|
921
|
+
const stack = [];
|
|
922
|
+
for (let index = packageNames.length - 1; index >= 0; index--) {
|
|
923
|
+
const name = packageNames[index];
|
|
924
|
+
if (name) stack.push({ name, baseDir: projectRoot, parentId: null, root: true });
|
|
925
|
+
}
|
|
926
|
+
while (stack.length > 0) {
|
|
927
|
+
const item = stack.pop();
|
|
928
|
+
if (!item) continue;
|
|
929
|
+
const packagePath = findPackagePath(item.name, item.baseDir);
|
|
930
|
+
if (!packagePath) continue;
|
|
931
|
+
const normalizedPath = normalizePackagePath(packagePath);
|
|
932
|
+
const existingNode = nodes.get(normalizedPath);
|
|
933
|
+
if (existingNode) {
|
|
934
|
+
if (item.root) {
|
|
935
|
+
existingNode.parentId = null;
|
|
936
|
+
}
|
|
937
|
+
if (item.root && !roots.includes(normalizedPath)) {
|
|
938
|
+
roots.push(normalizedPath);
|
|
939
|
+
}
|
|
940
|
+
continue;
|
|
941
|
+
}
|
|
942
|
+
const packageJson = readPackageJsonCached(normalizedPath);
|
|
943
|
+
if (!packageJson) continue;
|
|
944
|
+
const dependencyNames = Object.keys(packageJson.dependencies ?? {});
|
|
945
|
+
const peerDependencyNames = Object.keys(packageJson.peerDependencies ?? {});
|
|
946
|
+
const node = {
|
|
947
|
+
id: normalizedPath,
|
|
948
|
+
name: item.name,
|
|
949
|
+
version: packageJson.version ?? "unknown",
|
|
950
|
+
packagePath: normalizedPath,
|
|
951
|
+
parentId: item.parentId,
|
|
952
|
+
dependencyNames,
|
|
953
|
+
peerDependencyNames
|
|
954
|
+
};
|
|
955
|
+
nodes.set(normalizedPath, node);
|
|
956
|
+
if (item.root) roots.push(normalizedPath);
|
|
957
|
+
const childNames = [...dependencyNames, ...peerDependencyNames];
|
|
958
|
+
for (let index = childNames.length - 1; index >= 0; index--) {
|
|
959
|
+
const childName = childNames[index];
|
|
960
|
+
if (childName) {
|
|
961
|
+
stack.push({
|
|
962
|
+
name: childName,
|
|
963
|
+
baseDir: normalizedPath,
|
|
964
|
+
parentId: normalizedPath,
|
|
965
|
+
root: false
|
|
966
|
+
});
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
}
|
|
970
|
+
return { nodes, roots };
|
|
871
971
|
}
|
|
872
972
|
|
|
873
973
|
// src/core/dependency-analyzer.ts
|
|
@@ -900,8 +1000,13 @@ var DependencyAnalyzer = class {
|
|
|
900
1000
|
workspaceRootDeclaredLoaded = false;
|
|
901
1001
|
/** collectAllRelatedPackages 的 memo 缓存(单次 analyze 生命周期内有效) */
|
|
902
1002
|
collectCache = /* @__PURE__ */ new Map();
|
|
903
|
-
|
|
1003
|
+
/** 当前 analyze 使用的按安装路径区分的依赖图 */
|
|
1004
|
+
dependencyGraph = null;
|
|
1005
|
+
/** 注册表访问适配器(可注入以支持离线分析和确定性测试) */
|
|
1006
|
+
registryClient;
|
|
1007
|
+
constructor(options, mainPackageJson, installedDeps, registryClient = npmRegistryClient) {
|
|
904
1008
|
this.options = options;
|
|
1009
|
+
this.registryClient = registryClient;
|
|
905
1010
|
this.rawDeclaredDeps = {
|
|
906
1011
|
...mainPackageJson.dependencies,
|
|
907
1012
|
...mainPackageJson.devDependencies
|
|
@@ -1046,6 +1151,10 @@ var DependencyAnalyzer = class {
|
|
|
1046
1151
|
try {
|
|
1047
1152
|
this.resolveCatalogDependencies();
|
|
1048
1153
|
this.ensureWorkspaceRootDeclaredDepsLoaded();
|
|
1154
|
+
this.dependencyGraph = buildInstalledDependencyGraph(
|
|
1155
|
+
this.options.dependencies,
|
|
1156
|
+
this.options.projectRoot
|
|
1157
|
+
);
|
|
1049
1158
|
for (const depName of this.options.dependencies) {
|
|
1050
1159
|
this.analyzeDependencyRecursive(depName, []);
|
|
1051
1160
|
}
|
|
@@ -1074,12 +1183,18 @@ var DependencyAnalyzer = class {
|
|
|
1074
1183
|
this.rawDeclaredDeps = {};
|
|
1075
1184
|
this.declaredDeps = {};
|
|
1076
1185
|
this.collectCache.clear();
|
|
1186
|
+
this.dependencyGraph = null;
|
|
1077
1187
|
}
|
|
1078
1188
|
}
|
|
1079
1189
|
/**
|
|
1080
1190
|
* 递归分析单个依赖及其所有子依赖
|
|
1081
1191
|
*/
|
|
1082
1192
|
analyzeDependencyRecursive(packageName, dependencyPath) {
|
|
1193
|
+
const graphRoot = this.findGraphRoot(packageName);
|
|
1194
|
+
if (graphRoot) {
|
|
1195
|
+
this.populateAnalyzedDependenciesFromGraph();
|
|
1196
|
+
return this.analyzedDependencies.get(graphRoot.name) ?? null;
|
|
1197
|
+
}
|
|
1083
1198
|
if (this.visitedPackages.has(packageName)) {
|
|
1084
1199
|
logger4.debug(`Skipping already visited package: ${packageName}`);
|
|
1085
1200
|
return this.analyzedDependencies.get(packageName) ?? null;
|
|
@@ -1134,6 +1249,69 @@ var DependencyAnalyzer = class {
|
|
|
1134
1249
|
}
|
|
1135
1250
|
return rootInfo;
|
|
1136
1251
|
}
|
|
1252
|
+
findGraphRoot(packageName) {
|
|
1253
|
+
if (!this.dependencyGraph) return null;
|
|
1254
|
+
for (const rootId of this.dependencyGraph.roots) {
|
|
1255
|
+
const root = this.dependencyGraph.nodes.get(rootId);
|
|
1256
|
+
if (root?.name === packageName) return root;
|
|
1257
|
+
}
|
|
1258
|
+
return null;
|
|
1259
|
+
}
|
|
1260
|
+
getDependencyPathForGraphNode(node) {
|
|
1261
|
+
if (!this.dependencyGraph) return [];
|
|
1262
|
+
const names = [];
|
|
1263
|
+
let current = node;
|
|
1264
|
+
const visited = /* @__PURE__ */ new Set();
|
|
1265
|
+
while (current && !visited.has(current.id)) {
|
|
1266
|
+
visited.add(current.id);
|
|
1267
|
+
names.unshift(current.name);
|
|
1268
|
+
current = current.parentId ? this.dependencyGraph.nodes.get(current.parentId) : void 0;
|
|
1269
|
+
}
|
|
1270
|
+
return names.slice(0, -1);
|
|
1271
|
+
}
|
|
1272
|
+
populateAnalyzedDependenciesFromGraph() {
|
|
1273
|
+
if (!this.dependencyGraph) return;
|
|
1274
|
+
const rootVisibleNodeIds = /* @__PURE__ */ new Map();
|
|
1275
|
+
for (const node of this.dependencyGraph.nodes.values()) {
|
|
1276
|
+
const rootVisiblePath = findPackagePath(node.name, this.options.projectRoot);
|
|
1277
|
+
if (!rootVisiblePath) continue;
|
|
1278
|
+
const rootVisibleNode = this.dependencyGraph.nodes.get(
|
|
1279
|
+
this.normalizeInstalledPath(rootVisiblePath)
|
|
1280
|
+
);
|
|
1281
|
+
if (rootVisibleNode && !rootVisibleNodeIds.has(node.name)) {
|
|
1282
|
+
rootVisibleNodeIds.set(node.name, rootVisibleNode.id);
|
|
1283
|
+
}
|
|
1284
|
+
}
|
|
1285
|
+
const orderedNodes = [];
|
|
1286
|
+
const selectedNodeIds = /* @__PURE__ */ new Set();
|
|
1287
|
+
for (const nodeId of rootVisibleNodeIds.values()) {
|
|
1288
|
+
const node = this.dependencyGraph.nodes.get(nodeId);
|
|
1289
|
+
if (node && !selectedNodeIds.has(node.id)) {
|
|
1290
|
+
selectedNodeIds.add(node.id);
|
|
1291
|
+
orderedNodes.push(node);
|
|
1292
|
+
}
|
|
1293
|
+
}
|
|
1294
|
+
for (const node of this.dependencyGraph.nodes.values()) {
|
|
1295
|
+
if (!selectedNodeIds.has(node.id)) {
|
|
1296
|
+
orderedNodes.push(node);
|
|
1297
|
+
}
|
|
1298
|
+
}
|
|
1299
|
+
for (const node of orderedNodes) {
|
|
1300
|
+
if (this.analyzedDependencies.has(node.name)) continue;
|
|
1301
|
+
const packageJson = readPackageJsonCached(node.packagePath);
|
|
1302
|
+
if (!packageJson) continue;
|
|
1303
|
+
this.cacheInstalledPackageInfo(node.name, node.packagePath, packageJson);
|
|
1304
|
+
this.analyzedDependencies.set(node.name, {
|
|
1305
|
+
name: node.name,
|
|
1306
|
+
version: node.version,
|
|
1307
|
+
dependencyPath: this.getDependencyPathForGraphNode(node),
|
|
1308
|
+
dependencies: packageJson.dependencies ?? {},
|
|
1309
|
+
peerDependencies: packageJson.peerDependencies ?? {},
|
|
1310
|
+
peerDependenciesMeta: packageJson.peerDependenciesMeta
|
|
1311
|
+
});
|
|
1312
|
+
this.visitedPackages.add(node.name);
|
|
1313
|
+
}
|
|
1314
|
+
}
|
|
1137
1315
|
/**
|
|
1138
1316
|
* 缓存已安装包的信息(用于后续查找别名等)
|
|
1139
1317
|
*/
|
|
@@ -1169,13 +1347,24 @@ var DependencyAnalyzer = class {
|
|
|
1169
1347
|
*/
|
|
1170
1348
|
collectFirstLevelPeerDependencies() {
|
|
1171
1349
|
const peerDepsMap = /* @__PURE__ */ new Map();
|
|
1350
|
+
const hasInstalledGraphRoots = (this.dependencyGraph?.roots.length ?? 0) > 0;
|
|
1172
1351
|
for (const depName of this.options.dependencies) {
|
|
1352
|
+
if (hasInstalledGraphRoots && !this.findGraphRoot(depName)) {
|
|
1353
|
+
logger4.debug(`Skipping non-root configured dependency: ${depName}`);
|
|
1354
|
+
continue;
|
|
1355
|
+
}
|
|
1173
1356
|
const depInfo = this.analyzedDependencies.get(depName);
|
|
1174
1357
|
if (!depInfo) continue;
|
|
1175
1358
|
const peerDeps = depInfo.peerDependencies;
|
|
1176
1359
|
const peerMeta = depInfo.peerDependenciesMeta ?? {};
|
|
1177
1360
|
for (const [peerName, peerRange] of Object.entries(peerDeps)) {
|
|
1178
1361
|
const isOptional = peerMeta[peerName]?.optional === true;
|
|
1362
|
+
if (isOptional) {
|
|
1363
|
+
logger4.debug(
|
|
1364
|
+
`Skipping optional first-level peer dependency: ${peerName}@${peerRange} required by ${depName}`
|
|
1365
|
+
);
|
|
1366
|
+
continue;
|
|
1367
|
+
}
|
|
1179
1368
|
const existing = peerDepsMap.get(peerName) ?? [];
|
|
1180
1369
|
existing.push({
|
|
1181
1370
|
path: [depName],
|
|
@@ -1233,10 +1422,6 @@ var DependencyAnalyzer = class {
|
|
|
1233
1422
|
* 返回 null 表示包未安装
|
|
1234
1423
|
*/
|
|
1235
1424
|
getMainProjectVersion(packageName) {
|
|
1236
|
-
const cached = this.installedPackageCache.get(packageName);
|
|
1237
|
-
if (cached) {
|
|
1238
|
-
return cached.version;
|
|
1239
|
-
}
|
|
1240
1425
|
const { packagePath, pkgJson } = this.resolvePackageJson(packageName, this.options.projectRoot);
|
|
1241
1426
|
if (packagePath && pkgJson?.version) {
|
|
1242
1427
|
this.installedPackageCache.set(packageName, {
|
|
@@ -1246,6 +1431,10 @@ var DependencyAnalyzer = class {
|
|
|
1246
1431
|
});
|
|
1247
1432
|
return pkgJson.version;
|
|
1248
1433
|
}
|
|
1434
|
+
const cached = this.installedPackageCache.get(packageName);
|
|
1435
|
+
if (cached) {
|
|
1436
|
+
return cached.version;
|
|
1437
|
+
}
|
|
1249
1438
|
return null;
|
|
1250
1439
|
}
|
|
1251
1440
|
/**
|
|
@@ -1266,15 +1455,52 @@ var DependencyAnalyzer = class {
|
|
|
1266
1455
|
const mappings = await this.createAliasMappingsForConflict(conflict, allConflictPackageNames);
|
|
1267
1456
|
aliasMappings.push(...mappings);
|
|
1268
1457
|
}
|
|
1458
|
+
this.linkAliasPeerImporterPaths(aliasMappings);
|
|
1269
1459
|
return aliasMappings;
|
|
1270
1460
|
}
|
|
1461
|
+
getAliasCandidatePaths(aliasName) {
|
|
1462
|
+
const paths = /* @__PURE__ */ new Set();
|
|
1463
|
+
const addRootPath = (root) => {
|
|
1464
|
+
paths.add(path.join(root, "node_modules", aliasName));
|
|
1465
|
+
paths.add(path.join(this.normalizeInstalledPath(root), "node_modules", aliasName));
|
|
1466
|
+
};
|
|
1467
|
+
addRootPath(this.options.projectRoot);
|
|
1468
|
+
const workspaceRoot = this.workspaceDetector.getWorkspaceRoot();
|
|
1469
|
+
if (workspaceRoot) addRootPath(workspaceRoot);
|
|
1470
|
+
const installedPath = findPackagePath(aliasName, this.options.projectRoot);
|
|
1471
|
+
if (installedPath) paths.add(this.normalizeInstalledPath(installedPath));
|
|
1472
|
+
return [...paths];
|
|
1473
|
+
}
|
|
1474
|
+
/**
|
|
1475
|
+
* If one generated alias represents a package with a peer dependency that
|
|
1476
|
+
* is also aliased, its installed package directory must be an importer for
|
|
1477
|
+
* the peer alias. Otherwise the alias's own import resolves back to the
|
|
1478
|
+
* host version and breaks the peer closure.
|
|
1479
|
+
*/
|
|
1480
|
+
linkAliasPeerImporterPaths(mappings) {
|
|
1481
|
+
if (!this.dependencyGraph || mappings.length < 2) return;
|
|
1482
|
+
for (const importerMapping of mappings) {
|
|
1483
|
+
const peerNames = new Set(
|
|
1484
|
+
[...this.dependencyGraph.nodes.values()].filter((node) => node.name === importerMapping.originalName).flatMap((node) => node.peerDependencyNames)
|
|
1485
|
+
);
|
|
1486
|
+
if (peerNames.size === 0) continue;
|
|
1487
|
+
const importerPaths = this.getAliasCandidatePaths(importerMapping.aliasName);
|
|
1488
|
+
for (const peerMapping of mappings) {
|
|
1489
|
+
if (peerMapping === importerMapping || !peerNames.has(peerMapping.originalName) || peerMapping.importerPaths === void 0) {
|
|
1490
|
+
continue;
|
|
1491
|
+
}
|
|
1492
|
+
peerMapping.importerPaths = [
|
|
1493
|
+
.../* @__PURE__ */ new Set([...peerMapping.importerPaths ?? [], ...importerPaths])
|
|
1494
|
+
];
|
|
1495
|
+
}
|
|
1496
|
+
}
|
|
1497
|
+
}
|
|
1271
1498
|
/**
|
|
1272
1499
|
* 为单个冲突创建别名映射
|
|
1273
1500
|
*/
|
|
1274
1501
|
async createAliasMappingsForConflict(conflict, allConflictPackageNames) {
|
|
1275
1502
|
const { packageName, conflictingRanges } = conflict;
|
|
1276
|
-
|
|
1277
|
-
logger4.info(`Creating alias for "${packageName}": ${rangeGroups.length} version groups`);
|
|
1503
|
+
logger4.info(`Creating alias for "${packageName}"`);
|
|
1278
1504
|
const workspaceRoot = this.workspaceDetector.getWorkspaceRoot();
|
|
1279
1505
|
if (workspaceRoot) {
|
|
1280
1506
|
logger4.info(` Workspace root detected: ${workspaceRoot}`);
|
|
@@ -1303,14 +1529,117 @@ var DependencyAnalyzer = class {
|
|
|
1303
1529
|
);
|
|
1304
1530
|
}
|
|
1305
1531
|
}
|
|
1306
|
-
const versions = await fetchAllVersions(packageName, this.options.registry);
|
|
1307
|
-
if (versions.length === 0) {
|
|
1308
|
-
logger4.warn(`No versions found for ${packageName}`);
|
|
1309
|
-
return [];
|
|
1310
|
-
}
|
|
1311
1532
|
const existingAliasNames = this.getExistingAliasNames(packageName);
|
|
1312
1533
|
const usedAliasNames = /* @__PURE__ */ new Set();
|
|
1313
1534
|
const mappings = [];
|
|
1535
|
+
const installedAliasMatches = this.findInstalledAliasMatches(packageName);
|
|
1536
|
+
const installedAliasesByName = /* @__PURE__ */ new Map();
|
|
1537
|
+
for (const installedAlias of installedAliasMatches) {
|
|
1538
|
+
const aliases = installedAliasesByName.get(installedAlias.name);
|
|
1539
|
+
if (aliases) {
|
|
1540
|
+
aliases.push(installedAlias);
|
|
1541
|
+
} else {
|
|
1542
|
+
installedAliasesByName.set(installedAlias.name, [installedAlias]);
|
|
1543
|
+
}
|
|
1544
|
+
}
|
|
1545
|
+
for (const [aliasName, aliases] of installedAliasesByName) {
|
|
1546
|
+
const identities = new Set(
|
|
1547
|
+
aliases.map((alias) => `${alias.installedPath ?? alias.scope}\0${alias.version}`)
|
|
1548
|
+
);
|
|
1549
|
+
if (identities.size < 2) continue;
|
|
1550
|
+
logger4.warn(
|
|
1551
|
+
`Alias reuse skipped: ${JSON.stringify({
|
|
1552
|
+
code: "AMBIGUOUS_ALIAS_SCOPE",
|
|
1553
|
+
packageName,
|
|
1554
|
+
aliasName,
|
|
1555
|
+
candidates: aliases.map((alias) => ({
|
|
1556
|
+
installedPath: alias.installedPath ?? null,
|
|
1557
|
+
scope: alias.scope,
|
|
1558
|
+
version: alias.version
|
|
1559
|
+
}))
|
|
1560
|
+
})}`
|
|
1561
|
+
);
|
|
1562
|
+
return [];
|
|
1563
|
+
}
|
|
1564
|
+
const reusedAliasGroups = /* @__PURE__ */ new Map();
|
|
1565
|
+
const unresolvedRequests = [];
|
|
1566
|
+
for (const request of conflictingRanges) {
|
|
1567
|
+
const existingAlias = this.findExistingAliasForRanges(
|
|
1568
|
+
packageName,
|
|
1569
|
+
[request.requiredRange],
|
|
1570
|
+
/* @__PURE__ */ new Set()
|
|
1571
|
+
);
|
|
1572
|
+
if (!existingAlias) {
|
|
1573
|
+
unresolvedRequests.push(request);
|
|
1574
|
+
continue;
|
|
1575
|
+
}
|
|
1576
|
+
usedAliasNames.add(existingAlias.name);
|
|
1577
|
+
const aliasIdentity = `${existingAlias.name}\0${existingAlias.installedPath ?? existingAlias.scope}\0${existingAlias.version}`;
|
|
1578
|
+
const reusedGroup = reusedAliasGroups.get(aliasIdentity);
|
|
1579
|
+
if (reusedGroup) {
|
|
1580
|
+
reusedGroup.requests.push(request);
|
|
1581
|
+
} else {
|
|
1582
|
+
reusedAliasGroups.set(aliasIdentity, {
|
|
1583
|
+
alias: existingAlias,
|
|
1584
|
+
requests: [request]
|
|
1585
|
+
});
|
|
1586
|
+
}
|
|
1587
|
+
}
|
|
1588
|
+
const reusedGroupsByAliasName = /* @__PURE__ */ new Map();
|
|
1589
|
+
for (const reusedGroup of reusedAliasGroups.values()) {
|
|
1590
|
+
const groups = reusedGroupsByAliasName.get(reusedGroup.alias.name);
|
|
1591
|
+
if (groups) {
|
|
1592
|
+
groups.push(reusedGroup);
|
|
1593
|
+
} else {
|
|
1594
|
+
reusedGroupsByAliasName.set(reusedGroup.alias.name, [reusedGroup]);
|
|
1595
|
+
}
|
|
1596
|
+
}
|
|
1597
|
+
for (const [aliasName, groups] of reusedGroupsByAliasName) {
|
|
1598
|
+
if (groups.length < 2) continue;
|
|
1599
|
+
logger4.warn(
|
|
1600
|
+
`Alias reuse skipped: ${JSON.stringify({
|
|
1601
|
+
code: "AMBIGUOUS_ALIAS_SCOPE",
|
|
1602
|
+
packageName,
|
|
1603
|
+
aliasName,
|
|
1604
|
+
candidates: groups.map(({ alias, requests }) => ({
|
|
1605
|
+
installedPath: alias.installedPath ?? null,
|
|
1606
|
+
scope: alias.scope,
|
|
1607
|
+
version: alias.version,
|
|
1608
|
+
requesters: requests.map((request) => request.path.join(">"))
|
|
1609
|
+
}))
|
|
1610
|
+
})}`
|
|
1611
|
+
);
|
|
1612
|
+
return [];
|
|
1613
|
+
}
|
|
1614
|
+
for (const reusedGroup of reusedAliasGroups.values()) {
|
|
1615
|
+
mappings.push(
|
|
1616
|
+
this.buildAliasMapping(
|
|
1617
|
+
packageName,
|
|
1618
|
+
reusedGroup.alias.name,
|
|
1619
|
+
reusedGroup.alias.version,
|
|
1620
|
+
"",
|
|
1621
|
+
// 不需要安装
|
|
1622
|
+
reusedGroup.requests,
|
|
1623
|
+
allConflictPackageNames
|
|
1624
|
+
)
|
|
1625
|
+
);
|
|
1626
|
+
}
|
|
1627
|
+
if (unresolvedRequests.length === 0) {
|
|
1628
|
+
return mappings;
|
|
1629
|
+
}
|
|
1630
|
+
let versions;
|
|
1631
|
+
try {
|
|
1632
|
+
versions = await this.registryClient.fetchAllVersions(packageName, this.options.registry);
|
|
1633
|
+
} catch (error) {
|
|
1634
|
+
logger4.warn(`Failed to fetch versions for ${packageName}: ${String(error)}`);
|
|
1635
|
+
return mappings;
|
|
1636
|
+
}
|
|
1637
|
+
if (versions.length === 0) {
|
|
1638
|
+
logger4.warn(`No versions found for ${packageName}`);
|
|
1639
|
+
return mappings;
|
|
1640
|
+
}
|
|
1641
|
+
const rangeGroups = this.groupRangesByCompatibility(unresolvedRequests, versions);
|
|
1642
|
+
logger4.info(`Creating alias for "${packageName}": ${rangeGroups.length} version groups`);
|
|
1314
1643
|
for (let i = 0; i < rangeGroups.length; i++) {
|
|
1315
1644
|
const group = rangeGroups[i];
|
|
1316
1645
|
if (!group || group.length === 0) continue;
|
|
@@ -1336,14 +1665,22 @@ var DependencyAnalyzer = class {
|
|
|
1336
1665
|
* 按范围兼容性分组
|
|
1337
1666
|
* 有交集的范围放在一组,互斥的分开
|
|
1338
1667
|
*/
|
|
1339
|
-
groupRangesByCompatibility(requests) {
|
|
1668
|
+
groupRangesByCompatibility(requests, availableVersions) {
|
|
1340
1669
|
const groups = [];
|
|
1341
|
-
|
|
1670
|
+
const orderedRequests = requests.map((request, index) => ({
|
|
1671
|
+
request,
|
|
1672
|
+
index,
|
|
1673
|
+
satisfyingVersionCount: availableVersions.filter(
|
|
1674
|
+
(version) => satisfies(version, request.requiredRange)
|
|
1675
|
+
).length
|
|
1676
|
+
})).sort(
|
|
1677
|
+
(left, right) => left.satisfyingVersionCount - right.satisfyingVersionCount || left.index - right.index
|
|
1678
|
+
);
|
|
1679
|
+
for (const { request } of orderedRequests) {
|
|
1342
1680
|
let added = false;
|
|
1343
1681
|
for (const group of groups) {
|
|
1344
|
-
const
|
|
1345
|
-
|
|
1346
|
-
);
|
|
1682
|
+
const proposedRanges = [...group, request].map((item) => item.requiredRange);
|
|
1683
|
+
const canJoin = findBestVersion(availableVersions, proposedRanges) !== null;
|
|
1347
1684
|
if (canJoin) {
|
|
1348
1685
|
group.push(request);
|
|
1349
1686
|
added = true;
|
|
@@ -1351,6 +1688,9 @@ var DependencyAnalyzer = class {
|
|
|
1351
1688
|
}
|
|
1352
1689
|
}
|
|
1353
1690
|
if (!added) {
|
|
1691
|
+
if (findBestVersion(availableVersions, [request.requiredRange]) === null) {
|
|
1692
|
+
continue;
|
|
1693
|
+
}
|
|
1354
1694
|
groups.push([request]);
|
|
1355
1695
|
}
|
|
1356
1696
|
}
|
|
@@ -1360,11 +1700,7 @@ var DependencyAnalyzer = class {
|
|
|
1360
1700
|
* 为一个兼容组创建别名映射
|
|
1361
1701
|
*/
|
|
1362
1702
|
createAliasMappingForGroup(packageName, group, groupRanges, versions, existingAliasNames, usedAliasNames, allConflictPackageNames) {
|
|
1363
|
-
const existingAlias = this.findExistingAliasForRanges(
|
|
1364
|
-
packageName,
|
|
1365
|
-
groupRanges,
|
|
1366
|
-
usedAliasNames
|
|
1367
|
-
);
|
|
1703
|
+
const existingAlias = this.findExistingAliasForRanges(packageName, groupRanges, usedAliasNames);
|
|
1368
1704
|
if (existingAlias) {
|
|
1369
1705
|
logger4.debug(
|
|
1370
1706
|
` Reusing: ${existingAlias.name}@${existingAlias.version}${existingAlias.isWorkspaceAlias ? " (workspace)" : ""}`
|
|
@@ -1386,7 +1722,11 @@ var DependencyAnalyzer = class {
|
|
|
1386
1722
|
);
|
|
1387
1723
|
return null;
|
|
1388
1724
|
}
|
|
1389
|
-
const combinedExisting = /* @__PURE__ */ new Set([
|
|
1725
|
+
const combinedExisting = /* @__PURE__ */ new Set([
|
|
1726
|
+
...existingAliasNames,
|
|
1727
|
+
...usedAliasNames,
|
|
1728
|
+
...this.getReservedDependencyNames()
|
|
1729
|
+
]);
|
|
1390
1730
|
const aliasName = this.generateUniqueAliasName(packageName, bestVersion, combinedExisting);
|
|
1391
1731
|
const installSpec = createAliasInstallSpec(aliasName, packageName, bestVersion);
|
|
1392
1732
|
logger4.info(` New alias: ${aliasName}@${bestVersion}`);
|
|
@@ -1407,16 +1747,73 @@ var DependencyAnalyzer = class {
|
|
|
1407
1747
|
const usedByRoots = [
|
|
1408
1748
|
...new Set(group.map((r) => r.path[0]).filter((p) => p !== void 0))
|
|
1409
1749
|
];
|
|
1410
|
-
const
|
|
1750
|
+
const graphInstances = this.collectGraphRelatedPackageInstances(
|
|
1751
|
+
usedByRoots,
|
|
1752
|
+
allConflictPackageNames
|
|
1753
|
+
);
|
|
1754
|
+
const allDependents = graphInstances ? [...new Set(graphInstances.map((instance) => instance.name))] : this.collectAllRelatedPackages(usedByRoots, allConflictPackageNames);
|
|
1411
1755
|
return {
|
|
1412
1756
|
originalName: packageName,
|
|
1413
1757
|
aliasName,
|
|
1414
1758
|
installSpec,
|
|
1415
1759
|
resolvedVersion: version,
|
|
1416
1760
|
usedBy,
|
|
1417
|
-
allDependents
|
|
1761
|
+
allDependents,
|
|
1762
|
+
...graphInstances && graphInstances.length > 0 ? { importerPaths: [...new Set(graphInstances.map((instance) => instance.path))] } : {}
|
|
1418
1763
|
};
|
|
1419
1764
|
}
|
|
1765
|
+
/**
|
|
1766
|
+
* 收集所有已安装的现有别名,不按请求版本范围过滤。
|
|
1767
|
+
* 用于在范围筛选前识别同名 alias 的多路径/多版本歧义。
|
|
1768
|
+
*/
|
|
1769
|
+
findInstalledAliasMatches(packageName) {
|
|
1770
|
+
const matches = [];
|
|
1771
|
+
const npmAliases = this.existingAliasesMap.get(packageName) ?? [];
|
|
1772
|
+
for (const alias of npmAliases) {
|
|
1773
|
+
alias.installedVersion ??= this.getAliasInstalledVersion(alias.aliasName);
|
|
1774
|
+
if (!alias.installedVersion) continue;
|
|
1775
|
+
const installedAlias = this.installedPackageCache.get(alias.aliasName);
|
|
1776
|
+
if (installedAlias?.realName !== packageName) continue;
|
|
1777
|
+
matches.push({
|
|
1778
|
+
name: alias.aliasName,
|
|
1779
|
+
version: alias.installedVersion,
|
|
1780
|
+
installedPath: installedAlias?.path,
|
|
1781
|
+
scope: "local"
|
|
1782
|
+
});
|
|
1783
|
+
}
|
|
1784
|
+
const workspaceAliases = this.findWorkspaceAliasesForPackage(packageName);
|
|
1785
|
+
const workspaceRoot = this.workspaceDetector.getWorkspaceRoot();
|
|
1786
|
+
for (const wsAlias of workspaceAliases) {
|
|
1787
|
+
let installedVersion = null;
|
|
1788
|
+
let installedPath;
|
|
1789
|
+
if (workspaceRoot) {
|
|
1790
|
+
const { packagePath, pkgJson } = this.resolvePackageJson(wsAlias.aliasName, workspaceRoot);
|
|
1791
|
+
if (packagePath) {
|
|
1792
|
+
if (pkgJson?.name !== packageName) continue;
|
|
1793
|
+
installedVersion = pkgJson?.version ?? null;
|
|
1794
|
+
installedPath = packagePath;
|
|
1795
|
+
}
|
|
1796
|
+
}
|
|
1797
|
+
if (!installedVersion) {
|
|
1798
|
+
installedVersion = this.getAliasInstalledVersion(wsAlias.aliasName);
|
|
1799
|
+
if (installedVersion) {
|
|
1800
|
+
const installedAlias = this.installedPackageCache.get(wsAlias.aliasName);
|
|
1801
|
+
installedPath = installedAlias?.path;
|
|
1802
|
+
if (installedAlias?.realName !== packageName) continue;
|
|
1803
|
+
}
|
|
1804
|
+
}
|
|
1805
|
+
if (installedVersion) {
|
|
1806
|
+
matches.push({
|
|
1807
|
+
name: wsAlias.aliasName,
|
|
1808
|
+
version: installedVersion,
|
|
1809
|
+
isWorkspaceAlias: true,
|
|
1810
|
+
installedPath,
|
|
1811
|
+
scope: "workspace"
|
|
1812
|
+
});
|
|
1813
|
+
}
|
|
1814
|
+
}
|
|
1815
|
+
return matches;
|
|
1816
|
+
}
|
|
1420
1817
|
/**
|
|
1421
1818
|
* 查找满足指定范围的现有别名(排除已使用的)
|
|
1422
1819
|
* 优先查找当前项目的别名,然后查找 workspace 级别的别名
|
|
@@ -1433,17 +1830,27 @@ var DependencyAnalyzer = class {
|
|
|
1433
1830
|
logger4.debug(` Skip ${alias.aliasName}: already used`);
|
|
1434
1831
|
continue;
|
|
1435
1832
|
}
|
|
1436
|
-
|
|
1437
|
-
alias.installedVersion = this.getAliasInstalledVersion(alias.aliasName);
|
|
1438
|
-
}
|
|
1833
|
+
alias.installedVersion ??= this.getAliasInstalledVersion(alias.aliasName);
|
|
1439
1834
|
if (!alias.installedVersion) {
|
|
1440
1835
|
logger4.debug(` Skip ${alias.aliasName}: not installed`);
|
|
1441
1836
|
continue;
|
|
1442
1837
|
}
|
|
1838
|
+
const installedAlias = this.installedPackageCache.get(alias.aliasName);
|
|
1839
|
+
if (installedAlias?.realName !== packageName) {
|
|
1840
|
+
logger4.debug(
|
|
1841
|
+
` Skip ${alias.aliasName}: installed package name ${installedAlias?.realName ?? "unknown"} does not match ${packageName}`
|
|
1842
|
+
);
|
|
1843
|
+
continue;
|
|
1844
|
+
}
|
|
1443
1845
|
const allSatisfied = ranges.every((range) => satisfies(alias.installedVersion, range));
|
|
1444
1846
|
if (allSatisfied) {
|
|
1445
1847
|
logger4.info(` Reusing local alias: ${alias.aliasName}@${alias.installedVersion}`);
|
|
1446
|
-
return {
|
|
1848
|
+
return {
|
|
1849
|
+
name: alias.aliasName,
|
|
1850
|
+
version: alias.installedVersion,
|
|
1851
|
+
installedPath: installedAlias?.path,
|
|
1852
|
+
scope: "local"
|
|
1853
|
+
};
|
|
1447
1854
|
} else {
|
|
1448
1855
|
logger4.debug(
|
|
1449
1856
|
` Skip ${alias.aliasName}@${alias.installedVersion}: version doesn't satisfy all ranges`
|
|
@@ -1462,10 +1869,18 @@ var DependencyAnalyzer = class {
|
|
|
1462
1869
|
continue;
|
|
1463
1870
|
}
|
|
1464
1871
|
let installedVersion = null;
|
|
1872
|
+
let installedPath;
|
|
1465
1873
|
if (workspaceRoot) {
|
|
1466
1874
|
const { packagePath, pkgJson } = this.resolvePackageJson(wsAlias.aliasName, workspaceRoot);
|
|
1467
1875
|
if (packagePath) {
|
|
1876
|
+
if (pkgJson?.name !== packageName) {
|
|
1877
|
+
logger4.debug(
|
|
1878
|
+
` Skip ${wsAlias.aliasName}: installed package name ${pkgJson?.name ?? "unknown"} does not match ${packageName}`
|
|
1879
|
+
);
|
|
1880
|
+
continue;
|
|
1881
|
+
}
|
|
1468
1882
|
installedVersion = pkgJson?.version ?? null;
|
|
1883
|
+
installedPath = packagePath;
|
|
1469
1884
|
logger4.debug(
|
|
1470
1885
|
` Found ${wsAlias.aliasName} installed at workspace root: ${installedVersion}`
|
|
1471
1886
|
);
|
|
@@ -1474,6 +1889,14 @@ var DependencyAnalyzer = class {
|
|
|
1474
1889
|
if (!installedVersion) {
|
|
1475
1890
|
installedVersion = this.getAliasInstalledVersion(wsAlias.aliasName);
|
|
1476
1891
|
if (installedVersion) {
|
|
1892
|
+
const installedAlias = this.installedPackageCache.get(wsAlias.aliasName);
|
|
1893
|
+
installedPath = installedAlias?.path;
|
|
1894
|
+
if (installedAlias?.realName !== packageName) {
|
|
1895
|
+
logger4.debug(
|
|
1896
|
+
` Skip ${wsAlias.aliasName}: installed package name ${installedAlias?.realName ?? "unknown"} does not match ${packageName}`
|
|
1897
|
+
);
|
|
1898
|
+
continue;
|
|
1899
|
+
}
|
|
1477
1900
|
logger4.debug(` Found ${wsAlias.aliasName} installed at project: ${installedVersion}`);
|
|
1478
1901
|
}
|
|
1479
1902
|
}
|
|
@@ -1484,7 +1907,9 @@ var DependencyAnalyzer = class {
|
|
|
1484
1907
|
return {
|
|
1485
1908
|
name: wsAlias.aliasName,
|
|
1486
1909
|
version: installedVersion,
|
|
1487
|
-
isWorkspaceAlias: true
|
|
1910
|
+
isWorkspaceAlias: true,
|
|
1911
|
+
installedPath,
|
|
1912
|
+
scope: "workspace"
|
|
1488
1913
|
};
|
|
1489
1914
|
} else {
|
|
1490
1915
|
logger4.debug(
|
|
@@ -1493,27 +1918,6 @@ var DependencyAnalyzer = class {
|
|
|
1493
1918
|
}
|
|
1494
1919
|
continue;
|
|
1495
1920
|
}
|
|
1496
|
-
const declaredSpec = wsAlias.versionSpec;
|
|
1497
|
-
if (declaredSpec) {
|
|
1498
|
-
logger4.debug(
|
|
1499
|
-
` Checking ${wsAlias.aliasName} (declared: ${declaredSpec}) - not installed yet`
|
|
1500
|
-
);
|
|
1501
|
-
const hasIntersection = ranges.every((range) => rangesIntersect(declaredSpec, range));
|
|
1502
|
-
if (hasIntersection) {
|
|
1503
|
-
logger4.info(
|
|
1504
|
-
` Can reuse workspace alias: ${wsAlias.aliasName} (declared: ${declaredSpec})`
|
|
1505
|
-
);
|
|
1506
|
-
return {
|
|
1507
|
-
name: wsAlias.aliasName,
|
|
1508
|
-
version: declaredSpec,
|
|
1509
|
-
isWorkspaceAlias: true
|
|
1510
|
-
};
|
|
1511
|
-
} else {
|
|
1512
|
-
logger4.debug(
|
|
1513
|
-
` Skip ${wsAlias.aliasName}: declared range ${declaredSpec} doesn't intersect with [${ranges.join(", ")}]`
|
|
1514
|
-
);
|
|
1515
|
-
}
|
|
1516
|
-
}
|
|
1517
1921
|
}
|
|
1518
1922
|
logger4.debug(` No existing alias found for ${packageName}`);
|
|
1519
1923
|
return null;
|
|
@@ -1568,6 +1972,64 @@ var DependencyAnalyzer = class {
|
|
|
1568
1972
|
}
|
|
1569
1973
|
return names;
|
|
1570
1974
|
}
|
|
1975
|
+
/**
|
|
1976
|
+
* Return every dependency key that the host or its workspace root owns.
|
|
1977
|
+
*
|
|
1978
|
+
* Generated aliases share the package namespace with ordinary dependency
|
|
1979
|
+
* keys. Keeping the complete set here prevents a generated alias from
|
|
1980
|
+
* silently replacing an unrelated dependency declared by the user.
|
|
1981
|
+
*/
|
|
1982
|
+
getReservedDependencyNames() {
|
|
1983
|
+
this.ensureWorkspaceRootDeclaredDepsLoaded();
|
|
1984
|
+
return /* @__PURE__ */ new Set([
|
|
1985
|
+
...Object.keys(this.rawDeclaredDeps),
|
|
1986
|
+
...Object.keys(this.declaredDeps),
|
|
1987
|
+
...Object.keys(this.workspaceRootDeclaredDeps)
|
|
1988
|
+
]);
|
|
1989
|
+
}
|
|
1990
|
+
normalizeInstalledPath(packagePath) {
|
|
1991
|
+
try {
|
|
1992
|
+
return fs.realpathSync(packagePath);
|
|
1993
|
+
} catch {
|
|
1994
|
+
return path.resolve(packagePath);
|
|
1995
|
+
}
|
|
1996
|
+
}
|
|
1997
|
+
findGraphChildNode(parent, dependencyName) {
|
|
1998
|
+
if (!this.dependencyGraph) return null;
|
|
1999
|
+
const packagePath = findPackagePath(dependencyName, parent.packagePath);
|
|
2000
|
+
if (!packagePath) return null;
|
|
2001
|
+
return this.dependencyGraph.nodes.get(this.normalizeInstalledPath(packagePath)) ?? null;
|
|
2002
|
+
}
|
|
2003
|
+
/**
|
|
2004
|
+
* 收集图中指定根实例的所有后代实例。返回 null 表示当前分析没有
|
|
2005
|
+
* 对应的图根,调用方可为兼容旧测试/旧调用回退到名称遍历。
|
|
2006
|
+
*/
|
|
2007
|
+
collectGraphRelatedPackageInstances(packageNames, excludePackages = []) {
|
|
2008
|
+
if (!this.dependencyGraph) return null;
|
|
2009
|
+
const roots = packageNames.map(
|
|
2010
|
+
(packageName) => this.dependencyGraph.roots.map((rootId) => this.dependencyGraph.nodes.get(rootId)).find(
|
|
2011
|
+
(node) => node?.name === packageName
|
|
2012
|
+
)
|
|
2013
|
+
).filter((node) => node !== void 0);
|
|
2014
|
+
if (roots.length === 0) return null;
|
|
2015
|
+
const excludeSet = new Set(excludePackages);
|
|
2016
|
+
const visited = /* @__PURE__ */ new Set();
|
|
2017
|
+
const collected = [];
|
|
2018
|
+
const stack = roots.map((root) => root.id);
|
|
2019
|
+
while (stack.length > 0) {
|
|
2020
|
+
const nodeId = stack.pop();
|
|
2021
|
+
if (!nodeId || visited.has(nodeId)) continue;
|
|
2022
|
+
visited.add(nodeId);
|
|
2023
|
+
const node = this.dependencyGraph.nodes.get(nodeId);
|
|
2024
|
+
if (!node || excludeSet.has(node.name)) continue;
|
|
2025
|
+
collected.push({ name: node.name, path: node.packagePath });
|
|
2026
|
+
for (const dependencyName of [...node.dependencyNames, ...node.peerDependencyNames]) {
|
|
2027
|
+
const child = this.findGraphChildNode(node, dependencyName);
|
|
2028
|
+
if (child && !visited.has(child.id)) stack.push(child.id);
|
|
2029
|
+
}
|
|
2030
|
+
}
|
|
2031
|
+
return collected;
|
|
2032
|
+
}
|
|
1571
2033
|
/**
|
|
1572
2034
|
* 递归收集指定包的所有子依赖(dependencies + peerDependencies)
|
|
1573
2035
|
*
|
|
@@ -1642,6 +2104,12 @@ var DependencyAnalyzer = class {
|
|
|
1642
2104
|
if (cached) {
|
|
1643
2105
|
return cached;
|
|
1644
2106
|
}
|
|
2107
|
+
const graphInstances = this.collectGraphRelatedPackageInstances(packageNames, excludePackages);
|
|
2108
|
+
if (graphInstances) {
|
|
2109
|
+
const result2 = [...new Set(graphInstances.map((instance) => instance.name))];
|
|
2110
|
+
this.collectCache.set(cacheKey, result2);
|
|
2111
|
+
return result2;
|
|
2112
|
+
}
|
|
1645
2113
|
const collected = /* @__PURE__ */ new Set();
|
|
1646
2114
|
const visited = /* @__PURE__ */ new Set();
|
|
1647
2115
|
const excludeSet = new Set(excludePackages);
|
|
@@ -1721,13 +2189,25 @@ var AliasManager = class {
|
|
|
1721
2189
|
this.buildRules();
|
|
1722
2190
|
logger5.info(`Initialized ${this.aliasMappings.length} alias mappings`);
|
|
1723
2191
|
}
|
|
2192
|
+
/**
|
|
2193
|
+
* 清理当前 generation 的别名规则。
|
|
2194
|
+
*
|
|
2195
|
+
* Resolver 失效或回滚时必须移除旧规则,避免失败的 generation 继续参与解析。
|
|
2196
|
+
*/
|
|
2197
|
+
clear() {
|
|
2198
|
+
this.aliasMappings = [];
|
|
2199
|
+
this.rulesMap = /* @__PURE__ */ new Map();
|
|
2200
|
+
this.importerCache.clear();
|
|
2201
|
+
}
|
|
1724
2202
|
/**
|
|
1725
2203
|
* 基于 allDependents 构建规则(用 Set 做成员判断,避免超大正则导致的性能与长度问题)
|
|
1726
2204
|
*/
|
|
1727
2205
|
buildRules() {
|
|
1728
2206
|
this.rulesMap = /* @__PURE__ */ new Map();
|
|
2207
|
+
this.importerCache.clear();
|
|
1729
2208
|
for (const mapping of this.aliasMappings) {
|
|
1730
|
-
const
|
|
2209
|
+
const isPathScoped = mapping.importerPaths !== void 0;
|
|
2210
|
+
const dependents = new Set(isPathScoped ? [] : mapping.allDependents ?? []);
|
|
1731
2211
|
const includeList = this.options.includeRedirects[mapping.originalName] ?? [];
|
|
1732
2212
|
if (includeList.length > 0) {
|
|
1733
2213
|
for (const dep of includeList) {
|
|
@@ -1736,7 +2216,7 @@ var AliasManager = class {
|
|
|
1736
2216
|
logger5.debug(`Included redirects for ${mapping.originalName}: ${includeList.join(", ")}`);
|
|
1737
2217
|
}
|
|
1738
2218
|
const excludeList = this.options.excludeRedirects[mapping.originalName] ?? [];
|
|
1739
|
-
if (excludeList.length > 0) {
|
|
2219
|
+
if (!isPathScoped && excludeList.length > 0) {
|
|
1740
2220
|
for (const dep of excludeList) {
|
|
1741
2221
|
dependents.delete(dep);
|
|
1742
2222
|
}
|
|
@@ -1745,7 +2225,9 @@ var AliasManager = class {
|
|
|
1745
2225
|
const rule = {
|
|
1746
2226
|
originalName: mapping.originalName,
|
|
1747
2227
|
aliasName: mapping.aliasName,
|
|
1748
|
-
dependents
|
|
2228
|
+
dependents,
|
|
2229
|
+
importerPaths: isPathScoped ? mapping.importerPaths.map((path) => this.normalizeImporterPath(path)) : void 0,
|
|
2230
|
+
excludedPackages: new Set(excludeList)
|
|
1749
2231
|
};
|
|
1750
2232
|
const list = this.rulesMap.get(rule.originalName);
|
|
1751
2233
|
if (list) {
|
|
@@ -1788,12 +2270,17 @@ var AliasManager = class {
|
|
|
1788
2270
|
* - /p/node_modules/@s/a/dist/index.js -> ["@s/a"]
|
|
1789
2271
|
* - /p/node_modules/.pnpm/a@1/node_modules/a/ -> ["a"](会跳过 ".pnpm")
|
|
1790
2272
|
*/
|
|
1791
|
-
|
|
2273
|
+
normalizeImporterPath(importerPath) {
|
|
2274
|
+
const normalized = path.posix.normalize(importerPath.replace(/\\/g, "/"));
|
|
2275
|
+
if (normalized.length <= 1) return normalized;
|
|
2276
|
+
return normalized.replace(/\/+$/, "");
|
|
2277
|
+
}
|
|
2278
|
+
extractImporterPackageInstances(importer) {
|
|
1792
2279
|
const cached = this.importerCache.get(importer);
|
|
1793
2280
|
if (cached) {
|
|
1794
2281
|
return cached;
|
|
1795
2282
|
}
|
|
1796
|
-
const normalized =
|
|
2283
|
+
const normalized = this.normalizeImporterPath(importer);
|
|
1797
2284
|
const parts = normalized.split("/");
|
|
1798
2285
|
const packages = [];
|
|
1799
2286
|
for (let i = 0; i < parts.length - 1; i++) {
|
|
@@ -1805,15 +2292,59 @@ var AliasManager = class {
|
|
|
1805
2292
|
if (next.startsWith("@")) {
|
|
1806
2293
|
const name = parts[i + 2];
|
|
1807
2294
|
if (name) {
|
|
1808
|
-
packages.push(
|
|
2295
|
+
packages.push({
|
|
2296
|
+
name: `${next}/${name}`,
|
|
2297
|
+
path: this.normalizeImporterPath(parts.slice(0, i + 3).join("/"))
|
|
2298
|
+
});
|
|
1809
2299
|
}
|
|
1810
2300
|
continue;
|
|
1811
2301
|
}
|
|
1812
|
-
packages.push(
|
|
2302
|
+
packages.push({
|
|
2303
|
+
name: next,
|
|
2304
|
+
path: this.normalizeImporterPath(parts.slice(0, i + 2).join("/"))
|
|
2305
|
+
});
|
|
1813
2306
|
}
|
|
1814
2307
|
this.importerCache.set(importer, packages);
|
|
1815
2308
|
return packages;
|
|
1816
2309
|
}
|
|
2310
|
+
matchesImporterPath(importer, packagePath) {
|
|
2311
|
+
const importerCandidates = this.getNormalizedPathCandidates(importer);
|
|
2312
|
+
const packageCandidates = this.getNormalizedPathCandidates(packagePath);
|
|
2313
|
+
return [...importerCandidates].some(
|
|
2314
|
+
(normalizedImporter) => [...packageCandidates].some(
|
|
2315
|
+
(normalizedPackagePath) => normalizedImporter === normalizedPackagePath || normalizedImporter.startsWith(`${normalizedPackagePath}/`)
|
|
2316
|
+
)
|
|
2317
|
+
);
|
|
2318
|
+
}
|
|
2319
|
+
getNormalizedPathCandidates(path) {
|
|
2320
|
+
const candidates = /* @__PURE__ */ new Set([this.normalizeImporterPath(path)]);
|
|
2321
|
+
try {
|
|
2322
|
+
candidates.add(this.normalizeImporterPath(fs.realpathSync(path)));
|
|
2323
|
+
} catch {
|
|
2324
|
+
}
|
|
2325
|
+
return candidates;
|
|
2326
|
+
}
|
|
2327
|
+
getPathScopedMatch(rule, importer, importerInstances) {
|
|
2328
|
+
if (!rule.importerPaths) return null;
|
|
2329
|
+
const matchedPaths = rule.importerPaths.filter(
|
|
2330
|
+
(packagePath) => this.matchesImporterPath(importer, packagePath)
|
|
2331
|
+
);
|
|
2332
|
+
const includedInstances = importerInstances.filter(
|
|
2333
|
+
(instance) => rule.dependents.has(instance.name)
|
|
2334
|
+
);
|
|
2335
|
+
const bestPath = matchedPaths.reduce(
|
|
2336
|
+
(current, packagePath) => !current || packagePath.length > current.length ? packagePath : current,
|
|
2337
|
+
null
|
|
2338
|
+
);
|
|
2339
|
+
if (!bestPath && includedInstances.length === 0) return null;
|
|
2340
|
+
const nestedInstances = importerInstances.filter(
|
|
2341
|
+
(instance) => matchedPaths.some((matchedPath) => this.matchesImporterPath(instance.path, matchedPath))
|
|
2342
|
+
);
|
|
2343
|
+
return {
|
|
2344
|
+
excluded: nestedInstances.some((instance) => rule.excludedPackages.has(instance.name)) || includedInstances.some((instance) => rule.excludedPackages.has(instance.name)),
|
|
2345
|
+
specificity: bestPath?.length ?? 0
|
|
2346
|
+
};
|
|
2347
|
+
}
|
|
1817
2348
|
/**
|
|
1818
2349
|
* 解析模块请求
|
|
1819
2350
|
* @returns 解析后的模块名,如果不需要重定向则返回 null
|
|
@@ -1823,8 +2354,8 @@ var AliasManager = class {
|
|
|
1823
2354
|
if (!importer) {
|
|
1824
2355
|
return null;
|
|
1825
2356
|
}
|
|
1826
|
-
const
|
|
1827
|
-
if (
|
|
2357
|
+
const importerInstances = this.extractImporterPackageInstances(importer);
|
|
2358
|
+
if (importerInstances.length === 0) {
|
|
1828
2359
|
return null;
|
|
1829
2360
|
}
|
|
1830
2361
|
const requestPackageName = this.getRequestPackageName(request);
|
|
@@ -1835,14 +2366,32 @@ var AliasManager = class {
|
|
|
1835
2366
|
if (!candidateRules || candidateRules.length === 0) {
|
|
1836
2367
|
return null;
|
|
1837
2368
|
}
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
2369
|
+
const pathMatches = candidateRules.map((rule) => ({ rule, match: this.getPathScopedMatch(rule, importer, importerInstances) })).filter(
|
|
2370
|
+
(entry) => entry.match !== null
|
|
2371
|
+
).sort(
|
|
2372
|
+
(left, right) => right.match.specificity - left.match.specificity || left.rule.aliasName.localeCompare(right.rule.aliasName)
|
|
2373
|
+
);
|
|
2374
|
+
for (const { rule, match } of pathMatches) {
|
|
2375
|
+
if (match.excluded) {
|
|
2376
|
+
return null;
|
|
1845
2377
|
}
|
|
2378
|
+
if (request === rule.originalName) {
|
|
2379
|
+
logger5.debug(`Resolving ${request} -> ${rule.aliasName} (from ${importer})`);
|
|
2380
|
+
return rule.aliasName;
|
|
2381
|
+
}
|
|
2382
|
+
const prefix = `${rule.originalName}/`;
|
|
2383
|
+
if (request.startsWith(prefix)) {
|
|
2384
|
+
const resolved = `${rule.aliasName}${request.slice(rule.originalName.length)}`;
|
|
2385
|
+
logger5.debug(`Resolving ${request} -> ${resolved} (from ${importer})`);
|
|
2386
|
+
return resolved;
|
|
2387
|
+
}
|
|
2388
|
+
}
|
|
2389
|
+
for (const rule of candidateRules) {
|
|
2390
|
+
if (rule.importerPaths) continue;
|
|
2391
|
+
const hasExcludedImporter = importerInstances.some(
|
|
2392
|
+
({ name: pkg }) => rule.excludedPackages.has(pkg)
|
|
2393
|
+
);
|
|
2394
|
+
const shouldRedirect = !hasExcludedImporter && importerInstances.some(({ name: pkg }) => rule.dependents.has(pkg));
|
|
1846
2395
|
if (!shouldRedirect) {
|
|
1847
2396
|
continue;
|
|
1848
2397
|
}
|
|
@@ -1880,12 +2429,397 @@ var AliasManager = class {
|
|
|
1880
2429
|
function createAliasManager(options) {
|
|
1881
2430
|
return new AliasManager(options);
|
|
1882
2431
|
}
|
|
1883
|
-
var logger6 = createLogger("package-
|
|
2432
|
+
var logger6 = createLogger("package-manager-adapter");
|
|
2433
|
+
var PACKAGE_MANAGER_ENTRYPOINT_RULES = {
|
|
2434
|
+
npm: {
|
|
2435
|
+
cliVariables: ["NPM_CLI_JS"],
|
|
2436
|
+
cliBasenames: ["npm-cli.js", "npm.js"]
|
|
2437
|
+
},
|
|
2438
|
+
pnpm: {
|
|
2439
|
+
cliVariables: ["PNPM_CLI_JS"],
|
|
2440
|
+
cliBasenames: ["pnpm.cjs", "pnpm.js"]
|
|
2441
|
+
},
|
|
2442
|
+
yarn: {
|
|
2443
|
+
cliVariables: ["YARN_CLI_JS"],
|
|
2444
|
+
cliBasenames: ["yarn.js", "yarn.cjs"]
|
|
2445
|
+
}
|
|
2446
|
+
};
|
|
2447
|
+
var DEFAULT_TIMING = {
|
|
2448
|
+
timeoutMs: 12e4,
|
|
2449
|
+
terminateGraceMs: 5e3
|
|
2450
|
+
};
|
|
2451
|
+
function createPackageManagerAdapter(options, timing = DEFAULT_TIMING) {
|
|
2452
|
+
return {
|
|
2453
|
+
install: async (specs) => {
|
|
2454
|
+
const env = registryEnvironment(options.packageManager, options.registry);
|
|
2455
|
+
if (specs.length === 0) {
|
|
2456
|
+
return {
|
|
2457
|
+
success: true,
|
|
2458
|
+
exitCode: 0,
|
|
2459
|
+
stdout: "",
|
|
2460
|
+
stderr: "",
|
|
2461
|
+
timedOut: false
|
|
2462
|
+
};
|
|
2463
|
+
}
|
|
2464
|
+
const { command, args } = buildCommand(options.packageManager, specs, env);
|
|
2465
|
+
logger6.info(`Running: ${command} ${args.map((arg) => JSON.stringify(arg)).join(" ")}`);
|
|
2466
|
+
const child = child_process.spawn(command, args, {
|
|
2467
|
+
cwd: options.projectRoot,
|
|
2468
|
+
env,
|
|
2469
|
+
shell: false,
|
|
2470
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
2471
|
+
...process.platform === "win32" ? {} : { detached: true }
|
|
2472
|
+
});
|
|
2473
|
+
return new Promise((resolve3) => {
|
|
2474
|
+
let stdout = "";
|
|
2475
|
+
let stderr = "";
|
|
2476
|
+
let terminalError;
|
|
2477
|
+
let timedOut = false;
|
|
2478
|
+
let settled = false;
|
|
2479
|
+
let closeSeen = false;
|
|
2480
|
+
let timeoutId;
|
|
2481
|
+
let graceId;
|
|
2482
|
+
const clearTimers = () => {
|
|
2483
|
+
if (timeoutId !== void 0) {
|
|
2484
|
+
clearTimeout(timeoutId);
|
|
2485
|
+
}
|
|
2486
|
+
if (graceId !== void 0) {
|
|
2487
|
+
clearTimeout(graceId);
|
|
2488
|
+
}
|
|
2489
|
+
};
|
|
2490
|
+
const finish = (exitCode) => {
|
|
2491
|
+
if (settled) {
|
|
2492
|
+
return;
|
|
2493
|
+
}
|
|
2494
|
+
settled = true;
|
|
2495
|
+
clearTimers();
|
|
2496
|
+
resolve3({
|
|
2497
|
+
success: !timedOut && !terminalError && exitCode === 0,
|
|
2498
|
+
exitCode,
|
|
2499
|
+
stdout,
|
|
2500
|
+
stderr: stderr || (terminalError?.message ?? ""),
|
|
2501
|
+
timedOut
|
|
2502
|
+
});
|
|
2503
|
+
};
|
|
2504
|
+
child.stdout?.on("data", (data) => {
|
|
2505
|
+
stdout += data.toString();
|
|
2506
|
+
});
|
|
2507
|
+
child.stderr?.on("data", (data) => {
|
|
2508
|
+
stderr += data.toString();
|
|
2509
|
+
});
|
|
2510
|
+
child.on("error", (error) => {
|
|
2511
|
+
terminalError = error;
|
|
2512
|
+
});
|
|
2513
|
+
child.on("close", (exitCode) => {
|
|
2514
|
+
closeSeen = true;
|
|
2515
|
+
finish(exitCode);
|
|
2516
|
+
});
|
|
2517
|
+
timeoutId = setTimeout(() => {
|
|
2518
|
+
if (settled || closeSeen) {
|
|
2519
|
+
return;
|
|
2520
|
+
}
|
|
2521
|
+
timedOut = true;
|
|
2522
|
+
logger6.error(`Install timeout after ${timing.timeoutMs / 1e3}s`);
|
|
2523
|
+
sendTerminationSignal(child, "SIGTERM");
|
|
2524
|
+
graceId = setTimeout(() => {
|
|
2525
|
+
if (!settled && !closeSeen) {
|
|
2526
|
+
terminateProcessTree(child);
|
|
2527
|
+
}
|
|
2528
|
+
}, timing.terminateGraceMs);
|
|
2529
|
+
}, timing.timeoutMs);
|
|
2530
|
+
});
|
|
2531
|
+
}
|
|
2532
|
+
};
|
|
2533
|
+
}
|
|
2534
|
+
function buildCommand(packageManager, specs, environment) {
|
|
2535
|
+
const invocation = resolvePackageManagerInvocation(packageManager, process.platform, environment);
|
|
2536
|
+
switch (packageManager) {
|
|
2537
|
+
case "pnpm":
|
|
2538
|
+
return {
|
|
2539
|
+
command: invocation.command,
|
|
2540
|
+
args: [...invocation.argsPrefix, "add", "--save-exact", ...specs]
|
|
2541
|
+
};
|
|
2542
|
+
case "yarn":
|
|
2543
|
+
return {
|
|
2544
|
+
command: invocation.command,
|
|
2545
|
+
args: [...invocation.argsPrefix, "add", "--exact", ...specs]
|
|
2546
|
+
};
|
|
2547
|
+
case "npm":
|
|
2548
|
+
return {
|
|
2549
|
+
command: invocation.command,
|
|
2550
|
+
args: [...invocation.argsPrefix, "install", "--legacy-peer-deps", "--save-exact", ...specs]
|
|
2551
|
+
};
|
|
2552
|
+
}
|
|
2553
|
+
throw new Error(`Unsupported package manager: ${String(packageManager)}`);
|
|
2554
|
+
}
|
|
2555
|
+
function resolvePackageManagerCommand(packageManager, platform = process.platform) {
|
|
2556
|
+
return platform === "win32" ? `${packageManager}.cmd` : packageManager;
|
|
2557
|
+
}
|
|
2558
|
+
function resolvePackageManagerInvocation(packageManager, platform = process.platform, environment = process.env) {
|
|
2559
|
+
if (platform !== "win32") {
|
|
2560
|
+
return {
|
|
2561
|
+
command: resolvePackageManagerCommand(packageManager, platform),
|
|
2562
|
+
argsPrefix: []
|
|
2563
|
+
};
|
|
2564
|
+
}
|
|
2565
|
+
const windowsInvocation = resolveWindowsPackageManagerInvocation(packageManager, environment);
|
|
2566
|
+
if (!windowsInvocation) {
|
|
2567
|
+
throw new Error(`Could not resolve a Node entrypoint for ${packageManager}`);
|
|
2568
|
+
}
|
|
2569
|
+
return windowsInvocation;
|
|
2570
|
+
}
|
|
2571
|
+
function resolveWindowsPackageManagerInvocation(packageManager, environment) {
|
|
2572
|
+
const npmExecPath = getEnvironmentValue(environment, "npm_execpath");
|
|
2573
|
+
if (npmExecPath && matchesPackageManagerPath(packageManager, npmExecPath)) {
|
|
2574
|
+
const invocation = invocationFromPackageManagerPath(packageManager, npmExecPath, "win32");
|
|
2575
|
+
if (invocation) {
|
|
2576
|
+
return invocation;
|
|
2577
|
+
}
|
|
2578
|
+
}
|
|
2579
|
+
const pathValue = getEnvironmentValue(environment, "PATH");
|
|
2580
|
+
if (!pathValue) {
|
|
2581
|
+
return void 0;
|
|
2582
|
+
}
|
|
2583
|
+
for (const directory of pathValue.split(";")) {
|
|
2584
|
+
if (!directory) {
|
|
2585
|
+
continue;
|
|
2586
|
+
}
|
|
2587
|
+
const shimPath = path.win32.join(directory, `${packageManager}.cmd`);
|
|
2588
|
+
if (fs.existsSync(shimPath)) {
|
|
2589
|
+
const invocation = invocationFromPackageManagerPath(packageManager, shimPath, "win32");
|
|
2590
|
+
if (invocation) {
|
|
2591
|
+
return invocation;
|
|
2592
|
+
}
|
|
2593
|
+
}
|
|
2594
|
+
const executablePath = path.win32.join(directory, `${packageManager}.exe`);
|
|
2595
|
+
if (fs.existsSync(executablePath)) {
|
|
2596
|
+
return { command: executablePath, argsPrefix: [] };
|
|
2597
|
+
}
|
|
2598
|
+
}
|
|
2599
|
+
return void 0;
|
|
2600
|
+
}
|
|
2601
|
+
function invocationFromPackageManagerPath(packageManager, packageManagerPath, platform) {
|
|
2602
|
+
const lowerPath = packageManagerPath.toLowerCase();
|
|
2603
|
+
if (lowerPath.endsWith(".exe")) {
|
|
2604
|
+
return { command: packageManagerPath, argsPrefix: [] };
|
|
2605
|
+
}
|
|
2606
|
+
if (lowerPath.endsWith(".cmd") || lowerPath.endsWith(".bat")) {
|
|
2607
|
+
const entrypoint = parseWindowsShimEntrypoint(packageManager, packageManagerPath, platform);
|
|
2608
|
+
if (!entrypoint) {
|
|
2609
|
+
return void 0;
|
|
2610
|
+
}
|
|
2611
|
+
return { command: process.execPath, argsPrefix: [entrypoint] };
|
|
2612
|
+
}
|
|
2613
|
+
if (isJavaScriptEntrypoint(packageManagerPath)) {
|
|
2614
|
+
return { command: process.execPath, argsPrefix: [packageManagerPath] };
|
|
2615
|
+
}
|
|
2616
|
+
return void 0;
|
|
2617
|
+
}
|
|
2618
|
+
function parseWindowsShimEntrypoint(packageManager, shimPath, platform) {
|
|
2619
|
+
let shimContents;
|
|
2620
|
+
try {
|
|
2621
|
+
shimContents = fs.readFileSync(shimPath, "utf8");
|
|
2622
|
+
} catch (error) {
|
|
2623
|
+
logger6.debug(`Failed to read ${packageManager} shim: ${String(error)}`);
|
|
2624
|
+
return void 0;
|
|
2625
|
+
}
|
|
2626
|
+
const assignments = parseWindowsShimAssignments(shimContents);
|
|
2627
|
+
const rule = PACKAGE_MANAGER_ENTRYPOINT_RULES[packageManager];
|
|
2628
|
+
const allowedVariables = new Set(rule.cliVariables);
|
|
2629
|
+
for (const variable of rule.cliVariables) {
|
|
2630
|
+
const values = assignments.get(variable);
|
|
2631
|
+
if (!values) {
|
|
2632
|
+
continue;
|
|
2633
|
+
}
|
|
2634
|
+
for (const value of values) {
|
|
2635
|
+
const entrypoint = resolveShimTarget(
|
|
2636
|
+
value,
|
|
2637
|
+
assignments,
|
|
2638
|
+
shimPath,
|
|
2639
|
+
platform,
|
|
2640
|
+
allowedVariables
|
|
2641
|
+
);
|
|
2642
|
+
if (entrypoint && isKnownPackageManagerEntrypoint(packageManager, entrypoint)) {
|
|
2643
|
+
return entrypoint;
|
|
2644
|
+
}
|
|
2645
|
+
}
|
|
2646
|
+
}
|
|
2647
|
+
const directTargetPattern = /"((?:%~dp0|%dp0%)[\\/][^"\r\n]+\.(?:js|cjs|mjs))"/gi;
|
|
2648
|
+
for (const match of shimContents.matchAll(directTargetPattern)) {
|
|
2649
|
+
const target = match[1];
|
|
2650
|
+
if (target) {
|
|
2651
|
+
const entrypoint = resolveShimTarget(
|
|
2652
|
+
target,
|
|
2653
|
+
assignments,
|
|
2654
|
+
shimPath,
|
|
2655
|
+
platform,
|
|
2656
|
+
allowedVariables
|
|
2657
|
+
);
|
|
2658
|
+
if (entrypoint && isKnownPackageManagerEntrypoint(packageManager, entrypoint)) {
|
|
2659
|
+
return entrypoint;
|
|
2660
|
+
}
|
|
2661
|
+
}
|
|
2662
|
+
}
|
|
2663
|
+
const absoluteTargetPattern = /"([A-Za-z]:[\\/][^"\r\n]+\.(?:js|cjs|mjs))"/gi;
|
|
2664
|
+
for (const match of shimContents.matchAll(absoluteTargetPattern)) {
|
|
2665
|
+
const target = match[1];
|
|
2666
|
+
if (target) {
|
|
2667
|
+
const entrypoint = resolveShimTarget(
|
|
2668
|
+
target,
|
|
2669
|
+
assignments,
|
|
2670
|
+
shimPath,
|
|
2671
|
+
platform,
|
|
2672
|
+
allowedVariables
|
|
2673
|
+
);
|
|
2674
|
+
if (entrypoint && isKnownPackageManagerEntrypoint(packageManager, entrypoint)) {
|
|
2675
|
+
return entrypoint;
|
|
2676
|
+
}
|
|
2677
|
+
}
|
|
2678
|
+
}
|
|
2679
|
+
return void 0;
|
|
2680
|
+
}
|
|
2681
|
+
function parseWindowsShimAssignments(contents) {
|
|
2682
|
+
const assignments = /* @__PURE__ */ new Map();
|
|
2683
|
+
const assignmentPattern = /^\s*@?set\s+(?:"([A-Za-z_][A-Za-z0-9_]*)=([^"\r\n]*)"|([A-Za-z_][A-Za-z0-9_]*)=([^\r\n]*))\s*$/gim;
|
|
2684
|
+
for (const match of contents.matchAll(assignmentPattern)) {
|
|
2685
|
+
const name = (match[1] ?? match[3])?.toUpperCase();
|
|
2686
|
+
const value = (match[2] ?? match[4])?.trim();
|
|
2687
|
+
if (name && value !== void 0) {
|
|
2688
|
+
const values = assignments.get(name) ?? [];
|
|
2689
|
+
values.push(value);
|
|
2690
|
+
assignments.set(name, values);
|
|
2691
|
+
}
|
|
2692
|
+
}
|
|
2693
|
+
return assignments;
|
|
2694
|
+
}
|
|
2695
|
+
function resolveShimTarget(rawTarget, assignments, shimPath, platform, allowedVariables, seenVariables = /* @__PURE__ */ new Set()) {
|
|
2696
|
+
const target = rawTarget.trim().replace(/^"|"$/g, "");
|
|
2697
|
+
const markerMatch = target.match(/^%(?:~dp0|dp0%)([\\/].*)$/i);
|
|
2698
|
+
if (markerMatch?.[1]) {
|
|
2699
|
+
const pathModule = path.win32 ;
|
|
2700
|
+
const relativeTarget = markerMatch[1].replace(/^[\\/]/, "");
|
|
2701
|
+
const resolvedTarget = pathModule.resolve(pathModule.dirname(shimPath), relativeTarget);
|
|
2702
|
+
return isJavaScriptEntrypoint(resolvedTarget) ? resolvedTarget : void 0;
|
|
2703
|
+
}
|
|
2704
|
+
const variableMatch = target.match(/^%([A-Za-z_][A-Za-z0-9_]*)%([\\/].*)?$/);
|
|
2705
|
+
if (variableMatch?.[1]) {
|
|
2706
|
+
const variable = variableMatch[1].toUpperCase();
|
|
2707
|
+
if (!allowedVariables.has(variable)) {
|
|
2708
|
+
return void 0;
|
|
2709
|
+
}
|
|
2710
|
+
if (seenVariables.has(variable)) {
|
|
2711
|
+
return void 0;
|
|
2712
|
+
}
|
|
2713
|
+
const assignedValues = assignments.get(variable);
|
|
2714
|
+
if (!assignedValues) {
|
|
2715
|
+
return void 0;
|
|
2716
|
+
}
|
|
2717
|
+
const nextSeenVariables = new Set(seenVariables);
|
|
2718
|
+
nextSeenVariables.add(variable);
|
|
2719
|
+
for (const assignedValue of assignedValues) {
|
|
2720
|
+
const resolved = resolveShimTarget(
|
|
2721
|
+
`${assignedValue}${variableMatch[2] ?? ""}`,
|
|
2722
|
+
assignments,
|
|
2723
|
+
shimPath,
|
|
2724
|
+
platform,
|
|
2725
|
+
allowedVariables,
|
|
2726
|
+
nextSeenVariables
|
|
2727
|
+
);
|
|
2728
|
+
if (resolved) {
|
|
2729
|
+
return resolved;
|
|
2730
|
+
}
|
|
2731
|
+
}
|
|
2732
|
+
return void 0;
|
|
2733
|
+
}
|
|
2734
|
+
return isJavaScriptEntrypoint(target) ? target : void 0;
|
|
2735
|
+
}
|
|
2736
|
+
function isKnownPackageManagerEntrypoint(packageManager, filePath) {
|
|
2737
|
+
const fileName = path.win32.basename(filePath).toLowerCase();
|
|
2738
|
+
return PACKAGE_MANAGER_ENTRYPOINT_RULES[packageManager].cliBasenames.includes(fileName);
|
|
2739
|
+
}
|
|
2740
|
+
function matchesPackageManagerPath(packageManager, packageManagerPath, platform) {
|
|
2741
|
+
const pathModule = path.win32 ;
|
|
2742
|
+
const fileName = pathModule.basename(packageManagerPath).toLowerCase();
|
|
2743
|
+
return fileName === `${packageManager}.cmd` || fileName === `${packageManager}.exe` || isKnownPackageManagerEntrypoint(packageManager, packageManagerPath);
|
|
2744
|
+
}
|
|
2745
|
+
function isJavaScriptEntrypoint(filePath) {
|
|
2746
|
+
return /\.(?:js|cjs|mjs)$/i.test(filePath);
|
|
2747
|
+
}
|
|
2748
|
+
function getEnvironmentValue(environment, name) {
|
|
2749
|
+
const exactValue = environment[name];
|
|
2750
|
+
if (exactValue !== void 0) {
|
|
2751
|
+
return exactValue;
|
|
2752
|
+
}
|
|
2753
|
+
const lowerName = name.toLowerCase();
|
|
2754
|
+
const key = Object.keys(environment).find((candidate) => candidate.toLowerCase() === lowerName);
|
|
2755
|
+
return key ? environment[key] : void 0;
|
|
2756
|
+
}
|
|
2757
|
+
function registryEnvironment(packageManager, registry) {
|
|
2758
|
+
return {
|
|
2759
|
+
...process.env,
|
|
2760
|
+
npm_config_registry: registry,
|
|
2761
|
+
// Classic Yarn reads npm's registry setting; modern Yarn uses this key.
|
|
2762
|
+
...packageManager === "yarn" ? { YARN_NPM_REGISTRY_SERVER: registry } : {}
|
|
2763
|
+
};
|
|
2764
|
+
}
|
|
2765
|
+
function sendTerminationSignal(child, signal) {
|
|
2766
|
+
if (process.platform !== "win32" && child.pid) {
|
|
2767
|
+
try {
|
|
2768
|
+
process.kill(-child.pid, signal);
|
|
2769
|
+
return;
|
|
2770
|
+
} catch (error) {
|
|
2771
|
+
logger6.debug(`Failed to signal package-manager process group: ${String(error)}`);
|
|
2772
|
+
}
|
|
2773
|
+
}
|
|
2774
|
+
try {
|
|
2775
|
+
child.kill(signal);
|
|
2776
|
+
} catch (error) {
|
|
2777
|
+
logger6.debug(`Failed to signal package-manager process: ${String(error)}`);
|
|
2778
|
+
}
|
|
2779
|
+
}
|
|
2780
|
+
function terminateProcessTree(child) {
|
|
2781
|
+
if (process.platform === "win32") {
|
|
2782
|
+
if (!child.pid) {
|
|
2783
|
+
try {
|
|
2784
|
+
child.kill("SIGKILL");
|
|
2785
|
+
} catch (error) {
|
|
2786
|
+
logger6.debug(`Failed to terminate package-manager process: ${String(error)}`);
|
|
2787
|
+
}
|
|
2788
|
+
return;
|
|
2789
|
+
}
|
|
2790
|
+
const taskkill = child_process.spawn("taskkill", ["/pid", String(child.pid), "/t", "/f"], {
|
|
2791
|
+
shell: false,
|
|
2792
|
+
stdio: "ignore"
|
|
2793
|
+
});
|
|
2794
|
+
taskkill.on("error", (error) => {
|
|
2795
|
+
logger6.debug(`Failed to terminate package-manager process tree: ${error.message}`);
|
|
2796
|
+
});
|
|
2797
|
+
return;
|
|
2798
|
+
}
|
|
2799
|
+
if (child.pid) {
|
|
2800
|
+
try {
|
|
2801
|
+
process.kill(-child.pid, "SIGKILL");
|
|
2802
|
+
return;
|
|
2803
|
+
} catch (error) {
|
|
2804
|
+
logger6.debug(`Failed to terminate package-manager process group: ${String(error)}`);
|
|
2805
|
+
}
|
|
2806
|
+
}
|
|
2807
|
+
try {
|
|
2808
|
+
child.kill("SIGKILL");
|
|
2809
|
+
} catch (error) {
|
|
2810
|
+
logger6.debug(`Failed to terminate package-manager process: ${String(error)}`);
|
|
2811
|
+
}
|
|
2812
|
+
}
|
|
2813
|
+
|
|
2814
|
+
// src/core/package-installer.ts
|
|
2815
|
+
var logger7 = createLogger("package-installer");
|
|
1884
2816
|
var INSTALL_TIMEOUT = 12e4;
|
|
1885
2817
|
var PackageInstaller = class {
|
|
1886
2818
|
options;
|
|
1887
|
-
|
|
2819
|
+
packageManager;
|
|
2820
|
+
constructor(options, packageManager = createPackageManagerAdapter(options)) {
|
|
1888
2821
|
this.options = options;
|
|
2822
|
+
this.packageManager = packageManager;
|
|
1889
2823
|
}
|
|
1890
2824
|
/**
|
|
1891
2825
|
* 安装别名依赖
|
|
@@ -1894,85 +2828,207 @@ var PackageInstaller = class {
|
|
|
1894
2828
|
const result = {
|
|
1895
2829
|
success: true,
|
|
1896
2830
|
installed: [],
|
|
2831
|
+
reused: [],
|
|
1897
2832
|
failed: [],
|
|
1898
2833
|
errors: []
|
|
1899
2834
|
};
|
|
1900
2835
|
if (mappings.length === 0) {
|
|
1901
|
-
|
|
2836
|
+
logger7.info("No aliases to install");
|
|
1902
2837
|
return result;
|
|
1903
2838
|
}
|
|
1904
|
-
const toInstall =
|
|
2839
|
+
const toInstall = [];
|
|
2840
|
+
const reportCollision = (mapping, verification) => {
|
|
2841
|
+
const collision = {
|
|
2842
|
+
code: "ALIAS_NAME_OCCUPIED",
|
|
2843
|
+
aliasName: mapping.aliasName,
|
|
2844
|
+
expected: {
|
|
2845
|
+
packageName: mapping.originalName,
|
|
2846
|
+
version: mapping.resolvedVersion
|
|
2847
|
+
},
|
|
2848
|
+
actual: {
|
|
2849
|
+
packageName: verification.actualPackageName,
|
|
2850
|
+
version: verification.actualVersion
|
|
2851
|
+
},
|
|
2852
|
+
reason: verification.reason
|
|
2853
|
+
};
|
|
2854
|
+
result.success = false;
|
|
2855
|
+
result.failed.push(mapping.aliasName);
|
|
2856
|
+
result.errors.push(`Alias collision: ${JSON.stringify(collision)}`);
|
|
2857
|
+
logger7.warn(`Alias collision: ${JSON.stringify(collision)}`);
|
|
2858
|
+
};
|
|
2859
|
+
const installedAliasPath = (aliasName) => {
|
|
2860
|
+
const local = path.join(this.options.projectRoot, "node_modules", aliasName);
|
|
2861
|
+
return fileExists(local) ? local : findPackagePath(aliasName, this.options.projectRoot);
|
|
2862
|
+
};
|
|
2863
|
+
const reportMissing = (mapping) => {
|
|
2864
|
+
result.success = false;
|
|
2865
|
+
result.failed.push(mapping.aliasName);
|
|
2866
|
+
result.errors.push("Alias is not installed or resolvable: " + mapping.aliasName);
|
|
2867
|
+
};
|
|
2868
|
+
for (const m of mappings) {
|
|
2869
|
+
const aliasPath = installedAliasPath(m.aliasName);
|
|
1905
2870
|
if (!m.installSpec) {
|
|
1906
|
-
|
|
1907
|
-
|
|
2871
|
+
if (!aliasPath) {
|
|
2872
|
+
reportMissing(m);
|
|
2873
|
+
continue;
|
|
2874
|
+
}
|
|
2875
|
+
const verification2 = this.verifyInstalledVersion(
|
|
2876
|
+
aliasPath,
|
|
2877
|
+
m.originalName,
|
|
2878
|
+
m.resolvedVersion
|
|
2879
|
+
);
|
|
2880
|
+
if (!verification2.matches) {
|
|
2881
|
+
reportCollision(m, verification2);
|
|
2882
|
+
continue;
|
|
2883
|
+
}
|
|
2884
|
+
logger7.debug(`Skipping ${m.aliasName}: reusing existing installation`);
|
|
2885
|
+
result.reused.push(m.aliasName);
|
|
2886
|
+
continue;
|
|
1908
2887
|
}
|
|
1909
|
-
|
|
1910
|
-
|
|
1911
|
-
|
|
2888
|
+
if (!aliasPath) {
|
|
2889
|
+
toInstall.push(m);
|
|
2890
|
+
continue;
|
|
1912
2891
|
}
|
|
1913
|
-
const
|
|
2892
|
+
const verification = this.verifyInstalledVersion(
|
|
1914
2893
|
aliasPath,
|
|
1915
2894
|
m.originalName,
|
|
1916
2895
|
m.resolvedVersion
|
|
1917
2896
|
);
|
|
1918
|
-
if (!
|
|
1919
|
-
|
|
1920
|
-
|
|
2897
|
+
if (!verification.matches) {
|
|
2898
|
+
reportCollision(m, verification);
|
|
2899
|
+
continue;
|
|
1921
2900
|
}
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
}
|
|
2901
|
+
logger7.debug(`${m.aliasName} already installed with correct version`);
|
|
2902
|
+
result.reused.push(m.aliasName);
|
|
2903
|
+
}
|
|
1925
2904
|
if (toInstall.length === 0) {
|
|
1926
|
-
|
|
2905
|
+
if (result.success) {
|
|
2906
|
+
logger7.info("All aliases already installed with correct versions");
|
|
2907
|
+
}
|
|
1927
2908
|
return result;
|
|
1928
2909
|
}
|
|
1929
|
-
|
|
2910
|
+
logger7.info(`Installing ${toInstall.length} alias packages...`);
|
|
1930
2911
|
const installSpecs = toInstall.map((m) => m.installSpec);
|
|
1931
|
-
|
|
2912
|
+
let installResult;
|
|
2913
|
+
try {
|
|
2914
|
+
installResult = await this.runInstall(installSpecs);
|
|
2915
|
+
} finally {
|
|
2916
|
+
clearPackageJsonCache();
|
|
2917
|
+
}
|
|
2918
|
+
const reusedBeforeInstall = new Set(result.reused);
|
|
2919
|
+
result.reused = [];
|
|
2920
|
+
for (const mapping of mappings) {
|
|
2921
|
+
if (!reusedBeforeInstall.has(mapping.aliasName)) continue;
|
|
2922
|
+
const aliasPath = installedAliasPath(mapping.aliasName);
|
|
2923
|
+
if (!aliasPath) {
|
|
2924
|
+
reportMissing(mapping);
|
|
2925
|
+
continue;
|
|
2926
|
+
}
|
|
2927
|
+
const verification = this.verifyInstalledVersion(
|
|
2928
|
+
aliasPath,
|
|
2929
|
+
mapping.originalName,
|
|
2930
|
+
mapping.resolvedVersion
|
|
2931
|
+
);
|
|
2932
|
+
if (verification.matches) {
|
|
2933
|
+
result.reused.push(mapping.aliasName);
|
|
2934
|
+
} else {
|
|
2935
|
+
reportCollision(mapping, verification);
|
|
2936
|
+
}
|
|
2937
|
+
}
|
|
1932
2938
|
if (installResult.success) {
|
|
1933
|
-
|
|
1934
|
-
|
|
2939
|
+
for (const mapping of toInstall) {
|
|
2940
|
+
const aliasPath = installedAliasPath(mapping.aliasName);
|
|
2941
|
+
if (!aliasPath) {
|
|
2942
|
+
reportMissing(mapping);
|
|
2943
|
+
continue;
|
|
2944
|
+
}
|
|
2945
|
+
const verification = this.verifyInstalledVersion(
|
|
2946
|
+
aliasPath,
|
|
2947
|
+
mapping.originalName,
|
|
2948
|
+
mapping.resolvedVersion
|
|
2949
|
+
);
|
|
2950
|
+
if (verification.matches) {
|
|
2951
|
+
result.installed.push(mapping.aliasName);
|
|
2952
|
+
} else {
|
|
2953
|
+
reportCollision(mapping, verification);
|
|
2954
|
+
}
|
|
2955
|
+
}
|
|
2956
|
+
if (result.installed.length > 0) {
|
|
2957
|
+
logger7.info(`Successfully installed: ${result.installed.join(", ")}`);
|
|
2958
|
+
}
|
|
1935
2959
|
} else {
|
|
1936
2960
|
result.success = false;
|
|
1937
|
-
result.failed
|
|
1938
|
-
result.errors
|
|
1939
|
-
|
|
2961
|
+
result.failed.push(...toInstall.map((m) => m.aliasName));
|
|
2962
|
+
result.errors.push(...installResult.errors);
|
|
2963
|
+
logger7.error(`Failed to install aliases: ${installResult.errors.join(", ")}`);
|
|
1940
2964
|
}
|
|
1941
2965
|
return result;
|
|
1942
2966
|
}
|
|
1943
2967
|
/**
|
|
1944
2968
|
* 验证已安装的别名版本是否正确
|
|
1945
|
-
* @returns
|
|
2969
|
+
* @returns 验证结果及已安装包信息
|
|
1946
2970
|
*/
|
|
1947
2971
|
verifyInstalledVersion(aliasPath, expectedPackageName, expectedVersion) {
|
|
1948
2972
|
try {
|
|
1949
2973
|
const pkgJsonPath = path.join(aliasPath, "package.json");
|
|
1950
2974
|
if (!fileExists(pkgJsonPath)) {
|
|
1951
|
-
return
|
|
2975
|
+
return {
|
|
2976
|
+
matches: false,
|
|
2977
|
+
actualPackageName: null,
|
|
2978
|
+
actualVersion: null,
|
|
2979
|
+
reason: "missing-package-json"
|
|
2980
|
+
};
|
|
1952
2981
|
}
|
|
1953
2982
|
const pkgJson = readPackageJsonCached(aliasPath);
|
|
1954
2983
|
if (!pkgJson) {
|
|
1955
|
-
|
|
1956
|
-
return
|
|
2984
|
+
logger7.debug(`Failed to verify version: unable to read/parse ${pkgJsonPath}`);
|
|
2985
|
+
return {
|
|
2986
|
+
matches: false,
|
|
2987
|
+
actualPackageName: null,
|
|
2988
|
+
actualVersion: null,
|
|
2989
|
+
reason: "invalid-package-json"
|
|
2990
|
+
};
|
|
1957
2991
|
}
|
|
2992
|
+
const actualPackageName = pkgJson.name ?? null;
|
|
2993
|
+
const actualVersion = pkgJson.version ?? null;
|
|
1958
2994
|
if (pkgJson.name !== expectedPackageName) {
|
|
1959
|
-
|
|
2995
|
+
logger7.debug(
|
|
1960
2996
|
`Package name mismatch: expected ${expectedPackageName}, got ${pkgJson.name ?? "unknown"}`
|
|
1961
2997
|
);
|
|
1962
|
-
return
|
|
2998
|
+
return {
|
|
2999
|
+
matches: false,
|
|
3000
|
+
actualPackageName,
|
|
3001
|
+
actualVersion,
|
|
3002
|
+
reason: "package-name-mismatch"
|
|
3003
|
+
};
|
|
1963
3004
|
}
|
|
1964
3005
|
const installedClean = semver__default.default.clean(pkgJson.version ?? "");
|
|
1965
3006
|
const expectedClean = semver__default.default.clean(expectedVersion);
|
|
1966
3007
|
if (!installedClean || !expectedClean || installedClean !== expectedClean) {
|
|
1967
|
-
|
|
3008
|
+
logger7.debug(
|
|
1968
3009
|
`Version mismatch: expected ${expectedVersion}, got ${pkgJson.version ?? "unknown"}`
|
|
1969
3010
|
);
|
|
1970
|
-
return
|
|
3011
|
+
return {
|
|
3012
|
+
matches: false,
|
|
3013
|
+
actualPackageName,
|
|
3014
|
+
actualVersion,
|
|
3015
|
+
reason: "version-mismatch"
|
|
3016
|
+
};
|
|
1971
3017
|
}
|
|
1972
|
-
return
|
|
3018
|
+
return {
|
|
3019
|
+
matches: true,
|
|
3020
|
+
actualPackageName,
|
|
3021
|
+
actualVersion,
|
|
3022
|
+
reason: "matched"
|
|
3023
|
+
};
|
|
1973
3024
|
} catch (error) {
|
|
1974
|
-
|
|
1975
|
-
return
|
|
3025
|
+
logger7.debug(`Failed to verify version: ${String(error)}`);
|
|
3026
|
+
return {
|
|
3027
|
+
matches: false,
|
|
3028
|
+
actualPackageName: null,
|
|
3029
|
+
actualVersion: null,
|
|
3030
|
+
reason: "invalid-package-json"
|
|
3031
|
+
};
|
|
1976
3032
|
}
|
|
1977
3033
|
}
|
|
1978
3034
|
/**
|
|
@@ -1982,96 +3038,20 @@ var PackageInstaller = class {
|
|
|
1982
3038
|
if (packages.length === 0) {
|
|
1983
3039
|
return { success: true, errors: [] };
|
|
1984
3040
|
}
|
|
1985
|
-
const
|
|
1986
|
-
|
|
1987
|
-
|
|
1988
|
-
|
|
1989
|
-
|
|
1990
|
-
|
|
1991
|
-
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
|
|
1995
|
-
|
|
1996
|
-
|
|
1997
|
-
|
|
1998
|
-
|
|
1999
|
-
command = "npm";
|
|
2000
|
-
args = ["install", "--legacy-peer-deps", ...packages];
|
|
2001
|
-
break;
|
|
2002
|
-
}
|
|
2003
|
-
const fullCommand = `${command} ${args.join(" ")}`;
|
|
2004
|
-
logger6.info(`Running: ${fullCommand}`);
|
|
2005
|
-
const startTime = Date.now();
|
|
2006
|
-
return new Promise((resolve) => {
|
|
2007
|
-
let resolved = false;
|
|
2008
|
-
const child = child_process.spawn(command, args, {
|
|
2009
|
-
cwd: projectRoot,
|
|
2010
|
-
shell: true,
|
|
2011
|
-
stdio: ["pipe", "pipe", "pipe"]
|
|
2012
|
-
});
|
|
2013
|
-
let stdout = "";
|
|
2014
|
-
let stderr = "";
|
|
2015
|
-
const timeoutId = setTimeout(() => {
|
|
2016
|
-
if (!resolved) {
|
|
2017
|
-
resolved = true;
|
|
2018
|
-
logger6.error(`Install timeout after ${INSTALL_TIMEOUT / 1e3}s`);
|
|
2019
|
-
child.kill("SIGTERM");
|
|
2020
|
-
setTimeout(() => {
|
|
2021
|
-
if (!child.killed) {
|
|
2022
|
-
child.kill("SIGKILL");
|
|
2023
|
-
}
|
|
2024
|
-
}, 5e3);
|
|
2025
|
-
resolve({
|
|
2026
|
-
success: false,
|
|
2027
|
-
errors: [`Install timeout after ${INSTALL_TIMEOUT / 1e3}s`]
|
|
2028
|
-
});
|
|
2029
|
-
}
|
|
2030
|
-
}, INSTALL_TIMEOUT);
|
|
2031
|
-
child.stdout?.on("data", (data) => {
|
|
2032
|
-
stdout += data.toString();
|
|
2033
|
-
});
|
|
2034
|
-
child.stderr?.on("data", (data) => {
|
|
2035
|
-
stderr += data.toString();
|
|
2036
|
-
});
|
|
2037
|
-
child.on("error", (error) => {
|
|
2038
|
-
if (!resolved) {
|
|
2039
|
-
resolved = true;
|
|
2040
|
-
clearTimeout(timeoutId);
|
|
2041
|
-
logger6.error(`Install error: ${error.message}`);
|
|
2042
|
-
resolve({
|
|
2043
|
-
success: false,
|
|
2044
|
-
errors: [error.message]
|
|
2045
|
-
});
|
|
2046
|
-
}
|
|
2047
|
-
});
|
|
2048
|
-
child.on("close", (code) => {
|
|
2049
|
-
if (!resolved) {
|
|
2050
|
-
resolved = true;
|
|
2051
|
-
clearTimeout(timeoutId);
|
|
2052
|
-
const elapsed = ((Date.now() - startTime) / 1e3).toFixed(1);
|
|
2053
|
-
if (code === 0) {
|
|
2054
|
-
if (stdout) {
|
|
2055
|
-
logger6.debug(`stdout: ${stdout}`);
|
|
2056
|
-
}
|
|
2057
|
-
logger6.info(`Install completed in ${elapsed}s`);
|
|
2058
|
-
resolve({ success: true, errors: [] });
|
|
2059
|
-
} else {
|
|
2060
|
-
logger6.error(`Install failed with exit code ${code}`);
|
|
2061
|
-
if (stdout) {
|
|
2062
|
-
logger6.debug(`stdout: ${stdout}`);
|
|
2063
|
-
}
|
|
2064
|
-
if (stderr) {
|
|
2065
|
-
logger6.debug(`stderr: ${stderr}`);
|
|
2066
|
-
}
|
|
2067
|
-
resolve({
|
|
2068
|
-
success: false,
|
|
2069
|
-
errors: stderr ? [stderr] : [`Process exited with code ${code}`]
|
|
2070
|
-
});
|
|
2071
|
-
}
|
|
2072
|
-
}
|
|
2073
|
-
});
|
|
2074
|
-
});
|
|
3041
|
+
const runResult = await this.packageManager.install(packages);
|
|
3042
|
+
if (runResult.stdout) {
|
|
3043
|
+
logger7.debug(`stdout: ${runResult.stdout}`);
|
|
3044
|
+
}
|
|
3045
|
+
if (runResult.stderr) {
|
|
3046
|
+
logger7.debug(`stderr: ${runResult.stderr}`);
|
|
3047
|
+
}
|
|
3048
|
+
if (runResult.success) {
|
|
3049
|
+
logger7.info("Install completed");
|
|
3050
|
+
return { success: true, errors: [] };
|
|
3051
|
+
}
|
|
3052
|
+
const errorMessage = runResult.timedOut ? `Install timeout after ${INSTALL_TIMEOUT / 1e3}s` : runResult.stderr || `Process exited with code ${runResult.exitCode}`;
|
|
3053
|
+
logger7.error(`Install failed: ${errorMessage}`);
|
|
3054
|
+
return { success: false, errors: [errorMessage] };
|
|
2075
3055
|
}
|
|
2076
3056
|
};
|
|
2077
3057
|
function createPackageInstaller(options) {
|
|
@@ -2079,7 +3059,7 @@ function createPackageInstaller(options) {
|
|
|
2079
3059
|
}
|
|
2080
3060
|
|
|
2081
3061
|
// src/core/resolver.ts
|
|
2082
|
-
var
|
|
3062
|
+
var logger8 = createLogger("resolver");
|
|
2083
3063
|
var DEFAULT_OPTIONS = {
|
|
2084
3064
|
autoInstall: true,
|
|
2085
3065
|
debug: false,
|
|
@@ -2091,15 +3071,16 @@ var DepsConflictResolver = class {
|
|
|
2091
3071
|
hooks;
|
|
2092
3072
|
environmentDetector = null;
|
|
2093
3073
|
analyzer = null;
|
|
2094
|
-
aliasManager;
|
|
2095
|
-
installer;
|
|
3074
|
+
aliasManager = null;
|
|
3075
|
+
installer = null;
|
|
2096
3076
|
analysisResult = null;
|
|
2097
3077
|
initialized = false;
|
|
3078
|
+
initializationPromise = null;
|
|
2098
3079
|
constructor(userOptions, hooks = {}) {
|
|
2099
3080
|
this.userOptions = userOptions;
|
|
2100
3081
|
this.hooks = hooks;
|
|
2101
3082
|
if (userOptions.debug) {
|
|
2102
|
-
|
|
3083
|
+
logger8.setLevel(1 /* DEBUG */);
|
|
2103
3084
|
}
|
|
2104
3085
|
}
|
|
2105
3086
|
/**
|
|
@@ -2111,7 +3092,7 @@ var DepsConflictResolver = class {
|
|
|
2111
3092
|
if (!userOptions.packageManager || userOptions.packageManager === "auto") {
|
|
2112
3093
|
const detected = this.environmentDetector.getDetectionResult();
|
|
2113
3094
|
packageManager = detected.packageManager;
|
|
2114
|
-
|
|
3095
|
+
logger8.info(
|
|
2115
3096
|
`Auto-detected package manager: ${packageManager} (from ${detected.detectedFrom})`
|
|
2116
3097
|
);
|
|
2117
3098
|
} else {
|
|
@@ -2121,7 +3102,7 @@ var DepsConflictResolver = class {
|
|
|
2121
3102
|
if (!userOptions.registry) {
|
|
2122
3103
|
registry = await this.environmentDetector.getRegistryForPackageManager(packageManager);
|
|
2123
3104
|
if (registry !== DEFAULT_NPM_REGISTRY) {
|
|
2124
|
-
|
|
3105
|
+
logger8.info(`Auto-detected registry: ${registry}`);
|
|
2125
3106
|
}
|
|
2126
3107
|
} else {
|
|
2127
3108
|
registry = userOptions.registry;
|
|
@@ -2146,34 +3127,74 @@ var DepsConflictResolver = class {
|
|
|
2146
3127
|
if (this.initialized) {
|
|
2147
3128
|
return;
|
|
2148
3129
|
}
|
|
2149
|
-
|
|
3130
|
+
const initialization = this.initializationPromise ??= this.initializeGeneration();
|
|
3131
|
+
try {
|
|
3132
|
+
await initialization;
|
|
3133
|
+
} catch (error) {
|
|
3134
|
+
if (this.initializationPromise === initialization) {
|
|
3135
|
+
this.initializationPromise = null;
|
|
3136
|
+
this.rollbackGeneration();
|
|
3137
|
+
}
|
|
3138
|
+
throw error;
|
|
3139
|
+
}
|
|
3140
|
+
}
|
|
3141
|
+
/**
|
|
3142
|
+
* 清理已完成的初始化状态,使下一次 initialize 创建新的分析 generation。
|
|
3143
|
+
*
|
|
3144
|
+
* 初始化尚未完成时不能失效当前 generation,否则并发调用者会观察到
|
|
3145
|
+
* 不一致的部分状态。
|
|
3146
|
+
*/
|
|
3147
|
+
invalidate() {
|
|
3148
|
+
if (this.initializationPromise && !this.initialized) {
|
|
3149
|
+
throw new Error("Cannot invalidate while initialization is in progress");
|
|
3150
|
+
}
|
|
3151
|
+
this.initialized = false;
|
|
3152
|
+
this.initializationPromise = null;
|
|
3153
|
+
this.rollbackGeneration();
|
|
3154
|
+
}
|
|
3155
|
+
/**
|
|
3156
|
+
* 回滚未完成或已失效的 generation,确保外部不会观察到半成品规则。
|
|
3157
|
+
*/
|
|
3158
|
+
rollbackGeneration() {
|
|
3159
|
+
this.initialized = false;
|
|
3160
|
+
this.analysisResult = null;
|
|
3161
|
+
this.analyzer = null;
|
|
3162
|
+
this.aliasManager?.clear?.();
|
|
3163
|
+
this.aliasManager = null;
|
|
3164
|
+
this.installer = null;
|
|
3165
|
+
}
|
|
3166
|
+
async initializeGeneration() {
|
|
3167
|
+
logger8.info("Initializing dependencies resolver...");
|
|
2150
3168
|
const projectRoot = this.userOptions.projectRoot ?? process.cwd();
|
|
2151
3169
|
const validRoot = findProjectRoot(projectRoot);
|
|
2152
3170
|
if (!validRoot) {
|
|
2153
3171
|
throw new Error(`Could not find package.json in ${projectRoot} or parent directories`);
|
|
2154
3172
|
}
|
|
2155
3173
|
if (validRoot !== projectRoot) {
|
|
2156
|
-
|
|
3174
|
+
logger8.debug(`Adjusted project root to: ${validRoot}`);
|
|
2157
3175
|
}
|
|
2158
3176
|
this.options = await this.resolveOptions(this.userOptions, validRoot);
|
|
2159
3177
|
if (this.options.debug) {
|
|
2160
|
-
|
|
3178
|
+
logger8.setLevel(1 /* DEBUG */);
|
|
2161
3179
|
}
|
|
2162
3180
|
this.aliasManager = createAliasManager(this.options);
|
|
2163
3181
|
this.installer = createPackageInstaller(this.options);
|
|
2164
3182
|
this.analyzer = createDependencyAnalyzer(this.options);
|
|
2165
3183
|
this.analysisResult = await this.analyzer.analyze();
|
|
2166
3184
|
this.logMissingFirstLevelPeers(this.analysisResult);
|
|
2167
|
-
this.aliasManager.initFromAnalysisResult(this.analysisResult);
|
|
2168
3185
|
if (this.hooks.onAnalysisComplete) {
|
|
2169
3186
|
await this.hooks.onAnalysisComplete(this.analysisResult);
|
|
2170
3187
|
}
|
|
2171
3188
|
if (this.options.autoInstall) {
|
|
2172
3189
|
await this.installDependencies();
|
|
3190
|
+
} else {
|
|
3191
|
+
this.setActiveAliasMappings(
|
|
3192
|
+
this.analysisResult.aliasMappings.filter((mapping) => mapping.installSpec === "")
|
|
3193
|
+
);
|
|
2173
3194
|
}
|
|
2174
3195
|
this.analyzer = null;
|
|
2175
3196
|
this.initialized = true;
|
|
2176
|
-
|
|
3197
|
+
logger8.info("Dependencies resolver initialized");
|
|
2177
3198
|
}
|
|
2178
3199
|
/**
|
|
2179
3200
|
* 输出第一层依赖中缺失的 peer 依赖警告(不自动安装,仅提示)
|
|
@@ -2185,9 +3206,9 @@ var DepsConflictResolver = class {
|
|
|
2185
3206
|
if (!missing || missing.length === 0) {
|
|
2186
3207
|
return;
|
|
2187
3208
|
}
|
|
2188
|
-
|
|
3209
|
+
logger8.warn(`Found ${missing.length} unsatisfied peer dependencies (not auto-installing):`);
|
|
2189
3210
|
for (const peer of missing) {
|
|
2190
|
-
|
|
3211
|
+
logger8.warn(
|
|
2191
3212
|
` - ${peer.packageName}@${peer.requiredRange} (required by ${peer.requestedBy})`
|
|
2192
3213
|
);
|
|
2193
3214
|
}
|
|
@@ -2203,23 +3224,101 @@ var DepsConflictResolver = class {
|
|
|
2203
3224
|
* 这样可以避免"什么依赖都自动安装"的问题,用户可以根据警告自行决定是否安装缺失的依赖
|
|
2204
3225
|
*/
|
|
2205
3226
|
async installDependencies() {
|
|
2206
|
-
if (!this.analysisResult) {
|
|
3227
|
+
if (!this.analysisResult || !this.installer) {
|
|
2207
3228
|
throw new Error("Resolver not initialized. Call initialize() first.");
|
|
2208
3229
|
}
|
|
2209
3230
|
const { aliasMappings } = this.analysisResult;
|
|
2210
|
-
|
|
3231
|
+
let aliasResult;
|
|
3232
|
+
try {
|
|
3233
|
+
aliasResult = await this.installer.installAliases(aliasMappings);
|
|
3234
|
+
} catch (error) {
|
|
3235
|
+
this.setActiveAliasMappings([]);
|
|
3236
|
+
throw error;
|
|
3237
|
+
}
|
|
3238
|
+
const completedMappings = this.filterCompletedMappings(aliasMappings, aliasResult, false);
|
|
3239
|
+
this.setActiveAliasMappings(completedMappings, aliasResult.failed ?? []);
|
|
2211
3240
|
if (!aliasResult.success) {
|
|
2212
|
-
|
|
3241
|
+
logger8.warn(`Some alias installations failed: ${aliasResult.errors.join(", ")}`);
|
|
2213
3242
|
}
|
|
2214
3243
|
if (this.hooks.onInstallComplete) {
|
|
2215
|
-
await this.hooks.onInstallComplete(
|
|
3244
|
+
await this.hooks.onInstallComplete(
|
|
3245
|
+
this.filterCompletedMappings(aliasMappings, aliasResult, true)
|
|
3246
|
+
);
|
|
2216
3247
|
}
|
|
2217
3248
|
}
|
|
3249
|
+
/**
|
|
3250
|
+
* Select only mappings whose installer outcome explicitly proved reuse or
|
|
3251
|
+
* installation. Hook callers retain the pre-Task-9 compatibility fallback
|
|
3252
|
+
* for old installer results that omitted `reused`.
|
|
3253
|
+
*/
|
|
3254
|
+
filterCompletedMappings(aliasMappings, aliasResult, allowLegacyReuse) {
|
|
3255
|
+
const failedAliases = new Set(aliasResult.failed ?? []);
|
|
3256
|
+
const successfulAliases = /* @__PURE__ */ new Set([
|
|
3257
|
+
...aliasResult.installed ?? [],
|
|
3258
|
+
...aliasResult.reused ?? []
|
|
3259
|
+
]);
|
|
3260
|
+
if (allowLegacyReuse && aliasResult.success !== false) {
|
|
3261
|
+
for (const mapping of aliasMappings) {
|
|
3262
|
+
if (mapping.installSpec === "" && !failedAliases.has(mapping.aliasName)) {
|
|
3263
|
+
successfulAliases.add(mapping.aliasName);
|
|
3264
|
+
}
|
|
3265
|
+
}
|
|
3266
|
+
}
|
|
3267
|
+
return aliasMappings.filter(
|
|
3268
|
+
(mapping) => successfulAliases.has(mapping.aliasName) && !failedAliases.has(mapping.aliasName)
|
|
3269
|
+
);
|
|
3270
|
+
}
|
|
3271
|
+
/**
|
|
3272
|
+
* Publish a new active mapping set while keeping the complete analysis
|
|
3273
|
+
* result available for diagnostics.
|
|
3274
|
+
*/
|
|
3275
|
+
setActiveAliasMappings(mappings, blockedAliasNames = []) {
|
|
3276
|
+
if (!this.aliasManager || !this.analysisResult) {
|
|
3277
|
+
return;
|
|
3278
|
+
}
|
|
3279
|
+
const activeAliasNames = new Set(mappings.map((mapping) => mapping.aliasName));
|
|
3280
|
+
const inactiveAliasNames = new Set(blockedAliasNames);
|
|
3281
|
+
for (const mapping of this.analysisResult.aliasMappings) {
|
|
3282
|
+
if (!activeAliasNames.has(mapping.aliasName)) {
|
|
3283
|
+
inactiveAliasNames.add(mapping.aliasName);
|
|
3284
|
+
}
|
|
3285
|
+
}
|
|
3286
|
+
const activeMappings = mappings.map((mapping) => {
|
|
3287
|
+
if (!mapping.importerPaths || inactiveAliasNames.size === 0) {
|
|
3288
|
+
return mapping;
|
|
3289
|
+
}
|
|
3290
|
+
return {
|
|
3291
|
+
...mapping,
|
|
3292
|
+
importerPaths: mapping.importerPaths.filter(
|
|
3293
|
+
(importerPath) => ![...inactiveAliasNames].some(
|
|
3294
|
+
(aliasName) => this.isAliasPackagePath(importerPath, aliasName)
|
|
3295
|
+
)
|
|
3296
|
+
)
|
|
3297
|
+
};
|
|
3298
|
+
});
|
|
3299
|
+
this.aliasManager.initFromAnalysisResult({
|
|
3300
|
+
...this.analysisResult,
|
|
3301
|
+
aliasMappings: activeMappings
|
|
3302
|
+
});
|
|
3303
|
+
}
|
|
3304
|
+
/**
|
|
3305
|
+
* Check whether an importer path belongs to an alias package directory.
|
|
3306
|
+
* Package paths can be nested under pnpm's virtual store, so matching the
|
|
3307
|
+
* `node_modules/<alias>` segment is more reliable than checking a basename.
|
|
3308
|
+
*/
|
|
3309
|
+
isAliasPackagePath(importerPath, aliasName) {
|
|
3310
|
+
const normalizedPath = importerPath.replace(/\\/g, "/").replace(/\/+$/, "");
|
|
3311
|
+
const marker = `node_modules/${aliasName}`;
|
|
3312
|
+
return normalizedPath === marker || normalizedPath.startsWith(`${marker}/`) || normalizedPath.endsWith(`/${marker}`) || normalizedPath.includes(`/${marker}/`);
|
|
3313
|
+
}
|
|
2218
3314
|
/**
|
|
2219
3315
|
* 解析模块请求
|
|
2220
3316
|
* @returns 解析后的模块名,如果不需要重定向则返回 null
|
|
2221
3317
|
*/
|
|
2222
3318
|
resolveModule(request, importer) {
|
|
3319
|
+
if (!this.initialized || !this.aliasManager) {
|
|
3320
|
+
return null;
|
|
3321
|
+
}
|
|
2223
3322
|
if (this.hooks.beforeResolve) {
|
|
2224
3323
|
const hookResult = this.hooks.beforeResolve(request, importer);
|
|
2225
3324
|
if (hookResult !== void 0) {
|
|
@@ -2233,6 +3332,9 @@ var DepsConflictResolver = class {
|
|
|
2233
3332
|
* 返回别名名称到实际路径的映射,供构建工具插件转换为各自的格式
|
|
2234
3333
|
*/
|
|
2235
3334
|
getAliasPathMappings() {
|
|
3335
|
+
if (!this.initialized || !this.aliasManager) {
|
|
3336
|
+
return [];
|
|
3337
|
+
}
|
|
2236
3338
|
return this.aliasManager.getAliasPathMappings();
|
|
2237
3339
|
}
|
|
2238
3340
|
/**
|