dsh-crate 0.5.3 → 0.5.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/client/client.js +2060 -459
  2. package/lib/body-progress.js +4 -3
  3. package/lib/changelog.js +15 -2
  4. package/lib/discovery-cache.js +210 -0
  5. package/lib/discovery-compatibility.js +91 -93
  6. package/lib/dsh-cli.js +36 -6
  7. package/lib/github-install-target.js +53 -0
  8. package/lib/hot.js +361 -27
  9. package/lib/index.js +6 -5
  10. package/lib/install.js +37 -0
  11. package/lib/patch.js +116 -72
  12. package/lib/pending-rows.js +3 -4
  13. package/lib/pnpm-compat.js +79 -1
  14. package/lib/proc-text.js +16 -1
  15. package/lib/recovery.js +2 -1
  16. package/lib/registry.js +27 -6
  17. package/lib/release-candidates.js +4 -0
  18. package/lib/routes.js +390 -131
  19. package/lib/themes.js +24 -8
  20. package/lib/types/body-progress.d.ts +2 -1
  21. package/lib/types/changelog.d.ts +10 -1
  22. package/lib/types/discovery-cache.d.ts +38 -0
  23. package/lib/types/discovery-compatibility.d.ts +16 -12
  24. package/lib/types/dsh-cli.d.ts +19 -2
  25. package/lib/types/github-install-target.d.ts +11 -0
  26. package/lib/types/hot.d.ts +87 -5
  27. package/lib/types/install.d.ts +19 -0
  28. package/lib/types/patch.d.ts +6 -2
  29. package/lib/types/registry.d.ts +9 -8
  30. package/lib/types/release-candidates.d.ts +2 -0
  31. package/lib/types/routes.d.ts +2 -2
  32. package/lib/types/themes.d.ts +7 -1
  33. package/lib/types/update-notification-settings.d.ts +5 -0
  34. package/lib/types/update-notifications.d.ts +51 -0
  35. package/lib/types/updates.d.ts +5 -1
  36. package/lib/update-notification-settings.js +6 -0
  37. package/lib/update-notifications.js +166 -0
  38. package/lib/updates.js +41 -11
  39. package/lib/verify.js +5 -2
  40. package/package.json +1 -1
package/lib/install.js CHANGED
@@ -1004,6 +1004,43 @@ export function removeDanglingHostBridge(name, profileDirectory, hostDirectory)
1004
1004
  logEvent('info', 'uninstall', `${name}: removed the dangling host bridge the boot projection left at ${bridge}`);
1005
1005
  return true;
1006
1006
  }
1007
+ /**
1008
+ * Remove the link a confirmed uninstall left at `node_modules/<name>` (#1191).
1009
+ *
1010
+ * A plugin installed from a local checkout (`link:`) is a junction or
1011
+ * directory symlink into that checkout. The uninstall has removed the
1012
+ * dependency from package.json and the lockfile, but on Windows the link was
1013
+ * reported still there, and the next install of the same name (the online
1014
+ * release) makes pnpm rename `<name>_tmp_*` over it, which Windows refuses
1015
+ * with EPERM.
1016
+ *
1017
+ * Only a link is ever touched, and only when the manifest no longer lists
1018
+ * `name` — a link the profile still owns must survive. `rmSync` without
1019
+ * `recursive` unlinks the link itself and never reaches the checkout it points
1020
+ * at (the same measurement the host-bridge cleanup above relies on).
1021
+ *
1022
+ * @returns the checkout path the removed link pointed at, or null when there
1023
+ * was nothing to remove. Never throws: the uninstall already succeeded.
1024
+ */
1025
+ export function removeLeftoverProfileLink(profile, name, profileDirectory) {
1026
+ const path = join(profileDirectory, 'node_modules', name);
1027
+ try {
1028
+ if (!lstatSync(path).isSymbolicLink())
1029
+ return null;
1030
+ if (readInstalled(profile, profileDirectory)[name] !== undefined)
1031
+ return null;
1032
+ const target = readlinkSync(path);
1033
+ rmSync(path, { force: true });
1034
+ logEvent('info', 'uninstall', `${name}: removed the leftover link at node_modules/${name} (it pointed at ${target}); the checkout itself was not touched (#1191)`);
1035
+ return target;
1036
+ }
1037
+ catch (error) {
1038
+ if (error.code !== 'ENOENT') {
1039
+ logEvent('warn', 'uninstall', `${name}: could not remove the leftover link at node_modules/${name} — ${error instanceof Error ? error.message : String(error)}`);
1040
+ }
1041
+ return null;
1042
+ }
1043
+ }
1007
1044
  /**
1008
1045
  * Group flat `{id, owner}` conflict hits by the installed plugin that owns
1009
1046
  * them. What the user has to decide is which PLUGINS to uninstall, not which
package/lib/patch.js CHANGED
@@ -30,6 +30,7 @@ import { fileURLToPath } from 'node:url';
30
30
  import { logEvent } from './log.js';
31
31
  import { parsePatchFile, parsePatchText } from './check.js';
32
32
  import { bundleOptOutRowIds, bundlePatchInsertedIds, declaredBundlePatchFiles, parsePatchRows } from './profile.js';
33
+ import { NPM_NAME_RE } from './sources.js';
33
34
  /**
34
35
  * Host infrastructure rows: disabling any of these breaks the very chain
35
36
  * the patch layer runs on (e.g. timer → HMR, webserver → the page itself),
@@ -145,10 +146,29 @@ function nextPatchContentLine(lines, from) {
145
146
  * does not carry the key at all.
146
147
  */
