@deepseek-ai/dsh-plugin-manager 0.2.1-rc.3 → 0.2.2-alpha.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.
@@ -40,9 +40,14 @@ import { join } from 'node:path';
40
40
  import { pathToFileURL } from 'node:url';
41
41
  import { withFileLock, writeFileAtomic } from '@deepseek-ai/dsh-atomic-write';
42
42
  import z from '@deepseek-ai/schemastery';
43
- import { TypertRemoteService, Remote } from '@deepseek-ai/dsh-typert-protocol';
43
+ import semver from 'semver';
44
+ import { TypertRemoteService, Remote, RemoteError, remoteErrorOf } from '@deepseek-ai/dsh-typert-protocol';
45
+ import { detailImageResponse, NPM_FILE_SOURCES } from '@deepseek-ai/dsh-plugin-detail';
46
+ import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout';
47
+ import { readBundleDocument, readBundleImage } from "./bundle-detail.js";
44
48
  import { pluginEntryId, readPluginInventory } from '@deepseek-ai/dsh-host-plugin-inventory';
45
- import { readPluginMeta, readProfileManifest, resolveBundleDir, loadOverlayPatches, composeEntries, readProfilePatches, OPTIONAL_BUNDLES, bundlePatchPaths, evaluatePluginCompatibility, readProfileCompatibility, readProfileVersionExemptions, setProfileVersionExemption, PROFILE_COMPATIBILITY_FILENAME, OFFICIAL_ON_DEMAND_CATALOG, getDshRuntimeVersion, ResolutionRestartRequired, } from '@deepseek-ai/dsh-app-boot';
49
+ import { readPluginMeta, readProfileManifest, resolveBundleDir, loadOverlayPatches, composeEntries, readProfilePatches, bundlePatchPaths, evaluatePluginCompatibility, readProfileCompatibility, readProfileVersionExemptions, setProfileVersionExemption, validatePluginVersionExemption, PROFILE_COMPATIBILITY_FILENAME, getDshRuntimeVersion, ResolutionRestartRequired, assertBundlePlatform, UnsupportedBundlePlatformError, } from '@deepseek-ai/dsh-app-boot';
50
+ import { OPTIONAL_BUNDLES, OFFICIAL_ON_DEMAND_CATALOG, PROTECTED_PLUGINS } from '@deepseek-ai/dsh-official-bundles';
46
51
  import { bundleManifest, readProfileRegistry, registryArguments, runProfilePnpm, saveManifest, viewProfilePackage } from "./operations.js";
47
52
  import { classifyInstallFailure } from "./install-failure.js";
48
53
  import { officialBundleInstallTarget } from "./official-install-target.js";
@@ -52,29 +57,26 @@ import { flatten, writePluginEnabled } from "./patch.js";
52
57
  import { incompatiblePlugin, ManagementFailure } from "./failure.js";
53
58
  import { approveBuilds, recordPendingBuilds } from "./build-approval.js";
54
59
  import { checkGithubConnection } from "./github-connection.js";
60
+ import { chooseGitTransport, sshGitSpec } from "./git-transport.js";
61
+ import { newerVersions, VERSION_FIELDS, VERSION_LIST_FIELDS, versionFacts } from "./versions.js";
55
62
  export { classifyInstallFailure } from "./install-failure.js";
56
63
  export { InvalidInstallSpecError, parseInstallSpec } from "./install-spec.js";
64
+ /** The Fetch route serving images beside bundle detail documents. */
65
+ const DETAIL_FILE_PATH = '/api/plugin-manager/detail-file';
57
66
  /** An http(s) URL, as pnpm's `--registry` takes it. */
58
67
  const REGISTRY_URL = /^https?:\/\/\S+$/;
59
- const protectedModules = new Set([
60
- '@deepseek-ai/dsh-plugin-manager', '@deepseek-ai/cordis-plugin-loader',
61
- '@deepseek-ai/cordis-plugin-include', '@deepseek-ai/dsh-api-gateway',
62
- '@deepseek-ai/dsh-host-webserver', '@deepseek-ai/dsh-client-modules',
63
- '@deepseek-ai/dsh-client-ui-settings-plugin-inventory', '@deepseek-ai/dsh-client-ui-plugin-manager',
64
- '@deepseek-ai/dsh-host-plugin-inventory', '@deepseek-ai/dsh-typert-registry',
65
- '@deepseek-ai/dsh-api-remotes', '@deepseek-ai/dsh-api-remote-access',
66
- '@deepseek-ai/cordis-plugin-timer', '@deepseek-ai/dsh-client-connection',
67
- '@deepseek-ai/dsh-host-frontend-static', '@deepseek-ai/dsh-tools',
68
- '@deepseek-ai/dsh-hmr',
69
- ]);
70
68
  /** The profile files an installation writes and a failed or cancelled one restores. */
71
69
  const RESTORED_FILES = ['package.json', 'pnpm-lock.yaml'];
70
+ /** The manifest fields an inspection reads for a registry spec. */
71
+ const INSPECT_FIELDS = ['name', 'version', 'description', 'dsh'];
72
72
  /** pnpm's colour escapes, which a JSON answer may be wrapped in. */
73
73
  const ANSI_SEQUENCE = /\x1b\[[0-9;]*m/g;
74
74
  /** Preserve the exact observed diagnostic, including non-Error failures. */
75
75
  function messageOf(error) { return error instanceof Error ? error.message : String(error); }
76
76
  /** An expected refusal keeps its code; anything else becomes an operation error carrying its exact diagnostic. */
77
77
  function managementError(error) {
78
+ if (error instanceof UnsupportedBundlePlatformError)
79
+ return { code: 'unsupported-platform' };
78
80
  if (!(error instanceof ManagementFailure))
79
81
  return { code: 'operation-error', diagnostic: messageOf(error) };
80
82
  return { code: error.code, ...error.incompatible === undefined ? {} : { incompatible: error.incompatible } };
@@ -109,6 +111,52 @@ function inspectionOf(kind, manifest, registry) {
109
111
  function refused(problem, reason) {
110
112
  return { status: 'refused', problem, reason };
111
113
  }
114
+ /**
115
+ * Why an update cannot replace a listed bundle, or what it replaces.
116
+ * @param bundle The listed bundle, or undefined for a name the inventory does not list.
117
+ * @param name The package name, for the refusal.
118
+ * @returns The bundle, its installed version, and its registry spec; or the refusal's diagnostic.
119
+ */
120
+ function updateRefusal(bundle, name) {
121
+ if (bundle === undefined || !bundle.installed || bundle.availability !== 'profile' || bundle.official || bundle.source === undefined) {
122
+ return `${name} is not a third-party package installed in this profile`;
123
+ }
124
+ // A management bundle cannot be removed, so it cannot be replaced either.
125
+ if (bundle.readOnlyReason !== undefined)
126
+ return `${bundle.name} carries plugin management and cannot be removed`;
127
+ const installed = bundle.version;
128
+ if (installed === undefined || semver.valid(installed) === null)
129
+ return `${bundle.name} declares no semver version`;
130
+ const parsed = parsedForRegistry(bundle.source);
131
+ // A protocol in the saved range, such as an `npm:` alias, names another package than the dependency.
132
+ if (parsed.kind !== 'registry' || parsed.name !== bundle.name || parsed.range?.includes(':') === true) {
133
+ return `${bundle.name} is not installed from a registry under its own name`;
134
+ }
135
+ return { bundle, installed, parsed };
136
+ }
137
+ /**
138
+ * Map items with at most `limit` calls in flight, stopping new calls once one answers `stop`.
139
+ * @param items - the items, in order.
140
+ * @param limit - the most calls in flight.
141
+ * @param map - the call for one item.
142
+ * @param stop - whether an answer ends the remaining calls.
143
+ * @returns the answers of the calls that ran, in item order; items after a stop stay absent.
144
+ */
145
+ async function mapConcurrent(items, limit, map, stop) {
146
+ const answers = items.map(() => undefined);
147
+ let next = 0;
148
+ let stopped = false;
149
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
150
+ while (!stopped && next < items.length) {
151
+ const index = next++;
152
+ const answer = await map(items[index]);
153
+ answers[index] = answer;
154
+ if (stop(answer))
155
+ stopped = true;
156
+ }
157
+ }));
158
+ return answers;
159
+ }
112
160
  /** The refusal `pnpm view --json` prints on stdout, `{ error: { code, message } }`, as one log line; empty for anything else. */
