@dsh-plugin/dsh-pack-plugin 0.0.0-stage → 0.0.1

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 (76) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +178 -3
  3. package/cordis.patch.yml +9 -0
  4. package/icons/folder-zip-line.svg +1 -0
  5. package/lib/ball.js +597 -0
  6. package/lib/client.js +2934 -0
  7. package/lib/host.js +51745 -0
  8. package/lib/migrate-helper.js +35346 -0
  9. package/lib/progress-main.cjs +79 -0
  10. package/lib/progress-window.ps1 +114 -0
  11. package/lib/progress.html +126 -0
  12. package/lib/publish-to-github/SKILL.md +132 -0
  13. package/package.json +77 -4
  14. package/src/ball-entry.js +5 -0
  15. package/src/ball-host.js +99 -0
  16. package/src/ball-settings.js +352 -0
  17. package/src/ball.js +418 -0
  18. package/src/channel.js +12 -0
  19. package/src/client-plugin.js +58 -0
  20. package/src/client-rpc.js +14 -0
  21. package/src/client.js +5 -0
  22. package/src/core/discovery.js +192 -0
  23. package/src/core/dspack.js +93 -0
  24. package/src/core/extension-files.js +102 -0
  25. package/src/core/extension-install.js +295 -0
  26. package/src/core/extension-patch.js +369 -0
  27. package/src/core/extension-skills.js +164 -0
  28. package/src/core/extension-validate.js +127 -0
  29. package/src/core/extensions.js +207 -0
  30. package/src/core/home-store.js +32 -0
  31. package/src/core/host.js +149 -0
  32. package/src/core/index.js +59 -0
  33. package/src/core/inspect.js +162 -0
  34. package/src/core/install.js +775 -0
  35. package/src/core/managed-install.js +84 -0
  36. package/src/core/manifest.js +717 -0
  37. package/src/core/market.js +268 -0
  38. package/src/core/mcp-composition.js +189 -0
  39. package/src/core/mcp-install.js +112 -0
  40. package/src/core/mcp-transport.js +116 -0
  41. package/src/core/pack.js +371 -0
  42. package/src/core/plugin-metadata.js +355 -0
  43. package/src/core/registry.js +316 -0
  44. package/src/core/repo.js +339 -0
  45. package/src/core/scan.js +78 -0
  46. package/src/core/security.js +101 -0
  47. package/src/core/special.js +50 -0
  48. package/src/core/tar.js +103 -0
  49. package/src/core/update-config.js +234 -0
  50. package/src/core/update.js +792 -0
  51. package/src/core/vendored.js +715 -0
  52. package/src/core/workspace.js +95 -0
  53. package/src/endpoints.js +455 -0
  54. package/src/ensure-manager.js +186 -0
  55. package/src/host-node.js +625 -0
  56. package/src/host.js +17 -0
  57. package/src/index.d.ts +7 -0
  58. package/src/index.js +39 -0
  59. package/src/junction.js +142 -0
  60. package/src/migrate-helper.js +225 -0
  61. package/src/migrate.js +56 -0
  62. package/src/packaged.js +9 -0
  63. package/src/profiles.js +106 -0
  64. package/src/progress-main.cjs +79 -0
  65. package/src/progress-window.ps1 +114 -0
  66. package/src/progress.html +126 -0
  67. package/src/progress.js +132 -0
  68. package/src/rpc.js +157 -0
  69. package/src/runtime.js +43 -0
  70. package/src/section-gate.js +50 -0
  71. package/src/settings-nav-icon.js +188 -0
  72. package/src/settings.js +1611 -0
  73. package/src/skills/index.js +90 -0
  74. package/src/skills/publish-to-github/SKILL.md +132 -0
  75. package/src/tasks.js +145 -0
  76. package/src/v6-dialogs.js +312 -0
