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
@@ -0,0 +1,506 @@
1
+ /**
2
+ * Profile snapshots — issue #98 (phase 3), implementing the snapshot half of
3
+ * #19: before any ordering / preset change is applied, the profile's
4
+ * composition-critical files are captured as a timestamped snapshot; a failed
5
+ * or unwanted change can be rolled back in one step.
6
+ *
7
+ * A snapshot is a single JSON document under `<profile>/.dsh-crate/
8
+ * snapshots/<timestamp>-<seq>.json` describing the files that define the
9
+ * profile's composition: package.json (dependency + bundle list),
10
+ * cordis.patch.yml (the user patch layer) and state.json (market disable
11
+ * list + groups). Version 2 records optional-file absence explicitly;
12
+ * restoring validates every path, reconciles writes and deletions, and rolls
13
+ * completed actions back if a later action fails.
14
+ *
15
+ * Retention: after every create, snapshots are pruned to the most recent
16
+ * `maxSnapshots` (default 20); the cap is configurable through the market
17
+ * plugin config (`maxSnapshots`) and each snapshot can also be deleted
18
+ * individually from the UI.
19
+ */
20
+ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
21
+ import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
22
+ import { logEvent } from './log.js';
23
+ import { stateDir } from './state.js';
24
+ const SNAPSHOT_FORMAT = 'dsh-crate/profile-snapshot';
25
+ /** 0.4.x 写下的快照格式标识,只用于读取旧快照。 */
26
+ const LEGACY_SNAPSHOT_FORMAT = 'dsh-shelfry/profile-snapshot';
27
+ const SNAPSHOT_VERSION = 2;
28
+ /**
29
+ * Snapshot ids are generated by nextSnapshotId and must never be attacker-
30
+ * shaped: anything else (paths, '..', absolute paths) is refused BEFORE it
31
+ * reaches the filesystem, so restoreSnapshot/deleteSnapshot cannot escape the
32
+ * snapshots directory (issue #98 review B3 — same discipline as backup.ts).
33
+ */
34
+ const SNAPSHOT_ID_RE = /^snapshot-[0-9A-Za-z-]+$/;
35
+ function validSnapshotId(id) {
36
+ return SNAPSHOT_ID_RE.test(id);
37
+ }
38
+ /** The files a snapshot captures, relative to the profile directory. */
39
+ const SNAPSHOT_FILES = ['package.json', 'cordis.patch.yml', '.dsh-crate/state.json'];
40
+ function hasOwn(value, key) {
41
+ return Object.prototype.hasOwnProperty.call(value, key);
42
+ }
43
+ /**
44
+ * Strict shape validation for a parsed snapshot document (issue #98 analysis:
45
+ * snapshot JSON validation). A snapshot that fails these checks is corrupt —
46
+ * it can never be restored safely, so listing it would only offer the user a
47
+ * restore that must fail.
48
+ */
49
+ function validateSnapshotDocument(value) {
50
+ if (value === null || typeof value !== 'object') {
51
+ return { ok: false, error: 'corrupt snapshot document / 快照文档损坏' };
52
+ }
53
+ const snap = value;
54
+ if (typeof snap.id !== 'string' || !validSnapshotId(snap.id)) {
55
+ return { ok: false, error: 'corrupt snapshot id / 快照 id 损坏' };
56
+ }
57
+ if (typeof snap.createdAt !== 'number' || !Number.isFinite(snap.createdAt)) {
58
+ return { ok: false, error: 'corrupt snapshot timestamp / 快照时间损坏' };
59
+ }
60
+ if (!Array.isArray(snap.files)) {
61
+ return { ok: false, error: 'corrupt snapshot: files is not an array / 快照损坏:files 不是数组' };
62
+ }
63
+ // Existing unversioned documents are legacy v1. Their omitted optional
64
+ // paths remain no-ops: older capture also omitted unreadable/invalid files,
65
+ // so absence cannot be inferred safely after the fact.
66
+ const legacy = !hasOwn(snap, 'format') && !hasOwn(snap, 'version');
67
+ const legacyFormat = snap.format === LEGACY_SNAPSHOT_FORMAT;
68
+ if (!legacy && !legacyFormat && (snap.format !== SNAPSHOT_FORMAT || snap.version !== SNAPSHOT_VERSION)) {
69
+ return { ok: false, error: 'unsupported snapshot format or version / 不支持的快照格式或版本' };
70
+ }
71
+ const byPath = new Map();
72
+ for (const file of snap.files) {
73
+ if (file === null || typeof file !== 'object') {
74
+ return { ok: false, error: 'corrupt snapshot file entry / 快照文件条目损坏' };
75
+ }
76
+ const entry = file;
77
+ const rawPath = entry.path;
78
+ // 0.4.x 的快照把状态文件记在旧目录名下,读取时映射到新目录。
79
+ const path = rawPath === '.dsh-shelfry/state.json' ? '.dsh-crate/state.json' : rawPath;
80
+ if (typeof path !== 'string'
81
+ || !SNAPSHOT_FILES.includes(path)
82
+ || path.includes('..')) {
83
+ return { ok: false, error: `unsafe snapshot path: ${String(rawPath)} / 快照路径不安全` };
84
+ }
85
+ if (byPath.has(path)) {
86
+ return { ok: false, error: `duplicate snapshot path: ${path} / 快照路径重复` };
87
+ }
88
+ const hasJson = hasOwn(entry, 'json');
89
+ const hasLines = hasOwn(entry, 'lines');
90
+ const hasAbsent = hasOwn(entry, 'absent');
91
+ if (Number(hasJson) + Number(hasLines) + Number(hasAbsent) !== 1) {
92
+ return { ok: false, error: `snapshot file ${entry.path} must have exactly one representation / 快照文件表示无效` };
93
+ }
94
+ if (hasLines && (!Array.isArray(entry.lines) || !entry.lines.every(line => typeof line === 'string'))) {
95
+ return { ok: false, error: `snapshot file ${entry.path} has invalid lines / 快照文件行无效` };
96
+ }
97
+ if (hasAbsent && (legacy || entry.absent !== true || path === 'package.json')) {
98
+ return { ok: false, error: `snapshot file ${rawPath} has invalid absence marker / 快照文件缺失标记无效` };
99
+ }
100
+ if ((path === 'package.json' || path === '.dsh-crate/state.json') && !hasJson && !hasAbsent) {
101
+ return { ok: false, error: `snapshot file ${rawPath} has the wrong representation / 快照文件表示类型错误` };
102
+ }
103
+ if (path === 'cordis.patch.yml' && !hasLines && !hasAbsent) {
104
+ return { ok: false, error: `snapshot file ${rawPath} has the wrong representation / 快照文件表示类型错误` };
105
+ }
106
+ byPath.set(path, { ...entry, path });
107
+ }
108
+ if (!legacy && SNAPSHOT_FILES.some(path => !byPath.has(path))) {
109
+ return { ok: false, error: 'v2 snapshot does not describe every composition file / v2 快照未描述全部组合文件' };
110
+ }
111
+ if (!byPath.has('package.json')) {
112
+ return { ok: false, error: 'snapshot has no package.json / 快照缺少 package.json' };
113
+ }
114
+ const files = SNAPSHOT_FILES.flatMap(path => {
115
+ const file = byPath.get(path);
116
+ return file === undefined ? [] : [file];
117
+ });
118
+ return {
119
+ ok: true,
120
+ value: {
121
+ snapshot: { ...snap, files },
122
+ files,
123
+ },
124
+ };
125
+ }
126
+ /**
127
+ * Atomic same-directory replace (write temp + rename): a crash mid-write can
128
+ * never leave a snapshot file truncated — a half-written snapshot would parse
129
+ * as corrupt forever and could not be restored.
130
+ */
131
+ function writeFileAtomic(file, content) {
132
+ const temp = `${file}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
133
+ try {
134
+ writeFileSync(temp, content);
135
+ renameSync(temp, file);
136
+ }
137
+ catch (error) {
138
+ try {
139
+ rmSync(temp, { force: true });
140
+ }
141
+ catch { /* best-effort temp cleanup */ }
142
+ throw error;
143
+ }
144
+ }
145
+ function isMissingFileError(error) {
146
+ return error !== null
147
+ && typeof error === 'object'
148
+ && 'code' in error
149
+ && error.code === 'ENOENT';
150
+ }
151
+ /**
152
+ * `readFileSync` also reports ENOENT for a dangling symlink. Check the path
153
+ * entry itself before recording absence so an unreadable composition path can
154
+ * never be silently converted into a delete instruction for a later restore.
155
+ */
156
+ function isTrulyAbsent(path, readError) {
157
+ if (!isMissingFileError(readError))
158
+ return false;
159
+ try {
160
+ lstatSync(path);
161
+ return false;
162
+ }
163
+ catch (statError) {
164
+ return isMissingFileError(statError);
165
+ }
166
+ }
167
+ /** Absolute snapshot directory for a profile. */
168
+ function snapshotDir(profileDir) {
169
+ return join(stateDir(profileDir), 'snapshots');
170
+ }
171
+ function snapshotFile(profileDir, id) {
172
+ if (!validSnapshotId(id))
173
+ throw new Error('invalid snapshot id / 无效的快照 id');
174
+ return join(snapshotDir(profileDir), `${id}.json`);
175
+ }
176
+ /** Basename of the next snapshot (timestamp + sequence for same-ms saves). */
177
+ function nextSnapshotId(profileDir) {
178
+ const dir = snapshotDir(profileDir);
179
+ let names = [];
180
+ try {
181
+ names = readdirSync(dir);
182
+ }
183
+ catch { /* directory absent — no collisions */ }
184
+ const now = new Date().toISOString().replace(/[:.]/g, '-');
185
+ let seq = 0;
186
+ let id = `snapshot-${now}`;
187
+ while (names.includes(`${id}.json`)) {
188
+ seq += 1;
189
+ id = `snapshot-${now}-${String(seq)}`;
190
+ }
191
+ return id;
192
+ }
193
+ /** Default number of snapshots retained; configurable via `maxSnapshots`. */
194
+ export const DEFAULT_MAX_SNAPSHOTS = 20;
195
+ function captureError(path, reason, reasonZh) {
196
+ return `profile composition could not be captured: ${path} ${reason} / 无法捕获 profile 组合:${path} ${reasonZh}`;
197
+ }
198
+ function errorCode(error) {
199
+ if (error === null || typeof error !== 'object' || !('code' in error))
200
+ return undefined;
201
+ return typeof error.code === 'string' ? error.code : undefined;
202
+ }
203
+ function captureReadError(path, error) {
204
+ const code = errorCode(error);
205
+ const suffix = code === undefined ? '' : ` (${code})`;
206
+ return captureError(path, `could not be read${suffix}`, `无法读取${suffix}`);
207
+ }
208
+ /**
209
+ * Prune the snapshot directory to the `max` most recent snapshots (newest
210
+ * first). Extra ones are deleted oldest-first. A non-positive cap is clamped
211
+ * to 1 — a 0/negative max must never drop the snapshot that was just created
212
+ * nor invert to keeping the OLDEST set (issue #98 review hardening).
213
+ * @returns the ids that were deleted.
214
+ */
215
+ export function pruneSnapshots(profileDir, max) {
216
+ return pruneSnapshotsKeeping(profileDir, max);
217
+ }
218
+ /** Refuse an existing parent that could redirect a restore outside the profile. */
219
+ function ensureSafeRestoreParent(profileDir, parent, snapshotPath) {
220
+ const root = resolve(profileDir);
221
+ const relativeParent = relative(root, resolve(parent));
222
+ if (relativeParent === '')
223
+ return;
224
+ if (isAbsolute(relativeParent) || relativeParent === '..' || relativeParent.startsWith(`..${sep}`)) {
225
+ throw new Error(`unsafe snapshot restore path: ${snapshotPath} / 快照恢复路径不安全`);
226
+ }
227
+ let current = root;
228
+ for (const part of relativeParent.split(sep)) {
229
+ current = resolve(current, part);
230
+ let stat;
231
+ try {
232
+ stat = lstatSync(current);
233
+ }
234
+ catch (error) {
235
+ if (isMissingFileError(error))
236
+ return;
237
+ throw error;
238
+ }
239
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
240
+ throw new Error(`unsafe snapshot restore path: ${snapshotPath} / 快照恢复路径不安全`);
241
+ }
242
+ }
243
+ }
244
+ function snapshotIdOrderKey(id) {
245
+ const generated = /^(snapshot-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z)(?:-(\d+))?$/;
246
+ const match = generated.exec(id);
247
+ return match === null
248
+ ? { category: 1, primary: id, sequence: 0n, fallback: id }
249
+ : { category: 0, primary: match[1], sequence: BigInt(match[2] ?? '0'), fallback: id };
250
+ }
251
+ /** @internal Deterministic newest-first order for equal-createdAt documents. */
252
+ export function compareSnapshotIdsNewest(a, b) {
253
+ const aKey = snapshotIdOrderKey(a);
254
+ const bKey = snapshotIdOrderKey(b);
255
+ if (aKey.category !== bKey.category)
256
+ return aKey.category - bKey.category;
257
+ if (aKey.primary !== bKey.primary)
258
+ return aKey.primary < bKey.primary ? 1 : -1;
259
+ if (aKey.sequence !== bKey.sequence)
260
+ return aKey.sequence < bKey.sequence ? 1 : -1;
261
+ return aKey.fallback === bKey.fallback ? 0 : aKey.fallback < bKey.fallback ? 1 : -1;
262
+ }
263
+ function pruneSnapshotsKeeping(profileDir, max, keepId) {
264
+ const cap = Math.max(1, max);
265
+ const all = listSnapshots(profileDir);
266
+ if (all.length <= cap)
267
+ return [];
268
+ // Sequence-suffixed ids can share createdAt. Creation must pin its own id
269
+ // ahead of that tie so it never returns a snapshot pruning just removed.
270
+ const ordered = keepId === undefined
271
+ ? all
272
+ : [...all.filter(snap => snap.id === keepId), ...all.filter(snap => snap.id !== keepId)];
273
+ const dropped = ordered.slice(cap);
274
+ for (const snap of dropped)
275
+ deleteSnapshot(profileDir, snap.id);
276
+ if (dropped.length > 0) {
277
+ logEvent('info', 'snapshot', `pruned ${dropped.length} old snapshot(s) (cap ${cap}): ${dropped.map(s => s.id).join(', ')}`);
278
+ }
279
+ return dropped.map(s => s.id);
280
+ }
281
+ /**
282
+ * Capture the profile's composition into a version 2 snapshot. Missing
283
+ * optional files are represented explicitly. An existing optional file that
284
+ * cannot be read makes capture fail. Invalid market state is represented as
285
+ * absent because every state reader already observes it as empty and the next
286
+ * state write replaces it. A missing, unreadable, or invalid package.json is
287
+ * not snapshot-able. After creating, the directory is pruned to the most
288
+ * recent `maxSnapshots`.
289
+ */
290
+ export function createProfileSnapshot(profileDir, maxSnapshots = DEFAULT_MAX_SNAPSHOTS) {
291
+ const packagePath = join(profileDir, 'package.json');
292
+ let packageText;
293
+ try {
294
+ packageText = readFileSync(packagePath, 'utf8');
295
+ }
296
+ catch (error) {
297
+ const failure = isTrulyAbsent(packagePath, error)
298
+ ? captureError('package.json', 'is missing', '缺失')
299
+ : captureReadError('package.json', error);
300
+ logEvent('error', 'snapshot', failure);
301
+ return { ok: false, error: failure };
302
+ }
303
+ let packageJson;
304
+ try {
305
+ packageJson = JSON.parse(packageText);
306
+ }
307
+ catch {
308
+ const failure = captureError('package.json', 'contains invalid JSON', '包含无效 JSON');
309
+ logEvent('error', 'snapshot', failure);
310
+ return { ok: false, error: failure };
311
+ }
312
+ const files = [{ path: 'package.json', json: packageJson }];
313
+ for (const path of SNAPSHOT_FILES.slice(1)) {
314
+ const absolutePath = join(profileDir, path);
315
+ let text;
316
+ try {
317
+ text = readFileSync(absolutePath, 'utf8');
318
+ }
319
+ catch (error) {
320
+ if (isTrulyAbsent(absolutePath, error))
321
+ files.push({ path, absent: true });
322
+ else {
323
+ const failure = captureReadError(path, error);
324
+ logEvent('error', 'snapshot', failure);
325
+ return { ok: false, error: failure };
326
+ }
327
+ continue;
328
+ }
329
+ if (path === '.dsh-crate/state.json') {
330
+ try {
331
+ files.push({ path, json: JSON.parse(text) });
332
+ }
333
+ catch {
334
+ // readMarketState treats malformed state as empty and every state write
335
+ // replaces it, so absence is the exact observable composition state.
336
+ files.push({ path, absent: true });
337
+ logEvent('warn', 'snapshot', `${path} contains invalid JSON; captured as absent because Market reads it as empty`);
338
+ }
339
+ }
340
+ else {
341
+ files.push({ path, lines: text.split('\n') });
342
+ }
343
+ }
344
+ const id = nextSnapshotId(profileDir);
345
+ const snapshot = {
346
+ format: SNAPSHOT_FORMAT,
347
+ version: SNAPSHOT_VERSION,
348
+ id,
349
+ createdAt: Date.now(),
350
+ files,
351
+ };
352
+ mkdirSync(snapshotDir(profileDir), { recursive: true, mode: 0o700 });
353
+ writeFileAtomic(snapshotFile(profileDir, id), `${JSON.stringify(snapshot, null, 2)}\n`);
354
+ logEvent('info', 'snapshot', `created ${id} (${files.map(file => file.path).join(', ')})`);
355
+ pruneSnapshotsKeeping(profileDir, maxSnapshots, id);
356
+ return { ok: true, snapshot };
357
+ }
358
+ /**
359
+ * All snapshots for a profile, newest first. Files that are unparseable,
360
+ * shape-invalid (bad id/createdAt/files), or whose internal id does not match
361
+ * the file name are skipped — a snapshot that could never be restored is not
362
+ * listed (issue #98 analysis: snapshot JSON validation).
363
+ */
364
+ export function listSnapshots(profileDir) {
365
+ let names;
366
+ try {
367
+ names = readdirSync(snapshotDir(profileDir)).filter(name => name.endsWith('.json'));
368
+ }
369
+ catch {
370
+ return [];
371
+ }
372
+ const snapshots = [];
373
+ for (const name of names) {
374
+ try {
375
+ const id = name.slice(0, -5);
376
+ const value = JSON.parse(readFileSync(snapshotFile(profileDir, id), 'utf8'));
377
+ const validated = validateSnapshotDocument(value);
378
+ if (validated.ok && validated.value.snapshot.id === id)
379
+ snapshots.push(validated.value.snapshot);
380
+ }
381
+ catch { /* corrupt snapshot — skip */ }
382
+ }
383
+ return snapshots.sort((a, b) => b.createdAt - a.createdAt || compareSnapshotIdsNewest(a.id, b.id));
384
+ }
385
+ /**
386
+ * Restore a snapshot's files into the profile. Version 2 absence markers
387
+ * remove files created after capture; omitted optional files in unversioned
388
+ * legacy snapshots remain untouched. Every path is validated before mutation,
389
+ * each write uses a same-directory temp + rename, and a failure mid-restore
390
+ * rolls completed writes/deletions back to their pre-restore contents.
391
+ * @returns the paths restored; an error result when the snapshot is unsafe,
392
+ * unknown, or a write failed (with any partial writes rolled back).
393
+ */
394
+ export function restoreSnapshot(profileDir, id) {
395
+ if (!validSnapshotId(id)) {
396
+ return { ok: false, restored: [], error: 'invalid snapshot id / 无效的快照 id' };
397
+ }
398
+ let parsed;
399
+ try {
400
+ parsed = JSON.parse(readFileSync(snapshotFile(profileDir, id), 'utf8'));
401
+ }
402
+ catch {
403
+ return { ok: false, restored: [], error: 'snapshot not found / 快照不存在' };
404
+ }
405
+ const validated = validateSnapshotDocument(parsed);
406
+ if (!validated.ok)
407
+ return { ok: false, restored: [], error: validated.error };
408
+ if (validated.value.snapshot.id !== id) {
409
+ return { ok: false, restored: [], error: 'snapshot id does not match its filename / 快照 id 与文件名不匹配' };
410
+ }
411
+ // Materialize every target + its current content FIRST, so a rollback can
412
+ // restore the pre-restore bytes even if the profile already changed.
413
+ const writes = [];
414
+ for (const file of validated.value.files) {
415
+ const target = join(profileDir, file.path);
416
+ const content = file.absent === true
417
+ ? null
418
+ : file.json !== undefined
419
+ ? `${JSON.stringify(file.json, null, 2)}\n`
420
+ : Array.isArray(file.lines) ? `${file.lines.join('\n')}` : '';
421
+ let previous = null;
422
+ // Rollback records bytes, not filesystem object identity. Replacing a
423
+ // symlink or other non-regular target could not be restored faithfully.
424
+ try {
425
+ ensureSafeRestoreParent(profileDir, dirname(target), file.path);
426
+ if (!lstatSync(target).isFile()) {
427
+ return {
428
+ ok: false,
429
+ restored: [],
430
+ error: `unsafe restore target is not a regular file: ${file.path} / 恢复目标不是常规文件`,
431
+ };
432
+ }
433
+ }
434
+ catch (error) {
435
+ if (!isMissingFileError(error)) {
436
+ return { ok: false, restored: [], error: error instanceof Error ? error.message : String(error) };
437
+ }
438
+ }
439
+ try {
440
+ previous = readFileSync(target, 'utf8');
441
+ }
442
+ catch (error) {
443
+ if (!isMissingFileError(error)) {
444
+ return { ok: false, restored: [], error: error instanceof Error ? error.message : String(error) };
445
+ }
446
+ }
447
+ writes.push({ path: file.path, target, content, previous });
448
+ }
449
+ const completed = [];
450
+ try {
451
+ for (const write of writes) {
452
+ if (write.content === null)
453
+ rmSync(write.target, { force: true });
454
+ else {
455
+ mkdirSync(dirname(write.target), { recursive: true });
456
+ writeFileAtomic(write.target, write.content);
457
+ }
458
+ completed.push(write);
459
+ }
460
+ }
461
+ catch (error) {
462
+ // Roll back completed actions in reverse, including recreating a file that
463
+ // an explicit absence marker deleted before a later action failed.
464
+ let rollbackError = null;
465
+ for (const write of [...completed].reverse()) {
466
+ try {
467
+ if (write.previous !== null) {
468
+ mkdirSync(dirname(write.target), { recursive: true });
469
+ writeFileAtomic(write.target, write.previous);
470
+ }
471
+ else
472
+ rmSync(write.target, { force: true });
473
+ }
474
+ catch (restoreError) {
475
+ rollbackError ??= restoreError;
476
+ }
477
+ }
478
+ const detail = error instanceof Error ? error.message : String(error);
479
+ const rollbackDetail = rollbackError === null
480
+ ? ''
481
+ : `; rollback incomplete: ${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)}`;
482
+ const rollbackStatus = rollbackError === null
483
+ ? `failed and was rolled back: ${detail}`
484
+ : `failed; rollback incomplete (${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)}); original failure: ${detail}`;
485
+ logEvent('error', 'snapshot', `restore ${id} ${rollbackStatus}`);
486
+ return { ok: false, restored: [], error: `${detail}${rollbackDetail}` };
487
+ }
488
+ const restored = writes.map(write => write.path);
489
+ logEvent('info', 'snapshot', `restored ${id}: ${restored.join(', ')}`);
490
+ return { ok: true, restored };
491
+ }
492
+ /** Delete one snapshot; true only when it existed and was removed. */
493
+ export function deleteSnapshot(profileDir, id) {
494
+ if (!validSnapshotId(id))
495
+ return false;
496
+ const file = snapshotFile(profileDir, id);
497
+ if (!existsSync(file))
498
+ return false;
499
+ try {
500
+ rmSync(file);
501
+ return true;
502
+ }
503
+ catch {
504
+ return false;
505
+ }
506
+ }
@@ -0,0 +1,164 @@
1
+ /**
2
+ * Safe discovery for legacy Git -> verified npm source migrations (#461).
3
+ *
4
+ * This intentionally does less than the normal catalog matcher. A migration
5
+ * changes package name/publisher and build provenance, so only repository
6
+ * evidence carried by the installed Git spec may authorize it:
7
+ *
8
+ * - bare github:owner/repo matches only the catalog root for that repo;
9
+ * - #path:/subdir matches only that exact catalog subpath;
10
+ * - branch/tag/commit/semver selectors are not migrated in v1;
11
+ * - more than one matching verified npm entry is ambiguous and fails closed.
12
+ */
13
+ import { NPM_NAME_RE, isGitHostedSpec, isLocalSpec, parseSourceUrl, repoOfTarget } from './sources.js';
14
+ function migratableGitIdentity(spec) {
15
+ if (!spec.startsWith('github:'))
16
+ return null;
17
+ const hash = spec.indexOf('#');
18
+ if (hash !== -1) {
19
+ const selector = spec.slice(hash + 1);
20
+ // A path selector identifies which package inside a monorepo. Any
21
+ // other selector expresses an explicit version/ref choice and is
22
+ // deliberately preserved rather than silently discarded.
23
+ if (!selector.startsWith('path:/') || selector.includes('&'))
24
+ return null;
25
+ }
26
+ return repoOfTarget(spec);
27
+ }
28
+ export function findGitToNpmMigration(plugins, spec) {
29
+ const identity = migratableGitIdentity(spec);
30
+ if (identity === null)
31
+ return null;
32
+ const pathAt = identity.indexOf('#path:/');
33
+ const wantedRepo = pathAt === -1 ? identity : identity.slice(0, pathAt);
34
+ const wantedPath = pathAt === -1 ? null : identity.slice(pathAt + '#path:/'.length);
35
+ const candidates = plugins.flatMap((plugin) => {
36
+ if (typeof plugin.npm !== 'string' || !NPM_NAME_RE.test(plugin.npm))
37
+ return [];
38
+ const source = parseSourceUrl(plugin.url);
39
+ if (source === null || source.repo.toLowerCase() !== wantedRepo)
40
+ return [];
41
+ if (wantedPath === null) {
42
+ // A collection root must not guess which /tree/ child was meant.
43
+ if (source.subpath !== null)
44
+ return [];
45
+ }
46
+ else if (source.subpath?.toLowerCase() !== wantedPath) {
47
+ return [];
48
+ }
49
+ return [plugin.npm];
50
+ });
51
+ if (candidates.length !== 1)
52
+ return null;
53
+ return { kind: 'git-to-npm', repo: identity, target: candidates[0] };
54
+ }
55
+ /**
56
+ * The catalog entry that publishes `to` on npm, or null when no single entry
57
+ * does.
58
+ *
59
+ * The rename target arrives from an update failure's own artifact, but the
60
+ * `migrate-source` body is user-reachable all the same: this keeps the route
61
+ * from pointing a profile at a package name the catalog does not publish on
62
+ * npm. Two entries claiming one npm name is ambiguous and fails closed, the
63
+ * same rule {@link findGitToNpmMigration} follows.
64
+ */
65
+ export function findNpmTargetEntry(plugins, to) {
66
+ // Compare against the install target, not the display name: that is what the
67
+ // route is about to `add`, and it is what the catalog rules (E10/E11) keep
68
+ // unique. A listing whose npm target is another package cannot satisfy a
69
+ // rename to its display name.
70
+ const matches = plugins.filter(plugin => {
71
+ const target = typeof plugin.npm === 'string' ? plugin.npm : plugin.name;
72
+ return NPM_NAME_RE.test(target) && target === to;
73
+ });
74
+ return matches.length === 1 ? matches[0] : null;
75
+ }
76
+ /**
77
+ * The catalog entry that declares `from` as a package it used to be (#1012).
78
+ *
79
+ * This is the discovery the update failure cannot provide: a user whose old
80
+ * version range no longer resolves never installs anything, so no
81
+ * "came back under another name" evidence is produced. The catalog states the
82
+ * rename up front instead — but it is external input, so two entries claiming
83
+ * one former name is ambiguity, and ambiguity fails closed exactly like
84
+ * {@link findGitToNpmMigration}.
85
+ *
86
+ * Only entries that can actually be installed from npm qualify: an entry whose
87
+ * own target is not a valid npm name has no successor this transaction could
88
+ * install.
89
+ */
90
+ export function findCatalogRename(plugins, from) {
91
+ const wanted = from.toLowerCase();
92
+ const candidates = [];
93
+ for (const plugin of plugins) {
94
+ const previous = Array.isArray(plugin.previousNpm) ? plugin.previousNpm : [];
95
+ if (!previous.some(name => typeof name === 'string' && name.toLowerCase() === wanted))
96
+ continue;
97
+ const target = typeof plugin.npm === 'string' && NPM_NAME_RE.test(plugin.npm) ? plugin.npm : null;
98
+ // An entry may never name itself as its own predecessor; the runtime
99
+ // normalizer drops that, and this keeps a hand-built catalog honest too.
100
+ if (target === null || target.toLowerCase() === wanted)
101
+ continue;
102
+ candidates.push({ entry: plugin, target });
103
+ }
104
+ return candidates.length === 1 ? candidates[0] : null;
105
+ }
106
+ /**
107
+ * Installed packages that answer to one of this entry's former names (#1012).
108
+ *
109
+ * A renamed package usually re-registers the very same bundle ids, so two
110
+ * package names that were one plugin cannot coexist in a profile: the trial
111
+ * boot rejects duplicate loader ids while the two sit side by side. That makes
112
+ * "install the new name as well" the one obvious move that bricks the next
113
+ * start, which is why the install route refuses it before pnpm runs.
114
+ *
115
+ * A name on this list is a claim, not proof: the caller still compares the
116
+ * rows both sides declare before it refuses anything, so a stale catalog
117
+ * field can cost a click at worst and never a wrong refusal.
118
+ */
119
+ export function declaredPredecessors(plugin, installed) {
120
+ const previous = Array.isArray(plugin.previousNpm) ? plugin.previousNpm : [];
121
+ const found = [];
122
+ for (const value of previous) {
123
+ if (typeof value !== 'string' || value === '')
124
+ continue;
125
+ const wanted = value.toLowerCase();
126
+ for (const name of Object.keys(installed)) {
127
+ if (name.toLowerCase() === wanted && !found.includes(name))
128
+ found.push(name);
129
+ }
130
+ }
131
+ return found;
132
+ }
133
+ /**
134
+ * True when the two sides still register at least one of the same loader rows.
135
+ *
136
+ * This is the check that keeps a stale catalog from refusing an install it has
137
+ * no business refusing: two packages that insert different rows can coexist in
138
+ * a profile, so a `previousNpm` that points at one of them is a guess, not the
139
+ * plugin coming back. Only readable, non-empty row sets can prove sameness —
140
+ * a missing side proves nothing and the caller falls back to the declaration.
141
+ */
142
+ export function sameLoaderRows(installed, incoming) {
143
+ if (installed.length === 0 || incoming.length === 0)
144
+ return false;
145
+ const present = new Set(installed);
146
+ return incoming.some(id => present.has(id));
147
+ }
148
+ /**
149
+ * True when a dependency spec is a plain registry version range — the only
150
+ * shape the rename transaction can replace.
151
+ *
152
+ * The route refuses anything carrying a protocol, a path prefix or an alias
153
+ * (`github:`, `file:`, `workspace:`, `npm:` …), because those describe a
154
+ * source this transaction cannot reproduce for the new name. Discovery is
155
+ * kept to the exact same test so the market never offers a migration the
156
+ * route would answer with 400.
157
+ */
158
+ export function isRegistryRangeSpec(spec) {
159
+ if (spec === '')
160
+ return false;
161
+ if (isGitHostedSpec(spec) || isLocalSpec(spec))
162
+ return false;
163
+ return !/[:/\\]/.test(spec);
164
+ }