@pikecode/api-key-manager 2.0.0 → 2.0.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.
Files changed (60) hide show
  1. package/README.md +444 -151
  2. package/bin/akm.js +340 -11
  3. package/package.json +29 -12
  4. package/src/CommandRegistry.js +58 -3
  5. package/src/commands/BaseCommand.js +68 -1
  6. package/src/commands/add/prompts.js +280 -0
  7. package/src/commands/add/providerSaver.js +74 -0
  8. package/src/commands/add/summaryPrinter.js +29 -0
  9. package/src/commands/add.js +54 -439
  10. package/src/commands/backup.js +396 -0
  11. package/src/commands/batch.js +313 -0
  12. package/src/commands/benchmark.js +323 -0
  13. package/src/commands/claude-clean.js +253 -0
  14. package/src/commands/clone.js +265 -0
  15. package/src/commands/current.js +89 -41
  16. package/src/commands/edit.js +3 -207
  17. package/src/commands/health.js +264 -0
  18. package/src/commands/list.js +120 -35
  19. package/src/commands/mcp.js +467 -0
  20. package/src/commands/remove.js +89 -26
  21. package/src/commands/stats.js +281 -0
  22. package/src/commands/switch/claude-settings-compatibility.js +113 -0
  23. package/src/commands/switch/launch-args-helper.js +84 -0
  24. package/src/commands/switch/provider-choices-helper.js +72 -0
  25. package/src/commands/switch/provider-details-helper.js +46 -0
  26. package/src/commands/switch/provider-edit-questions-helper.js +124 -0
  27. package/src/commands/switch/provider-launcher.js +20 -0
  28. package/src/commands/switch/provider-manager.js +214 -0
  29. package/src/commands/switch/status-helper.js +124 -0
  30. package/src/commands/switch/ui-screen-renderer.js +77 -0
  31. package/src/commands/switch.js +471 -958
  32. package/src/commands/validate.js +310 -0
  33. package/src/config.js +541 -55
  34. package/src/constants/index.js +234 -0
  35. package/src/constants/ui.js +108 -0
  36. package/src/index.js +11 -4
  37. package/src/navigation/EscNavigationManager.js +5 -5
  38. package/src/utils/atomic-file.js +47 -0
  39. package/src/utils/claude-settings.js +4 -4
  40. package/src/utils/codex-files.js +418 -0
  41. package/src/utils/codex-launcher.js +104 -0
  42. package/src/utils/concurrency.js +30 -0
  43. package/src/utils/config-opener.js +22 -2
  44. package/src/utils/env-launcher.js +50 -44
  45. package/src/utils/env-utils.js +52 -0
  46. package/src/utils/error-handler.js +27 -28
  47. package/src/utils/health-checker.js +350 -0
  48. package/src/utils/import-validator.js +210 -0
  49. package/src/utils/inquirer-setup.js +11 -0
  50. package/src/utils/launch-args.js +155 -0
  51. package/src/utils/logger.js +0 -1
  52. package/src/utils/provider-status-checker.js +211 -64
  53. package/src/utils/secrets.js +22 -0
  54. package/src/utils/shell-snippets.js +32 -0
  55. package/src/utils/terminal-format.js +22 -4
  56. package/src/utils/ui-helper.js +96 -86
  57. package/src/utils/update-checker.js +41 -12
  58. package/src/utils/validator.js +115 -88
  59. package/bin/cc.js +0 -101
  60. package/src/utils/storage.js +0 -55