113
161
  function printedError(printed) {
114
162
  let parsed;
@@ -130,7 +178,7 @@ function bundleSelection(manifest) {
130
178
  }
131
179
  /**
132
180
  * The package an installation spec names before pnpm runs: a registry name, a local directory's manifest name, or the
133
- * dependency saved with this git or tarball spec, compared as the plugin list shows saved specs.
181
+ * dependency saved with this git or tarball spec or the SSH form of its Git URL, compared as the plugin list shows saved specs.
134
182
  * @param spec The installation spec.
135
183
  * @param dependencies The profile's saved dependencies.
136
184
  * @param profileDir The profile directory saved local paths are relative to.
@@ -142,7 +190,8 @@ function specPackageName(spec, dependencies, profileDir) {
142
190
  return parsed.name;
143
191
  if (parsed.kind === 'path')
144
192
  return packageName(parsed.path);
145
- const specs = parsed.kind === 'tarball' && parsed.path !== undefined ? [spec, `file:${parsed.path}`] : [spec];
193
+ const alternative = parsed.kind === 'tarball' && parsed.path !== undefined ? `file:${parsed.path}` : sshGitSpec(parsed);
194
+ const specs = alternative === undefined ? [spec] : [spec, alternative];
146
195
  return Object.entries(dependencies).find(([dependency, saved]) => specs.includes(dependencySpec(dependency, saved, profileDir)))?.[0];
147
196
  }
148
197
  /** The package name a local directory declares, or `undefined` without a readable manifest. */
@@ -167,16 +216,46 @@ function parsedForRegistry(spec) {
167
216
  return { kind: 'registry', spec, name: spec };
168
217
  }
169
218
  }
219
+ /** Only registry package names are retained before installation resolves its target. */
220
+ function installOperationTarget(spec) {
221
+ let parsed;
222
+ try {
223
+ parsed = parseInstallSpec(spec);
224
+ }
225
+ catch (_error) {
226
+ return null; /* Invalid specs remain private; installation owns their refusal. */
227
+ }
228
+ return parsed.kind === 'registry' ? parsed.name : null;
229
+ }
230
+ /** Exemption facts use canonical package identity, never the raw request or installed version. */
231
+ function exemptionOperationIdentity(packageVersion, runtimeVersion) {
232
+ try {
233
+ validatePluginVersionExemption(packageVersion, runtimeVersion);
234
+ }
235
+ catch (_error) {
236
+ return { target: null }; /* The operation still owns validation failure reporting. */
237
+ }
238
+ const separator = packageVersion.lastIndexOf('@');
239
+ return { target: installOperationTarget(packageVersion.slice(0, separator)),
240
+ version: diagnosticVersion(packageVersion.slice(separator + 1)) };
241
+ }
242
+ /** Unusable file metadata must not discard the rest of an operation record. */
243
+ function diagnosticVersion(value) {
244
+ return typeof value === 'string' && value.length <= 128 ? value : undefined;
245
+ }
170
246
  /** Manage profile files and apply their declared reload lifecycle. */
