zen-fs-config 0.10.2 → 0.10.4

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/dist/index.d.mts CHANGED
@@ -1014,8 +1014,13 @@ interface IConfigRepo {
1014
1014
  * replaceBackend: old pair is rebuilt against the new target).
1015
1015
  */
1016
1016
  replaceAppDataGroupBackend(groupId: string, backendId: string, type: string, options: Record<string, unknown>, description?: string): Promise<AppDataGroup>;
1017
- /** Remove a data-sync group (stops sync, removes descriptor). */
1018
- removeAppDataGroup(id: string): Promise<void>;
1017
+ /**
1018
+ * Remove a data-sync group (stops sync, removes descriptor).
1019
+ *
1020
+ * @param appId 目标登记所属 appId;默认本实例的 appId。传其它 appId 时只删
1021
+ * 配置仓里该 appId 的登记与引导副本(写墓碑),不会 dispose 别的实例里的组。
1022
+ */
1023
+ removeAppDataGroup(id: string, appId?: string): Promise<void>;
1019
1024
  /**
1020
1025
  * List config-sync backends that can be used as account sources
1021
1026
  * for data-sync backends. Returns backends that have `accountFields`
@@ -1353,6 +1358,12 @@ declare class ConfigRepo implements IConfigRepo {
1353
1358
  * unlink() 是否成功来判定。
1354
1359
  */
1355
1360
  private readonly tombstoneConfirmations;
1361
+ /**
1362
+ * 上次从副本预取墓碑的时间戳(毫秒)。
1363
+ * 节流用:preSyncHook 每轮都会调用 {@link prefetchReplicaTombstones},
1364
+ * 但远端墓碑不会秒级变化,一分钟一次足够。
1365
+ */
1366
+ private lastTombstonePrefetchAt;
1356
1367
  /** Per-backend sync state (successful pairs + connect failures). */
1357
1368
  private backendStates;
1358
1369
  /**
@@ -1387,6 +1398,12 @@ declare class ConfigRepo implements IConfigRepo {
1387
1398
  * 见 `healEmptyBootstrapDescriptors()`。
1388
1399
  */
1389
1400
  private explicitEmptyDescriptors;
1401
+ /**
1402
+ * 描述符文件路径 → 已确认在远端不存在。目录清单按 ETag 复用,删除不会
1403
+ * 改变 ETag,所以清单会长期保留已删除的文件名;这里记住 404 结果,
1404
+ * 避免每次 `listAppDataGroups()` 都为同一批死文件再发一次 GET。
1405
+ */
1406
+ private missingDescriptorFiles;
1390
1407
  /**
1391
1408
  * Tracks the background initial sync started by createConfigRepo().
1392
1409
  * `flush()` and `dispose()` will await this if it hasn't completed yet,
@@ -1442,6 +1459,21 @@ declare class ConfigRepo implements IConfigRepo {
1442
1459
  private refreshSyncExclusions;
1443
1460
  /** Invalidate the tombstone cache — call after tombstones are modified. */
1444
1461
  private invalidateTombstoneCache;
1462
+ /**
1463
+ * 把各副本上的墓碑合并进本地,必须早于本轮的快照比对。
1464
+ *
1465
+ * 为什么需要它:墓碑文件本身也是被同步的文件,一个节点在「拿到墓碑」之前
1466
+ * 就已经跑完了 preSyncHook —— 这时它本地没有该路径的墓碑,同步就会把自己
1467
+ * 那份陈旧副本当成「本地新增」推回远端(BiDirectional + source-wins),
1468
+ * 删除被复活。只靠墓碑文件被同步拉下来,永远慢半拍。
1469
+ *
1470
+ * 所以在每轮同步之前先只读地把副本上的 `.meta/tombstones/` 合并到本地:
1471
+ * 合并完成后排除表立刻生效,随后的 processTombstones() 会把本地陈旧副本
1472
+ * 一并清掉,同步再不会把它推上去。
1473
+ *
1474
+ * @param minIntervalMs 节流间隔(0 = 立即执行)。preSyncHook 传 60s。
1475
+ */
1476
+ private prefetchReplicaTombstones;
1445
1477
  /**
1446
1478
  * 写入成功即撤销该路径(及其被删祖先目录)上的墓碑。
1447
1479
  *
@@ -1944,7 +1976,15 @@ declare class ConfigRepo implements IConfigRepo {
1944
1976
  * 真实意图,允许推送空副本,不参与自愈。
1945
1977
  */
1946
1978
  private healEmptyBootstrapDescriptors;
1947
- removeAppDataGroup(id: string): Promise<void>;
1979
+ /**
1980
+ * 删除一个数据组的登记(`.config/app-data-groups/{appId}/{id}.json` + 该组
1981
+ * 在配置仓的后端描述符)。
1982
+ *
1983
+ * @param appId 目标登记所属的 appId,默认为本实例的 appId。传其它 appId 时
1984
+ * 只删配置仓里那份登记与引导副本,不会(也无法)去 dispose 另一个
1985
+ * appId 实例里的组句柄 —— 调用方应优先走实例注册表,让实例自己刷新。
1986
+ */
1987
+ removeAppDataGroup(id: string, appId?: string): Promise<void>;
1948
1988
  listAccountBackends(): Promise<BackendDescriptor[]>;
1949
1989
  private tryParse;
1950
1990
  private assertNotDisposed;
package/dist/index.d.ts CHANGED
@@ -1014,8 +1014,13 @@ interface IConfigRepo {
1014
1014
  * replaceBackend: old pair is rebuilt against the new target).
1015
1015
  */
1016
1016
  replaceAppDataGroupBackend(groupId: string, backendId: string, type: string, options: Record<string, unknown>, description?: string): Promise<AppDataGroup>;
1017
- /** Remove a data-sync group (stops sync, removes descriptor). */
1018
- removeAppDataGroup(id: string): Promise<void>;
1017
+ /**
1018
+ * Remove a data-sync group (stops sync, removes descriptor).
1019
+ *
1020
+ * @param appId 目标登记所属 appId;默认本实例的 appId。传其它 appId 时只删
1021
+ * 配置仓里该 appId 的登记与引导副本(写墓碑),不会 dispose 别的实例里的组。
1022
+ */
1023
+ removeAppDataGroup(id: string, appId?: string): Promise<void>;
1019
1024
  /**
1020
1025
  * List config-sync backends that can be used as account sources
1021
1026
  * for data-sync backends. Returns backends that have `accountFields`
@@ -1353,6 +1358,12 @@ declare class ConfigRepo implements IConfigRepo {
1353
1358
  * unlink() 是否成功来判定。
1354
1359
  */
1355
1360
  private readonly tombstoneConfirmations;
1361
+ /**
1362
+ * 上次从副本预取墓碑的时间戳(毫秒)。
1363
+ * 节流用:preSyncHook 每轮都会调用 {@link prefetchReplicaTombstones},
1364
+ * 但远端墓碑不会秒级变化,一分钟一次足够。
1365
+ */
1366
+ private lastTombstonePrefetchAt;
1356
1367
  /** Per-backend sync state (successful pairs + connect failures). */
1357
1368
  private backendStates;
1358
1369
  /**
@@ -1387,6 +1398,12 @@ declare class ConfigRepo implements IConfigRepo {
1387
1398
  * 见 `healEmptyBootstrapDescriptors()`。
1388
1399
  */
1389
1400
  private explicitEmptyDescriptors;
1401
+ /**
1402
+ * 描述符文件路径 → 已确认在远端不存在。目录清单按 ETag 复用,删除不会
1403
+ * 改变 ETag,所以清单会长期保留已删除的文件名;这里记住 404 结果,
1404
+ * 避免每次 `listAppDataGroups()` 都为同一批死文件再发一次 GET。
1405
+ */
1406
+ private missingDescriptorFiles;
1390
1407
  /**
1391
1408
  * Tracks the background initial sync started by createConfigRepo().
1392
1409
  * `flush()` and `dispose()` will await this if it hasn't completed yet,
@@ -1442,6 +1459,21 @@ declare class ConfigRepo implements IConfigRepo {
1442
1459
  private refreshSyncExclusions;
1443
1460
  /** Invalidate the tombstone cache — call after tombstones are modified. */
1444
1461
  private invalidateTombstoneCache;
1462
+ /**
1463
+ * 把各副本上的墓碑合并进本地,必须早于本轮的快照比对。
1464
+ *
1465
+ * 为什么需要它:墓碑文件本身也是被同步的文件,一个节点在「拿到墓碑」之前
1466
+ * 就已经跑完了 preSyncHook —— 这时它本地没有该路径的墓碑,同步就会把自己
1467
+ * 那份陈旧副本当成「本地新增」推回远端(BiDirectional + source-wins),
1468
+ * 删除被复活。只靠墓碑文件被同步拉下来,永远慢半拍。
1469
+ *
1470
+ * 所以在每轮同步之前先只读地把副本上的 `.meta/tombstones/` 合并到本地:
1471
+ * 合并完成后排除表立刻生效,随后的 processTombstones() 会把本地陈旧副本
1472
+ * 一并清掉,同步再不会把它推上去。
1473
+ *
1474
+ * @param minIntervalMs 节流间隔(0 = 立即执行)。preSyncHook 传 60s。
1475
+ */
1476
+ private prefetchReplicaTombstones;
1445
1477
  /**
1446
1478
  * 写入成功即撤销该路径(及其被删祖先目录)上的墓碑。
1447
1479
  *
@@ -1944,7 +1976,15 @@ declare class ConfigRepo implements IConfigRepo {
1944
1976
  * 真实意图,允许推送空副本,不参与自愈。
1945
1977
  */
1946
1978
  private healEmptyBootstrapDescriptors;
