@twinsearth/timemachine-dsh-plugin 0.2.3 → 0.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/restore.mjs CHANGED
@@ -16,14 +16,15 @@ import { readArchive, readRestorePoint } from './point.mjs';
16
16
  import { mergeRegistry, registryDocument, registrySummary } from './registry.mjs';
17
17
  import { inspectSessionBuffer, isV4Header, remapSessionCwd } from './session-log.mjs';
18
18
  import { normalizeRegistry } from './scan.mjs';
19
- import { reinstallPlugins, SELF_PLUGIN } from './plugins.mjs';
19
+ import { filterProfilePatch, reinstallPlugins, sanitizeProfilePackage, SELF_PLUGIN } from './plugins.mjs';
20
20
  import { atomicWriteFile, atomicWriteJson, copyFileDurable, ensureDir, isInside, readJson, safeSegment, sha256, stamp } from './util/fs.mjs';
21
- import { encodeSegment, projectKey, profileDir, resolveDshHome, sessionDir } from './util/paths.mjs';
21
+ import { encodeSegment, missingDriveForPath, projectKey, profileDir, resolveDshHome, sessionDir } from './util/paths.mjs';
22
22
 
23
23
  export const RESTORE_CODES = Object.freeze({
24
24
  SESSION_INVALID: 'TIMEMACHINE_SESSION_INVALID',
25
25
  SESSION_MISSING: 'TIMEMACHINE_SESSION_MISSING',
26
26
  PATH_INVALID: 'TIMEMACHINE_PATH_INVALID',
27
+ PATH_DRIVE_MISSING: 'TIMEMACHINE_PATH_DRIVE_MISSING',
27
28
  VERIFY_FAILED: 'TIMEMACHINE_VERIFY_FAILED',
28
29
  APPLY_FAILED: 'TIMEMACHINE_APPLY_FAILED',
29
30
  PLUGIN_INSTALL_FAILED: 'TIMEMACHINE_PLUGIN_INSTALL_FAILED',
@@ -104,6 +105,7 @@ export function planRestore(input) {
104
105
  const targetDocument = registryDocument(targetRegistryRaw);
105
106
 
106
107
  const warnings = [];
108
+ const pathIssues = [];
107
109
  if (point.source_platform !== undefined && point.source_platform !== process.platform) {
108
110
  warnings.push(`还原点来自 ${point.source_platform},本机是 ${process.platform};工作区路径必须重新映射。`);
109
111
  }
@@ -204,6 +206,18 @@ export function planRestore(input) {
204
206
  const existing = targetDocument.tables.workspaces[targetId];
205
207
  const targetPathExists = fs.existsSync(workspace.target_path);
206
208
  if (!targetPathExists) warnings.push(`工作区目录不存在,将按映射路径创建:${workspace.target_path}`);
209
+ const missingDrive = missingDriveForPath(workspace.target_path);
210
+ if (missingDrive !== null) {
211
+ const message = `本机没有 ${missingDrive} 盘,无法还原工作区“${workspace.source_title}”到 ${workspace.target_path};请修改工作区文件夹。`;
212
+ pathIssues.push({
213
+ code: RESTORE_CODES.PATH_DRIVE_MISSING,
214
+ drive: missingDrive,
215
+ source_path: workspace.source_path,
216
+ target_path: workspace.target_path,
217
+ message,
218
+ });
219
+ warnings.push(message);
220
+ }
207
221
  workspacePlan.push({
208
222
  source_id: workspace.source_id,
209
223
  source_path: workspace.source_path,
@@ -287,7 +301,7 @@ export function planRestore(input) {
287
301
  if (!archive.map.has(rel)) return { ok: false, reason_code: RESTORE_CODES.PLUGIN_PACKAGE_INVALID, detail: `${name}: ${rel} is missing` };
288
302
  }
289
303
  if (includeConfig && !includePlugins && plugins.length === 0 && (point.plugins ?? []).length > 0) {
290
- warnings.push('本还原点包含第三方插件清单,但本次未勾选“安装第三方插件”;配置里仍会写入插件条目,DSH 可能提示插件缺失。');
304
+ warnings.push('本还原点包含第三方插件清单,但本次未勾选“安装第三方插件”;配置中只保留本机已安装的插件条目。');
291
305
  }
292
306
  const overwrites = sessions.filter((session) => session.action === 'overwrite').length;
293
307
  if (overwrites > 0) warnings.push(`${overwrites} 个同名会话已存在,会被本还原点覆盖;覆盖前会写入 .timemachine-backups。`);
@@ -319,6 +333,7 @@ export function planRestore(input) {
319
333
  added_sessions: merged.added_sessions,
320
334
  },
321
335
  workspaces: workspacePlan,
336
+ path_issues: pathIssues,
322
337
  plugins,
323
338
  plugin_packages: pluginPackages,
324
339
  will: {
@@ -376,6 +391,14 @@ function backupExisting(target, rel, backupDir) {
376
391
  */
377
392
  export function applyRestore(plan, options = {}) {
378
393
  if (!plan?.ok) return plan;
394
+ if (Array.isArray(plan.path_issues) && plan.path_issues.length > 0) {
395
+ return {
396
+ ok: false,
397
+ reason_code: RESTORE_CODES.PATH_DRIVE_MISSING,
398
+ detail: plan.path_issues.map((row) => row.message).join(';'),
399
+ path_issues: plan.path_issues,
400
+ };
401
+ }
379
402
  // plan carries absolute targets; resolve the live home from the registry file.
380
403
  const home = path.dirname(path.dirname(plan.registry.target_file));
381
404
  const backupDir = options.backupDir ?? backupDirFor(home);
@@ -659,6 +682,16 @@ export async function registerRestoredWorkspaces(workspaceRegistry, plan) {
659
682
  export async function restorePoint(input) {
660
683
  const plan = planRestore(input);
661
684
  if (!plan.ok) return plan;
685
+ if (Array.isArray(plan.path_issues) && plan.path_issues.length > 0) {
686
+ return {
687
+ ok: false,
688
+ reason_code: RESTORE_CODES.PATH_DRIVE_MISSING,
689
+ detail: plan.path_issues.map((row) => row.message).join(';'),
690
+ stage: 'preflight',
691
+ path_issues: plan.path_issues,
692
+ plan_ready: true,
693
+ };
694
+ }
662
695
  const dshHome = dshHomeForPlan(plan);
663
696
  const profile = typeof input.profile === 'string' && input.profile !== '' ? input.profile : plan.point.profile;
664
697
  const profilePath = profileDir(dshHome, profile);
@@ -688,6 +721,9 @@ export async function restorePoint(input) {
688
721
  packages,
689
722
  runner: input.runner,
690
723
  pnpmFile: input.pnpmFile,
724
+ dshVersion: input.dshVersion,
725
+ manifests: input.manifests,
726
+ checkCompatibility: input.checkCompatibility,
691
727
  onProgress: input.onProgress,
692
728
  });
693
729
  } catch (error) {
@@ -724,30 +760,63 @@ export async function restorePoint(input) {
724
760
  };
725
761
  }
726
762
 
727
- // pnpm writes the installed versions into package.json. Re-apply the
728
- // archived package metadata, but keep the versions that were just installed.
729
- const archived = plan.config_buffers?.find((row) => row.target_rel === `profiles/${profile}/package.json`);
730
- if (archived !== undefined) {
731
- try {
732
- const current = JSON.parse(fs.readFileSync(packageFile, 'utf8'));
733
- const next = JSON.parse(archived.buffer.toString('utf8'));
734
- next.dependencies = isObject(next.dependencies) ? next.dependencies : {};
735
- if (isObject(current.dependencies)) {
736
- for (const row of install.installed ?? []) {
737
- if (typeof current.dependencies[row.name] === 'string') next.dependencies[row.name] = current.dependencies[row.name];
763
+ }
764
+
765
+ // The archive may come from a machine with a larger plugin set. Never write
766
+ // a package.json / cordis.patch.yml entry that the target profile cannot
767
+ // resolve: DSH refuses the whole profile at boot and the plugin manager
768
+ // becomes unusable. This runs even when the user chose "config only"
769
+ // (installPlugins=false), which previously copied the archived dependency
770
+ // list without installing any of it.
771
+ const profileWarnings = [];
772
+ const archivedPackage = plan.config_buffers?.find((row) => row.target_rel === `profiles/${profile}/package.json`);
773
+ if (archivedPackage !== undefined) {
774
+ try {
775
+ const currentPackage = JSON.parse(fs.readFileSync(path.join(profilePath, 'package.json'), 'utf8'));
776
+ const installedNames = Array.isArray(install?.installed) ? install.installed.map((row) => row.name) : [];
777
+ const sanitized = sanitizeProfilePackage({
778
+ profileDir: profilePath,
779
+ pkg: JSON.parse(archivedPackage.buffer.toString('utf8')),
780
+ installed: installedNames,
781
+ });
782
+ if (currentPackage?.dependencies !== null && typeof currentPackage?.dependencies === 'object') {
783
+ for (const name of Object.keys(sanitized.pkg.dependencies ?? {})) {
784
+ if (typeof currentPackage.dependencies[name] === 'string') {
785
+ sanitized.pkg.dependencies[name] = currentPackage.dependencies[name];
738
786
  }
739
787
  }
740
- plan.configOverrides = { [`profiles/${profile}/package.json`]: Buffer.from(`${JSON.stringify(next, null, 2)}\n`, 'utf8') };
741
- } catch { /* keep the archived package.json */ }
742
- }
788
+ }
789
+ plan.configOverrides = plan.configOverrides ?? {};
790
+ plan.configOverrides[`profiles/${profile}/package.json`] = Buffer.from(`${JSON.stringify(sanitized.pkg, null, 2)}\n`, 'utf8');
791
+ const dropped = [...new Set([...sanitized.dropped_bundles, ...sanitized.dropped_dependencies])];
792
+ if (dropped.length > 0) {
793
+ profileWarnings.push(`以下第三方插件未安装,已从还原后的 package.json 移除:${dropped.join('、')}。`);
794
+ }
795
+ } catch { /* keep the archived package.json if it cannot be sanitized */ }
796
+ }
797
+
798
+ const archivedPatch = plan.config_buffers?.find((row) => row.target_rel === `profiles/${profile}/cordis.patch.yml`);
799
+ if (archivedPatch !== undefined) {
800
+ try {
801
+ const original = archivedPatch.buffer.toString('utf8');
802
+ const filtered = filterProfilePatch({ profileDir: profilePath, text: original });
803
+ if (filtered.text !== original) {
804
+ plan.configOverrides = plan.configOverrides ?? {};
805
+ plan.configOverrides[`profiles/${profile}/cordis.patch.yml`] = Buffer.from(filtered.text, 'utf8');
806
+ }
807
+ if (filtered.dropped.length > 0) {
808
+ profileWarnings.push(`以下插件未安装,已从还原后的 cordis.patch.yml 移除配置:${[...new Set(filtered.dropped)].join('、')}。`);
809
+ }
810
+ } catch { /* keep the archived patch if it cannot be filtered */ }
743
811
  }
812
+ const restoreWarnings = [...(Array.isArray(install?.warnings) ? install.warnings : []), ...profileWarnings];
744
813
  const liveRegistry = input.workspaceRegistry ?? null;
745
814
  const applied = applyRestore(plan, {
746
815
  configOverrides: plan.configOverrides,
747
816
  backupDir,
748
817
  skipRegistry: liveRegistry !== null,
749
818
  });
750
- if (!applied.ok) return { ...applied, stage: 'file-restore', plugins: install };
819
+ if (!applied.ok) return { ...applied, stage: 'file-restore', plugins: install, plugin_warnings: restoreWarnings };
751
820
 
752
821
  let live = null;
753
822
  if (liveRegistry !== null) {
@@ -759,6 +828,7 @@ export async function restorePoint(input) {
759
828
  point: plan.point,
760
829
  stage: 'restored',
761
830
  plugins: install,
831
+ plugin_warnings: restoreWarnings,
762
832
  restore: applied,
763
833
  workspaces: live?.workspaces ?? applied.workspaces,
764
834
  display: live?.display ?? null,
@@ -1,3 +1,4 @@
1
+ import fs from 'node:fs';
1
2
  import os from 'node:os';
2
3
  import path from 'node:path';
3
4
 
@@ -72,7 +73,28 @@ export function platformLabel(platform = process.platform) {
72
73
 
73
74
  /** True when a path is a Windows drive path (imported from a Windows machine). */
74
75
  export function isWindowsPath(value) {
75
- return typeof value === 'string' && (/^[A-Za-z]:[\\/]/u.test(value) || value.startsWith('\\\\'));
76
+ return typeof value === 'string' && (/^[A-Za-z]:[\\/]/u.test(value) || value.startsWith('\\\\') || value.startsWith('//'));
77
+ }
78
+
79
+ /**
80
+ * Return `D:` when a Windows path points at a drive that is not mounted on
81
+ * this machine. Non-Windows platforms and relative paths never report a
82
+ * missing drive. The injectable `exists`/`platform` pair keeps this testable
83
+ * on every CI runner.
84
+ */
85
+ export function missingDriveForPath(value, options = {}) {
86
+ if (typeof value !== 'string') return null;
87
+ const platform = options.platform ?? process.platform;
88
+ if (platform !== 'win32') return null;
89
+ const match = /^([A-Za-z]):(?:[\\/]|$)/u.exec(value.trim());
90
+ if (match === null) return null;
91
+ const drive = `${match[1].toUpperCase()}:`;
92
+ const exists = options.exists ?? fs.existsSync;
93
+ try {
94
+ return exists(`${drive}\\`) ? null : drive;
95
+ } catch {
96
+ return drive;
97
+ }
76
98
  }
77
99
 
78
100
  /** Normalize a user-entered path for comparisons; case-insensitive on Windows. */
package/src/version.mjs CHANGED
@@ -1,2 +1,2 @@
1
1
  /** Single source for the version shown in the panel header and health routes. */
2
- export const PLUGIN_VERSION = '0.2.3';
2
+ export const PLUGIN_VERSION = '0.2.6';