dsh-mobile-plugin 0.5.68 → 0.5.70

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.
@@ -14,6 +14,9 @@
14
14
  * 已有的 `POST /plugin/market/install`。能力面对手机只多「读一份公开 JSON」(外网 GET),
15
15
  * 仍然不碰 shell、不碰系统设置、不写任意文件。
16
16
  *
17
+ * 两个目录源:社区精选清单(默认,`SOURCES`)与我们自己的手机扩展市场清单(`REGISTRY_SOURCE`),
18
+ * 缓存与在飞请求按源分开。App 的市场页用 `source=registry` 选后者;读社区清单的既有调用方默认不变。
19
+ *
17
20
  * 三个取舍:
18
21
  * 1. **缓存收窄后的结果,不缓存原文**:源清单 14MB / 4MB,缓存原文等于在宿主进程里常驻
19
22
  * 十几 MB;收窄后通常是几百 KB 到一两 MB。10 分钟有效,过期重拉。
@@ -31,6 +34,8 @@
31
34
  */
32
35
 
33
36
  const { sendJson } = require('../shared/http-util');
37
+ const fs = require('node:fs');
38
+ const path = require('node:path');
34
39
 
35
40
  /**
36
41
  * 数据源,按顺序试,前一个失败才试下一个。两份清单是社区同一批数据的两条腿:
@@ -51,6 +56,24 @@ const SOURCES = [
51
56
  },
52
57
  ];
53
58
 
59
+ /**
60
+ * 我们自己的「手机扩展市场」目录源(format-1,只用这一份)。
61
+ *
62
+ * 与上面社区清单分开:社区那份是一万多条通用 DSH 插件,这里只收「带手机扩展声明」的,
63
+ * 体积很小。App 的市场页用 `?source=registry` 指向它,不影响读社区清单的既有调用方。
64
+ *
65
+ * 这份清单是**本插件包内的一份数据**(extension-registry/index.json),随插件 npm 包发版,
66
+ * host 直接从自己包里读,不走网络、不依赖任何外部托管。作者投稿合进清单后,下一次发插件版
67
+ * 用户就拿到新目录 —— 代价是收录要等一次发版,换来的是零托管、零外部依赖、零发布流水线。
68
+ */
69
+ const REGISTRY_SOURCE = {
70
+ id: 'registry',
71
+ file: path.join(__dirname, '..', '..', 'extension-registry', 'index.json'),
72
+ url: 'builtin:extension-registry/index.json', // 回执里给 App 看的来源标识,不是可访问地址。
73
+ // 清单条目按「主源」形状输出(name 是显示名、npm 是安装包名),跟社区 plugins.json 同源同解析。
74
+ format: 'plugins',
75
+ };
76
+
54
77
  /** 缓存有效期:清单一天更新不了几次,10 分钟足够新,也不至于每次翻页都拉 14MB。 */
55
78
  const CACHE_TTL_MS = 10 * 60 * 1000;
56
79
  /** 每个源最多试两次:14MB 的 CDN 偶发断流很常见,一次失败不代表源坏了。 */
@@ -82,12 +105,13 @@ const NPM_NAME_MAX = 214;
82
105
  /** 收录日期只认 `YYYY-MM-DD`。 */
83
106
  const DAY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
84
107
 
85
- /** 收窄后的缓存:{ source, fetchedAt, fetchedAtWall, items, categories }。 */
86
- let cache = null;
87
- /** 正在飞的那一次拉取;并发请求等它。 */
88
- let inflight = null;
89
- /** 测试注入点:假 fetch 与假时钟。真跑时就是全局 fetch / Date.now。 */
108
+ /** 收窄后的缓存,按源 key 分开:社区清单与我们自己的扩展市场互不影响。 */
109
+ const cache = new Map();
110
+ /** 正在飞的那一次拉取,同样按源 key;并发请求等它。 */
111
+ const inflight = new Map();
112
+ /** 测试注入点:假 fetch / 假读文件 / 假时钟。真跑时就是全局 fetch / fs.readFile / Date.now。 */
90
113
  let fetchImpl = null;
