@auto-mas/auto-mas-plugin-market 0.2.1 → 0.2.2

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 (2) hide show
  1. package/dist/server/market.js +115 -33
  2. package/package.json +9 -1
@@ -9,12 +9,22 @@ export const publicNpmRegistry = 'https://registry.npmjs.org/';
9
9
  const searchTerm = pluginPackagePrefix.slice(0, -1);
10
10
  const legacyKeyword = 'cordis-mas-plugin';
11
11
  const searchLimit = 30;
12
+ const manifestConcurrency = 6;
13
+ const descriptionLimit = 350;
12
14
  const compressedLimit = 16 * 1024 * 1024;
13
15
  const expandedLimit = 64 * 1024 * 1024;
14
16
  const inflate = promisify(gunzip);
15
17
  const packageName = /^(?:@[a-z0-9][a-z0-9_.-]*\/)?[a-z0-9][a-z0-9_.-]*$/;
16
18
  const versionPattern = /^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
17
19
  const reservedPath = /^(?:con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³]|conin\$|conout\$)(?:\.|$)/i;
20
+ const statusLabels = new Map([
21
+ ['stable', '正式版'], ['beta', '测试版'], ['testing-welcome', '欢迎测试'],
22
+ ['developing', '开发中'], ['discouraged', '不推荐'],
23
+ ]);
24
+ const categoryLabels = new Map([
25
+ ['adapter', '专项适配'], ['theme', '主题'], ['notification', '通知'],
26
+ ['game-management', '游戏管理'], ['information', '信息拓展'], ['core', '基础功能'], ['utility', '实用工具'],
27
+ ]);
18
28
  function object(value) {
19
29
  return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
20
30
  }
@@ -91,42 +101,101 @@ async function requestJson(url, limit, request, signal) {
91
101
  throw new Error('npm 注册表返回了无效的 JSON');
92
102
  }
93
103
  }
