@dsh-workbench/shared 1.1.5 → 1.1.6

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.
@@ -0,0 +1,482 @@
1
+ import { createHash } from 'node:crypto';
2
+ import type {
3
+ DiscoverFilter,
4
+ IndexSourceSpec,
5
+ MarketIndex,
6
+ MarketIndexEntry,
7
+ MarketIndexParse,
8
+ MarketIndexProblem,
9
+ MarketIndexSource,
10
+ MarketIndexVersion,
11
+ MarketLocalizedText,
12
+ MarketSourceConfig,
13
+ } from '../contract/protocol/market-index.js';
14
+ import { MARKET_INDEX_DIR, MARKET_INDEX_FORMAT } from '../contract/protocol/market-index.js';
15
+ import { marketText } from '../lib/market-index.js';
16
+ import type { MarketDocFields, MarketEntryDocParse } from './market-index-doc.js';
17
+ import { compareVersions, isValidVersion } from './version.js';
18
+
19
+ const NPM_NAME = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/;
20
+ const GIT_COMMIT = /^[0-9a-f]{40}$/;
21
+ const MAX_ICON_CHARS = 32 * 1024;
22
+
23
+
24
+ export function compareSemver(left: string, right: string): number | undefined {
25
+ return compareVersions(left, right);
26
+ }
27
+
28
+ export function httpUrlProblem(url: string): string | undefined {
29
+ let parsed: URL;
30
+ try {
31
+ parsed = new URL(url);
32
+ } catch {
33
+ return '不是合法 URL';
34
+ }
35
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return '只收 http / https';
36
+ if (parsed.username !== '' || parsed.password !== '') return 'URL 不能带凭据';
37
+ if (parsed.search !== '' || parsed.hash !== '') return 'URL 不能带 query / fragment';
38
+ return undefined;
39
+ }
40
+
41
+ export function gitUrlOk(url: string): boolean {
42
+ if (url === '') return false;
43
+ if (/^[^@\s]+@[^@\s:]+:[^@\s]+$/.test(url)) return true;
44
+ let parsed: URL;
45
+ try {
46
+ parsed = new URL(url);
47
+ } catch {
48
+ return false;
49
+ }
50
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'ssh:' && parsed.protocol !== 'http:') return false;
51
+ if (parsed.password !== '') return false;
52
+ if (parsed.username !== '' && parsed.protocol !== 'ssh:') return false;
53
+ if (parsed.search !== '' || parsed.hash !== '') return false;
54
+ return true;
55
+ }
56
+
57
+ function asRecord(value: unknown): Readonly<Record<string, unknown>> | undefined {
58
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
59
+ ? (value as Readonly<Record<string, unknown>>)
60
+ : undefined;
61
+ }
62
+
63
+ function asText(value: unknown): string {
64
+ return typeof value === 'string' ? value.trim() : '';
65
+ }
66
+
67
+ function asTextArray(value: unknown): string[] {
68
+ return Array.isArray(value)
69
+ ? value.flatMap((item) => (typeof item === 'string' && item.trim() !== '' ? [item.trim()] : []))
70
+ : [];
71
+ }
72
+
73
+ function asLocalized(value: unknown): MarketLocalizedText | undefined {
74
+ const record = asRecord(value);
75
+ if (record === undefined) return undefined;
76
+ const zh = asText(record['zh']);
77
+ const en = asText(record['en']);
78
+ return zh === '' && en === '' ? undefined : { ...(zh === '' ? {} : { zh }), ...(en === '' ? {} : { en }) };
79
+ }
80
+
81
+ function problem(kind: MarketIndexProblem['kind'], detail: string, at?: string): MarketIndexProblem {
82
+ return { kind, detail, ...(at === undefined ? {} : { at }) };
83
+ }
84
+
85
+ function sourceOf(raw: unknown, at: string): MarketIndexSource | MarketIndexProblem {
86
+ const record = asRecord(raw);
87
+ if (record === undefined) return problem('source', 'source 必须是一个对象', at);
88
+ if (record['type'] === 'npm') {
89
+ const registry = record['registry'];
90
+ if (registry !== undefined && asText(registry) === '') {
91
+ return problem('source', 'npm source 的 registry 必须是非空字符串', at);
92
+ }
93
+ return { type: 'npm', ...(registry === undefined ? {} : { registry: asText(registry) }) };
94
+ }
95
+ if (record['type'] === 'git') {
96
+ const url = asText(record['url']);
97
+ const commit = asText(record['commit']);
98
+ if (url === '') return problem('source', 'git source 缺 url', at);
99
+ if (!GIT_COMMIT.test(commit)) {
100
+ return problem('git-commit', `git source 的 commit 必须是 40 位小写 SHA(现在是 ${JSON.stringify(commit)})`, at);
101
+ }
102
+ const path = record['path'];
103
+ return {
104
+ type: 'git',
105
+ url,
106
+ commit,
107
+ ...(path === undefined || asText(path) === '' ? {} : { path: asText(path) }),
108
+ };
109
+ }
110
+ return problem('source', 'source.type 只能是 npm 或 git', at);
111
+ }
112
+
113
+ function versionOf(raw: unknown, at: string): MarketIndexVersion | MarketIndexProblem {
114
+ const record = asRecord(raw);
115
+ if (record === undefined) return problem('version', '版本必须是一个对象', at);
116
+ const version = asText(record['version']);
117
+ if (!isValidVersion(version)) return problem('version', `版本号不是合法 SemVer:${JSON.stringify(version)}`, at);
118
+ const source = sourceOf(record['source'], `${at}.source`);
119
+ if ('kind' in source) return source;
120
+ const timestamp = record['publishTimestamp'];
121
+ if (timestamp !== undefined && (!Number.isInteger(timestamp) || (timestamp as number) < 0)) {
122
+ return problem('timestamp', 'publishTimestamp 必须是 Unix 秒整数', at);
123
+ }
124
+ const engines = asRecord(record['engines']);
125
+ const dsh = engines === undefined ? '' : asText(engines['dsh']);
126
+ return {
127
+ version,
128
+ source,
129
+ ...(timestamp === undefined ? {} : { publishTimestamp: timestamp as number }),
130
+ ...(dsh === '' ? {} : { engines: { dsh } }),
131
+ };
132
+ }
133
+
134
+ function versionsOf(raw: unknown, at: string): readonly MarketIndexVersion[] | MarketIndexProblem {
135
+ if (!Array.isArray(raw) || raw.length === 0) return problem('versions', 'versions 必须是非空数组', at);
136
+ const versions: MarketIndexVersion[] = [];
137
+ const seen = new Set<string>();
138
+ for (const [index, item] of raw.entries()) {
139
+ const parsed = versionOf(item, `${at}[${String(index)}]`);
140
+ if ('kind' in parsed) return parsed;
141
+ if (seen.has(parsed.version)) return problem('versions', `版本重复:${parsed.version}`, at);
142
+ seen.add(parsed.version);
143
+ versions.push(parsed);
144
+ }
145
+ for (let index = 1; index < versions.length; index += 1) {
146
+ const order = compareSemver(versions[index - 1]?.version ?? '', versions[index]?.version ?? '');
147
+ if (order === undefined || order < 0) {
148
+ return problem('version-order', 'versions 必须按 SemVer 降序', at);
149
+ }
150
+ }
151
+ return versions;
152
+ }
153
+
154
+ function iconProblem(icon: string): MarketIndexProblem | undefined {
155
+ if (icon.length > MAX_ICON_CHARS) return problem('icon', 'icon 超过 32 KiB');
156
+ if (icon.startsWith('data:image/')) return icon.includes(';base64,') ? undefined : problem('icon', 'data URL 必须是 base64');
157
+ if (/^https?:\/\//i.test(icon)) return undefined;
158
+ return problem('icon', 'icon 只能是 base64 data URL 或 http(s) URL');
159
+ }
160
+
161
+ const MAX_OWNER_CHARS = 200;
162
+ const UNIT_ID = /^[a-z][a-z0-9-]*$/;
163
+
164
+ function ownerProblem(owner: string): MarketIndexProblem | undefined {
165
+ if (/[\r\n]/u.test(owner)) return problem('owner', 'owner 只能是一行署名');
166
+ if (owner.length > MAX_OWNER_CHARS) return problem('owner', 'owner 超过 200 字');
167
+ return undefined;
168
+ }
169
+
170
+ function metadataOf(raw: unknown): MarketIndexEntry['metadata'] {
171
+ const record = asRecord(raw);
172
+ if (record === undefined) return undefined;
173
+ const workbench = record['workbench'] === true;
174
+ const unit = asText(record['unit']);
175
+ const category = asText(record['category']);
176
+ const labels = asTextArray(record['labels']);
177
+ const keywords = asTextArray(record['keywords']);
178
+ const sortKeysRecord = asRecord(record['sortKeys']);
179
+ const sortKeys =
180
+ sortKeysRecord === undefined
181
+ ? undefined
182
+ : Object.fromEntries(
183
+ Object.entries(sortKeysRecord).flatMap(([key, value]) =>
184
+ typeof value === 'string' || typeof value === 'number' ? [[key, value] as const] : [],
185
+ ),
186
+ );
187
+ return {
188
+ ...(workbench ? { workbench: true } : {}),
189
+ ...(unit === '' ? {} : { unit }),
190
+ ...(category === '' ? {} : { category }),
191
+ ...(labels.length === 0 ? {} : { labels }),
192
+ ...(keywords.length === 0 ? {} : { keywords }),
193
+ ...(sortKeys === undefined || Object.keys(sortKeys).length === 0 ? {} : { sortKeys }),
194
+ };
195
+ }
196
+
197
+ function entryOf(raw: unknown, at: string): MarketIndexEntry | MarketIndexProblem {
198
+ const record = asRecord(raw);
199
+ if (record === undefined) return problem('plugin', '插件条目必须是对象', at);
200
+ const name = asText(record['name']);
201
+ if (name === '' || name.length > 214 || !NPM_NAME.test(name)) {
202
+ return problem('name', `不是合法 npm 包名:${JSON.stringify(name)}`, at);
203
+ }
204
+ const versions = versionsOf(record['versions'], `${at}.versions`);
205
+ if ('kind' in versions) return versions;
206
+ const icon = asText(record['icon']);
207
+ if (icon !== '') {
208
+ const badIcon = iconProblem(icon);
209
+ if (badIcon !== undefined) return badIcon;
210
+ }
211
+ const title = asLocalized(record['title']);
212
+ const description = asLocalized(record['description']);
213
+ const author = asText(record['author']);
214
+ const owner = asText(record['owner']);
215
+ if (owner !== '') {
216
+ const badOwner = ownerProblem(owner);
217
+ if (badOwner !== undefined) return badOwner;
218
+ }
219
+ const homepage = asText(record['homepage']);
220
+ const metadata = metadataOf(record['metadata']);
221
+ if (metadata?.unit !== undefined && !UNIT_ID.test(metadata.unit)) {
222
+ return problem('unit', `metadata.unit 只能是小写字母开头的 a-z0-9-(现在是 ${JSON.stringify(metadata.unit)})`, at);
223
+ }
224
+ return {
225
+ name,
226
+ versions,
227
+ ...(title === undefined ? {} : { title }),
228
+ ...(description === undefined ? {} : { description }),
229
+ ...(author === '' ? {} : { author }),
230
+ ...(owner === '' ? {} : { owner }),
231
+ ...(homepage === '' ? {} : { homepage }),
232
+ ...(icon === '' ? {} : { icon }),
233
+ ...(metadata === undefined ? {} : { metadata }),
234
+ };
235
+ }
236
+
237
+ export function parseMarketIndex(raw: unknown): MarketIndexParse {
238
+ const record = asRecord(raw);
239
+ if (record === undefined) return { ok: false, problems: [problem('not-object', '索引必须是一个 JSON 对象')] };
240
+ if (record['format'] !== MARKET_INDEX_FORMAT) {
241
+ return {
242
+ ok: false,
243
+ problems: [problem('format', `format 必须是 ${String(MARKET_INDEX_FORMAT)}(现在是 ${JSON.stringify(record['format'])})`)],
244
+ };
245
+ }
246
+ const plugins = record['plugins'];
247
+ if (!Array.isArray(plugins)) return { ok: false, problems: [problem('plugins', 'plugins 必须是数组')] };
248
+ const entries: MarketIndexEntry[] = [];
249
+ const problems: MarketIndexProblem[] = [];
250
+ const seen = new Set<string>();
251
+ for (const [index, item] of plugins.entries()) {
252
+ const parsed = entryOf(item, `plugins[${String(index)}]`);
253
+ if ('kind' in parsed) {
254
+ problems.push(parsed);
255
+ continue;
256
+ }
257
+ if (seen.has(parsed.name)) {
258
+ problems.push(problem('duplicate-name', `插件名重复:${parsed.name}`, `plugins[${String(index)}]`));
259
+ continue;
260
+ }
261
+ seen.add(parsed.name);
262
+ entries.push(parsed);
263
+ }
264
+ if (problems.length > 0) return { ok: false, problems };
265
+ const title = asLocalized(record['title']);
266
+ const description = asLocalized(record['description']);
267
+ const metadata = asRecord(record['metadata']);
268
+ return {
269
+ ok: true,
270
+ index: {
271
+ format: MARKET_INDEX_FORMAT,
272
+ plugins: entries,
273
+ ...(title === undefined ? {} : { title }),
274
+ ...(description === undefined ? {} : { description }),
275
+ ...(metadata === undefined ? {} : { metadata: metadata as MarketIndex['metadata'] }),
276
+ },
277
+ };
278
+ }
279
+
280
+ export function parseMarketIndexJson(text: string): MarketIndexParse {
281
+ try {
282
+ return parseMarketIndex(JSON.parse(text) as unknown);
283
+ } catch (error) {
284
+ return {
285
+ ok: false,
286
+ problems: [problem('not-json', `JSON 解析失败:${error instanceof Error ? error.message : String(error)}`)],
287
+ };
288
+ }
289
+ }
290
+
291
+ export function sortMarketVersions(versions: readonly MarketIndexVersion[]): MarketIndexVersion[] {
292
+ return [...versions].sort((left, right) => (compareSemver(right.version, left.version) ?? 0));
293
+ }
294
+
295
+ export function upsertMarketEntry(index: MarketIndex, entry: MarketIndexEntry): MarketIndex {
296
+ const found = index.plugins.findIndex((item) => item.name === entry.name);
297
+ if (found === -1) return { ...index, plugins: [...index.plugins, entry] };
298
+ const current = index.plugins[found];
299
+ if (current === undefined) return { ...index, plugins: [...index.plugins, entry] };
300
+ const merged = new Map<string, MarketIndexVersion>();
301
+ for (const one of current.versions) merged.set(one.version, one);
302
+ for (const one of entry.versions) merged.set(one.version, one);
303
+ const owner = current.owner ?? entry.owner;
304
+ const plugins = [...index.plugins];
305
+ plugins[found] = {
306
+ ...current,
307
+ ...entry,
308
+ ...(owner === undefined ? {} : { owner }),
309
+ versions: sortMarketVersions([...merged.values()]),
310
+ };
311
+ return { ...index, plugins };
312
+ }
313
+
314
+ export function marketEntryLabels(entry: MarketIndexEntry): readonly string[] {
315
+ return entry.metadata?.labels ?? [];
316
+ }
317
+
318
+ export function filterMarketIndex(index: MarketIndex, filter: DiscoverFilter): readonly MarketIndexEntry[] {
319
+ const query = (filter.query ?? '').trim().toLowerCase();
320
+ const category = (filter.category ?? '').trim();
321
+ const label = (filter.label ?? '').trim();
322
+ return index.plugins.filter((entry) => {
323
+ if (category !== '' && entry.metadata?.category !== category) return false;
324
+ if (label !== '' && !marketEntryLabels(entry).includes(label)) return false;
325
+ if (query === '') return true;
326
+ const haystack = [
327
+ entry.name,
328
+ marketText(entry.title, 'zh'),
329
+ marketText(entry.title, 'en'),
330
+ marketText(entry.description, 'zh'),
331
+ marketText(entry.description, 'en'),
332
+ entry.author ?? '',
333
+ ...(entry.metadata?.keywords ?? []),
334
+ ]
335
+ .join(' ')
336
+ .toLowerCase();
337
+ return haystack.includes(query);
338
+ });
339
+ }
340
+
341
+ export function marketSourceKey(source: IndexSourceSpec): string {
342
+ const canonical = JSON.stringify([source.kind, source.url.trim(), source.ref ?? '', source.path ?? '']);
343
+ return createHash('sha256').update(canonical).digest('hex').slice(0, 16);
344
+ }
345
+
346
+ export type SourceConfigParse =
347
+ | { readonly ok: true; readonly source: MarketSourceConfig }
348
+ | { readonly ok: false; readonly problem: MarketIndexProblem };
349
+
350
+ export function parseSourceConfig(raw: unknown): SourceConfigParse {
351
+ const record = asRecord(raw);
352
+ if (record === undefined) return { ok: false, problem: problem('source', '索引源必须是对象') };
353
+ const id = asText(record['id']);
354
+ const label = asText(record['label']);
355
+ const kind = record['kind'];
356
+ const url = asText(record['url']);
357
+ if (id === '') return { ok: false, problem: problem('source', '索引源缺 id') };
358
+ if (label === '') return { ok: false, problem: problem('source', '索引源缺 label') };
359
+ if (kind !== 'http' && kind !== 'git') return { ok: false, problem: problem('source', 'kind 只能是 http 或 git') };
360
+ if (kind === 'http') {
361
+ const bad = httpUrlProblem(url);
362
+ if (bad !== undefined) return { ok: false, problem: problem('source', bad) };
363
+ return { ok: true, source: { id, label, kind, url } };
364
+ }
365
+ if (!gitUrlOk(url)) {
366
+ return { ok: false, problem: problem('source', 'git 地址不合格(只收 https / ssh / scp 形式,且不能带凭据)') };
367
+ }
368
+ const ref = asText(record['ref']);
369
+ const path = asText(record['path']);
370
+ const localPath = asText(record['localPath']);
371
+ const policy = record['policy'];
372
+ if (policy !== undefined && policy !== 'artifacts-in-repo' && policy !== 'catalog-only') {
373
+ return { ok: false, problem: problem('source', 'policy 只能是 artifacts-in-repo 或 catalog-only') };
374
+ }
375
+ return {
376
+ ok: true,
377
+ source: {
378
+ id,
379
+ label,
380
+ kind,
381
+ url,
382
+ ...(ref === '' ? {} : { ref }),
383
+ ...(path === '' ? {} : { path }),
384
+ ...(localPath === '' ? {} : { localPath }),
385
+ ...(policy === undefined ? {} : { policy: policy as MarketSourceConfig['policy'] }),
386
+ },
387
+ };
388
+ }
389
+
390
+
391
+ function docFieldsOf(record: Readonly<Record<string, unknown>>, at: string): MarketDocFields | MarketIndexProblem {
392
+ const name = asText(record['name']);
393
+ if (name === '' || name.length > 214 || !NPM_NAME.test(name)) {
394
+ return problem('name', `不是合法 npm 包名:${JSON.stringify(name)}`, at);
395
+ }
396
+ const icon = asText(record['icon']);
397
+ if (icon !== '') {
398
+ const badIcon = iconProblem(icon);
399
+ if (badIcon !== undefined) return badIcon;
400
+ }
401
+ const owner = asText(record['owner']);
402
+ if (owner !== '') {
403
+ const badOwner = ownerProblem(owner);
404
+ if (badOwner !== undefined) return badOwner;
405
+ }
406
+ const metadata = metadataOf(record['metadata']);
407
+ if (metadata?.unit !== undefined && !UNIT_ID.test(metadata.unit)) {
408
+ return problem('unit', `metadata.unit 只能是小写字母开头的 a-z0-9-(现在是 ${JSON.stringify(metadata.unit)})`, at);
409
+ }
410
+ const title = asLocalized(record['title']);
411
+ const description = asLocalized(record['description']);
412
+ const author = asText(record['author']);
413
+ const homepage = asText(record['homepage']);
414
+ return {
415
+ name,
416
+ ...(title === undefined ? {} : { title }),
417
+ ...(description === undefined ? {} : { description }),
418
+ ...(author === '' ? {} : { author }),
419
+ ...(owner === '' ? {} : { owner }),
420
+ ...(homepage === '' ? {} : { homepage }),
421
+ ...(icon === '' ? {} : { icon }),
422
+ ...(metadata === undefined ? {} : { metadata }),
423
+ };
424
+ }
425
+
426
+ export function parseMarketEntryDoc(raw: unknown): MarketEntryDocParse {
427
+ const record = asRecord(raw);
428
+ if (record === undefined) return { ok: false, problems: [problem('entry', '条目文件必须是一个 JSON 对象')] };
429
+ const fields = docFieldsOf(record, 'entry');
430
+ if ('kind' in fields) return { ok: false, problems: [fields] };
431
+ const version = asText(record['version']);
432
+ const timestamp = record['publishTimestamp'];
433
+ if (timestamp !== undefined && (!Number.isInteger(timestamp) || (timestamp as number) < 0)) {
434
+ return { ok: false, problems: [problem('timestamp', 'publishTimestamp 必须是 Unix 秒整数', 'entry')] };
435
+ }
436
+ if (version === '') {
437
+ if (timestamp === undefined) {
438
+ return { ok: false, problems: [problem('timestamp', '元数据文件要有 publishTimestamp', 'entry')] };
439
+ }
440
+ const epoch = record['epoch'];
441
+ if (epoch !== undefined && (!Number.isInteger(epoch) || (epoch as number) < 0)) {
442
+ return { ok: false, problems: [problem('timestamp', 'epoch 必须是非负整数', 'entry')] };
443
+ }
444
+ return {
445
+ ok: true,
446
+ doc: { ...fields, publishTimestamp: timestamp as number, ...(epoch === undefined ? {} : { epoch: epoch as number }) },
447
+ };
448
+ }
449
+ if (!isValidVersion(version)) {
450
+ return { ok: false, problems: [problem('version', `版本号不是合法 SemVer:${JSON.stringify(version)}`, 'entry')] };
451
+ }
452
+ const source = sourceOf(record['source'], 'entry.source');
453
+ if ('kind' in source) return { ok: false, problems: [source] };
454
+ const engines = asRecord(record['engines']);
455
+ const dsh = engines === undefined ? '' : asText(engines['dsh']);
456
+ return {
457
+ ok: true,
458
+ doc: {
459
+ ...fields,
460
+ version,
461
+ source,
462
+ ...(timestamp === undefined ? {} : { publishTimestamp: timestamp as number }),
463
+ ...(dsh === '' ? {} : { engines: { dsh } }),
464
+ },
465
+ };
466
+ }
467
+ function indexPathBase(dir: string): string {
468
+ return dir.replace(/^\/+|\/+$/g, '') || MARKET_INDEX_DIR;
469
+ }
470
+
471
+ export function marketEntryPath(dir: string, name: string, version: string): string {
472
+ if (!NPM_NAME.test(name)) throw new Error(`不是合法包名:${JSON.stringify(name)}`);
473
+ if (!isValidVersion(version)) throw new Error(`不是合法版本号:${JSON.stringify(version)}`);
474
+ return `${indexPathBase(dir)}/${name}/${version}.json`;
475
+ }
476
+
477
+ export function marketMetaPath(dir: string, name: string, epoch: number, suffix: string): string {
478
+ if (!NPM_NAME.test(name)) throw new Error(`不是合法包名:${JSON.stringify(name)}`);
479
+ if (!Number.isInteger(epoch) || epoch < 0) throw new Error(`epoch 不合法:${String(epoch)}`);
480
+ if (!/^[a-z0-9]{4,16}$/u.test(suffix)) throw new Error(`后缀不合法:${suffix}`);
481
+ return `${indexPathBase(dir)}/${name}/meta-${String(epoch)}-${suffix}.json`;
482
+ }