@linxin666/dsh-client-ui-plugin-manager 0.4.15 → 0.4.17

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/index.js CHANGED
@@ -1888,6 +1888,65 @@ function nativeManagerRestartRequired(outcome) {
1888
1888
  if (typeof outcome !== "object" || outcome === null) return false;
1889
1889
  return outcome.application === "restart-required";
1890
1890
  }
1891
+ /** The phase an update ended on, named for the person reading the failure. */
1892
+ const NATIVE_UPDATE_STEP_LABELS = {
1893
+ check: "检查新版本时被拒",
1894
+ remove: "移除已安装版本时被拒",
1895
+ install: "安装新版本时失败"
1896
+ };
1897
+ /**
1898
+ * What one official `updateBundle` run reported as its failure, or undefined
1899
+ * when the target landed.
1900
+ *
1901
+ * The verdict of the phase that ended the run is the only place the reason
1902
+ * lives — the manager folds a refused run into the resolved value instead of
1903
+ * rejecting it — so the phase is named beside the manager's own words: a
1904
+ * refusal to remove is a different fact from a refusal to install.
1905
+ * @param outcome - the resolved value of `updateBundle`.
1906
+ * @returns the failure text to report, or undefined for a run that landed.
1907
+ */
1908
+ function nativeUpdateFailure(outcome) {
1909
+ if (typeof outcome !== "object" || outcome === null) return void 0;
1910
+ const value = outcome;
1911
+ const failure = nativeManagerFailure(value.result);
1912
+ if (failure === void 0) return void 0;
1913
+ return `${NATIVE_UPDATE_STEP_LABELS[value.step ?? ""] ?? "更新未完成"}(${failure})`;
1914
+ }
1915
+ /**
1916
+ * The official manager's refusal code for one update, or undefined when the
1917
+ * target landed. {@link nativeUpdateFailure} renders that verdict for the
1918
+ * person; this is the same verdict read for a decision, which is how the update
1919
+ * path recognises a `bundle-in-use` removal it answers with one retry.
1920
+ * @param outcome - the resolved value of `updateBundle`.
1921
+ */
1922
+ function nativeUpdateRefusalCode(outcome) {
1923
+ if (typeof outcome !== "object" || outcome === null) return void 0;
1924
+ return nativeManagerRefusalCode(outcome.result);
1925
+ }
1926
+ /**
1927
+ * Whether one update landed on disk but is not loaded in this process: the
1928
+ * phase that ended it answered `application: 'restart-required'`.
1929
+ * @param outcome - the resolved value of `updateBundle`.
1930
+ */
1931
+ function nativeUpdateRestartRequired(outcome) {
1932
+ if (typeof outcome !== "object" || outcome === null) return false;
1933
+ return nativeManagerRestartRequired(outcome.result);
1934
+ }
1935
+ /**
1936
+ * How a failed update left the version it removed, as a clause appended to the
1937
+ * failure: the official manager reinstalls that version itself, so the report
1938
+ * says whether the plugin is back or the person has to reinstall it by hand.
1939
+ * @param outcome - the resolved value of `updateBundle`.
1940
+ * @returns the clause, or an empty string when no reinstallation ran.
1941
+ */
1942
+ function nativeUpdateRestoreNote(outcome) {
1943
+ if (typeof outcome !== "object" || outcome === null) return "";
1944
+ const value = outcome;
1945
+ if (value.restore === void 0) return "";
1946
+ const from = typeof value.from === "string" && value.from !== "" ? value.from : "更新前的版本";
1947
+ const failure = nativeManagerFailure(value.restore);
1948
+ return failure === void 0 ? `;已装回 ${from}` : `;装回 ${from} 也失败:${failure},请手动重新安装`;
1949
+ }
1891
1950
  /** The gateway: serializes CLI operations through one job table and one mutation queue. */