94
- async function marketSearchPage(text, request) {
104
+ async function npmVersionManifest(registry, name, version, request, signal) {
105
+ const url = new URL(`${encodeURIComponent(name)}/${encodeURIComponent(version)}`, registry);
106
+ const metadata = await requestJson(url, 1024 * 1024, request, signal);
107
+ if (metadata.name !== name || metadata.version !== version)
108
+ throw new Error('npm 注册表返回的包名或版本不符');
109
+ return metadata;
110
+ }
111
+ async function marketSearchPage(text, request, signal, from = 0) {
95
112
  const endpoint = new URL('/-/v1/search', publicNpmRegistry);
96
113
  endpoint.searchParams.set('text', text);
97
114
  endpoint.searchParams.set('size', String(searchLimit));
98
- const found = await requestJson(endpoint, 1024 * 1024, request);
115
+ if (from)
116
+ endpoint.searchParams.set('from', String(from));
117
+ const found = await requestJson(endpoint, 1024 * 1024, request, signal);
99
118
  if (!Array.isArray(found.objects))
100
119
  throw new Error('npm 注册表没有返回有效的搜索结果');
101
- return found.objects.slice(0, searchLimit).flatMap(item => {
120
+ const candidates = found.objects.slice(0, searchLimit).flatMap(item => {
102
121
  const pkg = object(object(item).package);
103
122
  if (!discoverableName(pkg.name) || !exactVersion(pkg.version))
104
123
  return [];
124
+ const publisher = object(pkg.publisher).username;
105
125
  return [{
106
126
  name: pkg.name, version: pkg.version,
107
- description: typeof pkg.description === 'string' ? pkg.description.slice(0, 350) : '',
108
- publisher: typeof object(pkg.publisher).username === 'string' ? object(pkg.publisher).username : '',
127
+ description: typeof pkg.description === 'string' ? pkg.description.slice(0, descriptionLimit) : '',
128
+ publisher: typeof publisher === 'string' ? publisher : '',
109
129
  updated: typeof pkg.date === 'string' ? pkg.date.slice(0, 10) : '',
110
130
  }];
111
131
  });
132
+ return { candidates, hasMore: typeof found.total === 'number' && found.total > from + searchLimit };
133
+ }
134
+ function descriptionText(value) {
135
+ return typeof value === 'string' && value.trim() ? value.trim().slice(0, descriptionLimit) : undefined;
136
+ }
137
+ async function readMarketItem(candidate, request, signal) {
138
+ const manifest = await npmVersionManifest(publicNpmRegistry, candidate.name, candidate.version, request, signal);
139
+ const metadata = object(manifest.mas);
140
+ if (metadata.hidden === true)
141
+ return undefined;
142
+ const descriptions = object(metadata.description);
143
+ const description = ['zh-CN', 'zh', 'cn', 'en'].map(locale => descriptionText(descriptions[locale])).find(Boolean)
144
+ ?? descriptionText(manifest.description) ?? Object.values(descriptions).map(descriptionText).find(Boolean)
145
+ ?? descriptionText(candidate.description) ?? '';
146
+ const item = { ...candidate, description };
147
+ if (typeof metadata.status === 'string')
148
+ item.status = statusLabels.get(metadata.status) ?? '其他';
149
+ if (typeof metadata.category === 'string')
150
+ item.category = categoryLabels.get(metadata.category) ?? '其他';
151
+ return item;
112
152
  }
113
153
  export async function searchMarket(search = '', request = fetch) {
114
154
  const term = search.trim().slice(0, 120);
115
155
  const query = (prefix) => term ? `${prefix} ${term}` : prefix;
156
+ const signal = AbortSignal.timeout(15000);
157
+ const rows = [];
158
+ const seen = new Set();
159
+ let verified = 0;
160
+ async function append(candidates) {
161
+ const pending = candidates.filter(({ name }) => {
162
+ if (seen.has(name))
163
+ return false;
164
+ seen.add(name);
165
+ return true;
166
+ });
167
+ for (let offset = 0; offset < pending.length && rows.length < searchLimit && !signal.aborted; offset += manifestConcurrency) {
168
+ const batch = pending.slice(offset, offset + manifestConcurrency);
169
+ const results = await Promise.allSettled(batch.map(candidate => readMarketItem(candidate, request, signal)));
170
+ for (const result of results) {
171
+ if (result.status !== 'fulfilled')
172
+ continue;
173
+ ++verified;
174
+ if (result.value)
175
+ rows.push(result.value);
176
+ }
177
+ }
178
+ }
179
+ async function appendPage(text, from = 0) {
180
+ const page = await marketSearchPage(text, request, signal, from).catch(error => {
181
+ if (!seen.size)
182
+ throw error;
183
+ });
184
+ if (page)
185
+ await append(page.candidates);
186
+ }
116
187
  // npm's full-text search can rank unrelated packages highly. Start with the
117
- // plugin keyword and use full-text results to catch valid names without it.
118
- const indexed = await marketSearchPage(query(`keywords:${searchTerm}`), request);
119
- if (indexed.length === searchLimit)
120
- return indexed;
121
- const supplemental = await marketSearchPage(query(searchTerm), request).catch(error => {
122
- if (!indexed.length)
123
- throw error;
124
- return [];
125
- });
126
- const additional = new Map(supplemental.map(item => [item.name, item]));
127
- for (const item of indexed)
128
- additional.delete(item.name);
129
- return [...indexed, ...additional.values()].slice(0, searchLimit);
188
+ // plugin keyword and use one full-text page to catch valid names without it.
189
+ const indexedQuery = query(`keywords:${searchTerm}`);
190
+ const indexed = await marketSearchPage(indexedQuery, request, signal);
191
+ await append(indexed.candidates);
192
+ if (rows.length < searchLimit && indexed.hasMore && !signal.aborted)
193
+ await appendPage(indexedQuery, searchLimit);
194
+ if (rows.length < searchLimit && !signal.aborted)
195
+ await appendPage(query(searchTerm));
196
+ if (seen.size && !verified)
197
+ throw new Error('npm 注册表没有返回可验证的插件版本信息');
198
+ return rows.slice(0, searchLimit);
130
199
  }
131
200
  function archivePath(path, directory) {
132
201
  const value = directory ? path.replace(/\/$/, '') : path;
@@ -259,10 +328,7 @@ export async function fetchPluginTarball(name, version, request = fetch, options
259
328
  if (!exactVersion(version))
260
329
  throw new Error('请输入完整的 SemVer 版本,例如 1.2.3');
261
330
  const registry = new URL(normalizeNpmRegistry(options.registry ?? publicNpmRegistry));
262
- const url = new URL(`${encodeURIComponent(name)}/${encodeURIComponent(version)}`, registry);
263
- const metadata = await requestJson(url, 1024 * 1024, request, options.signal);
264
- if (metadata.name !== name || metadata.version !== version)
265
- throw new Error('npm 注册表返回的包名或版本不符');
331
+ const metadata = await npmVersionManifest(registry, name, version, request, options.signal);
266
332
  if (!validMarketPackage(metadata))
267
333
  throw new Error(`市场插件包名应为 ${pluginPackagePrefix}<名称>`);
268
334
  const dist = object(metadata.dist);
@@ -355,13 +421,33 @@ export function createMarketFeature(dataDir) {
355
421
  return id;
356
422
  };
357
423
  const installing = new Set();
358
- let browse;
424
+ const searches = new Map();
425
+ const browseMarket = (input) => {
426
+ const term = typeof input.search === 'string' ? input.search.trim().slice(0, 120) : '';
427
+ const now = Date.now();
428
+ const cached = searches.get(term);
429
+ if (cached && cached.until > now)
430
+ return cached.items;
431
+ searches.delete(term);
432
+ if (searches.size >= 20) {
433
+ const oldest = searches.keys().next().value;
434
+ if (oldest !== undefined)
435
+ searches.delete(oldest);
436
+ }
437
+ const items = searchMarket(term).catch(error => {
438
+ if (searches.get(term)?.items === items)
439
+ searches.delete(term);
440
+ throw error;
441
+ });
442
+ searches.set(term, { until: now + 30000, items });
443
+ return items;
444
+ };
359
445
  ui.panel(ctx, 'market', [
360
- { type: 'table', title: '探索插件', query: 'market.browse', columns: [
361
- { key: 'name', label: '包名' }, { key: 'version', label: '版本' }, { key: 'description', label: '说明' },
446
+ { type: 'table', title: '探索插件', query: 'market.search', submitLabel: '搜索', fields: [{ key: 'search', label: '搜索词' }], columns: [
447
+ { key: 'name', label: '包名' }, { key: 'version', label: '版本' }, { key: 'category', label: '分类' },
448
+ { key: 'status', label: '发布状态' }, { key: 'description', label: '说明' },
362
449
  { key: 'publisher', label: '发布者' }, { key: 'updated', label: '更新日期' },
363
450
  ] },
364
- { type: 'form', title: '搜索插件', action: 'market.search', result: true, fields: [{ key: 'search', label: '搜索词' }] },
365
451
  { type: 'text', title: '审核第三方插件', text: '安装后可在插件配置页审核。启用插件会以 AUTO-MASC 后端的账户权限执行第三方代码。' },
366
452
  { type: 'form', title: '安装指定版本', action: 'market.install', result: true, fields: [
367
453
  { key: 'name', label: 'npm 包名', required: true, hint: `例如 @auto-mas/${pluginPackagePrefix}adapter-maaend` },
@@ -380,14 +466,10 @@ export function createMarketFeature(dataDir) {
380
466
  { type: 'form', title: '为精简发行保留随包插件', action: 'market.retain-bundle', result: true,
381
467
  fields: [{ key: 'confirmed', label: '将兼容发行附带的可选插件复制到当前数据目录', kind: 'boolean' }] },
382
468
  ], {
383
- 'market.browse': () => {
384
- if (!browse || browse.until < Date.now()) {
385
- browse = { until: Date.now() + 30000, pages: searchMarket().catch(error => { browse = undefined; throw error; }) };
386
- }
387
- return browse.pages;
388
- },
469
+ 'market.browse': browseMarket,
470
+ 'market.search': browseMarket,
389
471
  }, {
390
- 'market.search': input => searchMarket(typeof input.search === 'string' ? input.search : ''),
472
+ 'market.search': browseMarket,
391
473
  'market.retain-bundle': input => {
392
474
  if (input.confirmed !== true)
393
475
  throw new Error('请确认保留随包插件');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@auto-mas/auto-mas-plugin-market",
3
- "version": "0.2.1",
3
+ "version": "0.2.2",
4
4
  "license": "AGPL-3.0-only",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -18,6 +18,14 @@
18
18
  "access": "public"
19
19
  },
20
20
  "description": "AUTO-MAS market Cordis component",
21
+ "mas": {
22
+ "hidden": false,
23
+ "category": "core",
24
+ "description": {
25
+ "zh": "查找和安装公共 npm 上的 Cordis 插件",
26
+ "en": "Find and install Cordis plugins from public npm"
27
+ }
28
+ },
21
29
  "autoMas": {
22
30
  "id": "market",
23
31
  "abi": 1,