1947
- removeAppDataGroup(id: string): Promise<void>;
1979
+ /**
1980
+ * 删除一个数据组的登记(`.config/app-data-groups/{appId}/{id}.json` + 该组
1981
+ * 在配置仓的后端描述符)。
1982
+ *
1983
+ * @param appId 目标登记所属的 appId,默认为本实例的 appId。传其它 appId 时
1984
+ * 只删配置仓里那份登记与引导副本,不会(也无法)去 dispose 另一个
1985
+ * appId 实例里的组句柄 —— 调用方应优先走实例注册表,让实例自己刷新。
1986
+ */
1987
+ removeAppDataGroup(id: string, appId?: string): Promise<void>;
1948
1988
  listAccountBackends(): Promise<BackendDescriptor[]>;
1949
1989
  private tryParse;
1950
1990
  private assertNotDisposed;
package/dist/index.js CHANGED
@@ -1789,7 +1789,7 @@ var META_BACKENDS_DIR = `${META_DIR}/backends`;
1789
1789
  var TOMBSTONES_DIR = `${META_DIR}/tombstones`;
1790
1790
  var ALIASES_DIR = `${META_DIR}/aliases`;
1791
1791
  var RECREATE_AFTER_DELETE_SKEW_MS = 3e3;
1792
- var TOMBSTONE_RETENTION_MS = 24 * 60 * 60 * 1e3;
1792
+ var TOMBSTONE_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3;
1793
1793
  var TOMBSTONE_PLACEHOLDER_RETENTION_MS = 10 * 60 * 1e3;