1892
1951
  var CliGateway = class {
1893
1952
  facts;
@@ -2227,37 +2286,135 @@ var CliGateway = class {
2227
2286
  * contract the browser half drives is identical either way.
2228
2287
  */
2229
2288
  update(id, version) {
2230
- const spec = `${id}@${version}`;
2231
- const job = {
2289
+ const job = this.newUpdateJob(id, version);
2290
+ this.jobs.set(job.id, job);
2291
+ const unsafe = unsafeSpecReason(job.spec);
2292
+ if (unsafe !== void 0) {
2293
+ job.phase = "error";
2294
+ job.error = unsafe;
2295
+ this.retainFinished(job.id);
2296
+ return { jobId: job.id };
2297
+ }
2298
+ this.enqueue(() => this.settleUpdateJob(job));
2299
+ return { jobId: job.id };
2300
+ }
2301
+ /**
2302
+ * One update job, registered but not yet queued.
2303
+ *
2304
+ * Both the single-plugin update and the batch runner settle this same shape,
2305
+ * so a batch row is applied by exactly the code an update from the plugin's
2306
+ * own page runs: the official in-process manager on an application-owned
2307
+ * profile, the CLI everywhere else.
2308
+ * @param id - installed package name.
2309
+ * @param version - the exact version the update must land on.
2310
+ */
2311
+ newUpdateJob(id, version) {
2312
+ return {
2232
2313
  id: `job-${++this.counter}`,
2233
2314
  action: "update",
2234
- spec,
2315
+ spec: `${id}@${version}`,
2235
2316
  targetId: id,
2236
2317
  targetVersion: version,
2237
2318
  phase: "running"
2238
2319
  };
2320
+ }
2321
+ /**
2322
+ * Apply a whole batch of updates in one run.
2323
+ *
2324
+ * The official manager only replaces one bundle at a time (`updateBundle`), and
2325
+ * the CLI only adds one spec at a time, so a batch is this host's sequence over
2326
+ * that single-plugin primitive rather than a second writer: one job, one
2327
+ * mutation-lock slot, one poll. Rows are applied in the order given, and a row
2328
+ * that cannot be applied — refused by the route's own gate before the run, or
2329
+ * by the writer during it — is recorded and skipped instead of ending the run,
2330
+ * because every managed writer below is atomic per plugin.
2331
+ *
2332
+ * The batch job settles `done` once the last row is answered: the rows carry
2333
+ * the failures, and a run that failed every row is not a failed job but a job
2334
+ * whose every row failed, which is what the caller renders.
2335
+ * @param entries - the rows to apply, in order, each already resolved to the
2336
+ * version it must land on or to the reason it was refused.
2337
+ */
2338
+ updateAll(entries) {
2339
+ const job = {
2340
+ id: `job-${++this.counter}`,
2341
+ action: "update-all",
2342
+ spec: "",
2343
+ phase: "running",
2344
+ results: entries.map((entry) => {
2345
+ if (entry.kind === "refused") return {
2346
+ id: entry.id,
2347
+ phase: "error",
2348
+ error: entry.error
2349
+ };
2350
+ const unsafe = entry.kind === "migrate" ? unsafeSpecReason(entry.id) ?? unsafeSpecReason(entry.targetId) ?? unsafeSpecReason(entry.targetSpec) : unsafeSpecReason(`${entry.id}@${entry.version}`);
2351
+ if (unsafe !== void 0) return {
2352
+ id: entry.id,
2353
+ phase: "error",
2354
+ error: unsafe
2355
+ };
2356
+ const targetVersion = entry.kind === "migrate" ? entry.targetVersion : entry.version;
2357
+ return {
2358
+ id: entry.id,
2359
+ targetVersion,
2360
+ phase: "pending"
2361
+ };
2362
+ })
2363
+ };
2239
2364
  this.jobs.set(job.id, job);
2240
- const unsafe = unsafeSpecReason(spec);
2241
- if (unsafe !== void 0) {
2242
- job.phase = "error";
2243
- job.error = unsafe;
2365
+ this.enqueue(async () => {
2366
+ const native = this.nativeManager();
2367
+ const results = job.results ?? [];
2368
+ for (const [index, entry] of entries.entries()) {
2369
+ const row = results[index];
2370
+ if (row === void 0 || row.phase === "error" || entry.kind === "refused") continue;
2371
+ job.current = entry.id;
2372
+ row.phase = "running";
2373
+ const child = entry.kind === "migrate" ? this.newMigrationJob(entry.id, entry.targetId, entry.targetVersion, entry.targetSpec) : this.newUpdateJob(entry.id, entry.version);
2374
+ this.jobs.set(child.id, child);
2375
+ if (entry.kind === "migrate") await this.settleMigrationJob(child);
2376
+ else await this.settleUpdateJob(child, native);
2377
+ if (child.phase === "done") {
2378
+ row.phase = "done";
2379
+ row.landed = child.plugin?.version ?? (entry.kind === "migrate" ? entry.targetVersion : entry.version);
2380
+ if (child.restartRequired !== void 0 && child.restartRequired.length > 0) row.restartRequired = true;
2381
+ } else {
2382
+ row.phase = "error";
2383
+ row.error = child.error ?? "plugin-manager: 更新失败";
2384
+ }
2385
+ }
2386
+ job.current = void 0;
2387
+ job.phase = "done";
2244
2388
  this.retainFinished(job.id);
2245
- return { jobId: job.id };
2246
- }
2247
- const native = this.nativeManager();
2248
- if (native !== void 0) {
2249
- this.enqueueNativeUpdate(job, native);
2250
- return { jobId: job.id };
2251
- }
2252
- this.enqueue(() => this.run(job, [
2253
- "plugin",
2254
- "--profile",
2255
- this.facts.profileName,
2256
- "add",
2257
- spec
2258
- ], ADD_TIMEOUT_MS));
2389
+ });
2259
2390
  return { jobId: job.id };
2260
2391
  }
2392
+ /**
2393
+ * Run one update job to settlement through whichever writer owns this profile.
2394
+ *
2395
+ * An application-owned profile takes the official in-process manager, which is
2396
+ * the only writer the CLI accepts there; every other runtime keeps the CLI,
2397
+ * whose reconciliation guards this gateway compensates for (see {@link runInner}).
2398
+ * @param job - the update job being settled.
2399
+ * @param native - the official manager, or undefined when the CLI is the writer.
2400
+ */
2401
+ async settleUpdateJob(job, native = this.nativeManager()) {
2402
+ try {
2403
+ if (native !== void 0) await this.runNativeUpdate(job, native);
2404
+ else await this.runInner(job, [
2405
+ "plugin",
2406
+ "--profile",
2407
+ this.facts.profileName,
2408
+ "add",
2409
+ job.spec
2410
+ ], ADD_TIMEOUT_MS);
2411
+ } catch (error) {
2412
+ const reason = error instanceof Error ? error.message : String(error);
2413
+ job.phase = "error";
2414
+ job.error = native !== void 0 ? `plugin-manager: 官方插件管理器更新失败:${reason}` : `plugin-manager: unexpected gateway failure: ${reason}`;
2415
+ }
2416
+ this.retainFinished(job.id);
2417
+ }
2261
2418
  /** Start an install through the official in-process manager. */
2262
2419
  enqueueNativeInstall(job, native) {
2263
2420
  this.enqueue(async () => {
@@ -2314,36 +2471,33 @@ var CliGateway = class {
2314
2471
  }));
2315
2472
  job.phase = "done";
2316
2473
  }
2317
- /** Start an in-place update through the official in-process manager. */
2318
- enqueueNativeUpdate(job, native) {
2319
- this.enqueue(async () => {
2320
- try {
2321
- await this.runNativeUpdate(job, native);
2322
- } catch (error) {
2323
- job.phase = "error";
2324
- job.error = `plugin-manager: 官方插件管理器更新失败:${error instanceof Error ? error.message : String(error)}`;
2325
- }
2326
- this.retainFinished(job.id);
2327
- });
2328
- }
2329
2474
  /**
2330
2475
  * Run one update through the official in-process manager (an application-owned
2331
- * profile, where the CLI refuses to write). The manager resolves the registry,
2332
- * runs pnpm with the launcher's bundled toolchain and applies the bundle, then
2333
- * this reads the profile the same way the CLI path does: the dependency must
2334
- * still be there and the installed version must be the one the route resolved,
2335
- * so a green manager call that changed nothing is still reported as a failure.
2336
- * Its resolved verdict is read first ({@link nativeManagerFailure}): a refused
2337
- * run (pnpm exited non-zero, an incompatible version, a cancellation) resolves
2338
- * with `application: 'failed'`, and only that verdict carries the reason — the
2339
- * profile re-read can only show that the version did not move.
2476
+ * profile, where the CLI refuses to write).
2477
+ *
2478
+ * Since 0.2.2-rc.1 the manager owns the whole replacement: `updateBundle` checks
2479
+ * the target on the registry first (it must exist, declare a bundle and accept
2480
+ * the running DSH version), removes the installed version while the host mounts
2481
+ * `hmr`, installs the target with the selection it found, and reinstalls the
2482
+ * version it removed when that installation fails or is cancelled. This path
2483
+ * therefore no longer sequences those phases itself, and no longer has to
2484
+ * recognise the `already-installed` guard that made an in-place install
2485
+ * impossible. It adds only the two facts the official call does not cover:
2486
+ *
2487
+ * - **The bundle keeps its layer index.** The official removal drops the name
2488
+ * from `dsh.profile.bundles` and the reinstall appends it, and that array is
2489
+ * the layer order the loader applies patches in, so a batch would drift every
2490
+ * row's inheritance ({@link restoreBundleIndex} puts the name back).
2491
+ * - **A `bundle-in-use` refusal is answered once, not repeated** (issue #1905):
2492
+ * the official guard deselects the bundle and reloads before it judges whether
2493
+ * the rows still run, so the retry reads the state that reload left on disk
2494
+ * ({@link applyNativeUpdate}). A second refusal is final and names the restart.
2340
2495
  *
2341
- * An `already-installed` refusal is answered by {@link replaceInstalled}: the
2342
- * manager refuses to install a dependency the profile already carries while the
2343
- * host mounts `hmr` (0.2.1-rc.2, and dsh-base mounts that service on every
2344
- * profile host), so an in-place update there is only expressible as its two
2345
- * phases. The single call stays first so the day the manager accepts an
2346
- * in-place update this path needs no change.
2496
+ * The verdict is read first ({@link nativeUpdateFailure}): a refused run
2497
+ * resolves instead of rejecting, and only that verdict carries the reason — the
2498
+ * profile re-read can only show that the version did not move. The version
2499
+ * verification below is unchanged, so a green run that landed nothing is still
2500
+ * reported as 更新未生效.
2347
2501
  * @param job - the update job being settled.
2348
2502
  * @param native - the official manager.
2349
2503
  */
@@ -2355,28 +2509,27 @@ var CliGateway = class {
2355
2509
  job.error = "plugin-manager: update job is missing the target id or version";
2356
2510
  return;
2357
2511
  }
2358
- const before = await this.capture();
2359
- const carried = await readProfileManifest(this.facts.packageJsonPath);
2360
- const first = await native.installBundle(job.spec, {
2361
- enabled: true,
2362
- requestId: job.id
2363
- });
2364
- let refusal = nativeManagerFailure(first);
2365
- let restartRequired = nativeManagerRestartRequired(first);
2366
- if (refusal !== void 0 && nativeManagerRefusalCode(first) === "already-installed") {
2367
- const replacement = await this.replaceInstalled(job, native, targetId, carried.dependencies[targetId]);
2368
- refusal = replacement.failure;
2369
- restartRequired = replacement.restartRequired;
2512
+ const updateBundle = native.updateBundle?.bind(native);
2513
+ if (updateBundle === void 0) {
2514
+ job.phase = "error";
2515
+ job.error = `plugin-manager: 官方插件管理器没有提供 updateBundle(需要 DSH >= 0.2.2-rc.1),无法在该 profile 上更新 ${targetId}`;
2516
+ return;
2370
2517
  }
2518
+ const before = await this.capture();
2519
+ const previousSpec = (await readProfileManifest(this.facts.packageJsonPath)).dependencies[targetId];
2520
+ const index = await this.bundleIndexOf(targetId);
2521
+ const attempt = await this.applyNativeUpdate(updateBundle, targetId, targetVersion, job.id);
2522
+ const refusal = nativeUpdateFailure(attempt.outcome);
2371
2523
  if (refusal !== void 0) {
2524
+ if (await this.bundleSelectionLost(targetId)) await this.restoreBundleSelection(native, targetId);
2372
2525
  job.phase = "error";
2373
- job.error = `plugin-manager: 官方插件管理器更新失败:${refusal}`;
2526
+ job.error = `plugin-manager: 官方插件管理器更新失败:${refusal}${attempt.remedy}${nativeUpdateRestoreNote(attempt.outcome)}`;
2374
2527
  return;
2375
2528
  }
2376
2529
  const after = await this.capture();
2377
2530
  if (!after.dependencies.includes(targetId)) {
2378
2531
  job.phase = "error";
2379
- job.error = `plugin-manager: 官方插件管理器报告成功,但目标插件未保留在 profile 中(更新未生效)`;
2532
+ job.error = "plugin-manager: 官方插件管理器报告成功,但目标插件未保留在 profile 中(更新未生效)";
2380
2533
  return;
2381
2534
  }
2382
2535
  const manifest = await readProfileManifest(this.facts.packageJsonPath);
@@ -2386,6 +2539,8 @@ var CliGateway = class {
2386
2539
  job.error = `plugin-manager: 官方插件管理器报告成功,但 ${targetId} 仍为 ${updated.version},预期 ${targetVersion}(更新未生效)`;
2387
2540
  return;
2388
2541
  }
2542
+ if (nativeUpdateRestartRequired(attempt.outcome)) job.restartRequired = [targetId];
2543
+ if (previousSpec !== void 0) await this.restoreBundleIndex(targetId, previousSpec, index);
2389
2544
  if (await this.pruneOrphanOverrides(job) === void 0) return;
2390
2545
  job.plugin = updated;
2391
2546
  job.conflicts = significantChanges(diffLayer(before.layer, after.layer)).map((change) => ({
@@ -2394,82 +2549,39 @@ var CliGateway = class {
2394
2549
  from: change.from,
2395
2550
  to: change.to
2396
2551
  }));
2397
- if (restartRequired) job.restartRequired = [targetId];
2398
2552
  job.phase = "done";
2399
2553
  }
2400
2554
  /**
2401
- * Replace an installed bundle with the update job's target spec through the
2402
- * official manager, the only writer an application-owned profile accepts.
2403
- * Removing first is what makes the install possible: the manager's
2404
- * `already-installed` guard reads the profile, so the same name is a fresh
2405
- * dependency once the old one is gone.
2555
+ * Run one official update, answering its `bundle-in-use` removal refusal once.
2406
2556
  *
2407
- * A failed second phase reinstalls the spec the profile carried before the run,
2408
- * so an update that cannot land leaves a working plugin behind instead of an
2409
- * empty slot; the report says which of the two happened.
2410
- *
2411
- * Two facts make the replacement safe to repeat in one session:
2412
- *
2413
- * - **The bundle keeps its layer index.** A removal drops the name from
2414
- * `dsh.profile.bundles` and the reinstall appends it, so a plain
2415
- * remove-then-install moves the bundle behind every bundle that followed it
2416
- * and its patch layer starts overriding rows it never overrode
2417
- * ({@link restoreBundleIndex} puts it back).
2418
- * - **A `bundle-in-use` refusal is answered once, not repeated.** The
2419
- * official guard deselects the bundle and reloads before it checks whether
2420
- * the bundle's rows still run, so a real occupant cleared by that reload is
2421
- * gone on the second call: the update is retried exactly once against that
2422
- * settled state, and a second refusal restores the selection and names the
2423
- * restart the person has to do ({@link removeForReplacement}).
2424
- * - **A landed replacement can still need a restart.** The guard answers
2425
- * `application: 'restart-required'` when the removal applied and the
2426
- * replaced bundle's rows are already gone from the running process (issue
2427
- * #1905). The version does land, so that is a fact to report, not a failure:
2428
- * the update is `done` and names what only a restart loads.
2429
- *
2430
- * @param job - the update job whose spec is installed.
2431
- * @param native - the official manager.
2557
+ * The official guard deselects the bundle, reloads the profile and only then
2558
+ * checks whether the bundle's rows still hold a running fiber. A refusal is
2559
+ * therefore answered against the state that reload left on disk, which covers a
2560
+ * real occupant the reload cleared. It does not cover a reload that rebuilds
2561
+ * the very rows it just unloaded — the fresh fiber matches the guard again — so
2562
+ * the retry is worth exactly one call and never a loop, and a second refusal is
2563
+ * returned with the restart the person has to do.
2564
+ * @param updateBundle - the official manager's update primitive.
2432
2565
  * @param targetId - the installed bundle being replaced.
2433
- * @param previousSpec - the dependency spec the profile carried before the run.
2434
- * @returns the failure to report, or the restart fact once the target landed.
2566
+ * @param targetVersion - the exact version the update must land on.
2567
+ * @param requestId - the job id the run's progress and logs are tracked under.
2568
+ * @returns the manager's verdict for the run that decided the outcome, plus the
2569
+ * remedy text a refusal a retry could not clear needs.
2435
2570
  */
2436
- async replaceInstalled(job, native, targetId, previousSpec) {
2437
- if (previousSpec === void 0) return {
2438
- failure: `${targetId} 不在 profile 依赖中,无法替换已安装版本`,
2439
- restartRequired: false
2571
+ async applyNativeUpdate(updateBundle, targetId, targetVersion, requestId) {
2572
+ const first = await updateBundle(targetId, targetVersion, { requestId });
2573
+ if (nativeUpdateRefusalCode(first) !== "bundle-in-use") return {
2574
+ outcome: first,
2575
+ remedy: ""
2440
2576
  };
2441
- const index = await this.bundleIndexOf(targetId);
2442
- const removal = await this.removeForReplacement(native, targetId);
2443
- if (removal.failure !== void 0) {
2444
- if (removal.deselected) await this.restoreBundleSelection(native, targetId);
2445
- return {
2446
- failure: `已安装版本无法移除(${removal.failure}),本次更新未做改动${removal.remedy}`,
2447
- restartRequired: false
2448
- };
2449
- }
2450
- const installVerdict = await native.installBundle(job.spec, {
2451
- enabled: true,
2452
- requestId: job.id
2453
- });
2454
- const refusal = nativeManagerFailure(installVerdict);
2455
- const restartRequired = removal.restartRequired || nativeManagerRestartRequired(installVerdict);
2456
- if (refusal === void 0) {
2457
- await this.restoreBundleIndex(targetId, previousSpec, index);
2458
- return { restartRequired };
2459
- }
2460
- const restoreSpec = `${targetId}@${previousSpec}`;
2461
- const restoreFailure = nativeManagerFailure(await native.installBundle(restoreSpec, {
2462
- enabled: true,
2463
- requestId: job.id
2464
- }));
2465
- if (restoreFailure !== void 0) return {
2466
- failure: `${refusal};装回 ${restoreSpec} 也失败:${restoreFailure},请手动重新安装`,
2467
- restartRequired: false
2577
+ const second = await updateBundle(targetId, targetVersion, { requestId });
2578
+ if (nativeUpdateRefusalCode(second) !== "bundle-in-use") return {
2579
+ outcome: second,
2580
+ remedy: ""
2468
2581
  };
2469
- await this.restoreBundleIndex(targetId, previousSpec, index);
2470
2582
  return {
2471
- failure: `${refusal};已装回 ${restoreSpec}`,
2472
- restartRequired: false
2583
+ outcome: second,
2584
+ remedy: ";该插件仍由当前 DSH 进程加载,重启 DSH 后再执行本次更新即可"
2473
2585
  };
2474
2586
  }
2475
2587
  /**
@@ -2510,56 +2622,6 @@ var CliGateway = class {
2510
2622
  console.warn(`[plugin-manager] 未能恢复 ${name} 的 bundle 顺序(${spec}):${error instanceof Error ? error.message : String(error)}`);
2511
2623
  }
2512
2624
  }
2513
- /**
2514
- * Remove a bundle for the two-phase replacement, answering the official
2515
- * manager's in-use refusal instead of repeating it.
2516
- *
2517
- * Read the official `removeBundle` guard in order: it deselects the bundle,
2518
- * reloads the profile, and only then checks whether the bundle's own rows
2519
- * still hold a running fiber, which it reports as `bundle-in-use`. A refusal
2520
- * is therefore answered exactly once, against the state that reload left on
2521
- * disk: that covers a real occupant whose fiber the reload did clear.
2522
- *
2523
- * It does not cover a reload that rebuilds the very rows it just unloaded —
2524
- * the fresh fiber matches the guard again — so the retry is worth exactly one
2525
- * call and never a loop, and the second refusal names the restart instead of
2526
- * a bare code. A removal the guard does apply while the rows are already gone
2527
- * resolves as `application: 'restart-required'`; that is a success carrying a
2528
- * restart fact, which is reported as such rather than as a refusal.
2529
- * @param native - the official manager.
2530
- * @param name - the bundle to remove.
2531
- * @returns the refusal to report, whether the profile lost the selection on the
2532
- * way, the remedy text for that refusal, and whether the applied removal still
2533
- * needs a restart to load.
2534
- */
2535
- async removeForReplacement(native, name) {
2536
- const first = await native.removeBundle(name);
2537
- const failure = nativeManagerFailure(first);
2538
- if (failure === void 0) return {
2539
- deselected: false,
2540
- remedy: "",
2541
- restartRequired: nativeManagerRestartRequired(first)
2542
- };
2543
- if (nativeManagerRefusalCode(first) !== "bundle-in-use") return {
2544
- failure,
2545
- deselected: await this.bundleSelectionLost(name),
2546
- remedy: "",
2547
- restartRequired: false
2548
- };
2549
- const second = await native.removeBundle(name);
2550
- const retryFailure = nativeManagerFailure(second);
2551
- if (retryFailure === void 0) return {
2552
- deselected: false,
2553
- remedy: "",
2554
- restartRequired: nativeManagerRestartRequired(second)
2555
- };
2556
- return {
2557
- failure: retryFailure,
2558
- deselected: await this.bundleSelectionLost(name),
2559
- remedy: ";该插件仍由当前 DSH 进程加载,重启 DSH 后再执行本次更新即可",
2560
- restartRequired: false
2561
- };
2562
- }
2563
2625
  /** Whether a bundle is still an installed dependency but no longer selected. */
2564
2626
  async bundleSelectionLost(name) {
2565
2627
  try {
@@ -2580,7 +2642,21 @@ var CliGateway = class {
2580
2642
  }
2581
2643
  /** Start a deterministic legacy aggregate migration. */
2582
2644
  migrate(sourceId, targetId, targetVersion, targetSpec) {
2583
- const job = {
2645
+ const job = this.newMigrationJob(sourceId, targetId, targetVersion, targetSpec);
2646
+ this.jobs.set(job.id, job);
2647
+ const unsafe = unsafeSpecReason(sourceId) ?? unsafeSpecReason(targetId) ?? unsafeSpecReason(targetSpec);
2648
+ if (unsafe !== void 0) {
2649
+ job.phase = "error";
2650
+ job.error = unsafe;
2651
+ this.retainFinished(job.id);
2652
+ return { jobId: job.id };
2653
+ }
2654
+ this.enqueue(() => this.settleMigrationJob(job));
2655
+ return { jobId: job.id };
2656
+ }
2657
+ /** One legacy aggregate migration job, registered but not yet queued. */
2658
+ newMigrationJob(sourceId, targetId, targetVersion, targetSpec) {
2659
+ return {
2584
2660
  id: `job-${++this.counter}`,
2585
2661
  action: "migrate",
2586
2662
  spec: targetSpec,
@@ -2590,26 +2666,22 @@ var CliGateway = class {
2590
2666
  targetSpec,
2591
2667
  phase: "running"
2592
2668
  };
2593
- this.jobs.set(job.id, job);
2594
- const unsafe = unsafeSpecReason(sourceId) ?? unsafeSpecReason(targetId) ?? unsafeSpecReason(targetSpec);
2595
- if (unsafe !== void 0) {
2596
- job.phase = "error";
2597
- job.error = unsafe;
2598
- this.retainFinished(job.id);
2599
- return { jobId: job.id };
2600
- }
2601
- this.enqueue(async () => {
2602
- try {
2603
- await this.runMigration(job);
2604
- } catch (error) {
2605
- if (job.phase !== "error") {
2606
- job.phase = "error";
2607
- job.error = `plugin-manager: unexpected migration failure: ${error instanceof Error ? error.message : String(error)}`;
2608
- }
2669
+ }
2670
+ /**
2671
+ * Run one migration job to settlement; an unexpected failure settles the job
2672
+ * as an error without overwriting a verdict the run already recorded.
2673
+ * @param job - the migration job being settled.
2674
+ */
2675
+ async settleMigrationJob(job) {
2676
+ try {
2677
+ await this.runMigration(job);
2678
+ } catch (error) {
2679
+ if (job.phase !== "error") {
2680
+ job.phase = "error";
2681
+ job.error = `plugin-manager: unexpected migration failure: ${error instanceof Error ? error.message : String(error)}`;
2609
2682
  }
2610
- this.retainFinished(job.id);
2611
- });
2612
- return { jobId: job.id };
2683
+ }
2684
+ this.retainFinished(job.id);
2613
2685
  }
2614
2686
  /**
2615
2687
  * Start a removal; the caller polls {@link status}. An application-owned
@@ -2703,7 +2775,8 @@ var CliGateway = class {
2703
2775
  conflicts: job.conflicts === void 0 ? void 0 : [...job.conflicts],
2704
2776
  notices: job.notices === void 0 ? void 0 : [...job.notices],
2705
2777
  restartRequired: job.restartRequired === void 0 ? void 0 : [...job.restartRequired],
2706
- warnings: job.warnings === void 0 ? void 0 : [...job.warnings]
2778
+ warnings: job.warnings === void 0 ? void 0 : [...job.warnings],
2779
+ results: job.results === void 0 ? void 0 : job.results.map((row) => ({ ...row }))
2707
2780
  };
2708
2781
  }
2709
2782
  /**
@@ -4070,6 +4143,8 @@ const REGISTRY_TIMEOUT_MS = 3e4;
4070
4143
  const VERSION_TIMEOUT_MS = 1e4;
4071
4144
  /** Bounded capture of the version probe output, counted in bytes. */
4072
4145
  const VERSION_MAX_OUTPUT_BYTES = 4096;
4146
+ /** How many plugins one batch update may carry (a page's worth of installed plugins, not a queue). */
4147
+ const MAX_BATCH_UPDATES = 50;
4073
4148
  /** Grace period after SIGTERM before a stuck probe child is SIGKILLed. */
4074
4149
  const VERSION_ESCALATION_TIMEOUT_MS = 5e3;
4075
4150
  /** Successful probe freshness window before the host version is re-read. */
@@ -4303,6 +4378,94 @@ function makeGatewayRoutes(deps) {
4303
4378
  }
4304
4379
  writeJson(res, 200, gateway.install(installSpec));
4305
4380
  };
4381
+ /**
4382
+ * Resolve one update request against the live profile: the exact version to
4383
+ * install, the migration it needs instead, or the refusal that stops it.
4384
+ *
4385
+ * Every answer the update route gives before a job exists — not installed, not
4386
+ * a direct registry plugin, unresolvable version, already at it, a DSH minimum
4387
+ * this host does not satisfy — is produced here, so the single update and the
4388
+ * batch resolve a row by exactly the same rules. A batch turns a refusal into
4389
+ * that row's answer instead of dropping the whole run.
4390
+ * @param target - the installed package name.
4391
+ */
4392
+ const planUpdate = async (target) => {
4393
+ const patchText = await readPatchText(facts.patchPath);
4394
+ const row = (await snapshotGateway(facts, patchText)).plugins.find((plugin) => plugin.id === target);
4395
+ if (row === void 0) return {
4396
+ status: 404,
4397
+ error: `plugin-manager: plugin ${target} is not installed`
4398
+ };
4399
+ const migration = legacyMigrationFor(target);
4400
+ if (migration !== void 0) {
4401
+ const targetManifest = await fetchManifest(migration.to).catch(() => void 0);
4402
+ if (targetManifest === void 0 || targetManifest.version === "") return {
4403
+ status: 502,
4404
+ error: `plugin-manager: cannot resolve the migration target ${migration.to}`
4405
+ };
4406
+ const targetSpec = targetSpecForLegacy(row.source.spec, targetManifest.version);
4407
+ if (targetSpec === void 0) return {
4408
+ status: 400,
4409
+ error: `plugin-manager: cannot derive the migration target spec for ${target}`
4410
+ };
4411
+ const unsafeTarget = unsafeSpecReason(targetSpec);
4412
+ if (unsafeTarget !== void 0) return {
4413
+ status: 400,
4414
+ error: unsafeTarget
4415
+ };
4416
+ const requiresDsh = dshRequirementOf(targetManifest);
4417
+ if (requiresDsh !== void 0) {
4418
+ const { hostVersion, compatible } = await compatibleVerdict(requiresDsh);
4419
+ if (!compatible) return {
4420
+ status: 412,
4421
+ error: hostVersion === void 0 ? `plugin-manager: cannot verify the running DSH version for ${migration.to} against the declared requirement ${requiresDsh}; check the declaration and the DSH runtime before migrating` : `plugin-manager: ${migration.to} requires DSH ${requiresDsh} (current DSH ${hostVersion}); upgrade DSH before migrating`
4422
+ };
4423
+ }
4424
+ return {
4425
+ status: 200,
4426
+ kind: "migrate",
4427
+ targetId: migration.to,
4428
+ targetVersion: targetManifest.version,
4429
+ targetSpec
4430
+ };
4431
+ }
4432
+ if (row.source.kind !== "npm" || !isDirectRegistrySpec(row.source.spec)) return {
4433
+ status: 400,
4434
+ error: `plugin-manager: ${target} is not a direct npm registry plugin`
4435
+ };
4436
+ const manifest = await fetchManifest(target).catch(() => void 0);
4437
+ if (manifest === void 0) return {
4438
+ status: 502,
4439
+ error: `plugin-manager: cannot resolve the latest version for ${target}`
4440
+ };
4441
+ const latest = manifest.version;
4442
+ if (latest === "") return {
4443
+ status: 502,
4444
+ error: `plugin-manager: cannot resolve the latest version for ${target}`
4445
+ };
4446
+ const unsafeLatest = unsafeSpecReason(`${target}@${latest}`);
4447
+ if (unsafeLatest !== void 0) return {
4448
+ status: 502,
4449
+ error: unsafeLatest
4450
+ };
4451
+ if (row.version === latest && !gateway.lastUpdateFailed(target, latest)) return {
4452
+ status: 409,
4453
+ error: `plugin-manager: ${target} is already at ${latest}`
4454
+ };
4455
+ const requiresDsh = dshRequirementOf(manifest);
4456
+ if (requiresDsh !== void 0) {
4457
+ const { hostVersion, compatible } = await compatibleVerdict(requiresDsh);
4458
+ if (!compatible) return {
4459
+ status: 412,
4460
+ error: hostVersion === void 0 ? `plugin-manager: cannot verify the running DSH version for ${target} against the declared requirement ${requiresDsh}; check the declaration and the DSH runtime before updating` : `plugin-manager: ${target} requires DSH ${requiresDsh} (current DSH ${hostVersion}); upgrade DSH before updating`
4461
+ };
4462
+ }
4463
+ return {
4464
+ status: 200,
4465
+ kind: "update",
4466
+ version: latest
4467
+ };
4468
+ };
4306
4469
  const updateHandler = async (req, res) => {
4307
4470
  const id = (await readJsonBody(req, {
4308
4471
  maxBytes: 64 * 1024,
@@ -4323,76 +4486,14 @@ function makeGatewayRoutes(deps) {
4323
4486
  return;
4324
4487
  }
4325
4488
  const outcome = await gateway.withMutationLock(async () => {
4326
- const patchText = await readPatchText(facts.patchPath);
4327
- const row = (await snapshotGateway(facts, patchText)).plugins.find((plugin) => plugin.id === target);
4328
- if (row === void 0) return {
4329
- status: 404,
4330
- error: `plugin-manager: plugin ${target} is not installed`
4331
- };
4332
- const migration = legacyMigrationFor(target);
4333
- if (migration !== void 0) {
4334
- const targetManifest = await fetchManifest(migration.to).catch(() => void 0);
4335
- if (targetManifest === void 0 || targetManifest.version === "") return {
4336
- status: 502,
4337
- error: `plugin-manager: cannot resolve the migration target ${migration.to}`
4338
- };
4339
- const targetSpec = targetSpecForLegacy(row.source.spec, targetManifest.version);
4340
- if (targetSpec === void 0) return {
4341
- status: 400,
4342
- error: `plugin-manager: cannot derive the migration target spec for ${target}`
4343
- };
4344
- const unsafeTarget = unsafeSpecReason(targetSpec);
4345
- if (unsafeTarget !== void 0) return {
4346
- status: 400,
4347
- error: unsafeTarget
4348
- };
4349
- const requiresDsh = dshRequirementOf(targetManifest);
4350
- if (requiresDsh !== void 0) {
4351
- const { hostVersion, compatible } = await compatibleVerdict(requiresDsh);
4352
- if (!compatible) return {
4353
- status: 412,
4354
- error: hostVersion === void 0 ? `plugin-manager: cannot verify the running DSH version for ${migration.to} against the declared requirement ${requiresDsh}; check the declaration and the DSH runtime before migrating` : `plugin-manager: ${migration.to} requires DSH ${requiresDsh} (current DSH ${hostVersion}); upgrade DSH before migrating`
4355
- };
4356
- }
4357
- return {
4358
- status: 200,
4359
- job: gateway.migrate(target, migration.to, targetManifest.version, targetSpec)
4360
- };
4361
- }
4362
- if (row.source.kind !== "npm" || !isDirectRegistrySpec(row.source.spec)) return {
4363
- status: 400,
4364
- error: `plugin-manager: ${target} is not a direct npm registry plugin`
4365
- };
4366
- const manifest = await fetchManifest(target).catch(() => void 0);
4367
- if (manifest === void 0) return {
4368
- status: 502,
4369
- error: `plugin-manager: cannot resolve the latest version for ${target}`
4370
- };
4371
- const latest = manifest.version;
4372
- if (latest === "") return {
4373
- status: 502,
4374
- error: `plugin-manager: cannot resolve the latest version for ${target}`
4375
- };
4376
- const unsafeLatest = unsafeSpecReason(`${target}@${latest}`);
4377
- if (unsafeLatest !== void 0) return {
4378
- status: 502,
4379
- error: unsafeLatest
4380
- };
4381
- if (row.version === latest && !gateway.lastUpdateFailed(target, latest)) return {
4382
- status: 409,
4383
- error: `plugin-manager: ${target} is already at ${latest}`
4384
- };
4385
- const requiresDsh = dshRequirementOf(manifest);
4386
- if (requiresDsh !== void 0) {
4387
- const { hostVersion, compatible } = await compatibleVerdict(requiresDsh);
4388
- if (!compatible) return {
4389
- status: 412,
4390
- error: hostVersion === void 0 ? `plugin-manager: cannot verify the running DSH version for ${target} against the declared requirement ${requiresDsh}; check the declaration and the DSH runtime before updating` : `plugin-manager: ${target} requires DSH ${requiresDsh} (current DSH ${hostVersion}); upgrade DSH before updating`
4391
- };
4392
- }
4393
- return {
4394
- status: 200,
4395
- job: gateway.update(target, latest)
4489
+ const plan = await planUpdate(target);
4490
+ if ("error" in plan) return plan;
4491
+ return plan.kind === "migrate" ? {
4492
+ status: plan.status,
4493
+ job: gateway.migrate(target, plan.targetId, plan.targetVersion, plan.targetSpec)
4494
+ } : {
4495
+ status: plan.status,
4496
+ job: gateway.update(target, plan.version)
4396
4497
  };
4397
4498
  });
4398
4499
  if ("error" in outcome) {
@@ -4401,6 +4502,74 @@ function makeGatewayRoutes(deps) {
4401
4502
  }
4402
4503
  writeJson(res, outcome.status, outcome.job);
4403
4504
  };
4505
+ /**
4506
+ * Apply every listed plugin update in one run.
4507
+ *
4508
+ * The official manager updates one bundle at a time and the CLI adds one spec
4509
+ * at a time, so the batch is this gateway's sequence over that single-plugin
4510
+ * primitive: one job, one mutation-lock slot, one poll, and one ledger of rows.
4511
+ * Each id is resolved here first, exactly as a single update is, and a row that
4512
+ * cannot be resolved is carried into the job as its own answer rather than
4513
+ * failing the request — one plugin already at its newest version must not stop
4514
+ * the eight behind it.
4515
+ */
4516
+ const updatesHandler = async (req, res) => {
4517
+ const listed = (await readJsonBody(req, {
4518
+ maxBytes: 64 * 1024,
4519
+ objectOnly: true
4520
+ }) ?? {})["ids"];
4521
+ if (!Array.isArray(listed) || listed.length === 0) {
4522
+ writeJson(res, 400, { error: "plugin-manager: updates needs a non-empty ids array" });
4523
+ return;
4524
+ }
4525
+ if (listed.length > MAX_BATCH_UPDATES) {
4526
+ writeJson(res, 400, { error: `plugin-manager: updates accepts at most ${String(MAX_BATCH_UPDATES)} ids` });
4527
+ return;
4528
+ }
4529
+ const targets = [];
4530
+ for (const value of listed) {
4531
+ if (typeof value !== "string" || value.trim() === "") {
4532
+ writeJson(res, 400, { error: "plugin-manager: updates needs string ids" });
4533
+ return;
4534
+ }
4535
+ const target = value.trim();
4536
+ const unsafe = unsafeSpecReason(target);
4537
+ if (unsafe !== void 0) {
4538
+ writeJson(res, 400, { error: unsafe });
4539
+ return;
4540
+ }
4541
+ if (!targets.includes(target)) targets.push(target);
4542
+ }
4543
+ if (!deps.cliAvailable() && !gateway.usesNativeWriter()) {
4544
+ writeJson(res, 500, { error: "plugin-manager: dsh CLI not found on PATH" });
4545
+ return;
4546
+ }
4547
+ const entries = await gateway.withMutationLock(async () => {
4548
+ const plan = [];
4549
+ for (const target of targets) {
4550
+ const row = await planUpdate(target);
4551
+ if ("error" in row) plan.push({
4552
+ kind: "refused",
4553
+ id: target,
4554
+ error: row.error
4555
+ });
4556
+ else if (row.kind === "migrate") plan.push({
4557
+ kind: "migrate",
4558
+ id: target,
4559
+ targetId: row.targetId,
4560
+ targetVersion: row.targetVersion,
4561
+ targetSpec: row.targetSpec
4562
+ });
4563
+ else plan.push({
4564
+ kind: "apply",
4565
+ id: target,
4566
+ version: row.version
4567
+ });
4568
+ }
4569
+ return plan;
4570
+ });
4571
+ writeJson(res, 200, gateway.updateAll(entries));
4572
+ };
4404
4573
  const removeHandler = async (req, res) => {
4405
4574
  const id = (await readJsonBody(req, {
4406
4575
  maxBytes: 64 * 1024,
@@ -4602,6 +4771,11 @@ function makeGatewayRoutes(deps) {
4602
4771
  path: `${GATEWAY_PREFIX}/update`,
4603
4772
  handler: guard(updateHandler)
4604
4773
  },
4774
+ {
4775
+ kind: "exact",
4776
+ path: `${GATEWAY_PREFIX}/updates`,
4777
+ handler: guard(updatesHandler)
4778
+ },
4605
4779
  {
4606
4780
  kind: "exact",
4607
4781
  path: `${GATEWAY_PREFIX}/remove`,