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/verify.js ADDED
@@ -0,0 +1,904 @@
1
+ /**
2
+ * Post-install activation verification (P0-2): what "installed" actually
3
+ * means for a package in a dsh profile.
4
+ *
5
+ * Two sources of truth, in strict order of authority:
6
+ *
7
+ * 1. The LOADER INVENTORY (observed): whatever the loader is running right
8
+ * now is live, full stop. A plain library with no `dsh` field can be
9
+ * loaded by name from someone else's bundle patch — the official
10
+ * dsh-base patch loads `@deepseek-ai/dsh-tools`, which has no `dsh`
11
+ * field at all — so no manifest check may overrule it (#135).
12
+ * 2. The profile manifest (inferred): `<profile>/package.json` →
13
+ * `dsh.profile.bundles`, what the dsh CLI reconciled. This predicts what
14
+ * the NEXT boot will load, and is the only evidence available for a
15
+ * package that is not currently running.
16
+ *
17
+ * State taxonomy (IMPROVEMENT-PLAN P0-2):
18
+ * live – running in the current composition (hot mount or loader entry)
19
+ * restart – installed and will activate on the next boot, but not live now
20
+ * incompatible – the host's own boot gate will skip it on EVERY boot: its
21
+ * dsh peer range excludes the running runtime (#757). Restarting
22
+ * can never activate it — "restart to apply" would be a lie.
23
+ * inert – installed but not a profile-layer plugin (plain dependency, or
24
+ * client-only — the market shim-mounts those at boot)
25
+ * broken – would fail to load: listed as a bundle without a dsh surface,
26
+ * or a declared entry artifact that is missing
27
+ * missing – not present in node_modules
28
+ */
29
+ import { readFileSync, realpathSync, statSync } from 'node:fs';
30
+ import { createRequire, isBuiltin } from 'node:module';
31
+ import { Script } from 'node:vm';
32
+ import { join } from 'node:path';
33
+ import { listHotMounts, parseSimplePatch } from './hot.js';
34
+ import { userPatchPackageReferences } from './patch.js';
35
+ import { nameMatchesPackage } from './entry-identity.js';
36
+ import { bundlePatchInsertedIds, declaredBundlePatchFiles, hasDshManifest, hasLoadableEntry, pluginSubdirs, profileDir, readInstalled } from './profile.js';
37
+ import { compareSemver, composeLayers, parsePatchFile, satisfiesRange } from './check.js';
38
+ import { dshHostInfo } from './dsh-install.js';
39
+ /**
40
+ * Whether every bundle patch the package declares parses to an empty list.
41
+ *
42
+ * Such a bundle row loads nothing at boot: listing it in `dsh.profile.bundles`
43
+ * or taking it out changes nothing, so neither "restart to apply" nor the
44
+ * #696 "removed from bundles means off" inference applies to it (#813). A
45
+ * patch that is missing or unreadable is NOT empty — other verdicts own it.
46
+ */
47
+ export function bundlePatchIsEmpty(packageDir) {
48
+ const files = declaredBundlePatchFiles(packageDir);
49
+ return files.length > 0 && files.every(file => parsePatchFile(file)?.length === 0);
50
+ }
51
+ /**
52
+ * Whether the profile's own `cordis.patch.yml` names this package anywhere,
53
+ * at any depth — including rows nested in another plugin's config, such as
54
+ * an Agent preset's `plugins:` list, which never enter the host loader.
55
+ * Evidence of where the plugin comes from, not of whether it is running.
56
+ */
57
+ function profilePatchMentions(activeProfileDir, name) {
58
+ const rows = parsePatchFile(join(activeProfileDir, 'cordis.patch.yml'));
59
+ if (rows === null)
60
+ return false;
61
+ const seen = new Set();
62
+ const visit = (value) => {
63
+ if (value === null || typeof value !== 'object' || seen.has(value))
64
+ return false;
65
+ seen.add(value);
66
+ if (Array.isArray(value))
67
+ return value.some(visit);
68
+ const row = value;
69
+ if (nameMatchesPackage(row.name, name))
70
+ return true;
71
+ return Object.values(row).some(visit);
72
+ };
73
+ return rows.some(visit);
74
+ }
75
+ /** The profile manifest's `dsh.profile.bundles` — what the CLI reconciled. */
76
+ function readBundles(profile, explicitDir) {
77
+ try {
78
+ const manifest = JSON.parse(readFileSync(join(profileDir(profile, explicitDir), 'package.json'), 'utf8'));
79
+ const bundles = manifest.dsh?.profile?.bundles;
80
+ return new Set(Array.isArray(bundles) ? bundles.filter((n) => typeof n === 'string') : []);
81
+ }
82
+ catch {
83
+ return new Set();
84
+ }
85
+ }
86
+ /** Manifest-only library declaration; observed loader activity can override its status. */
87
+ export function isDeclaredLibraryDsh(dsh) {
88
+ return dsh?.kind === 'library' && dsh.bundle === undefined && dsh.client === undefined;
89
+ }
90
+ /**
91
+ * True when `live` contains the package itself or a subpath entry of it.
92
+ *
93
+ * The live set (see `liveNames` in routes.ts) holds loader entry names — the
94
+ * `name:` field of each bundle patch row. Bundles usually name the bare
95
+ * package (`dsh-crate`, `@scope/pkg`), but may point at a subpath entry
96
+ * (`@vectorize-io/hindsight-coding-agents/dsh`, `aegis/extensions/dsh/index.js`).
97
+ * Either form means the package's fiber is up and it must read as live;
98
+ * a different package sharing a name prefix (`@scope/pkg2` vs `@scope/pkg`)
99
+ * must not — the `/` bound keeps the match a real subpath.
100
+ */
101
+ function liveIncludes(live, packageName) {
102
+ for (const name of live)
103
+ if (nameMatchesPackage(name, packageName))
104
+ return true;
105
+ return false;
106
+ }
107
+ /**
108
+ * True when a loader entry this package's OWN bundle patch inserts is up.
109
+ *
110
+ * A carrier bundle (#103) ships no plugin of its own: its patch mounts
111
+ * ANOTHER package with configuration, so the live entry carries that other
112
+ * package's name and `liveIncludes` can never match. The entry ID is the
113
+ * part that belongs to this package — its patch created it — which is why
114
+ * matching on it is both sufficient and precise: a neighbour that happens
115
+ * to mount the same package does so under a different id.
116
+ *
117
+ * Without this the market kept telling users to restart for a plugin that
118
+ * had been running since the restart (#156).
119
+ */
120
+ function carriedRowLive(live, profileDirectory, packageName) {
121
+ try {
122
+ return bundlePatchInsertedIds(join(profileDirectory, 'node_modules', packageName))
123
+ .some(id => live.has(`#${id}`));
124
+ }
125
+ catch {
126
+ return false;
127
+ }
128
+ }
129
+ function readPkgDsh(profile, name, explicitDir) {
130
+ try {
131
+ const manifest = JSON.parse(readFileSync(join(profileDir(profile, explicitDir), 'node_modules', name, 'package.json'), 'utf8'));
132
+ return manifest.dsh ?? {};
133
+ }
134
+ catch {
135
+ return null;
136
+ }
137
+ }
138
+ function patchTextOf(profile, name, explicitDir) {
139
+ try {
140
+ return readFileSync(join(profileDir(profile, explicitDir), 'node_modules', name, 'cordis.patch.yml'), 'utf8');
141
+ }
142
+ catch {
143
+ return null;
144
+ }
145
+ }
146
+ /**
147
+ * Verify the activation state of one installed package.
148
+ * @param live - names live in the current composition; defaults to the
149
+ * market's hot-mount table (injectable for tests).
150
+ */
151
+ /**
152
+ * Whether the profile's OWN `cordis.patch.yml` inserts this package by name.
153
+ *
154
+ * A third evidence source beside the loader inventory and the package's own
155
+ * manifest, and the one that was missing (#165): a plugin the user wired up
156
+ * themselves declares nothing, is not hot-mounted until the next boot, and so
157
+ * fell through to `broken` — the market told them the install had failed
158
+ * verification while the plugin was, in fact, working.
159
+ *
160
+ * Read with the same parser the uninstall guard uses. Unreadable returns
161
+ * null, which is treated here as NO evidence rather than as evidence: this
162
+ * only ever upgrades a verdict away from `broken`, so being unsure has to
163
+ * leave the stricter answer standing.
164
+ */
165
+ function patchLoads(activeProfileDir, name) {
166
+ const references = userPatchPackageReferences(join(activeProfileDir, 'cordis.patch.yml'), name);
167
+ return references !== null && references.length > 0;
168
+ }
169
+ const isDshPeer = (peer) => peer === '@deepseek-ai/dsh' || peer.startsWith('@deepseek-ai/dsh-');
170
+ /**
171
+ * Predict the host's boot gate for one installed package. Returns the first
172
+ * dsh peer the running runtime fails, or null when the next boot would load
173
+ * it — or when we cannot tell (unknown runtime, unparseable range), because
174
+ * uncertainty must keep the old verdict, not invent a harsher one (#757).
175
+ *
176
+ * satisfiesRange runs with includePrerelease — the host's own semantics,
177
+ * since every published host line is itself a prerelease — and an EMPTY
178
+ * range counts as failing, mirroring the host: absence of a requirement is
179
+ * not permission.
180
+ *
181
+ * Known differences from the host's verdict, kept deliberate (#758): the
182
+ * runtime version comes from the @deepseek-ai/dsh-app-boot package.json
183
+ * this tree can locate, not the host's self-reported getDshRuntimeVersion;
184
+ * when no host is locatable the gate stands aside and the real boot still
185
+ * applies its own. Exemptions mirror readProfileVersionExemptions from the
186
+ * profile's compatibility.json. The FIRST failing dsh peer decides, as the
187
+ * host's skip does — only the reported culprit may differ when several
188
+ * peers fail at once.
189
+ */
190
+ export function hostPeerGate(activeProfileDir, name, facts) {
191
+ return peerGateAt(join(activeProfileDir, 'node_modules', name), name, facts);
192
+ }
193
+ /**
194
+ * The unmet requirement, if any, and the remedy side it points at.
195
+ *
196
+ * Which side of the range the runtime sits on decides the remedy: below the
197
+ * floor, upgrading the host genuinely helps; above the cap (#757's own
198
+ * shape) no upgrade can satisfy it, and suggesting one points the wrong way
199
+ * (#758).
200
+ */
201
+ function unmetOf(peer, range, runtimeVersion) {
202
+ const floor = /[0-9]+\.[0-9]+\.[0-9]+[-+0-9A-Za-z.]*/.exec(range);
203
+ const hostTooOld = floor !== null && compareSemver(runtimeVersion, floor[0]) < 0;
204
+ return { peer, range, runtimeVersion, hostTooOld };
205
+ }
206
+ /** Same prediction for a patch plugin resolved outside the profile's flat node_modules. */
207
+ function peerGateAt(packageDir, name, facts) {
208
+ if (facts.runtimeVersion === null)
209
+ return null;
210
+ let manifest;
211
+ try {
212
+ manifest = JSON.parse(readFileSync(join(packageDir, 'package.json'), 'utf8'));
213
+ }
214
+ catch {
215
+ return null;
216
+ }
217
+ const version = typeof manifest.version === 'string' ? manifest.version : '';
218
+ if (version !== '' && (facts.exemptions[`${name}@${version}`] ?? []).includes(facts.runtimeVersion)) {
219
+ return null;
220
+ }
221
+ // An own `engines.dsh` range decides ALONE and peerDependencies are then
222
+ // ignored — the host's rule, read from unmetRequirements in
223
+ // @deepseek-ai/dsh-app-boot, and the reason a gate that only read peers
224
+ // was too lenient on 62 of 2796 (package, runtime) pairs measured over the
225
+ // live catalog: `dsh-file-explorer-kit` (engines.dsh ^0.1.1) and
226
+ // `dsh-workspace-kit` (^0.1.2-rc.1) declare NO dsh peer at all, so the
227
+ // family that refuses them was invisible here and the card promised a
228
+ // restart the host would not honour. A non-string range throws inside the
229
+ // host's own evaluator; that is not a verdict this can predict, so the
230
+ // old answer stands (#757).
231
+ const engines = manifest.engines?.dsh;
232
+ if (engines !== undefined) {
233
+ if (typeof engines !== 'string')
234
+ return null;
235
+ const range = engines.trim();
236
+ // `workspace:` is substituted only for PEERS: the host counts it as an
237
+ // unmet range for engines, so an empty or invalid range stays unmet too.
238
+ const satisfied = range === '' ? false : satisfiesRange(facts.runtimeVersion, range, { includePrerelease: true });
239
+ return satisfied ? null : unmetOf('engines.dsh', range, facts.runtimeVersion);
240
+ }
241
+ for (const [peer, requirement] of Object.entries(manifest.peerDependencies ?? {})) {
242
+ if (!isDshPeer(peer) || typeof requirement !== 'string')
243
+ continue;
244
+ const range = requirement.trim();
245
+ const satisfied = range === '' ? false : satisfiesRange(facts.runtimeVersion, range, { includePrerelease: true });
246
+ if (satisfied === false)
247
+ return unmetOf(peer, range, facts.runtimeVersion);
248
+ }
249
+ return null;
250
+ }
251
+ /**
252
+ * #867: only the bundle's own effective loader rows are evidence, never its
253
+ * ordinary dependency closure or arbitrary names in plugin configuration.
254
+ * Compose every declared file together so later disables take effect. An
255
+ * unreadable file or an expression-gated row gives no rejection evidence.
256
+ */
257
+ function bundleRowPeerGate(packageDir, activeProfileDir, facts) {
258
+ if (facts.runtimeVersion === null)
259
+ return null;
260
+ try {
261
+ const patches = declaredBundlePatchFiles(packageDir).map(parsePatchFile);
262
+ if (patches.some(rows => rows === null))
263
+ return null;
264
+ const { resolvableRows } = composeLayers([{
265
+ label: 'bundle', kind: 'bundle', patches: patches.flatMap(rows => rows ?? []), parseError: null,
266
+ }]);
267
+ const checked = new Set();
268
+ for (const row of resolvableRows) {
269
+ if (row.activation !== 'required' || typeof row.name !== 'string')
270
+ continue;
271
+ // Bare npm names and subpath entries only. Relative files, builtins,
272
+ // aliases and expressions need runtime resolution; do not guess.
273
+ if (/^[.#/\\]|[:\\]/u.test(row.name) || isBuiltin(row.name))
274
+ continue;
275
+ const parts = row.name.split('/');
276
+ const name = parts.slice(0, row.name.startsWith('@') ? 2 : 1).join('/');
277
+ if (!/^(?:@[\w.-]+\/)?[\w-][\w.-]*$/u.test(name) || checked.has(name))
278
+ continue;
279
+ checked.add(name);
280
+ const directory = resolveBundleRowPackage(packageDir, activeProfileDir, name);
281
+ if (directory === null)
282
+ continue;
283
+ const gate = peerGateAt(directory, name, facts);
284
+ if (gate !== null)
285
+ return { name, gate };
286
+ }
287
+ }
288
+ catch { /* malformed or cyclic patch data — no reliable prediction */ }
289
+ return null;
290
+ }
291
+ /**
292
+ * Probe Node's search paths, without resolving an entry or requiring a
293
+ * package.json export. The real bundle path reaches pnpm's adjacent and
294
+ * nested dependencies; the profile anchor also covers workspace hoisting.
295
+ * Stop at a present directory even if its manifest is missing: a broken
296
+ * nearer copy must not borrow an incompatible manifest from a fallback.
297
+ */
298
+ function resolveBundleRowPackage(packageDir, activeProfileDir, name) {
299
+ const bundleAnchor = join(realpathSync(packageDir), 'package.json');
300
+ const manifest = JSON.parse(readFileSync(bundleAnchor, 'utf8'));
301
+ // The host publishes dependencies carried by selected bundles into its
302
+ // profile resolution. A stray nested copy not declared by this bundle is
303
+ // no evidence of what a profile row will import.
304
+ const carried = manifest.name === name || Object.hasOwn(manifest.dependencies ?? {}, name)
305
+ || Object.hasOwn(manifest.peerDependencies ?? {}, name);
306
+ const profileAnchor = join(activeProfileDir, 'package.json');
307
+ for (const anchor of carried ? [bundleAnchor, profileAnchor] : [profileAnchor]) {
308
+ for (const searchPath of createRequire(anchor).resolve.paths(name) ?? []) {
309
+ const candidate = join(searchPath, name);
310
+ try {
311
+ if (statSync(candidate).isDirectory())
312
+ return candidate;
313
+ }
314
+ catch { /* try the next Node search path */ }
315
+ }
316
+ }
317
+ return null;
318
+ }
319
+ /** The way out of a peer gate, in the direction the versions allow (#758). */
320
+ export function peerGateRemedy(gate) {
321
+ if (gate.hostTooOld) {
322
+ return {
323
+ zh: '升级 dsh、等插件更新适配或装回旧版本',
324
+ en: 'upgrade dsh, wait for an updated release, or go back to the previous version',
325
+ };
326
+ }
327
+ return {
328
+ zh: '等插件更新适配或装回旧版本;升级 dsh 解决不了',
329
+ en: 'wait for an updated release or go back to the previous version — upgrading dsh will not help',
330
+ };
331
+ }
332
+ let cachedRuntimeVersion;
333
+ /**
334
+ * Discover the host runtime version once per process. Prefers the package
335
+ * the host itself versions its runtime by (@deepseek-ai/dsh-app-boot, the
336
+ * getDshRuntimeVersion source); falls back to the CLI package version,
337
+ * which ships on the same line. null when no host is locatable at all
338
+ * (tests, plain node) — which disables the gate.
339
+ */
340
+ function discoverRuntimeVersion() {
341
+ if (cachedRuntimeVersion !== undefined)
342
+ return cachedRuntimeVersion;
343
+ const host = dshHostInfo();
344
+ let version = null;
345
+ if (host !== null) {
346
+ // The dsh package directory itself (a normal install) has the runtime
347
+ // as a sibling; a Desktop shell root keeps it under node_modules.
348
+ const candidates = [
349
+ join(host.directory, 'node_modules', '@deepseek-ai', 'dsh-app-boot'),
350
+ join(host.directory, '..', 'dsh-app-boot'),
351
+ ];
352
+ for (const dir of candidates) {
353
+ try {
354
+ const v = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')).version;
355
+ if (typeof v === 'string' && v !== '') {
356
+ version = v;
357
+ break;
358
+ }
359
+ }
360
+ catch { /* try the next layout */ }
361
+ }
362
+ if (version === null)
363
+ version = host.version;
364
+ }
365
+ cachedRuntimeVersion = version;
366
+ return version;
367
+ }
368
+ /**
369
+ * The production HostRuntimeFacts: the discovered runtime version plus the
370
+ * profile's own exemption list. Re-read per call so an edited
371
+ * compatibility.json takes effect without a market restart.
372
+ */
373
+ export function defaultHostRuntimeFacts(activeProfileDir) {
374
+ let exemptions = {};
375
+ try {
376
+ const raw = JSON.parse(readFileSync(join(activeProfileDir, 'compatibility.json'), 'utf8'));
377
+ exemptions = Object.fromEntries(Object.entries(raw).filter((entry) => Array.isArray(entry[1]) && entry[1].every(x => typeof x === 'string')));
378
+ }
379
+ catch { /* no exemption file — nothing may bypass the gate */ }
380
+ return { runtimeVersion: discoverRuntimeVersion(), exemptions };
381
+ }
382
+ export function verifyActivation(profile, name, live = new Set(listHotMounts()), explicitDir, isDisabled = false, hostFacts, loaderObserved = false,
383
+ /**
384
+ * The host's OWN row for this package exists and has no fiber (#1023).
385
+ * The loader creates an entry before it imports the module, so an entry
386
+ * that never got a fiber is a row the boot tried and did not activate —
387
+ * "restart to apply" would promise something the next start cannot deliver.
388
+ */
389
+ loaderNeverStarted = false) {
390
+ const activeProfileDir = profileDir(profile, explicitDir);
391
+ const bundles = readBundles(profile, activeProfileDir);
392
+ const inBundles = bundles.has(name);
393
+ const dsh = readPkgDsh(profile, name, activeProfileDir);
394
+ if (dsh === null) {
395
+ return { state: 'missing', reasons: ['未安装 / not installed'], bundle: inBundles, hot: false };
396
+ }
397
+ const declaredLibrary = isDeclaredLibraryDsh(dsh);
398
+ // A loader entry can remain after its fiber is switched off. Retain that
399
+ // evidence so an observed library can be re-enabled after disabling it.
400
+ const loaderLive = liveIncludes(live, name) || carriedRowLive(live, activeProfileDir, name);
401
+ // A user-disabled plugin reads as disabled, never as "restart to apply":
402
+ // the switch state (market disable list or the user patch layer) is the
403
+ // dominant fact, and the loader keeps it off on every boot.
404
+ if (isDisabled && (!declaredLibrary || loaderLive || loaderObserved)) {
405
+ return {
406
+ state: 'disabled',
407
+ reasons: ['已停用(市场开关或补丁层),重启后保持关闭 / disabled (market toggle or the patch layer) — stays off across restarts'],
408
+ bundle: inBundles,
409
+ hot: false,
410
+ };
411
+ }
412
+ const dir = join(activeProfileDir, 'node_modules', name);
413
+ // OBSERVED beats INFERRED (#135): the loader inventory is ground truth, so
414
+ // a package the loader is running is live no matter what its manifest says.
415
+ // Plain library packages legitimately carry no `dsh` field and are still
416
+ // loaded by name from a bundle patch — @deepseek-ai/dsh-tools is loaded by
417
+ // the official dsh-base patch and has no `dsh` field at all — so this check
418
+ // has to come before any manifest-based verdict.
419
+ if (!hasDshManifest(dir)) {
420
+ if (loaderLive) {
421
+ return {
422
+ state: 'live',
423
+ reasons: ['已由 Loader 加载(该包未声明 dsh 元数据,由某个 bundle patch 按名加载)/ loaded by the loader (no dsh metadata of its own — a bundle patch loads it by name)'],
424
+ bundle: inBundles,
425
+ hot: true,
426
+ };
427
+ }
428
+ // Not live and no dsh surface: for a package the profile lists as a
429
+ // BUNDLE this is a real defect; for a plain dependency it is normal —
430
+ // most dependencies are libraries, not plugins (#135).
431
+ if (inBundles && !patchLoads(activeProfileDir, name)) {
432
+ return {
433
+ state: 'broken',
434
+ reasons: ['已列入 profile bundle 层但未声明 dsh 元数据,加载会失败 / listed in the profile bundle layer but declares no dsh metadata — loading it fails'],
435
+ bundle: true,
436
+ hot: false,
437
+ };
438
+ }
439
+ if (inBundles) {
440
+ return {
441
+ state: 'restart',
442
+ reasons: ['由你自己的 cordis.patch.yml 按名加载,重启后生效 / loaded by name from your own cordis.patch.yml — live after a restart'],
443
+ bundle: true,
444
+ hot: false,
445
+ };
446
+ }
447
+ // A collection repository's ROOT package says nothing about itself and
448
+ // holds the plugins one level down (#892). Installed whole — which the
449
+ // market used to do before it learned to retarget one, and which a user
450
+ // can still do by hand — it lands on this list as "installed, not in
451
+ // effect" with no way out of that sentence. Name the plugins it does
452
+ // carry and the way to install one: the dead end is the bug.
453
+ const carried = pluginSubdirs(dir);
454
+ const shown = carried.slice(0, 3).join('、');
455
+ const more = carried.length > 3 ? `等 ${carried.length} 个` : '';
456
+ const shownEn = carried.slice(0, 3).join(', ');
457
+ const moreEn = carried.length > 3 ? ` and ${carried.length - 3} more` : '';
458
+ return {
459
+ state: 'inert',
460
+ reasons: [carried.length > 0
461
+ ? `这是集合仓库的根包,本身不是插件。可安装的子包:${shown}${more}。请装子包而不是它(仓库地址后加 #path:/子包目录) / this is a collection repository's root package, not a plugin itself; install one of its plugins instead — ${shownEn}${moreEn} — by adding #path:/<subdirectory> to the repository URL`
462
+ : '普通依赖(未声明 dsh 元数据),不是 profile 层插件;若它由某个 bundle patch 按名加载,启动后会显示为已加载 / a plain dependency with no dsh metadata — not a profile-layer plugin; if some bundle patch loads it by name it will read as live once running'],
463
+ bundle: false,
464
+ hot: false,
465
+ };
466
+ }
467
+ // A declared library is shared code, not a plugin waiting to start. This
468
+ // manifest fact does not overrule an observed loader entry or a real plugin
469
+ // surface, and a library need not have a loadable plugin entry artifact.
470
+ if (!loaderLive && !loaderObserved && declaredLibrary) {
471
+ return {
472
+ state: 'inert',
473
+ library: true,
474
+ reasons: ['供其他插件使用,无需启用 / for other plugins to use; no need to enable it'],
475
+ bundle: inBundles,
476
+ hot: false,
477
+ };
478
+ }
479
+ // Carrier bundles (#103) ship no entry of their own — what they mount is
480
+ // the point — so judge by "is anything loadable", not by this package's
481
+ // own artifact.
482
+ if (!loaderLive && !hasLoadableEntry(activeProfileDir, name) && !patchLoads(activeProfileDir, name)) {
483
+ return {
484
+ state: 'broken',
485
+ reasons: [
486
+ '声明的入口产物缺失(源码检出或构建被拦),下次启动会失败 / the declared entry artifact is missing (source-only checkout or blocked build) — the next boot would fail',
487
+ ],
488
+ bundle: inBundles,
489
+ hot: false,
490
+ };
491
+ }
492
+ if (loaderLive) {
493
+ const clientOnly = dsh.bundle === undefined && dsh.client !== undefined;
494
+ return {
495
+ state: 'live',
496
+ reasons: [
497
+ clientOnly
498
+ ? '已热加载(纯客户端插件 shim)/ live via the client-only shim'
499
+ : '已热加载(bundle patch)/ live via its bundle patch',
500
+ ],
501
+ bundle: inBundles,
502
+ hot: true,
503
+ };
504
+ }
505
+ // An empty bundle patch (#813): the bundle row brings nothing in, so a
506
+ // restart cannot change the verdict and "restart to apply" would stand
507
+ // forever. Say where the plugin comes from instead, when the profile's own
508
+ // patch names it; otherwise nothing loads it, and that is the truth.
509
+ if (dsh.client === undefined && bundlePatchIsEmpty(dir)) {
510
+ return profilePatchMentions(activeProfileDir, name)
511
+ ? {
512
+ state: 'inert',
513
+ loadedByProfile: true,
514
+ reasons: ['它自带的 bundle 补丁是空的,由你的配置(例如 Agent 预设)加载;市场看不到它是否正在运行 / its own bundle patch is empty, so your own setup (an Agent preset, for example) loads it; the market cannot see whether it is running'],
515
+ bundle: inBundles,
516
+ hot: false,
517
+ }
518
+ : {
519
+ state: 'inert',
520
+ reasons: ['它自带的 bundle 补丁是空的,你的配置里也没有引用它,所以不会加载 / its own bundle patch is empty and your setup does not reference it, so nothing loads it'],
521
+ bundle: inBundles,
522
+ hot: false,
523
+ };
524
+ }
525
+ if (inBundles) {
526
+ // #757: "restart to apply" is only honest when the next boot would
527
+ // actually load the bundle. The host skips bundles whose dsh peer
528
+ // range excludes the running runtime — predict that verdict here so
529
+ // the plugin reads as incompatible instead of promising a restart
530
+ // that cannot fix it.
531
+ const facts = hostFacts ?? defaultHostRuntimeFacts(activeProfileDir);
532
+ const gate = hostPeerGate(activeProfileDir, name, facts);
533
+ if (gate !== null) {
534
+ const remedy = peerGateRemedy(gate);
535
+ return {
536
+ state: 'incompatible',
537
+ reasons: [
538
+ `新版本要求宿主 ${gate.range},当前运行 ${gate.runtimeVersion},重启也不会生效;${remedy.zh} / the new version needs host ${gate.range}, but this host runs ${gate.runtimeVersion} — a restart will not activate it; ${remedy.en}`,
539
+ ],
540
+ bundle: true,
541
+ hot: false,
542
+ };
543
+ }
544
+ const child = bundleRowPeerGate(dir, activeProfileDir, facts);
545
+ if (child !== null) {
546
+ const { gate, name: plugin } = child;
547
+ const remedy = gate.hostTooOld
548
+ ? { zh: '升级 dsh,或更新此插件包以匹配当前 dsh', en: 'upgrade dsh, or update this bundle to match the current dsh' }
549
+ : { zh: '更新此插件包,或安装与当前 dsh 兼容的版本;升级 dsh 解决不了', en: 'update this bundle or install a version compatible with the current dsh — upgrading dsh will not help' };
550
+ return {
551
+ state: 'incompatible',
552
+ reasons: [
553
+ `它加载的插件 ${plugin} 要求 ${gate.peer} ${gate.range},当前 dsh 为 ${gate.runtimeVersion},重启也不会生效;${remedy.zh} / its plugin ${plugin} requires ${gate.peer} ${gate.range}, but dsh runs ${gate.runtimeVersion} — a restart will not activate it; ${remedy.en}`,
554
+ ],
555
+ bundle: true,
556
+ hot: false,
557
+ };
558
+ }
559
+ // #1023: an entry the loader created and never started is not a pending
560
+ // change. A restart re-runs the same import, so the banner it produced
561
+ // ("1 change needs a restart") could never be cleared by restarting.
562
+ if (loaderNeverStarted) {
563
+ return {
564
+ state: 'failed',
565
+ reasons: [
566
+ '宿主这次启动没能加载它;重启会再试一次,还是失败就说明它和当前宿主版本不兼容——更新它,或卸载 / the host could not load it during this start; a restart tries again, but if it keeps failing the package does not fit this host version — update it, or remove it',
567
+ ],
568
+ bundle: true,
569
+ hot: false,
570
+ };
571
+ }
572
+ const patch = patchTextOf(profile, name, activeProfileDir);
573
+ const complex = patch !== null && parseSimplePatch(patch) === null;
574
+ return {
575
+ state: 'restart',
576
+ reasons: [
577
+ complex
578
+ ? 'bundle patch 含配置/表达式,热挂载仅支持纯 insert;重启后由 bundle 层生效 / the bundle patch contains config/expression rows; hot-mount only supports plain inserts — it activates on restart'
579
+ : '已进入 profile bundle 层但本次未能热挂载;重启后生效 / in the bundle layer but not hot-mounted this session — it activates on restart',
580
+ ],
581
+ bundle: true,
582
+ hot: false,
583
+ };
584
+ }
585
+ // Not a profile-layer plugin. Client-only packages never enter bundles
586
+ // (the dsh CLI skips them), so the market shim-mounts them at boot —
587
+ // they still work, but "installed" never means "bundle layer".
588
+ if (dsh.client !== undefined) {
589
+ return {
590
+ state: 'inert',
591
+ reasons: [
592
+ '未声明 dsh.bundle,不会进入 profile bundle 层(纯客户端插件);重启后由市场自动挂载生效 / no dsh.bundle — client-only plugins never enter the bundle layer; the market shim-mounts them at the next boot',
593
+ ],
594
+ bundle: false,
595
+ hot: false,
596
+ };
597
+ }
598
+ return {
599
+ state: 'inert',
600
+ reasons: [
601
+ '未声明 dsh.bundle,已作为普通依赖安装,不会成为 profile 层 / no dsh.bundle — installed as a plain dependency, never a profile-layer plugin',
602
+ ],
603
+ bundle: false,
604
+ hot: false,
605
+ };
606
+ }
607
+ /**
608
+ * Correct a post-UPDATE verdict for a plugin that was already running.
609
+ *
610
+ * `verifyActivation` answers "is this name in the live loader inventory".
611
+ * That is the right question after an install and the wrong one after an
612
+ * update: the plugin was already live, so the answer stays "live" while the
613
+ * process keeps serving the module it imported at boot. Replacing files under
614
+ * a running composition does not re-import anything.
615
+ *
616
+ * Measured on a real host rather than reasoned about — updating the market
617
+ * from 1.11.3 to 1.12.2 left `/dsh-crate/status` reporting 1.11.3 with an
618
+ * unchanged boot id, while the update route called it hot-loaded in the same
619
+ * response. The browser half genuinely does refresh (the host re-serves the
620
+ * client bundle from disk), which is what makes the wrong verdict credible:
621
+ * the UI visibly becomes the new version while the server half does not.
622
+ *
623
+ * Only a plugin that was ALREADY live is affected. One that was missing,
624
+ * broken or disabled beforehand has nothing loaded to shadow the new build,
625
+ * so its fresh mount really does run the new code.
626
+ *
627
+ * Client-only packages are excluded for the same reason from the other end:
628
+ * they have no host half to go stale, and the browser fetches their bundle
629
+ * from disk on the next page load. Telling their users to restart would be
630
+ * #156 again, in a narrower place — see `hasHostHalf`.
631
+ * @param result the verdict computed from the loader inventory
632
+ * @param hostHalfWasLive whether a HOST half was live BEFORE the replacement
633
+ */
634
+ export function activationAfterReplace(result, hostHalfWasLive) {
635
+ if (!hostHalfWasLive || result.state !== 'live')
636
+ return result;
637
+ return {
638
+ ...result,
639
+ state: 'restart',
640
+ hot: false,
641
+ reasons: ['新版本已就位,但运行中的进程仍在使用启动时加载的旧模块——重启后生效(页面本身会立即变成新版,服务端不会) / the new build is in place, but the running process still serves the module it imported at boot — restart to apply (the page itself updates immediately; the server half does not)'],
642
+ };
643
+ }
644
+ /**
645
+ * Whether a package has a host (Node) half at all.
646
+ *
647
+ * A `dsh.client`-only package — themes, skins, most pure-UI plugins — runs
648
+ * no server code: the market shim-mounts it so the loader has a live row,
649
+ * and the browser re-fetches its bundle from disk on the next page load. An
650
+ * update to one takes effect on refresh, with no restart to ask for.
651
+ */
652
+ export function hasHostHalf(profile, name, explicitDir) {
653
+ const dsh = readPkgDsh(profile, name, explicitDir);
654
+ if (dsh === null)
655
+ return false;
656
+ // Only a DEFINITE client-only package is excluded — the same test
657
+ // verifyActivation uses for its own verdict. Testing `dsh.bundle` on its
658
+ // own would read a package that declares neither key (`"dsh": {}`, which
659
+ // the bundle layer still loads) as client-only, and quietly disable the
660
+ // correction for it.
661
+ return !(dsh.bundle === undefined && dsh.client !== undefined);
662
+ }
663
+ /**
664
+ * The client bundle path a package's `exports["./client"]` names, relative
665
+ * to the package root — or `null` when it cannot be resolved CONFIDENTLY.
666
+ *
667
+ * Returning null is the important half. This feeds a post-install check
668
+ * whose only job is to catch a corrupt bundle, and a resolver that guessed
669
+ * wrong would report a healthy plugin as broken — worse than the silence it
670
+ * replaces. So every shape this does not fully understand resolves to null
671
+ * and the check simply does not run: unresolvable is not evidence of damage.
672
+ *
673
+ * Handles the two shapes real plugins ship: a plain string, and a
674
+ * conditional object. For the object, only `browser` and `default` are
675
+ * consulted — those are the conditions the host's client loader actually
676
+ * activates; `import`/`require` describe a Node resolution this file is not
677
+ * modelling, and picking one of those could name a different artifact.
678
+ * Nested conditions recurse; anything else (arrays, non-relative targets)
679
+ * gives up.
680
+ */
681
+ export function clientBundlePath(exportsField, depth = 0) {
682
+ if (depth > 4)
683
+ return null;
684
+ if (typeof exportsField === 'string') {
685
+ // Only a relative in-package path. A bare specifier or URL is a shape
686
+ // this resolver does not model.
687
+ return exportsField.startsWith('./') ? exportsField : null;
688
+ }
689
+ if (exportsField === null || typeof exportsField !== 'object' || Array.isArray(exportsField))
690
+ return null;
691
+ const conditions = exportsField;
692
+ for (const key of ['browser', 'default']) {
693
+ if (conditions[key] === undefined)
694
+ continue;
695
+ const resolved = clientBundlePath(conditions[key], depth + 1);
696
+ if (resolved !== null)
697
+ return resolved;
698
+ }
699
+ return null;
700
+ }
701
+ /**
702
+ * One assignment of a string literal to a name, and the `configForms.get`
703
+ * call sites (#810).
704
+ *
705
+ * The namespace a client asks its config from is a PROFILE ENTRY ID, not a
706
+ * package name. A client that writes the package name reads nothing: the
707
+ * settings document has no entry under it, the call returns empty, and the
708
+ * plugin degrades silently — blank or unwritable settings forms, and in the
709
+ * reported case a panel stuck on a hardcoded fallback port. Nothing logs it,
710
+ * and nothing on the market side noticed.
711
+ *
712
+ * `configForms.get` is matched by name, so an aliased receiver
713
+ * (`const forms = ctx.configForms; forms.get("x")`) is not seen — the same
714
+ * honesty as the syntax check above: this reports what it can prove, and
715
+ * says nothing otherwise.
716
+ */
717
+ const STRING_ASSIGNMENT = /(?:^|[^\w$.])(?:var|let|const)?\s*([A-Za-z_$][\w$]*)\s*=\s*(['"])([^'"\\\n]*)\2/gu;
718
+ const CONFIG_FORMS_GET = /configForms\s*\.\s*get\s*\(\s*(?:([A-Za-z_$][\w$]*)|(['"])([^'"\\\n]*)\2)\s*\)/gu;
719
+ /** A value that is a plain loader entry id: a backslash means it is not one. */
720
+ function plainNamespace(value) {
721
+ return value !== '' && value.length <= 200 && !value.includes('\\') && /^[\w@/.:-]+$/u.test(value) ? value : null;
722
+ }
723
+ /**
724
+ * Every namespace a client bundle asks its config from (#810).
725
+ *
726
+ * One level of constant propagation, as asked for in the report: the plugin
727
+ * that started this writes `var NAMESPACE = "dsh-comfyui-canvas"` and calls
728
+ * `configForms.get(NAMESPACE)`, so a literal-only scan would miss the very
729
+ * case the check exists for. A name assigned twice is dropped rather than
730
+ * guessed at — which value it holds at the call site is not decidable from
731
+ * text alone, and a wrong guess here would be reported as a plugin defect.
732
+ */
733
+ export function configFormNamespaces(source) {
734
+ // Measured on a 750KB bundle: these scans cost ~9ms, because both walk
735
+ // every character, and this runs on a request the market polls. Almost no
736
+ // client mentions configForms at all, and — an order of magnitude rarer —
737
+ // almost none of those calls a method on it: for both, this pair of plain
738
+ // substring searches IS the whole cost (0.23ms measured), and only a client
739
+ // that actually asks for a config pays for a scan.
740
+ if (!source.includes('configForms') || !source.includes('configForms.get'))
741
+ return [];
742
+ const constants = new Map();
743
+ for (const match of source.matchAll(STRING_ASSIGNMENT)) {
744
+ const name = match[1];
745
+ const value = plainNamespace(match[3]);
746
+ constants.set(name, constants.has(name) || value === null ? null : value);
747
+ }
748
+ const namespaces = new Set();
749
+ for (const match of source.matchAll(CONFIG_FORMS_GET)) {
750
+ // A namespace is a loader entry id: no escapes, no whitespace runs, no
751
+ // arbitrary length. Anything else is not this pattern and stays out.
752
+ const value = plainNamespace(match[3] ?? '') ?? constants.get(match[1]) ?? null;
753
+ if (value !== null)
754
+ namespaces.add(value);
755
+ }
756
+ return [...namespaces];
757
+ }
758
+ /** The client bundle of an installed package, read; null when it has none to read. */
759
+ function readClientBundle(profile, name, explicitDir) {
760
+ const root = join(profileDir(profile, explicitDir), 'node_modules', name);
761
+ let manifest;
762
+ try {
763
+ manifest = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
764
+ }
765
+ catch {
766
+ return null;
767
+ }
768
+ if (manifest.dsh?.client === undefined)
769
+ return null;
770
+ const exportsField = manifest.exports;
771
+ const relative = exportsField !== null && typeof exportsField === 'object' && !Array.isArray(exportsField)
772
+ ? clientBundlePath(exportsField['./client'])
773
+ : null;
774
+ if (relative === null)
775
+ return null;
776
+ try {
777
+ return readFileSync(join(root, relative), 'utf8');
778
+ }
779
+ catch {
780
+ return null;
781
+ }
782
+ }
783
+ /**
784
+ * Installed plugins whose client reads its config from a name nothing serves
785
+ * (#810).
786
+ *
787
+ * `served` is the entry id set of the WHOLE composition — deliberately not
788
+ * this package's own ids: a package may legitimately mount another one
789
+ * (carrier form), and judging by own ids alone would flag those. `ownIdsOf`
790
+ * answers what the package itself declares, which is the value to write
791
+ * instead — the report asked for the correct spelling to be shown, not just
792
+ * the mistake.
793
+ *
794
+ * The scan reads one bundle per installed plugin. Measured against the same
795
+ * cost the syntax sweep above already pays (0.40ms per plugin on a 385KB
796
+ * bundle), so a 30-plugin profile is ~12ms — this runs on a request a user
797
+ * made, not in a loop.
798
+ */
799
+ export function findUnservedConfigNamespaces(profile, served, ownIdsOf, explicitDir) {
800
+ const found = [];
801
+ for (const name of Object.keys(readInstalled(profile, explicitDir))) {
802
+ const source = readClientBundle(profile, name, explicitDir);
803
+ if (source === null)
804
+ continue;
805
+ const unserved = configFormNamespaces(source).filter(namespace => !served.has(namespace));
806
+ if (unserved.length === 0)
807
+ continue;
808
+ found.push({ name, namespaces: unserved, ownEntryIds: ownIdsOf(name) });
809
+ }
810
+ return found;
811
+ }
812
+ /**
813
+ * Whether a package's client bundle still parses as JavaScript (#222).
814
+ *
815
+ * pnpm can leave a half-written or patch-mangled bundle behind — the report
816
+ * describes a profile whose client bundle was broken after an update. The
817
+ * browser is where that surfaces today, as a blank settings page long after
818
+ * the operation reported success, with nothing connecting the two.
819
+ *
820
+ * `vm.Script` COMPILES without executing: it catches the syntax damage this
821
+ * is looking for and never runs plugin code, so a hostile bundle gains
822
+ * nothing. A missing `dsh.client`, an unresolvable exports field, or a file
823
+ * that is simply absent all return ok — this check only ever fires on a file
824
+ * it actually read and actually failed to parse. Everything ambiguous stays
825
+ * silent, because a false "your plugin is corrupt" is the one outcome worse
826
+ * than not checking.
827
+ */
828
+ /**
829
+ * V8's wording when a classic-script parse trips over module syntax.
830
+ *
831
+ * Matched on the message because there is no flag-free way to compile a
832
+ * module here (`SourceTextModule` needs --experimental-vm-modules, which the
833
+ * host process does not set). If V8 ever rewords these, the failure mode is
834
+ * the false positive we had before rather than a missed real break — the
835
+ * safer direction of the two.
836
+ */
837
+ const MODULE_SYNTAX_ERROR = /Unexpected token 'export'|Cannot use import statement outside a module|await is only valid in async functions and the top level bodies of modules/;
838
+ /**
839
+ * Every installed plugin whose client bundle will not parse (#222 by
840
+ * @MicroMilo).
841
+ *
842
+ * The per-package check above only ever looked at what an operation added,
843
+ * which misses the failure that was actually reported: pnpm re-extracts the
844
+ * WHOLE tree on any install, so updating one plugin can restore another
845
+ * plugin's pristine — and broken — bundle, or fail to re-apply a patch that
846
+ * was holding it together. The damage then surfaces at the next boot as
847
+ * "failed to load plugins", with nothing connecting it to the install that
848
+ * caused it.
849
+ *
850
+ * Cheap enough to run on every operation: 0.40ms per plugin including the
851
+ * read (measured on a 385KB bundle), so a 30-plugin profile costs ~12ms
852
+ * against an install that takes seconds.
853
+ *
854
+ * Silent on ESM bundles, like the per-package check it calls — see there for
855
+ * why. Widening the sweep is exactly what would have turned that one false
856
+ * "corrupt" into one per ESM plugin in the profile.
857
+ *
858
+ * Callers compare a before-list with an after-list rather than reporting
859
+ * this one directly — a profile can carry a broken bundle indefinitely, and
860
+ * re-reporting a problem the user already had would put them in front of
861
+ * something this operation did not cause and cannot undo.
862
+ */
863
+ export function brokenClientBundles(profile, explicitDir) {
864
+ const broken = [];
865
+ for (const name of Object.keys(readInstalled(profile, explicitDir))) {
866
+ const check = checkClientBundle(profile, name, explicitDir);
867
+ if (!check.ok)
868
+ broken.push({ name, reason: check.reason ?? 'parse failed' });
869
+ }
870
+ return broken;
871
+ }
872
+ /** Bundles broken after an operation that were intact before it. */
873
+ export function newlyBrokenBundles(before, after) {
874
+ const seen = new Set(before.map(entry => entry.name));
875
+ return after.filter(entry => !seen.has(entry.name));
876
+ }
877
+ export function checkClientBundle(profile, name, explicitDir) {
878
+ // Declared but absent is verifyActivation's territory (a missing entry
879
+ // artifact is already `broken` there); duplicating it here would report one
880
+ // problem twice in two different vocabularies — so the reader's null covers
881
+ // both "no client bundle" and "declared but unreadable" with the same ok.
882
+ const source = readClientBundle(profile, name, explicitDir);
883
+ if (source === null)
884
+ return { ok: true, reason: null };
885
+ try {
886
+ new Script(source, { filename: `${name}/client` });
887
+ return { ok: true, reason: null };
888
+ }
889
+ catch (error) {
890
+ const message = error instanceof Error ? error.message : String(error);
891
+ // `new Script` compiles a CLASSIC script, so perfectly valid module
892
+ // syntax is a SyntaxError to it: `export`, `import`, and top-level
893
+ // `await` all throw. This package ships CJS, which is why nobody noticed
894
+ // — but a plugin whose client bundle is ESM was being told its file was
895
+ // corrupt, and offered a rollback for a file that is fine.
896
+ //
897
+ // That is the exact outcome this check's own contract forbids: a false
898
+ // "your plugin is corrupt" is worse than not checking. Module syntax
899
+ // means "cannot judge with this parser", not "broken".
900
+ if (MODULE_SYNTAX_ERROR.test(message))
901
+ return { ok: true, reason: null };
902
+ return { ok: false, reason: message };
903
+ }
904
+ }