dsh-crate 0.0.0-stage → 0.5.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.
Files changed (132) hide show
  1. package/LICENSE +27 -0
  2. package/README.md +288 -2
  3. package/README.zh.md +263 -0
  4. package/UPDATE-API-V1.md +207 -0
  5. package/assets/logo.svg +37 -0
  6. package/client/client.js +18964 -0
  7. package/cordis.patch.yml +4 -0
  8. package/lib/accelerate.js +194 -0
  9. package/lib/agents.js +67 -0
  10. package/lib/backup.js +688 -0
  11. package/lib/body-progress.js +173 -0
  12. package/lib/catalog-local-match.js +160 -0
  13. package/lib/catalog-npm.js +180 -0
  14. package/lib/changelog.js +462 -0
  15. package/lib/channels.js +64 -0
  16. package/lib/check.js +1557 -0
  17. package/lib/compatibility.js +243 -0
  18. package/lib/crate-catalog.js +179 -0
  19. package/lib/diagnostics.js +49 -0
  20. package/lib/discovery-compatibility.js +447 -0
  21. package/lib/drain-journal.js +164 -0
  22. package/lib/drain.js +1043 -0
  23. package/lib/dsh-cli.js +1373 -0
  24. package/lib/dsh-install.js +259 -0
  25. package/lib/entry-identity.js +85 -0
  26. package/lib/gist.js +369 -0
  27. package/lib/groups.js +108 -0
  28. package/lib/home-paths.js +29 -0
  29. package/lib/host-recovery.js +187 -0
  30. package/lib/hot.js +871 -0
  31. package/lib/http.js +252 -0
  32. package/lib/index.js +394 -0
  33. package/lib/install.js +1147 -0
  34. package/lib/lifecycle.js +37 -0
  35. package/lib/log-redaction.js +24 -0
  36. package/lib/log.js +204 -0
  37. package/lib/ndjson.js +154 -0
  38. package/lib/net.js +174 -0
  39. package/lib/official-desktop.js +619 -0
  40. package/lib/order.js +284 -0
  41. package/lib/patch.js +943 -0
  42. package/lib/pending-rows.js +142 -0
  43. package/lib/pending-updates.js +346 -0
  44. package/lib/pnpm-compat.js +972 -0
  45. package/lib/presets.js +282 -0
  46. package/lib/probe-context.js +20 -0
  47. package/lib/proc-text.js +69 -0
  48. package/lib/profile.js +1978 -0
  49. package/lib/recovery.js +1059 -0
  50. package/lib/region-probe.js +93 -0
  51. package/lib/regions.js +283 -0
  52. package/lib/registry.js +308 -0
  53. package/lib/release-candidates.js +115 -0
  54. package/lib/release-updates.js +70 -0
  55. package/lib/restart.js +688 -0
  56. package/lib/routes.js +7960 -0
  57. package/lib/settings.js +164 -0
  58. package/lib/shelfry-catalog.js +179 -0
  59. package/lib/snapshot.js +506 -0
  60. package/lib/source-migration.js +164 -0
  61. package/lib/sources.js +1005 -0
  62. package/lib/state.js +38 -0
  63. package/lib/store.js +163 -0
  64. package/lib/themes.js +350 -0
  65. package/lib/trial.js +125 -0
  66. package/lib/types/accelerate.d.ts +85 -0
  67. package/lib/types/agents.d.ts +52 -0
  68. package/lib/types/backup.d.ts +171 -0
  69. package/lib/types/body-progress.d.ts +94 -0
  70. package/lib/types/catalog-local-match.d.ts +39 -0
  71. package/lib/types/catalog-npm.d.ts +77 -0
  72. package/lib/types/changelog.d.ts +131 -0
  73. package/lib/types/channels.d.ts +56 -0
  74. package/lib/types/check.d.ts +353 -0
  75. package/lib/types/compatibility.d.ts +83 -0
  76. package/lib/types/crate-catalog.d.ts +48 -0
  77. package/lib/types/diagnostics.d.ts +29 -0
  78. package/lib/types/discovery-compatibility.d.ts +145 -0
  79. package/lib/types/drain-journal.d.ts +25 -0
  80. package/lib/types/drain.d.ts +306 -0
  81. package/lib/types/dsh-cli.d.ts +481 -0
  82. package/lib/types/dsh-install.d.ts +106 -0
  83. package/lib/types/entry-identity.d.ts +68 -0
  84. package/lib/types/gist.d.ts +79 -0
  85. package/lib/types/groups.d.ts +34 -0
  86. package/lib/types/home-paths.d.ts +13 -0
  87. package/lib/types/host-recovery.d.ts +95 -0
  88. package/lib/types/hot.d.ts +405 -0
  89. package/lib/types/http.d.ts +114 -0
  90. package/lib/types/index.d.ts +52 -0
  91. package/lib/types/install.d.ts +463 -0
  92. package/lib/types/lifecycle.d.ts +14 -0
  93. package/lib/types/log-redaction.d.ts +2 -0
  94. package/lib/types/log.d.ts +43 -0
  95. package/lib/types/ndjson.d.ts +52 -0
  96. package/lib/types/net.d.ts +94 -0
  97. package/lib/types/official-desktop.d.ts +59 -0
  98. package/lib/types/order.d.ts +100 -0
  99. package/lib/types/patch.d.ts +218 -0
  100. package/lib/types/pending-rows.d.ts +81 -0
  101. package/lib/types/pending-updates.d.ts +161 -0
  102. package/lib/types/pnpm-compat.d.ts +102 -0
  103. package/lib/types/presets.d.ts +94 -0
  104. package/lib/types/probe-context.d.ts +14 -0
  105. package/lib/types/proc-text.d.ts +29 -0
  106. package/lib/types/profile.d.ts +551 -0
  107. package/lib/types/recovery.d.ts +342 -0
  108. package/lib/types/region-probe.d.ts +50 -0
  109. package/lib/types/regions.d.ts +134 -0
  110. package/lib/types/registry.d.ts +160 -0
  111. package/lib/types/release-candidates.d.ts +42 -0
  112. package/lib/types/release-updates.d.ts +15 -0
  113. package/lib/types/restart.d.ts +279 -0
  114. package/lib/types/routes.d.ts +130 -0
  115. package/lib/types/settings.d.ts +112 -0
  116. package/lib/types/shelfry-catalog.d.ts +48 -0
  117. package/lib/types/snapshot.d.ts +93 -0
  118. package/lib/types/source-migration.d.ts +100 -0
  119. package/lib/types/sources.d.ts +391 -0
  120. package/lib/types/state.d.ts +20 -0
  121. package/lib/types/store.d.ts +47 -0
  122. package/lib/types/themes.d.ts +46 -0
  123. package/lib/types/trial.d.ts +61 -0
  124. package/lib/types/update-api-v1.d.ts +83 -0
  125. package/lib/types/updates.d.ts +273 -0
  126. package/lib/types/verify.d.ts +277 -0
  127. package/lib/update-api-v1.js +273 -0
  128. package/lib/updates.js +981 -0
  129. package/lib/verify.js +904 -0
  130. package/locale/en.json +5 -0
  131. package/locale/zh.json +6 -0
  132. package/package.json +113 -4