114
+ let readFileImpl = null;
91
115
  let clock = null;
92
116
 
93
117
  function nowMs() {
@@ -281,8 +305,23 @@ function narrowCatalog(document, source) {
281
305
  return { categories, items };
282
306
  }
283
307
 
284
- /** 拉一个源:读 JSON、把表单收窄。抛出的错误由 `loadCatalog` 记进失败原因。 */
308
+ /** 读一个源:registry 从本插件包内的文件读,社区源走网络。抛出的错误由 fetchCatalog 记进失败原因。 */
285
309
  async function fetchCatalogDocument(source) {
310
+ if (source.file) {
311
+ // 包内清单:随插件发版就在盘上,没有网络、没有超时,只有「文件在不在、是不是合法 JSON」。
312
+ const read = readFileImpl || fs.promises.readFile.bind(fs.promises);
313
+ let text;
314
+ try {
315
+ text = await read(source.file, 'utf8');
316
+ } catch (error) {
317
+ throw new Error(`读不到包内清单:${errorText(error)}`);
318
+ }
319
+ try {
320
+ return JSON.parse(text);
321
+ } catch {
322
+ throw new Error('包内清单不是合法 JSON');
323
+ }
324
+ }
286
325
  const doFetch = fetchImpl || globalThis.fetch;
287
326
  if (typeof doFetch !== 'function') throw new Error('这个运行时里没有 fetch,拉不了清单');
288
327
  const controller = typeof AbortController === 'function' ? new AbortController() : null;
@@ -313,15 +352,15 @@ async function fetchCatalogDocument(source) {
313
352
  * 按顺序试源,每个源最多两次;全挂了抛错,message 是每个源各自的失败原因拼接。
314
353
  * 成功时把**收窄后**的结果塞进缓存(不是原文)。
315
354
  */
316
- async function fetchCatalog() {
355
+ async function fetchCatalog(sources, cacheKey) {
317
356
  const failures = [];
318
- for (const source of SOURCES) {
357
+ for (const source of sources) {
319
358
  for (let attempt = 1; attempt <= ATTEMPTS_PER_SOURCE; attempt += 1) {
320
359
  try {
321
360
  const document = await fetchCatalogDocument(source);
322
361
  const { categories, items } = narrowCatalog(document, source);
323
362
  const fetchedAt = nowMs();
324
- cache = {
363
+ const result = {
325
364
  source: source.url,
326
365
  fetchedAt,
327
366
  // 墙钟另存一份:`fetchedAt` 走可注入的时钟(测试用),这一格永远是真实时间。
@@ -329,7 +368,8 @@ async function fetchCatalog() {
329
368
  items,
330
369
  categories,
331
370
  };
332
- return cache;
371
+ cache.set(cacheKey, result);
372
+ return result;
333
373
  } catch (error) {
334
374
  failures.push(`${source.url} 第 ${attempt} 次:${errorText(error)}`);
335
375
  }
@@ -345,13 +385,18 @@ async function fetchCatalog() {
345
385
  * - 过期 / 没有缓存时拉一次,**失败就抛**(绝不拿旧缓存冒充成功);
346
386
  * - 并发只允许一个在飞:后来者 await 同一个 Promise。
347
387
  */
348
- async function loadCatalog() {
388
+ async function loadCatalog(which = 'community') {
389
+ const registry = which === 'registry';
390
+ const sources = registry ? [REGISTRY_SOURCE] : SOURCES;
391
+ // registry 与社区清单各有自己的缓存槽;key 用固定串,URL 可被环境变量改也不影响命中。
392
+ const key = registry ? 'registry' : 'community';
349
393
  const at = nowMs();
350
- if (cache && at - cache.fetchedAt >= 0 && at - cache.fetchedAt < CACHE_TTL_MS) return cache;
351
- if (!inflight) {
352
- inflight = fetchCatalog().finally(() => { inflight = null; });
394
+ const hit = cache.get(key);
395
+ if (hit && at - hit.fetchedAt >= 0 && at - hit.fetchedAt < CACHE_TTL_MS) return hit;
396
+ if (!inflight.has(key)) {
397
+ inflight.set(key, fetchCatalog(sources, key).finally(() => { inflight.delete(key); }));
353
398
  }
354
- return inflight;
399
+ return inflight.get(key);
355
400
  }
356
401
 
357
402
  /** 搜索词:名字 / 作者 / 仓库名 / 双语标题与说明 / npm 名,大小写不敏感。 */
@@ -414,6 +459,8 @@ function intParam(raw, fallback) {
414
459
  * (手机拼错一个参数不该让整页变红,界面上的胶囊本来就只会给合法值)。
415
460
  */
416
461
  function parseQuery(searchParams) {
462
+ const rawSource = textOrNull(searchParams.get('source'), 16);
463
+ const which = rawSource === 'registry' ? 'registry' : 'community';
417
464
  const q = textOrNull(searchParams.get('q'), Q_MAX_CHARS) || '';
418
465
  const rawCategory = textOrNull(searchParams.get('category'), 64);
419
466
  const category = rawCategory && rawCategory !== 'all' ? rawCategory : 'all';
@@ -423,7 +470,7 @@ function parseQuery(searchParams) {
423
470
  const dir = DIRS.includes(rawDir) ? rawDir : (sort === 'name' ? 'asc' : 'desc');
424
471
  const offset = intParam(searchParams.get('offset'), 0);
425
472
  const limit = Math.min(Math.max(intParam(searchParams.get('limit'), LIMIT_DEFAULT), 1), LIMIT_MAX);
426
- return { q: q.toLowerCase(), category, sort, dir, offset, limit };
473
+ return { q: q.toLowerCase(), category, sort, dir, offset, limit, which };
427
474
  }
428
475
 
429
476
  /**
@@ -462,21 +509,21 @@ function pageOf(catalog, query) {
462
509
 
463
510
  /** GET /api/mobile/v1/plugin/catalog */
464
511
  async function handlePluginCatalog(ctx, req, res) {
512
+ let query;
513
+ try {
514
+ query = parseQuery(new URL((req && req.url) || '/', 'http://x').searchParams);
515
+ } catch {
516
+ query = parseQuery(new URLSearchParams());
517
+ }
465
518
  let catalog;
466
519
  try {
467
- catalog = await loadCatalog();
520
+ catalog = await loadCatalog(query.which);
468
521
  } catch (error) {
469
522
  return sendJson(res, 503, {
470
523
  ok: false,
471
524
  error: { code: 'catalog-unavailable', message: errorText(error) },
472
525
  });
473
526
  }
474
- let query;
475
- try {
476
- query = parseQuery(new URL((req && req.url) || '/', 'http://x').searchParams);
477
- } catch {
478
- query = parseQuery(new URLSearchParams());
479
- }
480
527
  const page = pageOf(catalog, query);
481
528
  sendJson(res, 200, { ok: true, ...page });
482
529
  }
@@ -490,12 +537,14 @@ module.exports = {
490
537
  normalizeItem,
491
538
  loadCatalog,
492
539
  SOURCES,
540
+ REGISTRY_SOURCE,
493
541
  CACHE_TTL_MS,
494
542
  LIMIT_DEFAULT,
495
543
  LIMIT_MAX,
496
544
  Q_MAX_CHARS,
497
545
  // 测试注入:假 fetch / 假时钟 / 清缓存(真跑时一个都不该被调用)
498
546
  __setFetchForTests(next) { fetchImpl = next || null; },
547
+ __setReadFileForTests(next) { readFileImpl = next || null; },
499
548
  __setClockForTests(next) { clock = next || null; },
500
- __resetForTests() { cache = null; inflight = null; fetchImpl = null; clock = null; },
549
+ __resetForTests() { cache.clear(); inflight.clear(); fetchImpl = null; readFileImpl = null; clock = null; },
501
550
  };