dsh-ntr 0.2.1 → 0.3.0

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