@deepseek-ai/dsh-plugin-manager 0.2.2-rc.1 → 0.2.2-rc.3

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 (70) hide show
  1. package/README.i18n.yaml +4 -4
  2. package/README.md +6 -5
  3. package/README.zh.md +6 -5
  4. package/lib/index.js +255 -68
  5. package/lib/typert.host.js +84 -66
  6. package/lib/typert.remote-client.d.ts.map +1 -0
  7. package/lib/typert.remote-client.js +77 -59
  8. package/lib/types/build-approval.d.ts.map +1 -0
  9. package/lib/types/build-approval.js.map +1 -0
  10. package/lib/types/bundle-detail.d.ts.map +1 -0
  11. package/lib/types/bundle-detail.js.map +1 -0
  12. package/lib/types/diagnostic.d.ts.map +1 -0
  13. package/lib/types/diagnostic.js +1 -0
  14. package/lib/types/diagnostic.js.map +1 -0
  15. package/lib/types/failure.d.ts.map +1 -0
  16. package/lib/types/failure.js.map +1 -0
  17. package/lib/types/git-transport.d.ts.map +1 -0
  18. package/lib/types/git-transport.js.map +1 -0
  19. package/lib/types/github-connection.d.ts +16 -5
  20. package/lib/types/github-connection.d.ts.map +1 -0
  21. package/lib/types/github-connection.js +18 -8
  22. package/lib/types/github-connection.js.map +1 -0
  23. package/lib/types/index.d.ts +39 -10
  24. package/lib/types/index.d.ts.map +1 -0
  25. package/lib/types/index.js +144 -46
  26. package/lib/types/index.js.map +1 -0
  27. package/lib/types/install-failure.d.ts.map +1 -0
  28. package/lib/types/install-failure.js.map +1 -0
  29. package/lib/types/install-spec.d.ts +13 -1
  30. package/lib/types/install-spec.d.ts.map +1 -0
  31. package/lib/types/install-spec.js +41 -1
  32. package/lib/types/install-spec.js.map +1 -0
  33. package/lib/types/official-install-target.d.ts.map +1 -0
  34. package/lib/types/official-install-target.js.map +1 -0
  35. package/lib/types/operations.d.ts +16 -4
  36. package/lib/types/operations.d.ts.map +1 -0
  37. package/lib/types/operations.js +38 -5
  38. package/lib/types/operations.js.map +1 -0
  39. package/lib/types/patch.d.ts.map +1 -0
  40. package/lib/types/patch.js.map +1 -0
  41. package/lib/types/registry.d.ts.map +1 -0
  42. package/lib/types/registry.js.map +1 -0
  43. package/lib/types/run-tree.d.ts.map +1 -0
  44. package/lib/types/run-tree.js.map +1 -0
  45. package/lib/types/tools.d.ts.map +1 -0
  46. package/lib/types/tools.js +2 -1
  47. package/lib/types/tools.js.map +1 -0
  48. package/lib/types/types.d.ts +31 -5
  49. package/lib/types/types.d.ts.map +1 -0
  50. package/lib/types/types.js.map +1 -0
  51. package/lib/types/versions.d.ts.map +1 -0
  52. package/lib/types/versions.js.map +1 -0
  53. package/package.json +39 -35
  54. package/src/build-approval.ts +96 -0
  55. package/src/bundle-detail.ts +104 -0
  56. package/src/diagnostic.ts +86 -0
  57. package/src/failure.ts +29 -0
  58. package/src/git-transport.ts +72 -0
  59. package/src/github-connection.ts +102 -0
  60. package/src/index.ts +1458 -0
  61. package/src/install-failure.ts +44 -0
  62. package/src/install-spec.ts +159 -0
  63. package/src/official-install-target.ts +58 -0
  64. package/src/operations.ts +695 -0
  65. package/src/patch.ts +78 -0
  66. package/src/registry.ts +98 -0
  67. package/src/run-tree.ts +77 -0
  68. package/src/tools.ts +164 -0
  69. package/src/types.ts +477 -0
  70. package/src/versions.ts +80 -0