147
148
  function entryKeyValue(lines, start, key) {
148
- const pattern = new RegExp(`^ {2}${key}:[ \\t]*(.*?)[ \\t]*$`, 'u');
149
+ return fieldValue(lines, start, 0, key);
150
+ }
151
+ /**
152
+ * The value of one field inside a row that starts before `start`.
153
+ *
154
+ * The field sits two spaces deeper than the `- id:` marker that opens the row.
155
+ * A top-level row is therefore written at two spaces and an inserted row — one
156
+ * nested under `- insert:` — at six, because the row itself sits at four. The
157
+ * block ends at the next line indented no deeper than the id; a comment at
158
+ * that depth is not structural and does not end it.
159
+ *
160
+ * @param indent - the column of the row's own `- id:` marker.
161
+ * @returns the scalar as written (comments stripped), or null when absent.
162
+ */
163
+ function fieldValue(lines, start, indent, key) {
164
+ const fieldIndent = indent + 2;
165
+ const pattern = new RegExp(`^ {${String(fieldIndent)}}${key}:[ \\t]*(.*?)[ \\t]*$`, 'u');
149
166
  for (let index = start; index < lines.length; index += 1) {
150
167
  const line = lines[index] ?? '';
151
- if (/^- /u.test(line))
168
+ const body = line.trimStart();
169
+ if (body === '')
170
+ continue;
171
+ if (line.length - body.length < fieldIndent && !body.startsWith('#'))
152
172
  return null;
153
173
  const match = pattern.exec(line);
154
174
  // A `#` starts a comment only after whitespace; `#` inside a bare scalar
@@ -185,13 +205,18 @@ function rowApplies(name, expected) {
185
205
  * treats a subpath name and a foreign package name the same way (#1113).
186
206
  */
187
207
  export function composedRowName(host, rowId) {
208
+ const prefix = includePrefix(host);
209
+ const profileId = prefix === '' ? rowId : prefix + rowId;
210
+ let directName = null;
188
211
  for (const entry of host.loader.entries()) {
189
- if (loaderEntryId(entry) !== rowId)
190
- continue;
191
- const name = entry.options?.name;
192
- return typeof name === 'string' && name !== '' ? name : null;
212
+ const id = loaderEntryId(entry);
213
+ const candidate = entry.options?.name;
214
+ if (id === profileId && candidate)
215
+ return candidate;
216
+ if (id === rowId && candidate)
217
+ directName = candidate;
193
218
  }
194
- return null;
219
+ return directName;
195
220
  }
196
221
  /**
197
222
  * Whether the user layer's flag for this row is a decision the host applies.
@@ -205,18 +230,7 @@ export function rowFlagApplies(state, rowId, expected) {
205
230
  const carried = state.names?.[rowId];
206
231
  return carried === undefined || rowApplies(carried, expected);
207
232
  }
208
- /** The state with one row's flags dropped when its `name` does not apply. */
209
- function withoutMismatchedRow(state, rowId, expected) {
210
- if (rowFlagApplies(state, rowId, expected))
211
- return state;
212
- return {
213
- disables: state.disables.filter(id => id !== rowId),
214
- forced: state.forced.filter(id => id !== rowId),
215
- inserts: state.inserts,
216
- ...(state.names !== undefined ? { names: state.names } : {}),
217
- };
218
- }
219
- export function readUserPatchState(patchPath) {
233
+ export function readUserPatchState(patchPath, expectedNameFor) {
220
234
  // The host composes the file in order, later entries override earlier ones,
221
235
  // so a row has one final flag: listing it as both disabled and forced showed
222
236
  // a plugin as off while the file had it on (#1099).
@@ -240,8 +254,24 @@ export function readUserPatchState(patchPath) {
240
254
  inInsert = false;
241
255
  if (inInsert) {
242
256
  const insertRow = /^ {4}- id: ([A-Za-z0-9_.-]+)/u.exec(line);
243
- if (insertRow !== null)
244
- inserts.push(insertRow[1]);
257
+ if (insertRow !== null) {
258
+ const inserted = insertRow[1];
259
+ inserts.push(inserted);
260
+ // An inserted row's own fields sit at six spaces, and the include
261
+ // composition applies `disabled` from either indent. Stopping at the id
262
+ // left every inserted row out of the flag map, so the market showed a
263
+ // plugin as on — with a toggle that could not be answered — while the
264
+ // loader had the row off.
265
+ const insertFlag = fieldValue(lines, index + 1, 4, 'disabled');
266
+ if (insertFlag === 'true' || insertFlag === 'false')
267
+ flags.set(inserted, insertFlag);
268
+ const insertNamed = fieldValue(lines, index + 1, 4, 'name');
269
+ const insertName = insertNamed === null ? null : insertNamed.replace(/^(['"])(.*)\1$/u, '$2');
270
+ if (insertName !== null && insertName !== '')
271
+ names.set(inserted, insertName);
272
+ else
273
+ names.delete(inserted);
274
+ }
245
275
  continue;
246
276
  }
247
277
  const disableRow = /^- id: (?:([A-Za-z0-9_.-]+)|'([A-Za-z0-9_.-]+)'|"([A-Za-z0-9_.-]+)")[ \t]*$/u.exec(line);
@@ -251,12 +281,14 @@ export function readUserPatchState(patchPath) {
251
281
  const value = entryKeyValue(lines, index + 1, 'disabled');
252
282
  if (value !== 'true' && value !== 'false')
253
283
  continue;
254
- flags.set(id, value);
255
284
  // A row that names a module is only applied by the host when that name is
256
285
  // the one the row's id composes to; the flag stays here so the caller can
257
286
  // make that comparison (#1113).
258
287
  const named = entryKeyValue(lines, index + 1, 'name');
259
288
  const unwrapped = named === null ? null : named.replace(/^(['"])(.*)\1$/u, '$2');
289
+ if (expectedNameFor !== undefined && !rowApplies(unwrapped, expectedNameFor(id)))
290
+ continue;
291
+ flags.set(id, value);
260
292
  if (unwrapped !== null && unwrapped !== '')
261
293
  names.set(id, unwrapped);
262
294
  else
@@ -602,16 +634,20 @@ function queuedWrite(fn) {
602
634
  function escapeRegExp(value) {
603
635
  return value.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
604
636
  }
605
- function rowBlock(rowId, disabled) {
606
- return `- id: ${rowId}\n disabled: ${disabled ? 'true' : 'false'}\n`;
637
+ const MARKET_ROW_MARKER = '# dsh-crate';
638
+ function moduleNameLine(name) {
639
+ return ` name: '${name}' ${MARKET_ROW_MARKER}`;
640
+ }
641
+ function rowBlock(rowId, disabled, name = null) {
642
+ const block = `- id: ${rowId}\n disabled: ${disabled ? 'true' : 'false'}\n`;
643
+ return name === null ? block : block + moduleNameLine(name) + '\n';
607
644
  }
608
645
  /**
609
646
  * Rewrite standalone id/flag rows while preserving the surrounding file.
610
- * Comments and blank lines may separate the fields (#930). Look beyond them
611
- * after the flag too: an indented config/name/key makes this a longer entry,
612
- * whose first lines must never be removed (#821). Trailing comments stay put.
647
+ * Also accept the module name market adds to its own rows (#1196). Any
648
+ * other key makes the entry a user configuration to preserve (#821).
613
649
  */
614
- function rewriteRowBlocks(text, rowId, disabled, replace, expected = null) {
650
+ function rewriteRowBlocks(text, rowId, disabled, replace, expected = null, owner = expected) {
615
651
  const id = escapeRegExp(rowId);
616
652
  const idLine = new RegExp(`^- id: (?:${id}|'${id}'|"${id}")[ \t]*$`, 'u');
617
653
  const lines = text.match(/[^\n]*(?:\n|$)/gu)?.filter(Boolean) ?? [];
@@ -622,22 +658,27 @@ function rewriteRowBlocks(text, rowId, disabled, replace, expected = null) {
622
658
  for (let index = 0; index < lines.length; index += 1) {
623
659
  if (!idLine.test(lines[index].replace(/\r?\n$/u, '')))
624
660
  continue;
625
- // A row that names another module is skipped by the host, so rewriting it
626
- // would report a change that never happens (#1113).
627
- const named = entryKeyValue(lines, index + 1, 'name');
628
- if (!rowApplies(named === null ? null : named.replace(/^(['"])(.*)\1$/u, '$2'), expected))
629
- continue;
630
661
  const flagIndex = nextPatchContentLine(lines, index + 1);
631
662
  const flag = /^ {2}disabled: (true|false)[ \t]*(?:\r?\n)?$/u.exec(lines[flagIndex] ?? '');
632
663
  if (flag === null || (disabled !== 'any' && flag[1] !== disabled))
633
664
  continue;
634
- const following = nextPatchContentLine(lines, flagIndex + 1);
665
+ let lastKey = flagIndex;
666
+ let name = null;
667
+ let following = nextPatchContentLine(lines, lastKey + 1);
668
+ const marker = /^ {2}name: (['"])([^'"]+)\1[ \t]+# dsh-crate[ \t]*(?:\r?\n)?$/u.exec(lines[following] ?? '');
669
+ if (marker !== null) {
670
+ name = marker[2];
671
+ if (!NPM_NAME_RE.test(name) || !rowApplies(name, expected) || !rowApplies(name, owner))
672
+ continue;
673
+ lastKey = following;
674
+ following = nextPatchContentLine(lines, lastKey + 1);
675
+ }
635
676
  if (/^[ \t]/u.test(lines[following] ?? ''))
636
677
  continue;
637
- const start = offsets[index], end = offsets[flagIndex + 1];
638
- result += text.slice(copied, start) + replace(text.slice(start, end));
678
+ const start = offsets[index], end = offsets[lastKey + 1];
679
+ result += text.slice(copied, start) + replace(text.slice(start, end), name);
639
680
  copied = end;
640
- index = flagIndex;
681
+ index = lastKey;
641
682
  }
642
683
  return result + text.slice(copied);
643
684
  }
@@ -750,12 +791,7 @@ function writePatchFile(patchPath, contents) {
750
791
  };
751
792
  }
752
793
  }
753
- function appendPatchEntry(patchPath, block) {
754
- let text = '';
755
- try {
756
- text = readPatchText(patchPath);
757
- }
758
- catch { /* created below */ }
794
+ function appendPatchEntry(patchPath, block, text) {
759
795
  const core = text.trim();
760
796
  if (core === '') {
761
797
  return writePatchFile(patchPath, block);
@@ -791,7 +827,7 @@ function appendPatchEntry(patchPath, block) {
791
827
  }
792
828
  // The dsh entry-list dialect decides: anything that does not parse as a
793
829
  // top-level array is left untouched (appending would deepen the break).
794
- if (parsePatchFile(patchPath) === null) {
830
+ if (parsePatchText(text) === null) {
795
831
  return {
796
832
  ok: false,
797
833
  reason: '补丁层不是合法的条目数组,已拒绝追加以免破坏;请先修正 YAML / the patch layer is not a valid entry list; refused to append — fix the YAML first',
@@ -810,6 +846,8 @@ function appendPatchEntry(patchPath, block) {
810
846
  * the one block at the same time.
811
847
  */
812
848
  export function disableRow(patchPath, rowId, options = {}) {
849
+ const expected = options.expectedName ?? null;
850
+ const name = options.recordModuleName === true && expected !== null && NPM_NAME_RE.test(expected) ? expected : null;
813
851
  return queuedWrite(async () => {
814
852
  if (!ROW_ID_RE.test(rowId)) {
815
853
  return { ok: false, reason: `行 id 含特殊字符,不支持写入补丁层 / row id ${rowId} cannot be written to the patch layer` };
@@ -823,32 +861,33 @@ export function disableRow(patchPath, rowId, options = {}) {
823
861
  }
824
862
  })();
825
863
  let kept = false;
826
- const next = rewriteRowBlocks(text, rowId, 'any', block => {
864
+ const next = rewriteRowBlocks(text, rowId, 'any', (block, recordedName) => {
827
865
  if (kept)
828
866
  return '';
829
867
  kept = true;
830
- return block.replace(/^ {2}disabled: false(?=[ \t]*(?:\r?\n|$))/mu, ' disabled: true');
831
- }, options.expectedName ?? null);
832
- if (next !== text) {
833
- const flipped = writePatchFile(patchPath, next);
834
- if (!flipped.ok)
868
+ const flipped = block.replace(/^ {2}disabled: false(?=[ \t]*(?:\r?\n|$))/mu, ' disabled: true');
869
+ if (recordedName !== null || name === null)
835
870
  return flipped;
871
+ const eol = block.includes('\r\n') ? '\r\n' : '\n';
872
+ return (flipped.endsWith('\n') ? flipped : flipped + eol) + moduleNameLine(name) + eol;
873
+ }, expected, options.packageName ?? expected);
874
+ if (next !== text) {
836
875
  // A longer entry for the row further down still has the last word.
837
- if (lastRowFlag(next, rowId, options.expectedName ?? null) !== 'true') {
838
- const result = appendPatchEntry(patchPath, rowBlock(rowId, true));
839
- if (!result.ok)
840
- return result;
841
- }
876
+ const result = lastRowFlag(next, rowId, expected) === 'true'
877
+ ? writePatchFile(patchPath, next)
878
+ : appendPatchEntry(patchPath, rowBlock(rowId, true, name), next);
879
+ if (!result.ok)
880
+ return result;
842
881
  logEvent('info', 'patch', `disabled row ${rowId} in ${patchPath}`);
843
882
  return { ok: true, reason: null };
844
883
  }
845
884
  // A row whose `name` is not this entry's owns nothing here: counting it
846
885
  // as already-disabled would answer "off" and change nothing, leaving the
847
886
  // plugin running (#1113).
848
- const state = withoutMismatchedRow(readUserPatchState(patchPath), rowId, options.expectedName ?? null);
887
+ const state = readUserPatchState(patchPath, id => id === rowId ? expected ?? options.packageName ?? null : null);
849
888
  if (state.disables.includes(rowId))
850
889
  return { ok: true, reason: null };
851
- const result = appendPatchEntry(patchPath, rowBlock(rowId, true));
890
+ const result = appendPatchEntry(patchPath, rowBlock(rowId, true, name), text);
852
891
  if (result.ok)
853
892
  logEvent('info', 'patch', `disabled row ${rowId} in ${patchPath}`);
854
893
  return result;
@@ -871,7 +910,7 @@ export function enableRow(patchPath, rowId, options = {}) {
871
910
  if (!ROW_ID_RE.test(rowId)) {
872
911
  return { ok: false, reason: `行 id 含特殊字符,不支持写入补丁层 / row id ${rowId} cannot be written to the patch layer` };
873
912
  }
874
- const state = withoutMismatchedRow(readUserPatchState(patchPath), rowId, expected);
913
+ const state = readUserPatchState(patchPath, id => id === rowId ? expected ?? options.packageName ?? null : null);
875
914
  const text = (() => {
876
915
  try {
877
916
  return readPatchText(patchPath);
@@ -880,30 +919,35 @@ export function enableRow(patchPath, rowId, options = {}) {
880
919
  return '';
881
920
  }
882
921
  })();
883
- const next = rewriteRowBlocks(text, rowId, 'true', () => '', expected);
922
+ let removedMarketName;
923
+ const next = rewriteRowBlocks(text, rowId, 'true', (_block, name) => {
924
+ if (name !== null)
925
+ removedMarketName = name;
926
+ return '';
927
+ }, expected, options.packageName ?? expected);
884
928
  if (next !== text) {
885
- const written = writePatchFile(patchPath, withPlaceholderRestored(next));
886
- if (!written.ok)
887
- return written;
888
929
  // A longer entry for the row may still have the last word — and so may a
889
930
  // spelling the line scanner cannot see (#1112). Ask the parser the host
890
931
  // uses; when the file is not readable as its dialect, fall back to the
891
932
  // scanner.
892
- const stillOff = composedRowFlag(next, rowId, expected) ?? lastRowFlag(next, rowId, expected);
893
- if (!cleanOnly && stillOff === 'true') {
894
- const result = appendPatchEntry(patchPath, rowBlock(rowId, false));
895
- if (!result.ok)
896
- return result;
897
- }
933
+ const target = expected ?? removedMarketName ?? options.packageName ?? null;
934
+ const stillOff = composedRowFlag(next, rowId, target) ?? lastRowFlag(next, rowId, target);
935
+ const written = !cleanOnly && stillOff === 'true'
936
+ ? appendPatchEntry(patchPath, rowBlock(rowId, false, removedMarketName ?? null), next)
937
+ : writePatchFile(patchPath, withPlaceholderRestored(next));
938
+ if (!written.ok)
939
+ return written;
898
940
  logEvent('info', 'patch', `${cleanOnly ? 'cleared the block on' : 'enabled'} row ${rowId} in ${patchPath}`);
899
- return { ok: true, reason: null };
941
+ return removedMarketName === undefined
942
+ ? { ok: true, reason: null }
943
+ : { ok: true, reason: null, removedMarketName };
900
944
  }
901
945
  // Nothing of the market's own to clean: the row's default stands.
902
946
  if (cleanOnly)
903
947
  return { ok: true, reason: null };
904
948
  if (state.forced.includes(rowId))
905
949
  return { ok: true, reason: null };
906
- const result = appendPatchEntry(patchPath, rowBlock(rowId, false));
950
+ const result = appendPatchEntry(patchPath, rowBlock(rowId, false), text);
907
951
  if (result.ok)
908
952
  logEvent('info', 'patch', `force-enabled row ${rowId} in ${patchPath}`);
909
953
  return result;
@@ -929,7 +973,7 @@ function withPlaceholderRestored(text) {
929
973
  }
930
974
  /** Remove every disable/force block the market (or the user) wrote for a
931
975
  * row — the uninstall cleanup, so a removed plugin leaves no orphan rows. */
932
- export function removeRowBlocks(patchPath, rowIds) {
976
+ export function removeRowBlocks(patchPath, rowIds, packageName = null) {
933
977
  let text = '';
934
978
  try {
935
979
  text = readPatchText(patchPath);
@@ -939,7 +983,7 @@ export function removeRowBlocks(patchPath, rowIds) {
939
983
  } // no file, nothing to remove
940
984
  let next = text;
941
985
  for (const rowId of rowIds)
942
- next = rewriteRowBlocks(next, rowId, 'any', () => '');
986
+ next = rewriteRowBlocks(next, rowId, 'any', () => '', packageName);
943
987
  if (next === text)
944
988
  return { ok: true, reason: null };
945
989
  const written = writePatchFile(patchPath, withPlaceholderRestored(next));
@@ -30,14 +30,13 @@
30
30
  * ordinary start after a restart.
31
31
  */
32
32
  import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
33
- import { dirname } from 'node:path';
33
+ import { dirname, join } from 'node:path';
34
34
  import { removeRowBlocks } from './patch.js';
35
35
  import { readInstalled } from './profile.js';
36
- import { statePath } from './state.js';
37
36
  const STATE_VERSION = 1;
38
37
  /** Same directory as the other durable per-profile state (see pending-updates.ts). */
39
38
  export function pendingRowsFile(profileDirectory) {
40
- return statePath(profileDirectory, 'pending-rows.json');
39
+ return join(profileDirectory, '.dsh-crate', 'pending-rows.json');
41
40
  }
42
41
  export class PendingRowJournal {
43
42
  file;
@@ -130,7 +129,7 @@ export function repairOrphanedRows(options) {
130
129
  report.kept.push(record.name);
131
130
  continue;
132
131
  }
133
- const cleaned = removeRowBlocks(record.patchPath, record.rows);
132
+ const cleaned = removeRowBlocks(record.patchPath, record.rows, record.name);
134
133
  if (!cleaned.ok) {
135
134
  report.failed.push(record.name);
136
135
  continue;
@@ -16,6 +16,7 @@
16
16
  import { existsSync, readFileSync } from 'node:fs';
17
17
  import { join } from 'node:path';
18
18
  import { CHINA_NPM_REGISTRY } from './regions.js';
19
+ import { classifyPeer } from './compatibility.js';
19
20
  /**
20
21
  * Decide the argv for a `dsh plugin <add|remove> …` call in the given profile.
21
22
  *
@@ -372,6 +373,52 @@ function storeRelinkAdvice(linked, wanted, profileDirectory) {
372
373
  en: `durable fix: write the store from the RECORD into the profile's pnpm-workspace.yaml, top level, camelCase, single quotes (a Windows path in double quotes is read as escape sequences and the whole file fails to parse):\n\n ${paste}\n\nNothing has to be reinstalled — the packages are already in that store, so just retry (stop dsh first if it holds the files open). ${verifyEn}If that path no longer exists (the drive changed, the directory was deleted), pinning it would tie the profile to an empty store — adopt the store pnpm now resolves instead (every package is downloaded again).`,
373
374
  };
374
375
  }
376
+ /** The DSH version the host's own rejection line names, or null when it is absent. */
377
+ function hostVersionInRejection(output) {
378
+ return /is incompatible with dsh ([0-9][0-9A-Za-z.+-]*)/.exec(output)?.[1] ?? null;
379
+ }
380
+ /**
381
+ * Which side of its declared range the host actually sits on (#1210).
382
+ *
383
+ * The host's line carries both facts this needs: the version it rejected
384
+ * against, and `requirements {...}` — the ranges it evaluated. Direction comes
385
+ * from {@link classifyPeer}, the same predicate the pre-flight uses, so the
386
+ * dialog and the pre-flight cannot disagree about which side is behind.
387
+ *
388
+ * null means "not provable from this text" — an unparseable range, no version,
389
+ * or declarations pointing opposite ways. Callers must then name no direction
390
+ * rather than assume the one the branch was originally written for.
391
+ */
392
+ function rejectedSide(output) {
393
+ const host = hostVersionInRejection(output);
394
+ const raw = /requirements (\{[^}]*\})/.exec(output)?.[1] ?? '';
395
+ if (host === null || raw === '')
396
+ return null;
397
+ let declared;
398
+ try {
399
+ declared = JSON.parse(raw);
400
+ }
401
+ catch {
402
+ return null;
403
+ }
404
+ if (declared === null || typeof declared !== 'object' || Array.isArray(declared))
405
+ return null;
406
+ const sides = new Set();
407
+ for (const [key, value] of Object.entries(declared)) {
408
+ if (typeof value !== 'string' || value.trim() === '')
409
+ continue;
410
+ const verdict = classifyPeer('', key, value, host, false);
411
+ if (verdict.kind === 'risk') {
412
+ sides.add(verdict.risk.direction === 'belowMin' ? 'host-too-old' : 'plugin-too-old');
413
+ }
414
+ else if (verdict.kind === 'warning' && verdict.warning.reason === 'aboveMax') {
415
+ // A `^` / `~` ceiling the author never wrote still names the line the
416
+ // host has left behind; the host is above it either way.
417
+ sides.add('plugin-too-old');
418
+ }
419
+ }
420
+ return sides.size === 1 ? [...sides][0] ?? null : null;
421
+ }
375
422
  export function classifyPnpmFailure(output, exitCode, context) {
376
423
  // #817: the host's silence watchdog (@deepseek-ai/dsh-plugin-manager,
377
424
  // `idleTimeoutMs`, 10 minutes by default) killed pnpm. Checked first: it is
@@ -691,10 +738,41 @@ export function classifyPnpmFailure(output, exitCode, context) {
691
738
  // market failure (#404's question, answered by the host).
692
739
  if (output.includes('dsh: installation rejected:') && /is incompatible with dsh \d/.test(output)) {
693
740
  const requirement = /requirements (\{[^}]*\})/.exec(output)?.[1] ?? '';
741
+ // #1210: which SIDE of the range the host sits on decides what the user can
742
+ // do about it, and both sides land in this one branch. The old text named
743
+ // one direction only ("needs a newer DSH"), so a release whose ceiling is
744
+ // BELOW the running host — @anionex/dsh-vision-toolkit capping at
745
+ // 0.2.2-rc.2 on a 0.2.2-rc.3 host — told the reader to upgrade a host that
746
+ // was already ahead, and pointed the report at the host instead of the
747
+ // plugin. Direction comes from the same predicate the pre-flight uses
748
+ // (`classifyPeer` → belowMin/aboveMax), not from a second one written here.
749
+ const exemption = '确实要装这一个,需要先在宿主的插件管理器(或 dsh 的 allow-version)里为这个具体版本授权,再重试';
750
+ const exemptionEn = 'to install this exact one anyway, grant the host\'s exact-version exemption for it first (plugin manager, or dsh\'s allow-version) and retry';
751
+ const declared = requirement === '' ? '' : `(它声明的需求:${requirement})`;
752
+ const declaredEn = requirement === '' ? '' : ` (it declares ${requirement})`;
753
+ const side = rejectedSide(output);
754
+ if (side === 'plugin-too-old') {
755
+ const host = hostVersionInRejection(output) ?? '当前版本';
756
+ return {
757
+ code: 'host-incompatible-install',
758
+ recoverable: false,
759
+ message: `这个插件的兼容上界低于当前运行的 DSH ${host},宿主在安装时自己拒绝了${declared}——是插件还没适配这个宿主版本,不是宿主落后。等插件发布覆盖 ${host} 的新版本,或改装一个仍覆盖它的旧版插件;${exemption} / this plugin's compatible ceiling is below the running DSH ${host}, and the HOST refused the install itself${declaredEn} — the plugin has not caught up with this host line, the host is not behind. Wait for a plugin release that covers ${host}, or install an older plugin version that still does; ${exemptionEn}`,
760
+ };
761
+ }
762
+ if (side === 'host-too-old') {
763
+ return {
764
+ code: 'host-incompatible-install',
765
+ recoverable: false,
766
+ message: `这个版本要求的 DSH 比当前运行的新,宿主在安装时自己拒绝了${declared}。换一个兼容的版本即可;${exemption} / this release needs a newer DSH than the one running, and the HOST refused the install itself${declaredEn} — not the market's check. Pick a compatible version; ${exemptionEn}`,
767
+ };
768
+ }
769
+ // Neither side is provable from the host's own text (an unparseable range,
770
+ // several declarations pointing opposite ways, or a rejection the two
771
+ // bounds do not explain). Keep the facts and name no direction.
694
772
  return {
695
773
  code: 'host-incompatible-install',
696
774
  recoverable: false,
697
- message: `这个版本要求的 DSH 比当前运行的新,宿主在安装时自己拒绝了${requirement === '' ? '' : `(它声明的需求:${requirement})`}。换一个兼容的版本即可;确实要装这一个,需要先在宿主的插件管理器(或 dsh 的 allow-version)里为这个具体版本授权,再重试 / this release needs a newer DSH than the one running, and the HOST refused the install itself${requirement === '' ? '' : ` (it declares ${requirement})`} — not the market's check. Pick a compatible version; to install this exact one anyway, grant the host's exact-version exemption for it first (plugin manager, or dsh's allow-version) and retry`,
775
+ message: `宿主在安装时以「与当前运行的 DSH 不兼容」为由拒绝了${declared}。换一个兼容的版本即可;${exemption} / the HOST refused the install as incompatible with the running DSH${declaredEn} — not the market's check. Pick a compatible version; ${exemptionEn}`,
698
776
  };
699
777
  }
700
778
  // #69: pnpm >= 10 blocks dependency build scripts by default. The install
package/lib/proc-text.js CHANGED
@@ -21,6 +21,21 @@ export function decodeChildOutput(bytes, platform = process.platform) {
21
21
  return new TextDecoder('utf-8', { fatal: true }).decode(bytes);
22
22
  }
23
23
  catch {
24
+ // A window cut through the middle of a UTF-8 character starts with its
25
+ // continuation bytes. Dropping them is what makes the rest UTF-8 again;
26
+ // without this the whole tail was read as GBK on Windows. Only taken when
27
+ // what remains is non-ASCII UTF-8, which GBK text does not happen to be.
28
+ let start = 0;
29
+ while (start < 3 && start < bytes.length && (bytes[start] & 0xc0) === 0x80)
30
+ start += 1;
31
+ if (start > 0) {
32
+ try {
33
+ const rest = new TextDecoder('utf-8', { fatal: true }).decode(bytes.subarray(start));
34
+ if (/[^\x00-\x7f]/u.test(rest))
35
+ return rest;
36
+ }
37
+ catch { /* not UTF-8 either way */ }
38
+ }
24
39
  // Not UTF-8. Only Windows consoles hand a child a non-UTF-8 code page;
25
40
  // elsewhere keep the previous behaviour (replace the bad bytes) rather
26
41
  // than invent Chinese out of binary noise.
@@ -53,7 +68,7 @@ export function createOutputBuffer(limit, platform = process.platform) {
53
68
  return;
54
69
  chunks.push(chunk);
55
70
  size += chunk.length;
56
- while (size > limit && chunks.length > 1) {
71
+ while (chunks.length > 1 && size - chunks[0].length >= limit) {
57
72
  size -= chunks.shift().length;
58
73
  }
59
74
  const first = chunks[0];
package/lib/recovery.js CHANGED
@@ -305,7 +305,8 @@ export async function applyRecovery(config, enabled) {
305
305
  }
306
306
  if (error === null) {
307
307
  for (const row of plugin.rows) {
308
- const result = want ? await enableRow(config.patchPath, row) : await disableRow(config.patchPath, row);
308
+ const options = { packageName: plugin.name };
309
+ const result = want ? await enableRow(config.patchPath, row, options) : await disableRow(config.patchPath, row, options);
309
310
  if (!result.ok) {
310
311
  error = result.reason ?? 'the patch layer refused the write';
311
312
  break;
package/lib/registry.js CHANGED
@@ -1,14 +1,27 @@
1
1
  /**
2
- * Registry access: crate 的目录(dsh-crate.json)每次请求都重新拉取。
3
- * 这里只负责抓取、重试、校验与 304 复用;字段映射见 src/crate-catalog.ts。
2
+ * Registry access: the curated list from awesome-dsh-plugin.com, fetched
3
+ * fresh on every request. See `loadRegistry` for why there is nothing
4
+ * behind it any more.
4
5
  */
5
6
  import { BODY_STALL_TIMEOUT_MS, HEADERS_TIMEOUT_MS, readBodyWhileProgressing } from './body-progress.js';
6
7
  import { logEvent } from './log.js';
7
8
  import { configuredProxy, marketFetch } from './net.js';
8
9
  import { catalogFromPackage } from './catalog-npm.js';
9
- import { activeRegion, catalogSourcesFor, routesFor } from './regions.js';
10
10
  import { asCrateRegistry, isCrateCatalog } from './crate-catalog.js';
11
+ import { activeRegion, catalogSourcesFor, routesFor } from './regions.js';
11
12
  import { NPM_NAME_RE } from './sources.js';
13
+ /**
14
+ * How long a successful catalog load may take before it leaves a line behind.
15
+ *
16
+ * A load that fails already documents itself: the thrown message carries the
17
+ * elapsed time and the attempt count. A load that SUCCEEDS carries nothing,
18
+ * so a market that took forty seconds and one that took two produce the same
19
+ * export — "(none — the buffer starts empty on every start)" — and a report
20
+ * cannot tell them apart (#1181: thirteen seconds, twenty, forty on the same
21
+ * machine, five minutes on the run that failed, all with an empty session).
22
+ * The threshold sits above any healthy load, so the ordinary case stays quiet.
23
+ */
24
+ const SLOW_CATALOG_MS = 5_000;
12
25
  /**
13
26
  * Category ids for one catalog entry, de-duplicated in declaration order.
14
27
  *
@@ -101,8 +114,8 @@ function sourceKey(source) {
101
114
  /**
102
115
  * 目录载荷分派:按结构选适配器,而不是按地区或地址。
103
116
  *
104
- * crate 的载荷带 `entries`,旧的目录带 `plugins`;两套结构各自校验,夹具
105
- * 与真实数据都不会误入对方的分支。
117
+ * crate 的载荷带 `entries`,上游目录带 `plugins`;两套结构各自校验,
118
+ * 夹具与真实数据都不会误入对方的分支。
106
119
  *
107
120
  * @param value - 已经 `JSON.parse` 过的目录载荷。
108
121
  * @throws 两个适配器都可能因为数据不可用而抛出,异常留给调用方重试。
@@ -193,6 +206,14 @@ export async function loadRegistry(region = activeRegion()) {
193
206
  if (sourceIndex >= ownSources) {
194
207
  logEvent('warn', 'registry', `catalog: the ${region} sources did not answer; read the catalog package from ${key} instead (#891)`);
195
208
  }
209
+ // Success is silent by default, which is what makes a slow one
210
+ // undiagnosable: the export says the same thing whether the market
211
+ // appeared in two seconds or in forty (#1181). One line above the
212
+ // threshold, none below it.
213
+ const elapsed = Date.now() - started;
214
+ if (elapsed >= SLOW_CATALOG_MS) {
215
+ logEvent('info', 'registry', `catalog: ${key} answered in ${(elapsed / 1000).toFixed(1)}s after ${String(attempts)} request attempt(s)`);
216
+ }
196
217
  return data;
197
218
  };
198
219
  // Two attempts each. A catalog fetch crossing a long, lossy path fails
@@ -213,7 +234,7 @@ export async function loadRegistry(region = activeRegion()) {
213
234
  return servedBy(reusable.data);
214
235
  if (data === null)
215
236
  throw new Error('the catalog package reported no change with nothing to reuse');
216
- const parsed = asRegistry(data);
237
+ const parsed = parseCatalog(data);
217
238
  served = { key, etag: null, modified: null, version, data: parsed };
218
239
  return servedBy(parsed);
219
240
  }
@@ -14,6 +14,10 @@ export function isStableReleaseVersion(value) {
14
14
  const parsed = semver(value);
15
15
  return parsed !== null && parsed.prerelease.length === 0;
16
16
  }
17
+ /** Accept a bounded exact npm release version, including prereleases. */
18
+ export function isExactReleaseVersion(value) {
19
+ return typeof value === 'string' && value.length <= 256 && value === value.trim() && semver(value) !== null;
20
+ }
17
21
  function compare(a, b) {
18
22
  for (let i = 0; i < 3; i++) {
19
23
  if (a.core[i] !== b.core[i])