1794
1794
  function tombstoneRetentionMs(tombstonePath) {
1795
1795
  if (tombstonePath.endsWith(".mtime") || tombstonePath === "/.keep" || tombstonePath.endsWith("/.keep")) {
@@ -3286,6 +3286,7 @@ function normalizeGroupName(value) {
3286
3286
  var CONFIG_ONLY_PREFIXES = [CONFIG_DIR, NODES_DIR, SHARED_DIR];
3287
3287
  var LOCAL_IDB_BACKEND_ID = "local-idb";
3288
3288
  var TOMBSTONE_RECREATE_SKEW_MS = 3e3;
3289
+ var TOMBSTONE_PREFETCH_INTERVAL_MS = 60 * 1e3;
3289
3290
  function tombstoneFileName(filePath) {
3290
3291
  return `${encodeMetaPath(filePath)}.json`;
3291
3292
  }
@@ -3431,6 +3432,12 @@ var ConfigRepo = class _ConfigRepo {
3431
3432
  * unlink() 是否成功来判定。
3432
3433
  */
3433
3434
  tombstoneConfirmations = /* @__PURE__ */ new Map();
3435
+ /**
3436
+ * 上次从副本预取墓碑的时间戳(毫秒)。
3437
+ * 节流用:preSyncHook 每轮都会调用 {@link prefetchReplicaTombstones},
3438
+ * 但远端墓碑不会秒级变化,一分钟一次足够。
3439
+ */
3440
+ lastTombstonePrefetchAt = 0;
3434
3441
  /** Per-backend sync state (successful pairs + connect failures). */
3435
3442
  backendStates = /* @__PURE__ */ new Map();
3436
3443
  /**
@@ -3465,6 +3472,12 @@ var ConfigRepo = class _ConfigRepo {
3465
3472
  * 见 `healEmptyBootstrapDescriptors()`。
3466
3473
  */
3467
3474
  explicitEmptyDescriptors = /* @__PURE__ */ new Set();
3475
+ /**
3476
+ * 描述符文件路径 → 已确认在远端不存在。目录清单按 ETag 复用,删除不会
3477
+ * 改变 ETag,所以清单会长期保留已删除的文件名;这里记住 404 结果,
3478
+ * 避免每次 `listAppDataGroups()` 都为同一批死文件再发一次 GET。
3479
+ */
3480
+ missingDescriptorFiles = /* @__PURE__ */ new Set();
3468
3481
  /**
3469
3482
  * Tracks the background initial sync started by createConfigRepo().
3470
3483
  * `flush()` and `dispose()` will await this if it hasn't completed yet,
@@ -3645,6 +3658,11 @@ var ConfigRepo = class _ConfigRepo {
3645
3658
  await this.initialSyncPromise;
3646
3659
  this.initialSyncPromise = null;
3647
3660
  }
3661
+ try {
3662
+ await this.prefetchReplicaTombstones();
3663
+ } catch (err) {
3664
+ log5.warn("[ConfigRepo] flush tombstone prefetch failed:", err);
3665
+ }
3648
3666
  await this.processTombstones();
3649
3667
  await this.healEmptyBootstrapDescriptors();
3650
3668
  const resultsMap = await this.syncEngine.syncAll();
@@ -3771,6 +3789,89 @@ var ConfigRepo = class _ConfigRepo {
3771
3789
  invalidateTombstoneCache() {
3772
3790
  this.tombstoneCache = null;
3773
3791
  }
3792
+ /**
3793
+ * 把各副本上的墓碑合并进本地,必须早于本轮的快照比对。
3794
+ *
3795
+ * 为什么需要它:墓碑文件本身也是被同步的文件,一个节点在「拿到墓碑」之前
3796
+ * 就已经跑完了 preSyncHook —— 这时它本地没有该路径的墓碑,同步就会把自己
3797
+ * 那份陈旧副本当成「本地新增」推回远端(BiDirectional + source-wins),
3798
+ * 删除被复活。只靠墓碑文件被同步拉下来,永远慢半拍。
3799
+ *
3800
+ * 所以在每轮同步之前先只读地把副本上的 `.meta/tombstones/` 合并到本地:
3801
+ * 合并完成后排除表立刻生效,随后的 processTombstones() 会把本地陈旧副本
3802
+ * 一并清掉,同步再不会把它推上去。
3803
+ *
3804
+ * @param minIntervalMs 节流间隔(0 = 立即执行)。preSyncHook 传 60s。
3805
+ */
3806
+ async prefetchReplicaTombstones(minIntervalMs = 0) {
3807
+ if (this.disposed || this.replicaBackends.size === 0) return;
3808
+ const now = Date.now();
3809
+ if (minIntervalMs > 0 && now - this.lastTombstonePrefetchAt < minIntervalMs) return;
3810
+ this.lastTombstonePrefetchAt = now;
3811
+ let local;
3812
+ try {
3813
+ local = await this.readTombstones();
3814
+ } catch {
3815
+ return;
3816
+ }
3817
+ const byPath = new Map(local.map((t) => [t.path, t]));
3818
+ let changed = false;
3819
+ for (const [replicaId, replica] of this.replicaBackends) {
3820
+ let remote;
3821
+ try {
3822
+ remote = await readTombstonesFromFs(replica.instance, (message) => log5.warn(`[ConfigRepo] prefetch tombstones (${replicaId}): ${message}`));
3823
+ } catch (err) {
3824
+ log5.warn(`[ConfigRepo] prefetch tombstones from ${replicaId} failed:`, err);
3825
+ continue;
3826
+ }
3827
+ for (const tombstone of remote) {
3828
+ if (!tombstone.path) continue;
3829
+ const tombstonePath = tombstonePathFor(tombstone.path, TOMBSTONES_DIR);
3830
+ const prev = byPath.get(tombstone.path);
3831
+ if (!prev) {
3832
+ byPath.set(tombstone.path, tombstone);
3833
+ try {
3834
+ await this.ensureDir(tombstonePath);
3835
+ await writeFileOverwrite(
3836
+ this.cachedFS,
3837
+ tombstonePath,
3838
+ new TextEncoder().encode(serializeTombstone(tombstone))
3839
+ );
3840
+ changed = true;
3841
+ } catch (err) {
3842
+ log5.warn(`[ConfigRepo] prefetch tombstone write failed for ${tombstone.path}:`, err);
3843
+ }
3844
+ continue;
3845
+ }
3846
+ const merged = {
3847
+ ...prev,
3848
+ deletedAt: Math.min(prev.deletedAt, tombstone.deletedAt),
3849
+ confirmedBy: Array.from(/* @__PURE__ */ new Set([...prev.confirmedBy, ...tombstone.confirmedBy]))
3850
+ };
3851
+ if (isDirectoryTombstone(tombstone) && !isDirectoryTombstone(prev)) {
3852
+ merged.type = "directory";
3853
+ }
3854
+ const dirty = merged.deletedAt !== prev.deletedAt || merged.confirmedBy.length !== prev.confirmedBy.length || merged.type === "directory" && prev.type !== "directory";
3855
+ if (!dirty) continue;
3856
+ byPath.set(tombstone.path, merged);
3857
+ try {
3858
+ await writeFileOverwrite(
3859
+ this.cachedFS,
3860
+ tombstonePath,
3861
+ new TextEncoder().encode(serializeTombstone(merged))
3862
+ );
3863
+ changed = true;
3864
+ } catch (err) {
3865
+ log5.warn(`[ConfigRepo] prefetch tombstone merge failed for ${tombstone.path}:`, err);
3866
+ }
3867
+ }
3868
+ }
3869
+ if (changed) {
3870
+ this.invalidateTombstoneCache();
3871
+ await this.readTombstones();
3872
+ log5.log("[ConfigRepo] prefetchReplicaTombstones: merged remote tombstones");
3873
+ }
3874
+ }
3774
3875
  /**
3775
3876
  * 写入成功即撤销该路径(及其被删祖先目录)上的墓碑。
3776
3877
  *
@@ -4198,6 +4299,12 @@ var ConfigRepo = class _ConfigRepo {
4198
4299
  async initialSyncAndDedup() {
4199
4300
  this.syncEngine.unwatchAll();
4200
4301
  await this.healEmptyBootstrapDescriptors();
4302
+ try {
4303
+ await this.prefetchReplicaTombstones();
4304
+ await this.processTombstones();
4305
+ } catch (err) {
4306
+ log5.warn("[ConfigRepo] initial tombstone prefetch failed:", err);
4307
+ }
4201
4308
  await this.syncEngine.syncAll();
4202
4309
  await this.readAllBackendDescriptors();
4203
4310
  await this.processTombstones();
@@ -4691,6 +4798,8 @@ var ConfigRepo = class _ConfigRepo {
4691
4798
  filter: this.syncFilter,
4692
4799
  preSyncHook: async () => {
4693
4800
  try {
4801
+ this.invalidateTombstoneCache();
4802
+ await this.prefetchReplicaTombstones(TOMBSTONE_PREFETCH_INTERVAL_MS);
4694
4803
  this.invalidateTombstoneCache();
4695
4804
  await this.processTombstones();
4696
4805
  } catch (err) {
@@ -5236,6 +5345,8 @@ var ConfigRepo = class _ConfigRepo {
5236
5345
  filter: this.syncFilter,
5237
5346
  preSyncHook: async () => {
5238
5347
  try {
5348
+ this.invalidateTombstoneCache();
5349
+ await this.prefetchReplicaTombstones(TOMBSTONE_PREFETCH_INTERVAL_MS);
5239
5350
  this.invalidateTombstoneCache();
5240
5351
  await this.processTombstones();
5241
5352
  } catch (err) {
@@ -5811,12 +5922,12 @@ var ConfigRepo = class _ConfigRepo {
5811
5922
  // IConfigRepo — App Data Groups (data-sync groups)
5812
5923
  // -----------------------------------------------------------------------
5813
5924
  /** Path for a single app data group descriptor: .config/app-data-groups/{appId}/{id}.json */
5814
- appDataGroupFilePath(id) {
5815
- return `${APP_DATA_GROUPS_DIR}/${this.appId}/${id}.json`;
5925
+ appDataGroupFilePath(id, appId = this.appId) {
5926
+ return `${APP_DATA_GROUPS_DIR}/${appId}/${id}.json`;
5816
5927
  }
5817
5928
  /** Legacy descriptor path: .meta/app-data-groups/{appId}/{id}.json */
5818
- legacyAppDataGroupFilePath(id) {
5819
- return `${LEGACY_APP_DATA_GROUPS_DIR}/${this.appId}/${id}.json`;
5929
+ legacyAppDataGroupFilePath(id, appId = this.appId) {
5930
+ return `${LEGACY_APP_DATA_GROUPS_DIR}/${appId}/${id}.json`;
5820
5931
  }
5821
5932
  /**
5822
5933
  * Write a data-group descriptor to `.config/app-data-groups/` (registration
@@ -5848,15 +5959,15 @@ var ConfigRepo = class _ConfigRepo {
5848
5959
  * 归属靠文件内的 `groupId` 字段区分:同一 app 下不同组即使后端 id 相同,
5849
5960
  * 也各用各自的文件,不会在同步时互相覆盖(同一组不同端点同理)。
5850
5961
  */
5851
- appDataBackendsDirPath() {
5852
- return `${APP_DATA_GROUPS_DIR}/${this.appId}/backends`;
5962
+ appDataBackendsDirPath(appId = this.appId) {
5963
+ return `${APP_DATA_GROUPS_DIR}/${appId}/backends`;
5853
5964
  }
5854
- appDataBackendFilePath(backendId) {
5855
- return `${this.appDataBackendsDirPath()}/${backendId}.json`;
5965
+ appDataBackendFilePath(backendId, appId = this.appId) {
5966
+ return `${this.appDataBackendsDirPath(appId)}/${backendId}.json`;
5856
5967
  }
5857
5968
  /** 读本 app 目录下所有后端文件(忽略损坏/非本格式的文件)。 */
5858
- async readAppDataBackendFiles() {
5859
- const dir = this.appDataBackendsDirPath();
5969
+ async readAppDataBackendFiles(appId = this.appId) {
5970
+ const dir = this.appDataBackendsDirPath(appId);
5860
5971
  let entries;
5861
5972
  try {
5862
5973
  entries = await this.cachedFS.readdir(dir);
@@ -5878,9 +5989,9 @@ var ConfigRepo = class _ConfigRepo {
5878
5989
  return out;
5879
5990
  }
5880
5991
  /** 读某个数据组声明的全部后端文件(按 id 去重,先到先得)。 */
5881
- async readAppDataBackendFilesForGroup(groupId) {
5992
+ async readAppDataBackendFilesForGroup(groupId, appId = this.appId) {
5882
5993
  const byId = /* @__PURE__ */ new Map();
5883
- for (const file of await this.readAppDataBackendFiles()) {
5994
+ for (const file of await this.readAppDataBackendFiles(appId)) {
5884
5995
  if (file.groupId !== groupId) continue;
5885
5996
  if (byId.has(file.id)) continue;
5886
5997
  const { groupId: _groupId, ...desc } = file;
@@ -6411,15 +6522,21 @@ var ConfigRepo = class _ConfigRepo {
6411
6522
  }
6412
6523
  for (const entry of entries) {
6413
6524
  if (!entry.endsWith(".json")) continue;
6525
+ const filePath = `${dir}/${entry}`;
6526
+ if (this.missingDescriptorFiles.has(filePath)) continue;
6414
6527
  try {
6415
- const raw = await this.cachedFS.readFile(`${dir}/${entry}`);
6528
+ const raw = await this.cachedFS.readFile(filePath);
6416
6529
  const desc = JSON.parse(new TextDecoder().decode(toUint8Array2(raw)));
6417
6530
  if (desc.id && desc.groupType === "data-sync" && !byId.has(desc.id)) {
6418
6531
  const descriptor = desc;
6419
6532
  descriptor.backends = await this.resolveAppDataGroupBackends(desc.id, descriptor);
6420
6533
  byId.set(desc.id, descriptor);
6421
6534
  }
6422
- } catch {
6535
+ } catch (err) {
6536
+ const code = err?.code;
6537
+ if (code === "ENOENT" || err instanceof Error && /not\s*found/i.test(err.message)) {
6538
+ this.missingDescriptorFiles.add(filePath);
6539
+ }
6423
6540
  }
6424
6541
  }
6425
6542
  }
@@ -6499,15 +6616,25 @@ var ConfigRepo = class _ConfigRepo {
6499
6616
  }
6500
6617
  }
6501
6618
  }
6502
- async removeAppDataGroup(id) {
6619
+ /**
6620
+ * 删除一个数据组的登记(`.config/app-data-groups/{appId}/{id}.json` + 该组
6621
+ * 在配置仓的后端描述符)。
6622
+ *
6623
+ * @param appId 目标登记所属的 appId,默认为本实例的 appId。传其它 appId 时
6624
+ * 只删配置仓里那份登记与引导副本,不会(也无法)去 dispose 另一个
6625
+ * appId 实例里的组句柄 —— 调用方应优先走实例注册表,让实例自己刷新。
6626
+ */
6627
+ async removeAppDataGroup(id, appId = this.appId) {
6503
6628
  this.assertNotDisposed();
6504
- const group = this.appDataGroups.get(id);
6505
- if (group) {
6506
- await group.dispose();
6507
- this.appDataGroups.delete(id);
6629
+ if (appId === this.appId) {
6630
+ const group = this.appDataGroups.get(id);
6631
+ if (group) {
6632
+ await group.dispose();
6633
+ this.appDataGroups.delete(id);
6634
+ }
6508
6635
  }
6509
- for (const backend of await this.readAppDataBackendFilesForGroup(id)) {
6510
- const backendPath = this.appDataBackendFilePath(backend.id);
6636
+ for (const backend of await this.readAppDataBackendFilesForGroup(id, appId)) {
6637
+ const backendPath = this.appDataBackendFilePath(backend.id, appId);
6511
6638
  try {
6512
6639
  await this.deleteFile(backendPath);
6513
6640
  } catch (err) {
@@ -6519,7 +6646,7 @@ var ConfigRepo = class _ConfigRepo {
6519
6646
  await this.unlinkVersionSidecar(this.cachedFS, backendPath);
6520
6647
  }
6521
6648
  }
6522
- for (const descPath of [this.appDataGroupFilePath(id), this.legacyAppDataGroupFilePath(id)]) {
6649
+ for (const descPath of [this.appDataGroupFilePath(id, appId), this.legacyAppDataGroupFilePath(id, appId)]) {
6523
6650
  try {
6524
6651
  await this.deleteFile(descPath);
6525
6652
  } catch (err) {
@@ -6531,7 +6658,7 @@ var ConfigRepo = class _ConfigRepo {
6531
6658
  await this.unlinkVersionSidecar(this.cachedFS, descPath);
6532
6659
  }
6533
6660
  }
6534
- log5.log(`[ConfigRepo] removeAppDataGroup: "${id}" removed`);
6661
+ log5.log(`[ConfigRepo] removeAppDataGroup: "${appId}/${id}" removed`);
6535
6662
  }
6536
6663
  async listAccountBackends() {
6537
6664
  this.assertNotDisposed();
@@ -6593,6 +6720,8 @@ var AppDataGroupImpl = class _AppDataGroupImpl {
6593
6720
  static PERMANENT_SYNC_EXCLUSIONS = [...CONFIG_ONLY_PREFIXES, GROUP_DESCRIPTOR_FILE3];
6594
6721
  tombstoneExcludePrefixes = [..._AppDataGroupImpl.PERMANENT_SYNC_EXCLUSIONS];
6595
6722
  syncFilter = { excludePrefixes: this.tombstoneExcludePrefixes };
6723
+ /** 上次从数据后端预取墓碑的时间戳(节流用,见 prefetchRemoteTombstones)。 */
6724
+ lastTombstonePrefetchAt = 0;
6596
6725
  constructor(groupId, appId, backends, pollIntervalMs, parent, descriptor = {}) {
6597
6726
  this.groupId = groupId;
6598
6727
  this.appId = appId;
@@ -7446,12 +7575,70 @@ var AppDataGroupImpl = class _AppDataGroupImpl {
7446
7575
  /** Delete tombstoned files on local + every connected backend before/after sync. */
7447
7576
  async runTombstonePass(stage) {
7448
7577
  try {
7578
+ await this.prefetchRemoteTombstones(TOMBSTONE_PREFETCH_INTERVAL_MS);
7449
7579
  await this.tombstones.process(this.tombstoneTargets());
7450
7580
  this.refreshSyncExclusions(await this.tombstones.list());
7451
7581
  } catch (err) {
7452
7582
  log5.warn(`[AppDataGroup:${this.groupId}] ${stage} tombstone pass failed:`, err);
7453
7583
  }
7454
7584
  }
7585
+ /**
7586
+ * 把各数据后端上的墓碑合并进本地 `.meta/tombstones/`。
7587
+ *
7588
+ * 与配置组的 `ConfigRepo.prefetchReplicaTombstones` 同一目的、同一合并规则:
7589
+ * 远端删除意图优先于本地副本,先合并再让 `process()` 清掉陈旧数据,避免
7590
+ * 「本地有、别处已删」的文件被这一轮同步写回后端。
7591
+ */
7592
+ async prefetchRemoteTombstones(minIntervalMs = 0) {
7593
+ if (this.disposed || this.dataBackends.size === 0) return;
7594
+ const now = Date.now();
7595
+ if (minIntervalMs > 0 && now - this.lastTombstonePrefetchAt < minIntervalMs) return;
7596
+ this.lastTombstonePrefetchAt = now;
7597
+ let local;
7598
+ try {
7599
+ local = await this.tombstones.list();
7600
+ } catch {
7601
+ return;
7602
+ }
7603
+ const byPath = new Map(local.map((t) => [t.path, t]));
7604
+ let changed = false;
7605
+ for (const [backendId, backend] of this.dataBackends) {
7606
+ let remote;
7607
+ try {
7608
+ remote = await readTombstonesFromFs(backend.instance, (message) => log5.warn(`[AppDataGroup:${this.groupId}] prefetch tombstones (${backendId}): ${message}`));
7609
+ } catch (err) {
7610
+ log5.warn(`[AppDataGroup:${this.groupId}] prefetch tombstones from ${backendId} failed:`, err);
7611
+ continue;
7612
+ }
7613
+ for (const tombstone of remote) {
7614
+ if (!tombstone.path) continue;
7615
+ const prev = byPath.get(tombstone.path);
7616
+ if (!prev) {
7617
+ byPath.set(tombstone.path, tombstone);
7618
+ await this.tombstones.write(tombstone);
7619
+ changed = true;
7620
+ continue;
7621
+ }
7622
+ const merged = {
7623
+ ...prev,
7624
+ deletedAt: Math.min(prev.deletedAt, tombstone.deletedAt),
7625
+ confirmedBy: Array.from(/* @__PURE__ */ new Set([...prev.confirmedBy, ...tombstone.confirmedBy]))
7626
+ };
7627
+ if (isDirectoryTombstone(tombstone) && !isDirectoryTombstone(prev)) {
7628
+ merged.type = "directory";
7629
+ }
7630
+ const dirty = merged.deletedAt !== prev.deletedAt || merged.confirmedBy.length !== prev.confirmedBy.length || merged.type === "directory" && prev.type !== "directory";
7631
+ if (!dirty) continue;
7632
+ byPath.set(tombstone.path, merged);
7633
+ await this.tombstones.write(merged);
7634
+ changed = true;
7635
+ }
7636
+ }
7637
+ if (changed) {
7638
+ this.refreshSyncExclusions(await this.tombstones.list());
7639
+ log5.log(`[AppDataGroup:${this.groupId}] prefetchRemoteTombstones: merged remote tombstones`);
7640
+ }
7641
+ }
7455
7642
  /**
7456
7643
  * 把当前墓碑路径写进同步排除表(原地更新共享数组)。
7457
7644
  *
package/dist/index.mjs CHANGED
@@ -995,7 +995,7 @@ var META_BACKENDS_DIR = `${META_DIR}/backends`;
995
995
  var TOMBSTONES_DIR = `${META_DIR}/tombstones`;
996
996
  var ALIASES_DIR = `${META_DIR}/aliases`;
997
997
  var RECREATE_AFTER_DELETE_SKEW_MS = 3e3;
998
- var TOMBSTONE_RETENTION_MS = 24 * 60 * 60 * 1e3;
998
+ var TOMBSTONE_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3;
999
999
  var TOMBSTONE_PLACEHOLDER_RETENTION_MS = 10 * 60 * 1e3;
1000
1000
  function tombstoneRetentionMs(tombstonePath) {
1001
1001
  if (tombstonePath.endsWith(".mtime") || tombstonePath === "/.keep" || tombstonePath.endsWith("/.keep")) {
@@ -2492,6 +2492,7 @@ function normalizeGroupName(value) {
2492
2492
  var CONFIG_ONLY_PREFIXES = [CONFIG_DIR, NODES_DIR, SHARED_DIR];
2493
2493
  var LOCAL_IDB_BACKEND_ID = "local-idb";
2494
2494
  var TOMBSTONE_RECREATE_SKEW_MS = 3e3;
2495
+ var TOMBSTONE_PREFETCH_INTERVAL_MS = 60 * 1e3;
2495
2496
  function tombstoneFileName(filePath) {
2496
2497
  return `${encodeMetaPath(filePath)}.json`;
2497
2498
  }
@@ -2637,6 +2638,12 @@ var ConfigRepo = class _ConfigRepo {
2637
2638
  * unlink() 是否成功来判定。
2638
2639
  */
2639
2640
  tombstoneConfirmations = /* @__PURE__ */ new Map();
2641
+ /**
2642
+ * 上次从副本预取墓碑的时间戳(毫秒)。
2643
+ * 节流用:preSyncHook 每轮都会调用 {@link prefetchReplicaTombstones},
2644
+ * 但远端墓碑不会秒级变化,一分钟一次足够。
2645
+ */
2646
+ lastTombstonePrefetchAt = 0;
2640
2647
  /** Per-backend sync state (successful pairs + connect failures). */
2641
2648
  backendStates = /* @__PURE__ */ new Map();
2642
2649
  /**
@@ -2671,6 +2678,12 @@ var ConfigRepo = class _ConfigRepo {
2671
2678
  * 见 `healEmptyBootstrapDescriptors()`。
2672
2679
  */
2673
2680
  explicitEmptyDescriptors = /* @__PURE__ */ new Set();
2681
+ /**
2682
+ * 描述符文件路径 → 已确认在远端不存在。目录清单按 ETag 复用,删除不会
2683
+ * 改变 ETag,所以清单会长期保留已删除的文件名;这里记住 404 结果,
2684
+ * 避免每次 `listAppDataGroups()` 都为同一批死文件再发一次 GET。
2685
+ */
2686
+ missingDescriptorFiles = /* @__PURE__ */ new Set();
2674
2687
  /**
2675
2688
  * Tracks the background initial sync started by createConfigRepo().
2676
2689
  * `flush()` and `dispose()` will await this if it hasn't completed yet,
@@ -2851,6 +2864,11 @@ var ConfigRepo = class _ConfigRepo {
2851
2864
  await this.initialSyncPromise;
2852
2865
  this.initialSyncPromise = null;
2853
2866
  }
2867
+ try {
2868
+ await this.prefetchReplicaTombstones();
2869
+ } catch (err) {
2870
+ log5.warn("[ConfigRepo] flush tombstone prefetch failed:", err);
2871
+ }
2854
2872
  await this.processTombstones();
2855
2873
  await this.healEmptyBootstrapDescriptors();
2856
2874
  const resultsMap = await this.syncEngine.syncAll();
@@ -2977,6 +2995,89 @@ var ConfigRepo = class _ConfigRepo {
2977
2995
  invalidateTombstoneCache() {
2978
2996
  this.tombstoneCache = null;
2979
2997
  }
2998
+ /**
2999
+ * 把各副本上的墓碑合并进本地,必须早于本轮的快照比对。
3000
+ *
3001
+ * 为什么需要它:墓碑文件本身也是被同步的文件,一个节点在「拿到墓碑」之前
3002
+ * 就已经跑完了 preSyncHook —— 这时它本地没有该路径的墓碑,同步就会把自己
3003
+ * 那份陈旧副本当成「本地新增」推回远端(BiDirectional + source-wins),
3004
+ * 删除被复活。只靠墓碑文件被同步拉下来,永远慢半拍。
3005
+ *
3006
+ * 所以在每轮同步之前先只读地把副本上的 `.meta/tombstones/` 合并到本地:
3007
+ * 合并完成后排除表立刻生效,随后的 processTombstones() 会把本地陈旧副本
3008
+ * 一并清掉,同步再不会把它推上去。
3009
+ *
3010
+ * @param minIntervalMs 节流间隔(0 = 立即执行)。preSyncHook 传 60s。
3011
+ */
3012
+ async prefetchReplicaTombstones(minIntervalMs = 0) {
3013
+ if (this.disposed || this.replicaBackends.size === 0) return;
3014
+ const now = Date.now();
3015
+ if (minIntervalMs > 0 && now - this.lastTombstonePrefetchAt < minIntervalMs) return;
3016
+ this.lastTombstonePrefetchAt = now;
3017
+ let local;
3018
+ try {
3019
+ local = await this.readTombstones();
3020
+ } catch {
3021
+ return;
3022
+ }
3023
+ const byPath = new Map(local.map((t) => [t.path, t]));
3024
+ let changed = false;
3025
+ for (const [replicaId, replica] of this.replicaBackends) {
3026
+ let remote;
3027
+ try {
3028
+ remote = await readTombstonesFromFs(replica.instance, (message) => log5.warn(`[ConfigRepo] prefetch tombstones (${replicaId}): ${message}`));
3029
+ } catch (err) {
3030
+ log5.warn(`[ConfigRepo] prefetch tombstones from ${replicaId} failed:`, err);
3031
+ continue;
3032
+ }
3033
+ for (const tombstone of remote) {
3034
+ if (!tombstone.path) continue;
3035
+ const tombstonePath = tombstonePathFor(tombstone.path, TOMBSTONES_DIR);
3036
+ const prev = byPath.get(tombstone.path);
3037
+ if (!prev) {
3038
+ byPath.set(tombstone.path, tombstone);
3039
+ try {
3040
+ await this.ensureDir(tombstonePath);
3041
+ await writeFileOverwrite(
3042
+ this.cachedFS,
3043
+ tombstonePath,
3044
+ new TextEncoder().encode(serializeTombstone(tombstone))
3045
+ );
3046
+ changed = true;
3047
+ } catch (err) {
3048
+ log5.warn(`[ConfigRepo] prefetch tombstone write failed for ${tombstone.path}:`, err);
3049
+ }
3050
+ continue;
3051
+ }
3052
+ const merged = {
3053
+ ...prev,
3054
+ deletedAt: Math.min(prev.deletedAt, tombstone.deletedAt),
3055
+ confirmedBy: Array.from(/* @__PURE__ */ new Set([...prev.confirmedBy, ...tombstone.confirmedBy]))
3056
+ };
3057
+ if (isDirectoryTombstone(tombstone) && !isDirectoryTombstone(prev)) {
3058
+ merged.type = "directory";
3059
+ }
3060
+ const dirty = merged.deletedAt !== prev.deletedAt || merged.confirmedBy.length !== prev.confirmedBy.length || merged.type === "directory" && prev.type !== "directory";
3061
+ if (!dirty) continue;
3062
+ byPath.set(tombstone.path, merged);
3063
+ try {
3064
+ await writeFileOverwrite(
3065
+ this.cachedFS,
3066
+ tombstonePath,
3067
+ new TextEncoder().encode(serializeTombstone(merged))
3068
+ );
3069
+ changed = true;
3070
+ } catch (err) {
3071
+ log5.warn(`[ConfigRepo] prefetch tombstone merge failed for ${tombstone.path}:`, err);
3072
+ }
3073
+ }
3074
+ }
3075
+ if (changed) {
3076
+ this.invalidateTombstoneCache();
3077
+ await this.readTombstones();
3078
+ log5.log("[ConfigRepo] prefetchReplicaTombstones: merged remote tombstones");
3079
+ }
3080
+ }
2980
3081
  /**
2981
3082
  * 写入成功即撤销该路径(及其被删祖先目录)上的墓碑。
2982
3083
  *
@@ -3404,6 +3505,12 @@ var ConfigRepo = class _ConfigRepo {
3404
3505
  async initialSyncAndDedup() {
3405
3506
  this.syncEngine.unwatchAll();
3406
3507
  await this.healEmptyBootstrapDescriptors();
3508
+ try {
3509
+ await this.prefetchReplicaTombstones();
3510
+ await this.processTombstones();
3511
+ } catch (err) {
3512
+ log5.warn("[ConfigRepo] initial tombstone prefetch failed:", err);
3513
+ }
3407
3514
  await this.syncEngine.syncAll();
3408
3515
  await this.readAllBackendDescriptors();
3409
3516
  await this.processTombstones();
@@ -3897,6 +4004,8 @@ var ConfigRepo = class _ConfigRepo {
3897
4004
  filter: this.syncFilter,
3898
4005
  preSyncHook: async () => {
3899
4006
  try {
4007
+ this.invalidateTombstoneCache();
4008
+ await this.prefetchReplicaTombstones(TOMBSTONE_PREFETCH_INTERVAL_MS);
3900
4009
  this.invalidateTombstoneCache();
3901
4010
  await this.processTombstones();
3902
4011
  } catch (err) {
@@ -4442,6 +4551,8 @@ var ConfigRepo = class _ConfigRepo {
4442
4551
  filter: this.syncFilter,
4443
4552
  preSyncHook: async () => {
4444
4553
  try {
4554
+ this.invalidateTombstoneCache();
4555
+ await this.prefetchReplicaTombstones(TOMBSTONE_PREFETCH_INTERVAL_MS);
4445
4556
  this.invalidateTombstoneCache();
4446
4557
  await this.processTombstones();
4447
4558
  } catch (err) {
@@ -5017,12 +5128,12 @@ var ConfigRepo = class _ConfigRepo {
5017
5128
  // IConfigRepo — App Data Groups (data-sync groups)
5018
5129
  // -----------------------------------------------------------------------
5019
5130
  /** Path for a single app data group descriptor: .config/app-data-groups/{appId}/{id}.json */
5020
- appDataGroupFilePath(id) {
5021
- return `${APP_DATA_GROUPS_DIR}/${this.appId}/${id}.json`;
5131
+ appDataGroupFilePath(id, appId = this.appId) {
5132
+ return `${APP_DATA_GROUPS_DIR}/${appId}/${id}.json`;
5022
5133
  }
5023
5134
  /** Legacy descriptor path: .meta/app-data-groups/{appId}/{id}.json */
5024
- legacyAppDataGroupFilePath(id) {
5025
- return `${LEGACY_APP_DATA_GROUPS_DIR}/${this.appId}/${id}.json`;
5135
+ legacyAppDataGroupFilePath(id, appId = this.appId) {
5136
+ return `${LEGACY_APP_DATA_GROUPS_DIR}/${appId}/${id}.json`;
5026
5137
  }
5027
5138
  /**
5028
5139
  * Write a data-group descriptor to `.config/app-data-groups/` (registration
@@ -5054,15 +5165,15 @@ var ConfigRepo = class _ConfigRepo {
5054
5165
  * 归属靠文件内的 `groupId` 字段区分:同一 app 下不同组即使后端 id 相同,
5055
5166
  * 也各用各自的文件,不会在同步时互相覆盖(同一组不同端点同理)。
5056
5167
  */
5057
- appDataBackendsDirPath() {
5058
- return `${APP_DATA_GROUPS_DIR}/${this.appId}/backends`;
5168
+ appDataBackendsDirPath(appId = this.appId) {
5169
+ return `${APP_DATA_GROUPS_DIR}/${appId}/backends`;
5059
5170
  }
5060
- appDataBackendFilePath(backendId) {
5061
- return `${this.appDataBackendsDirPath()}/${backendId}.json`;
5171
+ appDataBackendFilePath(backendId, appId = this.appId) {
5172
+ return `${this.appDataBackendsDirPath(appId)}/${backendId}.json`;
5062
5173
  }
5063
5174
  /** 读本 app 目录下所有后端文件(忽略损坏/非本格式的文件)。 */
5064
- async readAppDataBackendFiles() {
5065
- const dir = this.appDataBackendsDirPath();
5175
+ async readAppDataBackendFiles(appId = this.appId) {
5176
+ const dir = this.appDataBackendsDirPath(appId);
5066
5177
  let entries;
5067
5178
  try {
5068
5179
  entries = await this.cachedFS.readdir(dir);
@@ -5084,9 +5195,9 @@ var ConfigRepo = class _ConfigRepo {
5084
5195
  return out;
5085
5196
  }
5086
5197
  /** 读某个数据组声明的全部后端文件(按 id 去重,先到先得)。 */
5087
- async readAppDataBackendFilesForGroup(groupId) {
5198
+ async readAppDataBackendFilesForGroup(groupId, appId = this.appId) {
5088
5199
  const byId = /* @__PURE__ */ new Map();
5089
- for (const file of await this.readAppDataBackendFiles()) {
5200
+ for (const file of await this.readAppDataBackendFiles(appId)) {
5090
5201
  if (file.groupId !== groupId) continue;
5091
5202
  if (byId.has(file.id)) continue;
5092
5203
  const { groupId: _groupId, ...desc } = file;
@@ -5617,15 +5728,21 @@ var ConfigRepo = class _ConfigRepo {
5617
5728
  }
5618
5729
  for (const entry of entries) {
5619
5730
  if (!entry.endsWith(".json")) continue;
5731
+ const filePath = `${dir}/${entry}`;
5732
+ if (this.missingDescriptorFiles.has(filePath)) continue;
5620
5733
  try {
5621
- const raw = await this.cachedFS.readFile(`${dir}/${entry}`);
5734
+ const raw = await this.cachedFS.readFile(filePath);
5622
5735
  const desc = JSON.parse(new TextDecoder().decode(toUint8Array2(raw)));
5623
5736
  if (desc.id && desc.groupType === "data-sync" && !byId.has(desc.id)) {
5624
5737
  const descriptor = desc;
5625
5738
  descriptor.backends = await this.resolveAppDataGroupBackends(desc.id, descriptor);
5626
5739
  byId.set(desc.id, descriptor);
5627
5740
  }
5628
- } catch {
5741
+ } catch (err) {
5742
+ const code = err?.code;
5743
+ if (code === "ENOENT" || err instanceof Error && /not\s*found/i.test(err.message)) {
5744
+ this.missingDescriptorFiles.add(filePath);
5745
+ }
5629
5746
  }
5630
5747
  }
5631
5748
  }
@@ -5705,15 +5822,25 @@ var ConfigRepo = class _ConfigRepo {
5705
5822
  }
5706
5823
  }
5707
5824
  }
5708
- async removeAppDataGroup(id) {
5825
+ /**
5826
+ * 删除一个数据组的登记(`.config/app-data-groups/{appId}/{id}.json` + 该组
5827
+ * 在配置仓的后端描述符)。
5828
+ *
5829
+ * @param appId 目标登记所属的 appId,默认为本实例的 appId。传其它 appId 时
5830
+ * 只删配置仓里那份登记与引导副本,不会(也无法)去 dispose 另一个
5831
+ * appId 实例里的组句柄 —— 调用方应优先走实例注册表,让实例自己刷新。
5832
+ */
5833
+ async removeAppDataGroup(id, appId = this.appId) {
5709
5834
  this.assertNotDisposed();
5710
- const group = this.appDataGroups.get(id);
5711
- if (group) {
5712
- await group.dispose();
5713
- this.appDataGroups.delete(id);
5835
+ if (appId === this.appId) {
5836
+ const group = this.appDataGroups.get(id);
5837
+ if (group) {
5838
+ await group.dispose();
5839
+ this.appDataGroups.delete(id);
5840
+ }
5714
5841
  }
5715
- for (const backend of await this.readAppDataBackendFilesForGroup(id)) {
5716
- const backendPath = this.appDataBackendFilePath(backend.id);
5842
+ for (const backend of await this.readAppDataBackendFilesForGroup(id, appId)) {
5843
+ const backendPath = this.appDataBackendFilePath(backend.id, appId);
5717
5844
  try {
5718
5845
  await this.deleteFile(backendPath);
5719
5846
  } catch (err) {
@@ -5725,7 +5852,7 @@ var ConfigRepo = class _ConfigRepo {
5725
5852
  await this.unlinkVersionSidecar(this.cachedFS, backendPath);
5726
5853
  }
5727
5854
  }
5728
- for (const descPath of [this.appDataGroupFilePath(id), this.legacyAppDataGroupFilePath(id)]) {
5855
+ for (const descPath of [this.appDataGroupFilePath(id, appId), this.legacyAppDataGroupFilePath(id, appId)]) {
5729
5856
  try {
5730
5857
  await this.deleteFile(descPath);
5731
5858
  } catch (err) {
@@ -5737,7 +5864,7 @@ var ConfigRepo = class _ConfigRepo {
5737
5864
  await this.unlinkVersionSidecar(this.cachedFS, descPath);
5738
5865
  }
5739
5866
  }
5740
- log5.log(`[ConfigRepo] removeAppDataGroup: "${id}" removed`);
5867
+ log5.log(`[ConfigRepo] removeAppDataGroup: "${appId}/${id}" removed`);
5741
5868
  }
5742
5869
  async listAccountBackends() {
5743
5870
  this.assertNotDisposed();
@@ -5799,6 +5926,8 @@ var AppDataGroupImpl = class _AppDataGroupImpl {
5799
5926
  static PERMANENT_SYNC_EXCLUSIONS = [...CONFIG_ONLY_PREFIXES, GROUP_DESCRIPTOR_FILE3];
5800
5927
  tombstoneExcludePrefixes = [..._AppDataGroupImpl.PERMANENT_SYNC_EXCLUSIONS];
5801
5928
  syncFilter = { excludePrefixes: this.tombstoneExcludePrefixes };
5929
+ /** 上次从数据后端预取墓碑的时间戳(节流用,见 prefetchRemoteTombstones)。 */
5930
+ lastTombstonePrefetchAt = 0;
5802
5931
  constructor(groupId, appId, backends, pollIntervalMs, parent, descriptor = {}) {
5803
5932
  this.groupId = groupId;
5804
5933
  this.appId = appId;
@@ -6652,12 +6781,70 @@ var AppDataGroupImpl = class _AppDataGroupImpl {
6652
6781
  /** Delete tombstoned files on local + every connected backend before/after sync. */
6653
6782
  async runTombstonePass(stage) {
6654
6783
  try {
6784
+ await this.prefetchRemoteTombstones(TOMBSTONE_PREFETCH_INTERVAL_MS);
6655
6785
  await this.tombstones.process(this.tombstoneTargets());
6656
6786
  this.refreshSyncExclusions(await this.tombstones.list());
6657
6787
  } catch (err) {
6658
6788
  log5.warn(`[AppDataGroup:${this.groupId}] ${stage} tombstone pass failed:`, err);
6659
6789
  }
6660
6790
  }
6791
+ /**
6792
+ * 把各数据后端上的墓碑合并进本地 `.meta/tombstones/`。
6793
+ *
6794
+ * 与配置组的 `ConfigRepo.prefetchReplicaTombstones` 同一目的、同一合并规则:
6795
+ * 远端删除意图优先于本地副本,先合并再让 `process()` 清掉陈旧数据,避免
6796
+ * 「本地有、别处已删」的文件被这一轮同步写回后端。
6797
+ */
6798
+ async prefetchRemoteTombstones(minIntervalMs = 0) {
6799
+ if (this.disposed || this.dataBackends.size === 0) return;
6800
+ const now = Date.now();
6801
+ if (minIntervalMs > 0 && now - this.lastTombstonePrefetchAt < minIntervalMs) return;
6802
+ this.lastTombstonePrefetchAt = now;
6803
+ let local;
6804
+ try {
6805
+ local = await this.tombstones.list();
6806
+ } catch {
6807
+ return;
6808
+ }
6809
+ const byPath = new Map(local.map((t) => [t.path, t]));
6810
+ let changed = false;
6811
+ for (const [backendId, backend] of this.dataBackends) {
6812
+ let remote;
6813
+ try {
6814
+ remote = await readTombstonesFromFs(backend.instance, (message) => log5.warn(`[AppDataGroup:${this.groupId}] prefetch tombstones (${backendId}): ${message}`));
6815
+ } catch (err) {
6816
+ log5.warn(`[AppDataGroup:${this.groupId}] prefetch tombstones from ${backendId} failed:`, err);
6817
+ continue;
6818
+ }
6819
+ for (const tombstone of remote) {
6820
+ if (!tombstone.path) continue;
6821
+ const prev = byPath.get(tombstone.path);
6822
+ if (!prev) {
6823
+ byPath.set(tombstone.path, tombstone);
6824
+ await this.tombstones.write(tombstone);
6825
+ changed = true;
6826
+ continue;
6827
+ }
6828
+ const merged = {
6829
+ ...prev,
6830
+ deletedAt: Math.min(prev.deletedAt, tombstone.deletedAt),
6831
+ confirmedBy: Array.from(/* @__PURE__ */ new Set([...prev.confirmedBy, ...tombstone.confirmedBy]))
6832
+ };
6833
+ if (isDirectoryTombstone(tombstone) && !isDirectoryTombstone(prev)) {
6834
+ merged.type = "directory";
6835
+ }
6836
+ const dirty = merged.deletedAt !== prev.deletedAt || merged.confirmedBy.length !== prev.confirmedBy.length || merged.type === "directory" && prev.type !== "directory";
6837
+ if (!dirty) continue;
6838
+ byPath.set(tombstone.path, merged);
6839
+ await this.tombstones.write(merged);
6840
+ changed = true;
6841
+ }
6842
+ }
6843
+ if (changed) {
6844
+ this.refreshSyncExclusions(await this.tombstones.list());
6845
+ log5.log(`[AppDataGroup:${this.groupId}] prefetchRemoteTombstones: merged remote tombstones`);
6846
+ }
6847
+ }
6661
6848
  /**
6662
6849
  * 把当前墓碑路径写进同步排除表(原地更新共享数组)。
6663
6850
  *
@@ -27755,7 +27755,7 @@ var ZenFSConfig = (() => {
27755
27755
  var TOMBSTONES_DIR = `${META_DIR}/tombstones`;
27756
27756
  var ALIASES_DIR = `${META_DIR}/aliases`;
27757
27757
  var RECREATE_AFTER_DELETE_SKEW_MS = 3e3;
27758
- var TOMBSTONE_RETENTION_MS = 24 * 60 * 60 * 1e3;
27758
+ var TOMBSTONE_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3;
27759
27759
  var TOMBSTONE_PLACEHOLDER_RETENTION_MS = 10 * 60 * 1e3;
27760
27760
  function tombstoneRetentionMs(tombstonePath) {
27761
27761
  if (tombstonePath.endsWith(".mtime") || tombstonePath === "/.keep" || tombstonePath.endsWith("/.keep")) {
@@ -29243,6 +29243,7 @@ var ZenFSConfig = (() => {
29243
29243
  var CONFIG_ONLY_PREFIXES = [CONFIG_DIR, NODES_DIR, SHARED_DIR];
29244
29244
  var LOCAL_IDB_BACKEND_ID = "local-idb";
29245
29245
  var TOMBSTONE_RECREATE_SKEW_MS = 3e3;
29246
+ var TOMBSTONE_PREFETCH_INTERVAL_MS = 60 * 1e3;
29246
29247
  function tombstoneFileName(filePath) {
29247
29248
  return `${encodeMetaPath(filePath)}.json`;
29248
29249
  }
@@ -29371,6 +29372,12 @@ var ZenFSConfig = (() => {
29371
29372
  * unlink() 是否成功来判定。
29372
29373
  */
29373
29374
  __publicField(this, "tombstoneConfirmations", /* @__PURE__ */ new Map());
29375
+ /**
29376
+ * 上次从副本预取墓碑的时间戳(毫秒)。
29377
+ * 节流用:preSyncHook 每轮都会调用 {@link prefetchReplicaTombstones},
29378
+ * 但远端墓碑不会秒级变化,一分钟一次足够。
29379
+ */
29380
+ __publicField(this, "lastTombstonePrefetchAt", 0);
29374
29381
  /** Per-backend sync state (successful pairs + connect failures). */
29375
29382
  __publicField(this, "backendStates", /* @__PURE__ */ new Map());
29376
29383
  /**
@@ -29405,6 +29412,12 @@ var ZenFSConfig = (() => {
29405
29412
  * 见 `healEmptyBootstrapDescriptors()`。
29406
29413
  */
29407
29414
  __publicField(this, "explicitEmptyDescriptors", /* @__PURE__ */ new Set());
29415
+ /**
29416
+ * 描述符文件路径 → 已确认在远端不存在。目录清单按 ETag 复用,删除不会
29417
+ * 改变 ETag,所以清单会长期保留已删除的文件名;这里记住 404 结果,
29418
+ * 避免每次 `listAppDataGroups()` 都为同一批死文件再发一次 GET。
29419
+ */
29420
+ __publicField(this, "missingDescriptorFiles", /* @__PURE__ */ new Set());
29408
29421
  /**
29409
29422
  * Tracks the background initial sync started by createConfigRepo().
29410
29423
  * `flush()` and `dispose()` will await this if it hasn't completed yet,
@@ -29594,6 +29607,11 @@ var ZenFSConfig = (() => {
29594
29607
  await this.initialSyncPromise;
29595
29608
  this.initialSyncPromise = null;
29596
29609
  }
29610
+ try {
29611
+ await this.prefetchReplicaTombstones();
29612
+ } catch (err2) {
29613
+ log9.warn("[ConfigRepo] flush tombstone prefetch failed:", err2);
29614
+ }
29597
29615
  await this.processTombstones();
29598
29616
  await this.healEmptyBootstrapDescriptors();
29599
29617
  const resultsMap = await this.syncEngine.syncAll();
@@ -29714,6 +29732,89 @@ var ZenFSConfig = (() => {
29714
29732
  invalidateTombstoneCache() {
29715
29733
  this.tombstoneCache = null;
29716
29734
  }
29735
+ /**
29736
+ * 把各副本上的墓碑合并进本地,必须早于本轮的快照比对。
29737
+ *
29738
+ * 为什么需要它:墓碑文件本身也是被同步的文件,一个节点在「拿到墓碑」之前
29739
+ * 就已经跑完了 preSyncHook —— 这时它本地没有该路径的墓碑,同步就会把自己
29740
+ * 那份陈旧副本当成「本地新增」推回远端(BiDirectional + source-wins),
29741
+ * 删除被复活。只靠墓碑文件被同步拉下来,永远慢半拍。
29742
+ *
29743
+ * 所以在每轮同步之前先只读地把副本上的 `.meta/tombstones/` 合并到本地:
29744
+ * 合并完成后排除表立刻生效,随后的 processTombstones() 会把本地陈旧副本
29745
+ * 一并清掉,同步再不会把它推上去。
29746
+ *
29747
+ * @param minIntervalMs 节流间隔(0 = 立即执行)。preSyncHook 传 60s。
29748
+ */
29749
+ async prefetchReplicaTombstones(minIntervalMs = 0) {
29750
+ if (this.disposed || this.replicaBackends.size === 0) return;
29751
+ const now = Date.now();
29752
+ if (minIntervalMs > 0 && now - this.lastTombstonePrefetchAt < minIntervalMs) return;
29753
+ this.lastTombstonePrefetchAt = now;
29754
+ let local;
29755
+ try {
29756
+ local = await this.readTombstones();
29757
+ } catch {
29758
+ return;
29759
+ }
29760
+ const byPath = new Map(local.map((t) => [t.path, t]));
29761
+ let changed = false;
29762
+ for (const [replicaId, replica] of this.replicaBackends) {
29763
+ let remote;
29764
+ try {
29765
+ remote = await readTombstonesFromFs(replica.instance, (message) => log9.warn(`[ConfigRepo] prefetch tombstones (${replicaId}): ${message}`));
29766
+ } catch (err2) {
29767
+ log9.warn(`[ConfigRepo] prefetch tombstones from ${replicaId} failed:`, err2);
29768
+ continue;
29769
+ }
29770
+ for (const tombstone of remote) {
29771
+ if (!tombstone.path) continue;
29772
+ const tombstonePath = tombstonePathFor(tombstone.path, TOMBSTONES_DIR);
29773
+ const prev = byPath.get(tombstone.path);
29774
+ if (!prev) {
29775
+ byPath.set(tombstone.path, tombstone);
29776
+ try {
29777
+ await this.ensureDir(tombstonePath);
29778
+ await writeFileOverwrite(
29779
+ this.cachedFS,
29780
+ tombstonePath,
29781
+ new TextEncoder().encode(serializeTombstone(tombstone))
29782
+ );
29783
+ changed = true;
29784
+ } catch (err2) {
29785
+ log9.warn(`[ConfigRepo] prefetch tombstone write failed for ${tombstone.path}:`, err2);
29786
+ }
29787
+ continue;
29788
+ }
29789
+ const merged = {
29790
+ ...prev,
29791
+ deletedAt: Math.min(prev.deletedAt, tombstone.deletedAt),
29792
+ confirmedBy: Array.from(/* @__PURE__ */ new Set([...prev.confirmedBy, ...tombstone.confirmedBy]))
29793
+ };
29794
+ if (isDirectoryTombstone(tombstone) && !isDirectoryTombstone(prev)) {
29795
+ merged.type = "directory";
29796
+ }
29797
+ const dirty = merged.deletedAt !== prev.deletedAt || merged.confirmedBy.length !== prev.confirmedBy.length || merged.type === "directory" && prev.type !== "directory";
29798
+ if (!dirty) continue;
29799
+ byPath.set(tombstone.path, merged);
29800
+ try {
29801
+ await writeFileOverwrite(
29802
+ this.cachedFS,
29803
+ tombstonePath,
29804
+ new TextEncoder().encode(serializeTombstone(merged))
29805
+ );
29806
+ changed = true;
29807
+ } catch (err2) {
29808
+ log9.warn(`[ConfigRepo] prefetch tombstone merge failed for ${tombstone.path}:`, err2);
29809
+ }
29810
+ }
29811
+ }
29812
+ if (changed) {
29813
+ this.invalidateTombstoneCache();
29814
+ await this.readTombstones();
29815
+ log9.log("[ConfigRepo] prefetchReplicaTombstones: merged remote tombstones");
29816
+ }
29817
+ }
29717
29818
  /**
29718
29819
  * 写入成功即撤销该路径(及其被删祖先目录)上的墓碑。
29719
29820
  *
@@ -30141,6 +30242,12 @@ var ZenFSConfig = (() => {
30141
30242
  async initialSyncAndDedup() {
30142
30243
  this.syncEngine.unwatchAll();
30143
30244
  await this.healEmptyBootstrapDescriptors();
30245
+ try {
30246
+ await this.prefetchReplicaTombstones();
30247
+ await this.processTombstones();
30248
+ } catch (err2) {
30249
+ log9.warn("[ConfigRepo] initial tombstone prefetch failed:", err2);
30250
+ }
30144
30251
  await this.syncEngine.syncAll();
30145
30252
  await this.readAllBackendDescriptors();
30146
30253
  await this.processTombstones();
@@ -30634,6 +30741,8 @@ var ZenFSConfig = (() => {
30634
30741
  filter: this.syncFilter,
30635
30742
  preSyncHook: async () => {
30636
30743
  try {
30744
+ this.invalidateTombstoneCache();
30745
+ await this.prefetchReplicaTombstones(TOMBSTONE_PREFETCH_INTERVAL_MS);
30637
30746
  this.invalidateTombstoneCache();
30638
30747
  await this.processTombstones();
30639
30748
  } catch (err2) {
@@ -31179,6 +31288,8 @@ var ZenFSConfig = (() => {
31179
31288
  filter: this.syncFilter,
31180
31289
  preSyncHook: async () => {
31181
31290
  try {
31291
+ this.invalidateTombstoneCache();
31292
+ await this.prefetchReplicaTombstones(TOMBSTONE_PREFETCH_INTERVAL_MS);
31182
31293
  this.invalidateTombstoneCache();
31183
31294
  await this.processTombstones();
31184
31295
  } catch (err2) {
@@ -31750,12 +31861,12 @@ var ZenFSConfig = (() => {
31750
31861
  // IConfigRepo — App Data Groups (data-sync groups)
31751
31862
  // -----------------------------------------------------------------------
31752
31863
  /** Path for a single app data group descriptor: .config/app-data-groups/{appId}/{id}.json */
31753
- appDataGroupFilePath(id) {
31754
- return `${APP_DATA_GROUPS_DIR}/${this.appId}/${id}.json`;
31864
+ appDataGroupFilePath(id, appId = this.appId) {
31865
+ return `${APP_DATA_GROUPS_DIR}/${appId}/${id}.json`;
31755
31866
  }
31756
31867
  /** Legacy descriptor path: .meta/app-data-groups/{appId}/{id}.json */
31757
- legacyAppDataGroupFilePath(id) {
31758
- return `${LEGACY_APP_DATA_GROUPS_DIR}/${this.appId}/${id}.json`;
31868
+ legacyAppDataGroupFilePath(id, appId = this.appId) {
31869
+ return `${LEGACY_APP_DATA_GROUPS_DIR}/${appId}/${id}.json`;
31759
31870
  }
31760
31871
  /**
31761
31872
  * Write a data-group descriptor to `.config/app-data-groups/` (registration
@@ -31787,15 +31898,15 @@ var ZenFSConfig = (() => {
31787
31898
  * 归属靠文件内的 `groupId` 字段区分:同一 app 下不同组即使后端 id 相同,
31788
31899
  * 也各用各自的文件,不会在同步时互相覆盖(同一组不同端点同理)。
31789
31900
  */
31790
- appDataBackendsDirPath() {
31791
- return `${APP_DATA_GROUPS_DIR}/${this.appId}/backends`;
31901
+ appDataBackendsDirPath(appId = this.appId) {
31902
+ return `${APP_DATA_GROUPS_DIR}/${appId}/backends`;
31792
31903
  }
31793
- appDataBackendFilePath(backendId) {
31794
- return `${this.appDataBackendsDirPath()}/${backendId}.json`;
31904
+ appDataBackendFilePath(backendId, appId = this.appId) {
31905
+ return `${this.appDataBackendsDirPath(appId)}/${backendId}.json`;
31795
31906
  }
31796
31907
  /** 读本 app 目录下所有后端文件(忽略损坏/非本格式的文件)。 */
31797
- async readAppDataBackendFiles() {
31798
- const dir = this.appDataBackendsDirPath();
31908
+ async readAppDataBackendFiles(appId = this.appId) {
31909
+ const dir = this.appDataBackendsDirPath(appId);
31799
31910
  let entries2;
31800
31911
  try {
31801
31912
  entries2 = await this.cachedFS.readdir(dir);
@@ -31817,9 +31928,9 @@ var ZenFSConfig = (() => {
31817
31928
  return out;
31818
31929
  }
31819
31930
  /** 读某个数据组声明的全部后端文件(按 id 去重,先到先得)。 */
31820
- async readAppDataBackendFilesForGroup(groupId) {
31931
+ async readAppDataBackendFilesForGroup(groupId, appId = this.appId) {
31821
31932
  const byId = /* @__PURE__ */ new Map();
31822
- for (const file of await this.readAppDataBackendFiles()) {
31933
+ for (const file of await this.readAppDataBackendFiles(appId)) {
31823
31934
  if (file.groupId !== groupId) continue;
31824
31935
  if (byId.has(file.id)) continue;
31825
31936
  const { groupId: _groupId, ...desc } = file;
@@ -32350,15 +32461,21 @@ var ZenFSConfig = (() => {
32350
32461
  }
32351
32462
  for (const entry of entries2) {
32352
32463
  if (!entry.endsWith(".json")) continue;
32464
+ const filePath = `${dir}/${entry}`;
32465
+ if (this.missingDescriptorFiles.has(filePath)) continue;
32353
32466
  try {
32354
- const raw = await this.cachedFS.readFile(`${dir}/${entry}`);
32467
+ const raw = await this.cachedFS.readFile(filePath);
32355
32468
  const desc = JSON.parse(new TextDecoder().decode(toUint8Array2(raw)));
32356
32469
  if (desc.id && desc.groupType === "data-sync" && !byId.has(desc.id)) {
32357
32470
  const descriptor = desc;
32358
32471
  descriptor.backends = await this.resolveAppDataGroupBackends(desc.id, descriptor);
32359
32472
  byId.set(desc.id, descriptor);
32360
32473
  }
32361
- } catch {
32474
+ } catch (err2) {
32475
+ const code = err2?.code;
32476
+ if (code === "ENOENT" || err2 instanceof Error && /not\s*found/i.test(err2.message)) {
32477
+ this.missingDescriptorFiles.add(filePath);
32478
+ }
32362
32479
  }
32363
32480
  }
32364
32481
  }
@@ -32438,15 +32555,25 @@ var ZenFSConfig = (() => {
32438
32555
  }
32439
32556
  }
32440
32557
  }
32441
- async removeAppDataGroup(id) {
32558
+ /**
32559
+ * 删除一个数据组的登记(`.config/app-data-groups/{appId}/{id}.json` + 该组
32560
+ * 在配置仓的后端描述符)。
32561
+ *
32562
+ * @param appId 目标登记所属的 appId,默认为本实例的 appId。传其它 appId 时
32563
+ * 只删配置仓里那份登记与引导副本,不会(也无法)去 dispose 另一个
32564
+ * appId 实例里的组句柄 —— 调用方应优先走实例注册表,让实例自己刷新。
32565
+ */
32566
+ async removeAppDataGroup(id, appId = this.appId) {
32442
32567
  this.assertNotDisposed();
32443
- const group = this.appDataGroups.get(id);
32444
- if (group) {
32445
- await group.dispose();
32446
- this.appDataGroups.delete(id);
32568
+ if (appId === this.appId) {
32569
+ const group = this.appDataGroups.get(id);
32570
+ if (group) {
32571
+ await group.dispose();
32572
+ this.appDataGroups.delete(id);
32573
+ }
32447
32574
  }
32448
- for (const backend of await this.readAppDataBackendFilesForGroup(id)) {
32449
- const backendPath = this.appDataBackendFilePath(backend.id);
32575
+ for (const backend of await this.readAppDataBackendFilesForGroup(id, appId)) {
32576
+ const backendPath = this.appDataBackendFilePath(backend.id, appId);
32450
32577
  try {
32451
32578
  await this.deleteFile(backendPath);
32452
32579
  } catch (err2) {
@@ -32458,7 +32585,7 @@ var ZenFSConfig = (() => {
32458
32585
  await this.unlinkVersionSidecar(this.cachedFS, backendPath);
32459
32586
  }
32460
32587
  }
32461
- for (const descPath of [this.appDataGroupFilePath(id), this.legacyAppDataGroupFilePath(id)]) {
32588
+ for (const descPath of [this.appDataGroupFilePath(id, appId), this.legacyAppDataGroupFilePath(id, appId)]) {
32462
32589
  try {
32463
32590
  await this.deleteFile(descPath);
32464
32591
  } catch (err2) {
@@ -32470,7 +32597,7 @@ var ZenFSConfig = (() => {
32470
32597
  await this.unlinkVersionSidecar(this.cachedFS, descPath);
32471
32598
  }
32472
32599
  }
32473
- log9.log(`[ConfigRepo] removeAppDataGroup: "${id}" removed`);
32600
+ log9.log(`[ConfigRepo] removeAppDataGroup: "${appId}/${id}" removed`);
32474
32601
  }
32475
32602
  async listAccountBackends() {
32476
32603
  this.assertNotDisposed();
@@ -32541,6 +32668,8 @@ var ZenFSConfig = (() => {
32541
32668
  __publicField(this, "postDeleteTimer");
32542
32669
  __publicField(this, "tombstoneExcludePrefixes", [..._AppDataGroupImpl.PERMANENT_SYNC_EXCLUSIONS]);
32543
32670
  __publicField(this, "syncFilter", { excludePrefixes: this.tombstoneExcludePrefixes });
32671
+ /** 上次从数据后端预取墓碑的时间戳(节流用,见 prefetchRemoteTombstones)。 */
32672
+ __publicField(this, "lastTombstonePrefetchAt", 0);
32544
32673
  __publicField(this, "parent");
32545
32674
  __publicField(this, "_backends");
32546
32675
  /**
@@ -33393,12 +33522,70 @@ var ZenFSConfig = (() => {
33393
33522
  /** Delete tombstoned files on local + every connected backend before/after sync. */
33394
33523
  async runTombstonePass(stage) {
33395
33524
  try {
33525
+ await this.prefetchRemoteTombstones(TOMBSTONE_PREFETCH_INTERVAL_MS);
33396
33526
  await this.tombstones.process(this.tombstoneTargets());
33397
33527
  this.refreshSyncExclusions(await this.tombstones.list());
33398
33528
  } catch (err2) {
33399
33529
  log9.warn(`[AppDataGroup:${this.groupId}] ${stage} tombstone pass failed:`, err2);
33400
33530
  }
33401
33531
  }
33532
+ /**
33533
+ * 把各数据后端上的墓碑合并进本地 `.meta/tombstones/`。
33534
+ *
33535
+ * 与配置组的 `ConfigRepo.prefetchReplicaTombstones` 同一目的、同一合并规则:
33536
+ * 远端删除意图优先于本地副本,先合并再让 `process()` 清掉陈旧数据,避免
33537
+ * 「本地有、别处已删」的文件被这一轮同步写回后端。
33538
+ */
33539
+ async prefetchRemoteTombstones(minIntervalMs = 0) {
33540
+ if (this.disposed || this.dataBackends.size === 0) return;
33541
+ const now = Date.now();
33542
+ if (minIntervalMs > 0 && now - this.lastTombstonePrefetchAt < minIntervalMs) return;
33543
+ this.lastTombstonePrefetchAt = now;
33544
+ let local;
33545
+ try {
33546
+ local = await this.tombstones.list();
33547
+ } catch {
33548
+ return;
33549
+ }
33550
+ const byPath = new Map(local.map((t) => [t.path, t]));
33551
+ let changed = false;
33552
+ for (const [backendId, backend] of this.dataBackends) {
33553
+ let remote;
33554
+ try {
33555
+ remote = await readTombstonesFromFs(backend.instance, (message) => log9.warn(`[AppDataGroup:${this.groupId}] prefetch tombstones (${backendId}): ${message}`));
33556
+ } catch (err2) {
33557
+ log9.warn(`[AppDataGroup:${this.groupId}] prefetch tombstones from ${backendId} failed:`, err2);
33558
+ continue;
33559
+ }
33560
+ for (const tombstone of remote) {
33561
+ if (!tombstone.path) continue;
33562
+ const prev = byPath.get(tombstone.path);
33563
+ if (!prev) {
33564
+ byPath.set(tombstone.path, tombstone);
33565
+ await this.tombstones.write(tombstone);
33566
+ changed = true;
33567
+ continue;
33568
+ }
33569
+ const merged = {
33570
+ ...prev,
33571
+ deletedAt: Math.min(prev.deletedAt, tombstone.deletedAt),
33572
+ confirmedBy: Array.from(/* @__PURE__ */ new Set([...prev.confirmedBy, ...tombstone.confirmedBy]))
33573
+ };
33574
+ if (isDirectoryTombstone(tombstone) && !isDirectoryTombstone(prev)) {
33575
+ merged.type = "directory";
33576
+ }
33577
+ const dirty = merged.deletedAt !== prev.deletedAt || merged.confirmedBy.length !== prev.confirmedBy.length || merged.type === "directory" && prev.type !== "directory";
33578
+ if (!dirty) continue;
33579
+ byPath.set(tombstone.path, merged);
33580
+ await this.tombstones.write(merged);
33581
+ changed = true;
33582
+ }
33583
+ }
33584
+ if (changed) {
33585
+ this.refreshSyncExclusions(await this.tombstones.list());
33586
+ log9.log(`[AppDataGroup:${this.groupId}] prefetchRemoteTombstones: merged remote tombstones`);
33587
+ }
33588
+ }
33402
33589
  /**
33403
33590
  * 把当前墓碑路径写进同步排除表(原地更新共享数组)。
33404
33591
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zen-fs-config",
3
- "version": "0.10.2",
3
+ "version": "0.10.4",
4
4
  "description": "Distributed config management library built on ZenFS, zen-fs-cache, and zen-fs-sync",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",