package/src/index.ts ADDED
@@ -0,0 +1,1458 @@
1
+ /** Current-profile plugin and bundle management over shared dsh plugin operations. */
2
+ import { randomUUID } from 'node:crypto'
3
+ import { existsSync, readFileSync } from 'node:fs'
4
+ import { readFile, rm } from 'node:fs/promises'
5
+ import { join } from 'node:path'
6
+ import { pathToFileURL } from 'node:url'
7
+ import { withFileLock, writeFileAtomic } from '@deepseek-ai/dsh-atomic-write'
8
+ import { Context } from '@deepseek-ai/cordis'
9
+ import type { EntryOptions } from '@deepseek-ai/cordis-plugin-loader'
10
+ import type { PatchOptions } from '@deepseek-ai/cordis-plugin-include'
11
+ import z from '@deepseek-ai/schemastery'
12
+ import semver from 'semver'
13
+ import { TypertRemoteService, Remote, RemoteError, remoteErrorOf } from '@deepseek-ai/dsh-typert-protocol'
14
+ import { detailImageResponse, NPM_FILE_SOURCES } from '@deepseek-ai/dsh-plugin-detail'
15
+ import type { NpmFileSource } from '@deepseek-ai/dsh-plugin-detail/types'
16
+ import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout'
17
+ import type {} from '@deepseek-ai/dsh-client-connection'
18
+ import { readBundleDocument, readBundleImage, type BundleDetailOptions } from './bundle-detail.ts'
19
+ import { pluginEntryId, readPluginInventory } from '@deepseek-ai/dsh-host-plugin-inventory'
20
+ import {
21
+ readPluginMeta, readProfileManifest, resolveBundleDir, loadOverlayPatches, composeEntries,
22
+ readProfilePatches, bundlePatchPaths,
23
+ evaluatePluginCompatibility, readProfileCompatibility, readProfileVersionExemptions,
24
+ setProfileVersionExemption, validatePluginVersionExemption, PROFILE_COMPATIBILITY_FILENAME,
25
+ getDshRuntimeVersion, ResolutionRestartRequired,
26
+ assertBundlePlatform, UnsupportedBundlePlatformError,
27
+ } from '@deepseek-ai/dsh-app-boot'
28
+ import { OPTIONAL_BUNDLES, OFFICIAL_ON_DEMAND_CATALOG, PROTECTED_PLUGINS } from '@deepseek-ai/dsh-official-bundles'
29
+ import type {} from '@deepseek-ai/dsh-hmr'
30
+ import type { ProfileContext, ProfileManifest } from '@deepseek-ai/dsh-app-boot'
31
+ import { bundleManifest, readProfileRegistry, registryArguments, runProfilePnpm, saveManifest, viewProfilePackage } from './operations.ts'
32
+ import { classifyInstallFailure } from './install-failure.ts'
33
+ import { officialBundleInstallTarget } from './official-install-target.ts'
34
+ import { dependencySpec, InvalidInstallSpecError, parseInstallSpec, pinnedGitOrigin, type ParsedInstallSpec } from './install-spec.ts'
35
+ import { attributeFailure, normalizeRegistry, NPMMIRROR_REGISTRY, registryPlan } from './registry.ts'
36
+ import { flatten, writePluginEnabled } from './patch.ts'
37
+ import { incompatiblePlugin, ManagementFailure } from './failure.ts'
38
+ import { approveBuilds, recordPendingBuilds } from './build-approval.ts'
39
+ import { checkGitConnection, checkGithubConnection, type GithubConnectionFailure } from './github-connection.ts'
40
+ import { chooseGitTransport, sshGitSpec } from './git-transport.ts'
41
+ import { newerVersions, VERSION_FIELDS, VERSION_LIST_FIELDS, versionFacts } from './versions.ts'
42
+ import type {
43
+ BundleDetail, BundleInfo, BundleRowInfo, ChangeResult, InspectOptions, InstallBundleOptions, ListVersionsOptions, ManagementError,
44
+ PackageResult, PluginChange, PluginEntryId, PluginInfo, PluginInstallCancellation, PluginInstallProgress, PluginInstallRequestId,
45
+ PluginRegistries, PluginSpecInspection, PluginUpdateResult, PluginUpdateStep, PluginVersion, PluginVersionList, Registry,
46
+ RegistryAttempt, UpdateBundleOptions,
47
+ PluginOperation, PluginOperationId,
48
+ } from './types.ts'
49
+ export type * from './types.ts'
50
+ export { classifyInstallFailure, type InstallFailureFacts } from './install-failure.ts'
51
+ export { InvalidInstallSpecError, parseInstallSpec, pinnedGitOrigin, type ParsedInstallSpec } from './install-spec.ts'
52
+
53
+ /** The pnpm executable, registries, and limits for diagnostics, lookups and connection checks. */
54
+ export interface Config {
55
+ /** The pnpm executable name or path; resolved through `PATH` like the `dsh plugin` command. */
56
+ pnpmCommand?: string
57
+ /** Maximum retained package-operation diagnostic bytes. */
58
+ outputBytes?: number
59
+ /** Maximum time to wait for another process's profile package operation. */
60
+ lockWaitMs?: number
61
+ /** Bound on one registry lookup an inspection runs, in milliseconds. */
62
+ inspectTimeoutMs?: number
63
+ /** Maximum duration of the GitHub repository connection check before installation, in milliseconds. */
64
+ githubConnectionTimeoutMs?: number
65
+ /** Maximum duration of each HTTP(S) and SSH access probe of a self-hosted Git repository before installation, in milliseconds. */
66
+ gitTransportTimeoutMs?: number
67
+ /** Maximum time one captured package run may print nothing before the manager terminates it, in milliseconds. */
68
+ idleTimeoutMs?: number
69
+ /** The registry lookups and installations ask first, as an http(s) URL; absent, the one pnpm's own configuration names. */
70
+ registry?: string
71
+ /**
72
+ * Registries asked in turn, as http(s) URLs, while the one before is unreachable or holds no copy of the package.
73
+ * A registry outside this set and `registry` is asked alone, and so is the one pnpm's own configuration names
74
+ * unless that is npm's own registry or one of these.
75
+ */
76
+ fallbackRegistries?: string[]
77
+ /** How many of the newest versions above the installed one a version listing reads and returns. */
78
+ versionListLimit?: number
79
+ /** How many single-version registry lookups a version listing runs at once. */
80
+ versionLookupConcurrency?: number
81
+ /** Largest bundle detail document, and largest locale file read for one, in bytes. */
82
+ detailMaxBytes?: number
83
+ /** Largest image served beside a bundle detail document, in bytes. */
84
+ detailImageMaxBytes?: number
85
+ /** Deadline of one npm file CDN request for an offered bundle's detail document. */
86
+ detailFetchTimeoutMs?: number
87
+ /** npm file CDNs that offered bundles are read from, in order; a read's `npmFileSources` moves the CDNs it names first. */
88
+ detailNpmFileSources?: NpmFileSource[]
89
+ }
90
+
91
+ /** The Fetch route serving images beside bundle detail documents. */
92
+ const DETAIL_FILE_PATH = '/api/plugin-manager/detail-file'
93
+
94
+ /** An http(s) URL, as pnpm's `--registry` takes it. */
95
+ const REGISTRY_URL = /^https?:\/\/\S+$/
96
+
97
+ /** The profile files an installation writes and a failed or cancelled one restores. */
98
+ const RESTORED_FILES = ['package.json', 'pnpm-lock.yaml'] as const
99
+
100
+ /** The manifest fields an inspection reads for a registry spec. */
101
+ const INSPECT_FIELDS = ['name', 'version', 'description', 'dsh'] as const
102
+
103
+ /** pnpm's colour escapes, which a JSON answer may be wrapped in. */
104
+ const ANSI_SEQUENCE = /\x1b\[[0-9;]*m/g
105
+
106
+ /** Preserve the exact observed diagnostic, including non-Error failures. */
107
+ function messageOf(error: unknown): string { return error instanceof Error ? error.message : String(error) }
108
+
109
+ /** An expected refusal keeps its code; anything else becomes an operation error carrying its exact diagnostic. */
110
+ function managementError(error: unknown): ManagementError {
111
+ if (error instanceof UnsupportedBundlePlatformError) return { code: 'unsupported-platform' }
112
+ if (!(error instanceof ManagementFailure)) return { code: 'operation-error', diagnostic: messageOf(error) }
113
+ return { code: error.code, ...error.incompatible === undefined ? {} : { incompatible: error.incompatible } }
114
+ }
115
+
116
+ /** The caller stopped an installation; its files are restored before this is thrown. */
117
+ class InstallCancelledError extends Error {
118
+ constructor() {
119
+ super('Installation cancelled')
120
+ this.name = 'InstallCancelledError'
121
+ }
122
+ }
123
+
124
+ /** One installation the manager owns until its call settles. */
125
+ interface InstallControl {
126
+ readonly abort: AbortController
127
+ /** `applying` once pnpm has exited and the bundle is being selected and loaded, which cannot be stopped. */
128
+ phase: 'installing' | 'applying'
129
+ /** The active install's result, shared with clients recovering a lost response. */
130
+ result: Promise<ChangeResult | null>
131
+ }
132
+
133
+ /** A manifest field that is a string, when the manifest carries one. */
134
+ function stringField(manifest: object, field: string): string | undefined {
135
+ const value = (manifest as Record<string, unknown>)[field]
136
+ return typeof value === 'string' ? value : undefined
137
+ }
138
+
139
+ /** The fields of the dsh installation's own manifest the manager reads. */
140
+ interface InstallationManifest {
141
+ dependencies?: Record<string, string>
142
+ }
143
+
144
+ /** What a package manifest says about the package: identity, one-liner, and whether it is a bundle. */
145
+ function inspectionOf(kind: 'registry' | 'path', manifest: object, registry: Registry): Extract<PluginSpecInspection, { status: 'accepted' }> {
146
+ const dsh = (manifest as { dsh?: unknown }).dsh
147
+ const declared = typeof dsh === 'object' && dsh !== null ? dsh as { bundle?: unknown } : undefined
148
+ const bundle = declared !== undefined && typeof declared.bundle === 'object' && declared.bundle !== null
149
+ const name = stringField(manifest, 'name')
150
+ const version = stringField(manifest, 'version')
151
+ const description = stringField(manifest, 'description')
152
+ return {
153
+ status: 'accepted', kind, bundle, registry,
154
+ ...name === undefined ? {} : { name },
155
+ ...version === undefined ? {} : { version },
156
+ ...description === undefined || description === '' ? {} : { description },
157
+ }
158
+ }
159
+
160
+ function refused(problem: Extract<PluginSpecInspection, { status: 'refused' }>['problem'], reason: string): PluginSpecInspection {
161
+ return { status: 'refused', problem, reason }
162
+ }
163
+
164
+ /**
165
+ * An installed bundle an update can replace and its installed version: a registry copy with its parsed registry spec,
166
+ * or a Git copy with the saved spec that installs it again and the repository directory it pins.
167
+ */
168
+ type UpdateTarget<B> =
169
+ | { kind: 'registry'; bundle: B; installed: string; parsed: Extract<ParsedInstallSpec, { kind: 'registry' }> }
170
+ | { kind: 'git'; bundle: B; installed: string; source: string; origin: string }
171
+
172
+ /** What an update installs: the target spec, the registry asked first when one is named, and whether the save is exact. */
173
+ interface UpdatePlan {
174
+ spec: string
175
+ registry: Registry | undefined
176
+ saveExact: boolean
177
+ }
178
+
179
+ /**
180
+ * Why an update cannot replace a listed bundle, or what it replaces.
181
+ * @param bundle The listed bundle, or undefined for a name the inventory does not list.
182
+ * @param name The package name, for the refusal.
183
+ * @returns The bundle, its installed version, and how it was installed; or the refusal's diagnostic.
184
+ */
185
+ function updateRefusal<B extends Pick<BundleInfo, 'name' | 'installed' | 'availability' | 'official' | 'version' | 'source' | 'readOnlyReason'>>(
186
+ bundle: B | undefined, name: string,
187
+ ): UpdateTarget<B> | string {
188
+ if (bundle === undefined || !bundle.installed || bundle.availability !== 'profile' || bundle.official || bundle.source === undefined) {
189
+ return `${name} is not a third-party package installed in this profile`
190
+ }
191
+ // A management bundle cannot be removed, so it cannot be replaced either.
192
+ if (bundle.readOnlyReason !== undefined) return `${bundle.name} carries plugin management and cannot be removed`
193
+ const installed = bundle.version
194
+ if (installed === undefined || semver.valid(installed) === null) return `${bundle.name} declares no semver version`
195
+ // Only a pinned commit reinstalls the removed version when its replacement fails.
196
+ const origin = pinnedGitOrigin(bundle.source)
197
+ if (origin !== undefined) return { kind: 'git', bundle, installed, source: bundle.source, origin }
198
+ const parsed = parsedForRegistry(bundle.source)
199
+ // A protocol in the saved range, such as an `npm:` alias, names another package than the dependency.
200
+ if (parsed.kind !== 'registry' || parsed.name !== bundle.name || parsed.range?.includes(':') === true) {
201
+ return `${bundle.name} is installed neither from a registry under its own name nor from a Git commit`
202
+ }
203
+ return { kind: 'registry', bundle, installed, parsed }
204
+ }
205
+
206
+ /** What asking planned registries in turn answered: the parsed output and the registry that gave it, or the last refusal. */
207
+ type RegistryAnswer =
208
+ | { status: 'answered'; answer: unknown; registry: Registry; attempts: RegistryAttempt[] }
209
+ | { status: 'refused'; problem: NonNullable<RegistryAttempt['problem']>; reason: string; attempts: RegistryAttempt[] }
210
+
211
+ /**
212
+ * Map items with at most `limit` calls in flight, stopping new calls once one answers `stop`.
213
+ * @param items - the items, in order.
214
+ * @param limit - the most calls in flight.
215
+ * @param map - the call for one item.
216
+ * @param stop - whether an answer ends the remaining calls.
217
+ * @returns the answers of the calls that ran, in item order; items after a stop stay absent.
218
+ */
219
+ async function mapConcurrent<T, R>(
220
+ items: readonly T[], limit: number, map: (item: T) => Promise<R>, stop: (answer: R) => boolean,
221
+ ): Promise<(R | undefined)[]> {
222
+ const answers: (R | undefined)[] = items.map(() => undefined)
223
+ let next = 0
224
+ let stopped = false
225
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
226
+ while (!stopped && next < items.length) {
227
+ const index = next++
228
+ const answer = await map(items[index] as T)
229
+ answers[index] = answer
230
+ if (stop(answer)) stopped = true
231
+ }
232
+ }))
233
+ return answers
234
+ }
235
+
236
+ /** The refusal `pnpm view --json` prints on stdout, `{ error: { code, message } }`, as one log line; empty for anything else. */
237
+ function printedError(printed: string): string {
238
+ let parsed: unknown
239
+ try { parsed = JSON.parse(printed || 'null') }
240
+ catch { return '' /* not JSON: nothing pnpm printed as a refusal */ }
241
+ const error = typeof parsed === 'object' && parsed !== null ? (parsed as { error?: unknown }).error : undefined
242
+ if (typeof error !== 'object' || error === null) return ''
243
+ const { code, message } = error as { code?: unknown; message?: unknown }
244
+ return [code, message].filter((part): part is string => typeof part === 'string').join(' ')
245
+ }
246
+
247
+ /** What applying the saved profile reports into a change result. */
248
+ type Reload = Pick<ChangeResult, 'warnings' | 'restartReason'>
249
+
250
+ /** The bundles a profile manifest selects. */
251
+ function bundleSelection(manifest: ProfileManifest): readonly string[] {
252
+ return manifest.dsh?.profile?.bundles ?? []
253
+ }
254
+
255
+ /**
256
+ * The package an installation spec names before pnpm runs: a registry name, a local directory's manifest name, or the
257
+ * dependency saved with this git or tarball spec or the SSH form of its Git URL, compared as the plugin list shows saved specs.
258
+ * @param spec The installation spec.
259
+ * @param dependencies The profile's saved dependencies.
260
+ * @param profileDir The profile directory saved local paths are relative to.
261
+ * @returns The package name, or `undefined` when only the installation tells it.
262
+ */
263
+ function specPackageName(spec: string, dependencies: Readonly<Record<string, string>>, profileDir: string): string | undefined {
264
+ const parsed = parsedForRegistry(spec)
265
+ if (parsed.kind === 'registry') return parsed.name
266
+ if (parsed.kind === 'path') return packageName(parsed.path)
267
+ const alternative = parsed.kind === 'tarball' && parsed.path !== undefined ? `file:${parsed.path}` : sshGitSpec(parsed)
268
+ const specs = alternative === undefined ? [spec] : [spec, alternative]
269
+ return Object.entries(dependencies).find(([dependency, saved]) => specs.includes(dependencySpec(dependency, saved, profileDir)))?.[0]
270
+ }
271
+
272
+ /** The package name a local directory declares, or `undefined` without a readable manifest. */
273
+ function packageName(dir: string): string | undefined {
274
+ try {
275
+ return readProfileManifest('dsh', dir).name
276
+ } catch (_error) {
277
+ // pnpm reports the unreadable directory itself.
278
+ return undefined
279
+ }
280
+ }
281
+
282
+ /** The spec's form, for deciding whether a failed attempt was the registry's; a form the parser refuses has no host of its own. */
283
+ function parsedForRegistry(spec: string): ParsedInstallSpec {
284
+ try {
285
+ return parseInstallSpec(spec)
286
+ } catch (error) {
287
+ /* v8 ignore next -- parseInstallSpec throws nothing but its own refusal */
288
+ if (!(error instanceof InvalidInstallSpecError)) throw error
289
+ return { kind: 'registry', spec, name: spec }
290
+ }
291
+ }
292
+
293
+ /** Only registry package names are retained before installation resolves its target. */
294
+ function installOperationTarget(spec: string): string | null {
295
+ let parsed: ParsedInstallSpec
296
+ try { parsed = parseInstallSpec(spec) }
297
+ catch (_error) { return null /* Invalid specs remain private; installation owns their refusal. */ }
298
+ return parsed.kind === 'registry' ? parsed.name : null
299
+ }
300
+
301
+ /** Exemption facts use canonical package identity, never the raw request or installed version. */
302
+ function exemptionOperationIdentity(packageVersion: string, runtimeVersion: string): Pick<PluginOperation, 'target' | 'version'> {
303
+ try { validatePluginVersionExemption(packageVersion, runtimeVersion) }
304
+ catch (_error) { return { target: null } /* The operation still owns validation failure reporting. */ }
305
+ const separator = packageVersion.lastIndexOf('@')
306
+ return { target: installOperationTarget(packageVersion.slice(0, separator)),
307
+ version: diagnosticVersion(packageVersion.slice(separator + 1)) }
308
+ }
309
+
310
+ /** Unusable file metadata must not discard the rest of an operation record. */
311
+ function diagnosticVersion(value: unknown): string | undefined {
312
+ return typeof value === 'string' && value.length <= 128 ? value : undefined
313
+ }
314
+
315
+ declare module '@deepseek-ai/cordis' {
316
+ interface Context {
317
+ /** Persistent management of the current profile's composition and packages. */
318
+ pluginManager: PluginManager
319
+ }
320
+ }
321
+
322
+ /** Manage profile files and apply their declared reload lifecycle. */
323
+ export class PluginManager extends TypertRemoteService {
324
+ static inject = ['loader', 'profileContext']
325
+ static Config: z<Config> = z.object({
326
+ pnpmCommand: z.string().default('pnpm'),
327
+ outputBytes: z.number().step(1).min(1).default(16384),
328
+ lockWaitMs: z.number().step(1).min(0).default(120000),
329
+ inspectTimeoutMs: z.number().step(1).min(1000).default(20000),
330
+ githubConnectionTimeoutMs: z.number().step(1).min(1000).default(5000),
331
+ gitTransportTimeoutMs: z.number().step(1).min(1000).default(5000),
332
+ idleTimeoutMs: z.number().step(1).min(1000).default(600000),
333
+ registry: z.string().pattern(REGISTRY_URL),
334
+ fallbackRegistries: z.array(z.string().pattern(REGISTRY_URL)).default([NPMMIRROR_REGISTRY]),
335
+ versionListLimit: z.number().step(1).min(1).default(20),
336
+ versionLookupConcurrency: z.number().step(1).min(1).default(4),
337
+ detailMaxBytes: z.natural().min(1).default(1024 * 1024),
338
+ detailImageMaxBytes: z.natural().min(1).default(5 * 1024 * 1024),
339
+ detailFetchTimeoutMs: z.natural().min(1).max(MAX_TIMER_DELAY_MS).default(15000),
340
+ detailNpmFileSources: z.array(z.union(NPM_FILE_SOURCES)).min(1).default([...NPM_FILE_SOURCES]),
341
+ })
342
+ /** Management bundles remain protected if their files become unreadable. */
343
+ private readonly managementBundles = new Set<string>()
344
+ /**
345
+ * The registry each package was last installed from by this manager in this process. pnpm verifies lockfile tarball
346
+ * URLs against its default registry unless they belong to a named registry, so a later removal names it again.
347
+ */
348
+ private readonly installedFrom = new Map<string, Registry>()
349
+ private readonly ownerEntryId: string | undefined
350
+ private readonly packageOperations = new Set<Promise<unknown>>()
351
+ private readonly profile: ProfileContext
352
+ private readonly outputBytes: number
353
+ private readonly lockWaitMs: number
354
+ private readonly inspectTimeoutMs: number
355
+ private readonly githubConnectionTimeoutMs: number
356
+ private readonly gitTransportTimeoutMs: number
357
+ private readonly idleTimeoutMs: number
358
+ private readonly pnpmCommand: string
359
+ private readonly versionListLimit: number
360
+ private readonly versionLookupConcurrency: number
361
+ private readonly configuredRegistries: Omit<PluginRegistries, 'resolved'>
362
+ private readonly ownerContext: Context
363
+ private readonly abort = new AbortController()
364
+ /** Installations by request id, from their call until it settles. */
365
+ private readonly installs = new Map<PluginInstallRequestId, InstallControl>()
366
+ private readonly detail: BundleDetailOptions
367
+
368
+ constructor(ctx: Context, config: Config) {
369
+ super(ctx, 'pluginManager')
370
+ this.ownerEntryId = ctx.fiber.entry?.id
371
+ this.ownerContext = ctx
372
+ this.profile = ctx.profileContext
373
+ for (const name of this.profile.startedBundles) this.protectsManager(name)
374
+ this.outputBytes = (config as Required<Config>).outputBytes
375
+ this.lockWaitMs = (config as Required<Config>).lockWaitMs
376
+ this.inspectTimeoutMs = (config as Required<Config>).inspectTimeoutMs
377
+ this.githubConnectionTimeoutMs = (config as Required<Config>).githubConnectionTimeoutMs
378
+ this.gitTransportTimeoutMs = (config as Required<Config>).gitTransportTimeoutMs
379
+ this.idleTimeoutMs = (config as Required<Config>).idleTimeoutMs
380
+ this.pnpmCommand = (config as Required<Config>).pnpmCommand
381
+ this.versionListLimit = (config as Required<Config>).versionListLimit
382
+ this.versionLookupConcurrency = (config as Required<Config>).versionLookupConcurrency
383
+ this.configuredRegistries = {
384
+ registry: config.registry === undefined ? null : normalizeRegistry(config.registry),
385
+ fallbackRegistries: (config as Required<Config>).fallbackRegistries.map(normalizeRegistry),
386
+ }
387
+ const required = config as Required<Config>
388
+ this.detail = {
389
+ profile: this.profile, maxDocumentBytes: required.detailMaxBytes, maxImageBytes: required.detailImageMaxBytes,
390
+ npmFileSources: required.detailNpmFileSources, timeoutMs: required.detailFetchTimeoutMs, lifetime: this.abort.signal,
391
+ }
392
+ ctx.effect(() => async () => {
393
+ this.abort.abort()
394
+ await Promise.allSettled([...this.packageOperations])
395
+ }, 'plugin-manager: package cancellation')
396
+ ctx.inject(['connection'], (scope) => {
397
+ scope.effect(() => scope.connection.fetch.register({
398
+ path: DETAIL_FILE_PATH, methods: ['GET'], requestBody: 'buffered', fetch: request => this.serveDetailFile(request),
399
+ }), `plugin-manager: ${DETAIL_FILE_PATH}`)
400
+ })
401
+ }
402
+
403
+ /**
404
+ * Read a bundle's long description: the Markdown file its locale `meta.detail` names in `language`, otherwise its
405
+ * README. An installed bundle is read from its directory without network access; an official bundle the installation
406
+ * offers before it is installed is read from the npm file CDNs at its offered version. Nothing is cached.
407
+ * @param name - the bundle's package name, as `listBundles()` lists it.
408
+ * @param language - the display language, such as `zh-CN`; documents fall back through its prefixes to English.
409
+ * @param options - `npmFileSources` names npm file CDNs to ask first for an offered bundle, in order, such as the one
410
+ * a Client measured as fastest; configured CDNs it omits follow, and CDNs that are not configured are not asked.
411
+ * @returns the document with its origin and path, or `none`.
412
+ * @throws {RemoteError} `plugin-manager/unknown-bundle`, `plugin-manager/invalid-language`, or
413
+ * `plugin-manager/detail-unavailable`.
414
+ */
415
+ @Remote
416
+ async readBundleDetail(name: string, language: string, options?: { npmFileSources?: NpmFileSource[] }): Promise<BundleDetail> {
417
+ return await readBundleDocument(await this.listedBundle(name), language, options?.npmFileSources ?? [], this.detail)
418
+ }
419
+
420
+ private async listedBundle(name: string): Promise<BundleInfo> {
421
+ const bundle = (await this.listBundles()).find(candidate => candidate.name === name)
422
+ if (bundle === undefined) throw new RemoteError('plugin-manager/unknown-bundle', `No such bundle: ${name}`, { name })
423
+ return bundle
424
+ }
425
+
426
+ /**
427
+ * Answer `GET ${DETAIL_FILE_PATH}?bundle=<name>&document=<path>&path=<destination>[&sources=<cdn>,...]` with one image
428
+ * beside a bundle document; `sources` names npm file CDNs to ask first for an offered bundle, as `readBundleDetail` does.
429
+ */
430
+ private async serveDetailFile(request: Request): Promise<Response> {
431
+ const params = new URL(request.url).searchParams
432
+ const [bundle, document, path] = [params.get('bundle'), params.get('document'), params.get('path')]
433
+ // Images are read again on every request, so a reinstalled bundle shows its own.
434
+ const cache = 'no-store'
435
+ if (bundle === null || document === null || path === null) return detailImageResponse('invalid', cache)
436
+ try {
437
+ const image = await readBundleImage(await this.listedBundle(bundle), document, path, params.get('sources')?.split(',') ?? [], this.detail)
438
+ return detailImageResponse(image, cache)
439
+ } catch (error) {
440
+ const failure = remoteErrorOf(error)
441
+ if (failure?.code === 'plugin-manager/unknown-bundle') return detailImageResponse(undefined, cache)
442
+ if (failure?.code === 'plugin-manager/detail-unavailable') return detailImageResponse(failure.details.reason, cache)
443
+ throw error
444
+ }
445
+ }
446
+
447
+ /** Read exact plugin-version exemptions saved in this profile.
448
+ * @returns Accepted package-name@version keys with the runtime versions they may run on, and any
449
+ * record or file problem the reader rejected, which the caller reports instead of failing.
450
+ */
451
+ @Remote
452
+ listVersionExemptions(): { exemptions: Record<string, string[]>; warnings: string[] } {
453
+ const { exemptions, warnings } = readProfileCompatibility(this.profile.dir)
454
+ return { exemptions, warnings }
455
+ }
456
+
457
+ /** Grant or revoke one exact plugin/runtime exemption and reevaluate live plugins.
458
+ * @param packageVersion Exact manifest package name followed by @ and its version; never an installation spec or alias.
459
+ * @param runtimeVersion Exact current DSH version for grants; revocation may name a previous runtime.
460
+ * @param enabled Whether to grant rather than revoke the exemption.
461
+ * @param acceptRisk Required true for grants after the user accepts possible crashes and data loss.
462
+ * @returns Saved and runtime outcomes. Startup-only profiles require restart.
463
+ */
464
+ @Remote
465
+ setVersionExemption(packageVersion: string, runtimeVersion: string, enabled: boolean, acceptRisk?: boolean): Promise<ChangeResult> {
466
+ return this.change(result => this.configure(async () => {
467
+ await setProfileVersionExemption(this.profile.dir, packageVersion, runtimeVersion, enabled, acceptRisk === true)
468
+ Object.assign(result, await this.reload())
469
+ }), { stage: 'enable', target: packageVersion, enabled }, 'bundle', exemptionOperationIdentity(packageVersion, runtimeVersion))
470
+ }
471
+
472
+ /** Read current plugins, including why a row cannot be changed through the profile patch.
473
+ * @returns Current runtime entries with persistent patch targets.
474
+ */
475
+ @Remote
476
+ async listPlugins(): Promise<PluginInfo[]> {
477
+ const rows = flatten(composeEntries([readProfilePatches('dsh', this.profile)]))
478
+ const snapshot = await readPluginInventory(this.ctx)
479
+ return snapshot.entries.map((entry) => {
480
+ const actual = [...this.ctx.loader.entries()].find(row => row.id === entry.entryId)
481
+ const candidates = rows.filter(row => row.id === actual?.options.id)
482
+ const candidate = candidates[0]
483
+ if (PROTECTED_PLUGINS.has(entry.moduleName) || entry.entryId === this.ownerEntryId) {
484
+ return { ...entry, readOnlyReason: 'management-required' as const }
485
+ }
486
+ if (candidate === undefined || candidates.length > 1 || candidate.name !== entry.moduleName
487
+ || actual?.parent.tree.ctx.fiber.entry?.id !== 'include') {
488
+ return { ...entry, readOnlyReason: 'unaddressable' as const }
489
+ }
490
+ return { ...entry, patchId: candidate.id }
491
+ })
492
+ }
493
+
494
+ /** Read installed, installation-provided, and offline Official catalog bundles, plus selected non-bundle names.
495
+ * A dependency without a bundle patch is listed, as a `not-bundle` problem, only while it is selected.
496
+ * @returns Package versions, manifest descriptions, the installable spec of profile dependencies, rows, optional
497
+ * display metadata, activation selections, whether the installation offers the bundle, and removal availability.
498
+ */
499
+ @Remote
500
+ listBundles(): Promise<BundleInfo[]> {
501
+ return Promise.resolve(this.readBundles().map((bundle) => {
502
+ const target = updateRefusal(bundle, bundle.name)
503
+ return typeof target === 'string' ? bundle : { ...bundle, update: target.kind }
504
+ }))
505
+ }
506
+
507
+ /** The bundle inventory before update eligibility, which is derived from each listed bundle. */
508
+ private readBundles(): Omit<BundleInfo, 'update'>[] {
509
+ const manifest = readProfileManifest('dsh', this.profile.dir)
510
+ const exemptions = readProfileVersionExemptions(this.profile.dir)
511
+ const selected = bundleSelection(manifest)
512
+ const recorded = manifest.dependencies ?? {}
513
+ const dependencies = Object.keys(recorded)
514
+ const installation = JSON.parse(readFileSync(this.profile.installAnchor, 'utf8')) as InstallationManifest
515
+ const catalog = new Map(OFFICIAL_ON_DEMAND_CATALOG.map(entry => [entry.packageName, entry]))
516
+ const names = [...new Set([...selected, ...dependencies, ...Object.keys(installation.dependencies ?? {}), ...catalog.keys()])]
517
+ const bundles: Omit<BundleInfo, 'update'>[] = []
518
+ const runtimeVersion = getDshRuntimeVersion()
519
+ for (const name of names) {
520
+ const installed = dependencies.includes(name)
521
+ const optional = OPTIONAL_BUNDLES.includes(name)
522
+ const enabled = selected.includes(name)
523
+ const shipped = Object.hasOwn(installation.dependencies ?? {}, name)
524
+ const offered = catalog.get(name)
525
+ const official = optional || offered !== undefined
526
+ let target: Pick<BundleInfo, 'installTarget'> = {}
527
+ let targetError: ManagementError | undefined
528
+ if (offered !== undefined) {
529
+ try { target = { installTarget: officialBundleInstallTarget(name, this.profile.installAnchor, runtimeVersion) } }
530
+ catch (error) { targetError = managementError(error) }
531
+ }
532
+ const catalogMeta = offered === undefined ? {} : { meta: offered.meta }
533
+ if (offered !== undefined && !installed && !shipped) {
534
+ let platformError: ManagementError | undefined
535
+ try { assertBundlePlatform(offered.platforms, process.platform) }
536
+ catch (error) { platformError = managementError(error) }
537
+ const error = platformError ?? targetError ?? (enabled ? { code: 'not-bundle' as const } : undefined)
538
+ bundles.push({ name, official, availability: 'missing', ...catalogMeta, ...target, enabled, installed, optional,
539
+ ...platformError?.code === 'unsupported-platform' ? { listedByDefault: false } : {},
540
+ removable: enabled, rows: [], overrides: [],
541
+ ...error === undefined ? {} : { error } })
542
+ continue
543
+ }
544
+ // Installation-owned copies remain protected even if a profile also declares their names.
545
+ const owned = installed && !shipped
546
+ const removable = owned || (enabled && !installed && !shipped)
547
+ const sourceOf = (packageName?: string): { source?: string } =>
548
+ owned ? { source: dependencySpec(name, recorded[name] as string, this.profile.dir, packageName) } : {}
549
+ const readOnlyReason = this.protectsManager(name) ? 'management-required' as const : undefined
550
+ let availability: BundleInfo['availability'] = 'missing'
551
+ let version: string | undefined
552
+ let listing: Pick<BundleInfo, 'listedByDefault'> = {}
553
+ try {
554
+ const info = bundleManifest(name, this.profile.dir, this.profile.installAnchor)
555
+ availability = shipped ? 'installation' : 'profile'
556
+ if (info === undefined) {
557
+ if (enabled || offered !== undefined) bundles.push({ name, official, availability, ...catalogMeta, ...target,
558
+ ...sourceOf(), enabled, installed, optional, removable: removable && readOnlyReason === undefined,
559
+ ...(readOnlyReason === undefined ? {} : { readOnlyReason }), error: targetError ?? { code: 'not-bundle' }, rows: [], overrides: [] })
560
+ continue
561
+ }
562
+ version = info.version
563
+ const listedByDefault = info.dsh?.bundle?.listedByDefault
564
+ // The launcher ignores this display field, so an invalid value is a metadata diagnostic, not a load error.
565
+ const listingDiagnostic = listedByDefault === undefined || typeof listedByDefault === 'boolean'
566
+ ? undefined
567
+ : 'dsh.bundle.listedByDefault must be a boolean'
568
+ if (typeof listedByDefault === 'boolean') listing = { listedByDefault }
569
+ const compatibility = evaluatePluginCompatibility(info, exemptions)
570
+ if (compatibility !== undefined && !compatibility.exempted) throw new ManagementFailure('incompatible-version', [incompatiblePlugin(compatibility)])
571
+ const dir = resolveBundleDir('dsh', name, this.profile.installAnchor, this.profile.dir)
572
+ const read: BundleInfo['meta'] = offered?.meta ?? readPluginMeta(info.name ?? name, pathToFileURL(join(dir, 'package.json')).href)
573
+ const meta = listingDiagnostic === undefined
574
+ ? read
575
+ : { ...read, error: read?.error === undefined ? listingDiagnostic : `${read.error}; ${listingDiagnostic}` }
576
+ let platformError: ManagementError | undefined
577
+ try { assertBundlePlatform(info.dsh?.bundle?.platforms, process.platform) }
578
+ catch (error) { platformError = managementError(error) }
579
+ if (platformError?.code === 'unsupported-platform') listing = { listedByDefault: false }
580
+ const error = platformError ?? targetError
581
+ bundles.push({ name, official, availability, ...listing, ...target, ...(version === undefined ? {} : { version }),
582
+ ...(info.description === undefined || info.description === '' ? {} : { description: info.description }),
583
+ ...meta === undefined ? {} : { meta },
584
+ ...sourceOf(info.name), enabled, installed, optional, removable: removable && readOnlyReason === undefined,
585
+ ...(readOnlyReason === undefined ? {} : { readOnlyReason }),
586
+ ...this.declaredRows(name, info),
587
+ ...error === undefined ? {} : { error } })
588
+ } catch (error) {
589
+ if (enabled || installed || optional || offered !== undefined) {
590
+ bundles.push({ name, official, availability, ...listing, ...catalogMeta, ...target, ...(version === undefined ? {} : { version }),
591
+ ...sourceOf(), enabled, installed, optional, removable: removable && readOnlyReason === undefined,
592
+ ...(readOnlyReason === undefined ? {} : { readOnlyReason }),
593
+ error: targetError ?? managementError(error), rows: [], overrides: [] })
594
+ }
595
+ }
596
+ }
597
+ return bundles
598
+ }
599
+
600
+ /** Read the registries this manager asks: the configured first one, its fallbacks in order, and what pnpm's own configuration names.
601
+ * @returns The registries in pnpm's comparison form; null is the one pnpm's own configuration names, `resolved` as pnpm reads it now.
602
+ */
603
+ @Remote
604
+ async registries(): Promise<PluginRegistries> {
605
+ return {
606
+ ...this.configuredRegistries, fallbackRegistries: [...this.configuredRegistries.fallbackRegistries],
607
+ resolved: await readProfileRegistry(this.profile.dir, {
608
+ ...this.profile.packageManager ?? { command: this.pnpmCommand }, timeoutMs: this.inspectTimeoutMs,
609
+ }),
610
+ }
611
+ }
612
+
613
+ /** Read what a spec names before installing it.
614
+ * @param spec One package spec: a registry name, an absolute path, a git address, or a tarball.
615
+ * @param options The registry asked first.
616
+ * @param signal Ends a registry lookup early.
617
+ * @returns The package the spec names, or why it is refused.
618
+ */
619
+ @Remote
620
+ async inspect(spec: string, options?: InspectOptions, signal?: AbortSignal): Promise<PluginSpecInspection> {
621
+ let parsed
622
+ try {
623
+ parsed = parseInstallSpec(spec)
624
+ } catch (error) {
625
+ /* v8 ignore next 2 -- parseInstallSpec throws nothing but its own refusal */
626
+ if (!(error instanceof InvalidInstallSpecError)) throw error
627
+ return refused('invalid-spec', error.reason)
628
+ }
629
+ const manifest = readProfileManifest('dsh', this.profile.dir)
630
+ const installation = JSON.parse(readFileSync(this.profile.installAnchor, 'utf8')) as InstallationManifest
631
+ const known = new Set([
632
+ ...bundleSelection(manifest), ...Object.keys(manifest.dependencies ?? {}), ...Object.keys(installation.dependencies ?? {}),
633
+ ])
634
+ const plan = registryPlan(options?.registry, await this.registries())
635
+ const registry = plan[0] as Registry
636
+ switch (parsed.kind) {
637
+ case 'git': return { status: 'accepted', kind: 'git', bundle: null, registry, host: parsed.host }
638
+ case 'tarball':
639
+ if (parsed.path !== undefined && !existsSync(parsed.path)) return refused('not-a-package', 'the tarball does not exist')
640
+ return { status: 'accepted', kind: 'tarball', bundle: null, registry, ...parsed.host === undefined ? {} : { host: parsed.host } }
641
+ case 'path': {
642
+ if (!existsSync(parsed.path)) return refused('not-a-package', 'the path does not exist')
643
+ let read: object
644
+ try {
645
+ read = JSON.parse(await readFile(join(parsed.path, 'package.json'), 'utf8')) as object
646
+ } catch (error) {
647
+ return refused('not-a-package', `no readable package.json at the path: ${messageOf(error)}`)
648
+ }
649
+ const inspection = inspectionOf('path', read, registry)
650
+ if (inspection.name === undefined) return refused('not-a-package', 'the package.json names no package')
651
+ if (known.has(inspection.name)) return refused('already-installed', `${inspection.name} is already installed`)
652
+ if (!inspection.bundle) return refused('not-a-bundle', `${inspection.name} declares no dsh.bundle`)
653
+ return inspection
654
+ }
655
+ case 'registry': {
656
+ if (known.has(parsed.name)) return refused('already-installed', `${parsed.name} is already installed`)
657
+ const asked = await this.askRegistries(spec.trim(), INSPECT_FIELDS, plan, parsed, signal)
658
+ const registries = asked.attempts.map(attempt => attempt.registry)
659
+ if (asked.status === 'refused') return { status: 'refused', problem: asked.problem, reason: asked.reason, registries }
660
+ // pnpm prints a range's highest match as one object; npm's array of every match is read by its last entry.
661
+ const latest: unknown = Array.isArray(asked.answer) ? asked.answer.at(-1) : asked.answer
662
+ if (typeof latest !== 'object' || latest === null) return { status: 'refused', problem: 'unknown', reason: 'pnpm view answered no package', registries }
663
+ const inspection = inspectionOf('registry', latest, asked.registry)
664
+ const named = inspection.name === undefined ? { ...inspection, name: parsed.name } : inspection
665
+ if (!named.bundle) return { status: 'refused', problem: 'not-a-bundle', reason: `${named.name} declares no dsh.bundle`, registries }
666
+ return named
667
+ }
668
+ }
669
+ }
670
+
671
+ /** Read the published versions newer than an installed registry package's version, from the first registry that answers.
672
+ * Official bundles follow the DSH version and are not listed.
673
+ * @param name Installed profile dependency name.
674
+ * @param options The registry asked first; absent, the one the package was installed from in this process, else the configured one.
675
+ * @param signal Ends the lookups early.
676
+ * @returns At most `versionListLimit` newer versions, newest first, with their tags, deprecation, bundle declaration,
677
+ * and DSH compatibility, and the registry that answered; or why no list could be read, with every registry asked.
678
+ */
679
+ @Remote
680
+ async listVersions(name: string, options?: ListVersionsOptions, signal?: AbortSignal): Promise<PluginVersionList> {
681
+ const target = updateRefusal((await this.listBundles()).find(bundle => bundle.name === name), name)
682
+ if (typeof target === 'string') return { status: 'refused', problem: 'not-updatable', reason: target, attempts: [] }
683
+ if (target.kind === 'git') return { status: 'refused', problem: 'not-updatable', reason: `${name} is installed from Git, which lists no versions`, attempts: [] }
684
+ const plan = registryPlan(this.registryFor(name, options?.registry), await this.registries())
685
+ const listing = await this.askRegistries(name, VERSION_LIST_FIELDS, plan, target.parsed, signal)
686
+ if (listing.status === 'refused') return listing
687
+ let newer
688
+ try { newer = newerVersions(listing.answer, target.installed) }
689
+ catch (error) { return { status: 'refused', problem: 'unknown', reason: messageOf(error), attempts: listing.attempts } }
690
+ const listed = newer.slice(0, this.versionListLimit)
691
+ const exemptions = readProfileVersionExemptions(this.profile.dir)
692
+ const looked = await mapConcurrent(listed, this.versionLookupConcurrency, async (published) => {
693
+ const spec = `${name}@${published.version}`
694
+ const answer = await this.askRegistries(spec, VERSION_FIELDS, [listing.registry], { kind: 'registry', spec, name }, signal)
695
+ if (answer.status === 'refused') return answer
696
+ const facts = versionFacts(answer.answer, name, published.version)
697
+ let compatibility
698
+ try { compatibility = evaluatePluginCompatibility(facts.manifest, exemptions) }
699
+ catch (error) { return { status: 'refused' as const, problem: 'unknown' as const, reason: messageOf(error), attempts: answer.attempts } }
700
+ const version: PluginVersion = {
701
+ ...published, bundle: facts.bundle, ...facts.deprecated === undefined ? {} : { deprecated: facts.deprecated },
702
+ ...compatibility === undefined || compatibility.exempted ? {} : { incompatible: incompatiblePlugin(compatibility) },
703
+ }
704
+ return { status: 'read' as const, version }
705
+ }, answer => answer.status === 'refused')
706
+ const versions: PluginVersion[] = []
707
+ for (const answer of looked) {
708
+ /* v8 ignore next -- a lookup stops the rest only by refusing, which returns below */
709
+ if (answer === undefined) continue
710
+ if (answer.status === 'refused') return { ...answer, attempts: [...listing.attempts.slice(0, -1), ...answer.attempts] }
711
+ versions.push(answer.version)
712
+ }
713
+ return {
714
+ status: 'listed', installed: target.installed, registry: listing.registry, attempts: listing.attempts,
715
+ versions, omitted: newer.length - listed.length,
716
+ }
717
+ }
718
+
719
+ /**
720
+ * Replace an installed bundle with a newer version. A registry copy updates to `name@version`, checked on the registry
721
+ * first: it must exist, declare a bundle, and accept the running DSH version, or nothing changes. A Git copy updates
722
+ * to the Git spec `options.spec` names, which must pin a full commit of the repository directory the copy came from;
723
+ * with HMR, a network failure or timeout reaching its repository stops the update before anything changes. pnpm reads
724
+ * a Git package only while installing it, so its bundle and compatibility are checked then. Either target
725
+ * installation is undone, profile files and modules included, before its bundle loads unless it installs `name` at
726
+ * `version`. With HMR the installed version is removed, so its plugins stop, and the target is installed with the same
727
+ * selection; when that installation fails or is cancelled, the removed version is installed again: a registry copy
728
+ * from the registry it came from, a Git copy from its saved spec. Without HMR the target is installed over the running
729
+ * version and the result reports the restart.
730
+ * @param name Installed profile dependency name.
731
+ * @param version Exact version newer than the installed one.
732
+ * @param options The registry asked first, as for `listVersions`; the Git spec of `version`, required for and accepted
733
+ * only by a bundle `listBundles` lists with `update: 'git'`; and the request id naming the progress and the target
734
+ * installation's logs and cancellation.
735
+ * @returns The versions, the last step that ran with its result, and the reinstallation when one ran.
736
+ */
737
+ @Remote
738
+ async updateBundle(name: string, version: string, options?: UpdateBundleOptions): Promise<PluginUpdateResult> {
739
+ const requestId = options?.requestId
740
+ const announce = (step: PluginUpdateStep): void => {
741
+ if (requestId !== undefined) this.ownerContext.emit('plugin-manager/update-state', { requestId, step })
742
+ }
743
+ announce('checking')
744
+ const target = updateRefusal((await this.listBundles()).find(item => item.name === name), name)
745
+ const from = typeof target === 'string' ? '' : target.installed
746
+ const refusedBefore = (error: ManagementError): PluginUpdateResult => ({
747
+ from, to: version, step: 'check',
748
+ result: { changed: false, application: 'failed', stage: 'install', target: name, error },
749
+ })
750
+ if (typeof target === 'string') return refusedBefore({ code: 'invalid-spec', diagnostic: target })
751
+ const { bundle } = target
752
+ if (semver.valid(version) === null || !semver.gt(version, from)) {
753
+ return refusedBefore({ code: 'invalid-spec', diagnostic: `${version} is not a version newer than the installed ${from}` })
754
+ }
755
+ const planned = target.kind === 'git'
756
+ ? this.planGitUpdate(name, target.origin, options)
757
+ : await this.checkRegistryUpdate(name, version, options)
758
+ if ('code' in planned) return refusedBefore(planned)
759
+ const { spec, registry, saveExact } = planned
760
+ const { enabled } = bundle
761
+ // A lock timeout or disposal rejects instead of reporting; it reads as the failed step it is.
762
+ const settled = (stage: ChangeResult['stage'], target: string, operation: Promise<ChangeResult>): Promise<ChangeResult> =>
763
+ operation.catch((error: unknown) => ({ changed: false, application: 'failed', stage, target, error: managementError(error) }))
764
+ const installTarget = (): Promise<ChangeResult> => settled('install', spec, this.installBundle(spec, {
765
+ saveExact, enabled, expected: { name, version },
766
+ ...registry === undefined ? {} : { registry }, ...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
+ // A Git host that cannot be reached would fail the target and the reinstallation alike, so nothing is removed.
773
+ const unreachable = target.kind === 'git' ? await this.gitHostUnreachable(spec) : undefined
774
+ if (unreachable !== undefined) {
775
+ return {
776
+ from, to: version, step: 'check',
777
+ result: {
778
+ changed: false, application: 'failed', stage: 'install', target: name, failedAt: 'spec-host', packageResult: unreachable,
779
+ error: { code: 'operation-error', diagnostic: unreachable.output },
780
+ },
781
+ }
782
+ }
783
+ // The removed version is installed again where it came from, else over the configured plan, as its removal asks.
784
+ const previousRegistry = this.installedFrom.get(name)
785
+ announce('removing')
786
+ const removal = await settled('remove', name, this.removeBundle(name))
787
+ if (removal.application === 'failed' || removal.application === 'cancelled') return { from, to: version, step: 'remove', result: removal }
788
+ announce('installing')
789
+ const result = await installTarget()
790
+ if (result.application !== 'failed' && result.application !== 'cancelled') return { from, to: version, step: 'install', result }
791
+ announce('restoring')
792
+ // A target that installed but failed to start is still a dependency; it goes before the removed version returns.
793
+ if (result.stage === 'enable') await settled('remove', name, this.removeBundle(name))
794
+ // The reinstallation carries no request id, so cancelling the update cannot leave the package removed.
795
+ const previous = target.kind === 'git' ? target.source : `${name}@${from}`
796
+ const restore = await settled('install', previous, this.installBundle(previous, {
797
+ saveExact, enabled, ...previousRegistry === undefined ? {} : { registry: previousRegistry },
798
+ }))
799
+ return { from, to: version, step: 'install', result, restore }
800
+ }
801
+
802
+ /**
803
+ * The target of a Git copy's update: the caller's Git spec, pinned to a full commit of the copy's repository directory.
804
+ * @param name The package name.
805
+ * @param origin The repository directory the installed copy pins.
806
+ * @param options The caller's spec and registry.
807
+ * @returns The spec and the registry its dependencies are asked from first, or why the update is refused.
808
+ */
809
+ private planGitUpdate(name: string, origin: string, options: UpdateBundleOptions | undefined): UpdatePlan | ManagementError {
810
+ const spec = options?.spec
811
+ const pinned = spec === undefined ? undefined : pinnedGitOrigin(spec)
812
+ if (spec === undefined || pinned === undefined) {
813
+ return { code: 'invalid-spec', diagnostic: `${name} is installed from Git and updates only to a Git spec pinned to a full commit` }
814
+ }
815
+ if (pinned !== origin) {
816
+ return { code: 'invalid-spec', diagnostic: `${spec} is not in the repository directory ${name} is installed from, ${origin}` }
817
+ }
818
+ return { spec, registry: this.registryFor(name, options?.registry), saveExact: false }
819
+ }
820
+
821
+ /**
822
+ * Check that the network reaches the repository of a Git update's target. Only a network failure or a timeout
823
+ * counts: a check Git cannot run, or one the repository refuses without credentials, leaves the answer to pnpm.
824
+ * @param spec The target's pinned Git spec.
825
+ * @returns The failed check, or undefined when the host answered or the check could not tell.
826
+ */
827
+ private async gitHostUnreachable(spec: string): Promise<PackageResult | undefined> {
828
+ const parsed = parseInstallSpec(spec)
829
+ /* v8 ignore next -- planGitUpdate accepts only a pinned Git spec */
830
+ if (parsed.kind !== 'git') return undefined
831
+ const env = this.profile.packageManager?.env === undefined ? {} : { env: this.profile.packageManager.env }
832
+ const check = checkGitConnection(parsed, this.profile.dir, {
833
+ timeoutMs: this.githubConnectionTimeoutMs, outputBytes: this.outputBytes, signal: this.abort.signal, ...env,
834
+ })
835
+ this.packageOperations.add(check)
836
+ let failure: GithubConnectionFailure | undefined
837
+ try { failure = await check } finally { this.packageOperations.delete(check) }
838
+ this.abort.signal.throwIfAborted()
839
+ if (failure?.kind !== 'network' && failure?.kind !== 'timeout') return undefined
840
+ // The answer keeps a plain PackageResult; the check's command line stays out of the wire fields.
841
+ const { argv: _argv, ...packageResult } = failure
842
+ return packageResult
843
+ }
844
+
845
+ /**
846
+ * Check a registry copy's update target on the registry plan before anything changes.
847
+ * @param name The package name.
848
+ * @param version The target version.
849
+ * @param options The caller's registry, as for `listVersions`; a spec is refused.
850
+ * @returns The exact spec and the registry that answered for it, or why the target cannot replace the bundle.
851
+ */
852
+ private async checkRegistryUpdate(
853
+ name: string, version: string, options: UpdateBundleOptions | undefined,
854
+ ): Promise<UpdatePlan | ManagementError> {
855
+ const spec = `${name}@${version}`
856
+ if (options?.spec !== undefined) return { code: 'invalid-spec', diagnostic: `${name} is installed from a registry and updates only to ${spec}` }
857
+ const plan = registryPlan(this.registryFor(name, options?.registry), await this.registries())
858
+ const checked = await this.askRegistries(spec, VERSION_FIELDS, plan, { kind: 'registry', spec, name })
859
+ if (checked.status === 'refused') return { code: 'operation-error', diagnostic: checked.reason }
860
+ const facts = versionFacts(checked.answer, name, version)
861
+ if (!facts.bundle) return { code: 'not-bundle' }
862
+ let compatibility
863
+ try { compatibility = evaluatePluginCompatibility(facts.manifest, readProfileVersionExemptions(this.profile.dir)) }
864
+ catch (error) { return { code: 'operation-error', diagnostic: messageOf(error) } }
865
+ if (compatibility !== undefined && !compatibility.exempted) return { code: 'incompatible-version', incompatible: [incompatiblePlugin(compatibility)] }
866
+ return { spec, registry: checked.registry, saveExact: true }
867
+ }
868
+
869
+ /**
870
+ * The registry a version listing or an update asks first.
871
+ * @param name The package name.
872
+ * @param requested The caller's registry, when it named one.
873
+ * @returns The requested registry, else the one this process last installed the package from, else undefined for the configured one.
874
+ */
875
+ private registryFor(name: string, requested: Registry | undefined): Registry | undefined {
876
+ return requested !== undefined ? requested : this.installedFrom.get(name)
877
+ }
878
+
879
+ /**
880
+ * Ask registries in turn through `pnpm view`, moving to the next one while a failure is the registry's: unreachable,
881
+ * timed out, or without the package or version, which a mirror not yet synced reports.
882
+ * @param spec The registry spec viewed.
883
+ * @param fields The manifest fields printed.
884
+ * @param plan The registries, in order; never empty.
885
+ * @param parsed The spec's form, which decides whether a failure was the registry's.
886
+ * @param signal Ends the lookup; a dropped lookup is not carried to the next registry.
887
+ * @returns The parsed answer and the registry that gave it, or the last refusal, with every registry asked.
888
+ */
889
+ private async askRegistries(
890
+ spec: string, fields: readonly string[], plan: readonly Registry[], parsed: ParsedInstallSpec, signal?: AbortSignal,
891
+ ): Promise<RegistryAnswer> {
892
+ const attempts: RegistryAttempt[] = []
893
+ for (const [index, registry] of plan.entries()) {
894
+ const view = await viewProfilePackage(this.profile.dir, spec, {
895
+ ...this.profile.packageManager ?? { command: this.pnpmCommand },
896
+ fields, timeoutMs: this.inspectTimeoutMs, ...signal === undefined ? {} : { signal }, registry,
897
+ })
898
+ const printed = view.stdout.replace(ANSI_SEQUENCE, '').trim()
899
+ if (view.exitCode !== 0 || view.cause !== undefined || view.timedOut) {
900
+ // pnpm prints a refusal as `{ error: { code, message } }` on stdout, with nothing on stderr.
901
+ const log = [view.stderr.trim(), printedError(printed), view.cause === undefined ? '' : messageOf(view.cause)].filter(Boolean).join('\n')
902
+ const kind = classifyInstallFailure({ log, timedOut: view.timedOut, ...view.cause === undefined ? {} : { cause: view.cause } })
903
+ const reason = view.timedOut ? `pnpm view timed out after ${String(this.inspectTimeoutMs)}ms` : log || printed || `pnpm view exited with ${String(view.exitCode)}`
904
+ const problem = kind === 'not-found' || kind === 'no-matching-version' ? 'not-found' : kind === 'network' || kind === 'timeout' ? 'network' : 'unknown'
905
+ attempts.push({ registry, problem, reason })
906
+ if (index < plan.length - 1 && signal?.aborted !== true && attributeFailure(kind, log, parsed) === 'registry') continue
907
+ return { status: 'refused', problem, reason, attempts }
908
+ }
909
+ try {
910
+ const answer: unknown = JSON.parse(printed || 'null')
911
+ attempts.push({ registry })
912
+ return { status: 'answered', answer, registry, attempts }
913
+ } catch (error) {
914
+ const reason = `unreadable pnpm view output: ${messageOf(error)}`
915
+ attempts.push({ registry, problem: 'unknown', reason })
916
+ return { status: 'refused', problem: 'unknown', reason, attempts }
917
+ }
918
+ }
919
+ /* v8 ignore next -- the plan is never empty: every attempt returns or continues to the next */
920
+ throw new Error('no registry was asked')
921
+ }
922
+
923
+ /** Persist a plugin entry's desired enablement and apply it on live profiles.
924
+ * @param id Loader entry identity returned by listPlugins.
925
+ * @param enabled Whether the plugin should run.
926
+ * @returns Saved and runtime outcomes, including higher-priority overrides.
927
+ */
928
+ @Remote
929
+ setPluginEnabled(id: PluginEntryId, enabled: boolean): Promise<ChangeResult> {
930
+ return this.change(result => this.configure(async () => {
931
+ const row = (await this.listPlugins()).find(item => item.entryId === id)
932
+ if (row === undefined) throw new ManagementFailure('unknown-plugin')
933
+ if (row.readOnlyReason !== undefined) throw new ManagementFailure(row.readOnlyReason)
934
+ await writePluginEnabled(this.profile, row.patchId, row.moduleName, enabled)
935
+ Object.assign(result, await this.reload(enabled ? [row.patchId] : []))
936
+ const current = (await this.listPlugins()).find(item => item.entryId === id)
937
+ return current?.enabled !== enabled && this.ownerContext.get('hmr') !== undefined ? 'overridden' : undefined
938
+ }), { stage: 'enable', target: id, enabled }, 'plugin')
939
+ }
940
+
941
+ /** Select or remove a bundle layer while retaining installed dependencies.
942
+ * @param name Bundle package name.
943
+ * @param enabled Whether the bundle contributes its patch layer.
944
+ * @returns Persisted and runtime outcomes.
945
+ */
946
+ @Remote
947
+ setBundleEnabled(name: string, enabled: boolean): Promise<ChangeResult> {
948
+ return this.change(result => this.configure(async () => {
949
+ await this.selectBundle(name, enabled)
950
+ Object.assign(result, enabled ? await this.publishAndReload(this.bundleRows(name).map(row => row.id)) : await this.reload())
951
+ }), { stage: 'enable', target: name, enabled }, 'bundle')
952
+ }
953
+
954
+ /**
955
+ * Install a package using the same pnpm implementation as dsh plugin. GitHub
956
+ * repositories get a connection check bounded by githubConnectionTimeoutMs before pnpm starts;
957
+ * only network failures or timeouts stop installation, and a stop streams the check's diagnostic
958
+ * as the installation's install-log run under its request id, while pnpm owns authentication and transport fallback. An
959
+ * HTTP(S) Git URL on another host is installed over SSH instead when access probes bounded by gitTransportTimeoutMs
960
+ * find that only SSH can read it. A run
961
+ * that fails, is cancelled, or adds a package without a bundle patch restores
962
+ * `package.json` and `pnpm-lock.yaml` as they were; downloaded files can stay.
963
+ * @param spec One package spec, including local paths relative to the invocation directory.
964
+ * @param options Whether to activate the installed bundle (defaults to true), the request id a cancellation names,
965
+ * the pending build scripts to allow, whether to save an exact dependency, and the registry asked first.
966
+ * @returns Package-manager diagnostics, the registries asked, and the observed activation outcome.
967
+ */
968
+ @Remote
969
+ installBundle(spec: string, options?: InstallBundleOptions): Promise<ChangeResult> {
970
+ const requestId = options?.requestId
971
+ const control: InstallControl = { abort: new AbortController(), phase: 'installing', result: Promise.resolve(null) }
972
+ const stopped = (): boolean => control.abort.signal.aborted || this.abort.signal.aborted
973
+ if (requestId !== undefined) this.installs.set(requestId, control)
974
+ const announce = (phase: PluginInstallProgress['phase'], attempt?: PluginInstallProgress['attempt']): void => {
975
+ if (requestId !== undefined) this.ownerContext.emit('plugin-manager/install-state', { requestId, phase, ...attempt === undefined ? {} : { attempt } })
976
+ }
977
+ const result = this.change(async (result) => {
978
+ if (spec.trim() === '' || spec.startsWith('-')) throw new ManagementFailure('invalid-spec')
979
+ if (stopped()) throw new InstallCancelledError()
980
+ const before = readProfileManifest('dsh', this.profile.dir).dependencies ?? {}
981
+ // With HMR, an installed package is removed before another version is installed, so its plugins stop first.
982
+ const known = specPackageName(spec, before, this.profile.dir)
983
+ if (this.ownerContext.get('hmr') !== undefined && known !== undefined && Object.hasOwn(before, known)) {
984
+ throw new ManagementFailure('already-installed')
985
+ }
986
+ if (options?.approvedBuilds !== undefined) {
987
+ await approveBuilds(this.profile.dir, options.approvedBuilds)
988
+ result.approvedBuilds = options.approvedBuilds
989
+ }
990
+ const files = await this.readRestoredFiles()
991
+ let name: string
992
+ let version: string | undefined
993
+ try {
994
+ result.registries = []
995
+ const parsed = parsedForRegistry(spec)
996
+ const signal = AbortSignal.any([this.abort.signal, control.abort.signal])
997
+ const env = this.profile.packageManager?.env === undefined ? {} : { env: this.profile.packageManager.env }
998
+ const connection = checkGithubConnection(parsed, this.profile.dir, {
999
+ timeoutMs: this.githubConnectionTimeoutMs, outputBytes: this.outputBytes, signal, ...env,
1000
+ })
1001
+ this.packageOperations.add(connection)
1002
+ let connectionFailure: GithubConnectionFailure | undefined
1003
+ try { connectionFailure = await connection }
1004
+ finally { this.packageOperations.delete(connection) }
1005
+ if (stopped()) throw new InstallCancelledError()
1006
+ if (connectionFailure?.kind === 'network' || connectionFailure?.kind === 'timeout') {
1007
+ // The answer keeps a plain PackageResult; the check's command line is only streamed as the run below.
1008
+ const { argv, ...packageResult } = connectionFailure
1009
+ result.packageResult = packageResult
1010
+ result.failedAt = 'spec-host'
1011
+ // pnpm never runs, so the check is the installation's only run: stream its failure into the install log.
1012
+ // A timed-out Git reports no exit code of its own, unlike the result, which records the status it is read as.
1013
+ if (requestId !== undefined) {
1014
+ this.ownerContext.emit('plugin-manager/install-log', {
1015
+ requestId, jobId: randomUUID(), argv, cwd: this.profile.dir, stream: 'stderr',
1016
+ text: connectionFailure.output, exitCode: connectionFailure.timedOut === true ? null : connectionFailure.exitCode,
1017
+ })
1018
+ }
1019
+ throw new Error(connectionFailure.output)
1020
+ }
1021
+ const transport = chooseGitTransport(parsed, this.profile.dir, { timeoutMs: this.gitTransportTimeoutMs, signal, ...env })
1022
+ this.packageOperations.add(transport)
1023
+ let installSpec: string
1024
+ try { installSpec = await transport }
1025
+ finally { this.packageOperations.delete(transport) }
1026
+ if (stopped()) throw new InstallCancelledError()
1027
+ // The last run is the result's; the registries asked stay listed whatever the outcome.
1028
+ const plan = registryPlan(options?.registry, await this.registries())
1029
+ let run: PackageResult | undefined
1030
+ let used: Registry = null
1031
+ for (const [index, registry] of plan.entries()) {
1032
+ if (index > 0) await this.restoreFiles(files)
1033
+ // A stop that landed while the files went back, or before the first run, starts no run with a dead signal.
1034
+ if (stopped()) throw new InstallCancelledError()
1035
+ result.registries.push(registry)
1036
+ used = registry
1037
+ announce('installing', { registry, index: index + 1, total: plan.length })
1038
+ run = await this.runPnpm(
1039
+ ['add', installSpec, ...options?.saveExact === true ? ['--save-exact'] : [], ...registryArguments(registry)],
1040
+ control.abort.signal, requestId, options?.expected,
1041
+ )
1042
+ result.packageResult = run
1043
+ if (stopped()) throw new InstallCancelledError()
1044
+ // A compatibility refusal is the package's own answer, so no other registry is asked.
1045
+ if (run.incompatible !== undefined) throw new ManagementFailure('incompatible-version', run.incompatible)
1046
+ // So is a run that installed another package, version, or no bundle where the caller expects one.
1047
+ if (run.unmet !== undefined) throw new ManagementFailure(run.unmet)
1048
+ // A run this manager terminated is not a success, even when pnpm trapped the signal and exited 0.
1049
+ if (run.exitCode === 0 && run.timedOut !== true) break
1050
+ /* v8 ignore next 2 -- runPnpm classifies every run it does not report as succeeded */
1051
+ if (run.kind === undefined) break
1052
+ // What the last failed run could not reach; a later run that succeeds leaves nothing to say.
1053
+ delete result.failedAt
1054
+ // A run this manager terminated got no answer from the registry at all, so no registry explains it.
1055
+ if (run.timedOut === true) break
1056
+ const failedAt = attributeFailure(run.kind, run.output, parsedForRegistry(installSpec))
1057
+ if (failedAt !== 'other') result.failedAt = failedAt
1058
+ if (failedAt !== 'registry' || index === plan.length - 1) break
1059
+ }
1060
+ /* v8 ignore next -- the plan is never empty, so a run always settled */
1061
+ if (run === undefined) throw new Error('no registry was asked')
1062
+ // A terminated run reports no usable exit status, so neither its files nor its bundle are trusted.
1063
+ const succeeded = run.exitCode === 0 && run.timedOut !== true
1064
+ if (succeeded) delete result.failedAt
1065
+ if (!succeeded) {
1066
+ // pnpm-workspace.yaml is not restored, so the names it left undecided, or reported as blocked, are offered for approval.
1067
+ try { result.pendingBuilds = await recordPendingBuilds(this.profile.dir, run.output) }
1068
+ catch (error) {
1069
+ this.ownerContext.logger.warn('Could not read pending build approvals after pnpm failed', error)
1070
+ }
1071
+ throw new Error(run.output)
1072
+ }
1073
+ const after = readProfileManifest('dsh', this.profile.dir).dependencies ?? {}
1074
+ const installed = Object.keys(after).filter(name => before[name] !== after[name])
1075
+ // Without HMR a repeated installation can leave the saved dependency as it was.
1076
+ if (installed.length === 0) {
1077
+ const local = specPackageName(spec, after, this.profile.dir)
1078
+ if (local !== undefined && Object.hasOwn(after, local)) installed.push(local)
1079
+ }
1080
+ const target = installed[0]
1081
+ if (installed.length !== 1 || target === undefined) throw new ManagementFailure('ambiguous-install')
1082
+ name = target
1083
+ const dir = resolveBundleDir('dsh', name, this.profile.installAnchor, this.profile.dir)
1084
+ const manifest = bundleManifest(name, this.profile.dir, this.profile.installAnchor)
1085
+ if (manifest?.dsh?.bundle === undefined) throw new ManagementFailure('not-bundle')
1086
+ const compatibility = evaluatePluginCompatibility(manifest, readProfileVersionExemptions(this.profile.dir))
1087
+ if (compatibility !== undefined && !compatibility.exempted) throw new ManagementFailure('incompatible-version', [incompatiblePlugin(compatibility)])
1088
+ for (const file of bundlePatchPaths(dir, manifest.dsh.bundle)) loadOverlayPatches('dsh', file)
1089
+ version = manifest.version
1090
+ this.installedFrom.set(name, used)
1091
+ } catch (error) {
1092
+ // pnpm has exited by now, so the files it rewrote go back as they were.
1093
+ await this.restoreFiles(files)
1094
+ throw error
1095
+ }
1096
+ control.phase = 'applying'
1097
+ announce('applying')
1098
+ result.bundle = name
1099
+ if (version !== undefined) result.version = version
1100
+ result.target = name
1101
+ result.stage = 'enable'
1102
+ return this.configure(async () => {
1103
+ if (options?.enabled !== false) await this.selectBundle(name, true)
1104
+ // Without HMR the replaced package's plugins keep running until the restart the result already reports.
1105
+ if (Object.hasOwn(before, name) && this.ownerContext.get('hmr') === undefined) return
1106
+ // A selected bundle's own rows must start.
1107
+ const selected = bundleSelection(readProfileManifest('dsh', this.profile.dir)).includes(name)
1108
+ Object.assign(result, await this.publishAndReload(selected ? this.bundleRows(name).map(row => row.id) : []))
1109
+ })
1110
+ }, { stage: 'install', target: spec, enabled: options?.enabled !== false }, 'install')
1111
+ control.result = result
1112
+ return result.finally(() => { if (requestId !== undefined) this.installs.delete(requestId) })
1113
+ }
1114
+
1115
+ /** Recover the result of an active installation without cancelling it.
1116
+ * @param requestId The id supplied when installation started.
1117
+ * @returns The installation's outcome after it settles, or null if no active request has that id.
1118
+ * Completed results are not retained; null establishes neither success nor cancellation.
1119
+ */
1120
+ @Remote
1121
+ async waitForInstall(requestId: PluginInstallRequestId): Promise<ChangeResult | null> {
1122
+ return this.installs.get(requestId)?.result ?? null
1123
+ }
1124
+
1125
+ /** Stop an installation this manager owns and wait until its files are back.
1126
+ * @param requestId The id the installation was started with.
1127
+ * @returns `cancelled` once the Git check or pnpm exited and the files are restored, `too-late` once the bundle is being
1128
+ * applied, `not-running` for any other id.
1129
+ */
1130
+ @Remote
1131
+ async cancelInstall(requestId: PluginInstallRequestId): Promise<PluginInstallCancellation> {
1132
+ const control = this.installs.get(requestId)
1133
+ if (control === undefined) return { status: 'not-running' }
1134
+ if (control.phase === 'applying') return { status: 'too-late' }
1135
+ this.ownerContext.emit('plugin-manager/install-state', { requestId, phase: 'cancelling' })
1136
+ control.abort.abort()
1137
+ /* v8 ignore next -- change() folds every failure into its result; only a lock or disposal error rejects */
1138
+ await control.result.then(() => undefined, () => undefined)
1139
+ return { status: 'cancelled' }
1140
+ }
1141
+
1142
+ /** Unload and remove a profile-owned bundle dependency through dsh plugin's pnpm path; a selected name no
1143
+ * dependency holds is only deselected.
1144
+ * @param name Installed dependency or selected bundle name.
1145
+ * @returns Removal diagnostics and the remaining profile state.
1146
+ */
1147
+ @Remote
1148
+ removeBundle(name: string): Promise<ChangeResult> {
1149
+ return this.change(async (result) => {
1150
+ const installed = await this.configure(async () => {
1151
+ const bundle = (await this.listBundles()).find(item => item.name === name)
1152
+ if (bundle === undefined || !bundle.removable) throw new ManagementFailure('not-removable')
1153
+ if (this.ownerContext.get('hmr') === undefined && (this.profile.startedBundles.includes(name)
1154
+ || (bundle.error === undefined && this.bundleRows(name).some(row => [...this.ctx.loader.entries()]
1155
+ .some(entry => entry.options.id === row.id && entry.fiber !== undefined))))) {
1156
+ throw new ManagementFailure('stop-profile')
1157
+ }
1158
+ const contributions = bundle.error === undefined ? this.bundleRows(name) : []
1159
+ if (bundle.enabled) {
1160
+ await this.selectBundle(name, false)
1161
+ Object.assign(result, await this.reload())
1162
+ }
1163
+ if ([...this.ctx.loader.entries()].some(entry => entry.fiber?.uid != null
1164
+ && contributions.some(row => row.id === entry.options.id && row.name === entry.options.name))) {
1165
+ throw new ManagementFailure('bundle-in-use')
1166
+ }
1167
+ return bundle.installed
1168
+ })
1169
+ if (!installed) return
1170
+ // `pnpm remove` takes no `--registry` option; the generic configuration flag sets the same setting. A package
1171
+ // installed before this process started is removed with the registry an installation asks first.
1172
+ const registry = this.installedFrom.has(name) ? this.installedFrom.get(name) : this.configuredRegistries.registry
1173
+ result.packageResult = await this.runPnpm(['remove', name, ...typeof registry === 'string' ? [`--config.registry=${registry}`] : []])
1174
+ if (result.packageResult.exitCode !== 0 || result.packageResult.timedOut === true) {
1175
+ throw new Error(result.packageResult.output)
1176
+ }
1177
+ this.installedFrom.delete(name)
1178
+ Object.assign(result, await this.configure(() => this.publishAndReload()))
1179
+ }, { stage: 'remove', target: name }, 'remove')
1180
+ }
1181
+
1182
+ /** The rows a bundle's patch inserts and the existing rows it changes; an unreadable patch throws. */
1183
+ private declaredRows(name: string, info: ProfileManifest): Pick<BundleInfo, 'rows' | 'overrides'> {
1184
+ const bundle = info.dsh?.bundle
1185
+ /* v8 ignore next -- bundleManifest answers only manifests that declare a patch */
1186
+ if (bundle === undefined) return { rows: [], overrides: [] }
1187
+ const dir = resolveBundleDir('dsh', name, this.profile.installAnchor, this.profile.dir)
1188
+ const patches: PatchOptions[] = bundlePatchPaths(dir, bundle).flatMap(file => loadOverlayPatches('dsh', file))
1189
+ // One entry per row id: the Loader keeps a single entry for an id, whichever layer declared it last.
1190
+ const live = new Map<string, { entryId: PluginEntryId; baseUrl: string | undefined }>()
1191
+ for (const entry of this.ctx.loader.entries()) {
1192
+ /* v8 ignore next -- the Loader gives every entry an id before it is listed */
1193
+ if (typeof entry.options.id === 'string') live.set(entry.options.id, {
1194
+ entryId: pluginEntryId(entry.id), baseUrl: entry.parent.tree.ctx.baseUrl,
1195
+ })
1196
+ }
1197
+ const rows: BundleRowInfo[] = []
1198
+ const packages = this.ctx.get('pluginPackages')
1199
+ for (const row of flatten(composeEntries([patches.filter(item => item.insert !== undefined)]))) {
1200
+ // Group rows are containers without a plugin inventory entry; their children carry the switches.
1201
+ if (typeof row.id !== 'string' || typeof row.name !== 'string' || row.group === true) continue
1202
+ const active = live.get(row.id)
1203
+ const entryId = active?.entryId
1204
+ const base = active?.baseUrl ?? pathToFileURL(join(dir, 'package.json')).href
1205
+ const meta = packages?.metaOf(row.name, base)
1206
+ rows.push({ rowId: row.id, moduleName: row.name,
1207
+ ...entryId === undefined ? {} : { entryId }, ...meta === undefined ? {} : { meta } })
1208
+ }
1209
+ const declared = new Set(rows.map(row => row.rowId))
1210
+ const overrides = [...new Set(patches.flatMap(item =>
1211
+ item.insert === undefined && typeof item.id === 'string' && !declared.has(item.id) ? [item.id] : []))]
1212
+ return { rows, overrides }
1213
+ }
1214
+
1215
+ /** Run one pnpm command in the profile, streaming its output as install-log chunks; `expected` is the package an `add` must install. */
1216
+ private async runPnpm(
1217
+ args: readonly string[], signal?: AbortSignal, requestId?: PluginInstallRequestId, expected?: InstallBundleOptions['expected'],
1218
+ ): Promise<PackageResult> {
1219
+ const jobId = randomUUID()
1220
+ const argv = ['pnpm', ...args]
1221
+ const cwd = this.profile.dir
1222
+ const identity = requestId === undefined ? {} : { requestId }
1223
+ const task = runProfilePnpm({ ...this.profile, profile: this.profile.name }, args, {
1224
+ execution: 'service', ...this.profile.packageManager ?? { command: this.pnpmCommand },
1225
+ signal: signal === undefined ? this.abort.signal : AbortSignal.any([this.abort.signal, signal]),
1226
+ outputBytes: this.outputBytes, activateNewBundles: false, idleTimeoutMs: this.idleTimeoutMs,
1227
+ lookupTimeoutMs: this.inspectTimeoutMs, ...expected === undefined ? {} : { expected },
1228
+ onOutput: (text, stream) => {
1229
+ this.ownerContext.emit('plugin-manager/install-log', { ...identity, jobId, argv, cwd, stream, text })
1230
+ },
1231
+ })
1232
+ this.packageOperations.add(task)
1233
+ try {
1234
+ const result = await task
1235
+ this.ownerContext.emit('plugin-manager/install-log', {
1236
+ ...identity, jobId, argv, cwd, stream: 'stdout', text: '', exitCode: signal?.aborted === true ? null : result.exitCode,
1237
+ })
1238
+ // A terminated run keeps its own kind even when pnpm trapped the signal and exited 0.
1239
+ if (result.exitCode === 0 && result.timedOut !== true) return result
1240
+ return {
1241
+ ...result,
1242
+ kind: classifyInstallFailure({ log: result.output, ...result.timedOut === true ? { timedOut: true } : {} }),
1243
+ }
1244
+ } catch (error) {
1245
+ this.ownerContext.emit('plugin-manager/install-log', { ...identity, jobId, argv, cwd, stream: 'stderr', text: messageOf(error), exitCode: null })
1246
+ throw error
1247
+ } finally {
1248
+ this.packageOperations.delete(task)
1249
+ }
1250
+ }
1251
+
1252
+ /** The profile files an installation may rewrite, as they are now; absent files read as undefined. */
1253
+ private async readRestoredFiles(): Promise<Map<string, string | undefined>> {
1254
+ const files = new Map<string, string | undefined>()
1255
+ for (const name of RESTORED_FILES) {
1256
+ const path = join(this.profile.dir, name)
1257
+ files.set(path, existsSync(path) ? await readFile(path, 'utf8') : undefined)
1258
+ }
1259
+ return files
1260
+ }
1261
+
1262
+ /** Put the profile files back; pnpm has exited by the time this runs. */
1263
+ private async restoreFiles(files: Map<string, string | undefined>): Promise<void> {
1264
+ for (const [path, content] of files) {
1265
+ if (content === undefined) await rm(path, { force: true })
1266
+ else await writeFileAtomic(path, content, { mode: 0o600 })
1267
+ }
1268
+ }
1269
+
1270
+ private async selectBundle(name: string, enabled: boolean): Promise<void> {
1271
+ const manifest = readProfileManifest('dsh', this.profile.dir)
1272
+ const previous = bundleSelection(manifest)
1273
+ if (enabled || !previous.includes(name)) {
1274
+ const metadata = bundleManifest(name, this.profile.dir, this.profile.installAnchor)
1275
+ if (metadata === undefined) throw new ManagementFailure('not-bundle')
1276
+ if (enabled) {
1277
+ assertBundlePlatform(metadata.dsh?.bundle?.platforms, process.platform)
1278
+ const compatibility = evaluatePluginCompatibility(metadata, readProfileVersionExemptions(this.profile.dir))
1279
+ if (compatibility !== undefined && !compatibility.exempted) throw new ManagementFailure('incompatible-version', [incompatiblePlugin(compatibility)])
1280
+ this.bundleRows(name)
1281
+ }
1282
+ }
1283
+ if (!enabled && previous.includes(name)) {
1284
+ if (this.protectsManager(name)) throw new ManagementFailure('management-required')
1285
+ }
1286
+ const bundles = enabled ? [...previous, ...previous.includes(name) ? [] : [name]] : previous.filter(item => item !== name)
1287
+ if (JSON.stringify(previous) === JSON.stringify(bundles)) return
1288
+ manifest.dsh = { ...manifest.dsh, profile: { ...manifest.dsh?.profile, bundles } }
1289
+ await saveManifest(this.profile.dir, manifest)
1290
+ if (enabled) this.protectsManager(name)
1291
+ }
1292
+
1293
+ private bundleRows(name: string): EntryOptions[] {
1294
+ const info = bundleManifest(name, this.profile.dir, this.profile.installAnchor)
1295
+ if (info?.dsh?.bundle === undefined) return []
1296
+ const dir = resolveBundleDir('dsh', name, this.profile.installAnchor, this.profile.dir)
1297
+ return flatten(composeEntries([bundlePatchPaths(dir, info.dsh.bundle).flatMap(file => loadOverlayPatches('dsh', file))]))
1298
+ }
1299
+
1300
+ private protectsManager(name: string): boolean {
1301
+ if (this.managementBundles.has(name)) return true
1302
+ let rows: EntryOptions[]
1303
+ try { rows = this.bundleRows(name) } catch (_error) {
1304
+ // Unreadable bundles contribute no new rows; listBundles reports their diagnostics.
1305
+ return false
1306
+ }
1307
+ const protectedBundle = rows.some(row => PROTECTED_PLUGINS.has(row.name) || `include:${row.id}` === this.ownerEntryId)
1308
+ if (protectedBundle) this.managementBundles.add(name)
1309
+ return protectedBundle
1310
+ }
1311
+
1312
+ private configure<T>(operation: () => Promise<T>): Promise<T> {
1313
+ const hmr = this.ownerContext.get('hmr')
1314
+ const apply = () => { this.abort.signal.throwIfAborted(); return operation() }
1315
+ return hmr === undefined ? apply() : hmr.runExclusive(apply)
1316
+ }
1317
+
1318
+ /**
1319
+ * Publish the profile's runtime resolution without HMR, unless a deselected startup bundle still runs and needs the
1320
+ * current table. A publication that needs a restart waits for the restart the result already reports.
1321
+ */
1322
+ private async refreshPackages(): Promise<void> {
1323
+ const selected = bundleSelection(readProfileManifest('dsh', this.profile.dir))
1324
+ if (this.profile.startedBundles.some(name => !selected.includes(name))) return
1325
+ try {
1326
+ const packages = this.ownerContext.get('pluginPackages')
1327
+ // A dropped mapping's bundle is not running: the guard above keeps the table while a deselected startup bundle runs.
1328
+ if (packages?.resolution !== undefined) await packages.refresh()
1329
+ } catch (error) {
1330
+ if (!(error instanceof ResolutionRestartRequired)) throw error
1331
+ }
1332
+ }
1333
+
1334
+ /**
1335
+ * Apply a package change: without HMR, publish the runtime resolution when that is safe, then {@link reload}.
1336
+ * @param requiredIds Entry ids that must start.
1337
+ * @returns The reload's outcome.
1338
+ */
1339
+ private async publishAndReload(requiredIds: readonly string[] = []): Promise<Reload> {
1340
+ if (this.ownerContext.get('hmr') === undefined) await this.refreshPackages()
1341
+ return this.reload(requiredIds)
1342
+ }
1343
+
1344
+ /**
1345
+ * Apply the saved profile; with HMR it recomposes live, including the runtime resolution.
1346
+ * @param requiredIds Entry ids that must start.
1347
+ * @returns Warnings about entries that were already inactive, and why the change waits for a restart, if it does.
1348
+ */
1349
+ private async reload(requiredIds: readonly string[] = []): Promise<Reload> {
1350
+ const hmr = this.ownerContext.get('hmr')
1351
+ if (hmr === undefined) {
1352
+ // Startup-only profiles recompose at restart; the saved patches still have to compose.
1353
+ composeEntries([readProfilePatches('dsh', this.profile)])
1354
+ return { warnings: [] }
1355
+ }
1356
+ const { warnings, pending, restartReason } = await hmr.reconcileProfile(requiredIds)
1357
+ const restart = restartReason ?? pending[0]?.reason
1358
+ return restart === undefined ? { warnings } : { warnings, restartReason: restart }
1359
+ }
1360
+
1361
+ private async change(
1362
+ operation: (result: ChangeResult) => Promise<ChangeResult['application'] | void>,
1363
+ request: Pick<ChangeResult, 'stage' | 'target' | 'enabled'>,
1364
+ reason: PluginChange['reason'],
1365
+ identity?: Pick<PluginOperation, 'target' | 'version'>,
1366
+ ): Promise<ChangeResult> {
1367
+ const id = randomUUID() as PluginOperationId
1368
+ const target = identity === undefined ? this.operationTarget(reason, request.target) : identity.target
1369
+ const version = identity === undefined ? this.operationVersion(reason, reason === 'plugin' ? request.target : target) : identity.version
1370
+ const facts = { id, reason, stage: request.stage,
1371
+ target,
1372
+ ...version === undefined ? {} : { version },
1373
+ ...request.enabled === undefined ? {} : { enabled: request.enabled } }
1374
+ this.reportOperation({ ...facts, time: new Date().toISOString(), phase: 'started' })
1375
+ let settled: ChangeResult
1376
+ try {
1377
+ settled = await withFileLock(join(this.profile.dir, 'package.json'), async () => {
1378
+ this.abort.signal.throwIfAborted()
1379
+ const before = this.diskState()
1380
+ const result: ChangeResult = { ...request, changed: false,
1381
+ ...this.ownerContext.get('hmr') !== undefined ? { application: 'applied' } : { application: 'restart-required', restartReason: 'no-hmr' } }
1382
+ try {
1383
+ const outcome = await operation(result)
1384
+ if (outcome !== undefined) result.application = outcome
1385
+ // A reload that waits for a restart leaves the change saved but not applied.
1386
+ else if (result.application === 'applied' && result.restartReason !== undefined) result.application = 'restart-required'
1387
+ } catch (error) {
1388
+ if (error instanceof InstallCancelledError) {
1389
+ result.application = 'cancelled'
1390
+ } else {
1391
+ result.application = 'failed'
1392
+ result.error = managementError(error)
1393
+ }
1394
+ }
1395
+ if (result.application !== 'restart-required') delete result.restartReason
1396
+ result.changed = before !== this.diskState()
1397
+ this.ownerContext.emit('plugin-manager/changed', { reason })
1398
+ return result
1399
+ }, { waitMs: this.lockWaitMs })
1400
+ } catch (error) {
1401
+ this.reportOperation({ ...facts, time: new Date().toISOString(), phase: 'unknown' })
1402
+ throw error
1403
+ }
1404
+ const refusedVersion = reason === 'install'
1405
+ ? settled.error?.incompatible?.find(plugin => plugin.name === facts.target)?.version
1406
+ : undefined
1407
+ const observedVersion = diagnosticVersion(settled.version ?? refusedVersion)
1408
+ this.reportOperation({ ...facts, time: new Date().toISOString(), phase: 'settled',
1409
+ stage: settled.stage, target: settled.bundle === undefined ? facts.target : installOperationTarget(settled.bundle),
1410
+ application: settled.application, changed: settled.changed,
1411
+ ...observedVersion === undefined ? {} : { version: observedVersion },
1412
+ ...settled.error === undefined ? {} : { errorCode: settled.error.code },
1413
+ ...settled.restartReason === undefined ? {} : { restartReason: settled.restartReason } })
1414
+ return settled
1415
+ }
1416
+
1417
+ private reportOperation(operation: PluginOperation): void {
1418
+ void this.ownerContext.parallel('plugin-manager/operation', operation).catch((_error: unknown) => {
1419
+ // All subscribers run; diagnostic failures cannot change the management result.
1420
+ console.error('dsh plugin-manager: operation diagnostic delivery failed')
1421
+ })
1422
+ }
1423
+
1424
+ private operationTarget(reason: PluginChange['reason'], target: string): string | null {
1425
+ if (reason !== 'plugin') {
1426
+ const name = installOperationTarget(target)
1427
+ return reason === 'install' || name === target ? name : null
1428
+ }
1429
+ return target.length <= 256 && [...this.ctx.loader.entries()].some(entry => entry.id === target) ? target : null
1430
+ }
1431
+
1432
+ /** Read the request-time package version without preventing recovery from damaged metadata. */
1433
+ private operationVersion(reason: PluginChange['reason'], target: string | null): string | undefined {
1434
+ if (reason === 'install' || target === null) return undefined
1435
+ try {
1436
+ if (reason !== 'plugin') return diagnosticVersion(bundleManifest(target, this.profile.dir, this.profile.installAnchor)?.version)
1437
+ const entry = [...this.ctx.loader.entries()].find(row => row.id === target)
1438
+ const source = entry?.parent.tree.ctx.baseUrl
1439
+ if (entry === undefined || source === undefined) return undefined
1440
+ return diagnosticVersion(this.ownerContext.get('pluginPackages')?.packageOf(entry.options.name, source)?.version)
1441
+ } catch (_error) {
1442
+ // Disabling or removing a broken package must not depend on diagnostic metadata being readable.
1443
+ return undefined
1444
+ }
1445
+ }
1446
+
1447
+ private diskState(): string {
1448
+ return ['package.json', 'cordis.patch.yml', 'pnpm-workspace.yaml', PROFILE_COMPATIBILITY_FILENAME].map((file) => {
1449
+ try { return readFileSync(join(this.profile.dir, file), 'utf8') }
1450
+ catch (error) {
1451
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return ''
1452
+ throw error
1453
+ }
1454
+ }).join('\0')
1455
+ }
1456
+ }
1457
+
1458
+ export default PluginManager