dsh-crate 0.6.4 → 0.6.5

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.
@@ -51,3 +51,42 @@ export async function mismatchedWorkspaceRoot(target, name, region) {
51
51
  }
52
52
  return null;
53
53
  }
54
+ const PINNED_TARGET_RE = /^github:([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)#([0-9a-f]{40})$/i;
55
+ /**
56
+ * The package version a commit of a GitHub plugin holds, read from its
57
+ * package.json — or null when it cannot be read.
58
+ *
59
+ * The desktop host's in-place update wants the exact version the target will
60
+ * install, and for a Git spec that number exists only inside the repository.
61
+ * Null is an ordinary answer, not a failure: the caller then updates the old
62
+ * way, which needs no version. Only the `github:owner/repo#<commit>` shape is
63
+ * read; any other address is not worth a guess.
64
+ */
65
+ export async function githubPackageVersionAt(target, region) {
66
+ const match = PINNED_TARGET_RE.exec(target);
67
+ if (match === null)
68
+ return null;
69
+ const url = `https://raw.githubusercontent.com/${match[1]}/${match[2].toLowerCase()}/package.json`;
70
+ const signal = AbortSignal.timeout(FETCH_TIMEOUT_MS);
71
+ for (const route of githubRoutesFor('raw', region)) {
72
+ if (signal.aborted)
73
+ break;
74
+ try {
75
+ const response = await marketFetch(throughProxy(route, url), { signal, redirect: 'manual' });
76
+ if (!response.ok) {
77
+ await response.body?.cancel();
78
+ continue;
79
+ }
80
+ const bytes = await readBodyWhileProgressing(response, FETCH_TIMEOUT_MS, 'GitHub package manifest', MAX_MANIFEST_BYTES);
81
+ const manifest = JSON.parse(new TextDecoder().decode(bytes));
82
+ if (manifest === null || typeof manifest !== 'object')
83
+ continue;
84
+ rememberGithubRoute('raw', route);
85
+ return typeof manifest.version === 'string' ? manifest.version : null;
86
+ }
87
+ catch {
88
+ // Try the next route; a manifest nobody can read gives no version.
89
+ }
90
+ }
91
+ return null;
92
+ }
package/lib/index.js CHANGED
@@ -15,6 +15,8 @@ import { MAX_AUTO_REPAIR_ATTEMPTS } from './pending-updates.js';
15
15
  import { observeStartupRepair } from './startup-repair-report.js';
16
16
  import { modelAccess, registerFindPlugin, setModelAccess } from './find-plugin.js';
17
17
  import { loadRegistry } from './registry.js';
18
+ import { githubPackageVersionAt } from './github-install-target.js';
19
+ import { activeRegion } from './regions.js';
18
20
  export const name = 'dsh-crate';
19
21
  /**
20
22
  * How long after the market mounts an interrupted update is repaired.
@@ -332,7 +334,24 @@ export function apply(ctx, config) {
332
334
  // Hand the invocation to the runtime only. Do not register it
333
335
  // globally: other official-desktop installs still go through the
334
336
  // manager (#702). The market itself is the one exception (#982).
335
- hostPackageManagerOf(profileContext));
337
+ hostPackageManagerOf(profileContext), {
338
+ // A Git bundle's in-place update names the exact version of the
339
+ // commit it installs; the commit's package.json is the only place
340
+ // that number lives.
341
+ gitVersionAt: spec => githubPackageVersionAt(spec, activeRegion()),
342
+ // dsh 0.2.2+ announces the steps of an in-place update; the page
343
+ // shows which one is running instead of one fixed line.
344
+ watchUpdateSteps: (requestId, listener) => {
345
+ const subscribe = hostCtx.on;
346
+ if (typeof subscribe !== 'function')
347
+ return () => { };
348
+ const dispose = subscribe.call(hostCtx, 'plugin-manager/update-state', progress => {
349
+ if (progress.requestId === requestId && typeof progress.step === 'string')
350
+ listener(progress.step);
351
+ });
352
+ return typeof dispose === 'function' ? dispose : () => { };
353
+ },
354
+ });
336
355
  const resolved = {
337
356
  profile: profileName,
338
357
  ...(profileDirectory === undefined ? {} : { profileDirectory }),
@@ -1,7 +1,9 @@
1
1
  /** The official Electron profile is owned by DSH's in-process plugin manager. */
2
2
  import { randomUUID } from 'node:crypto';
3
3
  import { cancelActive as cancelHostChild, progress, runHostPnpm, TARGET_RE, } from './dsh-cli.js';
4
+ import { logEvent } from './log.js';
4
5
  import { classifyPnpmFailure } from './pnpm-compat.js';
6
+ import { compareSemver, isSemver } from './check.js';
5
7
  import { DeadlineExceeded, PendingUpdateJournal, repairInterruptedUpdates, withDeadline, } from './pending-updates.js';
6
8
  import { profileDir, readInstalledVersion } from './profile.js';
7
9
  import { activeRegion, DEFAULT_NPM_REGISTRY, routesFor } from './regions.js';
@@ -52,6 +54,20 @@ const INSTALL_DEADLINE_MS = HOST_IDLE_WATCHDOG_MS + DEADLINE_MARGIN_MS;
52
54
  * operation refusal (#928's spec caught it).
53
55
  */
54
56
  const OPERATION_DEADLINE_MS = REMOVE_DEADLINE_MS + INSTALL_DEADLINE_MS + DEADLINE_MARGIN_MS;
57
+ /**
58
+ * The bound around the host's own in-place update (`updateBundle`). The host
59
+ * runs the whole sequence itself — check the target, remove, install, and on a
60
+ * failed install remove again and put the old version back — so the market no
61
+ * longer sees the phases, only the one answer. Each of those phases can spend
62
+ * the host's silence watchdog on its own pnpm child, and the market must not
63
+ * answer for the host while the host is still diagnosing (#1250), so the bound
64
+ * is three phases long: check + install + the restore the host owes after a
65
+ * failed install. It is a backstop against a call that never settles, not a
66
+ * budget for a slow network.
67
+ */
68
+ const IN_PLACE_UPDATE_DEADLINE_MS = 3 * (HOST_IDLE_WATCHDOG_MS + DEADLINE_MARGIN_MS);
69
+ /** Strictly longer than the call it wraps, for the reason `OPERATION_DEADLINE_MS` gives. */
70
+ const IN_PLACE_OPERATION_DEADLINE_MS = IN_PLACE_UPDATE_DEADLINE_MS + DEADLINE_MARGIN_MS;
55
71
  /**
56
72
  * What a user can actually do when the market cannot perform an operation on
57
73
  * the official Desktop profile: the app's own Plugins page runs the same
@@ -109,6 +125,13 @@ function detail(error) {
109
125
  }
110
126
  return diagnostic;
111
127
  }
128
+ // The host's own reason for a refused check (the registry did not answer,
129
+ // the version is not there). Said with what it means for the user: nothing
130
+ // changed, and what to do.
131
+ const reason = code === 'operation-error' ? error.diagnostic : undefined;
132
+ if (typeof reason === 'string' && reason.trim() !== '') {
133
+ return `桌面端没能完成这次操作,现在的版本不受影响。原因见下,通常检查网络后重试即可。 / The desktop app could not finish this operation and your current version is unchanged. The reason is below; checking the network and retrying usually fixes it.\n${reason.trim().slice(0, 600)}`;
134
+ }
112
135
  return JSON.stringify(error);
113
136
  }
114
137
  /**
@@ -153,6 +176,20 @@ const REFUSAL_COPY = {
153
176
  zh: '桌面端没有在限定时间内答复这次操作:磁盘上可能已经改完了,市场只是没等到答复,所以没有回滚。重新打开 DSH 后市场会按磁盘状态核对;状态不对的话从「设置 → 插件」处理',
154
177
  en: 'the desktop app did not answer this operation in time: the change may already be on disk, and the market got no reply, so it rolled nothing back. Reopen DSH and the market checks what is actually there; if it still looks wrong, use Settings → Plugins',
155
178
  },
179
+ // Refusals of the in-place update (`updateBundle`, dsh 0.2.2+). Every one
180
+ // says what stopped, that the old version is still there, and what to do.
181
+ 'not-bundle': {
182
+ zh: '新版本不是一个 DSH 插件包,桌面端没有安装它,现在的版本不受影响。请稍后再试,或联系插件作者',
183
+ en: 'the new version is not a DSH plugin package, so the desktop app did not install it and your current version is unchanged. Try again later, or contact the plugin author',
184
+ },
185
+ 'unexpected-package': {
186
+ zh: '装出来的不是要求的版本(常见原因:这个版本还在新版本等待期内),桌面端已撤销这次更新,旧版本还在。过几天再更新一次',
187
+ en: 'what got installed was not the requested version (a common cause: it is still inside the fresh-release wait), so the desktop app undid the update and your old version is still there. Try again in a few days',
188
+ },
189
+ 'invalid-spec': {
190
+ zh: '桌面端不接受这次更新的目标,没有改动任何东西。请刷新市场后再试',
191
+ en: 'the desktop app did not accept the target of this update and changed nothing. Refresh the market and try again',
192
+ },
156
193
  'update-incomplete': {
157
194
  zh: '桌面端没有在限定时间内完成这次更新:插件可能已经被移除,新版本却还没装上。重新打开 DSH 后市场会自动补装;也可以现在从「设置 → 插件」重试',
158
195
  en: 'the desktop app did not finish this update in time: the plugin may already be removed while its replacement never installed. Reopen DSH and the market will finish the install, or retry from Settings → Plugins now',
@@ -248,6 +285,271 @@ function interrupted() {
248
285
  function unanswered() {
249
286
  return { application: 'failed', error: { code: 'operation-incomplete' }, repairOnRestart: true };
250
287
  }
288
+ /** What the update steps the host reports are called on the progress line. */
289
+ const UPDATE_STEP_LINES = {
290
+ checking: '正在确认新版本可以装 / Checking that the new version can be installed',
291
+ removing: '正在停掉旧版本 / Stopping the old version',
292
+ installing: '正在安装新版本 / Installing the new version',
293
+ restoring: '新版本没装上,正在装回旧版本 / The new version did not install; putting the old one back',
294
+ };
295
+ const GIT_HOSTS = { github: 'github.com', gitlab: 'gitlab.com', bitbucket: 'bitbucket.org' };
296
+ /**
297
+ * The repository directory of a Git spec pinned to one full commit, spelled the
298
+ * way the host compares them (`github.com/owner/repo`), or null for anything
299
+ * else — a floating spec, a path selector, an address the host would read
300
+ * differently. Only used to match a spec to the bundle it replaces; the host
301
+ * checks the same thing again before it changes anything.
302
+ */
303
+ function pinnedGitOrigin(spec) {
304
+ const hash = spec.indexOf('#');
305
+ if (hash === -1 || !/^[0-9a-f]{40}$/i.test(spec.slice(hash + 1)))
306
+ return null;
307
+ let location = spec.slice(0, hash);
308
+ const shorthand = /^(github|gitlab|bitbucket):([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)$/i.exec(location);
309
+ if (shorthand !== null)
310
+ location = `${GIT_HOSTS[shorthand[1].toLowerCase()]}/${shorthand[2]}`;
311
+ else if (/^(?:git\+)?https?:\/\/[^@]+$/i.test(location))
312
+ location = location.replace(/^git\+/i, '').replace(/^https?:\/\//i, '');
313
+ else
314
+ return null;
315
+ return location.replace(/\/+$/, '').replace(/\.git$/i, '').replace(/^[^/]+/, host => host.toLowerCase());
316
+ }
317
+ /**
318
+ * Whether this spec is an update the host's `updateBundle` can do, and if so
319
+ * exactly which one. Null means "use the remove-and-install path", always
320
+ * safe: that is the only path on 0.2.1, and it is what handles everything the
321
+ * in-place call refuses by contract —
322
+ *
323
+ * - a version that is not newer (a downgrade, a re-install of the same one,
324
+ * the update route's own rollback to the build from before);
325
+ * - a dist-tag or range instead of an exact version;
326
+ * - a package the host does not list as updatable (`update` absent): a link,
327
+ * a floating Git spec, an `npm:` alias, an installation-owned package;
328
+ *
329
+ * The market itself is NOT on that list any more. It used to be (#900: with
330
+ * HMR the host removes the bundle first, which unloads the code that was going
331
+ * to install the new one), because the pair was driven from here, step by
332
+ * step. `updateBundle` runs the pair inside the host, which does not care that
333
+ * the caller is gone; what is left to handle is the request that asked, see
334
+ * `updateInPlace`. A host without `updateBundle` never reaches this code and
335
+ * keeps the market's own overlay (`updateMarketInPlace`).
336
+ */
337
+ async function planInPlaceUpdate(manager, spec, context) {
338
+ // Why a spec went the old way, in the log: "did it use updateBundle" is the
339
+ // first thing a bug report about an update has to answer.
340
+ const decline = (reason) => {
341
+ logEvent('info', 'update-in-place', `${spec}: not updated in place (${reason}); using remove and install`);
342
+ return null;
343
+ };
344
+ if (typeof manager.updateBundle !== 'function' || typeof manager.listBundles !== 'function')
345
+ return null;
346
+ let rows;
347
+ try {
348
+ rows = await manager.listBundles();
349
+ }
350
+ catch {
351
+ // Reading the profile failed: the ordinary path reports that in its own words.
352
+ return decline('the host could not list its bundles');
353
+ }
354
+ if (!Array.isArray(rows))
355
+ return decline('the host listed no bundles');
356
+ const named = registryNameOf(spec);
357
+ let row;
358
+ let to = '';
359
+ let gitSpec;
360
+ if (named !== undefined) {
361
+ row = rows.find(entry => entry.name === named);
362
+ if (row?.update !== 'registry')
363
+ return decline(row === undefined ? 'not an installed bundle' : 'the host does not list it as updatable from a registry');
364
+ to = targetVersionOf(spec);
365
+ if (to === '')
366
+ return decline('the target is not an exact version');
367
+ }
368
+ else {
369
+ const origin = pinnedGitOrigin(spec);
370
+ if (origin === null)
371
+ return decline('not a Git spec pinned to one commit');
372
+ row = rows.find(entry => entry.update === 'git' && typeof entry.source === 'string' && pinnedGitOrigin(entry.source) === origin);
373
+ if (row === undefined)
374
+ return decline('no installed Git bundle comes from that repository commit pin');
375
+ if (context?.gitVersionAt === undefined)
376
+ return decline('the commit version cannot be read here');
377
+ try {
378
+ to = (await context.gitVersionAt(spec)) ?? '';
379
+ }
380
+ catch {
381
+ to = '';
382
+ }
383
+ if (to === '')
384
+ return decline('the commit version could not be read');
385
+ gitSpec = spec;
386
+ }
387
+ const from = row.version;
388
+ if (typeof from !== 'string' || !isSemver(from) || !isSemver(to))
389
+ return decline('a version is not a semver');
390
+ if (compareSemver(to, from) <= 0)
391
+ return decline(`${to} is not newer than ${from}`);
392
+ return { name: row.name, from, to, ...(gitSpec === undefined ? {} : { gitSpec }) };
393
+ }
394
+ /** `applied`, `restart-required` and `overridden` are the answers that mean the change was kept. */
395
+ function kept(result) {
396
+ return result?.application === 'applied' || result?.application === 'restart-required' || result?.application === 'overridden';
397
+ }
398
+ /**
399
+ * Update one bundle with the host's `updateBundle`: one call that checks the
400
+ * target, swaps the versions and, when the new one does not install, puts the
401
+ * old one back by itself.
402
+ *
403
+ * What stays of the old machinery, and why:
404
+ *
405
+ * - No second journal phase. The remove-then-install pair is the host's now,
406
+ * and it undoes its own half-done work, so the market has nothing in between
407
+ * to record. But the host's undo is still only as durable as its process: if
408
+ * the host dies, or the market stops waiting, between its removal and its
409
+ * reinstall, the package is gone from disk exactly as in #928. So ONE record
410
+ * brackets the call and is cleared the moment the answer proves the profile
411
+ * whole (updated, or old version back, or never touched); the next start
412
+ * reconciles from disk, as it always did, when no answer ever came.
413
+ * - The deadline stays, now around the one call (`IN_PLACE_UPDATE_DEADLINE_MS`).
414
+ *
415
+ * Returns null when the host refuses the spec itself (`invalid-spec` at the
416
+ * check, before it changed anything): the caller then takes the
417
+ * remove-and-install path, which is today's behavior for that spec.
418
+ */
419
+ async function updateInPlace(manager, plan, options, context) {
420
+ const spec = plan.gitSpec ?? `${plan.name}@${plan.to}`;
421
+ const record = context?.journal.begin({
422
+ profile: context.profile,
423
+ name: plan.name,
424
+ from: plan.from,
425
+ to: plan.to,
426
+ spec,
427
+ });
428
+ const settle = () => { if (record !== undefined)
429
+ context?.journal.finish(record.id); };
430
+ // The line a bug report needs to tell which path an update took.
431
+ logEvent('info', 'update-in-place', `${plan.name} ${plan.from} -> ${plan.to}: asking the host to update it in place`);
432
+ progress.lastLine = UPDATE_STEP_LINES.checking;
433
+ const unwatch = options.requestId === undefined
434
+ ? undefined
435
+ : context?.watchUpdateSteps?.(options.requestId, step => {
436
+ const line = UPDATE_STEP_LINES[step];
437
+ if (line !== undefined)
438
+ progress.lastLine = line;
439
+ });
440
+ let outcome;
441
+ try {
442
+ outcome = await withDeadline(trackManagerWrite(manager.updateBundle(plan.name, plan.to, {
443
+ ...(options.registry === undefined ? {} : { registry: options.registry }),
444
+ ...(plan.gitSpec === undefined ? {} : { spec: plan.gitSpec }),
445
+ ...(options.requestId === undefined ? {} : { requestId: options.requestId }),
446
+ })), IN_PLACE_UPDATE_DEADLINE_MS, `update ${plan.name}`);
447
+ }
448
+ catch (error) {
449
+ if (error instanceof DeadlineExceeded)
450
+ return interrupted();
451
+ // A call that threw never reported a result, which this host does only
452
+ // before it changes anything (the profile could not be read, the manager
453
+ // was disposed). The record stays unless the disk shows the old build.
454
+ if (context !== undefined && readInstalledVersion(context.profile, plan.name, context.profileDirectory) === plan.from)
455
+ settle();
456
+ throw error;
457
+ }
458
+ finally {
459
+ // The listener hangs off the context that asked, which a self-update has
460
+ // already disposed by now; letting go of it must never decide the answer.
461
+ try {
462
+ unwatch?.();
463
+ }
464
+ catch { /* nothing left to release */ }
465
+ }
466
+ const last = outcome.result;
467
+ logEvent('info', 'update-in-place', `${plan.name}: the host answered at step ${outcome.step}: ${last.application}${managementCode(last.error) === undefined ? '' : ` (${managementCode(last.error)})`}${outcome.restore === undefined ? '' : `; restore ${outcome.restore.application}`}`);
468
+ const asManaged = (result) => ({
469
+ application: result.application,
470
+ ...(result.error === undefined ? {} : { error: result.error }),
471
+ ...(result.packageResult === undefined ? {} : { packageResult: result.packageResult }),
472
+ });
473
+ // The market updating ITSELF. With HMR the host removes the running bundle
474
+ // before it installs the new one, so by the time this call answers, this
475
+ // very instance has been disposed and its replacement is serving (measured
476
+ // on dsh 0.2.2-rc.5 and 0.2.3-alpha.2, tests/web/desktop-update.e2e.ts).
477
+ // What survives is this closure: it can still answer the HTTP request —
478
+ // the response belongs to the web server, not to the plugin — but anything
479
+ // that asks the disposed context for a service (`loader`, to read what is
480
+ // live) throws, which turned a finished update into a 500. The caller is
481
+ // told, and answers from the result alone. Without HMR the host installs
482
+ // over the running version instead (`restart-required`), nothing is
483
+ // disposed, and the ordinary reply applies.
484
+ const tornDown = SELF_NAMES.has(plan.name) && outcome.step === 'install'
485
+ && (kept(last) ? last.application !== 'restart-required' : outcome.restore !== undefined);
486
+ const swapped = (result) => tornDown ? { ...result, selfSwapped: true } : result;
487
+ if (outcome.step === 'install' && kept(last)) {
488
+ settle();
489
+ if (last.application === 'restart-required')
490
+ markRestartPending();
491
+ return swapped({ ...asManaged(last), ...(last.application === 'applied' ? { liveSwap: true } : {}) });
492
+ }
493
+ if (outcome.step === 'check') {
494
+ settle();
495
+ // The host cannot express this update at all (not newer, not updatable):
496
+ // nothing changed, and the ordinary path can still do it.
497
+ if (managementCode(last.error) === 'invalid-spec')
498
+ return null;
499
+ // `not-bundle` at the check is the host reading `dsh` out of `pnpm view`,
500
+ // and pnpm 11 can answer that from its own install cache, which keeps only
501
+ // the fields an install needs: no `dsh`. Measured on dsh 0.2.2-rc.5 with
502
+ // the Tencent mirror (the China region's registry): any plugin that had
503
+ // not been republished since it was installed was refused this way, the
504
+ // market included, while the same `pnpm view` with an empty cache printed
505
+ // the bundle. Nothing changed yet, and the ordinary path installs and
506
+ // checks the real package, so it takes over; a version that truly is not
507
+ // a bundle is still refused there, by the install, and rolled back.
508
+ // (Libraries never get this far: the update list leaves them out, #793.)
509
+ if (managementCode(last.error) === 'not-bundle') {
510
+ logEvent('warn', 'update-in-place', `${plan.name}: the host's registry check found no bundle in ${plan.to}, which pnpm's metadata cache can cause; using the ordinary update path instead`);
511
+ return null;
512
+ }
513
+ return { ...asManaged(last), untouched: true };
514
+ }
515
+ if (outcome.step === 'remove') {
516
+ // The removal itself failed or was cancelled, so nothing was unloaded.
517
+ settle();
518
+ if (last.application === 'failed' && managementCode(last.error) === 'bundle-in-use' && restartPending()) {
519
+ return { ...asManaged(last), needsRestart: true, untouched: true };
520
+ }
521
+ return { ...asManaged(last), untouched: true };
522
+ }
523
+ // The install failed or was cancelled. With HMR the host removed the old
524
+ // version first and has tried to put it back.
525
+ if (outcome.restore !== undefined) {
526
+ if (kept(outcome.restore)) {
527
+ settle();
528
+ return swapped({
529
+ ...asManaged(last),
530
+ untouched: true,
531
+ note: '旧版本已经装回,没有丢东西。 / The old version was put back; nothing was lost.',
532
+ });
533
+ }
534
+ // Neither version is installed. Do not ask the same host to restore it
535
+ // again from the route (it just failed to) and keep the record, re-aimed
536
+ // at the OLD version: the target just failed to install, and the next
537
+ // start's repair must put back what the user had, not retry what failed.
538
+ if (record !== undefined && context !== undefined) {
539
+ context.journal.begin({ profile: context.profile, name: plan.name, from: plan.from, to: plan.from, spec: `${plan.name}@${plan.from}` });
540
+ }
541
+ return swapped({
542
+ ...asManaged(last),
543
+ repairOnRestart: true,
544
+ note: `旧版本也没能装回,这个插件现在是缺的。重新打开 DSH 后市场会自动装回 ${plan.from};也可以现在从「设置 → 插件」重新安装它。 / The old version could not be put back either, so the plugin is missing right now. Reopen DSH and the market will reinstall ${plan.from}, or reinstall it from Settings → Plugins now.`,
545
+ });
546
+ }
547
+ // No restore ran: a host without HMR installs over the running version and
548
+ // the failure left the old files in place. That is the ordinary failed
549
+ // install, and the route's own rollback applies as it always did.
550
+ settle();
551
+ return asManaged(last);
552
+ }
251
553
  /**
252
554
  * Overlay the market's own version without unloading it (#982, #900).
253
555
  *
@@ -344,6 +646,15 @@ async function updateMarketInPlace(spec, name, options, context) {
344
646
  */
345
647
  async function installOrReinstall(manager, spec, options, context) {
346
648
  const install = () => trackManagerWrite(manager.installBundle(spec, options));
649
+ // dsh 0.2.2+ replaces an installed bundle in one call. Everything it cannot
650
+ // express falls through to the remove-and-install path below, unchanged.
651
+ // (Not awaited on a manager without it: the install call stays synchronous.)
652
+ const plan = typeof manager.updateBundle === 'function' ? await planInPlaceUpdate(manager, spec, context) : null;
653
+ if (plan !== null) {
654
+ const updated = await updateInPlace(manager, plan, options, context);
655
+ if (updated !== null)
656
+ return updated;
657
+ }
347
658
  let first;
348
659
  try {
349
660
  // Bounded like every other manager call: a plain install the host never
@@ -498,15 +809,17 @@ function safeProfileDirectory(profile, explicit) {
498
809
  * quit it before running". The market only ever runs inside a live Desktop, so
499
810
  * for the market the answer is the same on every version: the app's own
500
811
  * plugin manager is the only door.
812
+ *
813
+ * `_profileDirectory` is unused by the manager bridge — it takes the profile
814
+ * by NAME — and optional because an explicitly configured `profile: desktop`
815
+ * may be the only thing that names this profile, with no launcher directory
816
+ * to go with it (#744). `packageManager` is where Official Desktop publishes
817
+ * its bundled pnpm; it is used only to overlay the market itself (#982), and
818
+ * other packages still go through the manager. `hooks` is what only the host
819
+ * process can supply to an in-place update (see `UpdateContext`); both are
820
+ * optional, and an update without them still works.
501
821
  */
502
- export function createOfficialDesktopRuntime(managerLookup, profileName,
503
- // Unused by the manager bridge — it takes the profile by NAME — and optional
504
- // because an explicitly configured `profile: desktop` may be the only thing
505
- // that names this profile, with no launcher directory to go with it (#744).
506
- _profileDirectory,
507
- // Official Desktop publishes its bundled pnpm here. Used only to overlay
508
- // the market itself (#982). Other packages still go through the manager.
509
- packageManager) {
822
+ export function createOfficialDesktopRuntime(managerLookup, profileName, _profileDirectory, packageManager, hooks) {
510
823
  let disposed = false;
511
824
  let repairing = false;
512
825
  // True only while the self-update overlay runs its own pnpm child: the one
@@ -523,6 +836,8 @@ packageManager) {
523
836
  journal,
524
837
  packageManager,
525
838
  onOwnChild: running => { ownsChild = running; },
839
+ ...(hooks?.gitVersionAt === undefined ? {} : { gitVersionAt: hooks.gitVersionAt }),
840
+ ...(hooks?.watchUpdateSteps === undefined ? {} : { watchUpdateSteps: hooks.watchUpdateSteps }),
526
841
  };
527
842
  const busy = () => active !== undefined || repairing || runningOperation() !== undefined;
528
843
  const runPlugin = (profile, argv) => {
@@ -590,7 +905,9 @@ packageManager) {
590
905
  // "working" forever, while its pnpm had in fact finished seconds later.
591
906
  // The update path has had these deadlines for exactly that reason; an
592
907
  // ordinary install or uninstall needs the same bound.
593
- const deadline = command === 'remove' ? REMOVE_DEADLINE_MS : OPERATION_DEADLINE_MS;
908
+ const deadline = command === 'remove'
909
+ ? REMOVE_DEADLINE_MS
910
+ : typeof manager.updateBundle === 'function' ? IN_PLACE_OPERATION_DEADLINE_MS : OPERATION_DEADLINE_MS;
594
911
  operation = withDeadline(command === 'remove'
595
912
  ? trackManagerWrite(manager.removeBundle(target))
596
913
  : installOrReinstall(manager, spec, options, updateContext), deadline, `${command} ${target}`).catch((error) => {
@@ -619,7 +936,8 @@ packageManager) {
619
936
  result.packageResult?.output ?? '',
620
937
  result.application === 'overridden' ? 'the plugin manager kept this change, but another layer overrides whether it is enabled' : '',
621
938
  ].filter(Boolean).join('\n');
622
- const message = ok ? '' : result.needsRestart === true ? RESTART_FIRST_MESSAGE : detail(result.error);
939
+ const account = result.needsRestart === true ? RESTART_FIRST_MESSAGE : detail(result.error);
940
+ const message = ok ? '' : result.note === undefined ? account : `${account} ${result.note}`;
623
941
  if (!ok)
624
942
  progress.error = message;
625
943
  // A later success for this package outdates what start-up repair said
@@ -646,12 +964,15 @@ packageManager) {
646
964
  // profile is untouched, and the route must not try to "restore" it.
647
965
  // A pre-install host check (#912) is the same shape even when the
648
966
  // manager attached a package result to its refusal.
649
- wroteNothing: !ok && !repairOnRestart && (result.packageResult === undefined || prePnpmHostFailure(result)),
967
+ wroteNothing: !ok && !repairOnRestart
968
+ && (result.untouched === true || result.packageResult === undefined || prePnpmHostFailure(result)),
650
969
  ...(repairOnRestart ? { repairOnRestart: true } : {}),
651
970
  // The manager's own code, kept machine-readable (#909): a client can
652
971
  // tell a self-update refusal from an ordinary failure.
653
972
  ...(ok ? {} : { refusalCode: managementCode(result.error) }),
654
973
  ...(result.needsRestart === true ? { needsRestart: true } : {}),
974
+ ...(result.selfSwapped === true ? { selfSwapped: true } : {}),
975
+ ...(ok && result.liveSwap === true ? { liveSwap: true } : {}),
655
976
  };
656
977
  }, (error) => {
657
978
  const message = detail(error);
@@ -879,7 +879,26 @@ export function classifyPnpmFailure(output, exitCode, context) {
879
879
  // tell "this mirror has not synced that release" from a ghost entry — but
880
880
  // a `.tgz` file name is not something the user can look up in their
881
881
  // package.json, so the sentence names the package in the path above it.
882
- const shown = pkg === undefined || !/\.tgz$/u.test(pkg) ? pkg : tarballOwner(output) ?? pkg;
882
+ const owner = pkg === undefined || !/\.tgz$/u.test(pkg) ? undefined : tarballOwner(output);
883
+ const shown = owner ?? pkg;
884
+ // A 404 for the DOWNLOAD of a version the registry's document lists is a
885
+ // mirror that has the release's metadata but not its file yet — the
886
+ // Tencent mirror, an hour after dsh-crate 1.81.1 was published, refused
887
+ // the market's own update this way. A ghost entry 404s on the package
888
+ // document instead. "Delete that line from package.json" is the wrong
889
+ // advice here: for the market it would delete the market. Same code, so
890
+ // every recovery that keys on `fetch-404` still runs.
891
+ const tarballVersion = owner === undefined || pkg === undefined
892
+ ? undefined
893
+ : pkg.slice(owner.slice(owner.lastIndexOf('/') + 1).length + 1, -'.tgz'.length) || undefined;
894
+ if (owner !== undefined && tarballVersion !== undefined) {
895
+ return {
896
+ code: 'fetch-404',
897
+ recoverable: false,
898
+ pkg,
899
+ message: `当前下载线路暂时拿不到 ${owner} ${tarballVersion} 的安装包。常见原因是线路还没同步刚发布的版本,不是你这边的问题。请过一会儿再试;若下载区域是中国大陆,也可改成「全球」后再试 / this download route cannot serve the package file for ${owner} ${tarballVersion} yet. Usually the route has not synced a just-published release; nothing on your side is wrong. Try again in a while; if Download region is China mainland, you can also switch it to Global and retry`,
900
+ };
901
+ }
883
902
  const zh = shown === undefined ? '' : `(${shown})`;
884
903
  const en = shown === undefined ? '' : ` (${shown})`;
885
904
  return {
package/lib/profile.js CHANGED
@@ -1001,6 +1001,10 @@ export function bundleOptOutRowIds(dir) {
1001
1001
  export function bundleExpressionRowIds(dir) {
1002
1002
  return declaredPatchRowIds(dir, 'expressionIds');
1003
1003
  }
1004
+ /** The `group: true` rows a package gates with an expression (#1305). */
1005
+ export function bundleGroupGateRowIds(dir) {
1006
+ return declaredPatchRowIds(dir, 'groupGateIds');
1007
+ }
1004
1008
  /**
1005
1009
  * Row ids a package's own patch sources declare for one role — the loop the
1006
1010
  * two readers above and below share.
@@ -1080,6 +1084,7 @@ export function parsePatchRows(text) {
1080
1084
  const insertedIds = [];
1081
1085
  const disabledIds = [];
1082
1086
  const expressionIds = [];
1087
+ const groupGateIds = [];
1083
1088
  {
1084
1089
  // CRLF too, for consistency with the hot-mount parser, which a
1085
1090
  // Windows-authored patch genuinely broke. Here it changes no outcome
@@ -1276,6 +1281,11 @@ export function parsePatchRows(text) {
1276
1281
  // plain, and the market must not write over it (#1043).
1277
1282
  if (payloadIndent === null && rowDeclaresExpressionDisabled(i) && !expressionIds.includes(id[1]))
1278
1283
  expressionIds.push(id[1]);
1284
+ // The parent of a package's components, gated by an expression: its
1285
+ // switch is the market's alone, because the plugins page toggles the
1286
+ // components under it, never the group itself (#1305).
1287
+ if (payloadIndent === null && rowDeclaresExpressionDisabled(i) && rowDeclaresGroup(i) && !groupGateIds.includes(id[1]))
1288
+ groupGateIds.push(id[1]);
1279
1289
  // A top-level `- id:` row closes any open insert block: it is a
1280
1290
  // sibling of `- insert:`, not a member of it.
1281
1291
  if (insertIndent !== null && indent > insertIndent) {
@@ -1288,7 +1298,7 @@ export function parsePatchRows(text) {
1288
1298
  }
1289
1299
  }
1290
1300
  }
1291
- return { names, ids, insertedIds, disabledIds, expressionIds };
1301
+ return { names, ids, insertedIds, disabledIds, expressionIds, groupGateIds };
1292
1302
  }
1293
1303
  /**
1294
1304
  * Where a package's bundle patches live, according to the package itself.