dsh-app-updater 1.3.2 → 1.3.4

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/lib/macos.js CHANGED
@@ -1,409 +1,494 @@
1
- /**
2
- * macOS 应用清单:把「本机装了哪些应用」真正列出来。
3
- *
4
- * 为什么需要这个模块:1.3.x 的 macOS 扫描只读了 `brew list --cask`,也就是
5
- * **只有通过 Homebrew 装过的应用才会出现在列表里**。一台正常使用的 Mac 上,
6
- * 绝大多数应用是拖 DMG 装的,于是 `brew list --cask` 返回空 → 界面显示
7
- * 「未检测到任何已安装应用」。这不是「没有应用」,而是**没有枚举应用**。
8
- *
9
- * 现在的做法:
10
- * 1. 枚举标准应用目录里的 `.app`(/Applications、/System/Applications 及其
11
- * Utilities 子目录、~/Applications),从每个 bundle 的 Info.plist 读版本;
12
- * 2. 用 Homebrew 的 cask 目录(formulae.brew.sh,缓存一天)把 `.app` 反向匹配到
13
- * cask token,从而知道**官网最新版本**;
14
- * 3. 只有「确实由 Homebrew 管理」的应用才标记为可一键更新 —— 其余应用如实列出,
15
- * 但标注为不可由本插件更新,绝不假装能更新。
16
- *
17
- * 这里只做「读」,不改动任何东西;所有命令都是绝对路径 + 参数数组,不经 shell。
18
- */
19
-
20
- import { readdir, readFile, writeFile, mkdir } from "node:fs/promises";
21
- import { existsSync } from "node:fs";
22
- import { join } from "node:path";
23
- import { homedir } from "node:os";
24
-
25
- import { runProcess } from "./proc.js";
26
- import { dataDir } from "./state.js";
27
- import { isNewer, looksLikeVersion } from "./version.js";
28
-
29
- /** macOS 放应用的标准目录(约定:这些目录第一层就是 `.app`)。 */
30
- export function applicationDirs(home = homedir()) {
31
- // 这些是 macOS 的 POSIX 路径,用字符串拼接而不是 path.join:
32
- // join 在 Windows 上会产出反斜杠,跨平台跑单测时就对不上了。
33
- const h = String(home || "").replace(/\/+$/, "");
34
- return [
35
- "/Applications",
36
- "/Applications/Utilities",
37
- "/System/Applications",
38
- "/System/Applications/Utilities",
39
- `${h}/Applications`,
40
- ];
41
- }
42
-
43
- /** cask 目录的缓存文件(放插件自己的数据目录,不碰宿主配置)。 */
44
- export function catalogCachePath(dir) {
45
- return join(dir || dataDir(), "cask-catalog.json");
46
- }
47
-
48
- const CATALOG_URL = "https://formulae.brew.sh/api/cask.json";
49
- const CATALOG_TTL_MS = 24 * 60 * 60 * 1000;
50
-
51
- /**
52
- * 从 cask 目录 JSON 建索引:
53
- * - byApp:`.app` 文件名(小写)→ 条目**数组**,用来「从已装应用反查 cask」;
54
- * - byToken:cask token → 条目,用来「从已装 cask 正查最新版本」。
55
- *
56
- * 一个 .app 可能被多个 cask 声明(例如 `iterm2` 与 `iterm2@nightly` 都装
57
- * `iTerm.app`),只留最后一个会让匹配随目录顺序漂移 —— 所以这里保留全部候选,
58
- * 由 pickCask 按「已装 > 非 nightly/非弃用 > token 精确匹配」挑选。
59
- *
60
- * @param {any} list formulae.brew.sh/api/cask.json 的内容
61
- */
62
- export function parseCaskCatalog(list) {
63
- const byApp = new Map();
64
- const byToken = new Map();
65
- const addCandidate = (appName, entry) => {
66
- const key = String(appName).toLowerCase();
67
- const bucket = byApp.get(key);
68
- if (bucket) bucket.push(entry);
69
- else byApp.set(key, [entry]);
70
- };
71
- for (const c of Array.isArray(list) ? list : []) {
72
- if (!c || typeof c !== "object" || !c.token) continue;
73
- const appNames = [];
74
- for (const art of Array.isArray(c.artifacts) ? c.artifacts : []) {
75
- if (!art || typeof art !== "object") continue;
76
- for (const raw of Array.isArray(art.app) ? art.app : []) {
77
- // 形如 "$APPDIR/Foo.app" 或 "Foo.app",只取最后一段
78
- const base = String(raw).split("/").pop();
79
- if (base && /\.app$/i.test(base)) appNames.push(base);
80
- }
81
- }
82
- const entry = {
83
- token: String(c.token),
84
- version: String(c.version == null ? "" : c.version).trim(),
85
- name: Array.isArray(c.name) && c.name.length ? String(c.name[0]) : String(c.token),
86
- appNames,
87
- deprecated: Boolean(c.deprecated),
88
- disabled: Boolean(c.disabled),
89
- autoUpdates: Boolean(c.auto_updates),
90
- };
91
- byToken.set(entry.token, entry);
92
- for (const appName of appNames) addCandidate(appName, entry);
93
- }
94
- return { byApp, byToken };
95
- }
96
-
97
- /** token 里的变体后缀(iterm2@nightly → iterm2),用于排序时优先主 cask。 */
98
- function baseToken(token) {
99
- return String(token || "").split("@")[0];
100
- }
101
-
102
- /**
103
- * 在多个候选 cask 里挑出最可能是「这个 .app 对应的那个 cask」。
104
- *
105
- * 优先级(越靠前越优先):
106
- * 1. 已安装(token 出现在 brews 里)—— 已装的就是用户实际在用的那个;
107
- * 2. 非 deprecated / disabled;
108
- * 3. 主 token(不带 @nightly 这类变体后缀);
109
- * 4. token 与应用名/应用文件名归一化后相等。
110
- */
111
- export function pickCask(candidates, { appName, bundleName, brews = new Map() } = {}) {
112
- if (!Array.isArray(candidates) || !candidates.length) return null;
113
- const keys = new Set([normalizeAppKey(appName), normalizeAppKey(bundleName)].filter(Boolean));
114
- const score = (entry) => {
115
- let s = 0;
116
- if (brews.has(entry.token)) s += 100;
117
- if (!entry.deprecated && !entry.disabled) s += 10;
118
- if (entry.token === baseToken(entry.token)) s += 5;
119
- if (keys.has(normalizeAppKey(entry.token))) s += 3;
120
- for (const n of entry.appNames) if (keys.has(normalizeAppKey(n))) s += 1;
121
- return s;
122
- };
123
- let best = candidates[0];
124
- let bestScore = score(best);
125
- for (const candidate of candidates.slice(1)) {
126
- const s = score(candidate);
127
- if (s > bestScore) {
128
- best = candidate;
129
- bestScore = s;
130
- }
131
- }
132
- return best;
133
- }
134
-
135
- /** 名字归一化:去掉 .app、空格与标点,只留字母数字,用于 token ↔ 应用名兜底匹配。 */
136
- export function normalizeAppKey(name) {
137
- return String(name || "")
138
- .replace(/\.app$/i, "")
139
- .toLowerCase()
140
- .replace(/[^a-z0-9]+/g, "");
141
- }
142
-
143
- /**
144
- * 在标准应用目录里找 `.app`(不进入 bundle 内部,避免把框架当应用)。
145
- * @returns {Promise<string[]>} 绝对路径,已去重
146
- */
147
- export async function listAppBundles(dirs, depth = 1) {
148
- const found = [];
149
- const seen = new Set();
150
- const walk = async (dir, level) => {
151
- let entries;
152
- try {
153
- entries = await readdir(dir, { withFileTypes: true });
154
- } catch {
155
- return; // 目录不存在 / 无权限:跳过,不影响其它目录
156
- }
157
- for (const entry of entries) {
158
- const full = join(dir, entry.name);
159
- if (/\.app$/i.test(entry.name)) {
160
- if (!seen.has(full)) {
161
- seen.add(full);
162
- found.push(full);
163
- }
164
- continue;
165
- }
166
- if (level > 0 && (entry.isDirectory() || entry.isSymbolicLink())) {
167
- await walk(full, level - 1);
168
- }
169
- }
170
- };
171
- for (const dir of dirs) await walk(dir, depth);
172
- return found;
173
- }
174
-
175
- /** 用 plutil 读 Info.plist(macOS 自带,binary plist 也能转 JSON)。 */
176
- async function readInfoPlist(appPath) {
177
- const plist = join(appPath, "Contents", "Info.plist");
178
- const res = await runProcess("/usr/bin/plutil", ["-convert", "json", "-o", "-", plist], { timeoutMs: 15000 });
179
- if (!res.ok) return null;
180
- try {
181
- return JSON.parse(res.stdout);
182
- } catch {
183
- return null;
184
- }
185
- }
186
-
187
- /**
188
- * 读一个 `.app` 的元信息。
189
- * @returns {Promise<{path:string,bundleName:string,name:string,version:string,bundleId:string,appStore:boolean,system:boolean}>}
190
- */
191
- export async function readAppBundle(appPath) {
192
- // macOS 上路径一定用 /,但单测在 Windows 上跑,两种分隔符都要能取到最后一段
193
- const bundleName = String(appPath).split(/[\\/]/).filter(Boolean).pop() || String(appPath);
194
- const info = {
195
- path: appPath,
196
- bundleName,
197
- name: bundleName.replace(/\.app$/i, ""),
198
- version: "",
199
- bundleId: "",
200
- appStore: existsSync(join(appPath, "Contents", "_MASReceipt", "receipt")),
201
- system: appPath.startsWith("/System/"),
202
- };
203
- const plist = await readInfoPlist(appPath);
204
- if (plist) {
205
- const short = plist.CFBundleShortVersionString;
206
- const bundle = plist.CFBundleVersion;
207
- info.version = String(short || bundle || "").trim();
208
- info.bundleId = String(plist.CFBundleIdentifier || "").trim();
209
- const display = plist.CFBundleDisplayName || plist.CFBundleName;
210
- if (display) info.name = String(display).trim();
211
- }
212
- if (!info.version) {
213
- // plutil 失败时的兜底:defaults 直接读单个键
214
- const res = await runProcess(
215
- "/usr/bin/defaults",
216
- ["read", join(appPath, "Contents", "Info"), "CFBundleShortVersionString"],
217
- { timeoutMs: 15000 }
218
- );
219
- if (res.ok) info.version = res.stdout.trim();
220
- }
221
- return info;
222
- }
223
-
224
- /** 枚举并读取全部已安装应用(并发有限,避免一次开几百个进程)。 */
225
- export async function scanAppBundles({ dirs, log, concurrency = 8 } = {}) {
226
- const paths = await listAppBundles(dirs || applicationDirs());
227
- const out = [];
228
- let index = 0;
229
- const worker = async () => {
230
- while (index < paths.length) {
231
- const current = paths[index];
232
- index += 1;
233
- try {
234
- out.push(await readAppBundle(current));
235
- } catch {
236
- /* 单个 bundle 读不出来不影响其它应用 */
237
- }
238
- }
239
- };
240
- await Promise.all(Array.from({ length: Math.min(concurrency, paths.length || 1) }, worker));
241
- if (log) log("info", `在应用目录里找到 ${out.length} 个 .app`);
242
- return out;
243
- }
244
-
245
- /** 读缓存的 cask 目录(超过 TTL 视为没有缓存)。 */
246
- export async function readCatalogCache(file, now = Date.now()) {
247
- try {
248
- const raw = JSON.parse(await readFile(file, "utf8"));
249
- if (!raw || typeof raw.fetchedAt !== "number") return null;
250
- if (now - raw.fetchedAt > CATALOG_TTL_MS) return null;
251
- return raw.list || null;
252
- } catch {
253
- return null;
254
- }
255
- }
256
-
257
- /** 抓取 cask 目录并写缓存;失败返回 null(调用方降级,不中断扫描)。 */
258
- export async function fetchCaskCatalog({ file, log, warnings, fetchImpl } = {}) {
259
- const cacheFile = file || catalogCachePath();
260
- const cached = await readCatalogCache(cacheFile);
261
- if (cached) return cached;
262
-
263
- const run = fetchImpl || (async () => {
264
- const res = await runProcess("/usr/bin/curl", ["-fsSL", "--max-time", "120", CATALOG_URL], { timeoutMs: 180000 });
265
- if (!res.ok) {
266
- throw new Error(String(res.stderr || "").trim().split("\n")[0] || `curl 退出码 ${res.code}`);
267
- }
268
- return JSON.parse(res.stdout);
269
- });
270
-
271
- try {
272
- const list = await run();
273
- if (!Array.isArray(list)) throw new Error("cask 目录格式不符合预期");
274
- try {
275
- await mkdir(dataDir(), { recursive: true });
276
- await writeFile(cacheFile, JSON.stringify({ fetchedAt: Date.now(), list }), "utf8");
277
- } catch {
278
- /* 缓存写不进去不影响本次扫描 */
279
- }
280
- if (log) log("info", `已读取 Homebrew cask 目录(${list.length} 个 cask)`);
281
- return list;
282
- } catch (err) {
283
- const message = String((err && err.message) || err);
284
- if (warnings) warnings.push(`读取 Homebrew cask 目录失败(不影响列出应用,但无法判断是否有新版本):${message}`);
285
- if (log) log("warn", `读取 Homebrew cask 目录失败:${message}`);
286
- return null;
287
- }
288
- }
289
-
290
- /**
291
- * 组装 macOS 应用列表(纯函数,便于单测)。
292
- *
293
- * @param {object} input
294
- * @param {Array} input.apps 已安装的 .app(scanAppBundles 的结果)
295
- * @param {Map<string,string>} input.brews 已装 cask:token → 已装版本
296
- * @param {Map<string,string>} input.outdated 可升级 cask:token → 可用版本
297
- * @param {{byApp:Map,byToken:Map}|null} input.catalog cask 目录索引
298
- * @param {object} input.settings
299
- * @returns {{items:Array, warnings:string[]}}
300
- */
301
- export function buildMacosItems({ apps = [], brews = new Map(), outdated = new Map(), catalog = null, settings = {} }) {
302
- const warnings = [];
303
- const items = [];
304
- const byApp = catalog ? catalog.byApp : new Map();
305
- const byToken = catalog ? catalog.byToken : new Map();
306
- /** 已被某个 .app 认领的 cask token,避免重复列出 */
307
- const claimed = new Set();
308
-
309
- // 没有 cask 目录时也能把「已装 cask」和 .app 对上:用 token 名归一化匹配,
310
- // 否则同一个应用会既作为 .app 出现、又作为 brew 条目再出现一次。
311
- const brewByName = new Map();
312
- for (const token of brews.keys()) brewByName.set(normalizeAppKey(token), token);
313
-
314
- const matchCask = (app) => {
315
- const direct = byApp.get(String(app.bundleName || "").toLowerCase());
316
- if (direct && direct.length) {
317
- return pickCask(direct, { appName: app.name, bundleName: app.bundleName, brews });
318
- }
319
- const key = normalizeAppKey(app.name || app.bundleName);
320
- for (const entry of byToken.values()) {
321
- if (normalizeAppKey(entry.token) === key) return entry;
322
- for (const appName of entry.appNames) {
323
- if (normalizeAppKey(appName) === key) return entry;
324
- }
325
- }
326
- const token = brewByName.get(key);
327
- if (token) return { token, version: "", name: token, appNames: [] };
328
- return null;
329
- };
330
-
331
- for (const app of apps) {
332
- // 注意:只有**显式**设为 false 才过滤。settings 缺字段时按默认「包含」处理,
333
- // 否则单测/老状态文件里缺字段会把应用整批吞掉。
334
- if (settings.includeStoreApps === false && app.appStore) continue;
335
- const cask = matchCask(app);
336
- const managed = Boolean(cask && brews.has(cask.token));
337
- // 非 Homebrew 管理的应用:默认列出(includeUnmanagedApps),关掉后只看 Homebrew 应用
338
- if (!managed && settings.includeUnmanagedApps === false) continue;
339
- if (cask && managed) claimed.add(cask.token);
340
-
341
- const latest = cask && looksLikeVersion(cask.version) ? cask.version : "";
342
- const forced = managed && outdated.get(cask.token) ? String(outdated.get(cask.token)) : "";
343
-
344
- let available = "";
345
- if (managed) {
346
- if (forced) available = forced;
347
- else if (latest && looksLikeVersion(app.version) && isNewer(latest, app.version)) available = latest;
348
- }
349
-
350
- let reason = null;
351
- if (app.system && !managed) reason = "system-component";
352
- else if (app.appStore && !managed) reason = "store-managed";
353
- else if (!managed) reason = "not-managed";
354
-
355
- const hasUpdate = Boolean(managed && available);
356
- items.push({
357
- id: managed ? `brew:${cask.token}` : `macapp:${app.bundleId || app.bundleName}`,
358
- name: app.name || app.bundleName,
359
- version: app.version || "",
360
- available,
361
- publisher: cask ? `Homebrew cask · ${cask.token}` : app.bundleId || "",
362
- source: managed ? "homebrew" : app.appStore ? "appstore" : "app",
363
- installLocation: app.path,
364
- hasUpdate,
365
- updateSupported: hasUpdate,
366
- reason: hasUpdate ? null : reason,
367
- kind: managed ? "cask" : "app",
368
- });
369
- }
370
-
371
- // 通过 Homebrew 装的、但标准目录里没找到 .app 的(字体、命令行 cask 等)也要列出来。
372
- // 它们本来就由 Homebrew 管理,不受「包含非 Homebrew 应用」开关影响。
373
- for (const [token, version] of brews) {
374
- if (claimed.has(token)) continue;
375
- const entry = byToken.get(token);
376
- const forced = outdated.get(token) ? String(outdated.get(token)) : "";
377
- const latest = entry && looksLikeVersion(entry.version) ? entry.version : "";
378
- let available = "";
379
- if (forced) available = forced;
380
- else if (latest && looksLikeVersion(version) && isNewer(latest, version)) available = latest;
381
- const hasUpdate = Boolean(available);
382
- items.push({
383
- id: `brew:${token}`,
384
- name: entry ? entry.name : token,
385
- version: version || "",
386
- available,
387
- publisher: `Homebrew cask · ${token}`,
388
- source: "homebrew",
389
- installLocation: "",
390
- hasUpdate,
391
- updateSupported: hasUpdate,
392
- reason: hasUpdate ? null : null,
393
- kind: "cask",
394
- });
395
- }
396
-
397
- if (!catalog) {
398
- warnings.push("没有可用的 Homebrew cask 目录:只显示 Homebrew 报告的更新,非 Homebrew 应用无法判断是否有新版本");
399
- }
400
- if (settings.includeUnmanagedApps === false) {
401
- warnings.push("「包含非 Homebrew 应用」已关闭:只显示由 Homebrew 管理的应用");
402
- }
403
-
404
- items.sort((a, b) => {
405
- if (a.hasUpdate !== b.hasUpdate) return a.hasUpdate ? -1 : 1;
406
- return String(a.name).localeCompare(String(b.name));
407
- });
408
- return { items, warnings };
409
- }
1
+ /**
2
+ * macOS 应用清单:把「本机装了哪些应用」真正列出来。
3
+ *
4
+ * 为什么需要这个模块:1.3.x 的 macOS 扫描只读了 `brew list --cask`,也就是
5
+ * **只有通过 Homebrew 装过的应用才会出现在列表里**。一台正常使用的 Mac 上,
6
+ * 绝大多数应用是拖 DMG 装的,于是 `brew list --cask` 返回空 → 界面显示
7
+ * 「未检测到任何已安装应用」。这不是「没有应用」,而是**没有枚举应用**。
8
+ *
9
+ * 现在的做法:
10
+ * 1. 枚举标准应用目录里的 `.app`(/Applications、/System/Applications 及其
11
+ * Utilities 子目录、~/Applications),从每个 bundle 的 Info.plist 读版本;
12
+ * 2. 用 Homebrew 的 cask 目录(formulae.brew.sh,缓存一天)把 `.app` 反向匹配到
13
+ * cask token,从而知道**官网最新版本**;
14
+ * 3. 只有「确实由 Homebrew 管理」的应用才标记为可一键更新 —— 其余应用如实列出,
15
+ * 但标注为不可由本插件更新,绝不假装能更新。
16
+ *
17
+ * 这里只做「读」,不改动任何东西;所有命令都是绝对路径 + 参数数组,不经 shell。
18
+ */
19
+
20
+ import { readdir, readFile, writeFile, mkdir } from "node:fs/promises";
21
+ import { existsSync } from "node:fs";
22
+ import { join } from "node:path";
23
+ import { homedir } from "node:os";
24
+
25
+ import { runProcess } from "./proc.js";
26
+ import { dataDir } from "./state.js";
27
+ import { isNewer, looksLikeVersion } from "./version.js";
28
+
29
+ /** macOS 放应用的标准目录(约定:这些目录第一层就是 `.app`)。 */
30
+ export function applicationDirs(home = homedir()) {
31
+ // 这些是 macOS 的 POSIX 路径,用字符串拼接而不是 path.join:
32
+ // join 在 Windows 上会产出反斜杠,跨平台跑单测时就对不上了。
33
+ const h = String(home || "").replace(/\/+$/, "");
34
+ return [
35
+ "/Applications",
36
+ "/Applications/Utilities",
37
+ "/System/Applications",
38
+ "/System/Applications/Utilities",
39
+ `${h}/Applications`,
40
+ ];
41
+ }
42
+
43
+ /** cask 目录的缓存文件(放插件自己的数据目录,不碰宿主配置)。 */
44
+ export function catalogCachePath(dir) {
45
+ return join(dir || dataDir(), "cask-catalog.json");
46
+ }
47
+
48
+ const CATALOG_URL = "https://formulae.brew.sh/api/cask.json";
49
+
50
+ /**
51
+ * cask 目录的下载地址,参与并发竞速。
52
+ *
53
+ * 为什么不止一个:`formulae.brew.sh` 在国内网络下常常只有 20~30 KB/s(实测 19 MB 的
54
+ * cask.json 跑 120 秒只下到 0.5 MB),而旧实现只给它一次 120 秒的机会 —— 于是每次扫描
55
+ * 都白等两分钟、最后拿不到目录,所有应用都算不出「可更新」。镜像站同样内容几秒就能下完,
56
+ * 所以官方地址仍然排第一,谁先下完用谁。
57
+ *
58
+ * 为什么**不**放阿里云:`mirrors.aliyun.com/homebrew/homebrew-bottles/api/cask.json` 是一份
59
+ * 冻结在 2025-05-22 的旧快照(13.7 MB,其余三源 19.3 MB;用 `isNewer` 全量比对有 2908 个
60
+ * cask 版本落后官方、1257 个缺失)。它结构同构、不会报错,只会让「已是最新」的结论悄悄变错 ——
61
+ * 而阿里云是国内最快的源,竞速里几乎总是它先返回,等于稳定拿到最旧的数据。
62
+ * 宁可少一个源,也不要一个又快又错的源。
63
+ */
64
+ const CATALOG_URLS = [
65
+ CATALOG_URL,
66
+ "https://mirrors.tuna.tsinghua.edu.cn/homebrew-bottles/api/cask.json",
67
+ "https://mirrors.ustc.edu.cn/homebrew-bottles/api/cask.json",
68
+ ];
69
+
70
+ /** 单个地址的超时:一个慢线路不该把整次扫描卡住好几分钟。 */
71
+ const CATALOG_FETCH_TIMEOUT_S = 60;
72
+ const CATALOG_TTL_MS = 24 * 60 * 60 * 1000;
73
+ /** 抓不到新目录时,已经过期的缓存最多还能用这么久(旧数据也比没有强)。 */
74
+ const CATALOG_STALE_MAX_MS = 30 * 24 * 60 * 60 * 1000;
75
+
76
+ /**
77
+ * 从 cask 目录 JSON 建索引:
78
+ * - byApp:`.app` 文件名(小写)→ 条目**数组**,用来「从已装应用反查 cask」;
79
+ * - byToken:cask token → 条目,用来「从已装 cask 正查最新版本」。
80
+ *
81
+ * 一个 .app 可能被多个 cask 声明(例如 `iterm2` 与 `iterm2@nightly` 都装
82
+ * `iTerm.app`),只留最后一个会让匹配随目录顺序漂移 —— 所以这里保留全部候选,
83
+ * 由 pickCask 按「已装 > 非 nightly/非弃用 > token 精确匹配」挑选。
84
+ *
85
+ * @param {any} list formulae.brew.sh/api/cask.json 的内容
86
+ */
87
+ export function parseCaskCatalog(list) {
88
+ const byApp = new Map();
89
+ const byToken = new Map();
90
+ const addCandidate = (appName, entry) => {
91
+ const key = String(appName).toLowerCase();
92
+ const bucket = byApp.get(key);
93
+ if (bucket) bucket.push(entry);
94
+ else byApp.set(key, [entry]);
95
+ };
96
+ for (const c of Array.isArray(list) ? list : []) {
97
+ if (!c || typeof c !== "object" || !c.token) continue;
98
+ const appNames = [];
99
+ for (const art of Array.isArray(c.artifacts) ? c.artifacts : []) {
100
+ if (!art || typeof art !== "object") continue;
101
+ for (const raw of Array.isArray(art.app) ? art.app : []) {
102
+ // 形如 "$APPDIR/Foo.app" 或 "Foo.app",只取最后一段
103
+ const base = String(raw).split("/").pop();
104
+ if (base && /\.app$/i.test(base)) appNames.push(base);
105
+ }
106
+ }
107
+ const entry = {
108
+ token: String(c.token),
109
+ version: String(c.version == null ? "" : c.version).trim(),
110
+ name: Array.isArray(c.name) && c.name.length ? String(c.name[0]) : String(c.token),
111
+ appNames,
112
+ deprecated: Boolean(c.deprecated),
113
+ disabled: Boolean(c.disabled),
114
+ autoUpdates: Boolean(c.auto_updates),
115
+ };
116
+ byToken.set(entry.token, entry);
117
+ for (const appName of appNames) addCandidate(appName, entry);
118
+ }
119
+ return { byApp, byToken };
120
+ }
121
+
122
+ /** token 里的变体后缀(iterm2@nightly → iterm2),用于排序时优先主 cask。 */
123
+ function baseToken(token) {
124
+ return String(token || "").split("@")[0];
125
+ }
126
+
127
+ /**
128
+ * 在多个候选 cask 里挑出最可能是「这个 .app 对应的那个 cask」。
129
+ *
130
+ * 优先级(越靠前越优先):
131
+ * 1. 已安装(token 出现在 brews 里)—— 已装的就是用户实际在用的那个;
132
+ * 2. 非 deprecated / disabled;
133
+ * 3. 主 token(不带 @nightly 这类变体后缀);
134
+ * 4. token 与应用名/应用文件名归一化后相等。
135
+ */
136
+ export function pickCask(candidates, { appName, bundleName, brews = new Map() } = {}) {
137
+ if (!Array.isArray(candidates) || !candidates.length) return null;
138
+ const keys = new Set([normalizeAppKey(appName), normalizeAppKey(bundleName)].filter(Boolean));
139
+ const score = (entry) => {
140
+ let s = 0;
141
+ if (brews.has(entry.token)) s += 100;
142
+ if (!entry.deprecated && !entry.disabled) s += 10;
143
+ if (entry.token === baseToken(entry.token)) s += 5;
144
+ if (keys.has(normalizeAppKey(entry.token))) s += 3;
145
+ for (const n of entry.appNames) if (keys.has(normalizeAppKey(n))) s += 1;
146
+ return s;
147
+ };
148
+ let best = candidates[0];
149
+ let bestScore = score(best);
150
+ for (const candidate of candidates.slice(1)) {
151
+ const s = score(candidate);
152
+ if (s > bestScore) {
153
+ best = candidate;
154
+ bestScore = s;
155
+ }
156
+ }
157
+ return best;
158
+ }
159
+
160
+ /** 名字归一化:去掉 .app、空格与标点,只留字母数字,用于 token ↔ 应用名兜底匹配。 */
161
+ export function normalizeAppKey(name) {
162
+ return String(name || "")
163
+ .replace(/\.app$/i, "")
164
+ .toLowerCase()
165
+ .replace(/[^a-z0-9]+/g, "");
166
+ }
167
+
168
+ /**
169
+ * 在标准应用目录里找 `.app`(不进入 bundle 内部,避免把框架当应用)。
170
+ * @returns {Promise<string[]>} 绝对路径,已去重
171
+ */
172
+ export async function listAppBundles(dirs, depth = 1) {
173
+ const found = [];
174
+ const seen = new Set();
175
+ const walk = async (dir, level) => {
176
+ let entries;
177
+ try {
178
+ entries = await readdir(dir, { withFileTypes: true });
179
+ } catch {
180
+ return; // 目录不存在 / 无权限:跳过,不影响其它目录
181
+ }
182
+ for (const entry of entries) {
183
+ const full = join(dir, entry.name);
184
+ if (/\.app$/i.test(entry.name)) {
185
+ if (!seen.has(full)) {
186
+ seen.add(full);
187
+ found.push(full);
188
+ }
189
+ continue;
190
+ }
191
+ if (level > 0 && (entry.isDirectory() || entry.isSymbolicLink())) {
192
+ await walk(full, level - 1);
193
+ }
194
+ }
195
+ };
196
+ for (const dir of dirs) await walk(dir, depth);
197
+ return found;
198
+ }
199
+
200
+ /** 用 plutil 读 Info.plist(macOS 自带,binary plist 也能转 JSON)。 */
201
+ async function readInfoPlist(appPath) {
202
+ const plist = join(appPath, "Contents", "Info.plist");
203
+ const res = await runProcess("/usr/bin/plutil", ["-convert", "json", "-o", "-", plist], { timeoutMs: 15000 });
204
+ if (!res.ok) return null;
205
+ try {
206
+ return JSON.parse(res.stdout);
207
+ } catch {
208
+ return null;
209
+ }
210
+ }
211
+
212
+ /**
213
+ * 读一个 `.app` 的元信息。
214
+ * @returns {Promise<{path:string,bundleName:string,name:string,version:string,bundleId:string,appStore:boolean,system:boolean}>}
215
+ */
216
+ export async function readAppBundle(appPath) {
217
+ // macOS 上路径一定用 /,但单测在 Windows 上跑,两种分隔符都要能取到最后一段
218
+ const bundleName = String(appPath).split(/[\\/]/).filter(Boolean).pop() || String(appPath);
219
+ const info = {
220
+ path: appPath,
221
+ bundleName,
222
+ name: bundleName.replace(/\.app$/i, ""),
223
+ version: "",
224
+ bundleId: "",
225
+ appStore: existsSync(join(appPath, "Contents", "_MASReceipt", "receipt")),
226
+ system: appPath.startsWith("/System/"),
227
+ };
228
+ const plist = await readInfoPlist(appPath);
229
+ if (plist) {
230
+ const short = plist.CFBundleShortVersionString;
231
+ const bundle = plist.CFBundleVersion;
232
+ info.version = String(short || bundle || "").trim();
233
+ info.bundleId = String(plist.CFBundleIdentifier || "").trim();
234
+ const display = plist.CFBundleDisplayName || plist.CFBundleName;
235
+ if (display) info.name = String(display).trim();
236
+ }
237
+ if (!info.version) {
238
+ // plutil 失败时的兜底:defaults 直接读单个键
239
+ const res = await runProcess(
240
+ "/usr/bin/defaults",
241
+ ["read", join(appPath, "Contents", "Info"), "CFBundleShortVersionString"],
242
+ { timeoutMs: 15000 }
243
+ );
244
+ if (res.ok) info.version = res.stdout.trim();
245
+ }
246
+ return info;
247
+ }
248
+
249
+ /** 枚举并读取全部已安装应用(并发有限,避免一次开几百个进程)。 */
250
+ export async function scanAppBundles({ dirs, log, concurrency = 8 } = {}) {
251
+ const paths = await listAppBundles(dirs || applicationDirs());
252
+ const out = [];
253
+ let index = 0;
254
+ const worker = async () => {
255
+ while (index < paths.length) {
256
+ const current = paths[index];
257
+ index += 1;
258
+ try {
259
+ out.push(await readAppBundle(current));
260
+ } catch {
261
+ /* 单个 bundle 读不出来不影响其它应用 */
262
+ }
263
+ }
264
+ };
265
+ await Promise.all(Array.from({ length: Math.min(concurrency, paths.length || 1) }, worker));
266
+ if (log) log("info", `在应用目录里找到 ${out.length} 个 .app`);
267
+ return out;
268
+ }
269
+
270
+ /**
271
+ * 读缓存的 cask 目录。
272
+ * @param {string} file 缓存文件
273
+ * @param {number} [now] 当前时间
274
+ * @param {{ allowStale?: boolean }} [opts] allowStale:TTL 过了也接受(用于网络抓取失败时兜底)
275
+ * @returns {Promise<Array|null>} 目录条目;不可用时为 null
276
+ */
277
+ export async function readCatalogCache(file, now = Date.now(), opts = {}) {
278
+ try {
279
+ const raw = JSON.parse(await readFile(file, "utf8"));
280
+ if (!raw || typeof raw.fetchedAt !== "number") return null;
281
+ const age = now - raw.fetchedAt;
282
+ if (age > (opts.allowStale ? CATALOG_STALE_MAX_MS : CATALOG_TTL_MS)) return null;
283
+ return Array.isArray(raw.list) && raw.list.length ? raw.list : null;
284
+ } catch {
285
+ return null;
286
+ }
287
+ }
288
+
289
+ /**
290
+ * 抓取 cask 目录并写缓存。
291
+ *
292
+ * 顺序:新鲜缓存 → 官方地址 → 镜像 → 过期缓存兜底 → null(调用方降级,不中断扫描)。
293
+ * 每个地址单独限时,绝不因为一条慢线路让整次扫描等上十几分钟。
294
+ */
295
+ export async function fetchCaskCatalog({ file, log, warnings, fetchImpl } = {}) {
296
+ const cacheFile = file || catalogCachePath();
297
+ const cached = await readCatalogCache(cacheFile);
298
+ if (cached) return cached;
299
+
300
+ /**
301
+ * 并发竞速取目录:官方地址与镜像同时开跑,谁先下完用谁,其余立刻取消。
302
+ *
303
+ * 为什么不用「依次重试」:官方线路实测 25 KB/s,串行等待等于每次扫描先干等
304
+ * 60 秒才知道该换镜像;并发竞速时镜像通常一两秒就返回,用户几乎不感知。
305
+ * 官方地址仍然参与竞速(网络正常时用官方数据,最权威)。
306
+ */
307
+ const run = fetchImpl || (async () => {
308
+ const controllers = [];
309
+ const failures = [];
310
+
311
+ const attempt = (url) => new Promise((resolve, reject) => {
312
+ const host = url.replace(/^https?:\/\//, "").split("/")[0];
313
+ const controller = new AbortController();
314
+ controllers.push(controller);
315
+ runProcess(
316
+ "/usr/bin/curl",
317
+ ["-fsSL", "--max-time", String(CATALOG_FETCH_TIMEOUT_S), url],
318
+ { timeoutMs: (CATALOG_FETCH_TIMEOUT_S + 15) * 1000, signal: controller.signal }
319
+ ).then((res) => {
320
+ if (!res.ok) {
321
+ const why = String(res.stderr || "").trim().split("\n")[0] || `curl 退出码 ${res.code}`;
322
+ throw new Error(`${host}: ${why}`);
323
+ }
324
+ const list = JSON.parse(res.stdout);
325
+ if (!Array.isArray(list) || !list.length) throw new Error(`${host}: 内容不是 cask 目录数组`);
326
+ resolve(list);
327
+ }).catch((err) => reject(new Error(String((err && err.message) || err))));
328
+ });
329
+
330
+ try {
331
+ // 全部并发起跑;Promise.any 拿到第一个成功的结果。
332
+ const list = await Promise.any(
333
+ CATALOG_URLS.map((url) => attempt(url).catch((err) => {
334
+ failures.push(String((err && err.message) || err));
335
+ throw err;
336
+ }))
337
+ );
338
+ return list;
339
+ } catch {
340
+ throw new Error(failures.join(";") || "所有 cask 目录地址都失败");
341
+ } finally {
342
+ // 无论成败,取消还在跑的下载,避免白白占用带宽。
343
+ for (const controller of controllers) {
344
+ try { controller.abort(); } catch { /* 已结束 */ }
345
+ }
346
+ }
347
+ });
348
+
349
+ try {
350
+ const list = await run();
351
+ if (!Array.isArray(list)) throw new Error("cask 目录格式不符合预期");
352
+ try {
353
+ await mkdir(dataDir(), { recursive: true });
354
+ await writeFile(cacheFile, JSON.stringify({ fetchedAt: Date.now(), list }), "utf8");
355
+ } catch {
356
+ /* 缓存写不进去不影响本次扫描 */
357
+ }
358
+ if (log) log("info", `已读取 Homebrew cask 目录(${list.length} 个 cask)`);
359
+ return list;
360
+ } catch (err) {
361
+ const message = String((err && err.message) || err);
362
+ // 所有地址都失败时,用过期缓存兜底:版本判断宁可略旧,也好过整屏「无法判断」。
363
+ const stale = await readCatalogCache(cacheFile, Date.now(), { allowStale: true });
364
+ if (stale) {
365
+ const text = `读取 Homebrew cask 目录失败,改用本地过期缓存(版本可能不是最新):${message}`;
366
+ if (warnings) warnings.push(text);
367
+ if (log) log("warn", text);
368
+ return stale;
369
+ }
370
+ if (warnings) warnings.push(`读取 Homebrew cask 目录失败(不影响列出应用,但无法判断是否有新版本):${message}`);
371
+ if (log) log("warn", `读取 Homebrew cask 目录失败:${message}`);
372
+ return null;
373
+ }
374
+ }
375
+
376
+ /**
377
+ * 组装 macOS 应用列表(纯函数,便于单测)。
378
+ *
379
+ * @param {object} input
380
+ * @param {Array} input.apps 已安装的 .app(scanAppBundles 的结果)
381
+ * @param {Map<string,string>} input.brews 已装 cask:token → 已装版本
382
+ * @param {Map<string,string>} input.outdated 可升级 cask:token → 可用版本
383
+ * @param {{byApp:Map,byToken:Map}|null} input.catalog cask 目录索引
384
+ * @param {object} input.settings
385
+ * @returns {{items:Array, warnings:string[]}}
386
+ */
387
+ export function buildMacosItems({ apps = [], brews = new Map(), outdated = new Map(), catalog = null, settings = {} }) {
388
+ const warnings = [];
389
+ const items = [];
390
+ const byApp = catalog ? catalog.byApp : new Map();
391
+ const byToken = catalog ? catalog.byToken : new Map();
392
+ /** 已被某个 .app 认领的 cask token,避免重复列出 */
393
+ const claimed = new Set();
394
+
395
+ // 没有 cask 目录时也能把「已装 cask」和 .app 对上:用 token 名归一化匹配,
396
+ // 否则同一个应用会既作为 .app 出现、又作为 brew 条目再出现一次。
397
+ const brewByName = new Map();
398
+ for (const token of brews.keys()) brewByName.set(normalizeAppKey(token), token);
399
+
400
+ const matchCask = (app) => {
401
+ const direct = byApp.get(String(app.bundleName || "").toLowerCase());
402
+ if (direct && direct.length) {
403
+ return pickCask(direct, { appName: app.name, bundleName: app.bundleName, brews });
404
+ }
405
+ const key = normalizeAppKey(app.name || app.bundleName);
406
+ for (const entry of byToken.values()) {
407
+ if (normalizeAppKey(entry.token) === key) return entry;
408
+ for (const appName of entry.appNames) {
409
+ if (normalizeAppKey(appName) === key) return entry;
410
+ }
411
+ }
412
+ const token = brewByName.get(key);
413
+ if (token) return { token, version: "", name: token, appNames: [] };
414
+ return null;
415
+ };
416
+
417
+ for (const app of apps) {
418
+ // 注意:只有**显式**设为 false 才过滤。settings 缺字段时按默认「包含」处理,
419
+ // 否则单测/老状态文件里缺字段会把应用整批吞掉。
420
+ if (settings.includeStoreApps === false && app.appStore) continue;
421
+ const cask = matchCask(app);
422
+ const managed = Boolean(cask && brews.has(cask.token));
423
+ // 非 Homebrew 管理的应用:默认列出(includeUnmanagedApps),关掉后只看 Homebrew 应用
424
+ if (!managed && settings.includeUnmanagedApps === false) continue;
425
+ if (cask && managed) claimed.add(cask.token);
426
+
427
+ const latest = cask && looksLikeVersion(cask.version) ? cask.version : "";
428
+ const forced = managed && outdated.get(cask.token) ? String(outdated.get(cask.token)) : "";
429
+
430
+ let available = "";
431
+ if (managed) {
432
+ if (forced) available = forced;
433
+ else if (latest && looksLikeVersion(app.version) && isNewer(latest, app.version)) available = latest;
434
+ }
435
+
436
+ let reason = null;
437
+ if (app.system && !managed) reason = "system-component";
438
+ else if (app.appStore && !managed) reason = "store-managed";
439
+ else if (!managed) reason = "not-managed";
440
+
441
+ const hasUpdate = Boolean(managed && available);
442
+ items.push({
443
+ id: managed ? `brew:${cask.token}` : `macapp:${app.bundleId || app.bundleName}`,
444
+ name: app.name || app.bundleName,
445
+ version: app.version || "",
446
+ available,
447
+ publisher: cask ? `Homebrew cask · ${cask.token}` : app.bundleId || "",
448
+ source: managed ? "homebrew" : app.appStore ? "appstore" : "app",
449
+ installLocation: app.path,
450
+ hasUpdate,
451
+ updateSupported: hasUpdate,
452
+ reason: hasUpdate ? null : reason,
453
+ kind: managed ? "cask" : "app",
454
+ });
455
+ }
456
+
457
+ // 通过 Homebrew 装的、但标准目录里没找到 .app 的(字体、命令行 cask 等)也要列出来。
458
+ // 它们本来就由 Homebrew 管理,不受「包含非 Homebrew 应用」开关影响。
459
+ for (const [token, version] of brews) {
460
+ if (claimed.has(token)) continue;
461
+ const entry = byToken.get(token);
462
+ const forced = outdated.get(token) ? String(outdated.get(token)) : "";
463
+ const latest = entry && looksLikeVersion(entry.version) ? entry.version : "";
464
+ let available = "";
465
+ if (forced) available = forced;
466
+ else if (latest && looksLikeVersion(version) && isNewer(latest, version)) available = latest;
467
+ const hasUpdate = Boolean(available);
468
+ items.push({
469
+ id: `brew:${token}`,
470
+ name: entry ? entry.name : token,
471
+ version: version || "",
472
+ available,
473
+ publisher: `Homebrew cask · ${token}`,
474
+ source: "homebrew",
475
+ installLocation: "",
476
+ hasUpdate,
477
+ updateSupported: hasUpdate,
478
+ reason: hasUpdate ? null : null,
479
+ kind: "cask",
480
+ });
481
+ }
482
+
483
+ if (!catalog) {
484
+ warnings.push("没有可用的 Homebrew cask 目录:只显示 Homebrew 报告的更新,非 Homebrew 应用无法判断是否有新版本");
485
+ }
486
+ /* 「包含非 Homebrew 应用」被关掉只是用户自己选的过滤条件,不是故障 ——
487
+ 不放进 warnings,否则界面会一直挂一条红色告警横幅。 */
488
+
489
+ items.sort((a, b) => {
490
+ if (a.hasUpdate !== b.hasUpdate) return a.hasUpdate ? -1 : 1;
491
+ return String(a.name).localeCompare(String(b.name));
492
+ });
493
+ return { items, warnings };
494
+ }