@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.
package/dist/model.js CHANGED
@@ -1,104 +1,51 @@
1
1
  import path from 'node:path';
2
2
  import { isDeepStrictEqual } from 'node:util';
3
3
  import { isObject, succeeded } from './machine.js';
4
- /** 顺序消费本次有限步骤;完成步骤只复核,继续不重新解析来源 */
5
- export function sequence(operations) {
6
- let index = 0;
7
- let active;
8
- const completed = [];
9
- const operation = {
10
- ...(operations.every(value => value.writes !== undefined)
11
- ? { writes: [...new Set(operations.flatMap(value => value.writes ?? []))] }
12
- : {}),
13
- get changes() {
14
- return [...(active ? [active] : operations.slice(index, index + 1)), ...operations.slice(index + 1)].flatMap(value => value.changes);
15
- },
16
- async run(report, signal) {
17
- for (const value of completed)
18
- await value.verify?.();
19
- while (index < operations.length) {
20
- cancelled(signal);
21
- const next = active ?? operations[index];
22
- if (!next)
23
- break;
24
- try {
25
- await next.run(report, signal);
26
- }
27
- catch (error) {
28
- active = next.remaining ? next.remaining() : next;
29
- if (!active) {
30
- completed.push(next);
31
- index++;
32
- }
33
- throw error;
34
- }
35
- completed.push(next);
36
- index++;
37
- active = undefined;
38
- }
39
- },
40
- remaining: () => (index < operations.length ? operation : undefined),
41
- async verify() {
42
- for (const value of completed)
43
- await value.verify?.();
44
- },
45
- };
46
- return operation;
47
- }
4
+ /**
5
+ * 校验配置根并推导用户配置与 CCW 存储路径
6
+ *
7
+ * @param options - 用户目录、配置根、平台及注入的系统能力
8
+ * @returns 工具域上下文,不创建目录或配置文件
9
+ * @throws Error - home、claudeRoot 或 cclineRoot 不是绝对路径或指向文件系统根
10
+ */
48
11
  export function context(options) {
49
12
  for (const directory of [options.home, options.claudeRoot, options.cclineRoot])
50
13
  if (!path.isAbsolute(directory) || path.resolve(directory) === path.parse(path.resolve(directory)).root)
51
14
  throw new Error('invalid-config-root');
52
15
  return {
53
16
  ...options,
17
+ effects: options.machine,
54
18
  settingsFile: path.join(options.claudeRoot, 'settings.json'),
55
19
  stateFile: options.claudeState ??
56
20
  path.join(options.claudeRoot === path.join(options.home, '.claude') ? options.home : options.claudeRoot, '.claude.json'),
57
21
  storage: path.join(options.home, '.ccw'),
58
22
  };
59
23
  }
60
- export function claudeEnvironment(ctx) {
61
- return { CLAUDE_CONFIG_DIR: ctx.stateFile === path.join(ctx.home, '.claude.json') ? undefined : ctx.claudeRoot };
62
- }
63
- /** POSIX 用户级可执行目录:Claude 原生安装、uv 与非 Windows OfficeCLI 的共同落点 */
24
+ /** 返回用户 .local/bin 路径,不创建目录 */
64
25
  export const userBinDirectory = (ctx) => path.join(ctx.home, '.local/bin');
65
- /** 用户级可执行目录内的平台二进制名(win32 补 .exe 后缀) */
26
+ /** 拼接用户可执行文件路径,在 Windows 下补充 .exe 后缀 */
66
27
  export const userBinary = (ctx, name) => path.join(userBinDirectory(ctx), ctx.platform === 'win32' ? `${name}.exe` : name);
