@dsh-workbench/shared 1.1.4 → 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.
Files changed (81) hide show
  1. package/dist/api/host-write.d.ts +4 -1
  2. package/dist/api/workbench-client.d.ts +2 -0
  3. package/dist/components/ApprovalPlan.css +7 -8
  4. package/dist/config/constants.d.ts +4 -0
  5. package/dist/config/constants.js +4 -0
  6. package/dist/contract/approval.d.ts +4 -0
  7. package/dist/contract/approval.js +4 -0
  8. package/dist/contract/command.d.ts +33 -0
  9. package/dist/contract/command.js +1 -1
  10. package/dist/contract/needs.d.ts +17 -0
  11. package/dist/contract/needs.js +41 -1
  12. package/dist/contract/protocol/bundle-install.d.ts +2 -0
  13. package/dist/contract/protocol/market-index.d.ts +3 -1
  14. package/dist/contract/protocol/market-index.js +2 -0
  15. package/dist/contract/unit.d.ts +10 -0
  16. package/dist/host/adapter-types.d.ts +2 -0
  17. package/dist/host/data-error.d.ts +2 -0
  18. package/dist/host/data-error.js +3 -0
  19. package/dist/host/http.js +1 -0
  20. package/dist/host/install-failure.d.ts +49 -0
  21. package/dist/host/install-failure.js +167 -0
  22. package/dist/host/installed-sources.d.ts +10 -0
  23. package/dist/host/installed-sources.js +64 -0
  24. package/dist/host/lib-install.d.ts +12 -1
  25. package/dist/host/lib-install.js +33 -1
  26. package/dist/host/market-index-claim.d.ts +2 -0
  27. package/dist/host/market-index-claim.js +7 -0
  28. package/dist/host/market-index-doc.d.ts +56 -0
  29. package/dist/host/market-index-doc.js +1 -0
  30. package/dist/host/market-index-parse.d.ts +23 -0
  31. package/dist/host/market-index-parse.js +485 -0
  32. package/dist/host/market-index.d.ts +13 -21
  33. package/dist/host/market-index.js +120 -368
  34. package/dist/host/paths.d.ts +7 -0
  35. package/dist/host/paths.js +17 -0
  36. package/dist/host/runtime-links.d.ts +7 -0
  37. package/dist/host/runtime-links.js +25 -0
  38. package/dist/host/tool-approval.d.ts +4 -2
  39. package/dist/host/tool-approval.js +4 -2
  40. package/dist/host.d.ts +3 -0
  41. package/dist/host.js +3 -0
  42. package/dist/i18n/en.js +50 -4
  43. package/dist/i18n/index.d.ts +51 -5
  44. package/dist/i18n/zh.d.ts +50 -4
  45. package/dist/i18n/zh.js +50 -4
  46. package/dist/index.d.ts +1 -0
  47. package/dist/index.js +1 -0
  48. package/package.json +1 -1
  49. package/src/api/host-write.ts +5 -1
  50. package/src/api/workbench-client.ts +2 -0
  51. package/src/components/ApprovalPlan.css +7 -8
  52. package/src/config/constants.ts +6 -0
  53. package/src/contract/__tests__/needs.test.ts +53 -0
  54. package/src/contract/approval.ts +4 -0
  55. package/src/contract/command.ts +22 -0
  56. package/src/contract/needs.ts +56 -1
  57. package/src/contract/protocol/bundle-install.ts +3 -0
  58. package/src/contract/protocol/market-index.ts +4 -0
  59. package/src/contract/unit.ts +11 -0
  60. package/src/host/__tests__/market-index.test.ts +114 -0
  61. package/src/host/adapter-types.ts +2 -0
  62. package/src/host/data-error.ts +3 -1
  63. package/src/host/http.ts +1 -0
  64. package/src/host/install-failure.test.ts +121 -0
  65. package/src/host/install-failure.ts +198 -0
  66. package/src/host/installed-sources.test.ts +80 -0
  67. package/src/host/installed-sources.ts +73 -0
  68. package/src/host/lib-install.ts +38 -2
  69. package/src/host/market-index-claim.ts +9 -0
  70. package/src/host/market-index-doc.ts +62 -0
  71. package/src/host/market-index-parse.ts +482 -0
  72. package/src/host/market-index.ts +162 -357
  73. package/src/host/paths.test.ts +26 -0
  74. package/src/host/paths.ts +18 -0
  75. package/src/host/runtime-links.test.ts +31 -0
  76. package/src/host/runtime-links.ts +23 -0
  77. package/src/host/tool-approval.ts +11 -4
  78. package/src/host.ts +3 -0
  79. package/src/i18n/en.ts +51 -4
  80. package/src/i18n/zh.ts +51 -4
  81. package/src/index.ts +1 -0