@@ -0,0 +1,418 @@
1
+ const fs = require('fs-extra');
2
+ const path = require('path');
3
+ const os = require('os');
4
+ const { validator } = require('./validator');
5
+ const { writeFileAtomic } = require('./atomic-file');
6
+
7
+ const CODEX_DIR_NAME = '.codex';
8
+ const CONFIG_TOML_FILE = 'config.toml';
9
+ const AUTH_JSON_FILE = 'auth.json';
10
+ const BACKUP_DIR_NAME = 'akm-backups';
11
+ const BACKUP_LIMIT = 10;
12
+ let backupSequence = 0;
13
+
14
+ function resolveCodexHome() {
15
+ return process.env.CODEX_HOME || path.join(os.homedir(), CODEX_DIR_NAME);
16
+ }
17
+
18
+ function buildCodexPaths(codexHome = resolveCodexHome()) {
19
+ return {
20
+ codexHome,
21
+ configTomlPath: path.join(codexHome, CONFIG_TOML_FILE),
22
+ authJsonPath: path.join(codexHome, AUTH_JSON_FILE)
23
+ };
24
+ }
25
+
26
+ function timestampSuffix() {
27
+ const now = new Date();
28
+ const pad = num => String(num).padStart(2, '0');
29
+ return [
30
+ now.getFullYear(),
31
+ pad(now.getMonth() + 1),
32
+ pad(now.getDate()),
33
+ '_',
34
+ pad(now.getHours()),
35
+ pad(now.getMinutes()),
36
+ pad(now.getSeconds()),
37
+ String(now.getMilliseconds()).padStart(3, '0')
38
+ ].join('');
39
+ }
40
+
41
+ async function ensureCodexHome(codexHome = resolveCodexHome()) {
42
+ await fs.ensureDir(codexHome);
43
+ return codexHome;
44
+ }
45
+
46
+ async function setSecurePermissions(filePath) {
47
+ if (process.platform === 'win32') {
48
+ return;
49
+ }
50
+ try {
51
+ await fs.chmod(filePath, 0o600);
52
+ } catch {
53
+ // 忽略权限设置失败
54
+ }
55
+ }
56
+
57
+ async function setSecureDirectoryPermissions(directoryPath) {
58
+ if (process.platform === 'win32') {
59
+ return;
60
+ }
61
+ try {
62
+ await fs.chmod(directoryPath, 0o700);
63
+ } catch {
64
+ // 权限收紧失败不应掩盖原始文件备份结果。
65
+ }
66
+ }
67
+
68
+ async function readCodexFiles(codexHome = resolveCodexHome()) {
69
+ const { configTomlPath, authJsonPath } = buildCodexPaths(codexHome);
70
+ const configToml = (await fs.pathExists(configTomlPath))
71
+ ? await fs.readFile(configTomlPath, 'utf8')
72
+ : null;
73
+ const authJson = (await fs.pathExists(authJsonPath))
74
+ ? await fs.readFile(authJsonPath, 'utf8')
75
+ : null;
76
+
77
+ return {
78
+ codexHome,
79
+ configToml,
80
+ authJson
81
+ };
82
+ }
83
+
84
+ async function backupCodexFiles(codexHome = resolveCodexHome()) {
85
+ const { configTomlPath, authJsonPath } = buildCodexPaths(codexHome);
86
+ const hasConfig = await fs.pathExists(configTomlPath);
87
+ const hasAuth = await fs.pathExists(authJsonPath);
88
+ if (!hasConfig && !hasAuth) {
89
+ return null;
90
+ }
91
+
92
+ const backupRoot = path.join(codexHome, BACKUP_DIR_NAME);
93
+ const backupDir = path.join(
94
+ backupRoot,
95
+ `backup-${timestampSuffix()}-${process.pid}-${backupSequence++}`
96
+ );
97
+ await fs.ensureDir(backupRoot);
98
+ await setSecureDirectoryPermissions(backupRoot);
99
+ await fs.ensureDir(backupDir);
100
+ await setSecureDirectoryPermissions(backupDir);
101
+
102
+ if (hasConfig) {
103
+ const backupConfigPath = path.join(backupDir, CONFIG_TOML_FILE);
104
+ await fs.copy(configTomlPath, backupConfigPath);
105
+ await setSecurePermissions(backupConfigPath);
106
+ }
107
+ if (hasAuth) {
108
+ const backupAuthPath = path.join(backupDir, AUTH_JSON_FILE);
109
+ await fs.copy(authJsonPath, backupAuthPath);
110
+ await setSecurePermissions(backupAuthPath);
111
+ }
112
+
113
+ const backupDirectories = (await fs.readdir(backupRoot))
114
+ .filter(name => name.startsWith('backup-'))
115
+ .sort()
116
+ .reverse();
117
+ await Promise.all(
118
+ backupDirectories.slice(BACKUP_LIMIT).map(name => fs.remove(path.join(backupRoot, name)))
119
+ );
120
+
121
+ return backupDir;
122
+ }
123
+
124
+ /**
125
+ * 移除 config.toml 顶层(第一个 [section] 之前)的 api_base_url 字段
126
+ * 只清理顶层,不影响 [model_providers.xxx] section 内的 base_url
127
+ * @param {string} configToml - 现有的 config.toml 内容
128
+ * @returns {string} 更新后的 config.toml 内容
129
+ */
130
+ function removeTopLevelApiBaseUrl(configToml) {
131
+ if (!configToml) return configToml;
132
+
133
+ const sectionStart = configToml.search(/^\[/m);
134
+ const topLevel = sectionStart === -1 ? configToml : configToml.slice(0, sectionStart);
135
+ const rest = sectionStart === -1 ? '' : configToml.slice(sectionStart);
136
+
137
+ const cleaned = topLevel.replace(/^api_base_url\s*=\s*["']?[^"'\n]*["']?\s*\n?/m, '');
138
+ return cleaned + rest;
139
+ }
140
+
141
+ /**
142
+ * 清理 AKM 写入的 model_provider 和对应 section,不修改用户自定义配置。
143
+ * @param {string} configToml - 现有的 config.toml 内容
144
+ * @returns {string} 清理后的 TOML 内容
145
+ */
146
+ function removeAkmModelProvider(configToml) {
147
+ if (!configToml) return configToml;
148
+
149
+ const lines = configToml.split('\n');
150
+ const result = [];
151
+ let inSection = false;
152
+ let skipAkmSection = false;
153
+
154
+ for (const line of lines) {
155
+ const sectionMatch = line.match(/^\s*\[([^\]]+)\]\s*(?:#.*)?$/);
156
+ if (sectionMatch) {
157
+ inSection = true;
158
+ skipAkmSection = sectionMatch[1] === 'model_providers.akm';
159
+ if (skipAkmSection) {
160
+ continue;
161
+ }
162
+ }
163
+
164
+ if (skipAkmSection) {
165
+ continue;
166
+ }
167
+
168
+ if (!inSection && /^\s*model_provider\s*=\s*["']akm["']\s*(?:#.*)?$/.test(line)) {
169
+ continue;
170
+ }
171
+
172
+ result.push(line);
173
+ }
174
+
175
+ return result.join('\n');
176
+ }
177
+
178
+ function setTopLevelModelProvider(configToml, providerKey) {
179
+ const lines = configToml.split('\n');
180
+ let beforeFirstSection = true;
181
+ let replaced = false;
182
+
183
+ const updated = lines.map(line => {
184
+ if (/^\s*\[[^\]]+\]\s*(?:#.*)?$/.test(line)) {
185
+ beforeFirstSection = false;
186
+ }
187
+
188
+ if (beforeFirstSection && /^\s*model_provider\s*=/.test(line)) {
189
+ replaced = true;
190
+ return line.replace(/^(\s*model_provider\s*=\s*)["'][^"'\n]*["']/, `$1"${providerKey}"`);
191
+ }
192
+
193
+ return line;
194
+ });
195
+
196
+ return replaced ? updated.join('\n') : `model_provider = "${providerKey}"\n${configToml}`;
197
+ }
198
+
199
+ function replaceAkmModelProviderSection(configToml, newSection) {
200
+ const lines = configToml.split('\n');
201
+ const result = [];
202
+ let skipAkmSection = false;
203
+ let inserted = false;
204
+
205
+ for (const line of lines) {
206
+ const sectionMatch = line.match(/^\s*\[([^\]]+)\]\s*(?:#.*)?$/);
207
+ if (sectionMatch) {
208
+ skipAkmSection = sectionMatch[1] === 'model_providers.akm';
209
+ if (skipAkmSection) {
210
+ if (!inserted) {
211
+ result.push(...newSection.split('\n'), '');
212
+ inserted = true;
213
+ }
214
+ continue;
215
+ }
216
+ }
217
+
218
+ if (!skipAkmSection) {
219
+ result.push(line);
220
+ }
221
+ }
222
+
223
+ if (inserted) {
224
+ return result.join('\n');
225
+ }
226
+
227
+ return result.join('\n').trimEnd() + '\n\n' + newSection + '\n';
228
+ }
229
+
230
+ /**
231
+ * 从 config.toml 中提取当前激活的 model_provider 的 base_url
232
+ * 读取 model_provider 字段,再从对应的 [model_providers.<key>] section 中取 base_url
233
+ * @param {string} configToml - config.toml 内容
234
+ * @returns {string|null} base_url 或 null
235
+ */
236
+ function extractBaseUrlFromConfigToml(configToml) {
237
+ if (!configToml) return null;
238
+
239
+ // 读取 model_provider = "xxx"
240
+ const providerMatch = configToml.match(/^model_provider\s*=\s*["']([^"']+)["']/m);
241
+ if (!providerMatch) return null;
242
+
243
+ const providerKey = providerMatch[1];
244
+
245
+ // 在对应 section 中找 base_url
246
+ const sectionRegex = new RegExp(
247
+ `\\[model_providers\\.${providerKey}\\][^\\[]*base_url\\s*=\\s*["']([^"']+)["']`,
248
+ 's'
249
+ );
250
+ const urlMatch = configToml.match(sectionRegex);
251
+ return urlMatch ? urlMatch[1] : null;
252
+ }
253
+
254
+ /**
255
+ * 更新 config.toml 中的 model_provider 和对应的 [model_providers.akm] section
256
+ * 使用固定 key "akm" 管理 akm 切换的供应商,不影响用户其他自定义配置
257
+ * @param {string} configToml - 现有的 config.toml 内容
258
+ * @param {string} baseUrl - 新供应商的 base_url
259
+ * @returns {string} 更新后的 config.toml 内容
260
+ */
261
+ function updateModelProvider(configToml, baseUrl) {
262
+ if (!configToml) configToml = '';
263
+
264
+ const providerKey = 'akm';
265
+ const newSection = [
266
+ `[model_providers.${providerKey}]`,
267
+ `name = "${providerKey}"`,
268
+ `base_url = "${baseUrl}"`,
269
+ 'wire_api = "responses"',
270
+ 'requires_openai_auth = true'
271
+ ].join('\n');
272
+
273
+ const result = setTopLevelModelProvider(configToml, providerKey);
274
+ return replaceAkmModelProviderSection(result, newSection);
275
+ }
276
+
277
+ /**
278
+ * @param {string} apiKey - API Key
279
+ * @returns {string} auth.json 内容
280
+ */
281
+ function buildAuthJson(apiKey) {
282
+ return JSON.stringify({ auth_mode: 'apikey', OPENAI_API_KEY: apiKey }, null, 2);
283
+ }
284
+
285
+ async function readExistingAuthJson(authJsonPath) {
286
+ if (!(await fs.pathExists(authJsonPath))) {
287
+ return {};
288
+ }
289
+
290
+ try {
291
+ const data = await fs.readJson(authJsonPath);
292
+ if (!data || typeof data !== 'object' || Array.isArray(data)) {
293
+ throw new Error('认证文件必须是 JSON 对象');
294
+ }
295
+ return data;
296
+ } catch (error) {
297
+ throw new Error(`Codex auth.json 格式无效,已停止写入: ${error.message}`);
298
+ }
299
+ }
300
+
301
+ async function readFileSnapshot(filePath) {
302
+ if (!(await fs.pathExists(filePath))) {
303
+ return { exists: false, content: null, mode: 0o600 };
304
+ }
305
+
306
+ const [content, stat] = await Promise.all([
307
+ fs.readFile(filePath),
308
+ fs.stat(filePath)
309
+ ]);
310
+ return {
311
+ exists: true,
312
+ content,
313
+ mode: stat.mode & 0o777
314
+ };
315
+ }
316
+
317
+ async function restoreFileSnapshot(filePath, snapshot) {
318
+ if (!snapshot.exists) {
319
+ await fs.remove(filePath);
320
+ return;
321
+ }
322
+
323
+ await writeFileAtomic(filePath, snapshot.content, { mode: snapshot.mode });
324
+ }
325
+
326
+ async function rollbackCodexFiles(paths, snapshots) {
327
+ await Promise.all([
328
+ restoreFileSnapshot(paths.authJsonPath, snapshots.authJson),
329
+ restoreFileSnapshot(paths.configTomlPath, snapshots.configToml)
330
+ ]);
331
+ }
332
+
333
+ /**
334
+ * 应用 Codex 配置(写入 auth.json,更新 config.toml 中的 provider 路由)
335
+ * akm 负责:
336
+ * 1. 写入 auth.json(API Key)
337
+ * 2. 更新 config.toml 中的 model_provider 和 [model_providers.akm] section
338
+ * 3. 清理之前错误写入的顶层 api_base_url 字段
339
+ * @param {object} config - 供应商配置
340
+ * @param {object} options - 选项
341
+ * @returns {Promise<{codexHome: string}>}
342
+ */
343
+ async function applyCodexConfig(config, options = {}) {
344
+ if (!config || !config.authToken) {
345
+ throw new Error('Codex 配置缺少 API Key');
346
+ }
347
+
348
+ if (config.baseUrl) {
349
+ const baseUrlError = validator.validateUrl(config.baseUrl);
350
+ if (baseUrlError) {
351
+ throw new Error(`Codex 基础 URL 无效: ${baseUrlError}`);
352
+ }
353
+ }
354
+
355
+ const codexHome = await ensureCodexHome(options.codexHome);
356
+ const { configTomlPath, authJsonPath } = buildCodexPaths(codexHome);
357
+
358
+ const snapshots = {
359
+ authJson: await readFileSnapshot(authJsonPath),
360
+ configToml: await readFileSnapshot(configTomlPath)
361
+ };
362
+
363
+ // 所有旧文件必须在任何写入发生前完成校验和目标内容计算。
364
+ await readExistingAuthJson(authJsonPath);
365
+ const authJsonContent = buildAuthJson(config.authToken);
366
+ let nextConfigToml = null;
367
+ const existingToml = snapshots.configToml.exists
368
+ ? snapshots.configToml.content.toString('utf8')
369
+ : '';
370
+
371
+ if (config.baseUrl) {
372
+ nextConfigToml = updateModelProvider(removeTopLevelApiBaseUrl(existingToml), config.baseUrl);
373
+ } else if (snapshots.configToml.exists) {
374
+ const cleanedToml = removeAkmModelProvider(removeTopLevelApiBaseUrl(existingToml));
375
+ if (cleanedToml !== existingToml) {
376
+ nextConfigToml = cleanedToml;
377
+ }
378
+ }
379
+
380
+ // 修改用户 Codex 文件前保留最近备份,便于恢复登录态和自定义配置。
381
+ await backupCodexFiles(codexHome);
382
+
383
+ const writeFile = options.writeFile || writeFileAtomic;
384
+ try {
385
+ await writeFile(authJsonPath, authJsonContent, { encoding: 'utf8', mode: 0o600 });
386
+ await setSecurePermissions(authJsonPath);
387
+
388
+ if (nextConfigToml !== null) {
389
+ await writeFile(configTomlPath, nextConfigToml, { encoding: 'utf8', mode: 0o600 });
390
+ await setSecurePermissions(configTomlPath);
391
+ }
392
+ } catch (error) {
393
+ try {
394
+ await rollbackCodexFiles({ authJsonPath, configTomlPath }, snapshots);
395
+ } catch (rollbackError) {
396
+ throw new Error(
397
+ `应用 Codex 配置失败且回滚失败: ${error.message}; ${rollbackError.message}`,
398
+ { cause: error }
399
+ );
400
+ }
401
+ throw new Error(`应用 Codex 配置失败,已恢复原文件: ${error.message}`, { cause: error });
402
+ }
403
+
404
+ return { codexHome };
405
+ }
406
+
407
+ module.exports = {
408
+ resolveCodexHome,
409
+ buildCodexPaths,
410
+ readCodexFiles,
411
+ applyCodexConfig,
412
+ backupCodexFiles,
413
+ removeTopLevelApiBaseUrl,
414
+ removeAkmModelProvider,
415
+ extractBaseUrlFromConfigToml,
416
+ updateModelProvider,
417
+ buildAuthJson
418
+ };
@@ -0,0 +1,104 @@
1
+ const spawn = require('cross-spawn');
2
+ const { sanitizeEnvValue, clearTerminal } = require('./env-utils');
3
+ const { applyCodexConfig } = require('./codex-files');
4
+ const { assertSupportedLaunchArgs } = require('./launch-args');
5
+ const { validator } = require('./validator');
6
+
7
+ /**
8
+ * 构建 Codex CLI 环境变量
9
+ * @param {object} config - 供应商配置
10
+ * @returns {object} 环境变量对象
11
+ */
12
+ function buildCodexEnvVariables(config) {
13
+ const env = { ...process.env };
14
+
15
+ delete env.OPENAI_API_KEY;
16
+ delete env.OPENAI_BASE_URL;
17
+ delete env.OPENAI_MODEL;
18
+
19
+ try {
20
+ // Codex CLI 使用 OpenAI 环境变量
21
+ if (config.authToken) {
22
+ env.OPENAI_API_KEY = sanitizeEnvValue(config.authToken);
23
+ }
24
+
25
+ if (config.baseUrl) {
26
+ const baseUrlError = validator.validateUrl(config.baseUrl);
27
+ if (baseUrlError) {
28
+ throw new Error(baseUrlError);
29
+ }
30
+ env.OPENAI_BASE_URL = sanitizeEnvValue(config.baseUrl);
31
+ }
32
+
33
+ // 支持自定义模型
34
+ if (config.models && config.models.primary) {
35
+ env.OPENAI_MODEL = sanitizeEnvValue(config.models.primary);
36
+ }
37
+
38
+ return env;
39
+ } catch (error) {
40
+ throw new Error(`配置验证失败: ${error.message}\n请使用 'akm edit ${config.name}' 修复配置`);
41
+ }
42
+ }
43
+
44
+ /**
45
+ * 使用环境变量注入方式执行 Codex CLI
46
+ * @param {object} config - 供应商配置
47
+ * @param {string[]} launchArgs - 启动参数
48
+ * @returns {Promise<void>}
49
+ */
50
+ async function executeCodexWithEnv(config, launchArgs = []) {
51
+ if (!config || config.ideName !== 'codex') {
52
+ throw new Error('无效的 Codex 供应商配置');
53
+ }
54
+
55
+ if (!config.authToken) {
56
+ throw new Error(`供应商 '${config.name}' 未配置 API Key,请使用 'akm edit ${config.name}' 添加`);
57
+ }
58
+
59
+ assertSupportedLaunchArgs('codex', launchArgs);
60
+
61
+ // 在写入 Codex 配置文件前完成全部输入校验。
62
+ const env = buildCodexEnvVariables(config);
63
+
64
+ // 写入 ~/.codex/config.toml 和 ~/.codex/auth.json
65
+ // 确保 Codex CLI 使用 API Key 认证方式
66
+ // 这样用户也可以直接运行 `codex` 命令而无需通过 akm
67
+ await applyCodexConfig(config);
68
+
69
+ // 处理参数:子命令放前面,选项放后面
70
+ const rawArgs = Array.isArray(launchArgs) ? [...launchArgs] : [];
71
+ const subcommands = rawArgs.filter(arg => !arg.startsWith('-'));
72
+ const options = rawArgs.filter(arg => arg.startsWith('-'));
73
+ const args = [...subcommands, ...options];
74
+
75
+ clearTerminal();
76
+
77
+ console.log('\n启动 Codex CLI...\n');
78
+
79
+ return new Promise((resolve, reject) => {
80
+ const child = spawn('codex', args, {
81
+ stdio: 'inherit',
82
+ env,
83
+ shell: false
84
+ });
85
+
86
+ child.on('close', (code) => {
87
+ if (code === 0) {
88
+ resolve();
89
+ } else {
90
+ reject(new Error(`Codex CLI 退出,退出代码: ${code}\n提示: 请检查 API 配置是否正确`));
91
+ }
92
+ });
93
+
94
+ child.on('error', (error) => {
95
+ if (error.code === 'ENOENT') {
96
+ reject(new Error('找不到 codex 命令\n请先安装 Codex CLI: npm i -g @openai/codex 或 brew install --cask codex'));
97
+ } else {
98
+ reject(new Error(`启动 Codex CLI 失败: ${error.message}`));
99
+ }
100
+ });
101
+ });
102
+ }
103
+
104
+ module.exports = { executeCodexWithEnv, buildCodexEnvVariables };
@@ -0,0 +1,30 @@
1
+ async function mapWithConcurrency(items, limit, mapper) {
2
+ if (!Array.isArray(items)) {
3
+ throw new TypeError('items 必须是数组');
4
+ }
5
+ if (!Number.isInteger(limit) || limit < 1) {
6
+ throw new TypeError('并发上限必须是正整数');
7
+ }
8
+ if (typeof mapper !== 'function') {
9
+ throw new TypeError('mapper 必须是函数');
10
+ }
11
+ if (items.length === 0) {
12
+ return [];
13
+ }
14
+
15
+ const results = new Array(items.length);
16
+ let nextIndex = 0;
17
+
18
+ async function worker() {
19
+ while (nextIndex < items.length) {
20
+ const currentIndex = nextIndex++;
21
+ results[currentIndex] = await mapper(items[currentIndex], currentIndex);
22
+ }
23
+ }
24
+
25
+ const workerCount = Math.min(limit, items.length);
26
+ await Promise.all(Array.from({ length: workerCount }, () => worker()));
27
+ return results;
28
+ }
29
+
30
+ module.exports = { mapWithConcurrency };
@@ -1,3 +1,9 @@
1
+ /**
2
+ * Config Opener Utility
3
+ * 使用默认应用打开配置文件
4
+ * @module utils/config-opener
5
+ */
6
+
1
7
  const fs = require('fs-extra');
2
8
  const path = require('path');
3
9
  const os = require('os');
@@ -5,10 +11,19 @@ const { spawn } = require('child_process');
5
11
 
6
12
  const AKM_CONFIG_FILE = path.join(os.homedir(), '.akm-config.json');
7
13
 
14
+ /**
15
+ * 检查配置文件是否存在
16
+ * @returns {Promise<boolean>} 文件是否存在
17
+ */
8
18
  function ensureConfigExists() {
9
19
  return fs.pathExists(AKM_CONFIG_FILE);
10
20
  }
11
21
 
22
+ /**
23
+ * 使用系统默认应用打开文件
24
+ * @param {string} filePath - 文件路径
25
+ * @returns {Promise<void>}
26
+ */
12
27
  function openFileWithDefaultApp(filePath) {
13
28
  return new Promise((resolve, reject) => {
14
29
  let command;
@@ -34,9 +49,14 @@ function openFileWithDefaultApp(filePath) {
34
49
 
35
50
  async function openAKMConfigFile() {
36
51
  if (!(await ensureConfigExists())) {
37
- throw new Error('未找到 ~/.akm-config.json,请先运行 akm add 创建配置');
52
+ throw new Error('未找到配置文件 ~/.akm-config.json\n请先运行 \'akm add\' 创建第一个供应商配置');
53
+ }
54
+
55
+ try {
56
+ await openFileWithDefaultApp(AKM_CONFIG_FILE);
57
+ } catch (error) {
58
+ throw new Error(`无法打开配置文件: ${error.message}\n配置文件位置: ${AKM_CONFIG_FILE}`);
38
59
  }
39
- await openFileWithDefaultApp(AKM_CONFIG_FILE);
40
60
  }
41
61
 
42
62
  module.exports = {