67
- /** 状态文件内 MCP 注册表的键名与读取面:mcp、officecli 与退役迁移共用 */
68
- export const MCP_SERVERS_KEY = 'mcpServers';
69
- export const readMcpServers = async (ctx) => object((await json(ctx.machine, ctx.stateFile))[MCP_SERVERS_KEY]);
70
- export function claudeProcessActive(name, command) {
71
- return (/(?:^|[\\/])(?:claude|Claude Code)(?:\.exe)?$/i.test(name) ||
72
- (/(?:^|[\\/])node(?:js)?(?:\.exe)?$/i.test(name) &&
73
- /(?:^|[\\/\s"'])@anthropic-ai[\\/]claude-code(?:[\\/]|$)/i.test(command)));
74
- }
75
- /** Claude 运行判定:枚举失败保持未知(null),不臆断未运行 */
76
- export async function claudeRunning(machine, signal) {
77
- const found = await machine.processes(signal);
78
- if (found === null)
79
- return null;
80
- return found.some(entry => claudeProcessActive(entry.name, entry.command));
81
- }
82
- /** 取 id 的 kind 段;"裸 id 或 kind: 前缀"的判定一律经此,不散写 startsWith */
28
+ /** 返回标识首个冒号之前的类别;不含冒号时返回原标识 */
83
29
  export function kindOf(id) {
84
30
  return id.split(':')[0] ?? id;
85
31
  }
86
- /** 取 kind 段后的余段:data: 的类别、mcp:/skill:/plugin: 的名字;裸 id 返回 undefined */
32
+ /** 返回首个冒号之后的名字或路径;不含冒号时返回 undefined */
87
33
  export function restOf(id) {
88
34
  const index = id.indexOf(':');
89
35
  return index === -1 ? undefined : id.slice(index + 1);
90
36
  }
91
- /** Claude 用户数据清理项的固定 id:编排、路由、渲染与标题表共用 */
92
- export const CLAUDE_DATA_ID = 'data:claude';
93
- /** 「备份并替换」表单同意值:终端产生,技能与 OfficeCLI 域消费 */
94
- export const REPLACE_CONSENT = 'yes';
95
- /** 普通安装任务的默认动作:settings 项进入配置而非重装 */
96
- export const defaultInstallAction = (id) => (id === 'settings' ? 'configure' : 'install');
97
- /** 归一路径用于等价比较:win32 大小写不敏感 */
37
+ /** 解析绝对路径供比较使用;Windows 路径转为小写,不解析符号链接 */
98
38
  export function normalizePath(platform, file) {
99
39
  return platform === 'win32' ? path.resolve(file).toLowerCase() : path.resolve(file);
100
40
  }
101
- /** 读取 JSON 对象;文件缺失回退空对象,解析失败或非对象抛 invalid-settings */
41
+ /**
42
+ * 读取并解析 JSON 对象
43
+ *
44
+ * @param machine - 读取文件文本的能力,文件缺失以 null 表示
45
+ * @param file - 目标 JSON 文件路径
46
+ * @returns 解析后的对象;文件缺失时返回空对象
47
+ * @throws Error - JSON 无效或不是对象时抛出 invalid-settings;读取异常原样传播
48
+ */
102
49
  export async function json(machine, file) {
103
50
  const text = await machine.read(file);
104
51
  let value;
@@ -112,7 +59,7 @@ export async function json(machine, file) {
112
59
  throw new Error('invalid-settings');
113
60
  return value;
114
61
  }
115
- /** 归一未定义为空对象;其余非对象抛 invalid-settings */
62
+ /** 将 undefined 视为空对象,其余非对象值以 invalid-settings 拒绝 */
116
63
  export function object(value) {
117
64
  if (value === undefined)
118
65
  return {};
@@ -120,96 +67,31 @@ export function object(value) {
120
67
  throw new Error('invalid-settings');
121
68
  return value;
122
69
  }
123
- export function apiConfigurationProblem(baseUrl, hasCredential) {
124
- if (!baseUrl?.trim())
125
- return hasCredential ? 'base-url-required' : 'api-fields-required';
126
- try {
127
- const url = new URL(baseUrl.trim());
128
- if (!['http:', 'https:'].includes(url.protocol) || url.password || url.username || url.search || url.hash)
129
- return 'invalid-base-url';
130
- }
131
- catch {
132
- return 'invalid-base-url';
133
- }
134
- return hasCredential ? null : 'credential-required';
135
- }
136
- /** 命令成功返回 stdout,失败抛给定码 */
70
+ /**
71
+ * 将命令结果转换为回执,不据此确认最终效果
72
+ *
73
+ * @param result - 底层适配器返回的命令结果
74
+ * @param failure - 命令失败或未确认返回时记录的问题码
75
+ * @returns 底层标记失败或退出码缺失时为未知回执,否则记录退出码是否为零
76
+ */
77
+ export function commandReceipt(result, failure) {
78
+ return result.failed || result.code === null
79
+ ? { kind: 'unknown', failure }
80
+ : { kind: 'returned', failure: succeeded(result) ? null : failure };
81
+ }
82
+ /** 返回成功命令的 stdout;失败时抛出指定问题码 */
137
83
  export function success(result, code = 'command-failed') {
138
84
  if (!succeeded(result))
139
85
  throw new Error(code);
140
86
  return result.stdout;
141
87
  }
88
+ /** 取消信号已触发时抛出 cancelled,未提供信号时不做处理 */
142
89
  export function cancelled(signal) {
143
90
  if (signal?.aborted)
144
91
  throw new Error('cancelled');
145
92
  }
146
- /** 断言值未变化;差异抛 target-changed */
93
+ /** 深度比较当前值与冻结值;不相等时抛出 target-changed */
147
94
  export function unchanged(value, expected) {
148
95
  if (!isDeepStrictEqual(value, expected))
149
96
  throw new Error('target-changed');
150
97
  }
151
- /** 删除冻结的字段;写入后回读失败时继续确认,保留并发新增的其他字段 */
152
- export function removeFields(ctx, file, before, changes, effect, parent) {
153
- let hasAttemptedWrite = false;
154
- let isWritten = false;
155
- let isComplete = false;
156
- const absent = (values) => Object.keys(before).every(key => values[key] === undefined);
157
- const read = async () => {
158
- const document = await json(ctx.machine, file);
159
- return parent === undefined ? document : object(document[parent]);
160
- };
161
- const verify = async () => {
162
- if (!absent(await read()))
163
- throw new Error('target-changed');
164
- };
165
- const operation = {
166
- writes: [file],
167
- get changes() {
168
- return isWritten ? [{ code: 'removal-confirm' }] : changes;
169
- },
170
- async run(report, signal) {
171
- cancelled(signal);
172
- if (Object.values(before).some(value => value !== undefined) &&
173
- !isWritten &&
174
- (!hasAttemptedWrite || !absent(await read()))) {
175
- await ctx.machine.editJson(file, document => {
176
- const values = parent === undefined ? document : object(document[parent]);
177
- for (const [key, value] of Object.entries(before))
178
- unchanged(values[key], value);
179
- for (const key of Object.keys(before))
180
- delete values[key];
181
- if (parent !== undefined)
182
- document[parent] = values;
183
- hasAttemptedWrite = true;
184
- });
185
- isWritten = true;
186
- }
187
- await verify();
188
- isComplete = true;
189
- report(effect);
190
- },
191
- remaining: () => (isComplete ? undefined : operation),
192
- verify,
193
- };
194
- return operation;
195
- }
196
- /** 合并冻结字段;提交后通知,再回读确认 */
197
- export async function editFields(ctx, file, before, changes, parent, onWritten) {
198
- await ctx.machine.editJson(file, document => {
199
- const target = parent === undefined ? document : object(document[parent]);
200
- for (const [key, value] of Object.entries(changes)) {
201
- unchanged(target[key], before[key]);
202
- if (value === undefined)
203
- delete target[key];
204
- else
205
- target[key] = value;
206
- }
207
- if (parent !== undefined)
208
- document[parent] = target;
209
- });
210
- onWritten?.();
211
- const after = await json(ctx.machine, file);
212
- const values = parent === undefined ? after : object(after[parent]);
213
- for (const [key, value] of Object.entries(changes))
214
- unchanged(values[key], value);
215
- }
@@ -1,35 +1,37 @@
1
1
  import { errorCode, succeeded } from './machine.js';
2
2
  const NPM_MIRROR = 'https://registry.npmmirror.com';
3
+ /** npm 官方公共注册表 */
3
4
  export const NPM_OFFICIAL = 'https://registry.npmjs.org';
5
+ /** npm 只读子进程的最长等待时间,单位为毫秒 */
4
6
  export const NPM_READ_TIMEOUT_MS = 5_000;
5
7
  const NPM_AUDIT_FREE = ['--no-audit', '--no-fund'];
6
- /** 需要安装期脚本的包(claude、ccline)以此启用脚本执行;字面量不得散布 */
8
+ /** Claude 与 CCometixLine 所需的安装期脚本开关,集中维护该固定策略 */
7
9
  export const NPM_ENABLE_SCRIPTS = ['--ignore-scripts=false'];
8
- const queryFlags = ['--fetch-retries=0', '--fetch-timeout=4000'];
9
- const installFlags = ['--fetch-retries=1', '--fetch-timeout=30000'];
10
- /** 精确三段版本号(无前后缀) */
10
+ const QUERY_FLAGS = ['--fetch-retries=0', '--fetch-timeout=4000'];
11
+ const INSTALL_FLAGS = ['--fetch-retries=1', '--fetch-timeout=30000'];
12
+ /**
13
+ * 判断输入是否为不含前后缀的三段数字版本号
14
+ *
15
+ * @param value - 待校验的边界数据
16
+ * @returns 是否可收窄为精确版本字符串
17
+ */
11
18
  export const isExactVersion = (value) => typeof value === 'string' && /^\d+\.\d+\.\d+$/.test(value);
12
- function registryFlags(registry, packageSpec) {
13
- const scope = /^(@[a-z0-9._-]+)\/[a-z0-9._-]+(?:@[^\s]+)?$/i.exec(packageSpec)?.[1];
14
- if (scope === undefined)
15
- return [`--registry=${registry}`];
16
- return [`--registry=${registry}`, `--${scope}:registry=${registry}`];
17
- }
18
- function registries(preferred = null) {
19
- const values = preferred === null ? [null, NPM_MIRROR] : [preferred, null, NPM_MIRROR];
20
- return values.filter((value, index) => values.indexOf(value) === index);
21
- }
22
- /** 查询当前 npm 配置,并在失败或返回无效值时尝试国内镜像 */
23
- export async function resolveNpmView(machine, packageSpec, field, parse, preferred = null) {
24
- for (const registry of registries(preferred)) {
25
- const args = [
26
- 'view',
27
- packageSpec,
28
- field,
29
- '--json',
30
- ...queryFlags,
31
- ...(registry === null ? [] : registryFlags(registry, packageSpec)),
32
- ];
19
+ /**
20
+ * 从当前 npm 来源及镜像查询并校验元数据
21
+ *
22
+ * @param packageSpec - 包名及可选版本或标签
23
+ * @param field - npm view 查询字段
24
+ * @param parse - 校验解析后的 JSON,无效值返回 null
25
+ * @returns 首个有效值及来源;npm 不可用或全部查询无效时为 null
26
+ * @throws Error - 来源配置或地址无法确认、配置查询拒绝或 npm 身份变化时拒绝
27
+ * @remarks 单次查询失败或内容无效时尝试镜像;返回来源供安装绑定,不修改 npm 配置
28
+ */
29
+ export async function resolveNpmView(machine, packageSpec, field, parse) {
30
+ for (const candidate of [null, NPM_MIRROR]) {
31
+ const registry = candidate === null ? await configuredRegistry(machine, packageSpec) : publicRegistry(candidate);
32
+ if (registry === null)
33
+ return null;
34
+ const args = ['view', packageSpec, field, '--json', ...QUERY_FLAGS, ...registryFlags(registry, packageSpec)];
33
35
  try {
34
36
  const result = await machine.npm(args, { timeoutMs: NPM_READ_TIMEOUT_MS });
35
37
  if (!succeeded(result))
@@ -45,23 +47,100 @@ export async function resolveNpmView(machine, packageSpec, field, parse, preferr
45
47
  }
46
48
  return null;
47
49
  }
48
- /** 为一次已冻结来源的安装设置网络边界,不改变用户 npm 配置 */
50
+ /**
51
+ * 为安装命令绑定已冻结的公开来源及网络参数
52
+ *
53
+ * @param args - 末项为目标包的 npm 安装参数
54
+ * @param registry - 已确认的来源地址,不能为 null
55
+ * @returns 保留目标包末项并补入来源、重试及关闭审计参数的新数组
56
+ * @throws Error - 目标包缺失时抛出 invalid-npm-command,来源无效时抛出 source-registry-unconfirmed
57
+ * @remarks 仅构造参数,不执行命令或修改 npm 配置;作用域包同时绑定作用域来源
58
+ */
49
59
  export function npmInstallArgs(args, registry) {
50
60
  const target = args.at(-1);
51
61
  if (target === undefined)
52
62
  throw new Error('invalid-npm-command');
63
+ if (registry === null)
64
+ throw new Error('source-registry-unconfirmed');
53
65
  return [
54
66
  ...args.slice(0, -1),
55
67
  ...NPM_AUDIT_FREE,
56
- ...installFlags,
57
- ...(registry === null ? [] : registryFlags(registry, target)),
68
+ ...INSTALL_FLAGS,
69
+ ...registryFlags(publicRegistry(registry), target),
58
70
  target,
59
71
  ];
60
72
  }
61
- /** 卸载同样规避审计与资助的网络请求 */
73
+ /**
74
+ * 为卸载命令补入关闭审计与资助查询的参数
75
+ *
76
+ * @param args - 末项为目标包的 npm 卸载参数
77
+ * @returns 保留目标包末项的新参数数组,不执行命令
78
+ * @throws Error - 目标包缺失时抛出 invalid-npm-command
79
+ */
62
80
  export function npmUninstallArgs(args) {
63
81
  const target = args.at(-1);
64
82
  if (target === undefined)
65
83
  throw new Error('invalid-npm-command');
66
84
  return [...args.slice(0, -1), ...NPM_AUDIT_FREE, target];
67
85
  }
86
+ /**
87
+ * 比较三段数字版本,用于阻止程序降级
88
+ *
89
+ * @param left - 左侧版本,正常比较要求为三段数字
90
+ * @param right - 右侧版本,正常比较要求为三段数字
91
+ * @returns 正值表示左侧更新,负值表示右侧更新,零表示三段相同
92
+ * @remarks 仅比较前三段且缺失段按零处理;不校验输入或解析版本后缀,非数字段可能产生 NaN
93
+ */
94
+ export function compareVersions(left, right) {
95
+ const leftParts = left.split('.').map(Number);
96
+ const rightParts = right.split('.').map(Number);
97
+ for (let index = 0; index < 3; index++) {
98
+ const difference = (leftParts[index] ?? 0) - (rightParts[index] ?? 0);
99
+ if (difference !== 0)
100
+ return difference;
101
+ }
102
+ return 0;
103
+ }
104
+ // 按 npm view 的项目及用户配置解析作用域来源,再将同一来源绑定到全局安装
105
+ async function configuredRegistry(machine, packageSpec) {
106
+ const scope = packageScope(packageSpec);
107
+ for (const key of [...(scope ? [`${scope}:registry`] : []), 'registry']) {
108
+ const result = await machine.npm(['config', 'get', key], { timeoutMs: NPM_READ_TIMEOUT_MS });
109
+ if (result.reason === 'npm-not-found')
110
+ return null;
111
+ if (!succeeded(result))
112
+ throw new Error('source-registry-unconfirmed');
113
+ const value = result.stdout.trim();
114
+ if (key !== 'registry' && (value === 'undefined' || value === 'null' || value === ''))
115
+ continue;
116
+ return publicRegistry(value);
117
+ }
118
+ throw new Error('source-registry-unconfirmed');
119
+ }
120
+ function registryFlags(registry, packageSpec) {
121
+ const scope = packageScope(packageSpec);
122
+ if (scope === undefined)
123
+ return [`--registry=${registry}`];
124
+ return [`--registry=${registry}`, `--${scope}:registry=${registry}`];
125
+ }
126
+ // 冻结的来源地址不含凭据、查询参数及片段,认证仍由 npm 处理
127
+ function publicRegistry(value) {
128
+ try {
129
+ const url = new URL(value);
130
+ if (value !== value.trim() ||
131
+ /[\r\n\0]/.test(value) ||
132
+ !['https:', 'http:'].includes(url.protocol) ||
133
+ url.username ||
134
+ url.password ||
135
+ url.search ||
136
+ url.hash)
137
+ throw new Error();
138
+ return value;
139
+ }
140
+ catch {
141
+ throw new Error('source-registry-unconfirmed');
142
+ }
143
+ }
144
+ function packageScope(packageSpec) {
145
+ return /^(@[a-z0-9._-]+)\/[a-z0-9._-]+(?:@[^\s]+)?$/i.exec(packageSpec)?.[1];
146
+ }