@@ -0,0 +1,355 @@
1
+ import { isLocaleString, parsePkgGitSpec } from './manifest.js';
2
+ import { exactNpm, verifyInstalledPluginSource, registryUrl } from './registry.js';
3
+ import { parseDocument } from 'yaml';
4
+
5
+ const object = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
6
+ const assetPrefix = 'assets/plugins/';
7
+ const maxIconBytes = 256 * 1024;
8
+ const isPackageId = (id) => /^(?:@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*$/i.test(id);
9
+ const safeRelative = (s) => typeof s === 'string' && s.length > 0 && s.split('/').every(
10
+ (p) => p !== '' && p !== '.' && p !== '..' && !/[\x00-\x1f\\:#?%<>|*"]|[. ]$/.test(p) &&
11
+ !/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(p),
12
+ );
13
+
14
+ function remoteIcon(raw) {
15
+ try {
16
+ const url = new URL(raw);
17
+ return url.protocol === 'https:' && !url.username && !url.password;
18
+ } catch {
19
+ return false;
20
+ }
21
+ }
22
+
23
+ /** 图标属于归档展示资源;安装器不得将其写入 profile 的 overrides。 */
24
+ export function isPluginAsset(raw) {
25
+ return safeRelative(raw) && raw.startsWith(assetPrefix) && /\.(svg|png|jpe?g|webp)$/i.test(raw);
26
+ }
27
+
28
+ /** 检查单个 profile 的插件描述及其精确选源,返回含插件 ID 的字段错误。 */
29
+ export function validatePluginMetadata(unit) {
30
+ if (unit?.plugins === undefined) {
31
+ return [];
32
+ }
33
+ if (!object(unit.plugins)) {
34
+ return ['plugins 必须是对象'];
35
+ }
36
+ const errors = [];
37
+ for (const [id, item] of Object.entries(unit.plugins)) {
38
+ const label = 'plugins[' + id + ']';
39
+ if (!id || (!unit.bundles?.includes?.(id) && !Object.hasOwn(unit.dependencies || {}, id))) {
40
+ errors.push(label + ' 必须对应本 profile 的 bundle 或依赖');
41
+ }
42
+ if (!object(item)) {
43
+ errors.push(label + ' 必须是对象');
44
+ continue;
45
+ }
46
+ for (const field of ['name', 'desc']) {
47
+ if (item[field] !== undefined && !isLocaleString(item[field])) {
48
+ errors.push(label + '.' + field + ' 必须是字符串或多语言对象');
49
+ }
50
+ }
51
+ if (item.icon !== undefined && (typeof item.icon !== 'string' || !(isPluginAsset(item.icon) || remoteIcon(item.icon)))) {
52
+ errors.push(label + '.icon 必须为 HTTPS 地址或 assets/plugins/ 下的图标路径');
53
+ }
54
+ if (item.source !== undefined) {
55
+ try {
56
+ if (!object(item.source) || item.source.type !== 'npm' || !exactNpm(id, unit.dependencies?.[id])) {
57
+ throw new Error('必须关联当前 profile 的精确 npm 版本');
58
+ }
59
+ if (Object.keys(item.source).some((key) => !['type', 'registry'].includes(key))) {
60
+ throw new Error('只允许 type 和 registry');
61
+ }
62
+ registryUrl(item.source.registry);
63
+ } catch (error) {
64
+ errors.push(label + '.source ' + error.message);
65
+ }
66
+ }
67
+ }
68
+ return errors;
69
+ }
70
+
71
+ /** 对归档资源交叉引用做大小和路径校验,两种包形态共用此规则。 */
72
+ export function validatePluginAssets(manifest, entries) {
73
+ const units = manifest.type === 'dshhome' ? Object.values(manifest.profiles || {}) : [manifest];
74
+ for (const unit of units) {
75
+ for (const [id, item] of Object.entries(unit?.plugins || {})) {
76
+ const icon = item?.icon;
77
+ if (typeof icon === 'string' && !remoteIcon(icon)) {
78
+ if (!isPluginAsset(icon) || !Object.hasOwn(entries, icon) || !entries[icon]?.length || entries[icon].length > maxIconBytes) {
79
+ throw new Error(id + ' 的归档图标缺失、路径无效或超过 256 KiB');
80
+ }
81
+ }
82
+ }
83
+ }
84
+ for (const id of Object.keys(manifest.vendored || {})) {
85
+ const users = units.filter((unit) => Object.hasOwn(unit?.dependencies || {}, id));
86
+ if (!users.some((unit) => unit.plugins?.[id]?.source)) {
87
+ continue;
88
+ }
89
+ const pins = new Set(users.map((unit) => {
90
+ const source = unit.plugins?.[id]?.source;
91
+ return unit.dependencies[id] + ' ' + (source ? registryUrl(source.registry) : '');
92
+ }));
93
+ if (pins.size > 1) {
94
+ throw new Error(id + ' 的共享内嵌副本与各 profile 的来源或版本不一致');
95
+ }
96
+ }
97
+ }
98
+
99
+ function plainPath(value) {
100
+ const rel = typeof value === 'string' ? value.replace(/^\.\//, '') : '';
101
+ return safeRelative(rel) ? rel : null;
102
+ }
103
+
104
+ /** npm 包本身可为 pnpm 的链接。进入包后只读取真实目录和文件。 */
105
+ async function packagePath(host, root, rel, finalType = 'file') {
106
+ if (!plainPath(rel)) {
107
+ return null;
108
+ }
109
+ const parts = rel.split('/');
110
+ let current = root;
111
+ for (const [i, part] of parts.entries()) {
112
+ const list = await host.readdir(current);
113
+ const entry = list?.find((e) => e.name === part);
114
+ if (entry?.type !== (i === parts.length - 1 ? finalType : 'dir')) {
115
+ return null;
116
+ }
117
+ current = host.joinPath(current, part);
118
+ }
119
+ return current;
120
+ }
121
+
122
+ async function collectLocales(host, pkgDir, pkg) {
123
+ const name = Object.create(null);
124
+ const desc = Object.create(null);
125
+ const files = new Map();
126
+ const exports = pkg.exports ?? { './locale/*.json': './locale/*.json' };
127
+ for (const [key, value] of Object.entries(exports)) {
128
+ const match = key.match(/^\.\/locale\/([\w*-]+)\.json$/);
129
+ if (!match) {
130
+ continue;
131
+ }
132
+ const template = typeof value === 'string' ? value : value?.default;
133
+ const target = typeof template === 'string' && plainPath(template.replace('*', 'lang')) ? template.replace(/^\.\//, '') : null;
134
+ if (!target) {
135
+ continue;
136
+ }
137
+ if (match[1] !== '*') {
138
+ files.set(match[1], target);
139
+ continue;
140
+ }
141
+ const slash = target.lastIndexOf('/');
142
+ const dirname = slash < 0 ? '' : target.slice(0, slash);
143
+ const filename = target.slice(slash + 1);
144
+ if (dirname.includes('*') || !filename.includes('*') || filename.indexOf('*') !== filename.lastIndexOf('*')) {
145
+ continue;
146
+ }
147
+ const [prefix, suffix] = filename.split('*');
148
+ const dir = dirname ? await packagePath(host, pkgDir, dirname, 'dir') : pkgDir;
149
+ if (!dir) {
150
+ continue;
151
+ }
152
+ for (const entry of (await host.readdir(dir)) || []) {
153
+ if (entry.type === 'file' && entry.name.startsWith(prefix) && entry.name.endsWith(suffix)) {
154
+ const lang = entry.name.slice(prefix.length, suffix ? -suffix.length : undefined);
155
+ if (/^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*$/.test(lang)) {
156
+ files.set(lang, (dirname ? dirname + '/' : '') + entry.name);
157
+ }
158
+ }
159
+ }
160
+ }
161
+ for (const [lang, rel] of files) {
162
+ const path = await packagePath(host, pkgDir, rel);
163
+ if (!path) {
164
+ continue;
165
+ }
166
+ const raw = await host.readTextFile(path);
167
+ const meta = raw ? JSON.parse(raw)?.meta : null;
168
+ if (typeof meta?.title === 'string' && meta.title.trim()) {
169
+ name[lang] = meta.title;
170
+ }
171
+ if (typeof meta?.description === 'string' && meta.description.trim()) {
172
+ desc[lang] = meta.description;
173
+ }
174
+ }
175
+ return {
176
+ name: Object.keys(name).length ? name : pkg.name,
177
+ desc: Object.keys(desc).length ? desc : typeof pkg.description === 'string' ? pkg.description : undefined,
178
+ };
179
+ }
180
+
181
+ async function registryContext(host, dir) {
182
+ const paths = ['pnpm-lock.yaml', 'node_modules/.modules.yaml', 'pnpm-workspace.yaml'];
183
+ const [lock, modules, workspace] = await Promise.all(paths.map(async (path) => {
184
+ const raw = await host.readTextFile(host.joinPath(dir, ...path.split('/')));
185
+ const doc = raw ? parseDocument(raw) : null;
186
+ return doc?.errors.length ? null : doc;
187
+ }));
188
+ const settings = Object.create(null);
189
+ const user = host.env?.('NPM_CONFIG_USERCONFIG') || host.env?.('npm_config_userconfig') || host.joinPath(host.homedir(), '.npmrc');
190
+ for (const path of [user, host.joinPath(dir, '.npmrc')]) {
191
+ const raw = await host.readTextFile(path);
192
+ for (const line of (raw || '').split(/\r?\n/)) {
193
+ const match = line.trim().match(/^(?:(@[a-z0-9._-]+):)?registry\s*=\s*(\S+)$/i);
194
+ if (match) {
195
+ settings[match[1] || 'default'] = match[2];
196
+ }
197
+ }
198
+ }
199
+ const envRegistry = host.env?.('npm_config_registry') || host.env?.('NPM_CONFIG_REGISTRY');
200
+ if (envRegistry) {
201
+ settings.default = envRegistry;
202
+ }
203
+ return { lock, modules, workspace, settings };
204
+ }
205
+
206
+ const publicNpm = 'https://registry.npmjs.org/';
207
+ const isPublic = (url) => typeof url === 'string' && (url === publicNpm || url + '/' === publicNpm);
208
+
209
+ function inferredPublic(scope, ctx) {
210
+ const installed = ctx.modules?.getIn(['registries', scope]) ?? ctx.modules?.getIn(['registries', 'default']);
211
+ const map = ctx.workspace?.get('registries')?.toJSON();
212
+ const workspaceRoute = map?.[scope] ?? map?.default ?? ctx.workspace?.get('registry');
213
+ const settings = ctx.settings[scope] ?? ctx.settings.default;
214
+ if ((installed != null && !isPublic(installed)) || (workspaceRoute != null && !isPublic(workspaceRoute)) ||
215
+ (settings != null && !isPublic(settings))) {
216
+ return false;
217
+ }
218
+ if (map && Object.values(map).some((v) => v && typeof v === 'object' && v.scopes?.includes?.(scope) && !isPublic(v.url))) {
219
+ return false;
220
+ }
221
+ return isPublic(installed) || isPublic(workspaceRoute) || isPublic(settings);
222
+ }
223
+
224
+ async function publicArtifact(host, pkg, id, release, source, loadContext) {
225
+ if (pkg.private === true || pkg.name !== id || pkg.version !== release || !exactNpm(id, release)) {
226
+ return false;
227
+ }
228
+ if (source && registryUrl(source.registry) !== publicNpm) {
229
+ return false;
230
+ }
231
+ const ctx = await loadContext();
232
+ const short = id.split('/').pop();
233
+ const publicUrl = 'https://registry.npmjs.org/' + id + '/-/' + short + '-' + release + '.tgz';
234
+ const key = ['packages', id + '@' + release, 'resolution'];
235
+ const resolved = ctx.lock?.getIn([...key, 'tarball']);
236
+ const integrity = ctx.lock?.getIn([...key, 'integrity']);
237
+ const recorded = resolved || pkg._resolved;
238
+ const scope = id.startsWith('@') ? id.split('/')[0] : 'default';
239
+ if (!source) {
240
+ if (recorded && recorded !== publicUrl) {
241
+ return false;
242
+ }
243
+ if (!recorded && (!integrity || !inferredPublic(scope, ctx))) {
244
+ return false;
245
+ }
246
+ }
247
+ const tmp = await host.mkdtemp('dspack-public-icon-');
248
+ try {
249
+ const file = host.joinPath(tmp, 'metadata.json');
250
+ await host.download('https://registry.npmjs.org/' + id.replace('/', '%2F') + '/' + encodeURIComponent(release), file);
251
+ const meta = JSON.parse(await host.readTextFile(file));
252
+ return meta?.name === id && meta.version === release && meta.dist?.tarball === publicUrl &&
253
+ (!integrity || meta.dist.integrity === integrity);
254
+ } catch {
255
+ // 离线导出或无法确认公开来源时,图标随归档分发。
256
+ return false;
257
+ } finally {
258
+ await host.rm(tmp, { recursive: true, force: true });
259
+ }
260
+ }
261
+
262
+ async function iconFor(host, pkgDir, pkg, id, release, source, context, entries) {
263
+ const value = pkg.exports?.['./icon'];
264
+ const rel = plainPath((typeof value === 'string' ? value : value?.default) || pkg.icon);
265
+ const ext = rel?.match(/\.(svg|png|jpe?g|webp)$/i)?.[1];
266
+ if (!ext) {
267
+ return undefined;
268
+ }
269
+ const path = await packagePath(host, pkgDir, rel);
270
+ if (!path) {
271
+ return undefined;
272
+ }
273
+ const bytes = await host.readFile(path);
274
+ if (!bytes?.length || bytes.length > maxIconBytes) {
275
+ return undefined;
276
+ }
277
+ if (await publicArtifact(host, pkg, id, release, source, context)) {
278
+ return 'https://cdn.jsdelivr.com/npm/' + id + '@' + release + '/' + rel.split('/').map(encodeURIComponent).join('/');
279
+ }
280
+ const asset = assetPrefix + await host.sha256(bytes) + '.' + ext.toLowerCase();
281
+ entries[asset] = bytes;
282
+ return asset;
283
+ }
284
+
285
+ /** 导出已安装插件的静态展示资料,作者指定的字段优先。 */
286
+ export async function collectPluginMetadata(host, profileDir, unit, { plugins, entries }) {
287
+ if (plugins !== undefined && !object(plugins)) {
288
+ throw new Error('plugins 必须是对象');
289
+ }
290
+ const raw = await host.readTextFile(host.joinPath(profileDir, 'package.json'));
291
+ const profile = raw ? JSON.parse(raw) : {};
292
+ let context;
293
+ const loadContext = () => context ??= registryContext(host, profileDir);
294
+ const ids = new Set([...(unit.bundles || []), ...Object.keys(plugins || {}), ...Object.keys(profile.dependencies || {})]);
295
+ const result = Object.create(null);
296
+ for (const id of ids) {
297
+ const git = parsePkgGitSpec(profile.dependencies?.[id]);
298
+ const coord = git ? 'github:' + git.owner + '/' + git.repo + (git.subpath ? '#path:/' + git.subpath : '') : id;
299
+ const key = unit.bundles?.includes(id) || Object.hasOwn(unit.dependencies || {}, id) ? id : coord;
300
+ const override = Object.hasOwn(plugins || {}, key) ? plugins[key] : undefined;
301
+ const dir = isPackageId(id) ? host.joinPath(profileDir, 'node_modules', ...id.split('/')) : null;
302
+ const installed = dir ? await packagePath(host, dir, 'package.json') : null;
303
+ const text = installed ? await host.readTextFile(installed) : null;
304
+ const pkg = text ? JSON.parse(text) : null;
305
+ const saved = await verifyInstalledPluginSource(host, profileDir, profile, id);
306
+ if (!override && !unit.bundles?.includes(id) && !pkg?.dsh?.bundle && !pkg?.dsh?.client && !saved) {
307
+ continue;
308
+ }
309
+ if (override !== undefined && !object(override)) {
310
+ throw new Error('plugins[' + key + '] 必须是对象');
311
+ }
312
+ const release = unit.dependencies?.[key];
313
+ const current = typeof release === 'string' && override?.version === release;
314
+ let source = saved && saved.version === release ? { type: 'npm', registry: saved.registry } : undefined;
315
+ if (current && Object.hasOwn(override, 'source')) {
316
+ source = override.source?.type === 'npm' && override.source.registry === undefined ? undefined : override.source;
317
+ }
318
+ const entry = pkg ? await collectLocales(host, dir, pkg) : { name: id };
319
+ if (source !== undefined && source !== null) {
320
+ entry.source = source;
321
+ }
322
+ for (const field of ['name', 'desc']) {
323
+ if (override && Object.hasOwn(override, field)) {
324
+ entry[field] = override[field];
325
+ }
326
+ }
327
+ if (override?.icon) {
328
+ entry.icon = override.icon;
329
+ if (isPluginAsset(entry.icon) && !Object.hasOwn(entries, entry.icon)) {
330
+ const path = await packagePath(host, profileDir, entry.icon);
331
+ if (path) {
332
+ entries[entry.icon] = await host.readFile(path);
333
+ }
334
+ }
335
+ } else if (pkg) {
336
+ const icon = await iconFor(host, dir, pkg, key, release, entry.source, loadContext, entries);
337
+ if (icon) {
338
+ entry.icon = icon;
339
+ }
340
+ }
341
+ if (entry.desc === undefined) {
342
+ delete entry.desc;
343
+ }
344
+ result[key] = entry;
345
+ }
346
+ if (Object.keys(result).length) {
347
+ unit.plugins = result;
348
+ }
349
+ const errors = validatePluginMetadata(unit);
350
+ if (errors.length) {
351
+ throw new Error(errors.join(';'));
352
+ }
353
+ validatePluginAssets(unit, entries);
354
+ return result;
355
+ }
@@ -0,0 +1,316 @@
1
+ import { gunzipSync } from 'fflate';
2
+ import { parseDocument } from 'yaml';
3
+ import validRange from 'semver/ranges/valid.js';
4
+ import satisfies from 'semver/functions/satisfies.js';
5
+
6
+ const npmName = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/;
7
+ const version = /^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-(?:(?:0|[1-9]\d*|\d*[A-Za-z-][A-Za-z0-9-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][A-Za-z0-9-]*))*))?(?:\+[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*)?$/;
8
+ const decoder = new TextDecoder();
9
+
10
+ /** 专用源只绑定当前 profile 中完整、确定的 npm 坐标。 */
11
+ export function exactNpm(id, value) {
12
+ return typeof id === 'string' && npmName.test(id) && typeof value === 'string' && version.test(value);
13
+ }
14
+
15
+ /** 分发文件里只保存服务地址,认证信息由安装机提供。 */
16
+ export function registryUrl(raw) {
17
+ if (typeof raw !== 'string' || !raw || raw !== raw.trim()) {
18
+ throw new Error('registry 必须是 HTTP(S) 地址');
19
+ }
20
+ const url = new URL(raw);
21
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || raw.includes('?') || raw.includes('#') || /[\\\s]/.test(raw)) {
22
+ throw new Error('registry 必须是无凭据、查询参数或片段的 HTTP(S) 地址');
23
+ }
24
+ return url.href.replace(/\/?$/, '/');
25
+ }
26
+
27
+ /** 本机 npm 认证项按请求域和路径匹配,私库令牌不发送到其余域名。 */
28
+ async function registryHeaders(host, url, authDir) {
29
+ if (new URL(url).protocol !== 'https:') {
30
+ return {};
31
+ }
32
+ const env = (key) => typeof host.env === 'function' ? host.env(key) : null;
33
+ const config = env('NPM_CONFIG_USERCONFIG') || env('npm_config_userconfig') || host.joinPath(host.homedir(), '.npmrc');
34
+ const paths = [config];
35
+ if (authDir) {
36
+ paths.push(host.joinPath(authDir, '.npmrc'));
37
+ }
38
+ const raw = (await Promise.all([...new Set(paths)].map((path) => host.readTextFile(path)))).join('\n');
39
+ const uri = new URL(url);
40
+ const request = '//' + uri.host + uri.pathname;
41
+ let match = null;
42
+ for (const line of (raw || '').split(/\r?\n/)) {
43
+ const parsed = line.trim().match(/^(\/\/[^=]*?\/):(_authToken|_auth)\s*=\s*(.+)$/);
44
+ if (!parsed || !request.startsWith(parsed[1]) || (match && parsed[1].length < match.prefix.length)) {
45
+ continue;
46
+ }
47
+ const token = parsed[3].replace(/^(['"])(.*)\1$/, '$2').replace(/\$\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g, (_, key) => env(key) || '');
48
+ if (token && !/[\r\n]/.test(token)) {
49
+ match = { prefix: parsed[1], value: (parsed[2] === '_auth' ? 'Basic ' : 'Bearer ') + token };
50
+ }
51
+ }
52
+ return match ? { Authorization: match.value } : {};
53
+ }
54
+
55
+ function tarballPackage(bytes) {
56
+ const tar = gunzipSync(bytes);
57
+ for (let offset = 0; offset + 512 <= tar.length;) {
58
+ const header = tar.subarray(offset, offset + 512);
59
+ const filename = decoder.decode(header.subarray(0, 100)).replace(/\0.*$/s, '');
60
+ const size = Number.parseInt(decoder.decode(header.subarray(124, 136)).replace(/\0.*$/s, '').trim(), 8);
61
+ if (!filename || !Number.isSafeInteger(size) || size < 0 || offset + 512 + size > tar.length) {
62
+ break;
63
+ }
64
+ offset += 512;
65
+ if (filename === 'package/package.json' && (header[156] === 48 || header[156] === 0)) {
66
+ return JSON.parse(decoder.decode(tar.subarray(offset, offset + size)));
67
+ }
68
+ offset += Math.ceil(size / 512) * 512;
69
+ }
70
+ throw new Error('tarball 缺少 package/package.json');
71
+ }
72
+
73
+ async function checkIntegrity(bytes, dist) {
74
+ const candidates = String(dist.integrity || '').split(/\s+/);
75
+ for (const bits of ['512', '384', '256']) {
76
+ const prefix = 'sha' + bits + '-';
77
+ const hashes = candidates.filter((entry) => entry.startsWith(prefix));
78
+ if (hashes.length) {
79
+ const digest = new Uint8Array(await globalThis.crypto.subtle.digest('SHA-' + bits, bytes));
80
+ const actual = prefix + btoa(String.fromCharCode(...digest));
81
+ if (!hashes.includes(actual)) {
82
+ throw new Error('tarball integrity 不符');
83
+ }
84
+ return;
85
+ }
86
+ }
87
+ throw new Error('registry 缺少可验证的 dist.integrity');
88
+ }
89
+
90
+ /** 在指定 registry 单独取得精确版本,验证元数据与压缩包身份,不参与其他依赖的解析。 */
91
+ export async function fetchPluginTarball(host, id, release, source, { authDir } = {}) {
92
+ if (!exactNpm(id, release)) {
93
+ throw new Error('依赖坐标必须是精确 npm 版本:' + id + '@' + release);
94
+ }
95
+ const base = registryUrl(source);
96
+ const headersFor = (url) => url.startsWith(base) ? registryHeaders(host, url, authDir) : {};
97
+ const temp = await host.mkdtemp('dspack-registry-');
98
+ try {
99
+ const metaUrl = base + id.replace('/', '%2F') + '/' + encodeURIComponent(release);
100
+ const file = host.joinPath(temp, 'metadata.json');
101
+ try {
102
+ await host.download(metaUrl, file, { headers: await headersFor(metaUrl), redirectHeaders: headersFor });
103
+ } catch {
104
+ throw new Error('无法从声明的 registry 获取版本元数据,请检查地址和本机 npm 凭据');
105
+ }
106
+ let meta;
107
+ try {
108
+ meta = JSON.parse(await host.readTextFile(file));
109
+ } catch {
110
+ throw new Error('registry 返回了无效的版本元数据');
111
+ }
112
+ if (meta?.name !== id || meta.version !== release) {
113
+ throw new Error('registry 返回的包名或版本不符');
114
+ }
115
+ const tarUrl = new URL(meta.dist?.tarball);
116
+ const localHttp = tarUrl.protocol === 'http:' && tarUrl.origin === new URL(base).origin;
117
+ if ((!localHttp && tarUrl.protocol !== 'https:') || tarUrl.username || tarUrl.password || tarUrl.hash) {
118
+ throw new Error('registry 返回了无效的 tarball 地址');
119
+ }
120
+ const archive = host.joinPath(temp, 'package.tgz');
121
+ try {
122
+ const headers = await headersFor(tarUrl.href);
123
+ await host.download(tarUrl.href, archive, { headers, redirectHeaders: headersFor });
124
+ } catch {
125
+ throw new Error('无法下载 registry 指定的 tarball');
126
+ }
127
+ const bytes = await host.readFile(archive);
128
+ if (!bytes?.length) {
129
+ throw new Error('tarball 为空');
130
+ }
131
+ await checkIntegrity(bytes, meta.dist);
132
+ const pkg = tarballPackage(bytes);
133
+ if (pkg.name !== id || pkg.version !== release) {
134
+ throw new Error('tarball 内的包名或版本不符');
135
+ }
136
+ return bytes;
137
+ } catch (error) {
138
+ throw new Error(id + '@' + release + ' [' + base + ']:' + error.message);
139
+ } finally {
140
+ await host.rm(temp, { recursive: true, force: true });
141
+ }
142
+ }
143
+
144
+ /** 只恢复本工具内容寻址文件的精确版本,用户改写的依赖不会继承旧的选源记录。 */
145
+ export function installedPluginSource(pkg, id) {
146
+ const record = pkg?.dsh?.packforge?.pluginSources?.[id];
147
+ if (!record || !exactNpm(id, record.version) || !/^[a-f0-9]{64}$/.test(record.sha256)) {
148
+ return null;
149
+ }
150
+ if (pkg.dependencies?.[id] !== 'file:.dspack-sources/' + record.sha256 + '.tgz') {
151
+ return null;
152
+ }
153
+ return { version: record.version, registry: registryUrl(record.registry) };
154
+ }
155
+
156
+ /** 验证本机来源记录仍匹配安装时保存的不可变原件。 */
157
+ export async function verifyInstalledPluginSource(host, dir, pkg, id) {
158
+ const saved = installedPluginSource(pkg, id);
159
+ if (!saved) {
160
+ return null;
161
+ }
162
+ const expected = pkg.dsh.packforge.pluginSources[id].sha256;
163
+ const bytes = await host.readFile(host.joinPath(dir, '.dspack-sources', expected + '.tgz'));
164
+ if (!bytes || await host.sha256(bytes) !== expected) {
165
+ throw new Error(id + '@' + saved.version + ' 的已安装来源记录缺少匹配的 tarball');
166
+ }
167
+ const actual = tarballPackage(bytes);
168
+ if (actual.name !== id || actual.version !== saved.version) {
169
+ throw new Error(id + '@' + saved.version + ' 的已安装来源与 tarball 身份不符');
170
+ }
171
+ return saved;
172
+ }
173
+
174
+ async function unlockSources(host, dir, sources) {
175
+ const path = host.joinPath(dir, 'pnpm-lock.yaml');
176
+ const raw = await host.readTextFile(path);
177
+ if (!raw) {
178
+ return;
179
+ }
180
+ const lock = parseDocument(raw);
181
+ if (lock.errors.length) {
182
+ throw new Error('专用源安装无法校验 pnpm-lock.yaml');
183
+ }
184
+ const files = new Set(Object.values(sources).map((source) => 'file:.dspack-sources/' + source.sha256 + '.tgz'));
185
+ let changed = false;
186
+ for (const id of Object.keys(sources)) {
187
+ for (const field of ['dependencies', 'optionalDependencies', 'devDependencies']) {
188
+ for (const key of [[field, id], ['importers', '.', field, id]]) {
189
+ if (lock.hasIn(key)) {
190
+ lock.deleteIn(key);
191
+ changed = true;
192
+ }
193
+ }
194
+ }
195
+ }
196
+ for (const section of ['packages', 'snapshots']) {
197
+ for (const item of lock.get(section)?.items || []) {
198
+ const key = item.key.value;
199
+ if (typeof key === 'string' && [...files].some((file) => key.includes(file))) {
200
+ lock.deleteIn([section, key]);
201
+ changed = true;
202
+ }
203
+ }
204
+ }
205
+ if (changed) {
206
+ await host.writeTextFile(path, lock.toString());
207
+ }
208
+ }
209
+
210
+ function assertSourceOverrides(id, release, pkg, overrides) {
211
+ const name = pkg.name;
212
+ for (const key of Object.keys(overrides || {})) {
213
+ const split = key.lastIndexOf('>');
214
+ if (split >= 0 && key.slice(0, split) !== name && !key.slice(0, split).startsWith(name + '@')) {
215
+ continue;
216
+ }
217
+ if (split >= 0 && pkg.version && key.slice(0, split).startsWith(name + '@')) {
218
+ const parentRange = key.slice(name.length + 1, split);
219
+ if (validRange(parentRange) && !satisfies(pkg.version, parentRange)) continue;
220
+ }
221
+ const selector = key.slice(split + 1);
222
+ if (selector === id || selector.startsWith(id + '@')) {
223
+ const range = selector.slice(id.length + 1);
224
+ if (!range || !validRange(range) || satisfies(release, range)) {
225
+ throw new Error(id + '@' + release + ' 的专用源与 overrides[' + key + '] 冲突');
226
+ }
227
+ }
228
+ }
229
+ }
230
+
231
+ async function workspaceOverrides(host, dir) {
232
+ const raw = await host.readTextFile(host.joinPath(dir, 'pnpm-workspace.yaml'));
233
+ const doc = raw ? parseDocument(raw) : null;
234
+ if (doc?.errors.length) {
235
+ throw new Error('专用源安装无法校验 pnpm-workspace.yaml');
236
+ }
237
+ return doc?.get('overrides')?.toJSON();
238
+ }
239
+
240
+ /** 比较合并后的直接依赖与暂存阶段已核验的来源,防止同版本改用旧锁或本地替换。 */
241
+ export async function verifyActivePluginSources(host, dir, unit, verifiedDir, { prepareLock = true } = {}) {
242
+ const declared = Object.entries(unit?.plugins || {}).filter(([, entry]) => entry?.source !== undefined);
243
+ if (!declared.length) {
244
+ return;
245
+ }
246
+ const pkg = JSON.parse(await host.readTextFile(host.joinPath(dir, 'package.json')));
247
+ const verified = JSON.parse(await host.readTextFile(host.joinPath(verifiedDir, 'package.json')));
248
+ const overrides = await workspaceOverrides(host, dir);
249
+ const pins = Object.create(null);
250
+ for (const [id, plugin] of declared) {
251
+ const release = unit.dependencies[id];
252
+ const actual = pkg.optionalDependencies?.[id] ?? pkg.dependencies?.[id] ?? pkg.devDependencies?.[id];
253
+ if (actual === undefined || (exactNpm(id, actual) && actual !== release)) {
254
+ continue;
255
+ }
256
+ const saved = await verifyInstalledPluginSource(host, dir, pkg, id);
257
+ if (saved && saved.version !== release && actual === pkg.dependencies[id]) {
258
+ continue;
259
+ }
260
+ const expected = verified?.dsh?.packforge?.pluginSources?.[id];
261
+ const active = pkg.dsh?.packforge?.pluginSources?.[id];
262
+ if (!expected || !saved || saved.version !== release || saved.registry !== registryUrl(plugin.source.registry) ||
263
+ active.sha256 !== expected.sha256 || ['optionalDependencies', 'devDependencies'].some((field) =>
264
+ Object.hasOwn(pkg[field] || {}, id) && pkg[field][id] !== actual)) {
265
+ throw new Error(id + '@' + release + ' 合并后的依赖与已验证来源不同,请重新处理冲突');
266
+ }
267
+ assertSourceOverrides(id, release, pkg, pkg.pnpm?.overrides);
268
+ assertSourceOverrides(id, release, pkg, overrides);
269
+ pins[id] = active;
270
+ }
271
+ if (prepareLock && Object.keys(pins).length) {
272
+ await unlockSources(host, dir, pins);
273
+ }
274
+ }
275
+
276
+ /** 在每个 profile 的依赖安装前固定本次归档的原件,后续 pnpm 重装也会读取相同内容。 */
277
+ export async function applyPluginSources(host, dir, unit, { vendored, entries, authDir } = {}) {
278
+ const declared = Object.entries(unit.plugins || {}).filter(([, plugin]) => plugin.source !== undefined);
279
+ if (!declared.length) {
280
+ return;
281
+ }
282
+ const pkgPath = host.joinPath(dir, 'package.json');
283
+ const pkg = JSON.parse(await host.readTextFile(pkgPath));
284
+ const overrides = await workspaceOverrides(host, dir);
285
+ const sources = Object.create(null);
286
+ for (const [id, plugin] of declared) {
287
+ const release = unit.dependencies?.[id];
288
+ if (plugin.source?.type !== 'npm' || !exactNpm(id, release)) {
289
+ throw new Error('无效的专用源依赖:' + id);
290
+ }
291
+ assertSourceOverrides(id, release, pkg, pkg.pnpm?.overrides);
292
+ assertSourceOverrides(id, release, pkg, overrides);
293
+ const bytes = await fetchPluginTarball(host, id, release, plugin.source.registry, { authDir });
294
+ const sha256 = await host.sha256(bytes);
295
+ if (vendored && Object.hasOwn(vendored, id)) {
296
+ const copy = vendored[id];
297
+ const supplied = entries?.[copy.path];
298
+ if (copy.version !== release || copy.sha256 !== sha256 || supplied?.length !== copy.size ||
299
+ !supplied || await host.sha256(supplied) !== sha256) {
300
+ throw new Error(id + '@' + release + ' 的内嵌 tarball 与指定源不符');
301
+ }
302
+ }
303
+ const rel = '.dspack-sources/' + sha256 + '.tgz';
304
+ await host.writeFile(host.joinPath(dir, ...rel.split('/')), bytes);
305
+ pkg.dependencies[id] = 'file:' + rel;
306
+ for (const field of ['optionalDependencies', 'devDependencies']) {
307
+ if (pkg[field] && Object.hasOwn(pkg[field], id)) {
308
+ pkg[field][id] = 'file:' + rel;
309
+ }
310
+ }
311
+ sources[id] = { version: release, registry: registryUrl(plugin.source.registry), sha256 };
312
+ }
313
+ pkg.dsh = { ...pkg.dsh, packforge: { ...pkg.dsh?.packforge, pluginSources: sources } };
314
+ await unlockSources(host, dir, sources);
315
+ await host.writeTextFile(pkgPath, JSON.stringify(pkg, null, 2) + '\n');
316
+ }