package/lib/state.js ADDED
@@ -0,0 +1,38 @@
1
+ import { existsSync, renameSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ /**
4
+ * 每个 profile 的状态目录名。
5
+ * 0.5 起由 `.dsh-shelfry` 改为 `.dsh-crate`,旧目录在首次访问时就地改名。
6
+ */
7
+ export const STATE_DIR_NAME = '.dsh-crate';
8
+ /** 0.4.x 使用的旧目录名,只用于迁移,不再写入。 */
9
+ const LEGACY_STATE_DIR_NAME = '.dsh-shelfry';
10
+ /**
11
+ * 返回可用的状态目录。
12
+ *
13
+ * 入参:profileDir —— profile 根目录的绝对路径。
14
+ * 返回:新目录路径;旧目录存在且新目录不存在时,先把旧目录改名再返回。
15
+ * 改名失败时回退到旧目录,保证数据仍可读写,不影响启动。
16
+ */
17
+ export function stateDir(profileDir) {
18
+ const current = join(profileDir, STATE_DIR_NAME);
19
+ const legacy = join(profileDir, LEGACY_STATE_DIR_NAME);
20
+ if (existsSync(current) || !existsSync(legacy))
21
+ return current;
22
+ try {
23
+ renameSync(legacy, current);
24
+ return current;
25
+ }
26
+ catch {
27
+ return legacy;
28
+ }
29
+ }
30
+ /**
31
+ * 拼出状态目录下的文件路径。
32
+ *
33
+ * 入参:profileDir —— profile 根目录;parts —— 目录内的相对路径片段。
34
+ * 返回:完成迁移后的绝对路径。
35
+ */
36
+ export function statePath(profileDir, ...parts) {
37
+ return join(stateDir(profileDir), ...parts);
38
+ }
package/lib/store.js ADDED
@@ -0,0 +1,163 @@
1
+ /**
2
+ * pnpm store hygiene: reclaim staging directories orphaned by aborted runs,
3
+ * and the profile-side quarantine pnpm never empties (`node_modules/.ignored`).
4
+ *
5
+ * pnpm extracts every fetched tarball under the store's `tmp/` directory as
6
+ * `tmp/_tmp_<pid>_<hex>/`. A run that is killed, cancelled, or timed out —
7
+ * or one that hard-fails mid-fetch — never finishes that staging step, so
8
+ * the directory survives. For `github:` sources the staged payload is the
9
+ * WHOLE repository tarball, so a single aborted install can leave hundreds
10
+ * of megabytes behind (e.g. an OpenViking monorepo install killed at ~88MB).
11
+ *
12
+ * The directory name carries the owning pnpm process id, which makes
13
+ * reclamation safe by construction: when that pid is gone, no live download
14
+ * can be using the directory. Live pnpm tmp dirs are never touched.
15
+ *
16
+ * Separately, under `nodeLinker: hoisted` pnpm moves alien / interrupted
17
+ * package directories into `node_modules/.ignored` and never reclaims them
18
+ * (#974; pnpm #13720). Those copies are already out of the tree — Node does
19
+ * not resolve through `.ignored` — so they are safe to delete once our pnpm
20
+ * process has exited. The pid in a `_tmp_<pid>_` name is historical there
21
+ * and is not consulted (Windows reuses pids; a live match would skip a
22
+ * dead quarantine). `.bak` leftovers stay: they are someone else's wreckage,
23
+ * not pnpm staging (#205, #974).
24
+ */
25
+ import { readdirSync, rmSync } from 'node:fs';
26
+ import { isAbsolute, join } from 'node:path';
27
+ import { logEvent } from './log.js';
28
+ /** pnpm store tmp staging prefix: `_tmp_<pid>_<random-hex>/`. */
29
+ const ORPHAN_TMP_RE = /^_tmp_(\d+)_/;
30
+ /** True when the process with this pid is still running (EPERM = exists). */
31
+ function pidAlive(pid) {
32
+ try {
33
+ process.kill(pid, 0);
34
+ return true;
35
+ }
36
+ catch (error) {
37
+ return error.code === 'EPERM';
38
+ }
39
+ }
40
+ /**
41
+ * Remove every orphaned staging directory under a pnpm store's `tmp/` whose
42
+ * owning pid is no longer alive. Directories that do not match the pnpm
43
+ * staging shape, and any that are locked or in use, are left alone.
44
+ * @param storePath - the pnpm store root (as printed by `pnpm store path`).
45
+ * @returns the removed directory names.
46
+ */
47
+ export function cleanOrphanedStoreTmp(storePath) {
48
+ const tmp = join(storePath, 'tmp');
49
+ let entries;
50
+ try {
51
+ entries = readdirSync(tmp, { withFileTypes: true });
52
+ }
53
+ catch {
54
+ return []; // no store tmp dir — nothing to reclaim
55
+ }
56
+ const removed = [];
57
+ for (const entry of entries) {
58
+ if (!entry.isDirectory())
59
+ continue;
60
+ const m = ORPHAN_TMP_RE.exec(entry.name);
61
+ if (m === null)
62
+ continue;
63
+ const pid = Number(m[1]);
64
+ if (pid > 0 && pidAlive(pid))
65
+ continue;
66
+ try {
67
+ rmSync(join(tmp, entry.name), { recursive: true, force: true });
68
+ removed.push(entry.name);
69
+ }
70
+ catch {
71
+ // Locked or still being written — leave it for a later run.
72
+ }
73
+ }
74
+ return removed;
75
+ }
76
+ /**
77
+ * Resolve the active profile's pnpm store root through the same runner the
78
+ * market uses for installs (so both the web and Desktop pnpm paths agree)
79
+ * and reclaim its orphaned staging directories.
80
+ * @returns the removed directory names, empty when the store cannot be resolved.
81
+ */
82
+ export async function cleanOrphanedStore(run, profile) {
83
+ let result;
84
+ try {
85
+ result = await run(profile, ['store', 'path']);
86
+ }
87
+ catch {
88
+ return [];
89
+ }
90
+ if (result.exitCode !== 0 || result.cancelled)
91
+ return [];
92
+ const lines = result.stdout.split('\n').map(line => line.trim()).filter(line => line !== '');
93
+ const storePath = lines[lines.length - 1] ?? '';
94
+ if (storePath === '' || !isAbsolute(storePath))
95
+ return [];
96
+ const removed = cleanOrphanedStoreTmp(storePath);
97
+ if (removed.length > 0) {
98
+ logEvent('info', 'install', `removed ${removed.length} orphaned pnpm store tmp dir(s) under ${storePath}: ${removed.slice(0, 3).join(', ')}${removed.length > 3 ? ', …' : ''}`);
99
+ }
100
+ return removed;
101
+ }
102
+ /** Same `.bak` shapes backup.ts refuses to re-export (#205). */
103
+ const BAK_NAME = /\.bak\b/;
104
+ /**
105
+ * Remove quarantined copies under the profile's `node_modules/.ignored`,
106
+ * except `.bak` leftovers. Scoped directories are walked one level so a
107
+ * leftover `@jimp/png` is reclaimed without deleting `@scope/foo.bak-*`.
108
+ * Locked entries are left for a later run.
109
+ */
110
+ export function cleanOrphanedIgnored(profileDirectory) {
111
+ const ignored = join(profileDirectory, 'node_modules', '.ignored');
112
+ let entries;
113
+ try {
114
+ entries = readdirSync(ignored, { withFileTypes: true });
115
+ }
116
+ catch {
117
+ return [];
118
+ }
119
+ const removed = [];
120
+ for (const entry of entries) {
121
+ if (BAK_NAME.test(entry.name))
122
+ continue;
123
+ const path = join(ignored, entry.name);
124
+ if (entry.isDirectory() && entry.name.startsWith('@')) {
125
+ let children;
126
+ try {
127
+ children = readdirSync(path, { withFileTypes: true });
128
+ }
129
+ catch {
130
+ continue;
131
+ }
132
+ let kept = 0;
133
+ for (const child of children) {
134
+ if (BAK_NAME.test(child.name)) {
135
+ kept += 1;
136
+ continue;
137
+ }
138
+ try {
139
+ rmSync(join(path, child.name), { recursive: true, force: true });
140
+ removed.push(`${entry.name}/${child.name}`);
141
+ }
142
+ catch {
143
+ kept += 1;
144
+ }
145
+ }
146
+ if (kept === 0) {
147
+ try {
148
+ rmSync(path, { recursive: true, force: true });
149
+ }
150
+ catch { /* leave the empty scope */ }
151
+ }
152
+ continue;
153
+ }
154
+ try {
155
+ rmSync(path, { recursive: true, force: true });
156
+ removed.push(entry.name);
157
+ }
158
+ catch {
159
+ // Locked or still being written — leave it for a later run.
160
+ }
161
+ }
162
+ return removed;
163
+ }
package/lib/themes.js ADDED
@@ -0,0 +1,350 @@
1
+ /**
2
+ * Theme lifecycle: classifying installed packages as themes (by the
3
+ * registry's theme category), live-toggling bundle-layer entries through
4
+ * the loader, and keeping exactly one theme active with the choice
5
+ * persisted across restarts.
6
+ */
7
+ import { readFileSync } from 'node:fs';
8
+ import { join } from 'node:path';
9
+ import { loadRegistry, pluginCategories } from './registry.js';
10
+ import { hotMount, hotUnmount, listHotMounts, writeDisabled } from './hot.js';
11
+ import { logEvent } from './log.js';
12
+ import { loaderEntryId } from './patch.js';
13
+ import { LifecyclePendingError, LifecycleWaitError, waitForLifecycle } from './lifecycle.js';
14
+ import { nameMatchesPackage } from './entry-identity.js';
15
+ import { bundlePatchInsertedIds, profileDir, readInstalled } from './profile.js';
16
+ import { parseSourceUrl, repoOfTarget } from './sources.js';
17
+ /**
18
+ * Whether an installed package declares itself a skin.
19
+ *
20
+ * The market's own criterion for "this is a theme" is the catalog, and the
21
+ * catalog does not list every skin a monorepo ships: the reporter's second
22
+ * skin is absent from it entirely, while the MANAGER that ships with them is
23
+ * a package from the same repo. Judging by repo alone made the manager a
24
+ * theme, so activating any other theme switched it off — and with it the
25
+ * user's own skin-management UI (#519). Both skins ship `skin.json` at their
26
+ * root (it names the package and its wiring); the manager ships none, which
27
+ * is the distinction the reporter pointed at.
28
+ */
29
+ function hasSkinManifest(profileDirectory, name) {
30
+ try {
31
+ const manifest = JSON.parse(readFileSync(join(profileDirectory, 'node_modules', name, 'skin.json'), 'utf8'));
32
+ return typeof manifest.id === 'string' && manifest.id !== '';
33
+ }
34
+ catch {
35
+ return false;
36
+ }
37
+ }
38
+ /**
39
+ * Whether a loader entry belongs to `packageName`.
40
+ *
41
+ * A bundle patch need not name its own package. Two shapes exist (#619, the
42
+ * toggle-side half of #71):
43
+ *
44
+ * - a SUBPATH entry — `aegis` mounts `aegis/extensions/dsh/index.js`,
45
+ * `toolshrink` mounts `toolshrink/harness`. Matched with the same `name/`
46
+ * bound `liveIncludes()` uses, so a differently-suffixed package
47
+ * (`toolshrink-extra`) can never match.
48
+ * - a CARRIER bundle — `@deepseek-ai/dsh-experimental-agent-team-profile`
49
+ * mounts entries named `@deepseek-ai/dsh-experimental-agent-team` and
50
+ * `@deepseek-ai/dsh-experimental-tool-agent-team`. There is no name
51
+ * relation at all, so this falls back to the entry id the package's own
52
+ * patch inserts — the rule `carriedRowLive()` uses (#156).
53
+ */
54
+ /**
55
+ * The bare package a loader entry's own name points at.
56
+ *
57
+ * `dsh-taiwind` and `aegis/extensions/dsh/index.js` both name a package;
58
+ * relative paths, absolute paths, URLs and cordis builtins name none. Unlike
59
+ * `packageOfEntryName()` this keeps a lone bare name, which is exactly the
60
+ * shape #1089 is about.
61
+ */
62
+ function namedPackage(entryName) {
63
+ if (typeof entryName !== 'string' || entryName === '')
64
+ return null;
65
+ if (entryName.startsWith('.') || entryName.startsWith('/') || entryName.startsWith('cordis:'))
66
+ return null;
67
+ if (entryName.includes('://'))
68
+ return null;
69
+ const parts = entryName.split('/');
70
+ // A scoped name needs `@scope/pkg` to be a package at all.
71
+ if (parts[0].startsWith('@'))
72
+ return parts.length >= 2 ? `${parts[0]}/${parts[1]}` : null;
73
+ return parts[0];
74
+ }
75
+ function ownsLoaderEntry(entry, packageName, ownedIds) {
76
+ const entryName = entry.options.name;
77
+ if (nameMatchesPackage(entryName, packageName))
78
+ return true;
79
+ // A YAML `id: 1` reaches the loader as a NUMBER (#1071); `.split` on it
80
+ // threw and took the caller down.
81
+ const id = loaderEntryId(entry);
82
+ if (id === '')
83
+ return false;
84
+ // Loader ids may carry an include prefix (`include:<key>:<id>`); the bare
85
+ // id is what a bundle patch declares.
86
+ return ownedIds.has(id.split(':').pop() ?? id);
87
+ }
88
+ /**
89
+ * Create the theme manager. `disabledThemes` is the live, shared set of
90
+ * themes the user switched off — the caller owns reading it at boot and
91
+ * replaying it; the manager mutates and persists it on switches.
92
+ */
93
+ export function createThemeManager(host, profile, disabledThemes, explicitDir) {
94
+ const activeProfileDir = profileDir(profile, explicitDir);
95
+ /** Installed package names classified as themes by the registry's theme category. */
96
+ async function installedThemeNames() {
97
+ const names = new Set();
98
+ try {
99
+ const registry = await loadRegistry();
100
+ const themeEntries = registry.plugins.filter(p => pluginCategories(p).includes('theme'));
101
+ const themeNames = new Set(themeEntries.map(p => p.name));
102
+ // Repo → the subdirectories its catalog entries point at, plus whether
103
+ // any entry is the repo itself. One repository can ship several PACKAGES
104
+ // — a skin manager and its skins — and matching by repo alone made every
105
+ // one of them a theme, so activating another theme switched the manager
106
+ // off too, taking the user's own management UI with it (#519).
107
+ const themeRepos = new Map();
108
+ for (const entry of themeEntries) {
109
+ const parsed = parseSourceUrl(entry.url);
110
+ if (parsed === null)
111
+ continue;
112
+ const key = parsed.repo.toLowerCase();
113
+ const record = themeRepos.get(key) ?? { root: false, subpaths: new Set() };
114
+ if (parsed.subpath === null)
115
+ record.root = true;
116
+ else
117
+ record.subpaths.add(parsed.subpath.toLowerCase());
118
+ themeRepos.set(key, record);
119
+ }
120
+ for (const [name, spec] of Object.entries(readInstalled(profile, activeProfileDir))) {
121
+ if (themeNames.has(name)) {
122
+ names.add(name);
123
+ continue;
124
+ }
125
+ const identity = repoOfTarget(String(spec).toLowerCase());
126
+ if (identity === null)
127
+ continue;
128
+ const at = identity.indexOf('#path:/');
129
+ const repo = at === -1 ? identity : identity.slice(0, at);
130
+ const subpath = at === -1 ? null : identity.slice(at + '#path:/'.length);
131
+ const record = themeRepos.get(repo);
132
+ if (record === undefined)
133
+ continue;
134
+ // Only a repo whose themes ALL live in subdirectories can be told
135
+ // apart this way. A catalog entry at the repo root says nothing about
136
+ // subdirectories, so that shape keeps the permissive match it had —
137
+ // which is also what keeps a monorepo skin working when the entry
138
+ // points at the repo.
139
+ if (subpath !== null && !record.root && record.subpaths.size > 0
140
+ && !record.subpaths.has(subpath) && !hasSkinManifest(activeProfileDir, name))
141
+ continue;
142
+ names.add(name);
143
+ }
144
+ }
145
+ catch { /* registry unavailable — nothing classifies as a theme */ }
146
+ return names;
147
+ }
148
+ /**
149
+ * Live-toggle a bundle-layer plugin through its loader entry. Bundle trees
150
+ * are in-memory (write is a no-op), so this never touches any file — the
151
+ * market persists the choice itself and replays it at boot.
152
+ * @returns true when a matching live entry was found and updated.
153
+ */
154
+ /** Every loader entry that belongs to this package (its own rows and names). */
155
+ function matchingEntries(name) {
156
+ const ownedIds = new Set(bundlePatchInsertedIds(join(activeProfileDir, 'node_modules', name)));
157
+ let installed = null;
158
+ return [...host.loader.entries()].filter(entry => {
159
+ if (!ownsLoaderEntry(entry, name, ownedIds))
160
+ return false;
161
+ // An entry whose name IS another installed package belongs to that
162
+ // package, even when this package's patch also declares its id
163
+ // (#1089: `dsh-tauri-pet` re-declared `dsh-taiwind`, so switching the
164
+ // pet off took tailwind's stylesheet down on every boot). The id
165
+ // fallback stays for CARRIER bundles (#619), whose carried packages are
166
+ // dependencies — the profile's own rows do not list them.
167
+ const owner = namedPackage(entry.options.name);
168
+ if (owner === null || owner === name)
169
+ return true;
170
+ installed ??= new Set(Object.keys(readInstalled(profile, activeProfileDir)));
171
+ return !installed.has(owner);
172
+ });
173
+ }
174
+ /**
175
+ * Entries whose last update did not settle.
176
+ *
177
+ * A rejected update leaves the loader object in a state nobody can describe,
178
+ * so a later ENABLE of the same entry is refused until a disable (which
179
+ * cannot make things worse) has been seen through. Without this an enable
180
+ * after a crashed disable reports success over a fiber that is not there.
181
+ */
182
+ const uncertainEntries = new WeakSet();
183
+ async function updateEntry(entry, disabled, restoring = false) {
184
+ if (!disabled && !restoring && uncertainEntries.has(entry)) {
185
+ throw new LifecycleWaitError('loader entry: runtime state is uncertain; retry disabling before enabling');
186
+ }
187
+ try {
188
+ await waitForLifecycle(entry, () => entry.update({ disabled }, false, true), `${entry.options.name ?? entry.options.id ?? 'entry'}: loader update`);
189
+ uncertainEntries.delete(entry);
190
+ }
191
+ catch (error) {
192
+ uncertainEntries.add(entry);
193
+ throw error;
194
+ }
195
+ }
196
+ /**
197
+ * Live-toggle a bundle-layer plugin through its loader entry.
198
+ *
199
+ * `requireLive` is the strict mode: the caller needs the requested state to
200
+ * be true when this returns, so an update that does not settle is an error
201
+ * rather than a log line, and every entry touched on the way is restored to
202
+ * the state it had before (#575, #582). The legacy theme and boot-replay
203
+ * callers keep the best-effort semantics they were written against.
204
+ *
205
+ * @returns true when a matching live entry was found and updated.
206
+ */
207
+ async function setEntryDisabled(name, disabledFlag, requireLive = false, rejectPending = false) {
208
+ const previous = [];
209
+ try {
210
+ let found = false;
211
+ // Whether ANY loader entry was selected, as opposed to whether an update
212
+ // landed. The log conflated the two (#788): `found` only turns true after
213
+ // a successful update, so an entry that WAS matched but whose update threw
214
+ // was reported as "no loader entry matched" — which sent the reporter
215
+ // looking for a naming bug (#619's shape) in a profile where the match
216
+ // was fine and the runtime was simply still busy.
217
+ let matched = false;
218
+ for (const entry of matchingEntries(name)) {
219
+ matched = true;
220
+ if (!disabledFlag && uncertainEntries.has(entry)) {
221
+ throw new LifecycleWaitError('loader entry: runtime state is uncertain; retry disabling before enabling');
222
+ }
223
+ if (requireLive)
224
+ previous.push({ entry, disabled: entry.options.disabled, live: entry.fiber !== undefined });
225
+ // Whether THIS entry's update landed, so the "-> off/on" line below is
226
+ // only written for a change that happened. It used to be written after
227
+ // a thrown update too, reading "off: fiber=true" for an entry that was
228
+ // still running.
229
+ let landed = false;
230
+ // A disable can land while the entry's init is still in flight: the
231
+ // options flip but the finishing init brings the fiber up anyway, and a
232
+ // plain re-update no-ops on the empty diff. Force the update and verify
233
+ // the live state, retrying until reality matches the flag.
234
+ for (let attempt = 0; attempt < 3; attempt++) {
235
+ try {
236
+ await updateEntry(entry, disabledFlag ? true : null);
237
+ found = true;
238
+ landed = true;
239
+ }
240
+ catch (error) {
241
+ // A strict caller cannot accept an update that did not settle; a
242
+ // pending one is also fatal for a caller that asked to be told.
243
+ if (requireLive || (rejectPending && error instanceof LifecycleWaitError))
244
+ throw error;
245
+ // "Still pending" is the SAME update that already timed out, not a
246
+ // new failure: the first `did not settle within 10s` stays in the
247
+ // log, and every retry that merely bumps into it would otherwise
248
+ // add a line that reads as one more thing going wrong (#788 — 25 of
249
+ // them across restarts for one stuck entry).
250
+ if (!(error instanceof LifecyclePendingError)) {
251
+ logEvent('warn', 'toggle', `${name}: entry update failed — ${error instanceof Error ? error.message : String(error)}`);
252
+ }
253
+ break;
254
+ }
255
+ const live = entry.fiber !== undefined;
256
+ if (live !== disabledFlag)
257
+ break;
258
+ await new Promise(resolvePromise => setTimeout(resolvePromise, 200));
259
+ }
260
+ if (requireLive && (entry.fiber !== undefined) === disabledFlag) {
261
+ throw new Error(`${name}: loader entry ${disabledFlag ? 'did not stop' : 'did not become live'}`);
262
+ }
263
+ if (landed) {
264
+ logEvent('info', 'toggle', `${name} -> ${disabledFlag ? 'off' : 'on'}: fiber=${String(entry.fiber !== undefined)}`);
265
+ }
266
+ }
267
+ if (!matched)
268
+ logEvent('info', 'toggle', `${name}: no loader entry matched`);
269
+ return found;
270
+ }
271
+ catch (error) {
272
+ // Put back what this call changed, in reverse, and say so when that
273
+ // fails too: a rollback that reports success while the runtime is
274
+ // somewhere else is the failure mode this exists for.
275
+ const rollbackErrors = [];
276
+ for (const { entry, disabled, live } of previous.reverse()) {
277
+ try {
278
+ await updateEntry(entry, disabled ?? null, true);
279
+ if (disabled === undefined)
280
+ delete entry.options.disabled;
281
+ if ((entry.fiber !== undefined) !== live)
282
+ throw new Error(`${name}: loader entry did not restore its previous live state`);
283
+ }
284
+ catch (rollbackError) {
285
+ rollbackErrors.push(rollbackError instanceof Error ? rollbackError.message : String(rollbackError));
286
+ }
287
+ }
288
+ if (rollbackErrors.length) {
289
+ throw new Error(`${error instanceof Error ? error.message : String(error)}; entry restoration failed: ${rollbackErrors.join('; ')}`);
290
+ }
291
+ throw error;
292
+ }
293
+ }
294
+ /**
295
+ * Make `name` the one active theme: deactivate every other installed theme
296
+ * (market hot mounts unmount; bundle-layer entries live-disable) and bring
297
+ * it up. The choice persists in state.json and is replayed at boot.
298
+ */
299
+ /**
300
+ * Make `name` the one active theme.
301
+ *
302
+ * Switching stops every other theme first, because they are mutually
303
+ * exclusive by construction. That makes the failure case the interesting
304
+ * one: if the new theme then cannot come up, the user is left with NO theme
305
+ * — the old one stopped, the new one never started, and the tab shows the
306
+ * plugin as enabled while the interface has lost its skin (#582, where the
307
+ * reported assertion was simply "the previous theme's fiber is undefined").
308
+ *
309
+ * So what this stopped is remembered, and a failed switch puts it back —
310
+ * both the live fiber and the disable flag that followed it. The attempted
311
+ * theme keeps neither: it never came up, and leaving it out of the disable
312
+ * set is what lets the next attempt try it again.
313
+ */
314
+ async function activateTheme(name) {
315
+ const themes = await installedThemeNames();
316
+ const stopped = [];
317
+ for (const other of themes) {
318
+ if (other === name)
319
+ continue;
320
+ if (listHotMounts().includes(other)) {
321
+ if (await hotUnmount(other))
322
+ stopped.push({ name: other, kind: 'hot' });
323
+ disabledThemes.add(other);
324
+ }
325
+ else if (await setEntryDisabled(other, true)) {
326
+ stopped.push({ name: other, kind: 'entry' });
327
+ disabledThemes.add(other);
328
+ }
329
+ }
330
+ disabledThemes.delete(name);
331
+ writeDisabled(activeProfileDir, disabledThemes);
332
+ const live = listHotMounts().includes(name)
333
+ || await setEntryDisabled(name, false)
334
+ || (await hotMount(host, activeProfileDir, name)).ok;
335
+ if (live)
336
+ return true;
337
+ for (const previous of stopped) {
338
+ const back = previous.kind === 'hot'
339
+ ? (await hotMount(host, activeProfileDir, previous.name)).ok
340
+ : await setEntryDisabled(previous.name, false);
341
+ if (back)
342
+ disabledThemes.delete(previous.name);
343
+ else
344
+ logEvent('warn', 'theme', `${previous.name}: could not be restored after ${name} failed to start`);
345
+ }
346
+ writeDisabled(activeProfileDir, disabledThemes);
347
+ return false;
348
+ }
349
+ return { installedThemeNames, setEntryDisabled, activateTheme };
350
+ }
package/lib/trial.js ADDED
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Trial validation for composition changes — issue #98 (phase 3), the
3
+ * "trial boot" half of #19 reduced to what is safe and offline: before any
4
+ * bundle-order or preset change is written to the profile, replay the
5
+ * composition with the CANDIDATE order using the same entry-list machinery
6
+ * the real boot uses (src/check.ts's buildBundleLayers + composeLayers), and
7
+ * refuse the change when the composed tree would fail to boot (duplicate
8
+ * loader entry ids, unresolvable bundle layers, unparseable patches).
9
+ *
10
+ * No process, no network, no writes to the profile: the real profile is only
11
+ * read; if the candidate is bad, the failure is reported and nothing is
12
+ * applied (the caller then skips the write-back entirely).
13
+ *
14
+ * Issue #125 review: the CURRENT composition is replayed alongside the
15
+ * candidate, so the response also carries a current-vs-candidate diff
16
+ * (overrides / orphans / duplicates the reorder introduces) — not just
17
+ * whether it boots.
18
+ *
19
+ * Bundle resolution is deliberately SHARED with the check report
20
+ * (check.ts's buildBundleLayers): the dsh installation anchor first, then
21
+ * Node's module search from the profile (workspace-root hoisting) — so the
22
+ * trial can never disagree with the diagnostics about what a bundle is or
23
+ * where it lives, and official bundles resolve even when they are only
24
+ * hoisted to the workspace root.
25
+ */
26
+ import { existsSync, readFileSync } from 'node:fs';
27
+ import { join } from 'node:path';
28
+ import { buildBundleLayers, composeLayers, duplicateEntryIdsAreFatal, findDshInstallDir, parsePatchFile, } from './check.js';
29
+ import { resolveDshHome } from './home-paths.js';
30
+ import { mergeOrder, readBundleStack } from './order.js';
31
+ /**
32
+ * Replay the profile composition with `newCommunityOrder` (the candidate
33
+ * community-bundle order; official bundles keep their exact positions) and
34
+ * report anything that would break the boot. Pure read.
35
+ */
36
+ export function trialValidate(profileDir, newCommunityOrder, options = {}) {
37
+ const errors = [];
38
+ const warnings = [];
39
+ const current = readBundleStack(profileDir);
40
+ // Same merge the apply path uses (order.ts mergeOrder): the trial replays
41
+ // EXACTLY the stack a successful apply would write.
42
+ const merged = mergeOrder(current.bundles, newCommunityOrder);
43
+ if (!merged.ok) {
44
+ return {
45
+ ok: false, errors: [{ layer: '(order)', message: merged.error }], warnings,
46
+ duplicates: [], rows: [],
47
+ diff: { overrides: [], orphans: [], duplicates: [] },
48
+ };
49
+ }
50
+ const candidate = merged.bundles;
51
+ // Shared bundle-layer build — identical resolution to analyzeProfile
52
+ // (dsh install anchor first, then Node module search from the profile).
53
+ let specs = {};
54
+ try {
55
+ const manifest = JSON.parse(readFileSync(join(profileDir, 'package.json'), 'utf8'));
56
+ specs = manifest.dependencies ?? {};
57
+ }
58
+ catch { /* specs stay empty — sources read as '(not a direct dependency)' */ }
59
+ const dshInstall = options.dshInstallDir !== undefined ? options.dshInstallDir : findDshInstallDir();
60
+ // Same user/home patch layers as the boot (and the check report) — shared
61
+ // by BOTH compositions.
62
+ const patchLayers = [];
63
+ const userPatchPath = join(profileDir, 'cordis.patch.yml');
64
+ if (existsSync(userPatchPath)) {
65
+ const patches = parsePatchFile(userPatchPath);
66
+ patchLayers.push({ label: 'user-patch', kind: 'user', patches: patches ?? [], parseError: null });
67
+ if (patches === null)
68
+ errors.push({ layer: 'user-patch', message: 'cordis.patch.yml is not a valid entry list / cordis.patch.yml 不是合法的条目列表' });
69
+ }
70
+ const home = resolveDshHome(options.homeDir);
71
+ const homePatchPath = join(home, 'cordis.patch.yml');
72
+ if (existsSync(homePatchPath)) {
73
+ const patches = parsePatchFile(homePatchPath);
74
+ patchLayers.push({ label: 'home-patch', kind: 'home', patches: patches ?? [], parseError: null });
75
+ if (patches === null)
76
+ errors.push({ layer: 'home-patch', message: 'home cordis.patch.yml is not a valid entry list / 全局 cordis.patch.yml 不是合法的条目列表' });
77
+ }
78
+ /** Compose the loader tree for one bundle order (current or candidate). */
79
+ const compose = (bundleOrder) => {
80
+ const built = buildBundleLayers(profileDir, bundleOrder, specs, dshInstall);
81
+ return { built, composed: composeLayers([...built.layers, ...patchLayers]) };
82
+ };
83
+ const currentState = compose(current.bundles);
84
+ const candidateState = compose(candidate);
85
+ const composed = candidateState.composed;
86
+ for (const bundle of candidateState.built.bundles) {
87
+ if (bundle.error !== null)
88
+ errors.push({ layer: bundle.name, message: bundle.error });
89
+ if (bundle.parseError !== null)
90
+ errors.push({ layer: bundle.name, message: bundle.parseError });
91
+ }
92
+ // Same version gate as the check report (#853): on a loader that folds one
93
+ // id into one entry (1.0.4+) this is an override, not a refusal. Making it
94
+ // fatal here is what rolled back every update for a profile that already
95
+ // had a package row and a user-patch row on one id.
96
+ const duplicateFatal = duplicateEntryIdsAreFatal(profileDir, dshInstall);
97
+ for (const dup of composed.duplicates) {
98
+ const message = `duplicate loader entry id ${JSON.stringify(dup.id)} (${dup.count} rows) / 重复的 loader 条目 id ${JSON.stringify(dup.id)}`;
99
+ if (duplicateFatal)
100
+ errors.push({ layer: dup.layers.join(' / '), message });
101
+ else
102
+ warnings.push({ layer: dup.layers.join(' / '), message: `${message} — 当前宿主会让后一层覆盖前一层,启动不受影响 / this host lets the later layer win, so the boot is unaffected` });
103
+ }
104
+ for (const orphan of composed.orphans) {
105
+ warnings.push({ layer: orphan.layer, message: `${orphan.id}: ${orphan.reason}` });
106
+ }
107
+ // Issue #125 review: what does the reorder CHANGE? Compare the candidate
108
+ // composition against the current one — only candidate-introduced
109
+ // overrides / orphans / duplicates are reported.
110
+ const currentDupIds = new Set(currentState.composed.duplicates.map(d => d.id));
111
+ const sameOverride = (a, b) => a.id === b.id && a.layer === b.layer && a.overriddenLayers.join('\u0000') === b.overriddenLayers.join('\u0000');
112
+ const diff = {
113
+ overrides: composed.overrides.filter(o => !currentState.composed.overrides.some(c => sameOverride(o, c))),
114
+ orphans: composed.orphans.filter(o => !currentState.composed.orphans.some(c => c.id === o.id && c.layer === o.layer)),
115
+ duplicates: composed.duplicates.filter(d => !currentDupIds.has(d.id)),
116
+ };
117
+ return {
118
+ ok: errors.length === 0,
119
+ errors,
120
+ warnings,
121
+ duplicates: composed.duplicates,
122
+ rows: composed.rows.map(row => ({ id: row.id, layer: row.layer })),
123
+ diff,
124
+ };
125
+ }