deps-conflict-resolver 1.2.0 → 1.3.0
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/README.en.md +12 -0
- package/README.md +12 -0
- package/dist/cli.cjs +4413 -0
- package/dist/cli.cjs.map +1 -0
- package/dist/cli.d.cts +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +4407 -0
- package/dist/cli.js.map +1 -0
- package/dist/{config.types-B44iN41C.d.cts → config.types-CVCkyLb5.d.cts} +1 -1
- package/dist/{config.types-B44iN41C.d.ts → config.types-CVCkyLb5.d.ts} +1 -1
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/{resolver-rN50QWL1.d.cts → resolver-BAIQL1Xf.d.cts} +1 -1
- package/dist/{resolver-7xnFE1PI.d.ts → resolver-DNFa0I8O.d.ts} +1 -1
- package/dist/vite.d.cts +1 -1
- package/dist/vite.d.ts +1 -1
- package/dist/webpack.d.cts +2 -2
- package/dist/webpack.d.ts +2 -2
- package/package.json +4 -1
package/dist/cli.cjs
ADDED
|
@@ -0,0 +1,4413 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
var path = require('path');
|
|
5
|
+
var fs = require('fs');
|
|
6
|
+
var module$1 = require('module');
|
|
7
|
+
var url = require('url');
|
|
8
|
+
var yaml = require('yaml');
|
|
9
|
+
var semver = require('semver');
|
|
10
|
+
var child_process = require('child_process');
|
|
11
|
+
var crypto = require('crypto');
|
|
12
|
+
var os = require('os');
|
|
13
|
+
var perf_hooks = require('perf_hooks');
|
|
14
|
+
|
|
15
|
+
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
16
|
+
|
|
17
|
+
var semver__default = /*#__PURE__*/_interopDefault(semver);
|
|
18
|
+
|
|
19
|
+
// src/constants.ts
|
|
20
|
+
var DEFAULT_NPM_REGISTRY = "https://registry.npmjs.org";
|
|
21
|
+
var LOCK_FILE_MAP = {
|
|
22
|
+
"pnpm-lock.yaml": "pnpm",
|
|
23
|
+
"yarn.lock": "yarn",
|
|
24
|
+
"package-lock.json": "npm",
|
|
25
|
+
"npm-shrinkwrap.json": "npm"
|
|
26
|
+
};
|
|
27
|
+
var DEFAULT_NPM_REGISTRY_TIMEOUT_MS = 1e4;
|
|
28
|
+
|
|
29
|
+
// src/utils/logger.ts
|
|
30
|
+
var DEFAULT_GLOBAL_LEVEL = 2 /* INFO */ | 4 /* WARN */ | 8 /* ERROR */;
|
|
31
|
+
var __GLOBAL_LEVEL__ = DEFAULT_GLOBAL_LEVEL;
|
|
32
|
+
var Logger = class {
|
|
33
|
+
prefix;
|
|
34
|
+
levelOverride;
|
|
35
|
+
constructor(config = {}) {
|
|
36
|
+
this.prefix = config.prefix ?? "[deps-conflict-resolver]";
|
|
37
|
+
this.levelOverride = config.level;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* 设置日志级别
|
|
41
|
+
*/
|
|
42
|
+
setLevel(level) {
|
|
43
|
+
__GLOBAL_LEVEL__ = level;
|
|
44
|
+
this.levelOverride = void 0;
|
|
45
|
+
}
|
|
46
|
+
getEffectiveLevel() {
|
|
47
|
+
return this.levelOverride ?? __GLOBAL_LEVEL__;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* 调试日志
|
|
51
|
+
*/
|
|
52
|
+
debug(...args) {
|
|
53
|
+
if (this.getEffectiveLevel() & 1 /* DEBUG */) {
|
|
54
|
+
console.debug(this.formatPrefix("DEBUG"), ...args);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* 信息日志
|
|
59
|
+
*/
|
|
60
|
+
info(...args) {
|
|
61
|
+
if (this.getEffectiveLevel() & 2 /* INFO */) {
|
|
62
|
+
console.info(this.formatPrefix("INFO"), ...args);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* 警告日志
|
|
67
|
+
*/
|
|
68
|
+
warn(...args) {
|
|
69
|
+
if (this.getEffectiveLevel() & 4 /* WARN */) {
|
|
70
|
+
console.warn(this.formatPrefix("WARN"), ...args);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* 错误日志
|
|
75
|
+
*/
|
|
76
|
+
error(...args) {
|
|
77
|
+
if (this.getEffectiveLevel() & 8 /* ERROR */) {
|
|
78
|
+
console.error(this.formatPrefix("ERROR"), ...args);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* 格式化前缀
|
|
83
|
+
*/
|
|
84
|
+
formatPrefix(level) {
|
|
85
|
+
return `${this.prefix} [${level}]`;
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
function createLogger(subPrefix, debug = false) {
|
|
89
|
+
return new Logger({
|
|
90
|
+
prefix: `[deps-conflict-resolver:${subPrefix}]`,
|
|
91
|
+
// debug=true 时强制当前 logger 输出所有日志;否则使用全局级别(默认 INFO/WARN/ERROR)
|
|
92
|
+
level: debug ? 15 /* ALL */ : void 0
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// src/utils/lru-cache.ts
|
|
97
|
+
var LruCache = class {
|
|
98
|
+
map = /* @__PURE__ */ new Map();
|
|
99
|
+
maxEntries;
|
|
100
|
+
constructor(options) {
|
|
101
|
+
this.maxEntries = options.maxEntries;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* 当前缓存条目数
|
|
105
|
+
*/
|
|
106
|
+
get size() {
|
|
107
|
+
return this.map.size;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* 获取最大条目数
|
|
111
|
+
*/
|
|
112
|
+
getMaxEntries() {
|
|
113
|
+
return this.maxEntries;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* 动态调整最大条目数
|
|
117
|
+
* - 调小会立即触发淘汰
|
|
118
|
+
*/
|
|
119
|
+
setMaxEntries(maxEntries) {
|
|
120
|
+
this.maxEntries = maxEntries;
|
|
121
|
+
if (this.maxEntries <= 0) {
|
|
122
|
+
this.map.clear();
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
this.trim();
|
|
126
|
+
}
|
|
127
|
+
clear() {
|
|
128
|
+
this.map.clear();
|
|
129
|
+
}
|
|
130
|
+
has(key) {
|
|
131
|
+
return this.map.has(key);
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* 获取并刷新 LRU 顺序(命中后会变成“最近使用”)
|
|
135
|
+
*/
|
|
136
|
+
get(key) {
|
|
137
|
+
if (this.maxEntries <= 0) {
|
|
138
|
+
return void 0;
|
|
139
|
+
}
|
|
140
|
+
if (!this.map.has(key)) {
|
|
141
|
+
return void 0;
|
|
142
|
+
}
|
|
143
|
+
const value = this.map.get(key);
|
|
144
|
+
this.map.delete(key);
|
|
145
|
+
this.map.set(key, value);
|
|
146
|
+
return value;
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* 写入并刷新 LRU 顺序
|
|
150
|
+
*/
|
|
151
|
+
set(key, value) {
|
|
152
|
+
if (this.maxEntries <= 0) {
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
if (this.map.has(key)) {
|
|
156
|
+
this.map.delete(key);
|
|
157
|
+
}
|
|
158
|
+
this.map.set(key, value);
|
|
159
|
+
this.trim();
|
|
160
|
+
}
|
|
161
|
+
delete(key) {
|
|
162
|
+
return this.map.delete(key);
|
|
163
|
+
}
|
|
164
|
+
trim() {
|
|
165
|
+
if (this.maxEntries <= 0) return;
|
|
166
|
+
while (this.map.size > this.maxEntries) {
|
|
167
|
+
const iter = this.map.keys().next();
|
|
168
|
+
if (iter.done) break;
|
|
169
|
+
this.map.delete(iter.value);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
// src/utils/fs.ts
|
|
175
|
+
function* iterateParentDirs(startDir) {
|
|
176
|
+
let currentDir = startDir;
|
|
177
|
+
while (true) {
|
|
178
|
+
yield currentDir;
|
|
179
|
+
const parentDir = path.dirname(currentDir);
|
|
180
|
+
if (parentDir === currentDir) {
|
|
181
|
+
break;
|
|
182
|
+
}
|
|
183
|
+
currentDir = parentDir;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
var DEFAULT_PACKAGE_JSON_CACHE_MAX_ENTRIES = 5e3;
|
|
187
|
+
var packageJsonCache = new LruCache({
|
|
188
|
+
maxEntries: DEFAULT_PACKAGE_JSON_CACHE_MAX_ENTRIES
|
|
189
|
+
});
|
|
190
|
+
var DEFAULT_REQUIRE_CACHE_MAX_ENTRIES = 200;
|
|
191
|
+
var requireCache = new LruCache({
|
|
192
|
+
maxEntries: DEFAULT_REQUIRE_CACHE_MAX_ENTRIES
|
|
193
|
+
});
|
|
194
|
+
var DEFAULT_PACKAGE_PATH_CACHE_MAX_ENTRIES = 2e4;
|
|
195
|
+
var packagePathCache = new LruCache({
|
|
196
|
+
maxEntries: DEFAULT_PACKAGE_PATH_CACHE_MAX_ENTRIES
|
|
197
|
+
});
|
|
198
|
+
function clearPackageJsonCache() {
|
|
199
|
+
packageJsonCache.clear();
|
|
200
|
+
packagePathCache.clear();
|
|
201
|
+
requireCache.clear();
|
|
202
|
+
}
|
|
203
|
+
function readJsonFileSync(filePath) {
|
|
204
|
+
try {
|
|
205
|
+
const content = fs.readFileSync(filePath, "utf-8");
|
|
206
|
+
return JSON.parse(content);
|
|
207
|
+
} catch {
|
|
208
|
+
return null;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
function fileExists(filePath) {
|
|
212
|
+
return fs.existsSync(filePath);
|
|
213
|
+
}
|
|
214
|
+
function readPackageJsonCached(dir) {
|
|
215
|
+
const pkgPath = path.join(dir, "package.json");
|
|
216
|
+
const cached = packageJsonCache.get(pkgPath);
|
|
217
|
+
if (cached !== void 0) {
|
|
218
|
+
return cached;
|
|
219
|
+
}
|
|
220
|
+
const result = readJsonFileSync(pkgPath);
|
|
221
|
+
packageJsonCache.set(pkgPath, result);
|
|
222
|
+
return result;
|
|
223
|
+
}
|
|
224
|
+
function findProjectRoot(startDir) {
|
|
225
|
+
for (const dir of iterateParentDirs(startDir)) {
|
|
226
|
+
if (fileExists(path.join(dir, "package.json"))) {
|
|
227
|
+
return dir;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
return null;
|
|
231
|
+
}
|
|
232
|
+
function findPackagePath(packageName, baseDir) {
|
|
233
|
+
const cacheKey = `${baseDir}\0${packageName}`;
|
|
234
|
+
const cached = packagePathCache.get(cacheKey);
|
|
235
|
+
if (cached !== void 0) {
|
|
236
|
+
return cached;
|
|
237
|
+
}
|
|
238
|
+
try {
|
|
239
|
+
let localRequire = requireCache.get(baseDir);
|
|
240
|
+
if (!localRequire) {
|
|
241
|
+
const baseUrl = url.pathToFileURL(path.join(baseDir, "package.json")).href;
|
|
242
|
+
localRequire = module$1.createRequire(baseUrl);
|
|
243
|
+
requireCache.set(baseDir, localRequire);
|
|
244
|
+
}
|
|
245
|
+
const metadataRequest = `${packageName}/package.json`;
|
|
246
|
+
const lookupPaths = localRequire.resolve.paths?.(metadataRequest);
|
|
247
|
+
if (lookupPaths) {
|
|
248
|
+
let visible = findSelfPackagePath(packageName, baseDir);
|
|
249
|
+
if (!visible) {
|
|
250
|
+
for (const directory of lookupPaths) {
|
|
251
|
+
const candidate = path.join(directory, packageName);
|
|
252
|
+
if (fileExists(candidate)) {
|
|
253
|
+
visible = candidate;
|
|
254
|
+
break;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
let resolved2 = visible;
|
|
259
|
+
if (visible) {
|
|
260
|
+
try {
|
|
261
|
+
resolved2 = fs.realpathSync(visible);
|
|
262
|
+
} catch {
|
|
263
|
+
resolved2 = path.resolve(visible);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
packagePathCache.set(cacheKey, resolved2);
|
|
267
|
+
return resolved2;
|
|
268
|
+
}
|
|
269
|
+
const pkgJsonPath = localRequire.resolve(metadataRequest);
|
|
270
|
+
const resolved = path.dirname(pkgJsonPath);
|
|
271
|
+
packagePathCache.set(cacheKey, resolved);
|
|
272
|
+
return resolved;
|
|
273
|
+
} catch {
|
|
274
|
+
const resolved = findPackagePathFallback(packageName, baseDir);
|
|
275
|
+
packagePathCache.set(cacheKey, resolved);
|
|
276
|
+
return resolved;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
function findSelfPackagePath(packageName, baseDir) {
|
|
280
|
+
for (const directory of iterateParentDirs(path.resolve(baseDir))) {
|
|
281
|
+
if (path.basename(directory) === "node_modules") break;
|
|
282
|
+
const manifest = readPackageJsonCached(directory);
|
|
283
|
+
if (!manifest) continue;
|
|
284
|
+
return manifest.name === packageName && "exports" in manifest && manifest.exports != null ? directory : null;
|
|
285
|
+
}
|
|
286
|
+
return null;
|
|
287
|
+
}
|
|
288
|
+
function findPackagePathFallback(packageName, baseDir) {
|
|
289
|
+
for (const dir of iterateParentDirs(baseDir)) {
|
|
290
|
+
const candidatePath = path.join(dir, "node_modules", packageName);
|
|
291
|
+
if (fileExists(candidatePath)) {
|
|
292
|
+
return candidatePath;
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
return null;
|
|
296
|
+
}
|
|
297
|
+
var logger = createLogger("environment-detector");
|
|
298
|
+
var EnvironmentDetector = class {
|
|
299
|
+
projectRoot;
|
|
300
|
+
detectionResult = null;
|
|
301
|
+
registryCache = null;
|
|
302
|
+
constructor(projectRoot) {
|
|
303
|
+
this.projectRoot = projectRoot;
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* 获取检测到的包管理器类型
|
|
307
|
+
*/
|
|
308
|
+
getPackageManager() {
|
|
309
|
+
const result = this.detect();
|
|
310
|
+
return result.packageManager;
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* 获取检测到的 registry
|
|
314
|
+
*/
|
|
315
|
+
async getRegistry() {
|
|
316
|
+
if (this.registryCache) {
|
|
317
|
+
return this.registryCache;
|
|
318
|
+
}
|
|
319
|
+
const result = this.detect();
|
|
320
|
+
this.registryCache = await this.detectRegistry(result.packageManager);
|
|
321
|
+
return this.registryCache;
|
|
322
|
+
}
|
|
323
|
+
/**
|
|
324
|
+
* 获取指定包管理器的 registry(兼容旧 API)
|
|
325
|
+
*/
|
|
326
|
+
async getRegistryForPackageManager(packageManager) {
|
|
327
|
+
return this.detectRegistry(packageManager);
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* 获取完整的检测结果
|
|
331
|
+
*/
|
|
332
|
+
getDetectionResult() {
|
|
333
|
+
return this.detect();
|
|
334
|
+
}
|
|
335
|
+
/**
|
|
336
|
+
* 重置缓存,强制重新检测
|
|
337
|
+
*/
|
|
338
|
+
reset() {
|
|
339
|
+
this.detectionResult = null;
|
|
340
|
+
this.registryCache = null;
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* 更新项目根目录
|
|
344
|
+
*/
|
|
345
|
+
setProjectRoot(projectRoot) {
|
|
346
|
+
this.projectRoot = projectRoot;
|
|
347
|
+
this.reset();
|
|
348
|
+
}
|
|
349
|
+
/**
|
|
350
|
+
* 检测项目使用的包管理器
|
|
351
|
+
*
|
|
352
|
+
* 检测优先级:
|
|
353
|
+
* 1. package.json 中的 packageManager 字段(如 "pnpm@8.0.0")- 向上遍历查找
|
|
354
|
+
* 2. lock 文件存在 - 向上遍历查找(支持 monorepo)
|
|
355
|
+
* 3. 默认为 npm
|
|
356
|
+
*/
|
|
357
|
+
detect() {
|
|
358
|
+
if (this.detectionResult) {
|
|
359
|
+
return this.detectionResult;
|
|
360
|
+
}
|
|
361
|
+
for (const currentDir of iterateParentDirs(this.projectRoot)) {
|
|
362
|
+
const pkgJsonPath = path.join(currentDir, "package.json");
|
|
363
|
+
if (fileExists(pkgJsonPath)) {
|
|
364
|
+
const pkgJson = readPackageJsonCached(currentDir);
|
|
365
|
+
const pmField = pkgJson?.packageManager;
|
|
366
|
+
if (pmField) {
|
|
367
|
+
const pm = this.parsePackageManagerField(pmField);
|
|
368
|
+
if (pm) {
|
|
369
|
+
logger.debug(`Detected package manager from package.json: ${pm} (at ${currentDir})`);
|
|
370
|
+
this.detectionResult = {
|
|
371
|
+
packageManager: pm,
|
|
372
|
+
detectedFrom: "packageJson",
|
|
373
|
+
rootDir: currentDir
|
|
374
|
+
};
|
|
375
|
+
return this.detectionResult;
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
for (const [lockFile, pm] of Object.entries(LOCK_FILE_MAP)) {
|
|
380
|
+
if (fileExists(path.join(currentDir, lockFile))) {
|
|
381
|
+
logger.debug(
|
|
382
|
+
`Detected package manager from lock file: ${pm} (${lockFile} at ${currentDir})`
|
|
383
|
+
);
|
|
384
|
+
this.detectionResult = {
|
|
385
|
+
packageManager: pm,
|
|
386
|
+
detectedFrom: "lockfile",
|
|
387
|
+
rootDir: currentDir
|
|
388
|
+
};
|
|
389
|
+
return this.detectionResult;
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
logger.debug("No lock file found, defaulting to npm");
|
|
394
|
+
this.detectionResult = {
|
|
395
|
+
packageManager: "npm",
|
|
396
|
+
detectedFrom: "default"
|
|
397
|
+
};
|
|
398
|
+
return this.detectionResult;
|
|
399
|
+
}
|
|
400
|
+
/**
|
|
401
|
+
* 解析 package.json 中的 packageManager 字段
|
|
402
|
+
* 格式如:pnpm@8.0.0, yarn@3.2.0, npm@9.0.0
|
|
403
|
+
*/
|
|
404
|
+
parsePackageManagerField(value) {
|
|
405
|
+
const match = value.match(/^(npm|yarn|pnpm)(@|$)/);
|
|
406
|
+
if (match) {
|
|
407
|
+
return match[1];
|
|
408
|
+
}
|
|
409
|
+
return null;
|
|
410
|
+
}
|
|
411
|
+
/**
|
|
412
|
+
* 检测项目使用的 registry
|
|
413
|
+
*
|
|
414
|
+
* 检测优先级:
|
|
415
|
+
* 1. 项目级 .npmrc(向上遍历,覆盖 monorepo 子包场景)
|
|
416
|
+
* 2. 用户级 .npmrc
|
|
417
|
+
* 3. 包管理器特定配置
|
|
418
|
+
* 4. 默认 registry
|
|
419
|
+
*/
|
|
420
|
+
async detectRegistry(packageManager) {
|
|
421
|
+
const defaultRegistry = DEFAULT_NPM_REGISTRY;
|
|
422
|
+
for (const dir of iterateParentDirs(this.projectRoot)) {
|
|
423
|
+
const npmrcPath = path.join(dir, ".npmrc");
|
|
424
|
+
if (fileExists(npmrcPath)) {
|
|
425
|
+
const registry2 = await this.parseRegistryFromNpmrc(npmrcPath);
|
|
426
|
+
if (registry2) {
|
|
427
|
+
logger.debug(`Detected registry from .npmrc: ${registry2} (at ${dir})`);
|
|
428
|
+
return registry2;
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
const homeDir = process.env.HOME ?? process.env.USERPROFILE ?? "";
|
|
433
|
+
if (homeDir) {
|
|
434
|
+
const userNpmrc = path.join(homeDir, ".npmrc");
|
|
435
|
+
if (fileExists(userNpmrc)) {
|
|
436
|
+
const registry2 = await this.parseRegistryFromNpmrc(userNpmrc);
|
|
437
|
+
if (registry2) {
|
|
438
|
+
logger.debug(`Detected registry from user .npmrc: ${registry2}`);
|
|
439
|
+
return registry2;
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
if (packageManager === "pnpm") {
|
|
443
|
+
const pnpmConfig = path.join(homeDir, ".pnpmrc");
|
|
444
|
+
if (fileExists(pnpmConfig)) {
|
|
445
|
+
const registry2 = await this.parseRegistryFromNpmrc(pnpmConfig);
|
|
446
|
+
if (registry2) {
|
|
447
|
+
logger.debug(`Detected registry from .pnpmrc: ${registry2}`);
|
|
448
|
+
return registry2;
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
if (packageManager === "yarn") {
|
|
453
|
+
for (const dir of iterateParentDirs(this.projectRoot)) {
|
|
454
|
+
const yarnrc = path.join(dir, ".yarnrc.yml");
|
|
455
|
+
if (fileExists(yarnrc)) {
|
|
456
|
+
const registry2 = await this.parseRegistryFromYarnrc(yarnrc);
|
|
457
|
+
if (registry2) {
|
|
458
|
+
logger.debug(`Detected registry from .yarnrc.yml: ${registry2} (at ${dir})`);
|
|
459
|
+
return registry2;
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
logger.debug(`Using default registry: ${defaultRegistry}`);
|
|
466
|
+
return defaultRegistry;
|
|
467
|
+
}
|
|
468
|
+
/**
|
|
469
|
+
* 从 .npmrc 文件解析 registry
|
|
470
|
+
*/
|
|
471
|
+
async parseRegistryFromNpmrc(filePath) {
|
|
472
|
+
try {
|
|
473
|
+
const content = await fs.promises.readFile(filePath, "utf-8");
|
|
474
|
+
const lines = content.split("\n");
|
|
475
|
+
for (const line of lines) {
|
|
476
|
+
const trimmed = line.trim();
|
|
477
|
+
if (!trimmed || trimmed.startsWith("#") || trimmed.startsWith(";")) {
|
|
478
|
+
continue;
|
|
479
|
+
}
|
|
480
|
+
const match = trimmed.match(/^registry\s*=\s*(.+)$/i);
|
|
481
|
+
if (match?.[1]) {
|
|
482
|
+
return match[1].trim().replace(/["']/g, "");
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
} catch {
|
|
486
|
+
}
|
|
487
|
+
return null;
|
|
488
|
+
}
|
|
489
|
+
/**
|
|
490
|
+
* 从 .yarnrc.yml 文件解析 registry
|
|
491
|
+
*/
|
|
492
|
+
async parseRegistryFromYarnrc(filePath) {
|
|
493
|
+
try {
|
|
494
|
+
const content = await fs.promises.readFile(filePath, "utf-8");
|
|
495
|
+
const lines = content.split("\n");
|
|
496
|
+
for (const line of lines) {
|
|
497
|
+
const trimmed = line.trim();
|
|
498
|
+
const match = trimmed.match(/^npmRegistryServer:\s*["']?(.+?)["']?\s*$/);
|
|
499
|
+
if (match?.[1]) {
|
|
500
|
+
return match[1];
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
} catch {
|
|
504
|
+
}
|
|
505
|
+
return null;
|
|
506
|
+
}
|
|
507
|
+
};
|
|
508
|
+
function createEnvironmentDetector(projectRoot) {
|
|
509
|
+
return new EnvironmentDetector(projectRoot);
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
// src/utils/version-spec.ts
|
|
513
|
+
var NPM_ALIAS_PATTERN = /^npm:(@?[^@]+)@(.+)$/;
|
|
514
|
+
function parseNpmAlias(versionSpec) {
|
|
515
|
+
const match = versionSpec.match(NPM_ALIAS_PATTERN);
|
|
516
|
+
if (match?.[1] && match?.[2]) {
|
|
517
|
+
return [match[1], match[2]];
|
|
518
|
+
}
|
|
519
|
+
return null;
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
// src/core/workspace-detector.ts
|
|
523
|
+
var logger2 = createLogger("workspace-detector");
|
|
524
|
+
var PROTOCOL_PREFIXES = {
|
|
525
|
+
"catalog:": "catalog",
|
|
526
|
+
"workspace:": "workspace",
|
|
527
|
+
"npm:": "npm",
|
|
528
|
+
"file:": "file",
|
|
529
|
+
"link:": "link",
|
|
530
|
+
"portal:": "portal"
|
|
531
|
+
};
|
|
532
|
+
function extractAliasesFromDeps(deps, targetPackage, definedIn, existingAliases) {
|
|
533
|
+
if (!deps) return [];
|
|
534
|
+
const aliases = [];
|
|
535
|
+
for (const [aliasName, versionSpec] of Object.entries(deps)) {
|
|
536
|
+
if (typeof versionSpec !== "string") continue;
|
|
537
|
+
if (existingAliases.has(aliasName)) continue;
|
|
538
|
+
const parsed = parseNpmAlias(versionSpec);
|
|
539
|
+
if (parsed?.[0] === targetPackage) {
|
|
540
|
+
aliases.push({
|
|
541
|
+
aliasName,
|
|
542
|
+
targetPackage,
|
|
543
|
+
versionSpec: parsed[1],
|
|
544
|
+
definedIn,
|
|
545
|
+
isWorkspaceRoot: true
|
|
546
|
+
});
|
|
547
|
+
existingAliases.add(aliasName);
|
|
548
|
+
logger2.debug(`Found alias: ${aliasName} -> ${targetPackage}@${parsed[1]} (in ${definedIn})`);
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
return aliases;
|
|
552
|
+
}
|
|
553
|
+
var WorkspaceDetector = class {
|
|
554
|
+
projectRoot;
|
|
555
|
+
detectionResult = null;
|
|
556
|
+
constructor(projectRoot) {
|
|
557
|
+
this.projectRoot = projectRoot;
|
|
558
|
+
}
|
|
559
|
+
/**
|
|
560
|
+
* 获取 workspace 检测结果
|
|
561
|
+
*/
|
|
562
|
+
detect() {
|
|
563
|
+
if (this.detectionResult) {
|
|
564
|
+
return this.detectionResult;
|
|
565
|
+
}
|
|
566
|
+
this.detectionResult = this.detectWorkspace();
|
|
567
|
+
return this.detectionResult;
|
|
568
|
+
}
|
|
569
|
+
/**
|
|
570
|
+
* 重置缓存
|
|
571
|
+
*/
|
|
572
|
+
reset() {
|
|
573
|
+
this.detectionResult = null;
|
|
574
|
+
}
|
|
575
|
+
/**
|
|
576
|
+
* 解析 catalog: 协议的版本
|
|
577
|
+
* @param packageName 包名
|
|
578
|
+
* @param versionSpec 版本规格(如 "catalog:" 或 "catalog:react17")
|
|
579
|
+
*/
|
|
580
|
+
resolveCatalogVersion(packageName, versionSpec) {
|
|
581
|
+
const result = {
|
|
582
|
+
original: versionSpec,
|
|
583
|
+
resolved: null,
|
|
584
|
+
catalogName: "default",
|
|
585
|
+
success: false
|
|
586
|
+
};
|
|
587
|
+
if (versionSpec === "catalog:" || versionSpec === "catalog:default") {
|
|
588
|
+
result.catalogName = "default";
|
|
589
|
+
} else if (versionSpec.startsWith("catalog:")) {
|
|
590
|
+
result.catalogName = versionSpec.slice("catalog:".length);
|
|
591
|
+
} else {
|
|
592
|
+
return result;
|
|
593
|
+
}
|
|
594
|
+
const workspace = this.detect();
|
|
595
|
+
if (!workspace.isMonorepo || !workspace.workspaceRoot) {
|
|
596
|
+
logger2.warn(`Cannot resolve catalog: protocol - not in a monorepo`);
|
|
597
|
+
return result;
|
|
598
|
+
}
|
|
599
|
+
if (result.catalogName === "default") {
|
|
600
|
+
const version = workspace.catalog?.[packageName];
|
|
601
|
+
if (version) {
|
|
602
|
+
result.resolved = version;
|
|
603
|
+
result.success = true;
|
|
604
|
+
logger2.debug(`Resolved ${packageName} from default catalog: ${version}`);
|
|
605
|
+
}
|
|
606
|
+
} else {
|
|
607
|
+
const namedCatalog = workspace.catalogs?.[result.catalogName];
|
|
608
|
+
if (namedCatalog) {
|
|
609
|
+
const version = namedCatalog[packageName];
|
|
610
|
+
if (version) {
|
|
611
|
+
result.resolved = version;
|
|
612
|
+
result.success = true;
|
|
613
|
+
logger2.debug(`Resolved ${packageName} from catalog:${result.catalogName}: ${version}`);
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
if (!result.success) {
|
|
618
|
+
logger2.warn(`Package "${packageName}" not found in catalog:${result.catalogName}`);
|
|
619
|
+
}
|
|
620
|
+
return result;
|
|
621
|
+
}
|
|
622
|
+
/**
|
|
623
|
+
* 解析版本规格(支持各种特殊协议)
|
|
624
|
+
* @param packageName 包名
|
|
625
|
+
* @param versionSpec 版本规格
|
|
626
|
+
* @returns 解析后的普通版本范围,或 null(如无法解析)
|
|
627
|
+
*/
|
|
628
|
+
resolveVersionSpec(packageName, versionSpec) {
|
|
629
|
+
const protocol = this.getVersionProtocol(versionSpec);
|
|
630
|
+
switch (protocol) {
|
|
631
|
+
case "catalog": {
|
|
632
|
+
const resolution = this.resolveCatalogVersion(packageName, versionSpec);
|
|
633
|
+
return resolution.resolved;
|
|
634
|
+
}
|
|
635
|
+
case "workspace":
|
|
636
|
+
case "file":
|
|
637
|
+
case "link":
|
|
638
|
+
case "portal":
|
|
639
|
+
return "*";
|
|
640
|
+
case "npm": {
|
|
641
|
+
const parsed = parseNpmAlias(versionSpec);
|
|
642
|
+
return parsed?.[1] ?? null;
|
|
643
|
+
}
|
|
644
|
+
default:
|
|
645
|
+
return versionSpec;
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
/**
|
|
649
|
+
* 判断版本规格的协议类型
|
|
650
|
+
*/
|
|
651
|
+
getVersionProtocol(versionSpec) {
|
|
652
|
+
for (const [prefix, protocol] of Object.entries(PROTOCOL_PREFIXES)) {
|
|
653
|
+
if (versionSpec.startsWith(prefix)) {
|
|
654
|
+
return protocol;
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
return "normal";
|
|
658
|
+
}
|
|
659
|
+
/**
|
|
660
|
+
* 从 workspace 根目录和 catalog 中查找已存在的别名
|
|
661
|
+
*/
|
|
662
|
+
findWorkspaceAliases(targetPackage) {
|
|
663
|
+
const workspace = this.detect();
|
|
664
|
+
if (!workspace.isMonorepo || !workspace.workspaceRoot) {
|
|
665
|
+
return [];
|
|
666
|
+
}
|
|
667
|
+
const existingAliases = /* @__PURE__ */ new Set();
|
|
668
|
+
const aliases = [];
|
|
669
|
+
const catalogPath = path.join(workspace.workspaceRoot, "pnpm-workspace.yaml");
|
|
670
|
+
if (workspace.workspaceType === "pnpm") {
|
|
671
|
+
aliases.push(
|
|
672
|
+
...extractAliasesFromDeps(workspace.catalog, targetPackage, catalogPath, existingAliases)
|
|
673
|
+
);
|
|
674
|
+
if (workspace.catalogs) {
|
|
675
|
+
for (const catalog of Object.values(workspace.catalogs)) {
|
|
676
|
+
aliases.push(
|
|
677
|
+
...extractAliasesFromDeps(catalog, targetPackage, catalogPath, existingAliases)
|
|
678
|
+
);
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
const rootPkgPath = path.join(workspace.workspaceRoot, "package.json");
|
|
683
|
+
const rootPkgJson = readPackageJsonCached(workspace.workspaceRoot);
|
|
684
|
+
if (rootPkgJson) {
|
|
685
|
+
aliases.push(
|
|
686
|
+
...extractAliasesFromDeps(
|
|
687
|
+
{ ...rootPkgJson.dependencies, ...rootPkgJson.optionalDependencies },
|
|
688
|
+
targetPackage,
|
|
689
|
+
rootPkgPath,
|
|
690
|
+
existingAliases
|
|
691
|
+
),
|
|
692
|
+
...extractAliasesFromDeps(
|
|
693
|
+
rootPkgJson.devDependencies,
|
|
694
|
+
targetPackage,
|
|
695
|
+
rootPkgPath,
|
|
696
|
+
existingAliases
|
|
697
|
+
)
|
|
698
|
+
);
|
|
699
|
+
}
|
|
700
|
+
return aliases;
|
|
701
|
+
}
|
|
702
|
+
/**
|
|
703
|
+
* 获取 workspace 根目录
|
|
704
|
+
*/
|
|
705
|
+
getWorkspaceRoot() {
|
|
706
|
+
const result = this.detect();
|
|
707
|
+
return result.workspaceRoot;
|
|
708
|
+
}
|
|
709
|
+
/**
|
|
710
|
+
* 检测 workspace
|
|
711
|
+
*/
|
|
712
|
+
detectWorkspace() {
|
|
713
|
+
for (const dir of iterateParentDirs(this.projectRoot)) {
|
|
714
|
+
const result = this.tryDetectWorkspaceAt(dir);
|
|
715
|
+
if (result) {
|
|
716
|
+
return result;
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
return {
|
|
720
|
+
isMonorepo: false,
|
|
721
|
+
workspaceRoot: null,
|
|
722
|
+
workspaceType: "none"
|
|
723
|
+
};
|
|
724
|
+
}
|
|
725
|
+
/**
|
|
726
|
+
* 尝试在指定目录检测 workspace
|
|
727
|
+
*/
|
|
728
|
+
tryDetectWorkspaceAt(dir) {
|
|
729
|
+
const pnpmWorkspacePath = path.join(dir, "pnpm-workspace.yaml");
|
|
730
|
+
if (fileExists(pnpmWorkspacePath)) {
|
|
731
|
+
const config = this.parsePnpmWorkspaceYaml(pnpmWorkspacePath);
|
|
732
|
+
logger2.debug(`Detected pnpm workspace at: ${dir}`);
|
|
733
|
+
return {
|
|
734
|
+
isMonorepo: true,
|
|
735
|
+
workspaceRoot: dir,
|
|
736
|
+
currentProjectPath: path.relative(dir, this.projectRoot) || ".",
|
|
737
|
+
workspaceType: "pnpm",
|
|
738
|
+
catalog: config.catalog,
|
|
739
|
+
catalogs: config.catalogs
|
|
740
|
+
};
|
|
741
|
+
}
|
|
742
|
+
const pkgJson = readPackageJsonCached(dir);
|
|
743
|
+
if (pkgJson?.workspaces) {
|
|
744
|
+
const isYarn = fileExists(path.join(dir, "yarn.lock"));
|
|
745
|
+
const workspaceType = isYarn ? "yarn" : "npm";
|
|
746
|
+
logger2.debug(`Detected ${workspaceType} workspace at: ${dir}`);
|
|
747
|
+
return {
|
|
748
|
+
isMonorepo: true,
|
|
749
|
+
workspaceRoot: dir,
|
|
750
|
+
currentProjectPath: path.relative(dir, this.projectRoot) || ".",
|
|
751
|
+
workspaceType
|
|
752
|
+
};
|
|
753
|
+
}
|
|
754
|
+
if (fileExists(path.join(dir, "lerna.json"))) {
|
|
755
|
+
logger2.debug(`Detected lerna workspace at: ${dir}`);
|
|
756
|
+
return {
|
|
757
|
+
isMonorepo: true,
|
|
758
|
+
workspaceRoot: dir,
|
|
759
|
+
currentProjectPath: path.relative(dir, this.projectRoot) || ".",
|
|
760
|
+
workspaceType: "lerna"
|
|
761
|
+
};
|
|
762
|
+
}
|
|
763
|
+
return null;
|
|
764
|
+
}
|
|
765
|
+
/**
|
|
766
|
+
* 解析 pnpm-workspace.yaml
|
|
767
|
+
*/
|
|
768
|
+
parsePnpmWorkspaceYaml(filePath) {
|
|
769
|
+
try {
|
|
770
|
+
const content = fs.readFileSync(filePath, "utf-8");
|
|
771
|
+
const parsed = yaml.parse(content);
|
|
772
|
+
return parsed ?? {};
|
|
773
|
+
} catch (error) {
|
|
774
|
+
logger2.warn(`Failed to parse pnpm-workspace.yaml: ${String(error)}`);
|
|
775
|
+
return {};
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
};
|
|
779
|
+
function createWorkspaceDetector(projectRoot) {
|
|
780
|
+
return new WorkspaceDetector(projectRoot);
|
|
781
|
+
}
|
|
782
|
+
function satisfies(version, range) {
|
|
783
|
+
try {
|
|
784
|
+
return semver__default.default.satisfies(version, range, { includePrerelease: false });
|
|
785
|
+
} catch {
|
|
786
|
+
return false;
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
function compare(v1, v2) {
|
|
790
|
+
try {
|
|
791
|
+
return semver__default.default.compare(v1, v2);
|
|
792
|
+
} catch {
|
|
793
|
+
return 0;
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
function findIntersection(versions, ranges) {
|
|
797
|
+
if (ranges.length === 0) return versions;
|
|
798
|
+
return versions.filter((version) => {
|
|
799
|
+
return ranges.every((range) => satisfies(version, range));
|
|
800
|
+
});
|
|
801
|
+
}
|
|
802
|
+
function findBestVersion(versions, ranges) {
|
|
803
|
+
const satisfyingVersions = findIntersection(versions, ranges);
|
|
804
|
+
if (satisfyingVersions.length === 0) {
|
|
805
|
+
return null;
|
|
806
|
+
}
|
|
807
|
+
let best = satisfyingVersions[0];
|
|
808
|
+
for (let i = 1; i < satisfyingVersions.length; i++) {
|
|
809
|
+
if (compare(satisfyingVersions[i], best) > 0) {
|
|
810
|
+
best = satisfyingVersions[i];
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
return best;
|
|
814
|
+
}
|
|
815
|
+
function createAliasInstallSpec(alias, packageName, version) {
|
|
816
|
+
return `${alias}@npm:${packageName}@${version}`;
|
|
817
|
+
}
|
|
818
|
+
function generateAliasName(packageName, version) {
|
|
819
|
+
let major;
|
|
820
|
+
try {
|
|
821
|
+
major = semver__default.default.major(version);
|
|
822
|
+
} catch {
|
|
823
|
+
const m = version.match(/^(\d+)/);
|
|
824
|
+
major = m ? Number(m[1]) : 0;
|
|
825
|
+
}
|
|
826
|
+
const cleanName = packageName.replace(/^@/, "").replace(/\//g, "-");
|
|
827
|
+
return `${cleanName}${major}`;
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
// src/core/registry-client.ts
|
|
831
|
+
var logger3 = createLogger("npm-registry");
|
|
832
|
+
var packageCache = /* @__PURE__ */ new Map();
|
|
833
|
+
var manifestCache = new LruCache({ maxEntries: 200 });
|
|
834
|
+
function clearNpmRegistryCache() {
|
|
835
|
+
packageCache.clear();
|
|
836
|
+
manifestCache.clear();
|
|
837
|
+
}
|
|
838
|
+
async function fetchWithTimeout(url, options = {}, consumeResponse, timeout = DEFAULT_NPM_REGISTRY_TIMEOUT_MS) {
|
|
839
|
+
const controller = new AbortController();
|
|
840
|
+
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
|
841
|
+
try {
|
|
842
|
+
const response = await fetch(url, {
|
|
843
|
+
...options,
|
|
844
|
+
signal: controller.signal
|
|
845
|
+
});
|
|
846
|
+
return await consumeResponse(response);
|
|
847
|
+
} finally {
|
|
848
|
+
clearTimeout(timeoutId);
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
async function fetchPackageInfo(packageName, registry2 = DEFAULT_NPM_REGISTRY) {
|
|
852
|
+
const cacheKey = `${registry2}:${packageName}`;
|
|
853
|
+
const cached = packageCache.get(cacheKey);
|
|
854
|
+
if (cached) {
|
|
855
|
+
return cached;
|
|
856
|
+
}
|
|
857
|
+
try {
|
|
858
|
+
const encodedName = packageName.startsWith("@") ? `@${encodeURIComponent(packageName.slice(1))}` : packageName;
|
|
859
|
+
const url = `${registry2.replace(/\/+$/, "")}/${encodedName}`;
|
|
860
|
+
logger3.debug(`Fetching package info from: ${url}`);
|
|
861
|
+
const { response, data } = await fetchWithTimeout(
|
|
862
|
+
url,
|
|
863
|
+
{
|
|
864
|
+
headers: {
|
|
865
|
+
Accept: "application/vnd.npm.install-v1+json"
|
|
866
|
+
}
|
|
867
|
+
},
|
|
868
|
+
async (fetchedResponse) => {
|
|
869
|
+
if (!fetchedResponse.ok) {
|
|
870
|
+
return { response: fetchedResponse, data: null };
|
|
871
|
+
}
|
|
872
|
+
return {
|
|
873
|
+
response: fetchedResponse,
|
|
874
|
+
data: await fetchedResponse.json()
|
|
875
|
+
};
|
|
876
|
+
}
|
|
877
|
+
);
|
|
878
|
+
if (!response.ok) {
|
|
879
|
+
if (response.status === 404) {
|
|
880
|
+
logger3.warn(`Package not found: ${packageName}`);
|
|
881
|
+
throw new Error(`Package not found: ${packageName} (HTTP 404)`);
|
|
882
|
+
}
|
|
883
|
+
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
884
|
+
}
|
|
885
|
+
const packageInfo = {
|
|
886
|
+
name: data.name,
|
|
887
|
+
versions: Object.keys(data.versions),
|
|
888
|
+
versionDetails: data.versions,
|
|
889
|
+
distTags: data["dist-tags"]
|
|
890
|
+
};
|
|
891
|
+
const cacheEntry = {
|
|
892
|
+
name: packageInfo.name,
|
|
893
|
+
versions: packageInfo.versions,
|
|
894
|
+
versionDetails: {},
|
|
895
|
+
distTags: packageInfo.distTags
|
|
896
|
+
};
|
|
897
|
+
packageCache.set(cacheKey, cacheEntry);
|
|
898
|
+
return packageInfo;
|
|
899
|
+
} catch (error) {
|
|
900
|
+
if (error instanceof Error && error.name === "AbortError") {
|
|
901
|
+
logger3.error(
|
|
902
|
+
`Timeout fetching package info for ${packageName} (>${DEFAULT_NPM_REGISTRY_TIMEOUT_MS}ms)`,
|
|
903
|
+
error
|
|
904
|
+
);
|
|
905
|
+
} else {
|
|
906
|
+
logger3.error(`Failed to fetch package info for ${packageName}:`, error);
|
|
907
|
+
}
|
|
908
|
+
throw error;
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
var npmRegistryClient = {
|
|
912
|
+
async fetchAllVersions(packageName, registry2) {
|
|
913
|
+
const info = await fetchPackageInfo(packageName, registry2);
|
|
914
|
+
return info?.versions ?? [];
|
|
915
|
+
},
|
|
916
|
+
async fetchPackageManifest(packageName, version, registry2) {
|
|
917
|
+
const key = `${registry2}\0${packageName}\0${version}`;
|
|
918
|
+
const cached = manifestCache.get(key);
|
|
919
|
+
if (cached) return cached;
|
|
920
|
+
const encodedName = packageName.startsWith("@") ? `@${encodeURIComponent(packageName.slice(1))}` : encodeURIComponent(packageName);
|
|
921
|
+
const url = `${registry2.replace(/\/+$/, "")}/${encodedName}/${encodeURIComponent(version)}`;
|
|
922
|
+
const manifest = await fetchWithTimeout(
|
|
923
|
+
url,
|
|
924
|
+
{
|
|
925
|
+
headers: { Accept: "application/json" }
|
|
926
|
+
},
|
|
927
|
+
async (response) => {
|
|
928
|
+
if (!response.ok) throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
929
|
+
return await response.json();
|
|
930
|
+
}
|
|
931
|
+
);
|
|
932
|
+
if (manifest.name !== packageName || manifest.version !== version) {
|
|
933
|
+
throw new Error(`Invalid manifest for ${packageName}@${version}`);
|
|
934
|
+
}
|
|
935
|
+
manifestCache.set(key, manifest);
|
|
936
|
+
return manifest;
|
|
937
|
+
}
|
|
938
|
+
};
|
|
939
|
+
function normalizePackagePath(packagePath) {
|
|
940
|
+
try {
|
|
941
|
+
return fs.realpathSync(packagePath);
|
|
942
|
+
} catch {
|
|
943
|
+
return path.resolve(packagePath);
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
function buildInstalledDependencyGraph(packageNames, projectRoot) {
|
|
947
|
+
const nodes = /* @__PURE__ */ new Map();
|
|
948
|
+
const roots = [];
|
|
949
|
+
const rootRequests = /* @__PURE__ */ new Map();
|
|
950
|
+
const stack = [];
|
|
951
|
+
for (let index = packageNames.length - 1; index >= 0; index--) {
|
|
952
|
+
const name = packageNames[index];
|
|
953
|
+
if (name) stack.push({ name, baseDir: projectRoot, parentId: null, root: true });
|
|
954
|
+
}
|
|
955
|
+
while (stack.length > 0) {
|
|
956
|
+
const item = stack.pop();
|
|
957
|
+
if (!item) continue;
|
|
958
|
+
const packagePath = findPackagePath(item.name, item.baseDir);
|
|
959
|
+
if (!packagePath) continue;
|
|
960
|
+
const normalizedPath = normalizePackagePath(packagePath);
|
|
961
|
+
if (item.root) rootRequests.set(item.name, normalizedPath);
|
|
962
|
+
if (item.parentId) nodes.get(item.parentId)?.resolvedChildren.set(item.name, normalizedPath);
|
|
963
|
+
const existingNode = nodes.get(normalizedPath);
|
|
964
|
+
if (existingNode) {
|
|
965
|
+
if (item.root) {
|
|
966
|
+
existingNode.parentId = null;
|
|
967
|
+
}
|
|
968
|
+
if (item.root && !roots.includes(normalizedPath)) {
|
|
969
|
+
roots.push(normalizedPath);
|
|
970
|
+
}
|
|
971
|
+
continue;
|
|
972
|
+
}
|
|
973
|
+
const packageJson = readPackageJsonCached(normalizedPath);
|
|
974
|
+
if (!packageJson) continue;
|
|
975
|
+
const dependencyNames = Object.keys({
|
|
976
|
+
...packageJson.dependencies,
|
|
977
|
+
...packageJson.optionalDependencies
|
|
978
|
+
});
|
|
979
|
+
const peerDependencyNames = Object.keys(packageJson.peerDependencies ?? {});
|
|
980
|
+
const node = {
|
|
981
|
+
id: normalizedPath,
|
|
982
|
+
name: item.name,
|
|
983
|
+
version: packageJson.version ?? "unknown",
|
|
984
|
+
packagePath: normalizedPath,
|
|
985
|
+
parentId: item.parentId,
|
|
986
|
+
dependencyNames,
|
|
987
|
+
peerDependencyNames,
|
|
988
|
+
resolvedChildren: /* @__PURE__ */ new Map()
|
|
989
|
+
};
|
|
990
|
+
nodes.set(normalizedPath, node);
|
|
991
|
+
if (item.root) roots.push(normalizedPath);
|
|
992
|
+
const childNames = [...dependencyNames, ...peerDependencyNames];
|
|
993
|
+
for (let index = childNames.length - 1; index >= 0; index--) {
|
|
994
|
+
const childName = childNames[index];
|
|
995
|
+
if (childName) {
|
|
996
|
+
stack.push({
|
|
997
|
+
name: childName,
|
|
998
|
+
baseDir: normalizedPath,
|
|
999
|
+
parentId: normalizedPath,
|
|
1000
|
+
root: false
|
|
1001
|
+
});
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
}
|
|
1005
|
+
return { nodes, roots, rootRequests };
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
// src/utils/module-request.ts
|
|
1009
|
+
function isVirtualModuleRequest(request) {
|
|
1010
|
+
return request.startsWith("\0");
|
|
1011
|
+
}
|
|
1012
|
+
function isPathLikeRequest(request) {
|
|
1013
|
+
if (!request) return false;
|
|
1014
|
+
if (request.startsWith(".")) {
|
|
1015
|
+
return true;
|
|
1016
|
+
}
|
|
1017
|
+
if (request.startsWith("/")) {
|
|
1018
|
+
return true;
|
|
1019
|
+
}
|
|
1020
|
+
if (/^[a-zA-Z]:[\\/]/.test(request)) {
|
|
1021
|
+
return true;
|
|
1022
|
+
}
|
|
1023
|
+
if (request.startsWith("\\\\")) {
|
|
1024
|
+
return true;
|
|
1025
|
+
}
|
|
1026
|
+
return false;
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
// src/core/resolution-error.ts
|
|
1030
|
+
var ResolutionError = class extends Error {
|
|
1031
|
+
constructor(diagnostics) {
|
|
1032
|
+
super(
|
|
1033
|
+
diagnostics.map((diagnostic) => "[" + diagnostic.code + "] " + diagnostic.message).join("\n")
|
|
1034
|
+
);
|
|
1035
|
+
this.diagnostics = diagnostics;
|
|
1036
|
+
this.name = "ResolutionError";
|
|
1037
|
+
}
|
|
1038
|
+
diagnostics;
|
|
1039
|
+
};
|
|
1040
|
+
|
|
1041
|
+
// src/core/alias-manager.ts
|
|
1042
|
+
var logger4 = createLogger("alias-manager");
|
|
1043
|
+
var NO_RULE = { reason: "no-rule", aliases: [], matchedPaths: [] };
|
|
1044
|
+
var NO_IMPORTER = { reason: "no-importer", aliases: [], matchedPaths: [] };
|
|
1045
|
+
var UNMATCHED = { reason: "unmatched", aliases: [], matchedPaths: [] };
|
|
1046
|
+
function normalizePath(path$1) {
|
|
1047
|
+
const normalized = path.posix.normalize(path$1.replace(/\\/g, "/"));
|
|
1048
|
+
return normalized.length <= 1 ? normalized : normalized.replace(/\/+$/, "");
|
|
1049
|
+
}
|
|
1050
|
+
function isWithin(path, directory) {
|
|
1051
|
+
return path === directory || path.startsWith(directory.endsWith("/") ? directory : directory + "/");
|
|
1052
|
+
}
|
|
1053
|
+
function packageInstances(path) {
|
|
1054
|
+
const parts = path.split("/");
|
|
1055
|
+
const instances = [];
|
|
1056
|
+
for (let index = 0; index < parts.length - 1; index++) {
|
|
1057
|
+
if (parts[index] !== "node_modules") continue;
|
|
1058
|
+
const name = parts[index + 1];
|
|
1059
|
+
if (!name || name.startsWith(".")) continue;
|
|
1060
|
+
const scopedName = name.startsWith("@") ? parts[index + 2] : void 0;
|
|
1061
|
+
if (name.startsWith("@") && !scopedName) continue;
|
|
1062
|
+
const end = scopedName ? index + 3 : index + 2;
|
|
1063
|
+
instances.push({
|
|
1064
|
+
name: scopedName ? name + "/" + scopedName : name,
|
|
1065
|
+
path: parts.slice(0, end).join("/")
|
|
1066
|
+
});
|
|
1067
|
+
}
|
|
1068
|
+
return instances;
|
|
1069
|
+
}
|
|
1070
|
+
var AliasManager = class {
|
|
1071
|
+
constructor(options) {
|
|
1072
|
+
this.options = options;
|
|
1073
|
+
}
|
|
1074
|
+
options;
|
|
1075
|
+
aliasMappings = [];
|
|
1076
|
+
rulesMap = /* @__PURE__ */ new Map();
|
|
1077
|
+
importerCache = new LruCache({ maxEntries: 1e3 });
|
|
1078
|
+
pathCache = new LruCache({ maxEntries: 5e3 });
|
|
1079
|
+
decisionCache = new LruCache({ maxEntries: 5e3 });
|
|
1080
|
+
diagnostics = /* @__PURE__ */ new Map();
|
|
1081
|
+
initFromAnalysisResult(result) {
|
|
1082
|
+
this.clear();
|
|
1083
|
+
this.aliasMappings = result.aliasMappings;
|
|
1084
|
+
for (const mapping of this.aliasMappings) {
|
|
1085
|
+
const pathScoped = mapping.importerPaths !== void 0;
|
|
1086
|
+
const rule = {
|
|
1087
|
+
aliasName: mapping.aliasName,
|
|
1088
|
+
pathScoped,
|
|
1089
|
+
dependents: /* @__PURE__ */ new Set([
|
|
1090
|
+
...pathScoped ? [] : mapping.allDependents,
|
|
1091
|
+
...this.options.includeRedirects[mapping.originalName] ?? []
|
|
1092
|
+
]),
|
|
1093
|
+
excludedPackages: new Set(this.options.excludeRedirects[mapping.originalName] ?? [])
|
|
1094
|
+
};
|
|
1095
|
+
let index = this.rulesMap.get(mapping.originalName);
|
|
1096
|
+
if (!index) {
|
|
1097
|
+
index = { paths: /* @__PURE__ */ new Map(), rules: [] };
|
|
1098
|
+
this.rulesMap.set(mapping.originalName, index);
|
|
1099
|
+
}
|
|
1100
|
+
index.rules.push(rule);
|
|
1101
|
+
for (const packagePath of mapping.importerPaths ?? []) {
|
|
1102
|
+
const candidates = this.pathCandidates(packagePath);
|
|
1103
|
+
const name = packageInstances(normalizePath(packagePath)).at(-1)?.name ?? readPackageJsonCached(packagePath)?.name;
|
|
1104
|
+
for (const candidate of candidates) {
|
|
1105
|
+
const entries = index.paths.get(candidate) ?? [];
|
|
1106
|
+
entries.push({ rule, scope: { path: candidate, name } });
|
|
1107
|
+
index.paths.set(candidate, entries);
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1110
|
+
}
|
|
1111
|
+
logger4.info("Initialized " + this.aliasMappings.length + " alias mappings");
|
|
1112
|
+
}
|
|
1113
|
+
clear() {
|
|
1114
|
+
this.aliasMappings = [];
|
|
1115
|
+
this.rulesMap.clear();
|
|
1116
|
+
this.importerCache.clear();
|
|
1117
|
+
this.pathCache.clear();
|
|
1118
|
+
this.decisionCache.clear();
|
|
1119
|
+
this.diagnostics.clear();
|
|
1120
|
+
}
|
|
1121
|
+
pathCandidates(path, moduleId = false) {
|
|
1122
|
+
const cacheKey = (moduleId ? "id\0" : "path\0") + path;
|
|
1123
|
+
const cached = this.pathCache.get(cacheKey);
|
|
1124
|
+
if (cached) return cached;
|
|
1125
|
+
let literalPath = path;
|
|
1126
|
+
let realPath;
|
|
1127
|
+
try {
|
|
1128
|
+
realPath = fs.realpathSync(path);
|
|
1129
|
+
} catch {
|
|
1130
|
+
if (moduleId) {
|
|
1131
|
+
const markers = [...path.matchAll(/[?#]/g)];
|
|
1132
|
+
for (let index = markers.length - 1; index >= 0; index--) {
|
|
1133
|
+
const candidate = path.slice(0, markers[index].index);
|
|
1134
|
+
try {
|
|
1135
|
+
if (!fs.statSync(candidate).isFile()) continue;
|
|
1136
|
+
realPath = fs.realpathSync(candidate);
|
|
1137
|
+
literalPath = candidate;
|
|
1138
|
+
break;
|
|
1139
|
+
} catch {
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
}
|
|
1144
|
+
const paths = /* @__PURE__ */ new Set([normalizePath(literalPath)]);
|
|
1145
|
+
if (realPath) paths.add(normalizePath(realPath));
|
|
1146
|
+
const candidates = [...paths];
|
|
1147
|
+
this.pathCache.set(cacheKey, candidates);
|
|
1148
|
+
return candidates;
|
|
1149
|
+
}
|
|
1150
|
+
importerInfo(importer) {
|
|
1151
|
+
const cached = this.importerCache.get(importer);
|
|
1152
|
+
if (cached) return cached;
|
|
1153
|
+
const paths = this.pathCandidates(importer, true);
|
|
1154
|
+
const instances = paths.flatMap(packageInstances);
|
|
1155
|
+
if (instances.length === 0) {
|
|
1156
|
+
for (const path$1 of paths) {
|
|
1157
|
+
let directory = path$1;
|
|
1158
|
+
while (true) {
|
|
1159
|
+
const manifest = readPackageJsonCached(directory);
|
|
1160
|
+
if (manifest?.name) {
|
|
1161
|
+
instances.push({ name: manifest.name, path: directory });
|
|
1162
|
+
break;
|
|
1163
|
+
}
|
|
1164
|
+
const parent = path.posix.dirname(directory);
|
|
1165
|
+
if (parent === directory) break;
|
|
1166
|
+
directory = parent;
|
|
1167
|
+
}
|
|
1168
|
+
}
|
|
1169
|
+
}
|
|
1170
|
+
const info = { paths, instances };
|
|
1171
|
+
this.importerCache.set(importer, info);
|
|
1172
|
+
return info;
|
|
1173
|
+
}
|
|
1174
|
+
requestPackageName(request) {
|
|
1175
|
+
if (!request || isPathLikeRequest(request) || isVirtualModuleRequest(request)) return "";
|
|
1176
|
+
const base = request.split(/[?#]/, 1)[0] ?? "";
|
|
1177
|
+
const parts = base.split("/");
|
|
1178
|
+
return base.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0] ?? "";
|
|
1179
|
+
}
|
|
1180
|
+
decide(packageName, importer) {
|
|
1181
|
+
if (!importer) return NO_IMPORTER;
|
|
1182
|
+
const index = this.rulesMap.get(packageName);
|
|
1183
|
+
if (!index) return NO_RULE;
|
|
1184
|
+
const cacheKey = packageName + "\0" + importer;
|
|
1185
|
+
const cached = this.decisionCache.get(cacheKey);
|
|
1186
|
+
if (cached) return cached;
|
|
1187
|
+
const info = this.importerInfo(importer);
|
|
1188
|
+
const matches = /* @__PURE__ */ new Map();
|
|
1189
|
+
for (const candidate of info.paths) {
|
|
1190
|
+
let path$1 = candidate;
|
|
1191
|
+
let distance = 0;
|
|
1192
|
+
while (true) {
|
|
1193
|
+
for (const { rule, scope } of index.paths.get(path$1) ?? []) {
|
|
1194
|
+
let match = matches.get(rule);
|
|
1195
|
+
if (!match) {
|
|
1196
|
+
match = { rule, specificity: Number.NEGATIVE_INFINITY, scopes: [], excluded: false };
|
|
1197
|
+
matches.set(rule, match);
|
|
1198
|
+
}
|
|
1199
|
+
match.specificity = Math.max(match.specificity, -distance);
|
|
1200
|
+
match.scopes.push(scope);
|
|
1201
|
+
}
|
|
1202
|
+
const parent = path.posix.dirname(path$1);
|
|
1203
|
+
if (parent === path$1) break;
|
|
1204
|
+
path$1 = parent;
|
|
1205
|
+
distance++;
|
|
1206
|
+
}
|
|
1207
|
+
}
|
|
1208
|
+
for (const rule of index.rules) {
|
|
1209
|
+
const included = info.instances.filter((instance) => rule.dependents.has(instance.name));
|
|
1210
|
+
let match = matches.get(rule);
|
|
1211
|
+
if (!match && included.length > 0) {
|
|
1212
|
+
match = { rule, specificity: Number.NEGATIVE_INFINITY, scopes: [], excluded: false };
|
|
1213
|
+
matches.set(rule, match);
|
|
1214
|
+
}
|
|
1215
|
+
if (!match) continue;
|
|
1216
|
+
match.excluded = match.scopes.some((scope) => scope.name && rule.excludedPackages.has(scope.name)) || info.instances.some(
|
|
1217
|
+
(instance) => rule.excludedPackages.has(instance.name) && (!rule.pathScoped || match.scopes.some(
|
|
1218
|
+
(scope) => isWithin(instance.path, scope.path) || isWithin(scope.path, instance.path)
|
|
1219
|
+
) || included.some(
|
|
1220
|
+
(parent) => isWithin(instance.path, parent.path) || isWithin(parent.path, instance.path)
|
|
1221
|
+
))
|
|
1222
|
+
);
|
|
1223
|
+
}
|
|
1224
|
+
let specificity = Number.NEGATIVE_INFINITY;
|
|
1225
|
+
let best = [];
|
|
1226
|
+
for (const match of matches.values()) {
|
|
1227
|
+
if (match.specificity > specificity) {
|
|
1228
|
+
specificity = match.specificity;
|
|
1229
|
+
best = [match];
|
|
1230
|
+
} else if (match.specificity === specificity) {
|
|
1231
|
+
best.push(match);
|
|
1232
|
+
}
|
|
1233
|
+
}
|
|
1234
|
+
let decision = UNMATCHED;
|
|
1235
|
+
if (best.length > 0) {
|
|
1236
|
+
const aliases = [...new Set(best.map((match) => match.rule.aliasName))].sort();
|
|
1237
|
+
const matchedPaths = [
|
|
1238
|
+
...new Set(best.flatMap((match) => match.scopes.map((scope) => scope.path)))
|
|
1239
|
+
].sort();
|
|
1240
|
+
decision = {
|
|
1241
|
+
reason: best.some((match) => match.excluded) ? "excluded" : aliases.length > 1 ? "ambiguous" : "redirected",
|
|
1242
|
+
aliases,
|
|
1243
|
+
matchedPaths
|
|
1244
|
+
};
|
|
1245
|
+
if (decision.reason === "ambiguous") {
|
|
1246
|
+
const key = packageName + "\0" + JSON.stringify([aliases, matchedPaths]);
|
|
1247
|
+
if (!this.diagnostics.has(key) && this.diagnostics.size < 1e3) {
|
|
1248
|
+
const diagnostic = {
|
|
1249
|
+
code: "AMBIGUOUS_IMPORTER",
|
|
1250
|
+
severity: "error",
|
|
1251
|
+
message: "Multiple aliases match the same importer for " + packageName + ": " + aliases.join(", "),
|
|
1252
|
+
packageName,
|
|
1253
|
+
aliases,
|
|
1254
|
+
importerPaths: matchedPaths
|
|
1255
|
+
};
|
|
1256
|
+
this.diagnostics.set(key, diagnostic);
|
|
1257
|
+
logger4.warn(diagnostic.message);
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1260
|
+
}
|
|
1261
|
+
this.decisionCache.set(cacheKey, decision);
|
|
1262
|
+
return decision;
|
|
1263
|
+
}
|
|
1264
|
+
resolveModule({ request, importer }) {
|
|
1265
|
+
const packageName = this.requestPackageName(request);
|
|
1266
|
+
if (!packageName) return null;
|
|
1267
|
+
const decision = this.decide(packageName, importer);
|
|
1268
|
+
if (decision.reason === "ambiguous" && this.options.strict) {
|
|
1269
|
+
throw new ResolutionError(this.getDiagnostics());
|
|
1270
|
+
}
|
|
1271
|
+
return decision.reason === "redirected" ? decision.aliases[0] + request.slice(packageName.length) : null;
|
|
1272
|
+
}
|
|
1273
|
+
explainResolution(request, importer) {
|
|
1274
|
+
const packageName = this.requestPackageName(request);
|
|
1275
|
+
const decision = packageName ? this.decide(packageName, importer) : NO_RULE;
|
|
1276
|
+
return {
|
|
1277
|
+
request,
|
|
1278
|
+
importer,
|
|
1279
|
+
resolved: decision.reason === "redirected" ? decision.aliases[0] + request.slice(packageName.length) : null,
|
|
1280
|
+
reason: decision.reason,
|
|
1281
|
+
aliases: [...decision.aliases],
|
|
1282
|
+
matchedPaths: [...decision.matchedPaths]
|
|
1283
|
+
};
|
|
1284
|
+
}
|
|
1285
|
+
getDiagnostics() {
|
|
1286
|
+
return [...this.diagnostics.values()].map(
|
|
1287
|
+
(diagnostic) => Object.assign({}, diagnostic, {
|
|
1288
|
+
aliases: [...diagnostic.aliases ?? []],
|
|
1289
|
+
importerPaths: [...diagnostic.importerPaths ?? []]
|
|
1290
|
+
})
|
|
1291
|
+
);
|
|
1292
|
+
}
|
|
1293
|
+
getAliasPathMappings() {
|
|
1294
|
+
return this.aliasMappings.map((mapping) => ({
|
|
1295
|
+
aliasName: mapping.aliasName,
|
|
1296
|
+
originalName: mapping.originalName,
|
|
1297
|
+
path: findPackagePath(mapping.aliasName, this.options.projectRoot) ?? path.join(this.options.projectRoot, "node_modules", mapping.aliasName)
|
|
1298
|
+
}));
|
|
1299
|
+
}
|
|
1300
|
+
};
|
|
1301
|
+
function createAliasManager(options) {
|
|
1302
|
+
return new AliasManager(options);
|
|
1303
|
+
}
|
|
1304
|
+
|
|
1305
|
+
// src/core/alias-peer-resolver.ts
|
|
1306
|
+
function actualPath(path) {
|
|
1307
|
+
try {
|
|
1308
|
+
return fs.realpathSync(path);
|
|
1309
|
+
} catch {
|
|
1310
|
+
return path;
|
|
1311
|
+
}
|
|
1312
|
+
}
|
|
1313
|
+
async function linkAliasPeers(mappings, options, registry2, diagnostics, peerConflicts = [], watchFiles) {
|
|
1314
|
+
if (mappings.length === 0) return;
|
|
1315
|
+
const readManifest = (directory) => {
|
|
1316
|
+
watchFiles?.add(path.join(actualPath(directory), "package.json"));
|
|
1317
|
+
return readPackageJsonCached(directory);
|
|
1318
|
+
};
|
|
1319
|
+
for (const mapping of mappings) {
|
|
1320
|
+
const previousPaths = new Set(Object.values(mapping.peerImporterPaths ?? {}).flat());
|
|
1321
|
+
if (mapping.importerPaths && previousPaths.size > 0) {
|
|
1322
|
+
mapping.importerPaths = mapping.importerPaths.filter((path) => !previousPaths.has(path));
|
|
1323
|
+
}
|
|
1324
|
+
mapping.peerImporterPaths = {};
|
|
1325
|
+
}
|
|
1326
|
+
const workspaceRoot = createWorkspaceDetector(options.projectRoot).getWorkspaceRoot();
|
|
1327
|
+
const manifests = /* @__PURE__ */ new Map();
|
|
1328
|
+
const installedPaths = /* @__PURE__ */ new Map();
|
|
1329
|
+
const consumerRequests = new Map(
|
|
1330
|
+
peerConflicts.map((conflict) => [conflict.packageName, conflict.requestedBy])
|
|
1331
|
+
);
|
|
1332
|
+
let contextResolver;
|
|
1333
|
+
for (const mapping of mappings) {
|
|
1334
|
+
const installedPath = findPackagePath(mapping.aliasName, options.projectRoot);
|
|
1335
|
+
const installed = installedPath ? readManifest(installedPath) : null;
|
|
1336
|
+
if (installed?.name === mapping.originalName && installed.version && satisfies(installed.version, mapping.resolvedVersion)) {
|
|
1337
|
+
manifests.set(mapping, installed);
|
|
1338
|
+
installedPaths.set(mapping, installedPath);
|
|
1339
|
+
continue;
|
|
1340
|
+
}
|
|
1341
|
+
if (mapping.installSpec && !options.offline && registry2.fetchPackageManifest) {
|
|
1342
|
+
try {
|
|
1343
|
+
const manifest = await registry2.fetchPackageManifest(
|
|
1344
|
+
mapping.originalName,
|
|
1345
|
+
mapping.resolvedVersion,
|
|
1346
|
+
options.registry
|
|
1347
|
+
);
|
|
1348
|
+
manifests.set(mapping, manifest);
|
|
1349
|
+
} catch (error) {
|
|
1350
|
+
diagnostics.push({
|
|
1351
|
+
code: "ALIAS_METADATA_UNAVAILABLE",
|
|
1352
|
+
severity: "error",
|
|
1353
|
+
packageName: mapping.originalName,
|
|
1354
|
+
aliases: [mapping.aliasName],
|
|
1355
|
+
message: "Cannot inspect selected version " + mapping.originalName + "@" + mapping.resolvedVersion + ": " + String(error)
|
|
1356
|
+
});
|
|
1357
|
+
}
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
for (const [importer, manifest] of manifests) {
|
|
1361
|
+
const importerPaths = /* @__PURE__ */ new Set([
|
|
1362
|
+
path.join(options.projectRoot, "node_modules", importer.aliasName),
|
|
1363
|
+
path.join(actualPath(options.projectRoot), "node_modules", importer.aliasName)
|
|
1364
|
+
]);
|
|
1365
|
+
if (workspaceRoot) importerPaths.add(path.join(workspaceRoot, "node_modules", importer.aliasName));
|
|
1366
|
+
const installedPath = installedPaths.get(importer);
|
|
1367
|
+
if (installedPath) importerPaths.add(actualPath(installedPath));
|
|
1368
|
+
const pendingInstallation = !installedPath && options.autoInstall && importer.installSpec;
|
|
1369
|
+
for (const [peerName, range] of Object.entries(manifest.peerDependencies ?? {})) {
|
|
1370
|
+
if (manifest.peerDependenciesMeta?.[peerName]?.optional) continue;
|
|
1371
|
+
const providers = /* @__PURE__ */ new Map();
|
|
1372
|
+
const providerAliases = /* @__PURE__ */ new Set();
|
|
1373
|
+
const checkContexts = importer.usedBy.length > 1 && consumerRequests.has(peerName);
|
|
1374
|
+
if (checkContexts) {
|
|
1375
|
+
for (const consumer of importer.usedBy) {
|
|
1376
|
+
const request = consumerRequests.get(peerName)?.find((entry) => entry.path.join(">") === consumer);
|
|
1377
|
+
if (!request) continue;
|
|
1378
|
+
let directory = options.projectRoot;
|
|
1379
|
+
for (const name of request.path) {
|
|
1380
|
+
const packageDirectory = findPackagePath(name, directory);
|
|
1381
|
+
directory = packageDirectory ? actualPath(packageDirectory) : null;
|
|
1382
|
+
if (!directory) break;
|
|
1383
|
+
}
|
|
1384
|
+
if (!directory) continue;
|
|
1385
|
+
if (!contextResolver) {
|
|
1386
|
+
contextResolver = new AliasManager({ ...options, strict: false });
|
|
1387
|
+
contextResolver.initFromAnalysisResult({
|
|
1388
|
+
aliasMappings: mappings,
|
|
1389
|
+
peerConflicts: [...peerConflicts],
|
|
1390
|
+
analyzedDependencies: /* @__PURE__ */ new Map(),
|
|
1391
|
+
missingFirstLevelPeers: []
|
|
1392
|
+
});
|
|
1393
|
+
}
|
|
1394
|
+
const decision = contextResolver.explainResolution(
|
|
1395
|
+
peerName,
|
|
1396
|
+
path.join(directory, "__peer_context__.js")
|
|
1397
|
+
);
|
|
1398
|
+
const selected = decision.reason === "redirected" || decision.reason === "ambiguous" ? mappings.filter((mapping) => decision.aliases.includes(mapping.aliasName)) : [];
|
|
1399
|
+
if (selected.length > 0) {
|
|
1400
|
+
for (const mapping of selected) {
|
|
1401
|
+
if (!satisfies(mapping.resolvedVersion, range)) continue;
|
|
1402
|
+
const path$1 = actualPath(
|
|
1403
|
+
findPackagePath(mapping.aliasName, options.projectRoot) ?? path.join(options.projectRoot, "node_modules", mapping.aliasName)
|
|
1404
|
+
);
|
|
1405
|
+
providers.set(path$1, [
|
|
1406
|
+
...providers.get(path$1) ?? [],
|
|
1407
|
+
consumer + " -> " + mapping.aliasName + "@" + mapping.resolvedVersion
|
|
1408
|
+
]);
|
|
1409
|
+
providerAliases.add(mapping.aliasName);
|
|
1410
|
+
}
|
|
1411
|
+
} else {
|
|
1412
|
+
const path = findPackagePath(peerName, directory);
|
|
1413
|
+
const provider = path ? readManifest(path) : null;
|
|
1414
|
+
if (path && provider?.version && satisfies(provider.version, range)) {
|
|
1415
|
+
const identity = actualPath(path);
|
|
1416
|
+
providers.set(identity, [
|
|
1417
|
+
...providers.get(identity) ?? [],
|
|
1418
|
+
consumer + " -> " + peerName + "@" + provider.version
|
|
1419
|
+
]);
|
|
1420
|
+
}
|
|
1421
|
+
}
|
|
1422
|
+
}
|
|
1423
|
+
}
|
|
1424
|
+
if (providers.size > 1) {
|
|
1425
|
+
diagnostics.push({
|
|
1426
|
+
code: "AMBIGUOUS_IMPORTER",
|
|
1427
|
+
severity: "error",
|
|
1428
|
+
packageName: peerName,
|
|
1429
|
+
aliases: [...providerAliases].sort(),
|
|
1430
|
+
requestedBy: [importer.aliasName],
|
|
1431
|
+
importerPaths: [...importerPaths],
|
|
1432
|
+
message: "Conflicting consumer peer contexts for " + importer.aliasName + ": " + [...providers.values()].flat().join("; ")
|
|
1433
|
+
});
|
|
1434
|
+
continue;
|
|
1435
|
+
}
|
|
1436
|
+
let candidates = mappings.filter(
|
|
1437
|
+
(mapping) => mapping !== importer && mapping.originalName === peerName && satisfies(mapping.resolvedVersion, range)
|
|
1438
|
+
);
|
|
1439
|
+
const sharedContexts = candidates.filter(
|
|
1440
|
+
(candidate) => checkContexts ? providerAliases.has(candidate.aliasName) : candidate.usedBy.some((consumer) => importer.usedBy.includes(consumer))
|
|
1441
|
+
);
|
|
1442
|
+
if (sharedContexts.length > 0) {
|
|
1443
|
+
candidates = sharedContexts;
|
|
1444
|
+
} else {
|
|
1445
|
+
const naturalPath = findPackagePath(peerName, installedPath ?? options.projectRoot);
|
|
1446
|
+
const natural = naturalPath ? readManifest(naturalPath) : null;
|
|
1447
|
+
if (natural?.version && satisfies(natural.version, range)) continue;
|
|
1448
|
+
}
|
|
1449
|
+
if (candidates.length === 1) {
|
|
1450
|
+
const peer = candidates[0];
|
|
1451
|
+
if (peer.importerPaths === void 0) continue;
|
|
1452
|
+
const paths = [...importerPaths];
|
|
1453
|
+
peer.importerPaths = [.../* @__PURE__ */ new Set([...peer.importerPaths, ...paths])];
|
|
1454
|
+
peer.peerImporterPaths = {
|
|
1455
|
+
...peer.peerImporterPaths,
|
|
1456
|
+
[importer.aliasName]: paths
|
|
1457
|
+
};
|
|
1458
|
+
continue;
|
|
1459
|
+
}
|
|
1460
|
+
if (candidates.length > 1) {
|
|
1461
|
+
diagnostics.push({
|
|
1462
|
+
code: "AMBIGUOUS_IMPORTER",
|
|
1463
|
+
severity: pendingInstallation ? "warning" : "error",
|
|
1464
|
+
packageName: peerName,
|
|
1465
|
+
aliases: candidates.map((candidate) => candidate.aliasName).sort(),
|
|
1466
|
+
requestedBy: [importer.aliasName],
|
|
1467
|
+
importerPaths: [...importerPaths],
|
|
1468
|
+
message: "Multiple peer contexts for " + importer.aliasName + " requiring " + peerName + "@" + range
|
|
1469
|
+
});
|
|
1470
|
+
continue;
|
|
1471
|
+
}
|
|
1472
|
+
diagnostics.push({
|
|
1473
|
+
code: "ALIAS_PEER_UNSATISFIED",
|
|
1474
|
+
severity: pendingInstallation ? "warning" : "error",
|
|
1475
|
+
packageName: peerName,
|
|
1476
|
+
requestedBy: [importer.aliasName],
|
|
1477
|
+
message: importer.aliasName + " requires " + peerName + "@" + range + (pendingInstallation ? "; provider availability will be checked after installation" : ", but no compatible alias or installed provider is available")
|
|
1478
|
+
});
|
|
1479
|
+
}
|
|
1480
|
+
}
|
|
1481
|
+
}
|
|
1482
|
+
function canonical(directory) {
|
|
1483
|
+
try {
|
|
1484
|
+
return fs.realpathSync(directory);
|
|
1485
|
+
} catch {
|
|
1486
|
+
return directory;
|
|
1487
|
+
}
|
|
1488
|
+
}
|
|
1489
|
+
function validateSharedPeerContexts(graph, mappings, options, diagnostics, watchFiles) {
|
|
1490
|
+
if (mappings.length === 0 || graph.rootRequests.size < 2) return;
|
|
1491
|
+
const readManifest = (directory) => {
|
|
1492
|
+
watchFiles?.add(path.join(directory, "package.json"));
|
|
1493
|
+
return readPackageJsonCached(directory);
|
|
1494
|
+
};
|
|
1495
|
+
const aliases = /* @__PURE__ */ new Map();
|
|
1496
|
+
const installedMappings = mappings.filter((mapping) => {
|
|
1497
|
+
const path = findPackagePath(mapping.aliasName, options.projectRoot);
|
|
1498
|
+
if (!path) return false;
|
|
1499
|
+
const physical = canonical(path);
|
|
1500
|
+
const manifest = readManifest(physical);
|
|
1501
|
+
if (manifest?.name !== mapping.originalName || !manifest.version || !satisfies(manifest.version, mapping.resolvedVersion))
|
|
1502
|
+
return false;
|
|
1503
|
+
aliases.set(mapping.aliasName, {
|
|
1504
|
+
path: physical,
|
|
1505
|
+
version: manifest.version,
|
|
1506
|
+
label: mapping.aliasName + "@" + manifest.version
|
|
1507
|
+
});
|
|
1508
|
+
return true;
|
|
1509
|
+
});
|
|
1510
|
+
if (installedMappings.length === 0) return;
|
|
1511
|
+
const resolver = new AliasManager({ ...options, strict: false });
|
|
1512
|
+
resolver.initFromAnalysisResult({
|
|
1513
|
+
aliasMappings: installedMappings,
|
|
1514
|
+
analyzedDependencies: /* @__PURE__ */ new Map(),
|
|
1515
|
+
peerConflicts: [],
|
|
1516
|
+
missingFirstLevelPeers: []
|
|
1517
|
+
});
|
|
1518
|
+
const aliasPaths = new Set([...aliases.values()].map((provider) => provider.path));
|
|
1519
|
+
const originals = new Set(installedMappings.map((mapping) => mapping.originalName));
|
|
1520
|
+
for (const peer of originals) {
|
|
1521
|
+
const hasExclusions = (options.excludeRedirects[peer]?.length ?? 0) > 0;
|
|
1522
|
+
const roots = [];
|
|
1523
|
+
for (const [consumer, nodeId] of graph.rootRequests) {
|
|
1524
|
+
const node = graph.nodes.get(nodeId);
|
|
1525
|
+
if (!node) continue;
|
|
1526
|
+
const manifest = readManifest(node.packagePath);
|
|
1527
|
+
const range = manifest?.peerDependencies?.[peer];
|
|
1528
|
+
if (!range || manifest?.peerDependenciesMeta?.[peer]?.optional) continue;
|
|
1529
|
+
const decision = resolver.explainResolution(
|
|
1530
|
+
peer,
|
|
1531
|
+
path.join(node.packagePath, "__peer_context__.js")
|
|
1532
|
+
);
|
|
1533
|
+
if (decision.reason === "ambiguous") continue;
|
|
1534
|
+
let provider = decision.resolved ? aliases.get(decision.aliases[0]) : void 0;
|
|
1535
|
+
if (!decision.resolved) {
|
|
1536
|
+
const path = findPackagePath(peer, node.packagePath);
|
|
1537
|
+
const natural = path ? readManifest(canonical(path)) : null;
|
|
1538
|
+
if (path && natural?.version)
|
|
1539
|
+
provider = {
|
|
1540
|
+
path: canonical(path),
|
|
1541
|
+
version: natural.version,
|
|
1542
|
+
label: peer + "@" + natural.version
|
|
1543
|
+
};
|
|
1544
|
+
}
|
|
1545
|
+
if (provider && satisfies(provider.version, range))
|
|
1546
|
+
roots.push({ nodeId, consumer, provider });
|
|
1547
|
+
}
|
|
1548
|
+
if (new Set(roots.map(({ provider }) => provider.path)).size < 2) continue;
|
|
1549
|
+
const visited = /* @__PURE__ */ new Set();
|
|
1550
|
+
const contexts = /* @__PURE__ */ new Map();
|
|
1551
|
+
const pending = [...roots];
|
|
1552
|
+
while (pending.length > 0) {
|
|
1553
|
+
const context = pending.pop();
|
|
1554
|
+
const key = context.nodeId + "\0" + context.provider.path;
|
|
1555
|
+
if (visited.has(key)) continue;
|
|
1556
|
+
visited.add(key);
|
|
1557
|
+
const node = graph.nodes.get(context.nodeId);
|
|
1558
|
+
if (!node || originals.has(node.name)) continue;
|
|
1559
|
+
if (hasExclusions && resolver.explainResolution(peer, path.join(node.packagePath, "__peer_context__.js")).reason === "excluded")
|
|
1560
|
+
continue;
|
|
1561
|
+
const manifest = readManifest(node.packagePath);
|
|
1562
|
+
const range = manifest?.peerDependencies?.[peer];
|
|
1563
|
+
if (range && !satisfies(context.provider.version, range)) continue;
|
|
1564
|
+
if (range && !manifest?.peerDependenciesMeta?.[peer]?.optional && !aliasPaths.has(node.packagePath) && !options.includeRedirects[peer]?.includes(node.name)) {
|
|
1565
|
+
let incoming = contexts.get(node.id);
|
|
1566
|
+
if (!incoming) contexts.set(node.id, incoming = /* @__PURE__ */ new Map());
|
|
1567
|
+
incoming.set(context.provider.path, context);
|
|
1568
|
+
}
|
|
1569
|
+
for (const child of node.resolvedChildren.values())
|
|
1570
|
+
pending.push({ ...context, nodeId: child });
|
|
1571
|
+
}
|
|
1572
|
+
for (const [nodeId, incoming] of contexts) {
|
|
1573
|
+
if (incoming.size < 2) continue;
|
|
1574
|
+
const node = graph.nodes.get(nodeId);
|
|
1575
|
+
diagnostics.push({
|
|
1576
|
+
code: "SHARED_PEER_CONTEXT",
|
|
1577
|
+
severity: "warning",
|
|
1578
|
+
packageName: peer,
|
|
1579
|
+
requestedBy: [...new Set([...incoming.values()].map(({ consumer }) => consumer))],
|
|
1580
|
+
importerPaths: [node.packagePath],
|
|
1581
|
+
message: "Shared package " + node.name + " has different incoming peer contexts: " + [...incoming.values()].map(({ consumer, provider }) => consumer + " -> " + provider.label).join("; ") + ". A single physical instance cannot inherit both providers. Isolate the package or explicitly configure its redirect scope."
|
|
1582
|
+
});
|
|
1583
|
+
}
|
|
1584
|
+
}
|
|
1585
|
+
}
|
|
1586
|
+
|
|
1587
|
+
// src/core/dependency-analyzer.ts
|
|
1588
|
+
var logger5 = createLogger("dependency-analyzer");
|
|
1589
|
+
var DependencyAnalyzer = class {
|
|
1590
|
+
options;
|
|
1591
|
+
/** 主项目声明的依赖(解析后的版本,catalog: 等协议已转换) */
|
|
1592
|
+
declaredDeps;
|
|
1593
|
+
/** 主项目声明的原始依赖(未解析,保留 catalog: 等协议) */
|
|
1594
|
+
rawDeclaredDeps;
|
|
1595
|
+
/** 分析结果:存储有 peer 依赖的包信息 */
|
|
1596
|
+
analyzedDependencies = /* @__PURE__ */ new Map();
|
|
1597
|
+
/** 已访问的包名(使用包名,同一个包只分析一次) */
|
|
1598
|
+
visitedPackages = /* @__PURE__ */ new Set();
|
|
1599
|
+
/** 已安装包的信息缓存(按需填充,避免扫描整个 node_modules) */
|
|
1600
|
+
installedPackageCache = /* @__PURE__ */ new Map();
|
|
1601
|
+
/**
|
|
1602
|
+
* 已存在的别名映射:真实包名 -> 别名信息列表
|
|
1603
|
+
* 从 package.json 的 npm:package@version 格式解析得到
|
|
1604
|
+
* 这是最准确的别名识别方式
|
|
1605
|
+
*/
|
|
1606
|
+
existingAliasesMap = /* @__PURE__ */ new Map();
|
|
1607
|
+
/** Workspace 检测器(用于 catalog 协议解析和 workspace 别名查找) */
|
|
1608
|
+
workspaceDetector;
|
|
1609
|
+
/** Workspace 级别的别名缓存 */
|
|
1610
|
+
workspaceAliasesCache = /* @__PURE__ */ new Map();
|
|
1611
|
+
/** workspace 根目录 package.json 声明的依赖(dependencies/devDependencies),用于“声明判断”合并 */
|
|
1612
|
+
workspaceRootDeclaredDeps = {};
|
|
1613
|
+
/** 是否已加载 workspaceRootDeclaredDeps */
|
|
1614
|
+
workspaceRootDeclaredLoaded = false;
|
|
1615
|
+
/** collectAllRelatedPackages 的 memo 缓存(单次 analyze 生命周期内有效) */
|
|
1616
|
+
collectCache = /* @__PURE__ */ new Map();
|
|
1617
|
+
/** 当前 analyze 使用的按安装路径区分的依赖图 */
|
|
1618
|
+
dependencyGraph = null;
|
|
1619
|
+
/** 注册表访问适配器(可注入以支持离线分析和确定性测试) */
|
|
1620
|
+
registryClient;
|
|
1621
|
+
graphPopulated = false;
|
|
1622
|
+
diagnostics = [];
|
|
1623
|
+
watchFiles = /* @__PURE__ */ new Set();
|
|
1624
|
+
injectedInstalledDeps;
|
|
1625
|
+
constructor(options, mainPackageJson, installedDeps, registryClient = npmRegistryClient) {
|
|
1626
|
+
this.options = options;
|
|
1627
|
+
this.registryClient = registryClient;
|
|
1628
|
+
this.injectedInstalledDeps = installedDeps;
|
|
1629
|
+
this.rawDeclaredDeps = {
|
|
1630
|
+
...mainPackageJson.dependencies,
|
|
1631
|
+
...mainPackageJson.devDependencies,
|
|
1632
|
+
...mainPackageJson.optionalDependencies
|
|
1633
|
+
};
|
|
1634
|
+
this.declaredDeps = { ...this.rawDeclaredDeps };
|
|
1635
|
+
this.workspaceDetector = createWorkspaceDetector(options.projectRoot);
|
|
1636
|
+
this.parseExistingAliases();
|
|
1637
|
+
if (installedDeps) {
|
|
1638
|
+
for (const [name, info] of installedDeps) {
|
|
1639
|
+
this.installedPackageCache.set(name, info);
|
|
1640
|
+
}
|
|
1641
|
+
}
|
|
1642
|
+
}
|
|
1643
|
+
/**
|
|
1644
|
+
* 统一封装:在指定 baseDir 下解析包安装路径并读取 package.json
|
|
1645
|
+
* - 用于收敛 findPackagePath + readPackageJsonCached 的重复逻辑
|
|
1646
|
+
* - 返回 { packagePath: null } 表示无法 resolve 到该包
|
|
1647
|
+
* - 返回 { packagePath, pkgJson: null } 表示找到了目录但 package.json 无法读取/解析
|
|
1648
|
+
*/
|
|
1649
|
+
resolvePackageJson(packageName, baseDir) {
|
|
1650
|
+
const packagePath = findPackagePath(packageName, baseDir);
|
|
1651
|
+
if (!packagePath) {
|
|
1652
|
+
return { packagePath: null, pkgJson: null };
|
|
1653
|
+
}
|
|
1654
|
+
const pkgJson = readPackageJsonCached(packagePath);
|
|
1655
|
+
this.watchFiles.add(path.join(this.normalizeInstalledPath(packagePath), "package.json"));
|
|
1656
|
+
return { packagePath, pkgJson };
|
|
1657
|
+
}
|
|
1658
|
+
/**
|
|
1659
|
+
* 加载 workspace 根目录 package.json 声明的依赖(dependencies/devDependencies)
|
|
1660
|
+
*
|
|
1661
|
+
* 目的:在 monorepo/workspace 场景下,“主工程声明”需要合并当前包与 workspace 根的声明,
|
|
1662
|
+
* 与 WorkspaceDetector 的 workspaceRoot 判断逻辑保持一致。
|
|
1663
|
+
*/
|
|
1664
|
+
ensureWorkspaceRootDeclaredDepsLoaded() {
|
|
1665
|
+
if (this.workspaceRootDeclaredLoaded) {
|
|
1666
|
+
return;
|
|
1667
|
+
}
|
|
1668
|
+
this.workspaceRootDeclaredLoaded = true;
|
|
1669
|
+
const workspaceRoot = this.workspaceDetector.getWorkspaceRoot();
|
|
1670
|
+
if (!workspaceRoot || workspaceRoot === this.options.projectRoot) {
|
|
1671
|
+
return;
|
|
1672
|
+
}
|
|
1673
|
+
const rootPkgJson = readPackageJsonCached(workspaceRoot);
|
|
1674
|
+
if (!rootPkgJson) {
|
|
1675
|
+
return;
|
|
1676
|
+
}
|
|
1677
|
+
this.workspaceRootDeclaredDeps = {
|
|
1678
|
+
...rootPkgJson.dependencies,
|
|
1679
|
+
...rootPkgJson.devDependencies,
|
|
1680
|
+
...rootPkgJson.optionalDependencies
|
|
1681
|
+
};
|
|
1682
|
+
}
|
|
1683
|
+
/**
|
|
1684
|
+
* 判断某个包是否在“主工程”声明(dependencies/devDependencies)
|
|
1685
|
+
*
|
|
1686
|
+
* 默认行为(与 workspace 判断逻辑一致):
|
|
1687
|
+
* - 非 workspace:只看当前 projectRoot 的 package.json
|
|
1688
|
+
* - workspace/monorepo:合并 projectRoot + workspaceRoot 两处 package.json 的声明
|
|
1689
|
+
*/
|
|
1690
|
+
isDeclaredInMainProject(packageName) {
|
|
1691
|
+
return Object.prototype.hasOwnProperty.call(this.declaredDeps, packageName) || Object.prototype.hasOwnProperty.call(this.workspaceRootDeclaredDeps, packageName);
|
|
1692
|
+
}
|
|
1693
|
+
/**
|
|
1694
|
+
* 解析 package.json 中的 npm: 协议别名
|
|
1695
|
+
* 格式:aliasName: "npm:realPackage@version"
|
|
1696
|
+
* 这是识别别名最准确的方式
|
|
1697
|
+
*/
|
|
1698
|
+
parseExistingAliases() {
|
|
1699
|
+
for (const [aliasName, versionSpec] of Object.entries(this.declaredDeps)) {
|
|
1700
|
+
if (typeof versionSpec !== "string") continue;
|
|
1701
|
+
const parsed = parseNpmAlias(versionSpec);
|
|
1702
|
+
if (parsed) {
|
|
1703
|
+
const [targetPackage, version] = parsed;
|
|
1704
|
+
const aliasInfo = {
|
|
1705
|
+
aliasName,
|
|
1706
|
+
targetPackage,
|
|
1707
|
+
versionSpec: version,
|
|
1708
|
+
installedVersion: null
|
|
1709
|
+
// 稍后在需要时填充
|
|
1710
|
+
};
|
|
1711
|
+
const existing = this.existingAliasesMap.get(targetPackage) ?? [];
|
|
1712
|
+
existing.push(aliasInfo);
|
|
1713
|
+
this.existingAliasesMap.set(targetPackage, existing);
|
|
1714
|
+
logger5.debug(`Found npm alias: ${aliasName} -> ${targetPackage}@${version}`);
|
|
1715
|
+
}
|
|
1716
|
+
}
|
|
1717
|
+
if (this.existingAliasesMap.size > 0) {
|
|
1718
|
+
logger5.debug(`Found ${this.existingAliasesMap.size} npm: protocol aliases`);
|
|
1719
|
+
}
|
|
1720
|
+
}
|
|
1721
|
+
/**
|
|
1722
|
+
* 获取别名的已安装版本(懒加载)
|
|
1723
|
+
*/
|
|
1724
|
+
getAliasInstalledVersion(aliasName) {
|
|
1725
|
+
const cached = this.installedPackageCache.get(aliasName);
|
|
1726
|
+
if (cached) {
|
|
1727
|
+
return cached.version;
|
|
1728
|
+
}
|
|
1729
|
+
const { packagePath, pkgJson } = this.resolvePackageJson(aliasName, this.options.projectRoot);
|
|
1730
|
+
if (packagePath && pkgJson?.version) {
|
|
1731
|
+
this.installedPackageCache.set(aliasName, {
|
|
1732
|
+
name: aliasName,
|
|
1733
|
+
version: pkgJson.version,
|
|
1734
|
+
path: packagePath,
|
|
1735
|
+
isAlias: true,
|
|
1736
|
+
realName: pkgJson.name
|
|
1737
|
+
});
|
|
1738
|
+
return pkgJson.version;
|
|
1739
|
+
}
|
|
1740
|
+
return null;
|
|
1741
|
+
}
|
|
1742
|
+
/**
|
|
1743
|
+
* 解析所有 catalog: 协议的依赖版本
|
|
1744
|
+
* 将 catalog:xxx 转换为实际的版本范围
|
|
1745
|
+
*/
|
|
1746
|
+
resolveCatalogDependencies() {
|
|
1747
|
+
for (const [pkgName, versionSpec] of Object.entries(this.rawDeclaredDeps)) {
|
|
1748
|
+
if (typeof versionSpec !== "string") continue;
|
|
1749
|
+
if (versionSpec.startsWith("catalog:")) {
|
|
1750
|
+
const resolved = this.workspaceDetector.resolveVersionSpec(pkgName, versionSpec);
|
|
1751
|
+
if (resolved) {
|
|
1752
|
+
this.declaredDeps[pkgName] = resolved;
|
|
1753
|
+
logger5.debug(`Resolved catalog dependency: ${pkgName} "${versionSpec}" -> "${resolved}"`);
|
|
1754
|
+
} else {
|
|
1755
|
+
logger5.warn(`Failed to resolve catalog dependency: ${pkgName}@${versionSpec}`);
|
|
1756
|
+
}
|
|
1757
|
+
} else if (versionSpec.startsWith("workspace:")) {
|
|
1758
|
+
const resolved = this.workspaceDetector.resolveVersionSpec(pkgName, versionSpec);
|
|
1759
|
+
if (resolved) {
|
|
1760
|
+
this.declaredDeps[pkgName] = resolved;
|
|
1761
|
+
logger5.debug(
|
|
1762
|
+
`Resolved workspace dependency: ${pkgName} "${versionSpec}" -> "${resolved}"`
|
|
1763
|
+
);
|
|
1764
|
+
}
|
|
1765
|
+
}
|
|
1766
|
+
}
|
|
1767
|
+
}
|
|
1768
|
+
/**
|
|
1769
|
+
* 分析依赖并找出冲突
|
|
1770
|
+
*/
|
|
1771
|
+
async analyze() {
|
|
1772
|
+
logger5.info("Starting dependency analysis...");
|
|
1773
|
+
this.watchFiles.clear();
|
|
1774
|
+
this.watchFiles.add(path.join(this.options.projectRoot, "package.json"));
|
|
1775
|
+
try {
|
|
1776
|
+
this.resolveCatalogDependencies();
|
|
1777
|
+
this.ensureWorkspaceRootDeclaredDepsLoaded();
|
|
1778
|
+
const workspaceRoot = this.workspaceDetector.getWorkspaceRoot();
|
|
1779
|
+
if (workspaceRoot) {
|
|
1780
|
+
this.watchFiles.add(path.join(workspaceRoot, "package.json"));
|
|
1781
|
+
const workspaceFile = path.join(workspaceRoot, "pnpm-workspace.yaml");
|
|
1782
|
+
if (fileExists(workspaceFile)) this.watchFiles.add(workspaceFile);
|
|
1783
|
+
}
|
|
1784
|
+
this.dependencyGraph = buildInstalledDependencyGraph(
|
|
1785
|
+
this.options.dependencies,
|
|
1786
|
+
this.options.projectRoot
|
|
1787
|
+
);
|
|
1788
|
+
for (const node of this.dependencyGraph.nodes.values()) {
|
|
1789
|
+
this.watchFiles.add(path.join(node.packagePath, "package.json"));
|
|
1790
|
+
}
|
|
1791
|
+
for (const depName of this.options.dependencies) {
|
|
1792
|
+
this.analyzeDependencyRecursive(depName, []);
|
|
1793
|
+
if (!this.findGraphRoot(depName) && !this.injectedInstalledDeps?.has(depName)) {
|
|
1794
|
+
this.diagnostics.push({
|
|
1795
|
+
code: "DEPENDENCY_NOT_FOUND",
|
|
1796
|
+
severity: "error",
|
|
1797
|
+
packageName: depName,
|
|
1798
|
+
message: "Configured dependency not found: " + depName
|
|
1799
|
+
});
|
|
1800
|
+
}
|
|
1801
|
+
}
|
|
1802
|
+
const peerDepsMap = this.collectFirstLevelPeerDependencies();
|
|
1803
|
+
const peerConflicts = this.analyzePeerConflicts(peerDepsMap);
|
|
1804
|
+
const aliasMappings = await this.generateAliasMappings(peerConflicts);
|
|
1805
|
+
validateSharedPeerContexts(
|
|
1806
|
+
this.dependencyGraph,
|
|
1807
|
+
aliasMappings,
|
|
1808
|
+
this.options,
|
|
1809
|
+
this.diagnostics,
|
|
1810
|
+
this.watchFiles
|
|
1811
|
+
);
|
|
1812
|
+
const missingFirstLevelPeers = this.findMissingFirstLevelPeers(peerDepsMap);
|
|
1813
|
+
const conflictsNeedingAlias = peerConflicts.filter((c) => c.needsAlias).length;
|
|
1814
|
+
logger5.info(
|
|
1815
|
+
`Analysis complete. Found ${conflictsNeedingAlias} first-level peer conflicts needing alias, ${missingFirstLevelPeers.length} missing peers (not auto-installing). Analyzed ${this.analyzedDependencies.size} packages, visited ${this.visitedPackages.size} packages total.`
|
|
1816
|
+
);
|
|
1817
|
+
return {
|
|
1818
|
+
watchFiles: [...this.watchFiles],
|
|
1819
|
+
diagnostics: this.diagnostics,
|
|
1820
|
+
analyzedDependencies: this.analyzedDependencies,
|
|
1821
|
+
peerConflicts,
|
|
1822
|
+
aliasMappings,
|
|
1823
|
+
missingFirstLevelPeers
|
|
1824
|
+
};
|
|
1825
|
+
} finally {
|
|
1826
|
+
clearPackageJsonCache();
|
|
1827
|
+
clearNpmRegistryCache();
|
|
1828
|
+
this.visitedPackages.clear();
|
|
1829
|
+
this.installedPackageCache.clear();
|
|
1830
|
+
this.existingAliasesMap.clear();
|
|
1831
|
+
this.workspaceAliasesCache.clear();
|
|
1832
|
+
this.workspaceRootDeclaredDeps = {};
|
|
1833
|
+
this.rawDeclaredDeps = {};
|
|
1834
|
+
this.declaredDeps = {};
|
|
1835
|
+
this.collectCache.clear();
|
|
1836
|
+
this.dependencyGraph = null;
|
|
1837
|
+
}
|
|
1838
|
+
}
|
|
1839
|
+
/**
|
|
1840
|
+
* 递归分析单个依赖及其所有子依赖
|
|
1841
|
+
*/
|
|
1842
|
+
analyzeDependencyRecursive(packageName, dependencyPath) {
|
|
1843
|
+
const graphRoot = this.findGraphRoot(packageName);
|
|
1844
|
+
if (graphRoot) {
|
|
1845
|
+
this.populateAnalyzedDependenciesFromGraph();
|
|
1846
|
+
return this.analyzedDependencies.get(packageName) ?? null;
|
|
1847
|
+
}
|
|
1848
|
+
if (this.visitedPackages.has(packageName)) {
|
|
1849
|
+
logger5.debug(`Skipping already visited package: ${packageName}`);
|
|
1850
|
+
return this.analyzedDependencies.get(packageName) ?? null;
|
|
1851
|
+
}
|
|
1852
|
+
let rootInfo = null;
|
|
1853
|
+
const stack = [
|
|
1854
|
+
{ name: packageName, path: dependencyPath }
|
|
1855
|
+
];
|
|
1856
|
+
while (stack.length > 0) {
|
|
1857
|
+
const item = stack.pop();
|
|
1858
|
+
if (!item) break;
|
|
1859
|
+
const name = item.name;
|
|
1860
|
+
const path = item.path;
|
|
1861
|
+
if (this.visitedPackages.has(name)) {
|
|
1862
|
+
continue;
|
|
1863
|
+
}
|
|
1864
|
+
this.visitedPackages.add(name);
|
|
1865
|
+
const { packagePath, pkgJson } = this.resolvePackageJson(name, this.options.projectRoot);
|
|
1866
|
+
if (!packagePath) {
|
|
1867
|
+
logger5.debug(`Package not found: ${name}`);
|
|
1868
|
+
continue;
|
|
1869
|
+
}
|
|
1870
|
+
if (!pkgJson) {
|
|
1871
|
+
logger5.debug(`Could not read package.json for: ${name}`);
|
|
1872
|
+
continue;
|
|
1873
|
+
}
|
|
1874
|
+
this.cacheInstalledPackageInfo(name, packagePath, pkgJson);
|
|
1875
|
+
logger5.debug(`Analyzing ${name}@${pkgJson.version}`);
|
|
1876
|
+
const depInfo = {
|
|
1877
|
+
name,
|
|
1878
|
+
version: pkgJson.version ?? "unknown",
|
|
1879
|
+
dependencyPath: [...path],
|
|
1880
|
+
dependencies: { ...pkgJson.dependencies, ...pkgJson.optionalDependencies },
|
|
1881
|
+
peerDependencies: pkgJson.peerDependencies ?? {},
|
|
1882
|
+
peerDependenciesMeta: pkgJson.peerDependenciesMeta
|
|
1883
|
+
};
|
|
1884
|
+
this.analyzedDependencies.set(name, depInfo);
|
|
1885
|
+
if (name === packageName) {
|
|
1886
|
+
rootInfo = depInfo;
|
|
1887
|
+
}
|
|
1888
|
+
const currentPath = [...path, name];
|
|
1889
|
+
const depsToCheck = [
|
|
1890
|
+
...Object.keys({ ...pkgJson.dependencies, ...pkgJson.optionalDependencies }),
|
|
1891
|
+
...Object.keys(pkgJson.peerDependencies ?? {})
|
|
1892
|
+
];
|
|
1893
|
+
for (const depName of depsToCheck) {
|
|
1894
|
+
if (this.visitedPackages.has(depName)) {
|
|
1895
|
+
continue;
|
|
1896
|
+
}
|
|
1897
|
+
stack.push({ name: depName, path: currentPath });
|
|
1898
|
+
}
|
|
1899
|
+
}
|
|
1900
|
+
return rootInfo;
|
|
1901
|
+
}
|
|
1902
|
+
findGraphRoot(packageName) {
|
|
1903
|
+
if (!this.dependencyGraph) return null;
|
|
1904
|
+
const rootId = this.dependencyGraph.rootRequests.get(packageName);
|
|
1905
|
+
return rootId ? this.dependencyGraph.nodes.get(rootId) ?? null : null;
|
|
1906
|
+
}
|
|
1907
|
+
getDependencyPathForGraphNode(node) {
|
|
1908
|
+
if (!this.dependencyGraph) return [];
|
|
1909
|
+
const names = [];
|
|
1910
|
+
let current = node;
|
|
1911
|
+
const visited = /* @__PURE__ */ new Set();
|
|
1912
|
+
while (current && !visited.has(current.id)) {
|
|
1913
|
+
visited.add(current.id);
|
|
1914
|
+
names.unshift(current.name);
|
|
1915
|
+
current = current.parentId ? this.dependencyGraph.nodes.get(current.parentId) : void 0;
|
|
1916
|
+
}
|
|
1917
|
+
return names.slice(0, -1);
|
|
1918
|
+
}
|
|
1919
|
+
populateAnalyzedDependenciesFromGraph() {
|
|
1920
|
+
if (!this.dependencyGraph || this.graphPopulated) return;
|
|
1921
|
+
this.graphPopulated = true;
|
|
1922
|
+
const rootVisibleNodeIds = /* @__PURE__ */ new Map();
|
|
1923
|
+
for (const node of this.dependencyGraph.nodes.values()) {
|
|
1924
|
+
const rootVisiblePath = findPackagePath(node.name, this.options.projectRoot);
|
|
1925
|
+
if (!rootVisiblePath) continue;
|
|
1926
|
+
const rootVisibleNode = this.dependencyGraph.nodes.get(
|
|
1927
|
+
this.normalizeInstalledPath(rootVisiblePath)
|
|
1928
|
+
);
|
|
1929
|
+
if (rootVisibleNode && !rootVisibleNodeIds.has(node.name)) {
|
|
1930
|
+
rootVisibleNodeIds.set(node.name, rootVisibleNode.id);
|
|
1931
|
+
}
|
|
1932
|
+
}
|
|
1933
|
+
const orderedNodes = [];
|
|
1934
|
+
const selectedNodeIds = /* @__PURE__ */ new Set();
|
|
1935
|
+
for (const nodeId of rootVisibleNodeIds.values()) {
|
|
1936
|
+
const node = this.dependencyGraph.nodes.get(nodeId);
|
|
1937
|
+
if (node && !selectedNodeIds.has(node.id)) {
|
|
1938
|
+
selectedNodeIds.add(node.id);
|
|
1939
|
+
orderedNodes.push(node);
|
|
1940
|
+
}
|
|
1941
|
+
}
|
|
1942
|
+
for (const node of this.dependencyGraph.nodes.values()) {
|
|
1943
|
+
if (!selectedNodeIds.has(node.id)) {
|
|
1944
|
+
orderedNodes.push(node);
|
|
1945
|
+
}
|
|
1946
|
+
}
|
|
1947
|
+
for (const node of orderedNodes) {
|
|
1948
|
+
if (this.analyzedDependencies.has(node.name)) continue;
|
|
1949
|
+
const packageJson = readPackageJsonCached(node.packagePath);
|
|
1950
|
+
if (!packageJson) continue;
|
|
1951
|
+
this.cacheInstalledPackageInfo(node.name, node.packagePath, packageJson);
|
|
1952
|
+
this.analyzedDependencies.set(node.name, {
|
|
1953
|
+
name: node.name,
|
|
1954
|
+
version: node.version,
|
|
1955
|
+
dependencyPath: this.getDependencyPathForGraphNode(node),
|
|
1956
|
+
dependencies: { ...packageJson.dependencies, ...packageJson.optionalDependencies },
|
|
1957
|
+
peerDependencies: packageJson.peerDependencies ?? {},
|
|
1958
|
+
peerDependenciesMeta: packageJson.peerDependenciesMeta
|
|
1959
|
+
});
|
|
1960
|
+
this.visitedPackages.add(node.name);
|
|
1961
|
+
}
|
|
1962
|
+
for (const [name, rootId] of this.dependencyGraph.rootRequests) {
|
|
1963
|
+
const node = this.dependencyGraph.nodes.get(rootId);
|
|
1964
|
+
if (!node || node.name === name) continue;
|
|
1965
|
+
const packageJson = readPackageJsonCached(node.packagePath);
|
|
1966
|
+
if (!packageJson) continue;
|
|
1967
|
+
this.cacheInstalledPackageInfo(name, node.packagePath, packageJson);
|
|
1968
|
+
this.analyzedDependencies.set(name, {
|
|
1969
|
+
name,
|
|
1970
|
+
version: node.version,
|
|
1971
|
+
dependencyPath: [],
|
|
1972
|
+
dependencies: { ...packageJson.dependencies, ...packageJson.optionalDependencies },
|
|
1973
|
+
peerDependencies: packageJson.peerDependencies ?? {},
|
|
1974
|
+
peerDependenciesMeta: packageJson.peerDependenciesMeta
|
|
1975
|
+
});
|
|
1976
|
+
this.visitedPackages.add(name);
|
|
1977
|
+
}
|
|
1978
|
+
}
|
|
1979
|
+
/**
|
|
1980
|
+
* 缓存已安装包的信息(用于后续查找别名等)
|
|
1981
|
+
*/
|
|
1982
|
+
cacheInstalledPackageInfo(packageName, packagePath, pkgJson) {
|
|
1983
|
+
if (this.installedPackageCache.has(packageName)) {
|
|
1984
|
+
return;
|
|
1985
|
+
}
|
|
1986
|
+
const info = {
|
|
1987
|
+
name: packageName,
|
|
1988
|
+
version: pkgJson.version ?? "unknown",
|
|
1989
|
+
path: packagePath
|
|
1990
|
+
};
|
|
1991
|
+
if (pkgJson.name && pkgJson.name !== packageName) {
|
|
1992
|
+
info.isAlias = true;
|
|
1993
|
+
info.realName = pkgJson.name;
|
|
1994
|
+
}
|
|
1995
|
+
const declaredSpec = this.declaredDeps[packageName];
|
|
1996
|
+
if (typeof declaredSpec === "string" && declaredSpec.startsWith("npm:")) {
|
|
1997
|
+
info.isAlias = true;
|
|
1998
|
+
info.realName = pkgJson.name;
|
|
1999
|
+
}
|
|
2000
|
+
this.installedPackageCache.set(packageName, info);
|
|
2001
|
+
}
|
|
2002
|
+
/**
|
|
2003
|
+
* 收集第一层依赖的 peer 依赖
|
|
2004
|
+
* 只分析用户指定的 dependencies 的直接 peerDependencies,不分析子依赖的 peerDependencies
|
|
2005
|
+
*
|
|
2006
|
+
* 注意:虽然只收集第一层的 peer 依赖用于冲突检测和别名安装,
|
|
2007
|
+
* 但依赖树仍然会被完整构建,用于后续的重定向判断
|
|
2008
|
+
*/
|
|
2009
|
+
collectFirstLevelPeerDependencies() {
|
|
2010
|
+
const peerDepsMap = /* @__PURE__ */ new Map();
|
|
2011
|
+
const hasInstalledGraphRoots = (this.dependencyGraph?.roots.length ?? 0) > 0;
|
|
2012
|
+
for (const depName of this.options.dependencies) {
|
|
2013
|
+
if (hasInstalledGraphRoots && !this.findGraphRoot(depName)) {
|
|
2014
|
+
logger5.debug(`Skipping non-root configured dependency: ${depName}`);
|
|
2015
|
+
continue;
|
|
2016
|
+
}
|
|
2017
|
+
const depInfo = this.analyzedDependencies.get(depName);
|
|
2018
|
+
if (!depInfo) continue;
|
|
2019
|
+
const peerDeps = depInfo.peerDependencies;
|
|
2020
|
+
const peerMeta = depInfo.peerDependenciesMeta ?? {};
|
|
2021
|
+
for (const [peerName, peerRange] of Object.entries(peerDeps)) {
|
|
2022
|
+
const isOptional = peerMeta[peerName]?.optional === true;
|
|
2023
|
+
if (isOptional) {
|
|
2024
|
+
logger5.debug(
|
|
2025
|
+
`Skipping optional first-level peer dependency: ${peerName}@${peerRange} required by ${depName}`
|
|
2026
|
+
);
|
|
2027
|
+
continue;
|
|
2028
|
+
}
|
|
2029
|
+
const existing = peerDepsMap.get(peerName) ?? [];
|
|
2030
|
+
existing.push({
|
|
2031
|
+
path: [depName],
|
|
2032
|
+
requiredRange: peerRange
|
|
2033
|
+
});
|
|
2034
|
+
peerDepsMap.set(peerName, existing);
|
|
2035
|
+
logger5.debug(
|
|
2036
|
+
`Found first-level peer dependency: ${peerName}@${peerRange} required by ${depName}${isOptional ? " (optional)" : ""}`
|
|
2037
|
+
);
|
|
2038
|
+
}
|
|
2039
|
+
}
|
|
2040
|
+
return peerDepsMap;
|
|
2041
|
+
}
|
|
2042
|
+
/**
|
|
2043
|
+
* 分析 peer 依赖冲突
|
|
2044
|
+
* 只有当主工程已安装某个依赖,且 peerDeps 要求的版本不兼容时,才需要别名
|
|
2045
|
+
*/
|
|
2046
|
+
analyzePeerConflicts(peerDepsMap) {
|
|
2047
|
+
const conflicts = [];
|
|
2048
|
+
for (const [packageName, requestedBy] of peerDepsMap) {
|
|
2049
|
+
const isDeclared = this.isDeclaredInMainProject(packageName);
|
|
2050
|
+
const mainVersion = isDeclared ? this.getMainProjectVersion(packageName) : null;
|
|
2051
|
+
const isInstalled = mainVersion !== null;
|
|
2052
|
+
if (!isDeclared || !isInstalled) {
|
|
2053
|
+
this.diagnostics.push({
|
|
2054
|
+
code: isDeclared ? "PEER_NOT_INSTALLED" : "PEER_NOT_DECLARED",
|
|
2055
|
+
severity: "error",
|
|
2056
|
+
packageName,
|
|
2057
|
+
requestedBy: requestedBy.map((request) => request.path.join(">")),
|
|
2058
|
+
message: packageName + (isDeclared ? " is declared but not installed" : " is not declared by the host")
|
|
2059
|
+
});
|
|
2060
|
+
}
|
|
2061
|
+
const conflictingRanges = [];
|
|
2062
|
+
for (const request of requestedBy) {
|
|
2063
|
+
const resolvedRange = this.workspaceDetector.resolveVersionSpec(packageName, request.requiredRange) ?? request.requiredRange;
|
|
2064
|
+
if (mainVersion && satisfies(mainVersion, resolvedRange)) ; else {
|
|
2065
|
+
conflictingRanges.push({
|
|
2066
|
+
...request,
|
|
2067
|
+
requiredRange: resolvedRange
|
|
2068
|
+
});
|
|
2069
|
+
}
|
|
2070
|
+
}
|
|
2071
|
+
const hasConflict = conflictingRanges.length > 0;
|
|
2072
|
+
const needsAlias = hasConflict && isDeclared && isInstalled;
|
|
2073
|
+
if (needsAlias) {
|
|
2074
|
+
logger5.info(
|
|
2075
|
+
`Peer conflict: ${packageName}@${mainVersion} - ${conflictingRanges.length} incompatible ranges`
|
|
2076
|
+
);
|
|
2077
|
+
}
|
|
2078
|
+
conflicts.push({
|
|
2079
|
+
packageName,
|
|
2080
|
+
mainProjectVersion: mainVersion,
|
|
2081
|
+
requiredRange: this.mergeRequiredRanges(requestedBy),
|
|
2082
|
+
requestedBy,
|
|
2083
|
+
conflictingRanges,
|
|
2084
|
+
hasConflict,
|
|
2085
|
+
needsAlias
|
|
2086
|
+
});
|
|
2087
|
+
}
|
|
2088
|
+
return conflicts;
|
|
2089
|
+
}
|
|
2090
|
+
/**
|
|
2091
|
+
* 获取已安装的包版本(从 node_modules 读取实际版本)
|
|
2092
|
+
* 返回 null 表示包未安装
|
|
2093
|
+
*/
|
|
2094
|
+
getMainProjectVersion(packageName) {
|
|
2095
|
+
const { packagePath, pkgJson } = this.resolvePackageJson(packageName, this.options.projectRoot);
|
|
2096
|
+
if (packagePath && pkgJson?.version) {
|
|
2097
|
+
this.installedPackageCache.set(packageName, {
|
|
2098
|
+
name: packageName,
|
|
2099
|
+
version: pkgJson.version,
|
|
2100
|
+
path: packagePath
|
|
2101
|
+
});
|
|
2102
|
+
return pkgJson.version;
|
|
2103
|
+
}
|
|
2104
|
+
const cached = this.injectedInstalledDeps?.get(packageName);
|
|
2105
|
+
if (cached) {
|
|
2106
|
+
return cached.version;
|
|
2107
|
+
}
|
|
2108
|
+
return null;
|
|
2109
|
+
}
|
|
2110
|
+
/**
|
|
2111
|
+
* 合并多个版本范围为描述字符串
|
|
2112
|
+
*/
|
|
2113
|
+
mergeRequiredRanges(requests) {
|
|
2114
|
+
const ranges = [...new Set(requests.map((r) => r.requiredRange))];
|
|
2115
|
+
return ranges.join(" || ");
|
|
2116
|
+
}
|
|
2117
|
+
/**
|
|
2118
|
+
* 生成别名映射
|
|
2119
|
+
*/
|
|
2120
|
+
async generateAliasMappings(conflicts) {
|
|
2121
|
+
const aliasMappings = [];
|
|
2122
|
+
const usedAliasNames = /* @__PURE__ */ new Set();
|
|
2123
|
+
const aliasNeeded = conflicts.filter((c) => c.needsAlias);
|
|
2124
|
+
const allConflictPackageNames = aliasNeeded.map((c) => c.packageName);
|
|
2125
|
+
for (const conflict of aliasNeeded) {
|
|
2126
|
+
const mappings = await this.createAliasMappingsForConflict(
|
|
2127
|
+
conflict,
|
|
2128
|
+
allConflictPackageNames,
|
|
2129
|
+
usedAliasNames
|
|
2130
|
+
);
|
|
2131
|
+
aliasMappings.push(...mappings);
|
|
2132
|
+
}
|
|
2133
|
+
await linkAliasPeers(
|
|
2134
|
+
aliasMappings,
|
|
2135
|
+
this.options,
|
|
2136
|
+
this.registryClient,
|
|
2137
|
+
this.diagnostics,
|
|
2138
|
+
conflicts,
|
|
2139
|
+
this.watchFiles
|
|
2140
|
+
);
|
|
2141
|
+
return aliasMappings;
|
|
2142
|
+
}
|
|
2143
|
+
/**
|
|
2144
|
+
* 为单个冲突创建别名映射
|
|
2145
|
+
*/
|
|
2146
|
+
async createAliasMappingsForConflict(conflict, allConflictPackageNames, usedAliasNames) {
|
|
2147
|
+
const { packageName, conflictingRanges } = conflict;
|
|
2148
|
+
logger5.info(`Creating alias for "${packageName}"`);
|
|
2149
|
+
const workspaceRoot = this.workspaceDetector.getWorkspaceRoot();
|
|
2150
|
+
if (workspaceRoot) {
|
|
2151
|
+
logger5.info(` Workspace root detected: ${workspaceRoot}`);
|
|
2152
|
+
const wsAliases = this.findWorkspaceAliasesForPackage(packageName);
|
|
2153
|
+
if (wsAliases.length > 0) {
|
|
2154
|
+
logger5.info(` Found ${wsAliases.length} workspace alias(es) for ${packageName}:`);
|
|
2155
|
+
for (const a of wsAliases) {
|
|
2156
|
+
logger5.info(
|
|
2157
|
+
` - ${a.aliasName}: npm:${packageName}@${a.versionSpec} (defined in: ${a.definedIn})`
|
|
2158
|
+
);
|
|
2159
|
+
}
|
|
2160
|
+
} else {
|
|
2161
|
+
logger5.info(
|
|
2162
|
+
` No workspace aliases found for ${packageName} (expected npm:${packageName}@version format in root package.json)`
|
|
2163
|
+
);
|
|
2164
|
+
}
|
|
2165
|
+
} else {
|
|
2166
|
+
logger5.info(` Not in a monorepo workspace`);
|
|
2167
|
+
}
|
|
2168
|
+
const localAliases = this.existingAliasesMap.get(packageName);
|
|
2169
|
+
if (localAliases && localAliases.length > 0) {
|
|
2170
|
+
logger5.info(` Found ${localAliases.length} local alias(es) for ${packageName}:`);
|
|
2171
|
+
for (const a of localAliases) {
|
|
2172
|
+
logger5.info(
|
|
2173
|
+
` - ${a.aliasName}: npm:${packageName}@${a.versionSpec} (installed: ${a.installedVersion ?? "not installed"})`
|
|
2174
|
+
);
|
|
2175
|
+
}
|
|
2176
|
+
}
|
|
2177
|
+
const existingAliasNames = this.getExistingAliasNames(packageName);
|
|
2178
|
+
const mappings = [];
|
|
2179
|
+
const installedAliasMatches = this.findInstalledAliasMatches(packageName);
|
|
2180
|
+
const installedAliasesByName = /* @__PURE__ */ new Map();
|
|
2181
|
+
for (const installedAlias of installedAliasMatches) {
|
|
2182
|
+
const aliases = installedAliasesByName.get(installedAlias.name);
|
|
2183
|
+
if (aliases) {
|
|
2184
|
+
aliases.push(installedAlias);
|
|
2185
|
+
} else {
|
|
2186
|
+
installedAliasesByName.set(installedAlias.name, [installedAlias]);
|
|
2187
|
+
}
|
|
2188
|
+
}
|
|
2189
|
+
for (const [aliasName, aliases] of installedAliasesByName) {
|
|
2190
|
+
const identities = new Set(
|
|
2191
|
+
aliases.map(
|
|
2192
|
+
(alias) => `${alias.installedPath ? this.normalizeInstalledPath(alias.installedPath) : alias.scope}\0${alias.version}`
|
|
2193
|
+
)
|
|
2194
|
+
);
|
|
2195
|
+
if (identities.size < 2) continue;
|
|
2196
|
+
this.diagnostics.push({
|
|
2197
|
+
code: "AMBIGUOUS_ALIAS_SCOPE",
|
|
2198
|
+
severity: "error",
|
|
2199
|
+
packageName,
|
|
2200
|
+
aliases: [aliasName],
|
|
2201
|
+
message: "Alias resolves to multiple installed identities: " + aliasName
|
|
2202
|
+
});
|
|
2203
|
+
logger5.warn(
|
|
2204
|
+
`Alias reuse skipped: ${JSON.stringify({
|
|
2205
|
+
code: "AMBIGUOUS_ALIAS_SCOPE",
|
|
2206
|
+
packageName,
|
|
2207
|
+
aliasName,
|
|
2208
|
+
candidates: aliases.map((alias) => ({
|
|
2209
|
+
installedPath: alias.installedPath ?? null,
|
|
2210
|
+
scope: alias.scope,
|
|
2211
|
+
version: alias.version
|
|
2212
|
+
}))
|
|
2213
|
+
})}`
|
|
2214
|
+
);
|
|
2215
|
+
return [];
|
|
2216
|
+
}
|
|
2217
|
+
const reusedAliasGroups = /* @__PURE__ */ new Map();
|
|
2218
|
+
const unresolvedRequests = [];
|
|
2219
|
+
for (const request of conflictingRanges) {
|
|
2220
|
+
const existingAlias = this.findExistingAliasForRanges(
|
|
2221
|
+
packageName,
|
|
2222
|
+
[request.requiredRange],
|
|
2223
|
+
/* @__PURE__ */ new Set()
|
|
2224
|
+
);
|
|
2225
|
+
if (!existingAlias) {
|
|
2226
|
+
unresolvedRequests.push(request);
|
|
2227
|
+
continue;
|
|
2228
|
+
}
|
|
2229
|
+
usedAliasNames.add(existingAlias.name);
|
|
2230
|
+
const aliasIdentity = `${existingAlias.name}\0${existingAlias.installedPath ? this.normalizeInstalledPath(existingAlias.installedPath) : existingAlias.scope}\0${existingAlias.version}`;
|
|
2231
|
+
const reusedGroup = reusedAliasGroups.get(aliasIdentity);
|
|
2232
|
+
if (reusedGroup) {
|
|
2233
|
+
reusedGroup.requests.push(request);
|
|
2234
|
+
} else {
|
|
2235
|
+
reusedAliasGroups.set(aliasIdentity, {
|
|
2236
|
+
alias: existingAlias,
|
|
2237
|
+
requests: [request]
|
|
2238
|
+
});
|
|
2239
|
+
}
|
|
2240
|
+
}
|
|
2241
|
+
const reusedGroupsByAliasName = /* @__PURE__ */ new Map();
|
|
2242
|
+
for (const reusedGroup of reusedAliasGroups.values()) {
|
|
2243
|
+
const groups = reusedGroupsByAliasName.get(reusedGroup.alias.name);
|
|
2244
|
+
if (groups) {
|
|
2245
|
+
groups.push(reusedGroup);
|
|
2246
|
+
} else {
|
|
2247
|
+
reusedGroupsByAliasName.set(reusedGroup.alias.name, [reusedGroup]);
|
|
2248
|
+
}
|
|
2249
|
+
}
|
|
2250
|
+
for (const [aliasName, groups] of reusedGroupsByAliasName) {
|
|
2251
|
+
if (groups.length < 2) continue;
|
|
2252
|
+
this.diagnostics.push({
|
|
2253
|
+
code: "AMBIGUOUS_ALIAS_SCOPE",
|
|
2254
|
+
severity: "error",
|
|
2255
|
+
packageName,
|
|
2256
|
+
aliases: [aliasName],
|
|
2257
|
+
message: "Alias resolves to multiple installed identities: " + aliasName
|
|
2258
|
+
});
|
|
2259
|
+
logger5.warn(
|
|
2260
|
+
`Alias reuse skipped: ${JSON.stringify({
|
|
2261
|
+
code: "AMBIGUOUS_ALIAS_SCOPE",
|
|
2262
|
+
packageName,
|
|
2263
|
+
aliasName,
|
|
2264
|
+
candidates: groups.map(({ alias, requests }) => ({
|
|
2265
|
+
installedPath: alias.installedPath ?? null,
|
|
2266
|
+
scope: alias.scope,
|
|
2267
|
+
version: alias.version,
|
|
2268
|
+
requesters: requests.map((request) => request.path.join(">"))
|
|
2269
|
+
}))
|
|
2270
|
+
})}`
|
|
2271
|
+
);
|
|
2272
|
+
return [];
|
|
2273
|
+
}
|
|
2274
|
+
for (const reusedGroup of reusedAliasGroups.values()) {
|
|
2275
|
+
mappings.push(
|
|
2276
|
+
this.buildAliasMapping(
|
|
2277
|
+
packageName,
|
|
2278
|
+
reusedGroup.alias.name,
|
|
2279
|
+
reusedGroup.alias.version,
|
|
2280
|
+
"",
|
|
2281
|
+
// 不需要安装
|
|
2282
|
+
reusedGroup.requests,
|
|
2283
|
+
allConflictPackageNames
|
|
2284
|
+
)
|
|
2285
|
+
);
|
|
2286
|
+
}
|
|
2287
|
+
if (unresolvedRequests.length === 0) {
|
|
2288
|
+
return mappings;
|
|
2289
|
+
}
|
|
2290
|
+
if (this.options.offline) {
|
|
2291
|
+
this.diagnostics.push({
|
|
2292
|
+
code: "OFFLINE_ALIAS_MISSING",
|
|
2293
|
+
severity: "error",
|
|
2294
|
+
packageName,
|
|
2295
|
+
requestedBy: unresolvedRequests.map((request) => request.path.join(">")),
|
|
2296
|
+
message: "No installed alias satisfies " + packageName + " in offline mode"
|
|
2297
|
+
});
|
|
2298
|
+
return mappings;
|
|
2299
|
+
}
|
|
2300
|
+
let versions;
|
|
2301
|
+
try {
|
|
2302
|
+
versions = await this.registryClient.fetchAllVersions(packageName, this.options.registry);
|
|
2303
|
+
} catch (error) {
|
|
2304
|
+
this.diagnostics.push({
|
|
2305
|
+
code: "REGISTRY_ERROR",
|
|
2306
|
+
severity: "error",
|
|
2307
|
+
packageName,
|
|
2308
|
+
message: "Failed to fetch versions for " + packageName + ": " + String(error)
|
|
2309
|
+
});
|
|
2310
|
+
logger5.warn(`Failed to fetch versions for ${packageName}: ${String(error)}`);
|
|
2311
|
+
return mappings;
|
|
2312
|
+
}
|
|
2313
|
+
if (versions.length === 0) {
|
|
2314
|
+
this.diagnostics.push({
|
|
2315
|
+
code: "NO_MATCHING_VERSION",
|
|
2316
|
+
severity: "error",
|
|
2317
|
+
packageName,
|
|
2318
|
+
message: "No versions available for " + packageName
|
|
2319
|
+
});
|
|
2320
|
+
logger5.warn(`No versions found for ${packageName}`);
|
|
2321
|
+
return mappings;
|
|
2322
|
+
}
|
|
2323
|
+
for (const request of unresolvedRequests) {
|
|
2324
|
+
if (!versions.some((version) => satisfies(version, request.requiredRange))) {
|
|
2325
|
+
this.diagnostics.push({
|
|
2326
|
+
code: "NO_MATCHING_VERSION",
|
|
2327
|
+
severity: "error",
|
|
2328
|
+
packageName,
|
|
2329
|
+
requestedBy: request.path,
|
|
2330
|
+
message: "No available version satisfies " + packageName + "@" + request.requiredRange
|
|
2331
|
+
});
|
|
2332
|
+
}
|
|
2333
|
+
}
|
|
2334
|
+
const rangeGroups = this.groupRangesByCompatibility(unresolvedRequests, versions);
|
|
2335
|
+
logger5.info(`Creating alias for "${packageName}": ${rangeGroups.length} version groups`);
|
|
2336
|
+
for (let i = 0; i < rangeGroups.length; i++) {
|
|
2337
|
+
const group = rangeGroups[i];
|
|
2338
|
+
if (!group || group.length === 0) continue;
|
|
2339
|
+
const groupRanges = [...new Set(group.map((r) => r.requiredRange))];
|
|
2340
|
+
logger5.debug(` Group ${i + 1}: ${groupRanges.join(", ")}`);
|
|
2341
|
+
const mapping = this.createAliasMappingForGroup(
|
|
2342
|
+
packageName,
|
|
2343
|
+
group,
|
|
2344
|
+
groupRanges,
|
|
2345
|
+
versions,
|
|
2346
|
+
existingAliasNames,
|
|
2347
|
+
usedAliasNames,
|
|
2348
|
+
allConflictPackageNames
|
|
2349
|
+
);
|
|
2350
|
+
if (mapping) {
|
|
2351
|
+
mappings.push(mapping);
|
|
2352
|
+
usedAliasNames.add(mapping.aliasName);
|
|
2353
|
+
}
|
|
2354
|
+
}
|
|
2355
|
+
return mappings;
|
|
2356
|
+
}
|
|
2357
|
+
/**
|
|
2358
|
+
* 按范围兼容性分组
|
|
2359
|
+
* 有交集的范围放在一组,互斥的分开
|
|
2360
|
+
*/
|
|
2361
|
+
groupRangesByCompatibility(requests, availableVersions) {
|
|
2362
|
+
const groups = [];
|
|
2363
|
+
const orderedRequests = requests.map((request, index) => ({
|
|
2364
|
+
request,
|
|
2365
|
+
index,
|
|
2366
|
+
satisfyingVersionCount: availableVersions.filter(
|
|
2367
|
+
(version) => satisfies(version, request.requiredRange)
|
|
2368
|
+
).length
|
|
2369
|
+
})).sort(
|
|
2370
|
+
(left, right) => left.satisfyingVersionCount - right.satisfyingVersionCount || left.index - right.index
|
|
2371
|
+
);
|
|
2372
|
+
for (const { request } of orderedRequests) {
|
|
2373
|
+
let added = false;
|
|
2374
|
+
for (const group of groups) {
|
|
2375
|
+
const proposedRanges = [...group, request].map((item) => item.requiredRange);
|
|
2376
|
+
const canJoin = findBestVersion(availableVersions, proposedRanges) !== null;
|
|
2377
|
+
if (canJoin) {
|
|
2378
|
+
group.push(request);
|
|
2379
|
+
added = true;
|
|
2380
|
+
break;
|
|
2381
|
+
}
|
|
2382
|
+
}
|
|
2383
|
+
if (!added) {
|
|
2384
|
+
if (findBestVersion(availableVersions, [request.requiredRange]) === null) {
|
|
2385
|
+
continue;
|
|
2386
|
+
}
|
|
2387
|
+
groups.push([request]);
|
|
2388
|
+
}
|
|
2389
|
+
}
|
|
2390
|
+
return groups;
|
|
2391
|
+
}
|
|
2392
|
+
/**
|
|
2393
|
+
* 为一个兼容组创建别名映射
|
|
2394
|
+
*/
|
|
2395
|
+
createAliasMappingForGroup(packageName, group, groupRanges, versions, existingAliasNames, usedAliasNames, allConflictPackageNames) {
|
|
2396
|
+
const existingAlias = this.findExistingAliasForRanges(packageName, groupRanges, usedAliasNames);
|
|
2397
|
+
if (existingAlias) {
|
|
2398
|
+
logger5.debug(
|
|
2399
|
+
` Reusing: ${existingAlias.name}@${existingAlias.version}${existingAlias.isWorkspaceAlias ? " (workspace)" : ""}`
|
|
2400
|
+
);
|
|
2401
|
+
return this.buildAliasMapping(
|
|
2402
|
+
packageName,
|
|
2403
|
+
existingAlias.name,
|
|
2404
|
+
existingAlias.version,
|
|
2405
|
+
"",
|
|
2406
|
+
// 不需要安装
|
|
2407
|
+
group,
|
|
2408
|
+
allConflictPackageNames
|
|
2409
|
+
);
|
|
2410
|
+
}
|
|
2411
|
+
const bestVersion = findBestVersion(versions, groupRanges);
|
|
2412
|
+
if (!bestVersion) {
|
|
2413
|
+
logger5.warn(
|
|
2414
|
+
` No version satisfies all ranges [${groupRanges.join(", ")}] for ${packageName}`
|
|
2415
|
+
);
|
|
2416
|
+
return null;
|
|
2417
|
+
}
|
|
2418
|
+
const combinedExisting = /* @__PURE__ */ new Set([
|
|
2419
|
+
...existingAliasNames,
|
|
2420
|
+
...usedAliasNames,
|
|
2421
|
+
...this.getReservedDependencyNames()
|
|
2422
|
+
]);
|
|
2423
|
+
const aliasName = this.generateUniqueAliasName(packageName, bestVersion, combinedExisting);
|
|
2424
|
+
const installSpec = createAliasInstallSpec(aliasName, packageName, bestVersion);
|
|
2425
|
+
logger5.info(` New alias: ${aliasName}@${bestVersion}`);
|
|
2426
|
+
return this.buildAliasMapping(
|
|
2427
|
+
packageName,
|
|
2428
|
+
aliasName,
|
|
2429
|
+
bestVersion,
|
|
2430
|
+
installSpec,
|
|
2431
|
+
group,
|
|
2432
|
+
allConflictPackageNames
|
|
2433
|
+
);
|
|
2434
|
+
}
|
|
2435
|
+
/**
|
|
2436
|
+
* 构建 AliasMapping 对象
|
|
2437
|
+
*/
|
|
2438
|
+
buildAliasMapping(packageName, aliasName, version, installSpec, group, allConflictPackageNames) {
|
|
2439
|
+
const usedBy = group.map((r) => r.path.join(">"));
|
|
2440
|
+
const usedByRoots = [
|
|
2441
|
+
...new Set(group.map((r) => r.path[0]).filter((p) => p !== void 0))
|
|
2442
|
+
];
|
|
2443
|
+
const graphInstances = this.collectGraphRelatedPackageInstances(
|
|
2444
|
+
usedByRoots,
|
|
2445
|
+
allConflictPackageNames
|
|
2446
|
+
);
|
|
2447
|
+
const allDependents = graphInstances ? [...new Set(graphInstances.map((instance) => instance.name))] : this.collectAllRelatedPackages(usedByRoots, allConflictPackageNames);
|
|
2448
|
+
return {
|
|
2449
|
+
originalName: packageName,
|
|
2450
|
+
aliasName,
|
|
2451
|
+
installSpec,
|
|
2452
|
+
resolvedVersion: version,
|
|
2453
|
+
usedBy,
|
|
2454
|
+
allDependents,
|
|
2455
|
+
...graphInstances && graphInstances.length > 0 ? { importerPaths: [...new Set(graphInstances.map((instance) => instance.path))] } : {}
|
|
2456
|
+
};
|
|
2457
|
+
}
|
|
2458
|
+
/**
|
|
2459
|
+
* 收集所有已安装的现有别名,不按请求版本范围过滤。
|
|
2460
|
+
* 用于在范围筛选前识别同名 alias 的多路径/多版本歧义。
|
|
2461
|
+
*/
|
|
2462
|
+
findInstalledAliasMatches(packageName) {
|
|
2463
|
+
const matches = [];
|
|
2464
|
+
const npmAliases = this.existingAliasesMap.get(packageName) ?? [];
|
|
2465
|
+
for (const alias of npmAliases) {
|
|
2466
|
+
alias.installedVersion ??= this.getAliasInstalledVersion(alias.aliasName);
|
|
2467
|
+
if (!alias.installedVersion) continue;
|
|
2468
|
+
const installedAlias = this.installedPackageCache.get(alias.aliasName);
|
|
2469
|
+
if (installedAlias?.realName !== packageName) continue;
|
|
2470
|
+
matches.push({
|
|
2471
|
+
name: alias.aliasName,
|
|
2472
|
+
version: alias.installedVersion,
|
|
2473
|
+
installedPath: installedAlias?.path,
|
|
2474
|
+
scope: "local"
|
|
2475
|
+
});
|
|
2476
|
+
}
|
|
2477
|
+
const workspaceAliases = this.findWorkspaceAliasesForPackage(packageName);
|
|
2478
|
+
const workspaceRoot = this.workspaceDetector.getWorkspaceRoot();
|
|
2479
|
+
for (const wsAlias of workspaceAliases) {
|
|
2480
|
+
let installedVersion = null;
|
|
2481
|
+
let installedPath;
|
|
2482
|
+
if (workspaceRoot) {
|
|
2483
|
+
const { packagePath, pkgJson } = this.resolvePackageJson(wsAlias.aliasName, workspaceRoot);
|
|
2484
|
+
if (packagePath) {
|
|
2485
|
+
if (pkgJson?.name !== packageName) continue;
|
|
2486
|
+
installedVersion = pkgJson?.version ?? null;
|
|
2487
|
+
installedPath = packagePath;
|
|
2488
|
+
}
|
|
2489
|
+
}
|
|
2490
|
+
if (!installedVersion) {
|
|
2491
|
+
installedVersion = this.getAliasInstalledVersion(wsAlias.aliasName);
|
|
2492
|
+
if (installedVersion) {
|
|
2493
|
+
const installedAlias = this.installedPackageCache.get(wsAlias.aliasName);
|
|
2494
|
+
installedPath = installedAlias?.path;
|
|
2495
|
+
if (installedAlias?.realName !== packageName) continue;
|
|
2496
|
+
}
|
|
2497
|
+
}
|
|
2498
|
+
if (installedVersion) {
|
|
2499
|
+
matches.push({
|
|
2500
|
+
name: wsAlias.aliasName,
|
|
2501
|
+
version: installedVersion,
|
|
2502
|
+
isWorkspaceAlias: true,
|
|
2503
|
+
installedPath,
|
|
2504
|
+
scope: "workspace"
|
|
2505
|
+
});
|
|
2506
|
+
}
|
|
2507
|
+
}
|
|
2508
|
+
return matches;
|
|
2509
|
+
}
|
|
2510
|
+
/**
|
|
2511
|
+
* 查找满足指定范围的现有别名(排除已使用的)
|
|
2512
|
+
* 优先查找当前项目的别名,然后查找 workspace 级别的别名
|
|
2513
|
+
*/
|
|
2514
|
+
findExistingAliasForRanges(packageName, ranges, excludeAliases) {
|
|
2515
|
+
logger5.debug(
|
|
2516
|
+
` Searching for existing alias for ${packageName} satisfying ranges: [${ranges.join(", ")}]`
|
|
2517
|
+
);
|
|
2518
|
+
const npmAliases = this.existingAliasesMap.get(packageName);
|
|
2519
|
+
if (npmAliases && npmAliases.length > 0) {
|
|
2520
|
+
logger5.debug(` Checking ${npmAliases.length} local alias(es)...`);
|
|
2521
|
+
for (const alias of npmAliases) {
|
|
2522
|
+
if (excludeAliases.has(alias.aliasName)) {
|
|
2523
|
+
logger5.debug(` Skip ${alias.aliasName}: already used`);
|
|
2524
|
+
continue;
|
|
2525
|
+
}
|
|
2526
|
+
alias.installedVersion ??= this.getAliasInstalledVersion(alias.aliasName);
|
|
2527
|
+
if (!alias.installedVersion) {
|
|
2528
|
+
logger5.debug(` Skip ${alias.aliasName}: not installed`);
|
|
2529
|
+
continue;
|
|
2530
|
+
}
|
|
2531
|
+
const installedAlias = this.installedPackageCache.get(alias.aliasName);
|
|
2532
|
+
if (installedAlias?.realName !== packageName) {
|
|
2533
|
+
logger5.debug(
|
|
2534
|
+
` Skip ${alias.aliasName}: installed package name ${installedAlias?.realName ?? "unknown"} does not match ${packageName}`
|
|
2535
|
+
);
|
|
2536
|
+
continue;
|
|
2537
|
+
}
|
|
2538
|
+
const allSatisfied = ranges.every((range) => satisfies(alias.installedVersion, range));
|
|
2539
|
+
if (allSatisfied) {
|
|
2540
|
+
logger5.info(` Reusing local alias: ${alias.aliasName}@${alias.installedVersion}`);
|
|
2541
|
+
return {
|
|
2542
|
+
name: alias.aliasName,
|
|
2543
|
+
version: alias.installedVersion,
|
|
2544
|
+
installedPath: installedAlias?.path,
|
|
2545
|
+
scope: "local"
|
|
2546
|
+
};
|
|
2547
|
+
} else {
|
|
2548
|
+
logger5.debug(
|
|
2549
|
+
` Skip ${alias.aliasName}@${alias.installedVersion}: version doesn't satisfy all ranges`
|
|
2550
|
+
);
|
|
2551
|
+
}
|
|
2552
|
+
}
|
|
2553
|
+
}
|
|
2554
|
+
const workspaceAliases = this.findWorkspaceAliasesForPackage(packageName);
|
|
2555
|
+
if (workspaceAliases.length > 0) {
|
|
2556
|
+
logger5.debug(` Checking ${workspaceAliases.length} workspace alias(es)...`);
|
|
2557
|
+
}
|
|
2558
|
+
for (const wsAlias of workspaceAliases) {
|
|
2559
|
+
if (excludeAliases.has(wsAlias.aliasName)) {
|
|
2560
|
+
logger5.debug(` Skip ${wsAlias.aliasName}: already used`);
|
|
2561
|
+
continue;
|
|
2562
|
+
}
|
|
2563
|
+
const { packagePath, pkgJson } = this.resolvePackageJson(
|
|
2564
|
+
wsAlias.aliasName,
|
|
2565
|
+
this.options.projectRoot
|
|
2566
|
+
);
|
|
2567
|
+
if (!packagePath || pkgJson?.name !== packageName || !pkgJson.version) continue;
|
|
2568
|
+
const installedVersion = pkgJson.version;
|
|
2569
|
+
if (ranges.every((range) => satisfies(installedVersion, range))) {
|
|
2570
|
+
logger5.info(` Reusing workspace alias: ${wsAlias.aliasName}@${installedVersion}`);
|
|
2571
|
+
return {
|
|
2572
|
+
name: wsAlias.aliasName,
|
|
2573
|
+
version: installedVersion,
|
|
2574
|
+
isWorkspaceAlias: true,
|
|
2575
|
+
installedPath: packagePath,
|
|
2576
|
+
scope: "workspace"
|
|
2577
|
+
};
|
|
2578
|
+
}
|
|
2579
|
+
}
|
|
2580
|
+
logger5.debug(` No existing alias found for ${packageName}`);
|
|
2581
|
+
return null;
|
|
2582
|
+
}
|
|
2583
|
+
/**
|
|
2584
|
+
* 查找 workspace 级别的别名(带缓存)
|
|
2585
|
+
*/
|
|
2586
|
+
findWorkspaceAliasesForPackage(packageName) {
|
|
2587
|
+
if (this.workspaceAliasesCache.has(packageName)) {
|
|
2588
|
+
return this.workspaceAliasesCache.get(packageName);
|
|
2589
|
+
}
|
|
2590
|
+
const aliases = this.workspaceDetector.findWorkspaceAliases(packageName);
|
|
2591
|
+
this.workspaceAliasesCache.set(packageName, aliases);
|
|
2592
|
+
return aliases;
|
|
2593
|
+
}
|
|
2594
|
+
/**
|
|
2595
|
+
* 生成唯一的别名名称,避免与已存在的别名冲突
|
|
2596
|
+
*/
|
|
2597
|
+
generateUniqueAliasName(packageName, version, existingNames) {
|
|
2598
|
+
const baseName = `${this.options.aliasPrefix}${generateAliasName(packageName, version)}`;
|
|
2599
|
+
if (!existingNames.has(baseName)) {
|
|
2600
|
+
return baseName;
|
|
2601
|
+
}
|
|
2602
|
+
const versionSuffix = version.replace(/\./g, "-");
|
|
2603
|
+
const nameWithVersion = `${this.options.aliasPrefix}${packageName.replace(/^@/, "").replace(/\//g, "-")}-${versionSuffix}`;
|
|
2604
|
+
if (!existingNames.has(nameWithVersion)) {
|
|
2605
|
+
return nameWithVersion;
|
|
2606
|
+
}
|
|
2607
|
+
let counter = 2;
|
|
2608
|
+
while (existingNames.has(`${baseName}-${counter}`)) {
|
|
2609
|
+
counter++;
|
|
2610
|
+
}
|
|
2611
|
+
return `${baseName}-${counter}`;
|
|
2612
|
+
}
|
|
2613
|
+
/**
|
|
2614
|
+
* 获取包的所有已存在的别名名称(不管版本是否符合)
|
|
2615
|
+
* 用于生成新别名时避免命名冲突
|
|
2616
|
+
*
|
|
2617
|
+
* 包含当前项目和 workspace 级别的别名
|
|
2618
|
+
*/
|
|
2619
|
+
getExistingAliasNames(packageName) {
|
|
2620
|
+
const names = /* @__PURE__ */ new Set();
|
|
2621
|
+
const npmAliases = this.existingAliasesMap.get(packageName);
|
|
2622
|
+
if (npmAliases) {
|
|
2623
|
+
for (const alias of npmAliases) {
|
|
2624
|
+
names.add(alias.aliasName);
|
|
2625
|
+
}
|
|
2626
|
+
}
|
|
2627
|
+
const workspaceAliases = this.findWorkspaceAliasesForPackage(packageName);
|
|
2628
|
+
for (const wsAlias of workspaceAliases) {
|
|
2629
|
+
names.add(wsAlias.aliasName);
|
|
2630
|
+
}
|
|
2631
|
+
return names;
|
|
2632
|
+
}
|
|
2633
|
+
/**
|
|
2634
|
+
* Return every dependency key that the host or its workspace root owns.
|
|
2635
|
+
*
|
|
2636
|
+
* Generated aliases share the package namespace with ordinary dependency
|
|
2637
|
+
* keys. Keeping the complete set here prevents a generated alias from
|
|
2638
|
+
* silently replacing an unrelated dependency declared by the user.
|
|
2639
|
+
*/
|
|
2640
|
+
getReservedDependencyNames() {
|
|
2641
|
+
this.ensureWorkspaceRootDeclaredDepsLoaded();
|
|
2642
|
+
return /* @__PURE__ */ new Set([
|
|
2643
|
+
...Object.keys(this.rawDeclaredDeps),
|
|
2644
|
+
...Object.keys(this.declaredDeps),
|
|
2645
|
+
...Object.keys(this.workspaceRootDeclaredDeps)
|
|
2646
|
+
]);
|
|
2647
|
+
}
|
|
2648
|
+
normalizeInstalledPath(packagePath) {
|
|
2649
|
+
try {
|
|
2650
|
+
return fs.realpathSync(packagePath);
|
|
2651
|
+
} catch {
|
|
2652
|
+
return path.resolve(packagePath);
|
|
2653
|
+
}
|
|
2654
|
+
}
|
|
2655
|
+
findGraphChildNode(parent, dependencyName) {
|
|
2656
|
+
if (!this.dependencyGraph) return null;
|
|
2657
|
+
const childId = parent.resolvedChildren.get(dependencyName);
|
|
2658
|
+
return childId ? this.dependencyGraph.nodes.get(childId) ?? null : null;
|
|
2659
|
+
}
|
|
2660
|
+
/**
|
|
2661
|
+
* 收集图中指定根实例的所有后代实例。返回 null 表示当前分析没有
|
|
2662
|
+
* 对应的图根,调用方可为兼容旧测试/旧调用回退到名称遍历。
|
|
2663
|
+
*/
|
|
2664
|
+
collectGraphRelatedPackageInstances(packageNames, excludePackages = []) {
|
|
2665
|
+
if (!this.dependencyGraph) return null;
|
|
2666
|
+
const roots = packageNames.map((packageName) => this.findGraphRoot(packageName)).filter((node) => node !== null);
|
|
2667
|
+
if (roots.length === 0) return null;
|
|
2668
|
+
const excludeSet = new Set(excludePackages);
|
|
2669
|
+
const visited = /* @__PURE__ */ new Set();
|
|
2670
|
+
const collected = [];
|
|
2671
|
+
const stack = roots.map((root) => root.id);
|
|
2672
|
+
while (stack.length > 0) {
|
|
2673
|
+
const nodeId = stack.pop();
|
|
2674
|
+
if (!nodeId || visited.has(nodeId)) continue;
|
|
2675
|
+
visited.add(nodeId);
|
|
2676
|
+
const node = this.dependencyGraph.nodes.get(nodeId);
|
|
2677
|
+
if (!node || excludeSet.has(node.name)) continue;
|
|
2678
|
+
collected.push({ name: node.name, path: node.packagePath });
|
|
2679
|
+
for (const dependencyName of [...node.dependencyNames, ...node.peerDependencyNames]) {
|
|
2680
|
+
const child = this.findGraphChildNode(node, dependencyName);
|
|
2681
|
+
if (child && !visited.has(child.id)) stack.push(child.id);
|
|
2682
|
+
}
|
|
2683
|
+
}
|
|
2684
|
+
return collected;
|
|
2685
|
+
}
|
|
2686
|
+
/**
|
|
2687
|
+
* 递归收集指定包的所有子依赖(dependencies + peerDependencies)
|
|
2688
|
+
*
|
|
2689
|
+
* 用于构建 allDependents 列表,这些包引用冲突依赖时都需要做重定向解析
|
|
2690
|
+
*
|
|
2691
|
+
* 逻辑说明:
|
|
2692
|
+
* - 冲突检测:只检测第一层依赖的 peerDependencies 与主工程的冲突
|
|
2693
|
+
* - 重定向范围:声明冲突 peerDep 的包及其所有子依赖都需要重定向
|
|
2694
|
+
* 因为这些子依赖内部引用冲突包时,也需要解析到别名版本
|
|
2695
|
+
* - 遇到冲突包(excludeTraversal)时,不加入 collected 也不遍历其子树,
|
|
2696
|
+
* 因为 analyzedDependencies 中存储的是主项目安装的版本(而非冲突库实际需要的版本),
|
|
2697
|
+
* 遍历它们会引入无关包(如 vue-router@5 的 peerDep pinia)
|
|
2698
|
+
*
|
|
2699
|
+
* 性能优化:优先从 analyzedDependencies 内存数据中读取,避免重复磁盘 I/O
|
|
2700
|
+
*/
|
|
2701
|
+
collectAllSubDependenciesRecursive(packageName, visited, collected, baseDir, excludeTraversal) {
|
|
2702
|
+
const stack = [{ name: packageName, baseDir }];
|
|
2703
|
+
while (stack.length > 0) {
|
|
2704
|
+
const item = stack.pop();
|
|
2705
|
+
if (!item) break;
|
|
2706
|
+
const name = item.name;
|
|
2707
|
+
const currentBaseDir = item.baseDir;
|
|
2708
|
+
if (excludeTraversal?.has(name)) {
|
|
2709
|
+
continue;
|
|
2710
|
+
}
|
|
2711
|
+
collected.add(name);
|
|
2712
|
+
const analyzed = this.analyzedDependencies.get(name);
|
|
2713
|
+
if (analyzed) {
|
|
2714
|
+
if (visited.has(name)) {
|
|
2715
|
+
continue;
|
|
2716
|
+
}
|
|
2717
|
+
visited.add(name);
|
|
2718
|
+
for (const depName of Object.keys(analyzed.dependencies)) {
|
|
2719
|
+
stack.push({ name: depName, baseDir: currentBaseDir });
|
|
2720
|
+
}
|
|
2721
|
+
for (const peerName of Object.keys(analyzed.peerDependencies)) {
|
|
2722
|
+
stack.push({ name: peerName, baseDir: currentBaseDir });
|
|
2723
|
+
}
|
|
2724
|
+
continue;
|
|
2725
|
+
}
|
|
2726
|
+
const { packagePath, pkgJson } = this.resolvePackageJson(name, currentBaseDir);
|
|
2727
|
+
if (!packagePath) {
|
|
2728
|
+
logger5.debug(
|
|
2729
|
+
`Package not found for dependency collection: ${name} (from ${currentBaseDir})`
|
|
2730
|
+
);
|
|
2731
|
+
continue;
|
|
2732
|
+
}
|
|
2733
|
+
if (visited.has(packagePath)) {
|
|
2734
|
+
continue;
|
|
2735
|
+
}
|
|
2736
|
+
visited.add(packagePath);
|
|
2737
|
+
if (!pkgJson) {
|
|
2738
|
+
continue;
|
|
2739
|
+
}
|
|
2740
|
+
const deps = { ...pkgJson.dependencies, ...pkgJson.optionalDependencies };
|
|
2741
|
+
const peerDeps = pkgJson.peerDependencies ?? {};
|
|
2742
|
+
for (const depName of Object.keys(deps)) {
|
|
2743
|
+
stack.push({ name: depName, baseDir: packagePath });
|
|
2744
|
+
}
|
|
2745
|
+
for (const peerName of Object.keys(peerDeps)) {
|
|
2746
|
+
stack.push({ name: peerName, baseDir: packagePath });
|
|
2747
|
+
}
|
|
2748
|
+
}
|
|
2749
|
+
}
|
|
2750
|
+
/**
|
|
2751
|
+
* 收集多个包的所有子依赖(用于 allDependents)
|
|
2752
|
+
* 包括 dependencies 和 peerDependencies 递归下去的所有包
|
|
2753
|
+
*/
|
|
2754
|
+
collectAllRelatedPackages(packageNames, excludePackages = []) {
|
|
2755
|
+
const cacheKey = JSON.stringify([packageNames.slice().sort(), excludePackages.slice().sort()]);
|
|
2756
|
+
const cached = this.collectCache.get(cacheKey);
|
|
2757
|
+
if (cached) {
|
|
2758
|
+
return cached;
|
|
2759
|
+
}
|
|
2760
|
+
const graphInstances = this.collectGraphRelatedPackageInstances(packageNames, excludePackages);
|
|
2761
|
+
if (graphInstances) {
|
|
2762
|
+
const result2 = [...new Set(graphInstances.map((instance) => instance.name))];
|
|
2763
|
+
this.collectCache.set(cacheKey, result2);
|
|
2764
|
+
return result2;
|
|
2765
|
+
}
|
|
2766
|
+
const collected = /* @__PURE__ */ new Set();
|
|
2767
|
+
const visited = /* @__PURE__ */ new Set();
|
|
2768
|
+
const excludeSet = new Set(excludePackages);
|
|
2769
|
+
for (const pkgName of packageNames) {
|
|
2770
|
+
this.collectAllSubDependenciesRecursive(
|
|
2771
|
+
pkgName,
|
|
2772
|
+
visited,
|
|
2773
|
+
collected,
|
|
2774
|
+
this.options.projectRoot,
|
|
2775
|
+
excludeSet
|
|
2776
|
+
);
|
|
2777
|
+
}
|
|
2778
|
+
for (const excludePkg of excludeSet) {
|
|
2779
|
+
collected.delete(excludePkg);
|
|
2780
|
+
}
|
|
2781
|
+
const result = Array.from(collected);
|
|
2782
|
+
this.collectCache.set(cacheKey, result);
|
|
2783
|
+
return result;
|
|
2784
|
+
}
|
|
2785
|
+
/**
|
|
2786
|
+
* 找出第一层依赖中缺失的 peer 依赖(无冲突)
|
|
2787
|
+
* 复用 collectFirstLevelPeerDependencies 已收集的 peerDepsMap,避免重复遍历
|
|
2788
|
+
*/
|
|
2789
|
+
findMissingFirstLevelPeers(peerDepsMap) {
|
|
2790
|
+
const missing = [];
|
|
2791
|
+
for (const [peerName, requests] of peerDepsMap) {
|
|
2792
|
+
if (this.isDeclaredInMainProject(peerName)) {
|
|
2793
|
+
continue;
|
|
2794
|
+
}
|
|
2795
|
+
for (const request of requests) {
|
|
2796
|
+
const requestedBy = request.path[0];
|
|
2797
|
+
if (!requestedBy) continue;
|
|
2798
|
+
const depInfo = this.analyzedDependencies.get(requestedBy);
|
|
2799
|
+
const isOptional = depInfo?.peerDependenciesMeta?.[peerName]?.optional === true;
|
|
2800
|
+
if (isOptional) {
|
|
2801
|
+
continue;
|
|
2802
|
+
}
|
|
2803
|
+
missing.push({
|
|
2804
|
+
packageName: peerName,
|
|
2805
|
+
requiredRange: request.requiredRange,
|
|
2806
|
+
requestedBy
|
|
2807
|
+
});
|
|
2808
|
+
}
|
|
2809
|
+
}
|
|
2810
|
+
return missing;
|
|
2811
|
+
}
|
|
2812
|
+
};
|
|
2813
|
+
function createDependencyAnalyzer(options, preparedAliases = []) {
|
|
2814
|
+
const mainPackageJson = readPackageJsonCached(options.projectRoot);
|
|
2815
|
+
if (!mainPackageJson) {
|
|
2816
|
+
throw new Error(`Could not read package.json at ${options.projectRoot}`);
|
|
2817
|
+
}
|
|
2818
|
+
const declared = {
|
|
2819
|
+
...mainPackageJson.dependencies,
|
|
2820
|
+
...mainPackageJson.devDependencies,
|
|
2821
|
+
...mainPackageJson.optionalDependencies
|
|
2822
|
+
};
|
|
2823
|
+
const additional = Object.fromEntries(
|
|
2824
|
+
preparedAliases.filter((mapping) => !Object.hasOwn(declared, mapping.aliasName)).map((mapping) => [
|
|
2825
|
+
mapping.aliasName,
|
|
2826
|
+
"npm:" + mapping.originalName + "@" + mapping.resolvedVersion
|
|
2827
|
+
])
|
|
2828
|
+
);
|
|
2829
|
+
return new DependencyAnalyzer(options, {
|
|
2830
|
+
...mainPackageJson,
|
|
2831
|
+
devDependencies: { ...additional, ...mainPackageJson.devDependencies }
|
|
2832
|
+
});
|
|
2833
|
+
}
|
|
2834
|
+
var logger6 = createLogger("package-manager-adapter");
|
|
2835
|
+
var PACKAGE_MANAGER_ENTRYPOINT_RULES = {
|
|
2836
|
+
npm: {
|
|
2837
|
+
cliVariables: ["NPM_CLI_JS"],
|
|
2838
|
+
cliBasenames: ["npm-cli.js", "npm.js"]
|
|
2839
|
+
},
|
|
2840
|
+
pnpm: {
|
|
2841
|
+
cliVariables: ["PNPM_CLI_JS"],
|
|
2842
|
+
cliBasenames: ["pnpm.cjs", "pnpm.js"]
|
|
2843
|
+
},
|
|
2844
|
+
yarn: {
|
|
2845
|
+
cliVariables: ["YARN_CLI_JS"],
|
|
2846
|
+
cliBasenames: ["yarn.js", "yarn.cjs"]
|
|
2847
|
+
}
|
|
2848
|
+
};
|
|
2849
|
+
var DEFAULT_TIMING = {
|
|
2850
|
+
timeoutMs: 12e4,
|
|
2851
|
+
terminateGraceMs: 5e3
|
|
2852
|
+
};
|
|
2853
|
+
function createPackageManagerAdapter(options, timing = DEFAULT_TIMING) {
|
|
2854
|
+
return {
|
|
2855
|
+
install: async (specs) => {
|
|
2856
|
+
const env = registryEnvironment(options.packageManager, options.registry);
|
|
2857
|
+
if (specs.length === 0) {
|
|
2858
|
+
return {
|
|
2859
|
+
success: true,
|
|
2860
|
+
exitCode: 0,
|
|
2861
|
+
stdout: "",
|
|
2862
|
+
stderr: "",
|
|
2863
|
+
timedOut: false
|
|
2864
|
+
};
|
|
2865
|
+
}
|
|
2866
|
+
const { command, args } = buildCommand(options.packageManager, specs, env);
|
|
2867
|
+
logger6.info(`Running: ${command} ${args.map((arg) => JSON.stringify(arg)).join(" ")}`);
|
|
2868
|
+
const child = child_process.spawn(command, args, {
|
|
2869
|
+
cwd: options.projectRoot,
|
|
2870
|
+
env,
|
|
2871
|
+
shell: false,
|
|
2872
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
2873
|
+
...process.platform === "win32" ? {} : { detached: true }
|
|
2874
|
+
});
|
|
2875
|
+
return new Promise((resolve5) => {
|
|
2876
|
+
let stdout = "";
|
|
2877
|
+
let stderr = "";
|
|
2878
|
+
let terminalError;
|
|
2879
|
+
let timedOut = false;
|
|
2880
|
+
let settled = false;
|
|
2881
|
+
let closeSeen = false;
|
|
2882
|
+
let timeoutId;
|
|
2883
|
+
let graceId;
|
|
2884
|
+
const clearTimers = () => {
|
|
2885
|
+
if (timeoutId !== void 0) {
|
|
2886
|
+
clearTimeout(timeoutId);
|
|
2887
|
+
}
|
|
2888
|
+
if (graceId !== void 0) {
|
|
2889
|
+
clearTimeout(graceId);
|
|
2890
|
+
}
|
|
2891
|
+
};
|
|
2892
|
+
const finish = (exitCode) => {
|
|
2893
|
+
if (settled) {
|
|
2894
|
+
return;
|
|
2895
|
+
}
|
|
2896
|
+
settled = true;
|
|
2897
|
+
clearTimers();
|
|
2898
|
+
resolve5({
|
|
2899
|
+
success: !timedOut && !terminalError && exitCode === 0,
|
|
2900
|
+
exitCode,
|
|
2901
|
+
stdout,
|
|
2902
|
+
stderr: stderr || (terminalError?.message ?? ""),
|
|
2903
|
+
timedOut
|
|
2904
|
+
});
|
|
2905
|
+
};
|
|
2906
|
+
child.stdout?.on("data", (data) => {
|
|
2907
|
+
stdout += data.toString();
|
|
2908
|
+
});
|
|
2909
|
+
child.stderr?.on("data", (data) => {
|
|
2910
|
+
stderr += data.toString();
|
|
2911
|
+
});
|
|
2912
|
+
child.on("error", (error) => {
|
|
2913
|
+
terminalError = error;
|
|
2914
|
+
});
|
|
2915
|
+
child.on("close", (exitCode) => {
|
|
2916
|
+
closeSeen = true;
|
|
2917
|
+
finish(exitCode);
|
|
2918
|
+
});
|
|
2919
|
+
timeoutId = setTimeout(() => {
|
|
2920
|
+
if (settled || closeSeen) {
|
|
2921
|
+
return;
|
|
2922
|
+
}
|
|
2923
|
+
timedOut = true;
|
|
2924
|
+
logger6.error(`Install timeout after ${timing.timeoutMs / 1e3}s`);
|
|
2925
|
+
sendTerminationSignal(child, "SIGTERM");
|
|
2926
|
+
graceId = setTimeout(() => {
|
|
2927
|
+
if (!settled && !closeSeen) {
|
|
2928
|
+
terminateProcessTree(child);
|
|
2929
|
+
}
|
|
2930
|
+
}, timing.terminateGraceMs);
|
|
2931
|
+
}, timing.timeoutMs);
|
|
2932
|
+
});
|
|
2933
|
+
}
|
|
2934
|
+
};
|
|
2935
|
+
}
|
|
2936
|
+
function buildCommand(packageManager, specs, environment) {
|
|
2937
|
+
const invocation = resolvePackageManagerInvocation(packageManager, process.platform, environment);
|
|
2938
|
+
switch (packageManager) {
|
|
2939
|
+
case "pnpm":
|
|
2940
|
+
return {
|
|
2941
|
+
command: invocation.command,
|
|
2942
|
+
args: [...invocation.argsPrefix, "add", "--save-exact", ...specs]
|
|
2943
|
+
};
|
|
2944
|
+
case "yarn":
|
|
2945
|
+
return {
|
|
2946
|
+
command: invocation.command,
|
|
2947
|
+
args: [...invocation.argsPrefix, "add", "--exact", ...specs]
|
|
2948
|
+
};
|
|
2949
|
+
case "npm":
|
|
2950
|
+
return {
|
|
2951
|
+
command: invocation.command,
|
|
2952
|
+
args: [...invocation.argsPrefix, "install", "--legacy-peer-deps", "--save-exact", ...specs]
|
|
2953
|
+
};
|
|
2954
|
+
}
|
|
2955
|
+
throw new Error(`Unsupported package manager: ${String(packageManager)}`);
|
|
2956
|
+
}
|
|
2957
|
+
function resolvePackageManagerCommand(packageManager, platform = process.platform) {
|
|
2958
|
+
return platform === "win32" ? `${packageManager}.cmd` : packageManager;
|
|
2959
|
+
}
|
|
2960
|
+
function resolvePackageManagerInvocation(packageManager, platform = process.platform, environment = process.env) {
|
|
2961
|
+
if (platform !== "win32") {
|
|
2962
|
+
return {
|
|
2963
|
+
command: resolvePackageManagerCommand(packageManager, platform),
|
|
2964
|
+
argsPrefix: []
|
|
2965
|
+
};
|
|
2966
|
+
}
|
|
2967
|
+
const windowsInvocation = resolveWindowsPackageManagerInvocation(packageManager, environment);
|
|
2968
|
+
if (!windowsInvocation) {
|
|
2969
|
+
throw new Error(`Could not resolve a Node entrypoint for ${packageManager}`);
|
|
2970
|
+
}
|
|
2971
|
+
return windowsInvocation;
|
|
2972
|
+
}
|
|
2973
|
+
function resolveWindowsPackageManagerInvocation(packageManager, environment) {
|
|
2974
|
+
const npmExecPath = getEnvironmentValue(environment, "npm_execpath");
|
|
2975
|
+
if (npmExecPath && matchesPackageManagerPath(packageManager, npmExecPath)) {
|
|
2976
|
+
const invocation = invocationFromPackageManagerPath(packageManager, npmExecPath, "win32");
|
|
2977
|
+
if (invocation) {
|
|
2978
|
+
return invocation;
|
|
2979
|
+
}
|
|
2980
|
+
}
|
|
2981
|
+
const pathValue = getEnvironmentValue(environment, "PATH");
|
|
2982
|
+
if (!pathValue) {
|
|
2983
|
+
return void 0;
|
|
2984
|
+
}
|
|
2985
|
+
for (const directory of pathValue.split(";")) {
|
|
2986
|
+
if (!directory) {
|
|
2987
|
+
continue;
|
|
2988
|
+
}
|
|
2989
|
+
const shimPath = path.win32.join(directory, `${packageManager}.cmd`);
|
|
2990
|
+
if (fs.existsSync(shimPath)) {
|
|
2991
|
+
const invocation = invocationFromPackageManagerPath(packageManager, shimPath, "win32");
|
|
2992
|
+
if (invocation) {
|
|
2993
|
+
return invocation;
|
|
2994
|
+
}
|
|
2995
|
+
}
|
|
2996
|
+
const executablePath = path.win32.join(directory, `${packageManager}.exe`);
|
|
2997
|
+
if (fs.existsSync(executablePath)) {
|
|
2998
|
+
return { command: executablePath, argsPrefix: [] };
|
|
2999
|
+
}
|
|
3000
|
+
}
|
|
3001
|
+
return void 0;
|
|
3002
|
+
}
|
|
3003
|
+
function invocationFromPackageManagerPath(packageManager, packageManagerPath, platform) {
|
|
3004
|
+
const lowerPath = packageManagerPath.toLowerCase();
|
|
3005
|
+
if (lowerPath.endsWith(".exe")) {
|
|
3006
|
+
return { command: packageManagerPath, argsPrefix: [] };
|
|
3007
|
+
}
|
|
3008
|
+
if (lowerPath.endsWith(".cmd") || lowerPath.endsWith(".bat")) {
|
|
3009
|
+
const entrypoint = parseWindowsShimEntrypoint(packageManager, packageManagerPath, platform);
|
|
3010
|
+
if (!entrypoint) {
|
|
3011
|
+
return void 0;
|
|
3012
|
+
}
|
|
3013
|
+
return { command: process.execPath, argsPrefix: [entrypoint] };
|
|
3014
|
+
}
|
|
3015
|
+
if (isJavaScriptEntrypoint(packageManagerPath)) {
|
|
3016
|
+
return { command: process.execPath, argsPrefix: [packageManagerPath] };
|
|
3017
|
+
}
|
|
3018
|
+
return void 0;
|
|
3019
|
+
}
|
|
3020
|
+
function parseWindowsShimEntrypoint(packageManager, shimPath, platform) {
|
|
3021
|
+
let shimContents;
|
|
3022
|
+
try {
|
|
3023
|
+
shimContents = fs.readFileSync(shimPath, "utf8");
|
|
3024
|
+
} catch (error) {
|
|
3025
|
+
logger6.debug(`Failed to read ${packageManager} shim: ${String(error)}`);
|
|
3026
|
+
return void 0;
|
|
3027
|
+
}
|
|
3028
|
+
const assignments = parseWindowsShimAssignments(shimContents);
|
|
3029
|
+
const rule = PACKAGE_MANAGER_ENTRYPOINT_RULES[packageManager];
|
|
3030
|
+
const allowedVariables = new Set(rule.cliVariables);
|
|
3031
|
+
for (const variable of rule.cliVariables) {
|
|
3032
|
+
const values = assignments.get(variable);
|
|
3033
|
+
if (!values) {
|
|
3034
|
+
continue;
|
|
3035
|
+
}
|
|
3036
|
+
for (const value of values) {
|
|
3037
|
+
const entrypoint = resolveShimTarget(
|
|
3038
|
+
value,
|
|
3039
|
+
assignments,
|
|
3040
|
+
shimPath,
|
|
3041
|
+
platform,
|
|
3042
|
+
allowedVariables
|
|
3043
|
+
);
|
|
3044
|
+
if (entrypoint && isKnownPackageManagerEntrypoint(packageManager, entrypoint)) {
|
|
3045
|
+
return entrypoint;
|
|
3046
|
+
}
|
|
3047
|
+
}
|
|
3048
|
+
}
|
|
3049
|
+
const directTargetPattern = /"((?:%~dp0|%dp0%)[\\/][^"\r\n]+\.(?:js|cjs|mjs))"/gi;
|
|
3050
|
+
for (const match of shimContents.matchAll(directTargetPattern)) {
|
|
3051
|
+
const target = match[1];
|
|
3052
|
+
if (target) {
|
|
3053
|
+
const entrypoint = resolveShimTarget(
|
|
3054
|
+
target,
|
|
3055
|
+
assignments,
|
|
3056
|
+
shimPath,
|
|
3057
|
+
platform,
|
|
3058
|
+
allowedVariables
|
|
3059
|
+
);
|
|
3060
|
+
if (entrypoint && isKnownPackageManagerEntrypoint(packageManager, entrypoint)) {
|
|
3061
|
+
return entrypoint;
|
|
3062
|
+
}
|
|
3063
|
+
}
|
|
3064
|
+
}
|
|
3065
|
+
const absoluteTargetPattern = /"([A-Za-z]:[\\/][^"\r\n]+\.(?:js|cjs|mjs))"/gi;
|
|
3066
|
+
for (const match of shimContents.matchAll(absoluteTargetPattern)) {
|
|
3067
|
+
const target = match[1];
|
|
3068
|
+
if (target) {
|
|
3069
|
+
const entrypoint = resolveShimTarget(
|
|
3070
|
+
target,
|
|
3071
|
+
assignments,
|
|
3072
|
+
shimPath,
|
|
3073
|
+
platform,
|
|
3074
|
+
allowedVariables
|
|
3075
|
+
);
|
|
3076
|
+
if (entrypoint && isKnownPackageManagerEntrypoint(packageManager, entrypoint)) {
|
|
3077
|
+
return entrypoint;
|
|
3078
|
+
}
|
|
3079
|
+
}
|
|
3080
|
+
}
|
|
3081
|
+
return void 0;
|
|
3082
|
+
}
|
|
3083
|
+
function parseWindowsShimAssignments(contents) {
|
|
3084
|
+
const assignments = /* @__PURE__ */ new Map();
|
|
3085
|
+
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;
|
|
3086
|
+
for (const match of contents.matchAll(assignmentPattern)) {
|
|
3087
|
+
const name = (match[1] ?? match[3])?.toUpperCase();
|
|
3088
|
+
const value = (match[2] ?? match[4])?.trim();
|
|
3089
|
+
if (name && value !== void 0) {
|
|
3090
|
+
const values = assignments.get(name) ?? [];
|
|
3091
|
+
values.push(value);
|
|
3092
|
+
assignments.set(name, values);
|
|
3093
|
+
}
|
|
3094
|
+
}
|
|
3095
|
+
return assignments;
|
|
3096
|
+
}
|
|
3097
|
+
function resolveShimTarget(rawTarget, assignments, shimPath, platform, allowedVariables, seenVariables = /* @__PURE__ */ new Set()) {
|
|
3098
|
+
const target = rawTarget.trim().replace(/^"|"$/g, "");
|
|
3099
|
+
const markerMatch = target.match(/^%(?:~dp0|dp0%)([\\/].*)$/i);
|
|
3100
|
+
if (markerMatch?.[1]) {
|
|
3101
|
+
const pathModule = path.win32 ;
|
|
3102
|
+
const relativeTarget = markerMatch[1].replace(/^[\\/]/, "");
|
|
3103
|
+
const resolvedTarget = pathModule.resolve(pathModule.dirname(shimPath), relativeTarget);
|
|
3104
|
+
return isJavaScriptEntrypoint(resolvedTarget) ? resolvedTarget : void 0;
|
|
3105
|
+
}
|
|
3106
|
+
const variableMatch = target.match(/^%([A-Za-z_][A-Za-z0-9_]*)%([\\/].*)?$/);
|
|
3107
|
+
if (variableMatch?.[1]) {
|
|
3108
|
+
const variable = variableMatch[1].toUpperCase();
|
|
3109
|
+
if (!allowedVariables.has(variable)) {
|
|
3110
|
+
return void 0;
|
|
3111
|
+
}
|
|
3112
|
+
if (seenVariables.has(variable)) {
|
|
3113
|
+
return void 0;
|
|
3114
|
+
}
|
|
3115
|
+
const assignedValues = assignments.get(variable);
|
|
3116
|
+
if (!assignedValues) {
|
|
3117
|
+
return void 0;
|
|
3118
|
+
}
|
|
3119
|
+
const nextSeenVariables = new Set(seenVariables);
|
|
3120
|
+
nextSeenVariables.add(variable);
|
|
3121
|
+
for (const assignedValue of assignedValues) {
|
|
3122
|
+
const resolved = resolveShimTarget(
|
|
3123
|
+
`${assignedValue}${variableMatch[2] ?? ""}`,
|
|
3124
|
+
assignments,
|
|
3125
|
+
shimPath,
|
|
3126
|
+
platform,
|
|
3127
|
+
allowedVariables,
|
|
3128
|
+
nextSeenVariables
|
|
3129
|
+
);
|
|
3130
|
+
if (resolved) {
|
|
3131
|
+
return resolved;
|
|
3132
|
+
}
|
|
3133
|
+
}
|
|
3134
|
+
return void 0;
|
|
3135
|
+
}
|
|
3136
|
+
return isJavaScriptEntrypoint(target) ? target : void 0;
|
|
3137
|
+
}
|
|
3138
|
+
function isKnownPackageManagerEntrypoint(packageManager, filePath) {
|
|
3139
|
+
const fileName = path.win32.basename(filePath).toLowerCase();
|
|
3140
|
+
return PACKAGE_MANAGER_ENTRYPOINT_RULES[packageManager].cliBasenames.includes(fileName);
|
|
3141
|
+
}
|
|
3142
|
+
function matchesPackageManagerPath(packageManager, packageManagerPath, platform) {
|
|
3143
|
+
const pathModule = path.win32 ;
|
|
3144
|
+
const fileName = pathModule.basename(packageManagerPath).toLowerCase();
|
|
3145
|
+
return fileName === `${packageManager}.cmd` || fileName === `${packageManager}.exe` || isKnownPackageManagerEntrypoint(packageManager, packageManagerPath);
|
|
3146
|
+
}
|
|
3147
|
+
function isJavaScriptEntrypoint(filePath) {
|
|
3148
|
+
return /\.(?:js|cjs|mjs)$/i.test(filePath);
|
|
3149
|
+
}
|
|
3150
|
+
function getEnvironmentValue(environment, name) {
|
|
3151
|
+
const exactValue = environment[name];
|
|
3152
|
+
if (exactValue !== void 0) {
|
|
3153
|
+
return exactValue;
|
|
3154
|
+
}
|
|
3155
|
+
const lowerName = name.toLowerCase();
|
|
3156
|
+
const key = Object.keys(environment).find((candidate) => candidate.toLowerCase() === lowerName);
|
|
3157
|
+
return key ? environment[key] : void 0;
|
|
3158
|
+
}
|
|
3159
|
+
function registryEnvironment(packageManager, registry2) {
|
|
3160
|
+
return {
|
|
3161
|
+
...process.env,
|
|
3162
|
+
npm_config_registry: registry2,
|
|
3163
|
+
// Classic Yarn reads npm's registry setting; modern Yarn uses this key.
|
|
3164
|
+
...packageManager === "yarn" ? { YARN_NPM_REGISTRY_SERVER: registry2 } : {}
|
|
3165
|
+
};
|
|
3166
|
+
}
|
|
3167
|
+
function sendTerminationSignal(child, signal) {
|
|
3168
|
+
if (process.platform !== "win32" && child.pid) {
|
|
3169
|
+
try {
|
|
3170
|
+
process.kill(-child.pid, signal);
|
|
3171
|
+
return;
|
|
3172
|
+
} catch (error) {
|
|
3173
|
+
logger6.debug(`Failed to signal package-manager process group: ${String(error)}`);
|
|
3174
|
+
}
|
|
3175
|
+
}
|
|
3176
|
+
try {
|
|
3177
|
+
child.kill(signal);
|
|
3178
|
+
} catch (error) {
|
|
3179
|
+
logger6.debug(`Failed to signal package-manager process: ${String(error)}`);
|
|
3180
|
+
}
|
|
3181
|
+
}
|
|
3182
|
+
function terminateProcessTree(child) {
|
|
3183
|
+
if (process.platform === "win32") {
|
|
3184
|
+
if (!child.pid) {
|
|
3185
|
+
try {
|
|
3186
|
+
child.kill("SIGKILL");
|
|
3187
|
+
} catch (error) {
|
|
3188
|
+
logger6.debug(`Failed to terminate package-manager process: ${String(error)}`);
|
|
3189
|
+
}
|
|
3190
|
+
return;
|
|
3191
|
+
}
|
|
3192
|
+
const taskkill = child_process.spawn("taskkill", ["/pid", String(child.pid), "/t", "/f"], {
|
|
3193
|
+
shell: false,
|
|
3194
|
+
stdio: "ignore"
|
|
3195
|
+
});
|
|
3196
|
+
taskkill.on("error", (error) => {
|
|
3197
|
+
logger6.debug(`Failed to terminate package-manager process tree: ${error.message}`);
|
|
3198
|
+
});
|
|
3199
|
+
return;
|
|
3200
|
+
}
|
|
3201
|
+
if (child.pid) {
|
|
3202
|
+
try {
|
|
3203
|
+
process.kill(-child.pid, "SIGKILL");
|
|
3204
|
+
return;
|
|
3205
|
+
} catch (error) {
|
|
3206
|
+
logger6.debug(`Failed to terminate package-manager process group: ${String(error)}`);
|
|
3207
|
+
}
|
|
3208
|
+
}
|
|
3209
|
+
try {
|
|
3210
|
+
child.kill("SIGKILL");
|
|
3211
|
+
} catch (error) {
|
|
3212
|
+
logger6.debug(`Failed to terminate package-manager process: ${String(error)}`);
|
|
3213
|
+
}
|
|
3214
|
+
}
|
|
3215
|
+
|
|
3216
|
+
// src/core/package-installer.ts
|
|
3217
|
+
var logger7 = createLogger("package-installer");
|
|
3218
|
+
var INSTALL_TIMEOUT = 12e4;
|
|
3219
|
+
var PackageInstaller = class {
|
|
3220
|
+
options;
|
|
3221
|
+
packageManager;
|
|
3222
|
+
constructor(options, packageManager = createPackageManagerAdapter(options)) {
|
|
3223
|
+
this.options = options;
|
|
3224
|
+
this.packageManager = packageManager;
|
|
3225
|
+
}
|
|
3226
|
+
/**
|
|
3227
|
+
* 安装别名依赖
|
|
3228
|
+
*/
|
|
3229
|
+
async installAliases(mappings) {
|
|
3230
|
+
const result = {
|
|
3231
|
+
success: true,
|
|
3232
|
+
installed: [],
|
|
3233
|
+
reused: [],
|
|
3234
|
+
failed: [],
|
|
3235
|
+
errors: []
|
|
3236
|
+
};
|
|
3237
|
+
if (mappings.length === 0) {
|
|
3238
|
+
logger7.info("No aliases to install");
|
|
3239
|
+
return result;
|
|
3240
|
+
}
|
|
3241
|
+
const toInstall = [];
|
|
3242
|
+
const reportCollision = (mapping, verification) => {
|
|
3243
|
+
const collision = {
|
|
3244
|
+
code: "ALIAS_NAME_OCCUPIED",
|
|
3245
|
+
aliasName: mapping.aliasName,
|
|
3246
|
+
expected: {
|
|
3247
|
+
packageName: mapping.originalName,
|
|
3248
|
+
version: mapping.resolvedVersion
|
|
3249
|
+
},
|
|
3250
|
+
actual: {
|
|
3251
|
+
packageName: verification.actualPackageName,
|
|
3252
|
+
version: verification.actualVersion
|
|
3253
|
+
},
|
|
3254
|
+
reason: verification.reason
|
|
3255
|
+
};
|
|
3256
|
+
result.success = false;
|
|
3257
|
+
result.failed.push(mapping.aliasName);
|
|
3258
|
+
result.errors.push(`Alias collision: ${JSON.stringify(collision)}`);
|
|
3259
|
+
logger7.warn(`Alias collision: ${JSON.stringify(collision)}`);
|
|
3260
|
+
};
|
|
3261
|
+
const installedAliasPath = (aliasName) => {
|
|
3262
|
+
const local = path.join(this.options.projectRoot, "node_modules", aliasName);
|
|
3263
|
+
return fileExists(local) ? local : findPackagePath(aliasName, this.options.projectRoot);
|
|
3264
|
+
};
|
|
3265
|
+
const reportMissing = (mapping) => {
|
|
3266
|
+
result.success = false;
|
|
3267
|
+
result.failed.push(mapping.aliasName);
|
|
3268
|
+
result.errors.push("Alias is not installed or resolvable: " + mapping.aliasName);
|
|
3269
|
+
};
|
|
3270
|
+
for (const m of mappings) {
|
|
3271
|
+
const aliasPath = installedAliasPath(m.aliasName);
|
|
3272
|
+
if (!m.installSpec) {
|
|
3273
|
+
if (!aliasPath) {
|
|
3274
|
+
reportMissing(m);
|
|
3275
|
+
continue;
|
|
3276
|
+
}
|
|
3277
|
+
const verification2 = this.verifyInstalledVersion(
|
|
3278
|
+
aliasPath,
|
|
3279
|
+
m.originalName,
|
|
3280
|
+
m.resolvedVersion
|
|
3281
|
+
);
|
|
3282
|
+
if (!verification2.matches) {
|
|
3283
|
+
reportCollision(m, verification2);
|
|
3284
|
+
continue;
|
|
3285
|
+
}
|
|
3286
|
+
logger7.debug(`Skipping ${m.aliasName}: reusing existing installation`);
|
|
3287
|
+
result.reused.push(m.aliasName);
|
|
3288
|
+
continue;
|
|
3289
|
+
}
|
|
3290
|
+
if (!aliasPath) {
|
|
3291
|
+
toInstall.push(m);
|
|
3292
|
+
continue;
|
|
3293
|
+
}
|
|
3294
|
+
const verification = this.verifyInstalledVersion(
|
|
3295
|
+
aliasPath,
|
|
3296
|
+
m.originalName,
|
|
3297
|
+
m.resolvedVersion
|
|
3298
|
+
);
|
|
3299
|
+
if (!verification.matches) {
|
|
3300
|
+
reportCollision(m, verification);
|
|
3301
|
+
continue;
|
|
3302
|
+
}
|
|
3303
|
+
logger7.debug(`${m.aliasName} already installed with correct version`);
|
|
3304
|
+
result.reused.push(m.aliasName);
|
|
3305
|
+
}
|
|
3306
|
+
if (toInstall.length === 0) {
|
|
3307
|
+
if (result.success) {
|
|
3308
|
+
logger7.info("All aliases already installed with correct versions");
|
|
3309
|
+
}
|
|
3310
|
+
return result;
|
|
3311
|
+
}
|
|
3312
|
+
logger7.info(`Installing ${toInstall.length} alias packages...`);
|
|
3313
|
+
const installSpecs = toInstall.map((m) => m.installSpec);
|
|
3314
|
+
let installResult;
|
|
3315
|
+
try {
|
|
3316
|
+
installResult = await this.runInstall(installSpecs);
|
|
3317
|
+
} finally {
|
|
3318
|
+
clearPackageJsonCache();
|
|
3319
|
+
}
|
|
3320
|
+
const reusedBeforeInstall = new Set(result.reused);
|
|
3321
|
+
result.reused = [];
|
|
3322
|
+
for (const mapping of mappings) {
|
|
3323
|
+
if (!reusedBeforeInstall.has(mapping.aliasName)) continue;
|
|
3324
|
+
const aliasPath = installedAliasPath(mapping.aliasName);
|
|
3325
|
+
if (!aliasPath) {
|
|
3326
|
+
reportMissing(mapping);
|
|
3327
|
+
continue;
|
|
3328
|
+
}
|
|
3329
|
+
const verification = this.verifyInstalledVersion(
|
|
3330
|
+
aliasPath,
|
|
3331
|
+
mapping.originalName,
|
|
3332
|
+
mapping.resolvedVersion
|
|
3333
|
+
);
|
|
3334
|
+
if (verification.matches) {
|
|
3335
|
+
result.reused.push(mapping.aliasName);
|
|
3336
|
+
} else {
|
|
3337
|
+
reportCollision(mapping, verification);
|
|
3338
|
+
}
|
|
3339
|
+
}
|
|
3340
|
+
if (installResult.success) {
|
|
3341
|
+
for (const mapping of toInstall) {
|
|
3342
|
+
const aliasPath = installedAliasPath(mapping.aliasName);
|
|
3343
|
+
if (!aliasPath) {
|
|
3344
|
+
reportMissing(mapping);
|
|
3345
|
+
continue;
|
|
3346
|
+
}
|
|
3347
|
+
const verification = this.verifyInstalledVersion(
|
|
3348
|
+
aliasPath,
|
|
3349
|
+
mapping.originalName,
|
|
3350
|
+
mapping.resolvedVersion
|
|
3351
|
+
);
|
|
3352
|
+
if (verification.matches) {
|
|
3353
|
+
result.installed.push(mapping.aliasName);
|
|
3354
|
+
} else {
|
|
3355
|
+
reportCollision(mapping, verification);
|
|
3356
|
+
}
|
|
3357
|
+
}
|
|
3358
|
+
if (result.installed.length > 0) {
|
|
3359
|
+
logger7.info(`Successfully installed: ${result.installed.join(", ")}`);
|
|
3360
|
+
}
|
|
3361
|
+
} else {
|
|
3362
|
+
result.success = false;
|
|
3363
|
+
result.failed.push(...toInstall.map((m) => m.aliasName));
|
|
3364
|
+
result.errors.push(...installResult.errors);
|
|
3365
|
+
logger7.error(`Failed to install aliases: ${installResult.errors.join(", ")}`);
|
|
3366
|
+
}
|
|
3367
|
+
return result;
|
|
3368
|
+
}
|
|
3369
|
+
/**
|
|
3370
|
+
* 验证已安装的别名版本是否正确
|
|
3371
|
+
* @returns 验证结果及已安装包信息
|
|
3372
|
+
*/
|
|
3373
|
+
verifyInstalledVersion(aliasPath, expectedPackageName, expectedVersion) {
|
|
3374
|
+
try {
|
|
3375
|
+
const pkgJsonPath = path.join(aliasPath, "package.json");
|
|
3376
|
+
if (!fileExists(pkgJsonPath)) {
|
|
3377
|
+
return {
|
|
3378
|
+
matches: false,
|
|
3379
|
+
actualPackageName: null,
|
|
3380
|
+
actualVersion: null,
|
|
3381
|
+
reason: "missing-package-json"
|
|
3382
|
+
};
|
|
3383
|
+
}
|
|
3384
|
+
const pkgJson = readPackageJsonCached(aliasPath);
|
|
3385
|
+
if (!pkgJson) {
|
|
3386
|
+
logger7.debug(`Failed to verify version: unable to read/parse ${pkgJsonPath}`);
|
|
3387
|
+
return {
|
|
3388
|
+
matches: false,
|
|
3389
|
+
actualPackageName: null,
|
|
3390
|
+
actualVersion: null,
|
|
3391
|
+
reason: "invalid-package-json"
|
|
3392
|
+
};
|
|
3393
|
+
}
|
|
3394
|
+
const actualPackageName = pkgJson.name ?? null;
|
|
3395
|
+
const actualVersion = pkgJson.version ?? null;
|
|
3396
|
+
if (pkgJson.name !== expectedPackageName) {
|
|
3397
|
+
logger7.debug(
|
|
3398
|
+
`Package name mismatch: expected ${expectedPackageName}, got ${pkgJson.name ?? "unknown"}`
|
|
3399
|
+
);
|
|
3400
|
+
return {
|
|
3401
|
+
matches: false,
|
|
3402
|
+
actualPackageName,
|
|
3403
|
+
actualVersion,
|
|
3404
|
+
reason: "package-name-mismatch"
|
|
3405
|
+
};
|
|
3406
|
+
}
|
|
3407
|
+
const installedClean = semver__default.default.clean(pkgJson.version ?? "");
|
|
3408
|
+
const expectedClean = semver__default.default.clean(expectedVersion);
|
|
3409
|
+
if (!installedClean || !expectedClean || installedClean !== expectedClean) {
|
|
3410
|
+
logger7.debug(
|
|
3411
|
+
`Version mismatch: expected ${expectedVersion}, got ${pkgJson.version ?? "unknown"}`
|
|
3412
|
+
);
|
|
3413
|
+
return {
|
|
3414
|
+
matches: false,
|
|
3415
|
+
actualPackageName,
|
|
3416
|
+
actualVersion,
|
|
3417
|
+
reason: "version-mismatch"
|
|
3418
|
+
};
|
|
3419
|
+
}
|
|
3420
|
+
return {
|
|
3421
|
+
matches: true,
|
|
3422
|
+
actualPackageName,
|
|
3423
|
+
actualVersion,
|
|
3424
|
+
reason: "matched"
|
|
3425
|
+
};
|
|
3426
|
+
} catch (error) {
|
|
3427
|
+
logger7.debug(`Failed to verify version: ${String(error)}`);
|
|
3428
|
+
return {
|
|
3429
|
+
matches: false,
|
|
3430
|
+
actualPackageName: null,
|
|
3431
|
+
actualVersion: null,
|
|
3432
|
+
reason: "invalid-package-json"
|
|
3433
|
+
};
|
|
3434
|
+
}
|
|
3435
|
+
}
|
|
3436
|
+
/**
|
|
3437
|
+
* 执行安装命令
|
|
3438
|
+
*/
|
|
3439
|
+
async runInstall(packages) {
|
|
3440
|
+
if (packages.length === 0) {
|
|
3441
|
+
return { success: true, errors: [] };
|
|
3442
|
+
}
|
|
3443
|
+
const runResult = await this.packageManager.install(packages);
|
|
3444
|
+
if (runResult.stdout) {
|
|
3445
|
+
logger7.debug(`stdout: ${runResult.stdout}`);
|
|
3446
|
+
}
|
|
3447
|
+
if (runResult.stderr) {
|
|
3448
|
+
logger7.debug(`stderr: ${runResult.stderr}`);
|
|
3449
|
+
}
|
|
3450
|
+
if (runResult.success) {
|
|
3451
|
+
logger7.info("Install completed");
|
|
3452
|
+
return { success: true, errors: [] };
|
|
3453
|
+
}
|
|
3454
|
+
const errorMessage = runResult.timedOut ? `Install timeout after ${INSTALL_TIMEOUT / 1e3}s` : runResult.stderr || `Process exited with code ${runResult.exitCode}`;
|
|
3455
|
+
logger7.error(`Install failed: ${errorMessage}`);
|
|
3456
|
+
return { success: false, errors: [errorMessage] };
|
|
3457
|
+
}
|
|
3458
|
+
};
|
|
3459
|
+
function createPackageInstaller(options) {
|
|
3460
|
+
return new PackageInstaller(options);
|
|
3461
|
+
}
|
|
3462
|
+
var registryKey = /* @__PURE__ */ Symbol.for("deps-conflict-resolver.project-preparation.v1");
|
|
3463
|
+
var registry = globalThis;
|
|
3464
|
+
var projects = registry[registryKey] ??= /* @__PURE__ */ new Map();
|
|
3465
|
+
var collectedProjects = new FinalizationRegistry(({ owner, ref }) => {
|
|
3466
|
+
if (projects.get(owner) === ref) projects.delete(owner);
|
|
3467
|
+
});
|
|
3468
|
+
function getProjectPreparation(projectRoot) {
|
|
3469
|
+
try {
|
|
3470
|
+
projectRoot = fs.realpathSync(projectRoot);
|
|
3471
|
+
} catch {
|
|
3472
|
+
projectRoot = path.resolve(projectRoot);
|
|
3473
|
+
}
|
|
3474
|
+
let owner = createWorkspaceDetector(projectRoot).getWorkspaceRoot() ?? projectRoot;
|
|
3475
|
+
if (owner === projectRoot) {
|
|
3476
|
+
for (const directory of iterateParentDirs(projectRoot)) {
|
|
3477
|
+
if (Object.keys(LOCK_FILE_MAP).some((file) => fs.existsSync(path.join(directory, file)))) {
|
|
3478
|
+
owner = directory;
|
|
3479
|
+
break;
|
|
3480
|
+
}
|
|
3481
|
+
}
|
|
3482
|
+
}
|
|
3483
|
+
try {
|
|
3484
|
+
owner = fs.realpathSync(owner);
|
|
3485
|
+
} catch {
|
|
3486
|
+
owner = path.resolve(owner);
|
|
3487
|
+
}
|
|
3488
|
+
let state = projects.get(owner)?.deref();
|
|
3489
|
+
if (!state) {
|
|
3490
|
+
state = { owner, revision: 0, writing: false, tail: Promise.resolve(), observers: /* @__PURE__ */ new Set() };
|
|
3491
|
+
const ref = new WeakRef(state);
|
|
3492
|
+
projects.set(owner, ref);
|
|
3493
|
+
collectedProjects.register(state, { owner, ref });
|
|
3494
|
+
}
|
|
3495
|
+
return state;
|
|
3496
|
+
}
|
|
3497
|
+
async function readOwner(path) {
|
|
3498
|
+
try {
|
|
3499
|
+
const value = JSON.parse(await fs.promises.readFile(path, "utf8"));
|
|
3500
|
+
if (value && typeof value === "object" && "pid" in value && "host" in value && "token" in value && "ticket" in value && Number.isInteger(value.pid) && Number(value.pid) > 0 && typeof value.host === "string" && typeof value.token === "string" && Number.isSafeInteger(value.ticket) && Number(value.ticket) >= 0) {
|
|
3501
|
+
return value;
|
|
3502
|
+
}
|
|
3503
|
+
} catch (error) {
|
|
3504
|
+
if (error.code === "ENOENT") return null;
|
|
3505
|
+
throw error;
|
|
3506
|
+
}
|
|
3507
|
+
throw new Error("Invalid dependency preparation lock record: " + path);
|
|
3508
|
+
}
|
|
3509
|
+
function exited(owner) {
|
|
3510
|
+
if (owner.host !== os.hostname()) return false;
|
|
3511
|
+
try {
|
|
3512
|
+
process.kill(owner.pid, 0);
|
|
3513
|
+
} catch (error) {
|
|
3514
|
+
return error.code === "ESRCH";
|
|
3515
|
+
}
|
|
3516
|
+
return false;
|
|
3517
|
+
}
|
|
3518
|
+
async function removeRecord(path) {
|
|
3519
|
+
await fs.promises.unlink(path).catch((error) => {
|
|
3520
|
+
if (error.code !== "ENOENT") throw error;
|
|
3521
|
+
});
|
|
3522
|
+
}
|
|
3523
|
+
async function readContenders(directory, token) {
|
|
3524
|
+
const contenders = [];
|
|
3525
|
+
for (const name of await fs.promises.readdir(directory)) {
|
|
3526
|
+
if (!name.endsWith(".json") || name === token + ".json") continue;
|
|
3527
|
+
const path$1 = path.join(directory, name);
|
|
3528
|
+
const owner = await readOwner(path$1);
|
|
3529
|
+
if (!owner) continue;
|
|
3530
|
+
if (owner.token + ".json" !== name)
|
|
3531
|
+
throw new Error("Invalid dependency preparation lock identity: " + path$1);
|
|
3532
|
+
if (exited(owner)) {
|
|
3533
|
+
await removeRecord(path$1);
|
|
3534
|
+
} else contenders.push(owner);
|
|
3535
|
+
}
|
|
3536
|
+
return contenders;
|
|
3537
|
+
}
|
|
3538
|
+
async function acquireLock(owner) {
|
|
3539
|
+
const user = typeof process.getuid === "function" ? String(process.getuid()) : crypto.createHash("sha256").update(os.userInfo().username).digest("hex");
|
|
3540
|
+
const key = crypto.createHash("sha256").update(owner).digest("hex");
|
|
3541
|
+
const directory = path.join(os.tmpdir(), "deps-conflict-resolver-locks-" + user, key + ".queue");
|
|
3542
|
+
await fs.promises.mkdir(directory, { recursive: true, mode: 448 });
|
|
3543
|
+
const token = crypto.randomUUID();
|
|
3544
|
+
const path$1 = path.join(directory, token + ".json");
|
|
3545
|
+
const candidate = path.join(directory, token + ".tmp");
|
|
3546
|
+
const record = { pid: process.pid, host: os.hostname(), token, ticket: 0 };
|
|
3547
|
+
const deadline = perf_hooks.performance.now() + 3e5;
|
|
3548
|
+
let published = false;
|
|
3549
|
+
try {
|
|
3550
|
+
await fs.promises.writeFile(candidate, JSON.stringify(record), { flag: "wx", mode: 384 });
|
|
3551
|
+
await fs.promises.link(candidate, path$1);
|
|
3552
|
+
published = true;
|
|
3553
|
+
await removeRecord(candidate);
|
|
3554
|
+
record.ticket = 1 + (await readContenders(directory, token)).reduce(
|
|
3555
|
+
(max, other) => Math.max(max, other.ticket),
|
|
3556
|
+
0
|
|
3557
|
+
);
|
|
3558
|
+
if (!Number.isSafeInteger(record.ticket))
|
|
3559
|
+
throw new Error("Dependency preparation ticket limit exceeded in " + owner);
|
|
3560
|
+
await fs.promises.writeFile(candidate, JSON.stringify(record), { flag: "wx", mode: 384 });
|
|
3561
|
+
await fs.promises.rename(candidate, path$1);
|
|
3562
|
+
while (true) {
|
|
3563
|
+
const blocked = (await readContenders(directory, token)).some(
|
|
3564
|
+
(other) => other.ticket === 0 || other.ticket < record.ticket || other.ticket === record.ticket && other.token < token
|
|
3565
|
+
);
|
|
3566
|
+
if (!blocked) return () => removeRecord(path$1);
|
|
3567
|
+
if (perf_hooks.performance.now() >= deadline)
|
|
3568
|
+
throw new Error(
|
|
3569
|
+
"Timed out waiting for dependency preparation in " + owner + " (lock: " + path$1 + ")"
|
|
3570
|
+
);
|
|
3571
|
+
await new Promise((done) => setTimeout(done, 25));
|
|
3572
|
+
}
|
|
3573
|
+
} catch (error) {
|
|
3574
|
+
try {
|
|
3575
|
+
await removeRecord(candidate);
|
|
3576
|
+
} finally {
|
|
3577
|
+
if (published) await removeRecord(path$1);
|
|
3578
|
+
}
|
|
3579
|
+
throw error;
|
|
3580
|
+
}
|
|
3581
|
+
}
|
|
3582
|
+
async function withProjectPreparation(state, task, current) {
|
|
3583
|
+
const previous = state.tail;
|
|
3584
|
+
let finish;
|
|
3585
|
+
state.tail = new Promise((done) => {
|
|
3586
|
+
finish = done;
|
|
3587
|
+
});
|
|
3588
|
+
await previous;
|
|
3589
|
+
let unlock;
|
|
3590
|
+
let changed = false;
|
|
3591
|
+
try {
|
|
3592
|
+
unlock = await acquireLock(state.owner);
|
|
3593
|
+
return await task(() => {
|
|
3594
|
+
if (!changed) {
|
|
3595
|
+
state.revision++;
|
|
3596
|
+
changed = true;
|
|
3597
|
+
}
|
|
3598
|
+
state.writing = true;
|
|
3599
|
+
});
|
|
3600
|
+
} finally {
|
|
3601
|
+
try {
|
|
3602
|
+
if (changed) {
|
|
3603
|
+
for (const ref of state.observers) {
|
|
3604
|
+
const observer = ref.deref();
|
|
3605
|
+
if (!observer) state.observers.delete(ref);
|
|
3606
|
+
else if (observer !== current) await observer.refresh();
|
|
3607
|
+
}
|
|
3608
|
+
}
|
|
3609
|
+
} finally {
|
|
3610
|
+
state.writing = false;
|
|
3611
|
+
try {
|
|
3612
|
+
await unlock?.();
|
|
3613
|
+
} finally {
|
|
3614
|
+
finish();
|
|
3615
|
+
}
|
|
3616
|
+
}
|
|
3617
|
+
}
|
|
3618
|
+
}
|
|
3619
|
+
async function waitForProjectPreparation(state) {
|
|
3620
|
+
while (true) {
|
|
3621
|
+
const ready = state.tail;
|
|
3622
|
+
await ready;
|
|
3623
|
+
if (ready === state.tail) return;
|
|
3624
|
+
}
|
|
3625
|
+
}
|
|
3626
|
+
var logger8 = createLogger("resolver");
|
|
3627
|
+
var DEFAULT_OPTIONS = {
|
|
3628
|
+
autoInstall: true,
|
|
3629
|
+
debug: false,
|
|
3630
|
+
aliasPrefix: "aliased-"
|
|
3631
|
+
};
|
|
3632
|
+
var DepsConflictResolver = class {
|
|
3633
|
+
options;
|
|
3634
|
+
userOptions;
|
|
3635
|
+
hooks;
|
|
3636
|
+
environmentDetector = null;
|
|
3637
|
+
analyzer = null;
|
|
3638
|
+
aliasManager = null;
|
|
3639
|
+
installer = null;
|
|
3640
|
+
analysisResult = null;
|
|
3641
|
+
initialized = false;
|
|
3642
|
+
initializationPromise = null;
|
|
3643
|
+
installationPromise = null;
|
|
3644
|
+
preparing = false;
|
|
3645
|
+
installResult = null;
|
|
3646
|
+
installDiagnostics = [];
|
|
3647
|
+
preparation = null;
|
|
3648
|
+
snapshotRevision = 0;
|
|
3649
|
+
snapshotError = null;
|
|
3650
|
+
snapshotGeneration = 0;
|
|
3651
|
+
snapshotSignature = "";
|
|
3652
|
+
snapshotInvalidated = false;
|
|
3653
|
+
activeMappings = [];
|
|
3654
|
+
snapshotObserver = null;
|
|
3655
|
+
observer = { refresh: () => this.refreshSnapshot() };
|
|
3656
|
+
constructor(userOptions, hooks = {}) {
|
|
3657
|
+
this.userOptions = userOptions;
|
|
3658
|
+
this.hooks = hooks;
|
|
3659
|
+
if (userOptions.debug) {
|
|
3660
|
+
logger8.setLevel(15 /* ALL */);
|
|
3661
|
+
}
|
|
3662
|
+
}
|
|
3663
|
+
/**
|
|
3664
|
+
* 解析配置,填充默认值(异步,支持自动检测)
|
|
3665
|
+
*/
|
|
3666
|
+
async resolveOptions(userOptions, projectRoot) {
|
|
3667
|
+
this.environmentDetector = createEnvironmentDetector(projectRoot);
|
|
3668
|
+
let packageManager;
|
|
3669
|
+
if (!userOptions.packageManager || userOptions.packageManager === "auto") {
|
|
3670
|
+
const detected = this.environmentDetector.getDetectionResult();
|
|
3671
|
+
packageManager = detected.packageManager;
|
|
3672
|
+
logger8.info(
|
|
3673
|
+
`Auto-detected package manager: ${packageManager} (from ${detected.detectedFrom})`
|
|
3674
|
+
);
|
|
3675
|
+
} else {
|
|
3676
|
+
packageManager = userOptions.packageManager;
|
|
3677
|
+
}
|
|
3678
|
+
let registry2;
|
|
3679
|
+
if (!userOptions.registry) {
|
|
3680
|
+
registry2 = await this.environmentDetector.getRegistryForPackageManager(packageManager);
|
|
3681
|
+
if (registry2 !== DEFAULT_NPM_REGISTRY) {
|
|
3682
|
+
logger8.info(`Auto-detected registry: ${registry2}`);
|
|
3683
|
+
}
|
|
3684
|
+
} else {
|
|
3685
|
+
registry2 = userOptions.registry;
|
|
3686
|
+
}
|
|
3687
|
+
return {
|
|
3688
|
+
...DEFAULT_OPTIONS,
|
|
3689
|
+
dependencies: userOptions.dependencies,
|
|
3690
|
+
projectRoot,
|
|
3691
|
+
packageManager,
|
|
3692
|
+
registry: registry2,
|
|
3693
|
+
autoInstall: userOptions.offline ? false : userOptions.autoInstall ?? DEFAULT_OPTIONS.autoInstall,
|
|
3694
|
+
offline: userOptions.offline ?? false,
|
|
3695
|
+
strict: userOptions.strict ?? false,
|
|
3696
|
+
debug: userOptions.debug ?? DEFAULT_OPTIONS.debug,
|
|
3697
|
+
aliasPrefix: userOptions.aliasPrefix ?? DEFAULT_OPTIONS.aliasPrefix,
|
|
3698
|
+
excludeRedirects: userOptions.excludeRedirects ?? {},
|
|
3699
|
+
includeRedirects: userOptions.includeRedirects ?? {}
|
|
3700
|
+
};
|
|
3701
|
+
}
|
|
3702
|
+
/**
|
|
3703
|
+
* 初始化解析器
|
|
3704
|
+
*/
|
|
3705
|
+
async initialize() {
|
|
3706
|
+
if (this.initialized) {
|
|
3707
|
+
if (this.preparation) await waitForProjectPreparation(this.preparation);
|
|
3708
|
+
this.snapshotCurrent();
|
|
3709
|
+
return;
|
|
3710
|
+
}
|
|
3711
|
+
const initialization = this.initializationPromise ??= this.initializeGeneration();
|
|
3712
|
+
try {
|
|
3713
|
+
await initialization;
|
|
3714
|
+
} catch (error) {
|
|
3715
|
+
if (this.initializationPromise === initialization) {
|
|
3716
|
+
this.initializationPromise = null;
|
|
3717
|
+
this.rollbackGeneration();
|
|
3718
|
+
}
|
|
3719
|
+
throw error;
|
|
3720
|
+
}
|
|
3721
|
+
}
|
|
3722
|
+
/**
|
|
3723
|
+
* 清理已完成的初始化状态,使下一次 initialize 创建新的分析 generation。
|
|
3724
|
+
*
|
|
3725
|
+
* 初始化尚未完成时不能失效当前 generation,否则并发调用者会观察到
|
|
3726
|
+
* 不一致的部分状态。
|
|
3727
|
+
*/
|
|
3728
|
+
invalidate() {
|
|
3729
|
+
if (this.initializationPromise && !this.initialized) {
|
|
3730
|
+
throw new Error("Cannot invalidate while initialization is in progress");
|
|
3731
|
+
}
|
|
3732
|
+
if (this.installationPromise) {
|
|
3733
|
+
throw new Error("Cannot invalidate while installation is in progress");
|
|
3734
|
+
}
|
|
3735
|
+
this.initialized = false;
|
|
3736
|
+
this.initializationPromise = null;
|
|
3737
|
+
this.rollbackGeneration();
|
|
3738
|
+
}
|
|
3739
|
+
/**
|
|
3740
|
+
* 回滚未完成或已失效的 generation,确保外部不会观察到半成品规则。
|
|
3741
|
+
*/
|
|
3742
|
+
rollbackGeneration() {
|
|
3743
|
+
this.initialized = false;
|
|
3744
|
+
if (this.snapshotObserver) this.preparation?.observers.delete(this.snapshotObserver);
|
|
3745
|
+
this.snapshotObserver = null;
|
|
3746
|
+
this.snapshotError = null;
|
|
3747
|
+
this.snapshotSignature = "";
|
|
3748
|
+
this.snapshotInvalidated = false;
|
|
3749
|
+
this.snapshotGeneration++;
|
|
3750
|
+
this.activeMappings = [];
|
|
3751
|
+
this.analysisResult = null;
|
|
3752
|
+
this.analyzer = null;
|
|
3753
|
+
this.aliasManager?.clear?.();
|
|
3754
|
+
this.aliasManager = null;
|
|
3755
|
+
this.installer = null;
|
|
3756
|
+
this.installResult = null;
|
|
3757
|
+
this.installDiagnostics = [];
|
|
3758
|
+
}
|
|
3759
|
+
async initializeGeneration() {
|
|
3760
|
+
clearPackageJsonCache();
|
|
3761
|
+
logger8.info("Initializing dependencies resolver...");
|
|
3762
|
+
const projectRoot = path.resolve(this.userOptions.projectRoot ?? process.cwd());
|
|
3763
|
+
const validRoot = findProjectRoot(projectRoot);
|
|
3764
|
+
if (!validRoot) {
|
|
3765
|
+
throw new Error(`Could not find package.json in ${projectRoot} or parent directories`);
|
|
3766
|
+
}
|
|
3767
|
+
if (validRoot !== projectRoot) {
|
|
3768
|
+
logger8.debug(`Adjusted project root to: ${validRoot}`);
|
|
3769
|
+
}
|
|
3770
|
+
let physicalRoot = validRoot;
|
|
3771
|
+
try {
|
|
3772
|
+
physicalRoot = fs.realpathSync(validRoot);
|
|
3773
|
+
} catch {
|
|
3774
|
+
}
|
|
3775
|
+
this.options = await this.resolveOptions(this.userOptions, physicalRoot);
|
|
3776
|
+
if (this.options.debug) {
|
|
3777
|
+
logger8.setLevel(15 /* ALL */);
|
|
3778
|
+
}
|
|
3779
|
+
this.aliasManager = createAliasManager(this.options);
|
|
3780
|
+
this.installer = createPackageInstaller(this.options);
|
|
3781
|
+
this.preparation = getProjectPreparation(this.options.projectRoot);
|
|
3782
|
+
if (this.hooks.onAnalysisComplete) {
|
|
3783
|
+
this.analysisResult = await withProjectPreparation(
|
|
3784
|
+
this.preparation,
|
|
3785
|
+
() => this.analyzeCurrent()
|
|
3786
|
+
);
|
|
3787
|
+
await this.hooks.onAnalysisComplete(this.analysisResult);
|
|
3788
|
+
}
|
|
3789
|
+
await withProjectPreparation(
|
|
3790
|
+
this.preparation,
|
|
3791
|
+
async (markChanged) => {
|
|
3792
|
+
this.analysisResult = await this.analyzeCurrent();
|
|
3793
|
+
this.logMissingFirstLevelPeers(this.analysisResult);
|
|
3794
|
+
this.assertResolved();
|
|
3795
|
+
if (this.options.autoInstall) {
|
|
3796
|
+
const installing = this.installGeneration(markChanged);
|
|
3797
|
+
this.installationPromise = installing;
|
|
3798
|
+
try {
|
|
3799
|
+
await installing;
|
|
3800
|
+
} finally {
|
|
3801
|
+
this.installationPromise = null;
|
|
3802
|
+
}
|
|
3803
|
+
} else {
|
|
3804
|
+
this.publishWithoutInstallation();
|
|
3805
|
+
}
|
|
3806
|
+
this.observeSnapshot();
|
|
3807
|
+
},
|
|
3808
|
+
this.observer
|
|
3809
|
+
);
|
|
3810
|
+
await waitForProjectPreparation(this.preparation);
|
|
3811
|
+
await this.notifyInstallComplete();
|
|
3812
|
+
this.assertResolved();
|
|
3813
|
+
const unresolved = this.getDiagnostics().filter(
|
|
3814
|
+
(diagnostic) => diagnostic.severity === "error"
|
|
3815
|
+
);
|
|
3816
|
+
if (unresolved.length > 0) {
|
|
3817
|
+
logger8.warn(
|
|
3818
|
+
"Resolver has " + unresolved.length + " unresolved conditions: " + [...new Set(unresolved.map((diagnostic) => diagnostic.code))].join(", ") + ". Inspect getDiagnostics() or run doctor for details."
|
|
3819
|
+
);
|
|
3820
|
+
}
|
|
3821
|
+
this.logSharedPeerWarnings();
|
|
3822
|
+
this.analyzer = null;
|
|
3823
|
+
this.initialized = true;
|
|
3824
|
+
logger8.info("Dependencies resolver initialized");
|
|
3825
|
+
}
|
|
3826
|
+
/**
|
|
3827
|
+
* 输出第一层依赖中缺失的 peer 依赖警告(不自动安装,仅提示)
|
|
3828
|
+
*
|
|
3829
|
+
* 放在 initialize 阶段统一输出,避免各插件重复打印,且在 autoInstall=false 时也能看到提示。
|
|
3830
|
+
*/
|
|
3831
|
+
logMissingFirstLevelPeers(result) {
|
|
3832
|
+
const missing = result.missingFirstLevelPeers;
|
|
3833
|
+
if (!missing || missing.length === 0) {
|
|
3834
|
+
return;
|
|
3835
|
+
}
|
|
3836
|
+
logger8.warn(`Found ${missing.length} unsatisfied peer dependencies (not auto-installing):`);
|
|
3837
|
+
for (const peer of missing) {
|
|
3838
|
+
logger8.warn(
|
|
3839
|
+
` - ${peer.packageName}@${peer.requiredRange} (required by ${peer.requestedBy})`
|
|
3840
|
+
);
|
|
3841
|
+
}
|
|
3842
|
+
}
|
|
3843
|
+
/**
|
|
3844
|
+
* 安装所需依赖
|
|
3845
|
+
*
|
|
3846
|
+
* 安装策略(按用户需求):
|
|
3847
|
+
* 1. 只自动安装「主工程已声明的依赖 & peerDeps 要求版本与主工程版本冲突」的别名版本
|
|
3848
|
+
* 2. 缺失的 peer 依赖(主工程未声明):不自动安装,只警告
|
|
3849
|
+
* 3. 内部依赖冲突(子依赖之间的版本冲突):不自动安装,只做编译时重定向
|
|
3850
|
+
*
|
|
3851
|
+
* 这样可以避免"什么依赖都自动安装"的问题,用户可以根据警告自行决定是否安装缺失的依赖
|
|
3852
|
+
*/
|
|
3853
|
+
installDependencies() {
|
|
3854
|
+
return this.installationPromise ??= this.prepareInstallation().finally(() => {
|
|
3855
|
+
this.installationPromise = null;
|
|
3856
|
+
});
|
|
3857
|
+
}
|
|
3858
|
+
async prepareInstallation() {
|
|
3859
|
+
if (!this.analysisResult || !this.installer || !this.preparation) {
|
|
3860
|
+
throw new Error("Resolver not initialized. Call initialize() first.");
|
|
3861
|
+
}
|
|
3862
|
+
this.preparing = true;
|
|
3863
|
+
try {
|
|
3864
|
+
await withProjectPreparation(
|
|
3865
|
+
this.preparation,
|
|
3866
|
+
async (markChanged) => {
|
|
3867
|
+
this.analysisResult = await this.analyzeCurrent();
|
|
3868
|
+
this.installDiagnostics = [];
|
|
3869
|
+
this.assertResolved();
|
|
3870
|
+
if (!this.options.offline) await this.installGeneration(markChanged);
|
|
3871
|
+
else this.publishWithoutInstallation();
|
|
3872
|
+
this.observeSnapshot();
|
|
3873
|
+
},
|
|
3874
|
+
this.observer
|
|
3875
|
+
);
|
|
3876
|
+
} finally {
|
|
3877
|
+
this.preparing = false;
|
|
3878
|
+
}
|
|
3879
|
+
await waitForProjectPreparation(this.preparation);
|
|
3880
|
+
await this.notifyInstallComplete();
|
|
3881
|
+
this.assertResolved();
|
|
3882
|
+
if (this.initialized) this.logSharedPeerWarnings();
|
|
3883
|
+
}
|
|
3884
|
+
async analyzeCurrent(offline = this.options.offline, preparedAliases = []) {
|
|
3885
|
+
clearPackageJsonCache();
|
|
3886
|
+
this.analyzer = createDependencyAnalyzer({ ...this.options, offline }, preparedAliases);
|
|
3887
|
+
try {
|
|
3888
|
+
return await this.analyzer.analyze();
|
|
3889
|
+
} finally {
|
|
3890
|
+
this.analyzer = null;
|
|
3891
|
+
}
|
|
3892
|
+
}
|
|
3893
|
+
publishWithoutInstallation() {
|
|
3894
|
+
const mappings = this.analysisResult.aliasMappings;
|
|
3895
|
+
this.setActiveAliasMappings(mappings.filter((mapping) => mapping.installSpec === ""));
|
|
3896
|
+
for (const mapping of mappings) {
|
|
3897
|
+
if (mapping.installSpec)
|
|
3898
|
+
this.installDiagnostics.push({
|
|
3899
|
+
code: "ALIAS_NOT_INSTALLED",
|
|
3900
|
+
severity: "error",
|
|
3901
|
+
packageName: mapping.originalName,
|
|
3902
|
+
aliases: [mapping.aliasName],
|
|
3903
|
+
message: "Alias is not active because installation is disabled: " + mapping.aliasName
|
|
3904
|
+
});
|
|
3905
|
+
}
|
|
3906
|
+
}
|
|
3907
|
+
async installGeneration(markChanged) {
|
|
3908
|
+
const report = {
|
|
3909
|
+
success: true,
|
|
3910
|
+
installed: [],
|
|
3911
|
+
reused: [],
|
|
3912
|
+
failed: [],
|
|
3913
|
+
errors: []
|
|
3914
|
+
};
|
|
3915
|
+
this.installResult = report;
|
|
3916
|
+
this.installDiagnostics = [];
|
|
3917
|
+
const blocked = /* @__PURE__ */ new Set();
|
|
3918
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
3919
|
+
const planned = this.analysisResult.aliasMappings;
|
|
3920
|
+
if (planned.some((mapping) => mapping.installSpec)) markChanged();
|
|
3921
|
+
let result;
|
|
3922
|
+
try {
|
|
3923
|
+
result = await this.installer.installAliases(planned);
|
|
3924
|
+
} catch (error) {
|
|
3925
|
+
this.setActiveAliasMappings([]);
|
|
3926
|
+
throw error;
|
|
3927
|
+
}
|
|
3928
|
+
report.success &&= result.success;
|
|
3929
|
+
for (const key of ["installed", "reused", "failed", "errors"]) {
|
|
3930
|
+
report[key] = [.../* @__PURE__ */ new Set([...report[key], ...result[key] ?? []])];
|
|
3931
|
+
}
|
|
3932
|
+
for (const aliasName of result.failed ?? []) {
|
|
3933
|
+
blocked.add(aliasName);
|
|
3934
|
+
this.installDiagnostics.push({
|
|
3935
|
+
code: "ALIAS_INSTALL_FAILED",
|
|
3936
|
+
severity: "error",
|
|
3937
|
+
packageName: planned.find((mapping) => mapping.aliasName === aliasName)?.originalName ?? aliasName,
|
|
3938
|
+
aliases: [aliasName],
|
|
3939
|
+
message: "Alias installation failed: " + aliasName + ". " + result.errors.join("; ")
|
|
3940
|
+
});
|
|
3941
|
+
}
|
|
3942
|
+
const changed = (result.installed?.length ?? 0) > 0 || (result.failed?.length ?? 0) > 0;
|
|
3943
|
+
if (!changed) {
|
|
3944
|
+
this.setActiveAliasMappings(this.filterCompletedMappings(planned, result, false), blocked);
|
|
3945
|
+
return;
|
|
3946
|
+
}
|
|
3947
|
+
this.analysisResult = await this.analyzeCurrent(
|
|
3948
|
+
result.success ? this.options.offline : true,
|
|
3949
|
+
this.filterCompletedMappings(planned, result, false)
|
|
3950
|
+
);
|
|
3951
|
+
const fresh = this.analysisResult.aliasMappings;
|
|
3952
|
+
const pending = fresh.filter(
|
|
3953
|
+
(mapping) => mapping.installSpec && !blocked.has(mapping.aliasName)
|
|
3954
|
+
);
|
|
3955
|
+
if (result.success && pending.length > 0 && attempt === 0) continue;
|
|
3956
|
+
if (result.success && pending.length > 0) {
|
|
3957
|
+
report.success = false;
|
|
3958
|
+
const message = "Dependency inputs changed during preparation; refusing to publish an unstable installation plan";
|
|
3959
|
+
report.errors.push(message);
|
|
3960
|
+
this.installDiagnostics.push({
|
|
3961
|
+
code: "PROJECT_STATE_CHANGED",
|
|
3962
|
+
severity: "error",
|
|
3963
|
+
packageName: this.options.dependencies.join(", "),
|
|
3964
|
+
message
|
|
3965
|
+
});
|
|
3966
|
+
}
|
|
3967
|
+
for (const mapping of planned) {
|
|
3968
|
+
if (blocked.has(mapping.aliasName) && !fresh.some((entry) => entry.aliasName === mapping.aliasName))
|
|
3969
|
+
fresh.push(mapping);
|
|
3970
|
+
}
|
|
3971
|
+
this.setActiveAliasMappings(
|
|
3972
|
+
fresh.filter((mapping) => !mapping.installSpec && !blocked.has(mapping.aliasName)),
|
|
3973
|
+
blocked
|
|
3974
|
+
);
|
|
3975
|
+
if (!report.success || pending.length === 0) return;
|
|
3976
|
+
}
|
|
3977
|
+
}
|
|
3978
|
+
observeSnapshot() {
|
|
3979
|
+
this.snapshotInvalidated = false;
|
|
3980
|
+
if (!this.snapshotObserver) {
|
|
3981
|
+
this.snapshotObserver = new WeakRef(this.observer);
|
|
3982
|
+
this.preparation.observers.add(this.snapshotObserver);
|
|
3983
|
+
}
|
|
3984
|
+
this.captureSnapshot();
|
|
3985
|
+
}
|
|
3986
|
+
async refreshSnapshot() {
|
|
3987
|
+
if (!this.analysisResult || !this.aliasManager) return;
|
|
3988
|
+
if (this.snapshotInvalidated) {
|
|
3989
|
+
this.snapshotRevision = this.preparation.revision;
|
|
3990
|
+
return;
|
|
3991
|
+
}
|
|
3992
|
+
const generation = this.snapshotGeneration;
|
|
3993
|
+
const previous = this.snapshotSignature;
|
|
3994
|
+
try {
|
|
3995
|
+
const analysis = await this.analyzeCurrent(true, this.activeMappings);
|
|
3996
|
+
if (generation !== this.snapshotGeneration) return;
|
|
3997
|
+
this.analysisResult = analysis;
|
|
3998
|
+
this.setActiveAliasMappings(analysis.aliasMappings.filter((mapping) => !mapping.installSpec));
|
|
3999
|
+
const changed = previous !== this.describeSnapshot();
|
|
4000
|
+
if (this.initialized && changed) {
|
|
4001
|
+
this.snapshotInvalidated = true;
|
|
4002
|
+
this.setActiveAliasMappings([]);
|
|
4003
|
+
this.installDiagnostics.push({
|
|
4004
|
+
code: "PROJECT_STATE_CHANGED",
|
|
4005
|
+
severity: "error",
|
|
4006
|
+
packageName: this.options.dependencies.join(", "),
|
|
4007
|
+
message: "Another preparation changed active dependency rules. Call invalidate() and initialize() before building again."
|
|
4008
|
+
});
|
|
4009
|
+
}
|
|
4010
|
+
} catch (error) {
|
|
4011
|
+
if (generation !== this.snapshotGeneration) return;
|
|
4012
|
+
this.snapshotInvalidated = true;
|
|
4013
|
+
this.setActiveAliasMappings([]);
|
|
4014
|
+
this.installDiagnostics.push({
|
|
4015
|
+
code: "PROJECT_STATE_CHANGED",
|
|
4016
|
+
severity: "error",
|
|
4017
|
+
packageName: this.options.dependencies.join(", "),
|
|
4018
|
+
message: "Cannot refresh dependency rules after another installation: " + String(error)
|
|
4019
|
+
});
|
|
4020
|
+
}
|
|
4021
|
+
this.captureSnapshot();
|
|
4022
|
+
}
|
|
4023
|
+
describeSnapshot() {
|
|
4024
|
+
const mappings = this.activeMappings.map((mapping) => [
|
|
4025
|
+
mapping.originalName,
|
|
4026
|
+
mapping.aliasName,
|
|
4027
|
+
mapping.resolvedVersion,
|
|
4028
|
+
[...mapping.usedBy].sort(),
|
|
4029
|
+
[...mapping.allDependents].sort(),
|
|
4030
|
+
mapping.importerPaths ? [...mapping.importerPaths].sort() : null
|
|
4031
|
+
]).sort((a, b) => String(a[1]).localeCompare(String(b[1])));
|
|
4032
|
+
const providers = (this.aliasManager?.getAliasPathMappings() ?? []).map((mapping) => {
|
|
4033
|
+
let path = mapping.path;
|
|
4034
|
+
try {
|
|
4035
|
+
path = fs.realpathSync(path);
|
|
4036
|
+
} catch {
|
|
4037
|
+
}
|
|
4038
|
+
return [mapping.aliasName, path, readPackageJsonCached(path)];
|
|
4039
|
+
}).sort((a, b) => String(a[0]).localeCompare(String(b[0])));
|
|
4040
|
+
return JSON.stringify([mappings, providers]);
|
|
4041
|
+
}
|
|
4042
|
+
captureSnapshot() {
|
|
4043
|
+
this.snapshotRevision = this.preparation.revision;
|
|
4044
|
+
this.snapshotSignature = this.describeSnapshot();
|
|
4045
|
+
const errors = this.generationDiagnostics().filter(
|
|
4046
|
+
(diagnostic) => diagnostic.severity === "error"
|
|
4047
|
+
);
|
|
4048
|
+
this.snapshotError = errors.length ? new ResolutionError(errors) : null;
|
|
4049
|
+
}
|
|
4050
|
+
async notifyInstallComplete() {
|
|
4051
|
+
if (!this.installResult || !this.hooks.onInstallComplete) return;
|
|
4052
|
+
await this.hooks.onInstallComplete(
|
|
4053
|
+
this.filterCompletedMappings(this.analysisResult.aliasMappings, this.installResult, true)
|
|
4054
|
+
);
|
|
4055
|
+
}
|
|
4056
|
+
snapshotCurrent() {
|
|
4057
|
+
if (!this.preparation) return true;
|
|
4058
|
+
if (this.preparation.writing || this.preparing || this.snapshotRevision !== this.preparation.revision) {
|
|
4059
|
+
const diagnostic = {
|
|
4060
|
+
code: "PROJECT_STATE_CHANGED",
|
|
4061
|
+
severity: "error",
|
|
4062
|
+
packageName: this.options.dependencies.join(", "),
|
|
4063
|
+
message: "Dependency preparation is changing this project; wait for preparation to finish before resolving modules"
|
|
4064
|
+
};
|
|
4065
|
+
if (this.options.strict) throw new ResolutionError([diagnostic]);
|
|
4066
|
+
return false;
|
|
4067
|
+
}
|
|
4068
|
+
if (this.options.strict && this.snapshotError) throw this.snapshotError;
|
|
4069
|
+
return true;
|
|
4070
|
+
}
|
|
4071
|
+
logSharedPeerWarnings() {
|
|
4072
|
+
for (const diagnostic of this.getDiagnostics()) {
|
|
4073
|
+
if (diagnostic.code === "SHARED_PEER_CONTEXT")
|
|
4074
|
+
logger8.warn(`[${diagnostic.code}] ${diagnostic.message}`);
|
|
4075
|
+
}
|
|
4076
|
+
}
|
|
4077
|
+
/**
|
|
4078
|
+
* Select only mappings whose installer outcome explicitly proved reuse or
|
|
4079
|
+
* installation. Hook callers retain the pre-Task-9 compatibility fallback
|
|
4080
|
+
* for old installer results that omitted `reused`.
|
|
4081
|
+
*/
|
|
4082
|
+
filterCompletedMappings(aliasMappings, aliasResult, allowLegacyReuse) {
|
|
4083
|
+
const failedAliases = new Set(aliasResult.failed ?? []);
|
|
4084
|
+
const successfulAliases = /* @__PURE__ */ new Set([
|
|
4085
|
+
...aliasResult.installed ?? [],
|
|
4086
|
+
...aliasResult.reused ?? []
|
|
4087
|
+
]);
|
|
4088
|
+
if (allowLegacyReuse && aliasResult.success !== false) {
|
|
4089
|
+
for (const mapping of aliasMappings) {
|
|
4090
|
+
if (mapping.installSpec === "" && !failedAliases.has(mapping.aliasName)) {
|
|
4091
|
+
successfulAliases.add(mapping.aliasName);
|
|
4092
|
+
}
|
|
4093
|
+
}
|
|
4094
|
+
}
|
|
4095
|
+
return aliasMappings.filter(
|
|
4096
|
+
(mapping) => successfulAliases.has(mapping.aliasName) && !failedAliases.has(mapping.aliasName)
|
|
4097
|
+
);
|
|
4098
|
+
}
|
|
4099
|
+
/**
|
|
4100
|
+
* Publish a new active mapping set while keeping the complete analysis
|
|
4101
|
+
* result available for diagnostics.
|
|
4102
|
+
*/
|
|
4103
|
+
setActiveAliasMappings(mappings, blockedAliasNames = []) {
|
|
4104
|
+
if (!this.aliasManager || !this.analysisResult) {
|
|
4105
|
+
return;
|
|
4106
|
+
}
|
|
4107
|
+
const activeAliasNames = new Set(mappings.map((mapping) => mapping.aliasName));
|
|
4108
|
+
const inactiveAliasNames = new Set(blockedAliasNames);
|
|
4109
|
+
for (const mapping of this.analysisResult.aliasMappings) {
|
|
4110
|
+
if (!activeAliasNames.has(mapping.aliasName)) {
|
|
4111
|
+
inactiveAliasNames.add(mapping.aliasName);
|
|
4112
|
+
}
|
|
4113
|
+
}
|
|
4114
|
+
const activeMappings = mappings.map((mapping) => {
|
|
4115
|
+
if (!mapping.importerPaths || inactiveAliasNames.size === 0) {
|
|
4116
|
+
return mapping;
|
|
4117
|
+
}
|
|
4118
|
+
const blockedPaths = new Set(
|
|
4119
|
+
Object.entries(mapping.peerImporterPaths ?? {}).filter(([aliasName]) => inactiveAliasNames.has(aliasName)).flatMap(([, paths]) => paths)
|
|
4120
|
+
);
|
|
4121
|
+
return {
|
|
4122
|
+
...mapping,
|
|
4123
|
+
peerImporterPaths: Object.fromEntries(
|
|
4124
|
+
Object.entries(mapping.peerImporterPaths ?? {}).filter(
|
|
4125
|
+
([aliasName]) => !inactiveAliasNames.has(aliasName)
|
|
4126
|
+
)
|
|
4127
|
+
),
|
|
4128
|
+
importerPaths: mapping.importerPaths.filter(
|
|
4129
|
+
(importerPath) => !blockedPaths.has(importerPath) && ![...inactiveAliasNames].some(
|
|
4130
|
+
(aliasName) => this.isAliasPackagePath(importerPath, aliasName)
|
|
4131
|
+
)
|
|
4132
|
+
)
|
|
4133
|
+
};
|
|
4134
|
+
});
|
|
4135
|
+
this.activeMappings = activeMappings;
|
|
4136
|
+
this.aliasManager.initFromAnalysisResult({
|
|
4137
|
+
...this.analysisResult,
|
|
4138
|
+
aliasMappings: activeMappings
|
|
4139
|
+
});
|
|
4140
|
+
}
|
|
4141
|
+
/**
|
|
4142
|
+
* Check whether an importer path belongs to an alias package directory.
|
|
4143
|
+
* Package paths can be nested under pnpm's virtual store, so matching the
|
|
4144
|
+
* `node_modules/<alias>` segment is more reliable than checking a basename.
|
|
4145
|
+
*/
|
|
4146
|
+
isAliasPackagePath(importerPath, aliasName) {
|
|
4147
|
+
const normalizedPath = importerPath.replace(/\\/g, "/").replace(/\/+$/, "");
|
|
4148
|
+
const marker = `node_modules/${aliasName}`;
|
|
4149
|
+
return normalizedPath === marker || normalizedPath.startsWith(`${marker}/`) || normalizedPath.endsWith(`/${marker}`) || normalizedPath.includes(`/${marker}/`);
|
|
4150
|
+
}
|
|
4151
|
+
/**
|
|
4152
|
+
* 解析模块请求
|
|
4153
|
+
* @returns 解析后的模块名,如果不需要重定向则返回 null
|
|
4154
|
+
*/
|
|
4155
|
+
resolveModule(request, importer) {
|
|
4156
|
+
if (!this.initialized || !this.aliasManager) {
|
|
4157
|
+
return null;
|
|
4158
|
+
}
|
|
4159
|
+
if (!this.snapshotCurrent()) return null;
|
|
4160
|
+
if (this.hooks.beforeResolve) {
|
|
4161
|
+
const hookResult = this.hooks.beforeResolve(request, importer);
|
|
4162
|
+
if (hookResult !== void 0) {
|
|
4163
|
+
return hookResult;
|
|
4164
|
+
}
|
|
4165
|
+
}
|
|
4166
|
+
return this.aliasManager.resolveModule({ request, importer });
|
|
4167
|
+
}
|
|
4168
|
+
/**
|
|
4169
|
+
* 获取别名路径映射
|
|
4170
|
+
* 返回别名名称到实际路径的映射,供构建工具插件转换为各自的格式
|
|
4171
|
+
*/
|
|
4172
|
+
getAliasPathMappings() {
|
|
4173
|
+
if (!this.initialized || !this.aliasManager) {
|
|
4174
|
+
return [];
|
|
4175
|
+
}
|
|
4176
|
+
if (!this.snapshotCurrent()) return [];
|
|
4177
|
+
return this.aliasManager.getAliasPathMappings();
|
|
4178
|
+
}
|
|
4179
|
+
/**
|
|
4180
|
+
* 获取分析结果
|
|
4181
|
+
*/
|
|
4182
|
+
getAnalysisResult() {
|
|
4183
|
+
return this.analysisResult;
|
|
4184
|
+
}
|
|
4185
|
+
generationDiagnostics() {
|
|
4186
|
+
return [
|
|
4187
|
+
...this.analysisResult?.diagnostics ?? [],
|
|
4188
|
+
...this.installDiagnostics,
|
|
4189
|
+
...this.aliasManager?.getDiagnostics?.() ?? []
|
|
4190
|
+
];
|
|
4191
|
+
}
|
|
4192
|
+
/** Inspect unresolved conditions without parsing logs. */
|
|
4193
|
+
getDiagnostics() {
|
|
4194
|
+
return [
|
|
4195
|
+
...this.initialized && this.preparation && (this.preparation.writing || this.preparing) ? [
|
|
4196
|
+
{
|
|
4197
|
+
code: "PROJECT_STATE_CHANGED",
|
|
4198
|
+
severity: "error",
|
|
4199
|
+
packageName: this.options.dependencies.join(", "),
|
|
4200
|
+
message: "Dependency preparation is in progress; wait before resolving modules"
|
|
4201
|
+
}
|
|
4202
|
+
] : [],
|
|
4203
|
+
...this.generationDiagnostics()
|
|
4204
|
+
].map(
|
|
4205
|
+
(diagnostic) => Object.assign({}, diagnostic, {
|
|
4206
|
+
...diagnostic.aliases && { aliases: [...diagnostic.aliases] },
|
|
4207
|
+
...diagnostic.requestedBy && { requestedBy: [...diagnostic.requestedBy] },
|
|
4208
|
+
...diagnostic.importerPaths && { importerPaths: [...diagnostic.importerPaths] }
|
|
4209
|
+
})
|
|
4210
|
+
);
|
|
4211
|
+
}
|
|
4212
|
+
assertResolved() {
|
|
4213
|
+
if (this.options.strict) {
|
|
4214
|
+
const errors = this.generationDiagnostics().filter(
|
|
4215
|
+
(diagnostic) => diagnostic.severity === "error"
|
|
4216
|
+
);
|
|
4217
|
+
if (errors.length > 0) throw new ResolutionError(errors);
|
|
4218
|
+
}
|
|
4219
|
+
}
|
|
4220
|
+
/** Explain a request; skipHook permits side-effect-free cache validation. */
|
|
4221
|
+
explainResolution(request, importer, options = {}) {
|
|
4222
|
+
if (!this.initialized || !this.aliasManager) {
|
|
4223
|
+
return {
|
|
4224
|
+
request,
|
|
4225
|
+
importer,
|
|
4226
|
+
resolved: null,
|
|
4227
|
+
reason: "inactive",
|
|
4228
|
+
aliases: [],
|
|
4229
|
+
matchedPaths: []
|
|
4230
|
+
};
|
|
4231
|
+
}
|
|
4232
|
+
if (!this.snapshotCurrent())
|
|
4233
|
+
return {
|
|
4234
|
+
request,
|
|
4235
|
+
importer,
|
|
4236
|
+
resolved: null,
|
|
4237
|
+
reason: "inactive",
|
|
4238
|
+
aliases: [],
|
|
4239
|
+
matchedPaths: []
|
|
4240
|
+
};
|
|
4241
|
+
if (!options.skipHook && this.hooks.beforeResolve) {
|
|
4242
|
+
const resolved = this.hooks.beforeResolve(request, importer);
|
|
4243
|
+
if (resolved !== void 0) {
|
|
4244
|
+
return { request, importer, resolved, reason: "hook", aliases: [], matchedPaths: [] };
|
|
4245
|
+
}
|
|
4246
|
+
}
|
|
4247
|
+
return this.aliasManager.explainResolution(request, importer);
|
|
4248
|
+
}
|
|
4249
|
+
getInstallResult() {
|
|
4250
|
+
return this.installResult && {
|
|
4251
|
+
...this.installResult,
|
|
4252
|
+
installed: [...this.installResult.installed],
|
|
4253
|
+
reused: [...this.installResult.reused],
|
|
4254
|
+
failed: [...this.installResult.failed],
|
|
4255
|
+
errors: [...this.installResult.errors]
|
|
4256
|
+
};
|
|
4257
|
+
}
|
|
4258
|
+
/**
|
|
4259
|
+
* 获取配置
|
|
4260
|
+
*/
|
|
4261
|
+
getOptions() {
|
|
4262
|
+
return { ...this.options };
|
|
4263
|
+
}
|
|
4264
|
+
};
|
|
4265
|
+
|
|
4266
|
+
// src/core/cli-runner.ts
|
|
4267
|
+
var HELP = [
|
|
4268
|
+
"Usage: deps-conflict-resolver <doctor|prepare> [packages...] [options]",
|
|
4269
|
+
"",
|
|
4270
|
+
"doctor Analyze without installing; scans runtime dependencies when none are listed.",
|
|
4271
|
+
"prepare Analyze and install verified aliases for the listed packages.",
|
|
4272
|
+
"",
|
|
4273
|
+
"Options:",
|
|
4274
|
+
" --root <directory> Project directory (defaults to cwd)",
|
|
4275
|
+
" --package-manager <manager> auto, npm, pnpm, or yarn",
|
|
4276
|
+
" --registry <url> Registry used for metadata and installation",
|
|
4277
|
+
" --offline Never query a registry or run installation",
|
|
4278
|
+
" --strict Return exit code 1 for unresolved conditions",
|
|
4279
|
+
" --json Emit a machine-readable report",
|
|
4280
|
+
" --help Show this help",
|
|
4281
|
+
""
|
|
4282
|
+
].join("\n");
|
|
4283
|
+
async function runCli(argv, output = {
|
|
4284
|
+
stdout: (text) => {
|
|
4285
|
+
process.stdout.write(text);
|
|
4286
|
+
},
|
|
4287
|
+
stderr: (text) => {
|
|
4288
|
+
process.stderr.write(text);
|
|
4289
|
+
}
|
|
4290
|
+
}) {
|
|
4291
|
+
const json = argv.includes("--json");
|
|
4292
|
+
try {
|
|
4293
|
+
if (argv.length === 0 || argv.includes("--help")) {
|
|
4294
|
+
output.stdout(HELP);
|
|
4295
|
+
return 0;
|
|
4296
|
+
}
|
|
4297
|
+
const [command, ...args] = argv;
|
|
4298
|
+
if (command !== "doctor" && command !== "prepare") {
|
|
4299
|
+
throw new Error("Unknown command: " + command + "\n" + HELP);
|
|
4300
|
+
}
|
|
4301
|
+
let root = process.cwd();
|
|
4302
|
+
let registry2;
|
|
4303
|
+
let packageManager = "auto";
|
|
4304
|
+
let offline = false;
|
|
4305
|
+
let strict = false;
|
|
4306
|
+
const packages = [];
|
|
4307
|
+
for (let index = 0; index < args.length; index++) {
|
|
4308
|
+
const arg = args[index];
|
|
4309
|
+
if (arg === "--json") continue;
|
|
4310
|
+
if (arg === "--offline") {
|
|
4311
|
+
offline = true;
|
|
4312
|
+
continue;
|
|
4313
|
+
}
|
|
4314
|
+
if (arg === "--strict") {
|
|
4315
|
+
strict = true;
|
|
4316
|
+
continue;
|
|
4317
|
+
}
|
|
4318
|
+
if (arg === "--root" || arg === "--registry" || arg === "--package-manager") {
|
|
4319
|
+
const value = args[++index];
|
|
4320
|
+
if (!value || value.startsWith("--")) throw new Error("Missing value for " + arg);
|
|
4321
|
+
if (arg === "--root") root = value;
|
|
4322
|
+
else if (arg === "--registry") registry2 = value;
|
|
4323
|
+
else {
|
|
4324
|
+
if (!["auto", "npm", "pnpm", "yarn"].includes(value))
|
|
4325
|
+
throw new Error("Unsupported package manager: " + value);
|
|
4326
|
+
packageManager = value;
|
|
4327
|
+
}
|
|
4328
|
+
continue;
|
|
4329
|
+
}
|
|
4330
|
+
if (arg.startsWith("-")) throw new Error("Unknown option: " + arg);
|
|
4331
|
+
packages.push(arg);
|
|
4332
|
+
}
|
|
4333
|
+
if (command === "prepare" && packages.length === 0) {
|
|
4334
|
+
throw new Error("prepare requires at least one dependency name");
|
|
4335
|
+
}
|
|
4336
|
+
const projectRoot = findProjectRoot(path.resolve(root));
|
|
4337
|
+
if (!projectRoot) throw new Error("Could not find package.json from " + root);
|
|
4338
|
+
const manifest = readPackageJsonCached(projectRoot);
|
|
4339
|
+
if (!manifest) throw new Error("Could not read package.json at " + projectRoot);
|
|
4340
|
+
const runtimeDependencies = { ...manifest.dependencies, ...manifest.optionalDependencies };
|
|
4341
|
+
const dependencies = [
|
|
4342
|
+
...new Set(
|
|
4343
|
+
packages.length > 0 ? packages : Object.keys(runtimeDependencies).filter((name) => !runtimeDependencies[name]?.startsWith("npm:")).filter(
|
|
4344
|
+
(name) => !Object.hasOwn(manifest.optionalDependencies ?? {}, name) || findPackagePath(name, projectRoot) !== null
|
|
4345
|
+
).sort()
|
|
4346
|
+
)
|
|
4347
|
+
];
|
|
4348
|
+
createLogger("cli").setLevel(0 /* SILENT */);
|
|
4349
|
+
const resolver = new DepsConflictResolver({
|
|
4350
|
+
projectRoot,
|
|
4351
|
+
dependencies,
|
|
4352
|
+
packageManager,
|
|
4353
|
+
registry: registry2,
|
|
4354
|
+
offline,
|
|
4355
|
+
autoInstall: command === "prepare"
|
|
4356
|
+
});
|
|
4357
|
+
await resolver.initialize();
|
|
4358
|
+
const analysis = resolver.getAnalysisResult();
|
|
4359
|
+
const diagnostics = resolver.getDiagnostics();
|
|
4360
|
+
const report = {
|
|
4361
|
+
schemaVersion: 1,
|
|
4362
|
+
command,
|
|
4363
|
+
projectRoot,
|
|
4364
|
+
packageManager: resolver.getOptions().packageManager,
|
|
4365
|
+
dependencies,
|
|
4366
|
+
aliases: analysis.aliasMappings,
|
|
4367
|
+
activeAliases: resolver.getAliasPathMappings(),
|
|
4368
|
+
diagnostics,
|
|
4369
|
+
installation: resolver.getInstallResult()
|
|
4370
|
+
};
|
|
4371
|
+
if (json) {
|
|
4372
|
+
output.stdout(JSON.stringify(report, null, 2) + "\n");
|
|
4373
|
+
} else {
|
|
4374
|
+
output.stdout(
|
|
4375
|
+
"Analyzed " + dependencies.length + " dependencies; " + report.activeAliases.length + " active aliases; " + diagnostics.length + " diagnostics.\n"
|
|
4376
|
+
);
|
|
4377
|
+
for (const mapping of analysis.aliasMappings) {
|
|
4378
|
+
const active = report.activeAliases.some((entry) => entry.aliasName === mapping.aliasName);
|
|
4379
|
+
output.stdout(
|
|
4380
|
+
" " + mapping.originalName + "@" + mapping.resolvedVersion + " -> " + mapping.aliasName + (active ? " (active)" : " (requires prepare)") + "\n"
|
|
4381
|
+
);
|
|
4382
|
+
}
|
|
4383
|
+
for (const diagnostic of diagnostics) {
|
|
4384
|
+
output.stdout(" [" + diagnostic.code + "] " + diagnostic.message + "\n");
|
|
4385
|
+
}
|
|
4386
|
+
}
|
|
4387
|
+
return diagnostics.some((diagnostic) => diagnostic.severity === "error") && (strict || command === "prepare") ? 1 : 0;
|
|
4388
|
+
} catch (error) {
|
|
4389
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
4390
|
+
if (json) {
|
|
4391
|
+
output.stdout(
|
|
4392
|
+
JSON.stringify(
|
|
4393
|
+
{
|
|
4394
|
+
error: message,
|
|
4395
|
+
diagnostics: error instanceof ResolutionError ? error.diagnostics : []
|
|
4396
|
+
},
|
|
4397
|
+
null,
|
|
4398
|
+
2
|
|
4399
|
+
) + "\n"
|
|
4400
|
+
);
|
|
4401
|
+
} else {
|
|
4402
|
+
output.stderr(message + "\n");
|
|
4403
|
+
}
|
|
4404
|
+
return 1;
|
|
4405
|
+
}
|
|
4406
|
+
}
|
|
4407
|
+
|
|
4408
|
+
// src/cli.ts
|
|
4409
|
+
void runCli(process.argv.slice(2)).then((code) => {
|
|
4410
|
+
process.exitCode = code;
|
|
4411
|
+
});
|
|
4412
|
+
//# sourceMappingURL=cli.cjs.map
|
|
4413
|
+
//# sourceMappingURL=cli.cjs.map
|