@hit-sudomaker/ccw 0.4.1 → 0.5.1

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.
@@ -1,427 +1,128 @@
1
1
  import path from 'node:path';
2
- import { isObject, succeeded } from './machine.js';
3
- import { claudeEnvironment, json, normalizePath, success, userBinDirectory } from './model.js';
4
- import { OFFICECLI_REPO_SLUG } from './management-catalog.js';
5
- import { npmInstallArgs, npmUninstallArgs, NPM_READ_TIMEOUT_MS } from './npm-registry.js';
6
- import { NPM_ENABLE_SCRIPTS } from './npm-registry.js';
7
- export const PROGRAM_PACKAGES = {
8
- claude: '@anthropic-ai/claude-code',
9
- officecli: '@officecli/officecli',
10
- };
11
- /** 包管理器包标识与定位旗标:安装/卸载/清点与输出校验共用,字面量不得散布 */
12
- const WINGET_CLAUDE_ID = 'Anthropic.ClaudeCode';
13
- const OFFICECLI_PACKAGE_ID = 'officecli';
14
- const WINGET_ID_FLAGS = ['--id', WINGET_CLAUDE_ID];
15
- const WINGET_MATCH_FLAGS = ['--exact', '--disable-interactivity'];
16
- /** npm 安装的脚本放行旗标:恒开 ignore-scripts,claude 另放行自身脚本与可选依赖 */
17
- export const npmScriptFlags = (kind) => kind === 'claude'
18
- ? [...NPM_ENABLE_SCRIPTS, `--allow-scripts=${PROGRAM_PACKAGES.claude}`, '--include=optional']
19
- : [...NPM_ENABLE_SCRIPTS];
20
- /** OfficeCLI 官方主页的认可形状(仓库标识单一出处) */
21
- const officecliHomepage = new RegExp(`^https://(?:github\\.com/${OFFICECLI_REPO_SLUG.replaceAll('.', '\\.')}/?|officecli\\.ai/?)$`);
22
- export function officeBinary(ctx) {
23
- const root = ctx.platform === 'win32'
24
- ? path.join(ctx.localAppData ?? path.join(ctx.home, 'AppData/Local'), 'OfficeCli')
25
- : userBinDirectory(ctx);
26
- if (!path.isAbsolute(root) || path.resolve(root) === path.parse(path.resolve(root)).root)
27
- throw new Error('invalid-config-root');
28
- return path.join(root, ctx.platform === 'win32' ? 'officecli.exe' : 'officecli');
29
- }
30
- export function samePath(ctx, left, right) {
31
- return normalizePath(ctx.platform, left) === normalizePath(ctx.platform, right);
32
- }
33
- export function containsPath(ctx, directory, file) {
34
- const root = path.resolve(directory);
35
- const target = path.resolve(file);
36
- return ctx.platform === 'win32'
37
- ? target.toLowerCase().startsWith(`${root.toLowerCase()}${path.sep}`)
38
- : target.startsWith(`${root}${path.sep}`);
39
- }
40
- export function npmScopeArgs(ctx, root) {
41
- if (root === undefined)
42
- return [];
43
- const prefix = ctx.platform === 'win32' ? path.dirname(root) : path.dirname(path.dirname(root));
44
- return [`--prefix=${prefix}`];
45
- }
46
- export async function npmGlobalRoot(ctx, expected) {
47
- const result = await ctx.machine.npm(['root', '-g', ...npmScopeArgs(ctx, expected)], {
48
- timeoutMs: NPM_READ_TIMEOUT_MS,
49
- });
50
- if (result.reason === 'npm-not-found')
51
- throw new Error('npm-not-found');
52
- const root = success(result).trim();
53
- if (!path.isAbsolute(root) || /[\r\n]/.test(root))
54
- throw new Error('invalid-npm-root');
55
- return root;
56
- }
57
- /** 冻结 npm 全局根;变更命令沿用显式前缀,继续前复核当前上下文 */
58
- export async function freezeNpmScope(ctx, root) {
59
- const npmRoot = root ?? (await npmGlobalRoot(ctx));
60
- const canonical = (await ctx.machine.realpath(npmRoot)) ?? npmRoot;
61
- const matches = async (current) => samePath(ctx, (await ctx.machine.realpath(current)) ?? current, canonical);
62
- const verify = async () => {
63
- if (!(await matches(await npmGlobalRoot(ctx))) || !(await matches(await npmGlobalRoot(ctx, npmRoot))))
64
- throw new Error('program-scope-unconfirmed');
2
+ import { isObject } from './machine.js';
3
+ import { normalizePath, success } from './model.js';
4
+ import { NPM_READ_TIMEOUT_MS } from './npm-registry.js';
5
+ /**
6
+ * 读取并核验当前 npm 的全局安装范围
7
+ *
8
+ * @param ctx - 提供平台、npm 身份及路径读取能力
9
+ * @returns 经再次核验的目录、真实路径、显式范围参数和 npm 身份快照
10
+ * @throws Error - npm 不可用、目录无效或读取期间范围及身份变化时拒绝 Promise
11
+ * @remarks 仅查询现状,不创建目录;后续写入前仍需调用 verifyNpmScope
12
+ */
13
+ export async function freezeNpmScope(ctx) {
14
+ const npmRoot = await npmGlobalRoot(ctx);
15
+ const scope = {
16
+ npmRoot,
17
+ canonical: (await ctx.machine.realpath(npmRoot)) ?? npmRoot,
18
+ args: npmScopeArgs(ctx, npmRoot),
19
+ identity: await ctx.machine.npmIdentity(),
65
20
  };
66
- await verify();
67
- return { npmRoot, args: npmScopeArgs(ctx, npmRoot), verify, matches };
21
+ await verifyNpmScope(ctx, scope);
22
+ return scope;
23
+ }
24
+ /**
25
+ * 重新核验冻结的 npm 身份与全局安装范围
26
+ *
27
+ * @param ctx - 提供 npm 查询及真实路径读取能力
28
+ * @param scope - 准备阶段冻结的目录、参数和程序身份
29
+ * @returns npm 身份、默认范围及显式范围均匹配时完成,不修改目标
30
+ * @throws Error - npm 不可用、目录无效、身份或安装范围变化时拒绝 Promise
31
+ */
32
+ export async function verifyNpmScope(ctx, scope) {
33
+ const identity = await ctx.machine.npmIdentity();
34
+ if (identity.entry !== scope.identity.entry ||
35
+ identity.binary !== scope.identity.binary ||
36
+ identity.stamp !== scope.identity.stamp)
37
+ throw new Error('program-scope-unconfirmed');
38
+ for (const root of [await npmGlobalRoot(ctx), await npmGlobalRoot(ctx, scope.npmRoot)])
39
+ if (!(await matchesNpmScope(ctx, scope, root)))
40
+ throw new Error('program-scope-unconfirmed');
68
41
  }
69
- export async function npmVersion(ctx, name, root, options = {}) {
42
+ /**
43
+ * 从 npm 全局安装记录读取指定包的版本
44
+ *
45
+ * @param ctx - 提供 npm 查询及目录读取能力
46
+ * @param name - 要精确匹配的包名
47
+ * @param root - 已冻结的全局包目录;省略时检查当前默认范围,允许 npm 尚未安装
48
+ * @returns 已校验的版本;包未登记、确认全局目录缺失或默认检查中 npm 缺失时返回 null
49
+ * @throws Error - 指定范围时 npm 缺失、命令失败、安装记录异常或版本字段无效时拒绝 Promise
50
+ * @remarks 退出码 1 仍需检查返回记录,不单凭非零退出码判定失败;版本记录不证明入口存在
51
+ */
52
+ export async function npmVersion(ctx, name, root) {
70
53
  const result = await ctx.machine.npm(['ls', '-g', ...npmScopeArgs(ctx, root), '--depth=0', '--json', name], {
71
54
  timeoutMs: NPM_READ_TIMEOUT_MS,
72
55
  });
73
56
  if (result.reason === 'npm-not-found') {
74
- if (options.needsNpm)
57
+ if (root !== undefined)
75
58
  throw new Error('npm-not-found');
76
59
  return null;
77
60
  }
78
61
  if (result.failed)
79
62
  throw new Error('npm-inspection-failed');
80
- let data;
63
+ let npmResult;
81
64
  try {
82
- data = JSON.parse(result.stdout);
65
+ npmResult = JSON.parse(result.stdout);
83
66
  }
84
67
  catch {
85
68
  throw new Error('invalid-npm-result');
86
69
  }
87
- if (isObject(data) &&
88
- isObject(data.error) &&
89
- data.error.code === 'ENOENT' &&
70
+ if (isObject(npmResult) &&
71
+ isObject(npmResult.error) &&
72
+ npmResult.error.code === 'ENOENT' &&
90
73
  (await ctx.machine.treeStamp(await npmGlobalRoot(ctx, root))) === null)
91
74
  return null;
92
- // npm ls 以退出码 1 表示未安装;其余非零才是检查失败
75
+ // npm ls 的退出码 1 也可能表示未安装,仍须继续检查错误字段与依赖记录
93
76
  if (result.code !== 0 && result.code !== 1)
94
77
  throw new Error('npm-inspection-failed');
95
- if (!isObject(data) || data.error !== undefined || (Array.isArray(data.problems) && data.problems.length))
78
+ if (!isObject(npmResult) ||
79
+ npmResult.error !== undefined ||
80
+ (Array.isArray(npmResult.problems) && npmResult.problems.length))
96
81
  throw new Error('npm-inspection-failed');
97
- if (data.dependencies === undefined)
82
+ if (npmResult.dependencies === undefined)
98
83
  return null;
99
- if (!isObject(data.dependencies))
84
+ if (!isObject(npmResult.dependencies))
100
85
  throw new Error('invalid-npm-result');
101
- const entry = data.dependencies[name];
86
+ const entry = npmResult.dependencies[name];
102
87
  if (entry === undefined)
103
88
  return null;
104
89
  if (!isObject(entry) || typeof entry.version !== 'string' || !/^\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/.test(entry.version))
105
90
  throw new Error('invalid-npm-result');
106
91
  return entry.version;
107
92
  }
108
- export async function npmBinary(ctx, kind, root) {
109
- const directory = path.join(root ?? (await npmGlobalRoot(ctx)), PROGRAM_PACKAGES[kind]);
110
- if (kind === 'officecli')
111
- return path.join(directory, 'vendor', ctx.platform === 'win32' ? 'officecli.exe' : 'officecli');
112
- const manifest = await json(ctx.machine, path.join(directory, 'package.json'));
113
- const relative = typeof manifest.bin === 'string' ? manifest.bin : isObject(manifest.bin) ? manifest.bin.claude : undefined;
114
- if (typeof relative !== 'string')
115
- throw new Error('program-not-ready');
116
- const binary = path.resolve(directory, relative);
117
- if (!binary.startsWith(`${directory}${path.sep}`))
118
- throw new Error('invalid-program-entry');
119
- return binary;
120
- }
121
- /** 将已定位入口归属到唯一渠道;无法确认所有权时保持 manual */
122
- export async function identifyProgramChannel(ctx, kind, binary, canonical, native) {
123
- let channel = samePath(ctx, binary, native) ? 'native' : 'manual';
124
- if (channel === 'native' && kind === 'claude') {
125
- const versionRoot = path.join(ctx.home, '.local/share/claude/versions');
126
- if (!containsPath(ctx, versionRoot, canonical)) {
127
- const stamp = await ctx.machine.treeStamp(binary);
128
- let hasMatchingVersion = false;
129
- for (const entry of await ctx.machine.entries(versionRoot)) {
130
- if (entry.kind === 'file' && (await ctx.machine.treeStamp(path.join(versionRoot, entry.name))) === stamp) {
131
- hasMatchingVersion = true;
132
- break;
133
- }
134
- }
135
- if (!hasMatchingVersion)
136
- channel = 'manual';
137
- }
138
- }
139
- const normalized = canonical.replaceAll('\\', '/').toLowerCase();
140
- if ((kind === 'claude' && /\/caskroom\/claude-code(?:@latest)?\//.test(normalized)) ||
141
- (kind === 'officecli' && /\/cellar\/officecli\/[^/]+\/(?:[^/]+\/)*officecli$/.test(normalized)))
142
- channel = 'brew';
143
- // WinGet 便携包目录带来源段;伪造版本目录不授予渠道身份与卸载资格
144
- if (kind === 'claude' &&
145
- /\/microsoft\/winget\/packages\/anthropic\.claudecode_microsoft\.winget\.source_8wekyb3d8bbwe\/(?:[^/]+\/)*claude\.exe$/.test(normalized))
146
- channel = 'winget';
147
- if (kind === 'officecli' && normalized.includes('/apps/officecli/')) {
148
- const appRoot = /^(.*[\\/]apps[\\/]officecli[\\/][^\\/]+)/i.exec(canonical)?.[1];
149
- const manifest = appRoot === undefined ? {} : await json(ctx.machine, path.join(appRoot, 'manifest.json'));
150
- const scoopRoot = await ctx.machine.realpath(ctx.scoopRoot ?? path.join(ctx.home, 'scoop'));
151
- const appParent = appRoot === undefined ? undefined : path.dirname(appRoot);
152
- if (scoopRoot !== null &&
153
- appParent !== undefined &&
154
- samePath(ctx, appParent, path.join(scoopRoot, 'apps/officecli')) &&
155
- typeof manifest.homepage === 'string' &&
156
- officecliHomepage.test(manifest.homepage))
157
- channel = 'scoop';
158
- }
159
- if (ctx.platform === 'linux' && channel === 'manual') {
160
- for (const [manager, args] of [
161
- ['apt', ['dpkg-query', '-S', canonical]],
162
- ['dnf', ['rpm', '-qf', '--qf', '%{NAME}\n', canonical]],
163
- ['apk', ['apk', 'info', '--who-owns', canonical]],
164
- ]) {
165
- const result = await ctx.machine.execute(args[0], args.slice(1));
166
- if (!succeeded(result) || kind !== 'claude')
167
- continue;
168
- const lines = result.stdout.trim().split(/\r?\n/);
169
- const isOwned = manager === 'apt'
170
- ? lines.length === 1 &&
171
- /^claude-code(?::[A-Za-z0-9_-]+)?: /.test(lines[0] ?? '') &&
172
- lines[0]?.endsWith(`: ${canonical}`)
173
- : manager === 'dnf'
174
- ? lines.length === 1 && lines[0] === 'claude-code'
175
- : lines.length === 1 &&
176
- lines[0]?.startsWith(`${canonical} is owned by `) &&
177
- /^claude-code-\d[A-Za-z0-9._+~]*-r\d+$/.test(lines[0].slice(`${canonical} is owned by `.length));
178
- if (isOwned) {
179
- channel = manager;
180
- break;
181
- }
182
- }
183
- }
184
- return {
185
- channel,
186
- packageName: channel === 'brew' && kind === 'claude' && normalized.includes('/caskroom/claude-code@latest/')
187
- ? 'claude-code@latest'
188
- : kind === 'claude'
189
- ? 'claude-code'
190
- : OFFICECLI_PACKAGE_ID,
191
- };
192
- }
193
- export function channelCanPinVersion(channel) {
194
- return channel === 'npm' || channel === 'native' || channel === 'winget';
195
- }
196
- async function scoopTarget(ctx, program) {
197
- const result = await ctx.machine.execute('scoop', ['prefix', OFFICECLI_PACKAGE_ID]);
198
- const prefix = result.stdout.trim();
199
- if (!succeeded(result) || !path.isAbsolute(prefix) || /[\r\n]/.test(prefix))
200
- throw new Error('program-scope-unconfirmed');
201
- const current = await ctx.machine.realpath(prefix);
202
- const binary = await ctx.machine.realpath(program.binary);
203
- if (current === null || binary === null || !samePath(ctx, path.join(current, 'officecli.exe'), binary))
204
- throw new Error('program-scope-unconfirmed');
205
- return current;
206
- }
207
- const BREW_ENV = { HOMEBREW_NO_AUTO_UPDATE: '1' };
208
- async function brewPackage(ctx, program, manager) {
209
- const result = await ctx.machine.execute(manager, ['list', program.kind === 'claude' ? '--cask' : '--formula', '--versions', program.packageName], { env: BREW_ENV });
210
- const canonical = await ctx.machine.realpath(program.binary);
211
- const packageRoot = path.join(path.dirname(path.dirname(manager)), program.kind === 'claude' ? 'Caskroom' : 'Cellar', program.packageName);
212
- if (canonical === null || !containsPath(ctx, packageRoot, canonical))
213
- throw new Error('program-scope-unconfirmed');
214
- const version = path.relative(packageRoot, canonical).split(path.sep)[0];
215
- const registered = result.stdout
216
- .split(/\r?\n/)
217
- .filter(line => line.trim())
218
- .map(line => line.trim().split(/\s+/));
219
- // 无版本参数的变更命令无法绑定同一包内的多版本
220
- if (!succeeded(result) ||
221
- registered.length !== 1 ||
222
- registered[0]?.length !== 2 ||
223
- registered[0][0] !== program.packageName ||
224
- registered[0][1] !== version)
225
- throw new Error('program-scope-unconfirmed');
226
- }
227
- /** 冻结管理器与安装根;后续观察只能匹配同一包的副本 */
228
- export async function freezeProgramScope(ctx, program) {
229
- const matches = (candidate) => Promise.resolve(candidate.channel === program.channel && samePath(ctx, candidate.binary, program.binary));
230
- if (program.channel === 'npm') {
231
- const scope = await freezeNpmScope(ctx, program.npmRoot);
232
- if (!samePath(ctx, await npmBinary(ctx, program.kind, scope.npmRoot), program.binary))
233
- throw new Error('program-scope-unconfirmed');
234
- return {
235
- npmRoot: scope.npmRoot,
236
- verify: scope.verify,
237
- matches: async (candidate) => candidate.channel === 'npm' && candidate.npmRoot !== undefined && (await scope.matches(candidate.npmRoot)),
238
- };
239
- }
240
- if (program.channel === 'brew') {
241
- const canonical = await ctx.machine.realpath(program.binary);
242
- const collection = program.kind === 'claude' ? 'Caskroom' : 'Cellar';
243
- const marker = `${path.sep}${collection}${path.sep}${program.packageName}${path.sep}`;
244
- const index = canonical?.indexOf(marker) ?? -1;
245
- if (canonical === null || index < 0)
246
- throw new Error('program-scope-unconfirmed');
247
- const root = canonical.slice(0, index);
248
- const packageRoot = path.join(root, collection, program.packageName);
249
- const manager = path.join(root, 'bin/brew');
250
- const executable = await ctx.machine.realpath(manager);
251
- const stamp = executable === null ? null : await ctx.machine.treeStamp(executable);
252
- if (executable === null || stamp === null)
253
- throw new Error('program-scope-unconfirmed');
254
- const verify = async () => {
255
- const current = await ctx.machine.realpath(manager);
256
- if (current === null || !samePath(ctx, current, executable) || (await ctx.machine.treeStamp(current)) !== stamp)
257
- throw new Error('program-scope-unconfirmed');
258
- const result = await ctx.machine.execute(manager, [collection === 'Cellar' ? '--cellar' : '--caskroom'], {
259
- env: BREW_ENV,
260
- });
261
- const location = result.stdout.trim();
262
- if (!succeeded(result) ||
263
- !path.isAbsolute(location) ||
264
- /[\r\n]/.test(location) ||
265
- !samePath(ctx, (await ctx.machine.realpath(location)) ?? location, path.join(root, collection)))
266
- throw new Error('program-scope-unconfirmed');
267
- };
268
- await verify();
269
- await brewPackage(ctx, program, manager);
270
- return {
271
- manager,
272
- verify,
273
- matches: async (candidate) => {
274
- const current = await ctx.machine.realpath(candidate.binary);
275
- return (candidate.channel === 'brew' &&
276
- candidate.packageName === program.packageName &&
277
- current !== null &&
278
- containsPath(ctx, packageRoot, current));
279
- },
280
- };
281
- }
282
- if (program.channel === 'scoop') {
283
- const expected = await scoopTarget(ctx, program);
284
- return {
285
- verify: async () => {
286
- if (!samePath(ctx, await scoopTarget(ctx, program), expected))
287
- throw new Error('program-scope-unconfirmed');
288
- },
289
- matches: async (candidate) => {
290
- const current = await ctx.machine.realpath(candidate.binary);
291
- return candidate.channel === 'scoop' && current !== null && containsPath(ctx, path.dirname(expected), current);
292
- },
293
- };
294
- }
295
- return { verify: async () => { }, matches };
296
- }
297
- /** npm 渠道占用前复核:版本与二进制位都未变才继续 */
298
- async function ensureNpmProgramUnchanged(ctx, program, scope) {
299
- if ((await npmVersion(ctx, PROGRAM_PACKAGES[program.kind], scope.npmRoot)) !== program.version ||
300
- !samePath(ctx, await npmBinary(ctx, program.kind, scope.npmRoot), program.binary))
301
- throw new Error('program-changed');
302
- }
303
- /** 渠道命令分发尾:解包校验命令并先行 brew 包裹,执行与成功判据由调用方决定 */
304
- async function dispatchChannelCommand(ctx, program, commands) {
305
- const command = commands[program.channel];
306
- if (command === undefined)
307
- throw new Error('channel-not-supported');
308
- const [executable, ...args] = command;
309
- if (!executable)
310
- throw new Error('channel-not-supported');
311
- if (program.channel === 'brew')
312
- await brewPackage(ctx, program, executable);
313
- return { executable, args };
93
+ /**
94
+ * 按平台路径规则比较两个路径
95
+ *
96
+ * @returns 解析为绝对路径后是否相同,Windows 忽略大小写
97
+ * @remarks 不读取文件系统,也不解析符号链接
98
+ */
99
+ export function samePath(ctx, left, right) {
100
+ return normalizePath(ctx.platform, left) === normalizePath(ctx.platform, right);
314
101
  }
315
- export async function maintainProgramChannel(ctx, program, scope, action, targetVersion, targetRegistry, packageCommandCompleted) {
316
- if (program.channel === 'manual')
317
- throw new Error('channel-not-supported');
318
- if (program.channel === 'npm') {
319
- await ensureNpmProgramUnchanged(ctx, program, scope);
320
- const args = npmInstallArgs([
321
- 'install',
322
- '-g',
323
- ...npmScopeArgs(ctx, scope.npmRoot),
324
- ...(action === 'reinstall' ? ['--force'] : []),
325
- ...npmScriptFlags(program.kind),
326
- `${PROGRAM_PACKAGES[program.kind]}@${targetVersion}`,
327
- ], targetRegistry ?? null);
328
- success(await ctx.machine.npm(args));
329
- await packageCommandCompleted();
330
- return;
331
- }
332
- if (program.channel === 'native') {
333
- if (program.kind !== 'claude' || targetVersion === null)
334
- throw new Error('channel-not-supported');
335
- success(await ctx.machine.execute(program.binary, ['install', targetVersion, ...(action === 'reinstall' ? ['--force'] : [])], { env: claudeEnvironment(ctx), cwd: ctx.home }));
336
- await packageCommandCompleted();
337
- return;
338
- }
339
- const commands = {
340
- brew: [
341
- scope.manager ?? '',
342
- action === 'reinstall' ? 'reinstall' : 'upgrade',
343
- ...(program.kind === 'claude' ? ['--cask'] : []),
344
- program.packageName,
345
- ],
346
- winget: [
347
- 'winget',
348
- action === 'reinstall' ? 'install' : 'upgrade',
349
- ...(action === 'reinstall' ? ['--force'] : []),
350
- ...WINGET_ID_FLAGS,
351
- ...(targetVersion !== null ? ['--version', targetVersion] : []),
352
- ...WINGET_MATCH_FLAGS,
353
- ],
354
- scoop: ['scoop', 'update', ...(action === 'reinstall' ? ['--force'] : []), OFFICECLI_PACKAGE_ID],
355
- apt: [
356
- 'apt-get',
357
- 'install',
358
- '--yes',
359
- action === 'reinstall' ? '--reinstall' : '--only-upgrade',
360
- program.packageName,
361
- ],
362
- dnf: ['dnf', action === 'reinstall' ? 'reinstall' : 'upgrade', '--assumeyes', program.packageName],
363
- apk: ['apk', action === 'reinstall' ? 'fix' : 'upgrade', program.packageName],
364
- };
365
- const { executable, args } = await dispatchChannelCommand(ctx, program, commands);
366
- success(await ctx.machine.execute(executable, args, program.channel === 'brew' ? { env: BREW_ENV } : undefined));
367
- await packageCommandCompleted();
102
+ /**
103
+ * 查询 npm 全局包目录,可限定到已冻结的安装范围
104
+ *
105
+ * @param expected - 已确认的包目录;省略时读取当前默认范围
106
+ * @returns npm 返回的绝对包目录,不创建或修改目录
107
+ * @throws Error - npm 不可用、查询失败或返回路径无效时拒绝
108
+ */
109
+ export async function npmGlobalRoot(ctx, expected) {
110
+ const result = await ctx.machine.npm(['root', '-g', ...npmScopeArgs(ctx, expected)], {
111
+ timeoutMs: NPM_READ_TIMEOUT_MS,
112
+ });
113
+ if (result.reason === 'npm-not-found')
114
+ throw new Error('npm-not-found');
115
+ const root = success(result).trim();
116
+ if (!path.isAbsolute(root) || /[\r\n]/.test(root))
117
+ throw new Error('invalid-npm-root');
118
+ return root;
368
119
  }
369
- export async function removeProgramChannel(ctx, program, scope) {
370
- if (program.channel === 'npm') {
371
- await ensureNpmProgramUnchanged(ctx, program, scope);
372
- return ctx.machine.npm(npmUninstallArgs(['uninstall', '-g', ...npmScopeArgs(ctx, scope.npmRoot), PROGRAM_PACKAGES[program.kind]]));
373
- }
374
- const commands = {
375
- brew: [scope.manager ?? '', 'uninstall', ...(program.kind === 'claude' ? ['--cask'] : []), program.packageName],
376
- winget: ['winget', 'uninstall', ...WINGET_ID_FLAGS, ...WINGET_MATCH_FLAGS],
377
- scoop: ['scoop', 'uninstall', OFFICECLI_PACKAGE_ID],
378
- apt: ['apt-get', 'remove', '--yes', program.packageName],
379
- dnf: ['dnf', 'remove', '--assumeyes', program.packageName],
380
- apk: ['apk', 'del', program.packageName],
381
- };
382
- const { executable, args } = await dispatchChannelCommand(ctx, program, commands);
383
- return ctx.machine.execute(executable, args, program.channel === 'brew' ? { env: BREW_ENV } : undefined);
120
+ async function matchesNpmScope(ctx, scope, root) {
121
+ return samePath(ctx, (await ctx.machine.realpath(root)) ?? root, scope.canonical);
384
122
  }
385
- export async function programPackageAbsent(ctx, program, scope) {
386
- if (program.channel === 'brew') {
387
- await scope.verify();
388
- if (scope.manager === undefined)
389
- return null;
390
- const result = await ctx.machine.execute(scope.manager, ['list', program.kind === 'claude' ? '--cask' : '--formula', '--versions'], { env: BREW_ENV });
391
- return !succeeded(result)
392
- ? null
393
- : !result.stdout.split(/\r?\n/).some(line => line.trim().split(/\s+/)[0] === program.packageName);
394
- }
395
- if (program.channel === 'winget') {
396
- const result = await ctx.machine.execute('winget', ['list', ...WINGET_ID_FLAGS, ...WINGET_MATCH_FLAGS]);
397
- if (result.failed || result.code === null)
398
- return null;
399
- if (result.code >>> 0 === 0x8a150014)
400
- return true;
401
- // 点号转义:包标识按字面匹配,形近 ID 不得计为仍在
402
- return result.code !== 0
403
- ? null
404
- : !new RegExp(`\\b${WINGET_CLAUDE_ID.replaceAll('.', '\\.')}\\b`, 'i').test(result.stdout);
405
- }
406
- if (program.channel === 'scoop') {
407
- const result = await ctx.machine.execute('scoop', ['list', OFFICECLI_PACKAGE_ID]);
408
- return !succeeded(result)
409
- ? null
410
- : !result.stdout.split(/\r?\n/).some(line => new RegExp(`^\\s*${OFFICECLI_PACKAGE_ID}\\s`, 'i').test(line));
411
- }
412
- if (program.channel === 'apt') {
413
- const result = await ctx.machine.execute('dpkg-query', ['-W', '-f=${Package} ${db:Status-Status}\n']);
414
- return !succeeded(result)
415
- ? null
416
- : !result.stdout.split(/\r?\n/).some(line => line.trim() === `${program.packageName} installed`);
417
- }
418
- if (program.channel === 'dnf') {
419
- const result = await ctx.machine.execute('rpm', ['-qa', '--qf', '%{NAME}\n']);
420
- return !succeeded(result) ? null : !result.stdout.split(/\r?\n/).some(line => line.trim() === program.packageName);
421
- }
422
- if (program.channel === 'apk') {
423
- const result = await ctx.machine.execute('apk', ['info']);
424
- return !succeeded(result) ? null : !result.stdout.split(/\r?\n/).some(line => line.trim() === program.packageName);
425
- }
426
- return null;
123
+ function npmScopeArgs(ctx, root) {
124
+ if (root === undefined)
125
+ return [];
126
+ const prefix = ctx.platform === 'win32' ? path.dirname(root) : path.dirname(path.dirname(root));
127
+ return [`--prefix=${prefix}`];
427
128
  }