@@ -1,22 +1,14 @@
1
- import type { DiscoverFilter, IndexSourceSpec, MarketIndex, MarketIndexEntry, MarketIndexParse, MarketIndexProblem, MarketIndexVersion, MarketSourceConfig } from '../contract/protocol/market-index.js';
2
- export { marketBranchOk, marketInstallTarget, marketText } from '../lib/market-index.js';
3
- export declare const MARKET_INDEX_SEED = "{\n \"format\": 1,\n \"plugins\": []\n}\n";
1
+ import type { MarketIndex, MarketIndexEntry, MarketIndexVersion } from '../contract/protocol/market-index.js';
2
+ import type { MarketEntryFile, MarketIndexAssemble, MarketMetaDoc, MarketVersionDoc } from './market-index-doc.js';
3
+ export declare const MARKET_ENTRIES_README_LINES: readonly string[];
4
4
  export declare const MARKET_INDEX_README_LINES: readonly string[];
5
- export declare function compareSemver(left: string, right: string): number | undefined;
6
- export declare function parseMarketIndex(raw: unknown): MarketIndexParse;
7
- export declare function parseMarketIndexJson(text: string): MarketIndexParse;
8
- export declare function sortMarketVersions(versions: readonly MarketIndexVersion[]): MarketIndexVersion[];
9
- export declare function upsertMarketEntry(index: MarketIndex, entry: MarketIndexEntry): MarketIndex;
10
- export declare function marketEntryLabels(entry: MarketIndexEntry): readonly string[];
11
- export declare function filterMarketIndex(index: MarketIndex, filter: DiscoverFilter): readonly MarketIndexEntry[];
12
- export declare function marketSourceKey(source: IndexSourceSpec): string;
13
- export type SourceConfigParse = {
14
- readonly ok: true;
15
- readonly source: MarketSourceConfig;
16
- } | {
17
- readonly ok: false;
18
- readonly problem: MarketIndexProblem;
19
- };
20
- export declare function parseSourceConfig(raw: unknown): SourceConfigParse;
21
- export declare function httpUrlProblem(url: string): string | undefined;
22
- export declare function gitUrlOk(url: string): boolean;
5
+ export { marketBranchOk, marketInstallTarget, marketText } from '../lib/market-index.js';
6
+ export type { MarketEntryDoc, MarketEntryDocParse, MarketEntryFile, MarketIndexAssemble, MarketMetaDoc, MarketVersionDoc, } from './market-index-doc.js';
7
+ export { compareSemver, filterMarketIndex, gitUrlOk, httpUrlProblem, marketEntryLabels, marketEntryPath, marketMetaPath, marketSourceKey, parseMarketEntryDoc, parseMarketIndex, parseMarketIndexJson, parseSourceConfig, sortMarketVersions, upsertMarketEntry, } from './market-index-parse.js';
8
+ export type { SourceConfigParse } from './market-index-parse.js';
9
+ export declare function marketVersionDocOf(entry: MarketIndexEntry, version: MarketIndexVersion): MarketVersionDoc;
10
+ export declare function marketMetaDocOf(entry: MarketIndexEntry, epoch: number, at: number): MarketMetaDoc;
11
+ export declare function assembleMarketIndex(files: readonly MarketEntryFile[]): MarketIndexAssemble;
12
+ export declare function marketEntryFilesOf(index: MarketIndex, dir?: string): readonly MarketEntryFile[];
13
+ export declare function collectMarketEntryFiles(dir: string): readonly MarketEntryFile[];
14
+ export declare function marketEntryFilesOfLegacy(text: string, dir?: string): readonly MarketEntryFile[] | undefined;
@@ -1,13 +1,18 @@
1
- import { createHash } from 'node:crypto';
2
- import { MARKET_INDEX_FORMAT } from '../contract/protocol/market-index.js';
3
- import { marketText } from '../lib/market-index.js';
4
- import { compareVersions, isValidVersion } from './version.js';
5
- export { marketBranchOk, marketInstallTarget, marketText } from '../lib/market-index.js';
6
- export const MARKET_INDEX_SEED = '{\n "format": 1,\n "plugins": []\n}\n';
1
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
2
+ import { join, relative, sep } from 'node:path';
3
+ import { MARKET_INDEX_DIR, MARKET_INDEX_FORMAT } from '../contract/protocol/market-index.js';
4
+ import { marketEntryPath, parseMarketEntryDoc, parseMarketIndexJson, sortMarketVersions, } from './market-index-parse.js';
5
+ export const MARKET_ENTRIES_README_LINES = [
6
+ '# 索引目录',
7
+ '',
8
+ '一个包一个目录,一个版本一个文件:`market/<包名>/<版本>.json`;产物在 `artifacts/<包名>/<版本>/`。',
9
+ '',
10
+ '`meta-<epoch>-<随机后缀>.json` 是只改标题 / 署名 / 说明时追加的元数据快照,读取时按 epoch 取最新的一份。',
11
+ ];
7
12
  export const MARKET_INDEX_README_LINES = [
8
13
  '# 模块市场索引',
9
14
  '',
10
- '这个仓库给 DeepSeek Harness 工作台当模块市场索引:`market.json`(format 1)列出可安装的模块与版本。',
15
+ '这个仓库给 DeepSeek Harness 工作台当模块市场索引:条目在 `market/<包名>/<版本>.json`,产物在 `artifacts/<包名>/<版本>/`。',
11
16
  '',
12
17
  '## 发布模块',
13
18
  '',
@@ -17,9 +22,10 @@ export const MARKET_INDEX_README_LINES = [
17
22
  'dsh-wb-module release --index <本仓库地址> --index-policy artifacts-in-repo',
18
23
  '```',
19
24
  '',
20
- '产物会提交到 `packages/<包名>/`(带 scope 时是 `packages/@scope/名字/`),并更新 `market.json`。',
25
+ '产物会提交到 `artifacts/<包名>/<版本>/`,条目提交到 `market/<包名>/<版本>.json`。',
26
+ '发布只新增文件、不改已有文件,两台机器同时发也不会冲突;老条目的 `packages/<包名>/` 路径继续可用。',
21
27
  '',
22
- '一个包名归第一次发布的人(`market.json` 里的 `owner`)。换一个署名发同名会被拒;要换人,先把这一条的 `owner` 改成新的人。',
28
+ '一个包名归第一次发布的人(条目文件里的 `owner`)。换一个署名发同名会被拒;要换人,先把这一条的 `owner` 改成新的人。',
23
29
  '同一个市场里,一个模块 id(`metadata.unit`)只能被一个条目使用;另一个包名想用同一个 id / 产物目录也会被拒。',
24
30
  '',
25
31
  '## 使用这个索引',
@@ -27,385 +33,131 @@ export const MARKET_INDEX_README_LINES = [
27
33
  '在工作台的「模块市场 → 发现」里添加本仓库地址,即可浏览与安装。',
28
34
  '',
29
35
  ];
30
- const NPM_NAME = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/;
31
- const GIT_COMMIT = /^[0-9a-f]{40}$/;
32
- const MAX_ICON_CHARS = 32 * 1024;
33
- function asRecord(value) {
34
- return typeof value === 'object' && value !== null && !Array.isArray(value)
35
- ? value
36
- : undefined;
37
- }
38
- function asText(value) {
39
- return typeof value === 'string' ? value.trim() : '';
40
- }
41
- function asTextArray(value) {
42
- return Array.isArray(value)
43
- ? value.flatMap((item) => (typeof item === 'string' && item.trim() !== '' ? [item.trim()] : []))
44
- : [];
45
- }
46
- function asLocalized(value) {
47
- const record = asRecord(value);
48
- if (record === undefined)
49
- return undefined;
50
- const zh = asText(record['zh']);
51
- const en = asText(record['en']);
52
- return zh === '' && en === '' ? undefined : { ...(zh === '' ? {} : { zh }), ...(en === '' ? {} : { en }) };
53
- }
36
+ export { marketBranchOk, marketInstallTarget, marketText } from '../lib/market-index.js';
37
+ export { compareSemver, filterMarketIndex, gitUrlOk, httpUrlProblem, marketEntryLabels, marketEntryPath, marketMetaPath, marketSourceKey, parseMarketEntryDoc, parseMarketIndex, parseMarketIndexJson, parseSourceConfig, sortMarketVersions, upsertMarketEntry, } from './market-index-parse.js';
54
38
  function problem(kind, detail, at) {
55
39
  return { kind, detail, ...(at === undefined ? {} : { at }) };
56
40
  }
57
- export function compareSemver(left, right) {
58
- return compareVersions(left, right);
59
- }
60
- function sourceOf(raw, at) {
61
- const record = asRecord(raw);
62
- if (record === undefined)
63
- return problem('source', 'source 必须是一个对象', at);
64
- if (record['type'] === 'npm') {
65
- const registry = record['registry'];
66
- if (registry !== undefined && asText(registry) === '') {
67
- return problem('source', 'npm source 的 registry 必须是非空字符串', at);
68
- }
69
- return { type: 'npm', ...(registry === undefined ? {} : { registry: asText(registry) }) };
70
- }
71
- if (record['type'] === 'git') {
72
- const url = asText(record['url']);
73
- const commit = asText(record['commit']);
74
- if (url === '')
75
- return problem('source', 'git source 缺 url', at);
76
- if (!GIT_COMMIT.test(commit)) {
77
- return problem('git-commit', `git source 的 commit 必须是 40 位小写 SHA(现在是 ${JSON.stringify(commit)})`, at);
78
- }
79
- const path = record['path'];
80
- return {
81
- type: 'git',
82
- url,
83
- commit,
84
- ...(path === undefined || asText(path) === '' ? {} : { path: asText(path) }),
85
- };
86
- }
87
- return problem('source', 'source.type 只能是 npm 或 git', at);
88
- }
89
- function versionOf(raw, at) {
90
- const record = asRecord(raw);
91
- if (record === undefined)
92
- return problem('version', '版本必须是一个对象', at);
93
- const version = asText(record['version']);
94
- if (!isValidVersion(version))
95
- return problem('version', `版本号不是合法 SemVer:${JSON.stringify(version)}`, at);
96
- const source = sourceOf(record['source'], `${at}.source`);
97
- if ('kind' in source)
98
- return source;
99
- const timestamp = record['publishTimestamp'];
100
- if (timestamp !== undefined && (!Number.isInteger(timestamp) || timestamp < 0)) {
101
- return problem('timestamp', 'publishTimestamp 必须是 Unix 秒整数', at);
102
- }
103
- const engines = asRecord(record['engines']);
104
- const dsh = engines === undefined ? '' : asText(engines['dsh']);
41
+ function docFieldsFromEntry(entry) {
105
42
  return {
106
- version,
107
- source,
108
- ...(timestamp === undefined ? {} : { publishTimestamp: timestamp }),
109
- ...(dsh === '' ? {} : { engines: { dsh } }),
43
+ name: entry.name,
44
+ ...(entry.title === undefined ? {} : { title: entry.title }),
45
+ ...(entry.description === undefined ? {} : { description: entry.description }),
46
+ ...(entry.author === undefined ? {} : { author: entry.author }),
47
+ ...(entry.owner === undefined ? {} : { owner: entry.owner }),
48
+ ...(entry.homepage === undefined ? {} : { homepage: entry.homepage }),
49
+ ...(entry.icon === undefined ? {} : { icon: entry.icon }),
50
+ ...(entry.metadata === undefined ? {} : { metadata: entry.metadata }),
110
51
  };
111
52
  }
112
- function versionsOf(raw, at) {
113
- if (!Array.isArray(raw) || raw.length === 0)
114
- return problem('versions', 'versions 必须是非空数组', at);
115
- const versions = [];
116
- const seen = new Set();
117
- for (const [index, item] of raw.entries()) {
118
- const parsed = versionOf(item, `${at}[${String(index)}]`);
119
- if ('kind' in parsed)
120
- return parsed;
121
- if (seen.has(parsed.version))
122
- return problem('versions', `版本重复:${parsed.version}`, at);
123
- seen.add(parsed.version);
124
- versions.push(parsed);
125
- }
126
- for (let index = 1; index < versions.length; index += 1) {
127
- const order = compareSemver(versions[index - 1]?.version ?? '', versions[index]?.version ?? '');
128
- if (order === undefined || order < 0) {
129
- return problem('version-order', 'versions 必须按 SemVer 降序', at);
130
- }
131
- }
132
- return versions;
133
- }
134
- function iconProblem(icon) {
135
- if (icon.length > MAX_ICON_CHARS)
136
- return problem('icon', 'icon 超过 32 KiB');
137
- if (icon.startsWith('data:image/'))
138
- return icon.includes(';base64,') ? undefined : problem('icon', 'data URL 必须是 base64');
139
- if (/^https?:\/\//i.test(icon))
140
- return undefined;
141
- return problem('icon', 'icon 只能是 base64 data URL 或 http(s) URL');
142
- }
143
- const MAX_OWNER_CHARS = 200;
144
- const UNIT_ID = /^[a-z][a-z0-9-]*$/;
145
- function ownerProblem(owner) {
146
- if (/[\r\n]/u.test(owner))
147
- return problem('owner', 'owner 只能是一行署名');
148
- if (owner.length > MAX_OWNER_CHARS)
149
- return problem('owner', 'owner 超过 200 字');
150
- return undefined;
151
- }
152
- function metadataOf(raw) {
153
- const record = asRecord(raw);
154
- if (record === undefined)
155
- return undefined;
156
- const workbench = record['workbench'] === true;
157
- const unit = asText(record['unit']);
158
- const category = asText(record['category']);
159
- const labels = asTextArray(record['labels']);
160
- const keywords = asTextArray(record['keywords']);
161
- const sortKeysRecord = asRecord(record['sortKeys']);
162
- const sortKeys = sortKeysRecord === undefined
163
- ? undefined
164
- : Object.fromEntries(Object.entries(sortKeysRecord).flatMap(([key, value]) => typeof value === 'string' || typeof value === 'number' ? [[key, value]] : []));
165
- return {
166
- ...(workbench ? { workbench: true } : {}),
167
- ...(unit === '' ? {} : { unit }),
168
- ...(category === '' ? {} : { category }),
169
- ...(labels.length === 0 ? {} : { labels }),
170
- ...(keywords.length === 0 ? {} : { keywords }),
171
- ...(sortKeys === undefined || Object.keys(sortKeys).length === 0 ? {} : { sortKeys }),
172
- };
53
+ export function marketVersionDocOf(entry, version) {
54
+ return { ...docFieldsFromEntry(entry), ...version };
173
55
  }
174
- function entryOf(raw, at) {
175
- const record = asRecord(raw);
176
- if (record === undefined)
177
- return problem('plugin', '插件条目必须是对象', at);
178
- const name = asText(record['name']);
179
- if (name === '' || name.length > 214 || !NPM_NAME.test(name)) {
180
- return problem('name', `不是合法 npm 包名:${JSON.stringify(name)}`, at);
181
- }
182
- const versions = versionsOf(record['versions'], `${at}.versions`);
183
- if ('kind' in versions)
184
- return versions;
185
- const icon = asText(record['icon']);
186
- if (icon !== '') {
187
- const badIcon = iconProblem(icon);
188
- if (badIcon !== undefined)
189
- return badIcon;
190
- }
191
- const title = asLocalized(record['title']);
192
- const description = asLocalized(record['description']);
193
- const author = asText(record['author']);
194
- const owner = asText(record['owner']);
195
- if (owner !== '') {
196
- const badOwner = ownerProblem(owner);
197
- if (badOwner !== undefined)
198
- return badOwner;
199
- }
200
- const homepage = asText(record['homepage']);
201
- const metadata = metadataOf(record['metadata']);
202
- if (metadata?.unit !== undefined && !UNIT_ID.test(metadata.unit)) {
203
- return problem('unit', `metadata.unit 只能是小写字母开头的 a-z0-9-(现在是 ${JSON.stringify(metadata.unit)})`, at);
204
- }
205
- return {
206
- name,
207
- versions,
208
- ...(title === undefined ? {} : { title }),
209
- ...(description === undefined ? {} : { description }),
210
- ...(author === '' ? {} : { author }),
211
- ...(owner === '' ? {} : { owner }),
212
- ...(homepage === '' ? {} : { homepage }),
213
- ...(icon === '' ? {} : { icon }),
214
- ...(metadata === undefined ? {} : { metadata }),
215
- };
56
+ export function marketMetaDocOf(entry, epoch, at) {
57
+ return { ...docFieldsFromEntry(entry), epoch, publishTimestamp: at };
216
58
  }
217
- export function parseMarketIndex(raw) {
218
- const record = asRecord(raw);
219
- if (record === undefined)
220
- return { ok: false, problems: [problem('not-object', '索引必须是一个 JSON 对象')] };
221
- if (record['format'] !== MARKET_INDEX_FORMAT) {
222
- return {
223
- ok: false,
224
- problems: [problem('format', `format 必须是 ${String(MARKET_INDEX_FORMAT)}(现在是 ${JSON.stringify(record['format'])})`)],
225
- };
226
- }
227
- const plugins = record['plugins'];
228
- if (!Array.isArray(plugins))
229
- return { ok: false, problems: [problem('plugins', 'plugins 必须是数组')] };
230
- const entries = [];
59
+ export function assembleMarketIndex(files) {
231
60
  const problems = [];
232
- const seen = new Set();
233
- for (const [index, item] of plugins.entries()) {
234
- const parsed = entryOf(item, `plugins[${String(index)}]`);
235
- if ('kind' in parsed) {
236
- problems.push(parsed);
61
+ const groups = new Map();
62
+ const ordered = [...files].sort((left, right) => (left.path < right.path ? -1 : left.path > right.path ? 1 : 0));
63
+ for (const file of ordered) {
64
+ let raw;
65
+ try {
66
+ raw = JSON.parse(file.text);
67
+ }
68
+ catch (error) {
69
+ problems.push(problem('not-json', `JSON 解析失败:${error instanceof Error ? error.message : String(error)}`, file.path));
237
70
  continue;
238
71
  }
239
- if (seen.has(parsed.name)) {
240
- problems.push(problem('duplicate-name', `插件名重复:${parsed.name}`, `plugins[${String(index)}]`));
72
+ const parsed = parseMarketEntryDoc(raw);
73
+ if (!parsed.ok) {
74
+ for (const one of parsed.problems)
75
+ problems.push({ ...one, at: file.path });
241
76
  continue;
242
77
  }
243
- seen.add(parsed.name);
244
- entries.push(parsed);
78
+ const doc = parsed.doc;
79
+ const group = groups.get(doc.name) ?? { versions: new Map(), meta: undefined, fallback: undefined };
80
+ const at = doc.publishTimestamp ?? 0;
81
+ if ('version' in doc) {
82
+ if (group.versions.has(doc.version)) {
83
+ problems.push(problem('duplicate-version', `版本重复:${doc.version}`, file.path));
84
+ }
85
+ group.versions.set(doc.version, {
86
+ version: doc.version,
87
+ source: doc.source,
88
+ ...(doc.publishTimestamp === undefined ? {} : { publishTimestamp: doc.publishTimestamp }),
89
+ ...(doc.engines === undefined ? {} : { engines: doc.engines }),
90
+ });
91
+ const newerFallback = group.fallback === undefined ||
92
+ at > group.fallback.at ||
93
+ (at === group.fallback.at && file.path > group.fallback.path);
94
+ if (newerFallback)
95
+ group.fallback = { at, path: file.path, doc };
96
+ }
97
+ else {
98
+ const epoch = doc.epoch ?? 0;
99
+ const newer = group.meta === undefined ||
100
+ epoch > group.meta.epoch ||
101
+ (epoch === group.meta.epoch && at > group.meta.at) ||
102
+ (epoch === group.meta.epoch && at === group.meta.at && file.path > group.meta.path);
103
+ if (newer)
104
+ group.meta = { epoch, at, path: file.path, doc };
105
+ }
106
+ groups.set(doc.name, group);
245
107
  }
246
108
  if (problems.length > 0)
247
109
  return { ok: false, problems };
248
- const title = asLocalized(record['title']);
249
- const description = asLocalized(record['description']);
250
- const metadata = asRecord(record['metadata']);
251
- return {
252
- ok: true,
253
- index: {
254
- format: MARKET_INDEX_FORMAT,
255
- plugins: entries,
256
- ...(title === undefined ? {} : { title }),
257
- ...(description === undefined ? {} : { description }),
258
- ...(metadata === undefined ? {} : { metadata: metadata }),
259
- },
260
- };
261
- }
262
- export function parseMarketIndexJson(text) {
263
- try {
264
- return parseMarketIndex(JSON.parse(text));
265
- }
266
- catch (error) {
110
+ const plugins = [...groups.entries()].map(([name, group]) => {
111
+ const meta = group.meta?.doc ?? group.fallback?.doc;
267
112
  return {
268
- ok: false,
269
- problems: [problem('not-json', `JSON 解析失败:${error instanceof Error ? error.message : String(error)}`)],
113
+ name,
114
+ versions: sortMarketVersions([...group.versions.values()]),
115
+ ...(meta?.title === undefined ? {} : { title: meta.title }),
116
+ ...(meta?.description === undefined ? {} : { description: meta.description }),
117
+ ...(meta?.author === undefined ? {} : { author: meta.author }),
118
+ ...(meta?.owner === undefined ? {} : { owner: meta.owner }),
119
+ ...(meta?.homepage === undefined ? {} : { homepage: meta.homepage }),
120
+ ...(meta?.icon === undefined ? {} : { icon: meta.icon }),
121
+ ...(meta?.metadata === undefined ? {} : { metadata: meta.metadata }),
270
122
  };
271
- }
272
- }
273
- export function sortMarketVersions(versions) {
274
- return [...versions].sort((left, right) => (compareSemver(right.version, left.version) ?? 0));
275
- }
276
- export function upsertMarketEntry(index, entry) {
277
- const found = index.plugins.findIndex((item) => item.name === entry.name);
278
- if (found === -1)
279
- return { ...index, plugins: [...index.plugins, entry] };
280
- const current = index.plugins[found];
281
- if (current === undefined)
282
- return { ...index, plugins: [...index.plugins, entry] };
283
- const merged = new Map();
284
- for (const one of current.versions)
285
- merged.set(one.version, one);
286
- for (const one of entry.versions)
287
- merged.set(one.version, one);
288
- const owner = current.owner ?? entry.owner;
289
- const plugins = [...index.plugins];
290
- plugins[found] = {
291
- ...current,
292
- ...entry,
293
- ...(owner === undefined ? {} : { owner }),
294
- versions: sortMarketVersions([...merged.values()]),
295
- };
296
- return { ...index, plugins };
297
- }
298
- export function marketEntryLabels(entry) {
299
- return entry.metadata?.labels ?? [];
300
- }
301
- export function filterMarketIndex(index, filter) {
302
- const query = (filter.query ?? '').trim().toLowerCase();
303
- const category = (filter.category ?? '').trim();
304
- const label = (filter.label ?? '').trim();
305
- return index.plugins.filter((entry) => {
306
- if (category !== '' && entry.metadata?.category !== category)
307
- return false;
308
- if (label !== '' && !marketEntryLabels(entry).includes(label))
309
- return false;
310
- if (query === '')
311
- return true;
312
- const haystack = [
313
- entry.name,
314
- marketText(entry.title, 'zh'),
315
- marketText(entry.title, 'en'),
316
- marketText(entry.description, 'zh'),
317
- marketText(entry.description, 'en'),
318
- entry.author ?? '',
319
- ...(entry.metadata?.keywords ?? []),
320
- ]
321
- .join(' ')
322
- .toLowerCase();
323
- return haystack.includes(query);
324
123
  });
325
- }
326
- export function marketSourceKey(source) {
327
- const canonical = JSON.stringify([source.kind, source.url.trim(), source.ref ?? '', source.path ?? '']);
328
- return createHash('sha256').update(canonical).digest('hex').slice(0, 16);
329
- }
330
- export function parseSourceConfig(raw) {
331
- const record = asRecord(raw);
332
- if (record === undefined)
333
- return { ok: false, problem: problem('source', '索引源必须是对象') };
334
- const id = asText(record['id']);
335
- const label = asText(record['label']);
336
- const kind = record['kind'];
337
- const url = asText(record['url']);
338
- if (id === '')
339
- return { ok: false, problem: problem('source', '索引源缺 id') };
340
- if (label === '')
341
- return { ok: false, problem: problem('source', '索引源缺 label') };
342
- if (kind !== 'http' && kind !== 'git')
343
- return { ok: false, problem: problem('source', 'kind 只能是 http 或 git') };
344
- if (kind === 'http') {
345
- const bad = httpUrlProblem(url);
346
- if (bad !== undefined)
347
- return { ok: false, problem: problem('source', bad) };
348
- return { ok: true, source: { id, label, kind, url } };
349
- }
350
- if (!gitUrlOk(url)) {
351
- return { ok: false, problem: problem('source', 'git 地址不合格(只收 https / ssh / scp 形式,且不能带凭据)') };
352
- }
353
- const ref = asText(record['ref']);
354
- const path = asText(record['path']);
355
- const localPath = asText(record['localPath']);
356
- const policy = record['policy'];
357
- if (policy !== undefined && policy !== 'artifacts-in-repo' && policy !== 'catalog-only') {
358
- return { ok: false, problem: problem('source', 'policy 只能是 artifacts-in-repo 或 catalog-only') };
124
+ plugins.sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0));
125
+ return { ok: true, index: { format: MARKET_INDEX_FORMAT, plugins } };
126
+ }
127
+ export function marketEntryFilesOf(index, dir = MARKET_INDEX_DIR) {
128
+ const files = [];
129
+ for (const entry of index.plugins) {
130
+ for (const version of entry.versions) {
131
+ files.push({
132
+ path: marketEntryPath(dir, entry.name, version.version),
133
+ text: `${JSON.stringify(marketVersionDocOf(entry, version), null, 2)}\n`,
134
+ });
135
+ }
359
136
  }
360
- return {
361
- ok: true,
362
- source: {
363
- id,
364
- label,
365
- kind,
366
- url,
367
- ...(ref === '' ? {} : { ref }),
368
- ...(path === '' ? {} : { path }),
369
- ...(localPath === '' ? {} : { localPath }),
370
- ...(policy === undefined ? {} : { policy: policy }),
371
- },
137
+ return files;
138
+ }
139
+ export function collectMarketEntryFiles(dir) {
140
+ if (!existsSync(dir))
141
+ return [];
142
+ const files = [];
143
+ const walk = (current) => {
144
+ for (const item of readdirSync(current, { withFileTypes: true })) {
145
+ const full = join(current, item.name);
146
+ if (item.isDirectory()) {
147
+ walk(full);
148
+ continue;
149
+ }
150
+ if (!item.name.endsWith('.json'))
151
+ continue;
152
+ files.push({ path: relative(dir, full).split(sep).join('/'), text: readFileSync(full, 'utf8') });
153
+ }
372
154
  };
155
+ walk(dir);
156
+ return files;
373
157
  }
374
- export function httpUrlProblem(url) {
375
- let parsed;
376
- try {
377
- parsed = new URL(url);
378
- }
379
- catch {
380
- return '不是合法 URL';
381
- }
382
- if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')
383
- return '只收 http / https';
384
- if (parsed.username !== '' || parsed.password !== '')
385
- return 'URL 不能带凭据';
386
- if (parsed.search !== '' || parsed.hash !== '')
387
- return 'URL 不能带 query / fragment';
388
- return undefined;
389
- }
390
- export function gitUrlOk(url) {
391
- if (url === '')
392
- return false;
393
- if (/^[^@\s]+@[^@\s:]+:[^@\s]+$/.test(url))
394
- return true;
395
- let parsed;
396
- try {
397
- parsed = new URL(url);
398
- }
399
- catch {
400
- return false;
401
- }
402
- if (parsed.protocol !== 'https:' && parsed.protocol !== 'ssh:' && parsed.protocol !== 'http:')
403
- return false;
404
- if (parsed.password !== '')
405
- return false;
406
- if (parsed.username !== '' && parsed.protocol !== 'ssh:')
407
- return false;
408
- if (parsed.search !== '' || parsed.hash !== '')
409
- return false;
410
- return true;
158
+ export function marketEntryFilesOfLegacy(text, dir = MARKET_INDEX_DIR) {
159
+ const parsed = parseMarketIndexJson(text);
160
+ if (!parsed.ok)
161
+ return undefined;
162
+ return marketEntryFilesOf(parsed.index, dir);
411
163
  }
@@ -10,3 +10,10 @@ export declare function vendorPeerLink(): {
10
10
  readonly parent: string;
11
11
  };
12
12
  export declare function npmCacheDir(): string;
13
+ export declare function libsBinDir(): string;
14
+ /**
15
+ * 把隔离运行时的共用依赖 bin 目录放到 PATH 最前面(可执行文件都从这儿找)。
16
+ * @param env 改哪份环境(默认当前进程)。
17
+ * @returns 真的插进去了就 `true`;已经在里面就 `false`。
18
+ */
19
+ export declare function ensureLibsBinOnPath(env?: NodeJS.ProcessEnv): boolean;
@@ -1,3 +1,4 @@
1
+ import { delimiter } from 'node:path';
1
2
  import { workbenchRoot } from './data-root.js';
2
3
  export function isolatedRoot() {
3
4
  return `${workbenchRoot()}/opencli`;
@@ -26,3 +27,19 @@ export function vendorPeerLink() {
26
27
  export function npmCacheDir() {
27
28
  return `${isolatedRoot()}/npm-cache`;
28
29
  }
30
+ export function libsBinDir() {
31
+ return `${libsPrefix()}/node_modules/.bin`;
32
+ }
33
+ /**
34
+ * 把隔离运行时的共用依赖 bin 目录放到 PATH 最前面(可执行文件都从这儿找)。
35
+ * @param env 改哪份环境(默认当前进程)。
36
+ * @returns 真的插进去了就 `true`;已经在里面就 `false`。
37
+ */
38
+ export function ensureLibsBinOnPath(env = process.env) {
39
+ const dir = libsBinDir();
40
+ const parts = (env.PATH ?? '').split(delimiter).filter((one) => one !== '');
41
+ if (parts.includes(dir))
42
+ return false;
43
+ env.PATH = [dir, ...parts].join(delimiter);
44
+ return true;
45
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * 让共用依赖也能 import opencli:把隔离运行时里那份 opencli 链接到 libs 的 node_modules。
3
+ * 跑在 libs 里的命令(比如 opencli-workflow 带的 gitops)会按包名找 @jackwener/opencli,
4
+ * 找不到就起不来 —— 它不在 libs 的依赖里,是运行时提供的那一份。
5
+ * @returns 这次真的建了链接就 `true`;已经有了、或运行时那份还没装,就是 `false`。
6
+ */
7
+ export declare function ensureLibsOpencliPeer(): boolean;
@@ -0,0 +1,25 @@
1
+ import { existsSync, mkdirSync, symlinkSync } from 'node:fs';
2
+ import { dirname } from 'node:path';
3
+ import { OPENCLI_NPM_PACKAGE, libsPrefix, toolchainOpencliDir } from './paths.js';
4
+ /**
5
+ * 让共用依赖也能 import opencli:把隔离运行时里那份 opencli 链接到 libs 的 node_modules。
6
+ * 跑在 libs 里的命令(比如 opencli-workflow 带的 gitops)会按包名找 @jackwener/opencli,
7
+ * 找不到就起不来 —— 它不在 libs 的依赖里,是运行时提供的那一份。
8
+ * @returns 这次真的建了链接就 `true`;已经有了、或运行时那份还没装,就是 `false`。
9
+ */
10
+ export function ensureLibsOpencliPeer() {
11
+ const link = `${libsPrefix()}/node_modules/${OPENCLI_NPM_PACKAGE}`;
12
+ if (existsSync(link))
13
+ return false;
14
+ const target = toolchainOpencliDir();
15
+ if (!existsSync(target))
16
+ return false;
17
+ try {
18
+ mkdirSync(dirname(link), { recursive: true });
19
+ symlinkSync(target, link);
20
+ return true;
21
+ }
22
+ catch {
23
+ return false;
24
+ }
25
+ }