171
247
  let PluginManager = (() => {
172
248
  let _classSuper = TypertRemoteService;
173
249
  let _instanceExtraInitializers = [];
250
+ let _readBundleDetail_decorators;
174
251
  let _listVersionExemptions_decorators;
175
252
  let _setVersionExemption_decorators;
176
253
  let _listPlugins_decorators;
177
254
  let _listBundles_decorators;
178
255
  let _registries_decorators;
179
256
  let _inspect_decorators;
257
+ let _listVersions_decorators;
258
+ let _updateBundle_decorators;
180
259
  let _setPluginEnabled_decorators;
181
260
  let _setBundleEnabled_decorators;
182
261
  let _installBundle_decorators;
@@ -186,24 +265,30 @@ let PluginManager = (() => {
186
265
  return class PluginManager extends _classSuper {
187
266
  static {
188
267
  const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
268
+ _readBundleDetail_decorators = [Remote];
189
269
  _listVersionExemptions_decorators = [Remote];
190
270
  _setVersionExemption_decorators = [Remote];
191
271
  _listPlugins_decorators = [Remote];
192
272
  _listBundles_decorators = [Remote];
193
273
  _registries_decorators = [Remote];
194
274
  _inspect_decorators = [Remote];
275
+ _listVersions_decorators = [Remote];
276
+ _updateBundle_decorators = [Remote];
195
277
  _setPluginEnabled_decorators = [Remote];
196
278
  _setBundleEnabled_decorators = [Remote];
197
279
  _installBundle_decorators = [Remote];
198
280
  _waitForInstall_decorators = [Remote];
199
281
  _cancelInstall_decorators = [Remote];
200
282
  _removeBundle_decorators = [Remote];
283
+ __esDecorate(this, null, _readBundleDetail_decorators, { kind: "method", name: "readBundleDetail", static: false, private: false, access: { has: obj => "readBundleDetail" in obj, get: obj => obj.readBundleDetail }, metadata: _metadata }, null, _instanceExtraInitializers);
201
284
  __esDecorate(this, null, _listVersionExemptions_decorators, { kind: "method", name: "listVersionExemptions", static: false, private: false, access: { has: obj => "listVersionExemptions" in obj, get: obj => obj.listVersionExemptions }, metadata: _metadata }, null, _instanceExtraInitializers);
202
285
  __esDecorate(this, null, _setVersionExemption_decorators, { kind: "method", name: "setVersionExemption", static: false, private: false, access: { has: obj => "setVersionExemption" in obj, get: obj => obj.setVersionExemption }, metadata: _metadata }, null, _instanceExtraInitializers);
203
286
  __esDecorate(this, null, _listPlugins_decorators, { kind: "method", name: "listPlugins", static: false, private: false, access: { has: obj => "listPlugins" in obj, get: obj => obj.listPlugins }, metadata: _metadata }, null, _instanceExtraInitializers);
204
287
  __esDecorate(this, null, _listBundles_decorators, { kind: "method", name: "listBundles", static: false, private: false, access: { has: obj => "listBundles" in obj, get: obj => obj.listBundles }, metadata: _metadata }, null, _instanceExtraInitializers);
205
288
  __esDecorate(this, null, _registries_decorators, { kind: "method", name: "registries", static: false, private: false, access: { has: obj => "registries" in obj, get: obj => obj.registries }, metadata: _metadata }, null, _instanceExtraInitializers);
206
289
  __esDecorate(this, null, _inspect_decorators, { kind: "method", name: "inspect", static: false, private: false, access: { has: obj => "inspect" in obj, get: obj => obj.inspect }, metadata: _metadata }, null, _instanceExtraInitializers);
290
+ __esDecorate(this, null, _listVersions_decorators, { kind: "method", name: "listVersions", static: false, private: false, access: { has: obj => "listVersions" in obj, get: obj => obj.listVersions }, metadata: _metadata }, null, _instanceExtraInitializers);
291
+ __esDecorate(this, null, _updateBundle_decorators, { kind: "method", name: "updateBundle", static: false, private: false, access: { has: obj => "updateBundle" in obj, get: obj => obj.updateBundle }, metadata: _metadata }, null, _instanceExtraInitializers);
207
292
  __esDecorate(this, null, _setPluginEnabled_decorators, { kind: "method", name: "setPluginEnabled", static: false, private: false, access: { has: obj => "setPluginEnabled" in obj, get: obj => obj.setPluginEnabled }, metadata: _metadata }, null, _instanceExtraInitializers);
208
293
  __esDecorate(this, null, _setBundleEnabled_decorators, { kind: "method", name: "setBundleEnabled", static: false, private: false, access: { has: obj => "setBundleEnabled" in obj, get: obj => obj.setBundleEnabled }, metadata: _metadata }, null, _instanceExtraInitializers);
209
294
  __esDecorate(this, null, _installBundle_decorators, { kind: "method", name: "installBundle", static: false, private: false, access: { has: obj => "installBundle" in obj, get: obj => obj.installBundle }, metadata: _metadata }, null, _instanceExtraInitializers);
@@ -219,9 +304,16 @@ let PluginManager = (() => {
219
304
  lockWaitMs: z.number().step(1).min(0).default(120000),
220
305
  inspectTimeoutMs: z.number().step(1).min(1000).default(20000),
221
306
  githubConnectionTimeoutMs: z.number().step(1).min(1000).default(5000),
307
+ gitTransportTimeoutMs: z.number().step(1).min(1000).default(5000),
222
308
  idleTimeoutMs: z.number().step(1).min(1000).default(600000),
223
309
  registry: z.string().pattern(REGISTRY_URL),
224
310
  fallbackRegistries: z.array(z.string().pattern(REGISTRY_URL)).default([NPMMIRROR_REGISTRY]),
311
+ versionListLimit: z.number().step(1).min(1).default(20),
312
+ versionLookupConcurrency: z.number().step(1).min(1).default(4),
313
+ detailMaxBytes: z.natural().min(1).default(1024 * 1024),
314
+ detailImageMaxBytes: z.natural().min(1).default(5 * 1024 * 1024),
315
+ detailFetchTimeoutMs: z.natural().min(1).max(MAX_TIMER_DELAY_MS).default(15000),
316
+ detailNpmFileSources: z.array(z.union(NPM_FILE_SOURCES)).min(1).default([...NPM_FILE_SOURCES]),
225
317
  });
226
318
  /** Management bundles remain protected if their files become unreadable. */
227
319
  managementBundles = (__runInitializers(this, _instanceExtraInitializers), new Set());
@@ -237,13 +329,17 @@ let PluginManager = (() => {
237
329
  lockWaitMs;
238
330
  inspectTimeoutMs;
239
331
  githubConnectionTimeoutMs;
332
+ gitTransportTimeoutMs;
240
333
  idleTimeoutMs;
241
334
  pnpmCommand;
335
+ versionListLimit;
336
+ versionLookupConcurrency;
242
337
  configuredRegistries;
243
338
  ownerContext;
244
339
  abort = new AbortController();
245
340
  /** Installations by request id, from their call until it settles. */
246
341
  installs = new Map();
342
+ detail;
247
343
  constructor(ctx, config) {
248
344
  super(ctx, 'pluginManager');
249
345
  this.ownerEntryId = ctx.fiber.entry?.id;
@@ -255,16 +351,74 @@ let PluginManager = (() => {
255
351
  this.lockWaitMs = config.lockWaitMs;
256
352
  this.inspectTimeoutMs = config.inspectTimeoutMs;
257
353
  this.githubConnectionTimeoutMs = config.githubConnectionTimeoutMs;
354
+ this.gitTransportTimeoutMs = config.gitTransportTimeoutMs;
258
355
  this.idleTimeoutMs = config.idleTimeoutMs;
259
356
  this.pnpmCommand = config.pnpmCommand;
357
+ this.versionListLimit = config.versionListLimit;
358
+ this.versionLookupConcurrency = config.versionLookupConcurrency;
260
359
  this.configuredRegistries = {
261
360
  registry: config.registry === undefined ? null : normalizeRegistry(config.registry),
262
361
  fallbackRegistries: config.fallbackRegistries.map(normalizeRegistry),
263
362
  };
363
+ const required = config;
364
+ this.detail = {
365
+ profile: this.profile, maxDocumentBytes: required.detailMaxBytes, maxImageBytes: required.detailImageMaxBytes,
366
+ npmFileSources: required.detailNpmFileSources, timeoutMs: required.detailFetchTimeoutMs, lifetime: this.abort.signal,
367
+ };
264
368
  ctx.effect(() => async () => {
265
369
  this.abort.abort();
266
370
  await Promise.allSettled([...this.packageOperations]);
267
371
  }, 'plugin-manager: package cancellation');
372
+ ctx.inject(['connection'], (scope) => {
373
+ scope.effect(() => scope.connection.fetch.register({
374
+ path: DETAIL_FILE_PATH, methods: ['GET'], requestBody: 'buffered', fetch: request => this.serveDetailFile(request),
375
+ }), `plugin-manager: ${DETAIL_FILE_PATH}`);
376
+ });
377
+ }
378
+ /**
379
+ * Read a bundle's long description: the Markdown file its locale `meta.detail` names in `language`, otherwise its
380
+ * README. An installed bundle is read from its directory without network access; an official bundle the installation
381
+ * offers before it is installed is read from the npm file CDNs at its offered version. Nothing is cached.
382
+ * @param name - the bundle's package name, as `listBundles()` lists it.
383
+ * @param language - the display language, such as `zh-CN`; documents fall back through its prefixes to English.
384
+ * @param options - `npmFileSources` names npm file CDNs to ask first for an offered bundle, in order, such as the one
385
+ * a Client measured as fastest; configured CDNs it omits follow, and CDNs that are not configured are not asked.
386
+ * @returns the document with its origin and path, or `none`.
387
+ * @throws {RemoteError} `plugin-manager/unknown-bundle`, `plugin-manager/invalid-language`, or
388
+ * `plugin-manager/detail-unavailable`.
389
+ */
390
+ async readBundleDetail(name, language, options) {
391
+ return await readBundleDocument(await this.listedBundle(name), language, options?.npmFileSources ?? [], this.detail);
392
+ }
393
+ async listedBundle(name) {
394
+ const bundle = (await this.listBundles()).find(candidate => candidate.name === name);
395
+ if (bundle === undefined)
396
+ throw new RemoteError('plugin-manager/unknown-bundle', `No such bundle: ${name}`, { name });
397
+ return bundle;
398
+ }
399
+ /**
400
+ * Answer `GET ${DETAIL_FILE_PATH}?bundle=<name>&document=<path>&path=<destination>[&sources=<cdn>,...]` with one image
401
+ * beside a bundle document; `sources` names npm file CDNs to ask first for an offered bundle, as `readBundleDetail` does.
402
+ */
403
+ async serveDetailFile(request) {
404
+ const params = new URL(request.url).searchParams;
405
+ const [bundle, document, path] = [params.get('bundle'), params.get('document'), params.get('path')];
406
+ // Images are read again on every request, so a reinstalled bundle shows its own.
407
+ const cache = 'no-store';
408
+ if (bundle === null || document === null || path === null)
409
+ return detailImageResponse('invalid', cache);
410
+ try {
411
+ const image = await readBundleImage(await this.listedBundle(bundle), document, path, params.get('sources')?.split(',') ?? [], this.detail);
412
+ return detailImageResponse(image, cache);
413
+ }
414
+ catch (error) {
415
+ const failure = remoteErrorOf(error);
416
+ if (failure?.code === 'plugin-manager/unknown-bundle')
417
+ return detailImageResponse(undefined, cache);
418
+ if (failure?.code === 'plugin-manager/detail-unavailable')
419
+ return detailImageResponse(failure.details.reason, cache);
420
+ throw error;
421
+ }
268
422
  }
269
423
  /** Read exact plugin-version exemptions saved in this profile.
270
424
  * @returns Accepted package-name@version keys with the runtime versions they may run on, and any
@@ -285,7 +439,7 @@ let PluginManager = (() => {
285
439
  return this.change(result => this.configure(async () => {
286
440
  await setProfileVersionExemption(this.profile.dir, packageVersion, runtimeVersion, enabled, acceptRisk === true);
287
441
  Object.assign(result, await this.reload());
288
- }), { stage: 'enable', target: packageVersion, enabled }, 'bundle');
442
+ }), { stage: 'enable', target: packageVersion, enabled }, 'bundle', exemptionOperationIdentity(packageVersion, runtimeVersion));
289
443
  }
290
444
  /** Read current plugins, including why a row cannot be changed through the profile patch.
291
445
  * @returns Current runtime entries with persistent patch targets.
@@ -297,7 +451,7 @@ let PluginManager = (() => {
297
451
  const actual = [...this.ctx.loader.entries()].find(row => row.id === entry.entryId);
298
452
  const candidates = rows.filter(row => row.id === actual?.options.id);
299
453
  const candidate = candidates[0];
300
- if (protectedModules.has(entry.moduleName) || entry.entryId === this.ownerEntryId) {
454
+ if (PROTECTED_PLUGINS.has(entry.moduleName) || entry.entryId === this.ownerEntryId) {
301
455
  return { ...entry, readOnlyReason: 'management-required' };
302
456
  }
303
457
  if (candidate === undefined || candidates.length > 1 || candidate.name !== entry.moduleName
@@ -313,6 +467,10 @@ let PluginManager = (() => {
313
467
  * display metadata, activation selections, whether the installation offers the bundle, and removal availability.
314
468
  */
315
469
  listBundles() {
470
+ return Promise.resolve(this.readBundles().map(bundle => ({ ...bundle, updatable: typeof updateRefusal(bundle, bundle.name) !== 'string' })));
471
+ }
472
+ /** The bundle inventory before update eligibility, which is derived from each listed bundle. */
473
+ readBundles() {
316
474
  const manifest = readProfileManifest('dsh', this.profile.dir);
317
475
  const exemptions = readProfileVersionExemptions(this.profile.dir);
318
476
  const selected = bundleSelection(manifest);
@@ -342,9 +500,18 @@ let PluginManager = (() => {
342
500
  }
343
501
  const catalogMeta = offered === undefined ? {} : { meta: offered.meta };
344
502
  if (offered !== undefined && !installed && !shipped) {
503
+ let platformError;
504
+ try {
505
+ assertBundlePlatform(offered.platforms, process.platform);
506
+ }
507
+ catch (error) {
508
+ platformError = managementError(error);
509
+ }
510
+ const error = platformError ?? targetError ?? (enabled ? { code: 'not-bundle' } : undefined);
345
511
  bundles.push({ name, official, availability: 'missing', ...catalogMeta, ...target, enabled, installed, optional,
512
+ ...platformError?.code === 'unsupported-platform' ? { listedByDefault: false } : {},
346
513
  removable: enabled, rows: [], overrides: [],
347
- ...targetError !== undefined ? { error: targetError } : enabled ? { error: { code: 'not-bundle' } } : {} });
514
+ ...error === undefined ? {} : { error } });
348
515
  continue;
349
516
  }
350
517
  // Installation-owned copies remain protected even if a profile also declares their names.
@@ -354,6 +521,7 @@ let PluginManager = (() => {
354
521
  const readOnlyReason = this.protectsManager(name) ? 'management-required' : undefined;
355
522
  let availability = 'missing';
356
523
  let version;
524
+ let listing = {};
357
525
  try {
358
526
  const info = bundleManifest(name, this.profile.dir, this.profile.installAnchor);
359
527
  availability = shipped ? 'installation' : 'profile';
@@ -365,29 +533,45 @@ let PluginManager = (() => {
365
533
  continue;
366
534
  }
367
535
  version = info.version;
536
+ const listedByDefault = info.dsh?.bundle?.listedByDefault;
537
+ if (listedByDefault !== undefined) {
538
+ if (typeof listedByDefault !== 'boolean')
539
+ throw new Error('dsh.bundle.listedByDefault must be a boolean');
540
+ listing = { listedByDefault };
541
+ }
368
542
  const compatibility = evaluatePluginCompatibility(info, exemptions);
369
543
  if (compatibility !== undefined && !compatibility.exempted)
370
544
  throw new ManagementFailure('incompatible-version', [incompatiblePlugin(compatibility)]);
371
545
  const dir = resolveBundleDir('dsh', name, this.profile.installAnchor, this.profile.dir);
372
546
  const meta = offered?.meta ?? readPluginMeta(info.name ?? name, pathToFileURL(join(dir, 'package.json')).href);
373
- bundles.push({ name, official, availability, ...target, ...(version === undefined ? {} : { version }),
547
+ let platformError;
548
+ try {
549
+ assertBundlePlatform(info.dsh?.bundle?.platforms, process.platform);
550
+ }
551
+ catch (error) {
552
+ platformError = managementError(error);
553
+ }
554
+ if (platformError?.code === 'unsupported-platform')
555
+ listing = { listedByDefault: false };
556
+ const error = platformError ?? targetError;
557
+ bundles.push({ name, official, availability, ...listing, ...target, ...(version === undefined ? {} : { version }),
374
558
  ...(info.description === undefined || info.description === '' ? {} : { description: info.description }),
375
559
  ...meta === undefined ? {} : { meta },
376
560
  ...sourceOf(info.name), enabled, installed, optional, removable: removable && readOnlyReason === undefined,
377
561
  ...(readOnlyReason === undefined ? {} : { readOnlyReason }),
378
562
  ...this.declaredRows(name, info),
379
- ...targetError === undefined ? {} : { error: targetError } });
563
+ ...error === undefined ? {} : { error } });
380
564
  }
381
565
  catch (error) {
382
566
  if (enabled || installed || optional || offered !== undefined) {
383
- bundles.push({ name, official, availability, ...catalogMeta, ...target, ...(version === undefined ? {} : { version }),
567
+ bundles.push({ name, official, availability, ...listing, ...catalogMeta, ...target, ...(version === undefined ? {} : { version }),
384
568
  ...sourceOf(), enabled, installed, optional, removable: removable && readOnlyReason === undefined,
385
569
  ...(readOnlyReason === undefined ? {} : { readOnlyReason }),
386
570
  error: targetError ?? managementError(error), rows: [], overrides: [] });
387
571
  }
388
572
  }
389
573
  }
390
- return Promise.resolve(bundles);
574
+ return bundles;
391
575
  }
392
576
  /** Read the registries this manager asks: the configured first one, its fallbacks in order, and what pnpm's own configuration names.
393
577
  * @returns The registries in pnpm's comparison form; null is the one pnpm's own configuration names, `resolved` as pnpm reads it now.
@@ -452,51 +636,212 @@ let PluginManager = (() => {
452
636
  case 'registry': {
453
637
  if (known.has(parsed.name))
454
638
  return refused('already-installed', `${parsed.name} is already installed`);
455
- const registries = [];
456
- const refusedBy = (problem, reason) => ({ status: 'refused', problem, reason, registries });
457
- for (const current of plan) {
458
- registries.push(current);
459
- const view = await viewProfilePackage(this.profile.dir, spec.trim(), {
460
- ...this.profile.packageManager ?? { command: this.pnpmCommand },
461
- timeoutMs: this.inspectTimeoutMs, ...signal === undefined ? {} : { signal }, registry: current,
462
- });
463
- const printed = view.stdout.replace(ANSI_SEQUENCE, '').trim();
464
- if (view.exitCode !== 0 || view.cause !== undefined || view.timedOut) {
465
- // pnpm prints a refusal as `{ error: { code, message } }` on stdout, with nothing on stderr.
466
- const log = [view.stderr.trim(), printedError(printed), view.cause === undefined ? '' : messageOf(view.cause)].filter(Boolean).join('\n');
467
- const kind = classifyInstallFailure({ log, timedOut: view.timedOut, ...view.cause === undefined ? {} : { cause: view.cause } });
468
- // A lookup the caller dropped is not carried to the next registry.
469
- if (registries.length < plan.length && signal?.aborted !== true && attributeFailure(kind, log, parsed) === 'registry')
470
- continue;
471
- const reason = view.timedOut ? `pnpm view timed out after ${String(this.inspectTimeoutMs)}ms` : log || printed || `pnpm view exited with ${String(view.exitCode)}`;
472
- if (kind === 'not-found' || kind === 'no-matching-version')
473
- return refusedBy('not-found', reason);
474
- if (kind === 'network' || kind === 'timeout')
475
- return refusedBy('network', reason);
476
- return refusedBy('unknown', reason);
477
- }
478
- let answer;
479
- try {
480
- answer = JSON.parse(printed || 'null');
481
- }
482
- catch (error) {
483
- return refusedBy('unknown', `unreadable pnpm view output: ${messageOf(error)}`);
484
- }
485
- // A range answers one object per matching version, oldest first.
486
- const latest = Array.isArray(answer) ? answer.at(-1) : answer;
487
- if (typeof latest !== 'object' || latest === null)
488
- return refusedBy('unknown', 'pnpm view answered no package');
489
- const inspection = inspectionOf('registry', latest, current);
490
- const named = inspection.name === undefined ? { ...inspection, name: parsed.name } : inspection;
491
- if (!named.bundle)
492
- return refusedBy('not-a-bundle', `${named.name} declares no dsh.bundle`);
493
- return named;
494
- }
495
- /* v8 ignore next -- the plan is never empty: every attempt returns or continues to the next */
496
- throw new Error('no registry was asked');
639
+ const asked = await this.askRegistries(spec.trim(), INSPECT_FIELDS, plan, parsed, signal);
640
+ const registries = asked.attempts.map(attempt => attempt.registry);
641
+ if (asked.status === 'refused')
642
+ return { status: 'refused', problem: asked.problem, reason: asked.reason, registries };
643
+ // pnpm prints a range's highest match as one object; npm's array of every match is read by its last entry.
644
+ const latest = Array.isArray(asked.answer) ? asked.answer.at(-1) : asked.answer;
645
+ if (typeof latest !== 'object' || latest === null)
646
+ return { status: 'refused', problem: 'unknown', reason: 'pnpm view answered no package', registries };
647
+ const inspection = inspectionOf('registry', latest, asked.registry);
648
+ const named = inspection.name === undefined ? { ...inspection, name: parsed.name } : inspection;
649
+ if (!named.bundle)
650
+ return { status: 'refused', problem: 'not-a-bundle', reason: `${named.name} declares no dsh.bundle`, registries };
651
+ return named;
497
652
  }
498
653
  }
499
654
  }
655
+ /** Read the published versions newer than an installed registry package's version, from the first registry that answers.
656
+ * Official bundles follow the DSH version and are not listed.
657
+ * @param name Installed profile dependency name.
658
+ * @param options The registry asked first; absent, the one the package was installed from in this process, else the configured one.
659
+ * @param signal Ends the lookups early.
660
+ * @returns At most `versionListLimit` newer versions, newest first, with their tags, deprecation, bundle declaration,
661
+ * and DSH compatibility, and the registry that answered; or why no list could be read, with every registry asked.
662
+ */
663
+ async listVersions(name, options, signal) {
664
+ const target = updateRefusal((await this.listBundles()).find(bundle => bundle.name === name), name);
665
+ if (typeof target === 'string')
666
+ return { status: 'refused', problem: 'not-updatable', reason: target, attempts: [] };
667
+ const plan = registryPlan(this.registryFor(name, options?.registry), await this.registries());
668
+ const listing = await this.askRegistries(name, VERSION_LIST_FIELDS, plan, target.parsed, signal);
669
+ if (listing.status === 'refused')
670
+ return listing;
671
+ let newer;
672
+ try {
673
+ newer = newerVersions(listing.answer, target.installed);
674
+ }
675
+ catch (error) {
676
+ return { status: 'refused', problem: 'unknown', reason: messageOf(error), attempts: listing.attempts };
677
+ }
678
+ const listed = newer.slice(0, this.versionListLimit);
679
+ const exemptions = readProfileVersionExemptions(this.profile.dir);
680
+ const looked = await mapConcurrent(listed, this.versionLookupConcurrency, async (published) => {
681
+ const spec = `${name}@${published.version}`;
682
+ const answer = await this.askRegistries(spec, VERSION_FIELDS, [listing.registry], { kind: 'registry', spec, name }, signal);
683
+ if (answer.status === 'refused')
684
+ return answer;
685
+ const facts = versionFacts(answer.answer, name, published.version);
686
+ let compatibility;
687
+ try {
688
+ compatibility = evaluatePluginCompatibility(facts.manifest, exemptions);
689
+ }
690
+ catch (error) {
691
+ return { status: 'refused', problem: 'unknown', reason: messageOf(error), attempts: answer.attempts };
692
+ }
693
+ const version = {
694
+ ...published, bundle: facts.bundle, ...facts.deprecated === undefined ? {} : { deprecated: facts.deprecated },
695
+ ...compatibility === undefined || compatibility.exempted ? {} : { incompatible: incompatiblePlugin(compatibility) },
696
+ };
697
+ return { status: 'read', version };
698
+ }, answer => answer.status === 'refused');
699
+ const versions = [];
700
+ for (const answer of looked) {
701
+ /* v8 ignore next -- a lookup stops the rest only by refusing, which returns below */
702
+ if (answer === undefined)
703
+ continue;
704
+ if (answer.status === 'refused')
705
+ return { ...answer, attempts: [...listing.attempts.slice(0, -1), ...answer.attempts] };
706
+ versions.push(answer.version);
707
+ }
708
+ return {
709
+ status: 'listed', installed: target.installed, registry: listing.registry, attempts: listing.attempts,
710
+ versions, omitted: newer.length - listed.length,
711
+ };
712
+ }
713
+ /**
714
+ * Replace an installed registry bundle with a newer published version. The target is checked on the registry first:
715
+ * it must exist, declare a bundle, and accept the running DSH version, or nothing changes. With HMR the installed
716
+ * version is removed, so its plugins stop, and the target is installed with the same selection; when that
717
+ * installation fails or is cancelled, the removed version is installed again from the registry it came from.
718
+ * Without HMR the target is installed over the running version and the result reports the restart.
719
+ * @param name Installed profile dependency name.
720
+ * @param version Exact published version newer than the installed one.
721
+ * @param options The registry asked first, as for `listVersions`, and the request id naming the progress and the
722
+ * target installation's logs and cancellation.
723
+ * @returns The versions, the last step that ran with its result, and the reinstallation when one ran.
724
+ */
725
+ async updateBundle(name, version, options) {
726
+ const requestId = options?.requestId;
727
+ const announce = (step) => {
728
+ if (requestId !== undefined)
729
+ this.ownerContext.emit('plugin-manager/update-state', { requestId, step });
730
+ };
731
+ announce('checking');
732
+ const target = updateRefusal((await this.listBundles()).find(item => item.name === name), name);
733
+ const from = typeof target === 'string' ? '' : target.installed;
734
+ const refusedBefore = (error) => ({
735
+ from, to: version, step: 'check',
736
+ result: { changed: false, application: 'failed', stage: 'install', target: name, error },
737
+ });
738
+ if (typeof target === 'string')
739
+ return refusedBefore({ code: 'invalid-spec', diagnostic: target });
740
+ const { bundle } = target;
741
+ if (semver.valid(version) === null || !semver.gt(version, from)) {
742
+ return refusedBefore({ code: 'invalid-spec', diagnostic: `${version} is not a version newer than the installed ${from}` });
743
+ }
744
+ const spec = `${name}@${version}`;
745
+ const plan = registryPlan(this.registryFor(name, options?.registry), await this.registries());
746
+ const checked = await this.askRegistries(spec, VERSION_FIELDS, plan, { kind: 'registry', spec, name });
747
+ if (checked.status === 'refused')
748
+ return refusedBefore({ code: 'operation-error', diagnostic: checked.reason });
749
+ const facts = versionFacts(checked.answer, name, version);
750
+ if (!facts.bundle)
751
+ return refusedBefore({ code: 'not-bundle' });
752
+ let compatibility;
753
+ try {
754
+ compatibility = evaluatePluginCompatibility(facts.manifest, readProfileVersionExemptions(this.profile.dir));
755
+ }
756
+ catch (error) {
757
+ return refusedBefore({ code: 'operation-error', diagnostic: messageOf(error) });
758
+ }
759
+ if (compatibility !== undefined && !compatibility.exempted) {
760
+ return refusedBefore({ code: 'incompatible-version', incompatible: [incompatiblePlugin(compatibility)] });
761
+ }
762
+ const { enabled } = bundle;
763
+ // A lock timeout or disposal rejects instead of reporting; it reads as the failed step it is.
764
+ const settled = (stage, target, operation) => operation.catch((error) => ({ changed: false, application: 'failed', stage, target, error: managementError(error) }));
765
+ const installTarget = () => settled('install', spec, this.installBundle(spec, {
766
+ saveExact: true, registry: checked.registry, enabled, ...requestId === undefined ? {} : { requestId },
767
+ }));
768
+ if (this.ownerContext.get('hmr') === undefined) {
769
+ announce('installing');
770
+ return { from, to: version, step: 'install', result: await installTarget() };
771
+ }
772
+ // The removed version is installed again where it came from, else over the configured plan, as its removal asks.
773
+ const previousRegistry = this.installedFrom.get(name);
774
+ announce('removing');
775
+ const removal = await settled('remove', name, this.removeBundle(name));
776
+ if (removal.application === 'failed' || removal.application === 'cancelled')
777
+ return { from, to: version, step: 'remove', result: removal };
778
+ announce('installing');
779
+ const result = await installTarget();
780
+ if (result.application !== 'failed' && result.application !== 'cancelled')
781
+ return { from, to: version, step: 'install', result };
782
+ announce('restoring');
783
+ // A target that installed but failed to start is still a dependency; it goes before the removed version returns.
784
+ if (result.stage === 'enable')
785
+ await settled('remove', name, this.removeBundle(name));
786
+ // The reinstallation carries no request id, so cancelling the update cannot leave the package removed.
787
+ const previous = `${name}@${from}`;
788
+ const restore = await settled('install', previous, this.installBundle(previous, {
789
+ saveExact: true, enabled, ...previousRegistry === undefined ? {} : { registry: previousRegistry },
790
+ }));
791
+ return { from, to: version, step: 'install', result, restore };
792
+ }
793
+ /**
794
+ * The registry a version listing or an update asks first.
795
+ * @param name The package name.
796
+ * @param requested The caller's registry, when it named one.
797
+ * @returns The requested registry, else the one this process last installed the package from, else undefined for the configured one.
798
+ */
799
+ registryFor(name, requested) {
800
+ return requested !== undefined ? requested : this.installedFrom.get(name);
801
+ }
802
+ /**
803
+ * Ask registries in turn through `pnpm view`, moving to the next one while a failure is the registry's: unreachable,
804
+ * timed out, or without the package or version, which a mirror not yet synced reports.
805
+ * @param spec The registry spec viewed.
806
+ * @param fields The manifest fields printed.
807
+ * @param plan The registries, in order; never empty.
808
+ * @param parsed The spec's form, which decides whether a failure was the registry's.
809
+ * @param signal Ends the lookup; a dropped lookup is not carried to the next registry.
810
+ * @returns The parsed answer and the registry that gave it, or the last refusal, with every registry asked.
811
+ */
812
+ async askRegistries(spec, fields, plan, parsed, signal) {
813
+ const attempts = [];
814
+ for (const [index, registry] of plan.entries()) {
815
+ const view = await viewProfilePackage(this.profile.dir, spec, {
816
+ ...this.profile.packageManager ?? { command: this.pnpmCommand },
817
+ fields, timeoutMs: this.inspectTimeoutMs, ...signal === undefined ? {} : { signal }, registry,
818
+ });
819
+ const printed = view.stdout.replace(ANSI_SEQUENCE, '').trim();
820
+ if (view.exitCode !== 0 || view.cause !== undefined || view.timedOut) {
821
+ // pnpm prints a refusal as `{ error: { code, message } }` on stdout, with nothing on stderr.
822
+ const log = [view.stderr.trim(), printedError(printed), view.cause === undefined ? '' : messageOf(view.cause)].filter(Boolean).join('\n');
823
+ const kind = classifyInstallFailure({ log, timedOut: view.timedOut, ...view.cause === undefined ? {} : { cause: view.cause } });
824
+ const reason = view.timedOut ? `pnpm view timed out after ${String(this.inspectTimeoutMs)}ms` : log || printed || `pnpm view exited with ${String(view.exitCode)}`;
825
+ const problem = kind === 'not-found' || kind === 'no-matching-version' ? 'not-found' : kind === 'network' || kind === 'timeout' ? 'network' : 'unknown';
826
+ attempts.push({ registry, problem, reason });
827
+ if (index < plan.length - 1 && signal?.aborted !== true && attributeFailure(kind, log, parsed) === 'registry')
828
+ continue;
829
+ return { status: 'refused', problem, reason, attempts };
830
+ }
831
+ try {
832
+ const answer = JSON.parse(printed || 'null');
833
+ attempts.push({ registry });
834
+ return { status: 'answered', answer, registry, attempts };
835
+ }
836
+ catch (error) {
837
+ const reason = `unreadable pnpm view output: ${messageOf(error)}`;
838
+ attempts.push({ registry, problem: 'unknown', reason });
839
+ return { status: 'refused', problem: 'unknown', reason, attempts };
840
+ }
841
+ }
842
+ /* v8 ignore next -- the plan is never empty: every attempt returns or continues to the next */
843
+ throw new Error('no registry was asked');
844
+ }
500
845
  /** Persist a plugin entry's desired enablement and apply it on live profiles.
501
846
  * @param id Loader entry identity returned by listPlugins.
502
847
  * @param enabled Whether the plugin should run.
@@ -529,7 +874,9 @@ let PluginManager = (() => {
529
874
  /**
530
875
  * Install a package using the same pnpm implementation as dsh plugin. GitHub
531
876
  * repositories get a connection check bounded by githubConnectionTimeoutMs before pnpm starts;
532
- * only network failures or timeouts stop installation, while pnpm owns authentication and transport fallback. A run
877
+ * only network failures or timeouts stop installation, while pnpm owns authentication and transport fallback. An
878
+ * HTTP(S) Git URL on another host is installed over SSH instead when access probes bounded by gitTransportTimeoutMs
879
+ * find that only SSH can read it. A run
533
880
  * that fails, is cancelled, or adds a package without a bundle patch restores
534
881
  * `package.json` and `pnpm-lock.yaml` as they were; downloaded files can stay.
535
882
  * @param spec One package spec, including local paths relative to the invocation directory.
@@ -567,10 +914,11 @@ let PluginManager = (() => {
567
914
  let version;
568
915
  try {
569
916
  result.registries = [];
570
- const connection = checkGithubConnection(parsedForRegistry(spec), this.profile.dir, {
571
- timeoutMs: this.githubConnectionTimeoutMs, outputBytes: this.outputBytes,
572
- signal: AbortSignal.any([this.abort.signal, control.abort.signal]),
573
- ...this.profile.packageManager?.env === undefined ? {} : { env: this.profile.packageManager.env },
917
+ const parsed = parsedForRegistry(spec);
918
+ const signal = AbortSignal.any([this.abort.signal, control.abort.signal]);
919
+ const env = this.profile.packageManager?.env === undefined ? {} : { env: this.profile.packageManager.env };
920
+ const connection = checkGithubConnection(parsed, this.profile.dir, {
921
+ timeoutMs: this.githubConnectionTimeoutMs, outputBytes: this.outputBytes, signal, ...env,
574
922
  });
575
923
  this.packageOperations.add(connection);
576
924
  let connectionFailure;
@@ -587,6 +935,17 @@ let PluginManager = (() => {
587
935
  result.failedAt = 'spec-host';
588
936
  throw new Error(connectionFailure.output);
589
937
  }
938
+ const transport = chooseGitTransport(parsed, this.profile.dir, { timeoutMs: this.gitTransportTimeoutMs, signal, ...env });
939
+ this.packageOperations.add(transport);
940
+ let installSpec;
941
+ try {
942
+ installSpec = await transport;
943
+ }
944
+ finally {
945
+ this.packageOperations.delete(transport);
946
+ }
947
+ if (stopped())
948
+ throw new InstallCancelledError();
590
949
  // The last run is the result's; the registries asked stay listed whatever the outcome.
591
950
  const plan = registryPlan(options?.registry, await this.registries());
592
951
  let run;
@@ -600,7 +959,7 @@ let PluginManager = (() => {
600
959
  result.registries.push(registry);
601
960
  used = registry;
602
961
  announce('installing', { registry, index: index + 1, total: plan.length });
603
- run = await this.runPnpm(['add', spec, ...options?.saveExact === true ? ['--save-exact'] : [], ...registryArguments(registry)], control.abort.signal, requestId);
962
+ run = await this.runPnpm(['add', installSpec, ...options?.saveExact === true ? ['--save-exact'] : [], ...registryArguments(registry)], control.abort.signal, requestId);
604
963
  result.packageResult = run;
605
964
  if (stopped())
606
965
  throw new InstallCancelledError();
@@ -618,7 +977,7 @@ let PluginManager = (() => {
618
977
  // A run this manager terminated got no answer from the registry at all, so no registry explains it.
619
978
  if (run.timedOut === true)
620
979
  break;
621
- const failedAt = attributeFailure(run.kind, run.output, parsedForRegistry(spec));
980
+ const failedAt = attributeFailure(run.kind, run.output, parsedForRegistry(installSpec));
622
981
  if (failedAt !== 'other')
623
982
  result.failedAt = failedAt;
624
983
  if (failedAt !== 'registry' || index === plan.length - 1)
@@ -632,7 +991,7 @@ let PluginManager = (() => {
632
991
  if (succeeded)
633
992
  delete result.failedAt;
634
993
  if (!succeeded) {
635
- // pnpm-workspace.yaml is not restored, so the names it left undecided, or reported as ignored, are offered for approval.
994
+ // pnpm-workspace.yaml is not restored, so the names it left undecided, or reported as blocked, are offered for approval.
636
995
  try {
637
996
  result.pendingBuilds = await recordPendingBuilds(this.profile.dir, run.output);
638
997
  }
@@ -854,6 +1213,7 @@ let PluginManager = (() => {
854
1213
  if (metadata === undefined)
855
1214
  throw new ManagementFailure('not-bundle');
856
1215
  if (enabled) {
1216
+ assertBundlePlatform(metadata.dsh?.bundle?.platforms, process.platform);
857
1217
  const compatibility = evaluatePluginCompatibility(metadata, readProfileVersionExemptions(this.profile.dir));
858
1218
  if (compatibility !== undefined && !compatibility.exempted)
859
1219
  throw new ManagementFailure('incompatible-version', [incompatiblePlugin(compatibility)]);
@@ -890,7 +1250,7 @@ let PluginManager = (() => {
890
1250
  // Unreadable bundles contribute no new rows; listBundles reports their diagnostics.
891
1251
  return false;
892
1252
  }
893
- const protectedBundle = rows.some(row => protectedModules.has(row.name) || `include:${row.id}` === this.ownerEntryId);
1253
+ const protectedBundle = rows.some(row => PROTECTED_PLUGINS.has(row.name) || `include:${row.id}` === this.ownerEntryId);
894
1254
  if (protectedBundle)
895
1255
  this.managementBundles.add(name);
896
1256
  return protectedBundle;
@@ -945,35 +1305,92 @@ let PluginManager = (() => {
945
1305
  const restart = restartReason ?? pending[0]?.reason;
946
1306
  return restart === undefined ? { warnings } : { warnings, restartReason: restart };
947
1307
  }
948
- async change(operation, request, reason) {
949
- return withFileLock(join(this.profile.dir, 'package.json'), async () => {
950
- this.abort.signal.throwIfAborted();
951
- const before = this.diskState();
952
- const result = { ...request, changed: false,
953
- ...this.ownerContext.get('hmr') !== undefined ? { application: 'applied' } : { application: 'restart-required', restartReason: 'no-hmr' } };
954
- try {
955
- const outcome = await operation(result);
956
- if (outcome !== undefined)
957
- result.application = outcome;
958
- // A reload that waits for a restart leaves the change saved but not applied.
959
- else if (result.application === 'applied' && result.restartReason !== undefined)
960
- result.application = 'restart-required';
961
- }
962
- catch (error) {
963
- if (error instanceof InstallCancelledError) {
964
- result.application = 'cancelled';
1308
+ async change(operation, request, reason, identity) {
1309
+ const id = randomUUID();
1310
+ const target = identity === undefined ? this.operationTarget(reason, request.target) : identity.target;
1311
+ const version = identity === undefined ? this.operationVersion(reason, reason === 'plugin' ? request.target : target) : identity.version;
1312
+ const facts = { id, reason, stage: request.stage,
1313
+ target,
1314
+ ...version === undefined ? {} : { version },
1315
+ ...request.enabled === undefined ? {} : { enabled: request.enabled } };
1316
+ this.reportOperation({ ...facts, time: new Date().toISOString(), phase: 'started' });
1317
+ let settled;
1318
+ try {
1319
+ settled = await withFileLock(join(this.profile.dir, 'package.json'), async () => {
1320
+ this.abort.signal.throwIfAborted();
1321
+ const before = this.diskState();
1322
+ const result = { ...request, changed: false,
1323
+ ...this.ownerContext.get('hmr') !== undefined ? { application: 'applied' } : { application: 'restart-required', restartReason: 'no-hmr' } };
1324
+ try {
1325
+ const outcome = await operation(result);
1326
+ if (outcome !== undefined)
1327
+ result.application = outcome;
1328
+ // A reload that waits for a restart leaves the change saved but not applied.
1329
+ else if (result.application === 'applied' && result.restartReason !== undefined)
1330
+ result.application = 'restart-required';
965
1331
  }
966
- else {
967
- result.application = 'failed';
968
- result.error = managementError(error);
1332
+ catch (error) {
1333
+ if (error instanceof InstallCancelledError) {
1334
+ result.application = 'cancelled';
1335
+ }
1336
+ else {
1337
+ result.application = 'failed';
1338
+ result.error = managementError(error);
1339
+ }
969
1340
  }
970
- }
971
- if (result.application !== 'restart-required')
972
- delete result.restartReason;
973
- result.changed = before !== this.diskState();
974
- this.ownerContext.emit('plugin-manager/changed', { reason });
975
- return result;
976
- }, { waitMs: this.lockWaitMs });
1341
+ if (result.application !== 'restart-required')
1342
+ delete result.restartReason;
1343
+ result.changed = before !== this.diskState();
1344
+ this.ownerContext.emit('plugin-manager/changed', { reason });
1345
+ return result;
1346
+ }, { waitMs: this.lockWaitMs });
1347
+ }
1348
+ catch (error) {
1349
+ this.reportOperation({ ...facts, time: new Date().toISOString(), phase: 'unknown' });
1350
+ throw error;
1351
+ }
1352
+ const refusedVersion = reason === 'install'
1353
+ ? settled.error?.incompatible?.find(plugin => plugin.name === facts.target)?.version
1354
+ : undefined;
1355
+ const observedVersion = diagnosticVersion(settled.version ?? refusedVersion);
1356
+ this.reportOperation({ ...facts, time: new Date().toISOString(), phase: 'settled',
1357
+ stage: settled.stage, target: settled.bundle === undefined ? facts.target : installOperationTarget(settled.bundle),
1358
+ application: settled.application, changed: settled.changed,
1359
+ ...observedVersion === undefined ? {} : { version: observedVersion },
1360
+ ...settled.error === undefined ? {} : { errorCode: settled.error.code },
1361
+ ...settled.restartReason === undefined ? {} : { restartReason: settled.restartReason } });
1362
+ return settled;
1363
+ }
1364
+ reportOperation(operation) {
1365
+ void this.ownerContext.parallel('plugin-manager/operation', operation).catch((_error) => {
1366
+ // All subscribers run; diagnostic failures cannot change the management result.
1367
+ console.error('dsh plugin-manager: operation diagnostic delivery failed');
1368
+ });
1369
+ }
1370
+ operationTarget(reason, target) {
1371
+ if (reason !== 'plugin') {
1372
+ const name = installOperationTarget(target);
1373
+ return reason === 'install' || name === target ? name : null;
1374
+ }
1375
+ return target.length <= 256 && [...this.ctx.loader.entries()].some(entry => entry.id === target) ? target : null;
1376
+ }
1377
+ /** Read the request-time package version without preventing recovery from damaged metadata. */
1378
+ operationVersion(reason, target) {
1379
+ if (reason === 'install' || target === null)
1380
+ return undefined;
1381
+ try {
1382
+ if (reason !== 'plugin')
1383
+ return diagnosticVersion(bundleManifest(target, this.profile.dir, this.profile.installAnchor)?.version);
1384
+ const entry = [...this.ctx.loader.entries()].find(row => row.id === target);
1385
+ const source = entry?.parent.tree.ctx.baseUrl;
1386
+ if (entry === undefined || source === undefined)
1387
+ return undefined;
1388
+ return diagnosticVersion(this.ownerContext.get('pluginPackages')?.packageOf(entry.options.name, source)?.version);
1389
+ }
1390
+ catch (_error) {
1391
+ // Disabling or removing a broken package must not depend on diagnostic metadata being readable.
1392
+ return undefined;
1393
+ }
977
1394
  }
978
1395
  diskState() {
979
1396
  return ['package.json', 'cordis.patch.yml', 'pnpm-workspace.yaml', PROFILE_COMPATIBILITY_FILENAME].map((file) => {