dsh-ntr 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/update.ts ADDED
@@ -0,0 +1,712 @@
1
+ /**
2
+ * Host-side built-in update for dsh-ntr.
3
+ *
4
+ * The plugin NEVER downloads a package, swaps files, or restarts itself. The
5
+ * harness plugin manager owns installation (profile bookkeeping, npm, the
6
+ * restart contract); this module only asks it what is installed, asks an npm
7
+ * registry what is published, and delegates the install back to the manager.
8
+ * Every method therefore reports a {@link PluginUpdateState} instead of
9
+ * throwing; version syntax is validated at the RPC boundary (`impl.ts`).
10
+ */
11
+
12
+ import type { PluginUpdateState } from './protocol.ts'
13
+
14
+ /** The npm package this plugin is published as, and the bundle name to look for. */
15
+ export const UPDATE_PACKAGE = 'dsh-ntr'
16
+
17
+ /** One npm registry request must answer within this window before the next is tried. */
18
+ const REGISTRY_TIMEOUT_MS = 8_000
19
+ /** A successful packument answer is reused for this long (per registry base). */
20
+ const CACHE_TTL_MS = 10 * 60 * 1000
21
+ /** Only stable releases are offered for install. */
22
+ const STABLE_VERSION = /^\d+\.\d+\.\d+$/
23
+ /** npm's public registry; the only base a private `resolved` may be widened to. */
24
+ export const NPM_PUBLIC_REGISTRY = 'https://registry.npmjs.org'
25
+ /** A version spec that resolves through a registry (as opposed to a link/tarball/git). */
26
+ const REGISTRY_VERSION_SPEC = /^(?:[\^~]|>=|<=|>|<|=)?\s*v?\d+(?:\.(?:\d+|[xX*])){0,2}(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/
27
+ /** Dist-tags that name a published release line rather than a local path. */
28
+ const REGISTRY_TAGS = new Set(['latest', 'next', 'beta', 'alpha', 'rc', 'stable'])
29
+
30
+ /**
31
+ * Structural view of one row from the harness plugin manager's
32
+ * `listBundles()`. Deliberately local: importing the host package would tie
33
+ * this module to a runtime version it must merely probe structurally.
34
+ */
35
+ export interface UpdateBundleInfo {
36
+ name: string; installed: boolean; removable?: boolean; enabled?: boolean
37
+ version?: string; source?: string; readOnlyReason?: string
38
+ error?: { code?: string; message?: string; diagnostic?: string }
39
+ }
40
+ /** Structural view of `pluginManager.registries()`. */
41
+ export interface UpdateRegistryPlan {
42
+ registry?: string | null; fallbackRegistries?: readonly string[]; resolved?: string | null
43
+ }
44
+ /** Structural view of the manager's `installBundle()` / `removeBundle()` result (a ChangeResult). */
45
+ export interface UpdateInstallResult {
46
+ application?: string; version?: string
47
+ error?: { code?: string; message?: string; diagnostic?: string }
48
+ }
49
+ /** The plugin-manager face this service needs. Every member is probed, never assumed. */
50
+ export interface UpdateManagerLike {
51
+ listBundles?(): Promise<readonly UpdateBundleInfo[]>
52
+ registries?(): Promise<UpdateRegistryPlan>
53
+ installBundle?(spec: string, options?: { enabled?: boolean; registry?: string }): Promise<UpdateInstallResult | undefined>
54
+ /**
55
+ * Native-update half of the harness: `installBundle` refuses to replace an
56
+ * already-installed bundle while HMR holds it, so the host removes first.
57
+ * Optional — older hosts cannot install at all and answer `already-installed`.
58
+ */
59
+ removeBundle?(name: string): Promise<UpdateInstallResult | undefined>
60
+ }
61
+
62
+ /**
63
+ * The shared eligibility verdict. `ok` carries the disk version (when the host
64
+ * reports one); the failure arm is already a full state, so check/apply can
65
+ * return it verbatim.
66
+ */
67
+ export type BundleEligibility =
68
+ | { ok: true; installed?: string }
69
+ | { ok: false; state: PluginUpdateState }
70
+
71
+ function messageOf(error: unknown): string {
72
+ if (error instanceof Error) return error.message
73
+ if (typeof error === 'string') return error
74
+ if (typeof error === 'object' && error !== null) {
75
+ const message = (error as Record<string, unknown>).message
76
+ if (typeof message === 'string') return message
77
+ }
78
+ return String(error)
79
+ }
80
+
81
+ /**
82
+ * The host's ChangeResult carries the human-readable cause in `diagnostic`
83
+ * (a `message` field is not always populated). Prefer it, then `message`, and
84
+ * keep the code prefix because the UI shows this verbatim.
85
+ */
86
+ function describeFieldError(error: { code?: string; message?: string; diagnostic?: string }): string {
87
+ const text = [error.diagnostic, error.message]
88
+ .find((part): part is string => typeof part === 'string' && part !== '')
89
+ const parts = [error.code, text]
90
+ .filter((part): part is string => typeof part === 'string' && part !== '')
91
+ return parts.length > 0 ? parts.join(': ') : 'the host reported a bundle error'
92
+ }
93
+
94
+ /** The version-spec half of a registry source: a range, wildcard, or dist-tag. */
95
+ function isRegistryRange(value: string): boolean {
96
+ if (value === '') return false
97
+ const lowered = value.toLowerCase()
98
+ if (lowered === '*' || lowered === 'x') return true
99
+ if (REGISTRY_TAGS.has(lowered)) return true
100
+ return REGISTRY_VERSION_SPEC.test(value)
101
+ }
102
+
103
+ /**
104
+ * Whether a `listBundles().source` value names a registry-resolvable version
105
+ * spec — the only install shape this updater may replace. The harness records
106
+ * a registry dependency as `<package>@<spec>` (`dependencySpec` in the plugin
107
+ * manager), so the spec half after the last `@` is what gets judged. The test
108
+ * is positive on purpose: link/file/git/workspace/URL/tarball/relative forms
109
+ * all carry a `:` / `/` / `\` or start with `.`, so they fall out without an
110
+ * ever-growing blacklist (a new source scheme must not become silently
111
+ * updatable).
112
+ */
113
+ export function isRegistrySpec(source: string): boolean {
114
+ const value = typeof source === 'string' ? source.trim() : ''
115
+ if (value === '') return false
116
+ if (value.startsWith('.')) return false
117
+ if (value.includes(':') || value.includes('/') || value.includes('\\')) return false
118
+ const at = value.lastIndexOf('@')
119
+ if (at === -1) return isRegistryRange(value)
120
+ const name = value.slice(0, at)
121
+ if (!/^[a-z0-9][a-z0-9._-]*$/i.test(name)) return false
122
+ return isRegistryRange(value.slice(at + 1))
123
+ }
124
+
125
+ /**
126
+ * Compare two semver strings (build metadata ignored, prerelease precedence per
127
+ * semver §11). Malformed segments count as `0`, so the function never throws on
128
+ * a value read off a registry.
129
+ */
130
+ export function compareVersions(a: string, b: string): number {
131
+ const parse = (raw: string): { core: number[]; pre?: string[] } => {
132
+ let value = raw.trim()
133
+ if (value.startsWith('v') || value.startsWith('V')) value = value.slice(1)
134
+ const plus = value.indexOf('+')
135
+ if (plus >= 0) value = value.slice(0, plus)
136
+ const dash = value.indexOf('-')
137
+ const corePart = dash >= 0 ? value.slice(0, dash) : value
138
+ const prePart = dash >= 0 ? value.slice(dash + 1) : undefined
139
+ const core = corePart.split('.').map(segment => {
140
+ const parsed = Number.parseInt(segment, 10)
141
+ return Number.isFinite(parsed) ? parsed : 0
142
+ })
143
+ return { core, pre: prePart === undefined || prePart === '' ? undefined : prePart.split('.') }
144
+ }
145
+ const left = parse(a)
146
+ const right = parse(b)
147
+ const length = Math.max(left.core.length, right.core.length, 3)
148
+ for (let i = 0; i < length; i += 1) {
149
+ const l = left.core[i] ?? 0
150
+ const r = right.core[i] ?? 0
151
+ if (l !== r) return l < r ? -1 : 1
152
+ }
153
+ if (left.pre === undefined && right.pre === undefined) return 0
154
+ if (left.pre === undefined) return 1
155
+ if (right.pre === undefined) return -1
156
+ const preLength = Math.max(left.pre.length, right.pre.length)
157
+ for (let i = 0; i < preLength; i += 1) {
158
+ const l = left.pre[i]
159
+ const r = right.pre[i]
160
+ if (l === undefined) return -1
161
+ if (r === undefined) return 1
162
+ const lNumeric = /^\d+$/.test(l)
163
+ const rNumeric = /^\d+$/.test(r)
164
+ if (lNumeric && rNumeric) {
165
+ const lNum = Number(l)
166
+ const rNum = Number(r)
167
+ if (lNum !== rNum) return lNum < rNum ? -1 : 1
168
+ continue
169
+ }
170
+ if (lNumeric !== rNumeric) return lNumeric ? -1 : 1
171
+ if (l !== r) return l < r ? -1 : 1
172
+ }
173
+ return 0
174
+ }
175
+
176
+ /**
177
+ * Turn the manager's registry plan into the ordered list this service will
178
+ * actually query, following the host's privacy rule: a *private* `resolved`
179
+ * registry must not be widened with the shared fallback chain.
180
+ *
181
+ * - No configured registry: query `resolved`; append fallbacks only when it is
182
+ * npm's public registry or one of the fallbacks themselves.
183
+ * - Configured registry: query it first, then `resolved` under the same
184
+ * condition, then the fallbacks.
185
+ *
186
+ * http(s) only (a private http registry is legitimate), trailing slashes
187
+ * normalized, duplicates dropped. A base that carries credentials in its URL is
188
+ * skipped: a bare GET cannot replay `.npmrc` auth, so it could only fail with a
189
+ * 401 that reads as "unreachable".
190
+ */
191
+ export function registryPlan(plan: UpdateRegistryPlan): string[] {
192
+ const normalize = (value: unknown): string | undefined => {
193
+ if (typeof value !== 'string') return undefined
194
+ const trimmed = value.trim().replace(/\/+$/, '')
195
+ if (!/^https?:\/\//i.test(trimmed)) return undefined
196
+ // Credentials in the URL cannot be replayed here: a bare GET would need the
197
+ // `.npmrc` auth the host keeps to itself, so such a base is never queried.
198
+ if (/^https?:\/\/[^/]*@/i.test(trimmed)) return undefined
199
+ return trimmed
200
+ }
201
+ const fallbacks: string[] = []
202
+ for (const fallback of plan.fallbackRegistries ?? []) {
203
+ const normalized = normalize(fallback)
204
+ if (normalized !== undefined && !fallbacks.includes(normalized)) fallbacks.push(normalized)
205
+ }
206
+ const resolved = normalize(plan.resolved)
207
+ const configured = normalize(plan.registry)
208
+ const shared = resolved !== undefined
209
+ && (resolved.toLowerCase() === NPM_PUBLIC_REGISTRY || fallbacks.includes(resolved))
210
+ const out: string[] = []
211
+ const add = (value: string | undefined): void => {
212
+ if (value === undefined || out.includes(value)) return
213
+ out.push(value)
214
+ }
215
+ if (configured !== undefined) {
216
+ add(configured)
217
+ if (shared) add(resolved)
218
+ for (const fallback of fallbacks) add(fallback)
219
+ } else if (resolved !== undefined) {
220
+ add(resolved)
221
+ if (shared) for (const fallback of fallbacks) add(fallback)
222
+ }
223
+ return out
224
+ }
225
+
226
+ /**
227
+ * Pick the version an update should offer.
228
+ *
229
+ * `dist-tags.latest` leads when it is a stable release newer than `current`
230
+ * (that is the line npm itself blesses). Otherwise the highest stable,
231
+ * non-deprecated published version wins — a lagging `latest` tag must not hide
232
+ * a newer release. When nothing is newer, the stable `latest` tag is still
233
+ * returned so the UI can say "you are on the latest release".
234
+ */
235
+ export function pickUpdateTarget(packument: unknown, current: string): { version?: string; publishedAt?: string } {
236
+ const row = typeof packument === 'object' && packument !== null ? packument as Record<string, unknown> : {}
237
+ const time = typeof row.time === 'object' && row.time !== null ? row.time as Record<string, unknown> : {}
238
+ const publishedAt = (version: string): string | undefined => {
239
+ const value = time[version]
240
+ return typeof value === 'string' ? value : undefined
241
+ }
242
+ const tags = typeof row['dist-tags'] === 'object' && row['dist-tags'] !== null
243
+ ? row['dist-tags'] as Record<string, unknown>
244
+ : undefined
245
+ const versions = typeof row.versions === 'object' && row.versions !== null
246
+ ? row.versions as Record<string, unknown>
247
+ : undefined
248
+ // A string `deprecated` is npm's tombstone; never offer that release.
249
+ const deprecated = (version: string): boolean => {
250
+ const meta = versions?.[version]
251
+ return typeof meta === 'object' && meta !== null
252
+ && typeof (meta as Record<string, unknown>).deprecated === 'string'
253
+ }
254
+ // `latest` only leads when the registry did not tombstone that very release.
255
+ const latest = typeof tags?.latest === 'string' && STABLE_VERSION.test(tags.latest) && !deprecated(tags.latest)
256
+ ? tags.latest
257
+ : undefined
258
+ if (latest !== undefined && compareVersions(latest, current) > 0) {
259
+ return { version: latest, publishedAt: publishedAt(latest) }
260
+ }
261
+ let best: string | undefined
262
+ for (const [version, meta] of Object.entries(versions ?? {})) {
263
+ if (!STABLE_VERSION.test(version)) continue
264
+ if (typeof meta === 'object' && meta !== null && typeof (meta as Record<string, unknown>).deprecated === 'string') continue
265
+ if (best === undefined || compareVersions(version, best) > 0) best = version
266
+ }
267
+ if (best !== undefined && compareVersions(best, current) > 0) {
268
+ return { version: best, publishedAt: publishedAt(best) }
269
+ }
270
+ if (latest !== undefined) return { version: latest, publishedAt: publishedAt(latest) }
271
+ return {}
272
+ }
273
+
274
+ /**
275
+ * Pure eligibility matrix, shared by check and apply.
276
+ *
277
+ * `undefined` means the manager (or one of its methods) is unavailable; an
278
+ * empty list means the manager answered but does not carry this plugin.
279
+ */
280
+ export function bundleEligibility(
281
+ bundles: readonly UpdateBundleInfo[] | undefined,
282
+ currentVersion: string,
283
+ ): BundleEligibility {
284
+ if (bundles === undefined) {
285
+ return {
286
+ ok: false,
287
+ state: {
288
+ status: 'unsupported',
289
+ current: currentVersion,
290
+ message: 'host does not expose the plugin manager',
291
+ },
292
+ }
293
+ }
294
+ const bundle = bundles.find(entry => entry.name === UPDATE_PACKAGE)
295
+ if (bundle === undefined || bundle.installed !== true) {
296
+ return { ok: false, state: { status: 'not-installed', current: currentVersion } }
297
+ }
298
+ const source = typeof bundle.source === 'string' ? bundle.source.trim() : ''
299
+ if (source === '') {
300
+ return {
301
+ ok: false,
302
+ state: {
303
+ status: 'unsupported',
304
+ current: currentVersion,
305
+ message: 'the host does not report where this plugin was installed from',
306
+ },
307
+ }
308
+ }
309
+ if (!isRegistrySpec(source)) {
310
+ // link: / file: / git+ / git@ / github: / workspace: / https tarball /
311
+ // relative path — the disk payload is not what the registry publishes.
312
+ return { ok: false, state: { status: 'source-install', current: currentVersion } }
313
+ }
314
+ if (bundle.removable === false) {
315
+ // The host refuses to unload it, so the remove-then-install path can only fail.
316
+ return {
317
+ ok: false,
318
+ state: {
319
+ status: 'managed',
320
+ current: currentVersion,
321
+ message: 'the host marks this bundle as not removable',
322
+ },
323
+ }
324
+ }
325
+ const readOnlyReason = typeof bundle.readOnlyReason === 'string' ? bundle.readOnlyReason.trim() : ''
326
+ if (readOnlyReason !== '') {
327
+ return {
328
+ ok: false,
329
+ state: { status: 'managed', current: currentVersion, message: readOnlyReason },
330
+ }
331
+ }
332
+ if (bundle.error !== undefined) {
333
+ return {
334
+ ok: false,
335
+ state: { status: 'failed', current: currentVersion, message: describeFieldError(bundle.error) },
336
+ }
337
+ }
338
+ const diskVersion = typeof bundle.version === 'string' && bundle.version.trim() !== ''
339
+ ? bundle.version.trim()
340
+ : undefined
341
+ if (diskVersion !== undefined && compareVersions(diskVersion, currentVersion) !== 0) {
342
+ // Installed on disk but the running host still has the old code loaded.
343
+ // Compare semantically: `v1.1.0` / `1.1.0+build` are the same release.
344
+ return {
345
+ ok: false,
346
+ state: {
347
+ status: 'restart-required',
348
+ current: currentVersion,
349
+ installed: diskVersion,
350
+ },
351
+ }
352
+ }
353
+ return { ok: true, ...(diskVersion === undefined ? {} : { installed: diskVersion }) }
354
+ }
355
+
356
+ /** Unwrap the manager's ChangeResult from the remote `{ok, value}` envelope. */
357
+ function unwrapInstallResult(raw: unknown): UpdateInstallResult | undefined {
358
+ if (raw === undefined || raw === null || typeof raw !== 'object') return undefined
359
+ const row = raw as Record<string, unknown>
360
+ if (typeof row.ok === 'boolean') {
361
+ if (!row.ok) {
362
+ const error = row.error
363
+ const shaped = typeof error === 'object' && error !== null ? error as Record<string, unknown> : {}
364
+ const message = typeof shaped.message === 'string'
365
+ ? shaped.message
366
+ : typeof error === 'string' ? error : undefined
367
+ return {
368
+ error: {
369
+ ...(typeof shaped.code === 'string' ? { code: shaped.code } : {}),
370
+ ...(typeof shaped.diagnostic === 'string' ? { diagnostic: shaped.diagnostic } : {}),
371
+ ...(message === undefined ? {} : { message }),
372
+ },
373
+ }
374
+ }
375
+ return unwrapInstallResult(row.value)
376
+ }
377
+ return row as unknown as UpdateInstallResult
378
+ }
379
+
380
+ /** Whether a ChangeResult means the requested tree is installed (restart or hot). */
381
+ function isInstallSuccess(result: UpdateInstallResult | undefined): result is UpdateInstallResult & { application: 'applied' | 'restart-required' } {
382
+ return result !== undefined && result.error === undefined
383
+ && (result.application === 'applied' || result.application === 'restart-required')
384
+ }
385
+
386
+ /**
387
+ * Whether a `removeBundle` ChangeResult really unloaded the tree. Only "no
388
+ * error and nothing contradicting the removal" counts: a `cancelled` /
389
+ * `overridden` / `failed` application without an `error` still leaves the
390
+ * bundle on disk, so retrying the install would hit `already-installed` again.
391
+ */
392
+ function isRemoveSuccess(result: UpdateInstallResult | undefined): boolean {
393
+ if (result === undefined) return true
394
+ if (result.error !== undefined) return false
395
+ return result.application === undefined
396
+ || result.application === 'applied'
397
+ || result.application === 'restart-required'
398
+ }
399
+
400
+ /** A registry URL fit for a message: credentials stripped, no trailing slash. */
401
+ function displayRegistry(base: string): string {
402
+ try {
403
+ const url = new URL(base)
404
+ url.username = ''
405
+ url.password = ''
406
+ return url.toString().replace(/\/+$/, '')
407
+ } catch {
408
+ return base.replace(/\/\/[^/@]*@/, '//')
409
+ }
410
+ }
411
+
412
+ export interface UpdateServiceOptions {
413
+ resolveManager(): UpdateManagerLike | undefined
414
+ currentVersion: string
415
+ isBusy(): boolean
416
+ fetchImpl?: typeof fetch
417
+ now?: () => number
418
+ }
419
+
420
+ /**
421
+ * Update checks and installs, memoized per registry base.
422
+ *
423
+ * Caching exists because the settings page polls: a 10-minute window keeps the
424
+ * check honest without turning every mount into a registry round trip. Apply
425
+ * clears the cache so the next check sees the freshly installed version.
426
+ */
427
+ export class UpdateService {
428
+ private readonly resolveManager: () => UpdateManagerLike | undefined
429
+ private readonly currentVersion: string
430
+ private readonly isBusy: () => boolean
431
+ private readonly fetchImpl: typeof fetch
432
+ private readonly now: () => number
433
+ private readonly cache = new Map<string, { at: number; target: { version?: string; publishedAt?: string } }>()
434
+ private applying = false
435
+ /** Registry that answered the last `available` check, passed through to apply. */
436
+ private lastTarget?: { version: string; registry: string }
437
+
438
+ constructor(options: UpdateServiceOptions) {
439
+ this.resolveManager = options.resolveManager
440
+ this.currentVersion = options.currentVersion
441
+ this.isBusy = options.isBusy
442
+ this.fetchImpl = options.fetchImpl ?? fetch
443
+ this.now = options.now ?? Date.now
444
+ }
445
+
446
+ /** The manager surface plus the disk-version verdict, or a ready-to-return failure state. */
447
+ private async eligibility(): Promise<BundleEligibility> {
448
+ const manager = this.resolveManager()
449
+ if (manager === undefined
450
+ || typeof manager.listBundles !== 'function'
451
+ || typeof manager.registries !== 'function'
452
+ || typeof manager.installBundle !== 'function') {
453
+ return bundleEligibility(undefined, this.currentVersion)
454
+ }
455
+ try {
456
+ return bundleEligibility(await manager.listBundles(), this.currentVersion)
457
+ } catch (error) {
458
+ return { ok: false, state: { status: 'failed', current: this.currentVersion, message: messageOf(error) } }
459
+ }
460
+ }
461
+
462
+ private async fetchTarget(base: string): Promise<{ version?: string; publishedAt?: string }> {
463
+ const response = await this.fetchImpl(`${base}/${UPDATE_PACKAGE}`, {
464
+ headers: { accept: 'application/json' },
465
+ signal: AbortSignal.timeout(REGISTRY_TIMEOUT_MS),
466
+ })
467
+ if (!response.ok) throw new Error(`registry ${base} answered ${String(response.status)}`)
468
+ return pickUpdateTarget(await response.json() as unknown, this.currentVersion)
469
+ }
470
+
471
+ /** One registry's packument, via the 10-minute cache. Throws when unreachable. */
472
+ private async targetFor(base: string): Promise<{ version?: string; publishedAt?: string }> {
473
+ const cached = this.cache.get(base)
474
+ if (cached !== undefined && this.now() - cached.at < CACHE_TTL_MS) return cached.target
475
+ const target = await this.fetchTarget(base)
476
+ this.cache.set(base, { at: this.now(), target })
477
+ return target
478
+ }
479
+
480
+ /**
481
+ * Ask the manager's registry chain what is published; never installs.
482
+ *
483
+ * A mirror may lag behind the rest of the chain, so a base that only knows
484
+ * the running (or an older) release does not end the walk — the next base
485
+ * gets its turn. `busy` is deliberately not checked here: reading a registry
486
+ * costs no ACP work, and the settings card should still be able to say what
487
+ * is out there while a turn runs.
488
+ */
489
+ async check(): Promise<PluginUpdateState> {
490
+ const current = this.currentVersion
491
+ if (this.applying) return { status: 'applying', current }
492
+ this.lastTarget = undefined
493
+ const eligible = await this.eligibility()
494
+ if (!eligible.ok) return eligible.state
495
+ const installed = eligible.installed === undefined ? {} : { installed: eligible.installed }
496
+ const manager = this.resolveManager()
497
+ let plan: UpdateRegistryPlan
498
+ try {
499
+ plan = (await manager?.registries?.()) ?? {}
500
+ } catch (error) {
501
+ return { status: 'failed', current, message: messageOf(error), ...installed }
502
+ }
503
+ const bases = registryPlan(plan)
504
+ const tried: string[] = []
505
+ let best: { version: string; publishedAt?: string } | undefined
506
+ let reached = 0
507
+ for (const base of bases) {
508
+ tried.push(base)
509
+ let target: { version?: string; publishedAt?: string }
510
+ try {
511
+ target = await this.targetFor(base)
512
+ } catch {
513
+ // Unreachable registry: the next one in the chain gets its turn.
514
+ continue
515
+ }
516
+ reached += 1
517
+ const latest = target.version
518
+ if (latest === undefined) continue
519
+ if (best === undefined || compareVersions(latest, best.version) > 0) {
520
+ best = { version: latest, ...(target.publishedAt === undefined ? {} : { publishedAt: target.publishedAt }) }
521
+ }
522
+ if (compareVersions(latest, current) > 0) {
523
+ if (this.applying) return { status: 'applying', current }
524
+ this.lastTarget = { version: latest, registry: base }
525
+ return {
526
+ status: 'available',
527
+ current,
528
+ latest,
529
+ ...(target.publishedAt === undefined ? {} : { publishedAt: target.publishedAt }),
530
+ registries: tried.map(displayRegistry),
531
+ ...installed,
532
+ }
533
+ }
534
+ }
535
+ // An install may have started while the registry walk was in flight; a late
536
+ // `available` must never reach the client after that.
537
+ if (this.applying) return { status: 'applying', current }
538
+ if (reached === 0) {
539
+ return {
540
+ status: 'failed',
541
+ current,
542
+ message: tried.length === 0
543
+ ? 'no npm registry is configured'
544
+ : `could not reach an npm registry (tried ${tried.map(displayRegistry).join(', ')})`,
545
+ ...(tried.length === 0 ? {} : { registries: tried.map(displayRegistry) }),
546
+ ...installed,
547
+ }
548
+ }
549
+ return {
550
+ status: 'current',
551
+ current,
552
+ ...(best === undefined
553
+ ? {}
554
+ : { latest: best.version, ...(best.publishedAt === undefined ? {} : { publishedAt: best.publishedAt }) }),
555
+ registries: tried.map(displayRegistry),
556
+ ...installed,
557
+ }
558
+ }
559
+
560
+ /**
561
+ * Install one exact version through the harness plugin manager.
562
+ *
563
+ * Re-entry while an install is running answers `applying` instead of
564
+ * stacking a second npm operation; the install itself is the host's job.
565
+ *
566
+ * With HMR alive the manager refuses to replace a bundle already in the
567
+ * profile (`already-installed`), so the host's own update semantics are
568
+ * remove-then-install. That is NOT self-replacement: a human gesture started
569
+ * it, the manager still performs every file operation, and it unloads the
570
+ * live module first — exactly what the host does for any bundle update. If
571
+ * the reinstall fails, the previous version is put back through the same
572
+ * `installBundle` path.
573
+ */
574
+ async apply(version: string): Promise<PluginUpdateState> {
575
+ const current = this.currentVersion
576
+ if (compareVersions(version, current) <= 0) {
577
+ // A downgrade (or the running version) is never an update. Version
578
+ // syntax is already enforced at the RPC boundary; answer instead of
579
+ // throwing so a stale UI click cannot surface as an RPC fault.
580
+ return {
581
+ status: 'failed',
582
+ current,
583
+ message: 'the requested version is not newer than the running plugin',
584
+ }
585
+ }
586
+ if (this.applying) return { status: 'applying', current }
587
+ this.applying = true
588
+ try {
589
+ const eligible = await this.eligibility()
590
+ if (!eligible.ok) return eligible.state
591
+ const installed = eligible.installed === undefined ? {} : { installed: eligible.installed }
592
+ if (this.isBusy()) return { status: 'busy', current, ...installed }
593
+ const manager = this.resolveManager()
594
+ const installBundle = manager?.installBundle
595
+ if (manager === undefined || installBundle === undefined) {
596
+ return { status: 'unsupported', current, message: 'host does not expose the plugin manager' }
597
+ }
598
+ const removeBundle = typeof manager.removeBundle === 'function' ? manager.removeBundle : undefined
599
+ const registry = this.lastTarget?.version === version ? this.lastTarget.registry : undefined
600
+ const options: { enabled: boolean; registry?: string } = {
601
+ enabled: true,
602
+ ...(registry === undefined ? {} : { registry }),
603
+ }
604
+ const install = async (target: string, extra: { enabled?: boolean; registry?: string }): Promise<UpdateInstallResult | undefined> =>
605
+ unwrapInstallResult(await installBundle.call(manager, `${UPDATE_PACKAGE}@${target}`, extra))
606
+ const rollback = async (): Promise<boolean> => {
607
+ // The failed install may already have written the target version into
608
+ // the profile, in which case reinstalling the running version answers
609
+ // `already-installed`. Native update semantics: unload first, ignore
610
+ // failures (the target may never have landed), then install through the
611
+ // host's default chain — the target's registry is not ours to reuse.
612
+ if (removeBundle !== undefined) {
613
+ try {
614
+ await removeBundle.call(manager, UPDATE_PACKAGE)
615
+ } catch {
616
+ // Best effort: a bundle that was never installed cannot be removed.
617
+ }
618
+ }
619
+ try {
620
+ return isInstallSuccess(await install(current, { enabled: true }))
621
+ } catch {
622
+ return false
623
+ }
624
+ }
625
+ let result: UpdateInstallResult | undefined
626
+ try {
627
+ result = await install(version, options)
628
+ } catch (error) {
629
+ return { status: 'failed', current, ...installed, message: messageOf(error) }
630
+ }
631
+ if (result?.error?.code === 'already-installed' && removeBundle !== undefined) {
632
+ let removed: UpdateInstallResult | undefined
633
+ try {
634
+ removed = unwrapInstallResult(await removeBundle.call(manager, UPDATE_PACKAGE))
635
+ } catch (error) {
636
+ return {
637
+ status: 'failed',
638
+ current,
639
+ ...installed,
640
+ message: `could not remove the running version: ${messageOf(error)}`,
641
+ }
642
+ }
643
+ if (!isRemoveSuccess(removed)) {
644
+ return {
645
+ status: 'failed',
646
+ current,
647
+ ...installed,
648
+ message: `could not remove the running version: ${removed?.error !== undefined
649
+ ? describeFieldError(removed.error)
650
+ : `the plugin manager answered ${removed?.application ?? 'no result'}`}`,
651
+ }
652
+ }
653
+ let retried: UpdateInstallResult | undefined
654
+ let retryFailure: string | undefined
655
+ try {
656
+ retried = await install(version, options)
657
+ } catch (error) {
658
+ retryFailure = messageOf(error)
659
+ }
660
+ if (retryFailure === undefined && isInstallSuccess(retried)) {
661
+ result = retried
662
+ } else {
663
+ const reason = retryFailure
664
+ ?? (retried?.error === undefined
665
+ ? retried?.application === undefined
666
+ ? 'the plugin manager returned no install result'
667
+ : `the plugin manager answered ${retried.application}`
668
+ : describeFieldError(retried.error))
669
+ const rolledBack = await rollback()
670
+ return {
671
+ status: 'failed',
672
+ current,
673
+ ...(rolledBack ? { installed: current } : {}),
674
+ message: `installing ${version} failed: ${reason}; ${rolledBack ? `rolled back to ${current}` : `rolling back to ${current} also failed`}`,
675
+ }
676
+ }
677
+ }
678
+ if (result !== undefined && result.error !== undefined) {
679
+ // Never report the target as installed here: the disk still holds the
680
+ // previous version.
681
+ return { status: 'failed', current, ...installed, message: describeFieldError(result.error) }
682
+ }
683
+ const application = result?.application
684
+ if (application === 'applied' || application === 'restart-required') {
685
+ this.cache.clear()
686
+ this.lastTarget = undefined
687
+ return { status: application, current, installed: result?.version ?? version }
688
+ }
689
+ if (application === 'overridden') {
690
+ return {
691
+ status: 'failed',
692
+ current,
693
+ ...installed,
694
+ message: 'the installation was overridden by a higher-level configuration',
695
+ }
696
+ }
697
+ if (application === 'cancelled') {
698
+ return { status: 'failed', current, ...installed, message: 'installation was cancelled' }
699
+ }
700
+ return {
701
+ status: 'failed',
702
+ current,
703
+ ...installed,
704
+ message: application === undefined
705
+ ? 'the plugin manager returned no install result'
706
+ : `the plugin manager returned an unexpected application state: ${application}`,
707
+ }
708
+ } finally {
709
+ this.applying = false
710
+ }
711
+ }
712
+ }