zen-fs-config 0.6.0 → 0.6.2

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.
@@ -27562,6 +27562,7 @@ var ZenFSConfig = (() => {
27562
27562
  }
27563
27563
 
27564
27564
  // src/group-meta.ts
27565
+ var log6 = createLogger("zen-fs-config:tombstones");
27565
27566
  var META_DIR = "/.meta";
27566
27567
  var GROUP_DESCRIPTOR_FILE = `${META_DIR}/group.json`;
27567
27568
  var META_BACKENDS_DIR = `${META_DIR}/backends`;
@@ -27632,6 +27633,141 @@ var ZenFSConfig = (() => {
27632
27633
  const normalized = filePath.startsWith("/") ? filePath : `/${filePath}`;
27633
27634
  return normalized.replace(/^\//, "").replace(/\//g, "__").replace(/\./g, "++");
27634
27635
  }
27636
+ function decodeMetaPath(entry) {
27637
+ if (!entry.endsWith(".json")) return null;
27638
+ const encoded = entry.slice(0, -".json".length);
27639
+ if (!encoded) return null;
27640
+ return `/${encoded.replace(/__/g, "/").replace(/\+\+/g, ".")}`;
27641
+ }
27642
+ function fallbackTombstone(path) {
27643
+ return { path, deletedAt: 0, deletedBy: "unknown", confirmedBy: [] };
27644
+ }
27645
+ function normalizeTombstoneRecord(value, fallbackPath) {
27646
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
27647
+ const record = value;
27648
+ const rawPath = typeof record.path === "string" ? record.path : fallbackPath;
27649
+ if (!rawPath) return null;
27650
+ const path = rawPath.startsWith("/") ? rawPath : `/${rawPath}`;
27651
+ const confirmedBy = Array.isArray(record.confirmedBy) ? record.confirmedBy.filter((id) => typeof id === "string") : [];
27652
+ return {
27653
+ path,
27654
+ deletedAt: typeof record.deletedAt === "number" ? record.deletedAt : 0,
27655
+ deletedBy: typeof record.deletedBy === "string" ? record.deletedBy : "unknown",
27656
+ confirmedBy
27657
+ };
27658
+ }
27659
+ function extractJsonObjects(raw) {
27660
+ const objects = [];
27661
+ let depth = 0;
27662
+ let start = -1;
27663
+ let inString = false;
27664
+ let escaped = false;
27665
+ for (let i = 0; i < raw.length; i++) {
27666
+ const ch = raw[i];
27667
+ if (inString) {
27668
+ if (escaped) escaped = false;
27669
+ else if (ch === "\\") escaped = true;
27670
+ else if (ch === '"') inString = false;
27671
+ continue;
27672
+ }
27673
+ if (ch === '"') {
27674
+ inString = true;
27675
+ continue;
27676
+ }
27677
+ if (ch === "{") {
27678
+ if (depth === 0) start = i;
27679
+ depth++;
27680
+ continue;
27681
+ }
27682
+ if (ch === "}") {
27683
+ if (depth === 0) continue;
27684
+ depth--;
27685
+ if (depth === 0 && start >= 0) {
27686
+ objects.push(raw.slice(start, i + 1));
27687
+ start = -1;
27688
+ }
27689
+ }
27690
+ }
27691
+ return objects;
27692
+ }
27693
+ function parseTombstoneFile(raw, fallbackPath) {
27694
+ const problems = [];
27695
+ const text = raw.trim();
27696
+ if (text === "") {
27697
+ problems.push("empty body");
27698
+ if (fallbackPath) {
27699
+ problems.push("path derived from filename");
27700
+ return { tombstones: [fallbackTombstone(fallbackPath)], problems };
27701
+ }
27702
+ problems.push("no path derivable from filename \u2014 skipped");
27703
+ return { tombstones: [], problems };
27704
+ }
27705
+ try {
27706
+ const parsed = normalizeTombstoneRecord(JSON.parse(text), fallbackPath);
27707
+ if (parsed) return { tombstones: [parsed], problems: [] };
27708
+ problems.push('JSON parsed but has no usable "path"');
27709
+ } catch (err2) {
27710
+ problems.push(`JSON parse error: ${err2 instanceof Error ? err2.message : String(err2)}`);
27711
+ }
27712
+ const recovered = extractJsonObjects(text).map((chunk) => {
27713
+ try {
27714
+ return normalizeTombstoneRecord(JSON.parse(chunk));
27715
+ } catch {
27716
+ return null;
27717
+ }
27718
+ }).filter((t) => t !== null);
27719
+ if (recovered.length > 0) {
27720
+ if (recovered.length > 1) problems.push(`${recovered.length} concatenated documents recovered`);
27721
+ return { tombstones: recovered, problems };
27722
+ }
27723
+ if (fallbackPath) {
27724
+ problems.push("no recoverable document; path derived from filename");
27725
+ return { tombstones: [fallbackTombstone(fallbackPath)], problems };
27726
+ }
27727
+ problems.push("no recoverable document and no path derivable from filename \u2014 skipped");
27728
+ return { tombstones: [], problems };
27729
+ }
27730
+ function mergeTombstone(byPath, tombstone) {
27731
+ const prev = byPath.get(tombstone.path);
27732
+ if (!prev) {
27733
+ byPath.set(tombstone.path, tombstone);
27734
+ return;
27735
+ }
27736
+ for (const id of tombstone.confirmedBy) {
27737
+ if (!prev.confirmedBy.includes(id)) prev.confirmedBy.push(id);
27738
+ }
27739
+ }
27740
+ async function readTombstonesFromFs(fs, warn2) {
27741
+ const byPath = /* @__PURE__ */ new Map();
27742
+ for (const dir of [TOMBSTONES_DIR, LEGACY_TOMBSTONES_DIR]) {
27743
+ let entries2;
27744
+ try {
27745
+ entries2 = await fs.readdir(dir);
27746
+ } catch {
27747
+ continue;
27748
+ }
27749
+ for (const entry of entries2) {
27750
+ if (!entry.endsWith(".json")) continue;
27751
+ const filePath = `${dir}/${entry}`;
27752
+ let raw;
27753
+ try {
27754
+ raw = new TextDecoder().decode(toBytes(await fs.readFile(filePath)));
27755
+ } catch (err2) {
27756
+ warn2(
27757
+ `[Tombstones] unreadable tombstone ${filePath}: ${err2 instanceof Error ? err2.message : String(err2)} \u2014 skipped`
27758
+ );
27759
+ continue;
27760
+ }
27761
+ const { tombstones, problems } = parseTombstoneFile(raw, decodeMetaPath(entry) ?? void 0);
27762
+ if (problems.length > 0) {
27763
+ const action = tombstones.length > 0 ? tombstones.map((t) => `"${t.path}" treated as deleted`).join(", ") : "skipped";
27764
+ warn2(`[Tombstones] corrupt tombstone ${filePath}: ${problems.join("; ")} \u2192 ${action}`);
27765
+ }
27766
+ for (const tombstone of tombstones) mergeTombstone(byPath, tombstone);
27767
+ }
27768
+ }
27769
+ return Array.from(byPath.values());
27770
+ }
27635
27771
  async function readGroupDescriptor(fs) {
27636
27772
  const parsed = await readJson(fs, GROUP_DESCRIPTOR_FILE);
27637
27773
  if (!parsed) return null;
@@ -27707,29 +27843,7 @@ var ZenFSConfig = (() => {
27707
27843
  }
27708
27844
  /** All tombstones, new path first, legacy only for paths not already seen. */
27709
27845
  async list() {
27710
- const byPath = /* @__PURE__ */ new Map();
27711
- for (const dir of [TOMBSTONES_DIR, LEGACY_TOMBSTONES_DIR]) {
27712
- let entries2;
27713
- try {
27714
- entries2 = await this.fs.readdir(dir);
27715
- } catch {
27716
- continue;
27717
- }
27718
- for (const entry of entries2) {
27719
- if (!entry.endsWith(".json")) continue;
27720
- const data = await readJson(this.fs, `${dir}/${entry}`);
27721
- if (!data || typeof data.path !== "string") continue;
27722
- const prev = byPath.get(data.path);
27723
- if (prev) {
27724
- for (const id of data.confirmedBy ?? []) {
27725
- if (!prev.confirmedBy.includes(id)) prev.confirmedBy.push(id);
27726
- }
27727
- } else {
27728
- byPath.set(data.path, data);
27729
- }
27730
- }
27731
- }
27732
- return Array.from(byPath.values());
27846
+ return readTombstonesFromFs(this.fs, (message) => log6.warn(message));
27733
27847
  }
27734
27848
  /** Write a tombstone (new + legacy mirror). */
27735
27849
  async write(tombstone) {
@@ -27955,7 +28069,7 @@ var ZenFSConfig = (() => {
27955
28069
  };
27956
28070
 
27957
28071
  // src/config-repo.ts
27958
- var log6 = createLogger("zen-fs-config:config-repo");
28072
+ var log7 = createLogger("zen-fs-config:config-repo");
27959
28073
  var GROUP_DESCRIPTOR_FILE2 = `${META_DIR}/group.json`;
27960
28074
  var GROUP_TYPE_FILE = `${CONFIG_DIR}/group-type`;
27961
28075
  var LEGACY_GROUP_TYPE_FILE = `${META_DIR}/group-type`;
@@ -28214,7 +28328,7 @@ var ZenFSConfig = (() => {
28214
28328
  const bytes = this.serializer.serialize(data, fullPath);
28215
28329
  this.configCache.set(fullPath, data);
28216
28330
  this.persistConfig(fullPath, bytes).catch((err2) => {
28217
- log6.error(`[zen-fs-config] Failed to persist ${fullPath}:`, err2);
28331
+ log7.error(`[zen-fs-config] Failed to persist ${fullPath}:`, err2);
28218
28332
  });
28219
28333
  }
28220
28334
  // -----------------------------------------------------------------------
@@ -28368,7 +28482,7 @@ var ZenFSConfig = (() => {
28368
28482
  await removeDirectoryTree(this.cachedFS, normalizedPath);
28369
28483
  this.invalidateTombstoneCache();
28370
28484
  this.schedulePostDeleteSync();
28371
- log6.log(`[ConfigRepo] deleteFile(directory): ${normalizedPath} (${files.length} file(s))`);
28485
+ log7.log(`[ConfigRepo] deleteFile(directory): ${normalizedPath} (${files.length} file(s))`);
28372
28486
  return;
28373
28487
  }
28374
28488
  await this.writeTombstoneFor(normalizedPath);
@@ -28389,7 +28503,7 @@ var ZenFSConfig = (() => {
28389
28503
  } catch {
28390
28504
  }
28391
28505
  }
28392
- log6.log(`[ConfigRepo] deleteFile: ${normalizedPath} (tombstone at ${tombstonePathFor(normalizedPath)})`);
28506
+ log7.log(`[ConfigRepo] deleteFile: ${normalizedPath} (tombstone at ${tombstonePathFor(normalizedPath)})`);
28393
28507
  this.invalidateTombstoneCache();
28394
28508
  this.schedulePostDeleteSync();
28395
28509
  }
@@ -28401,7 +28515,7 @@ var ZenFSConfig = (() => {
28401
28515
  this.postDeleteSyncTimer = void 0;
28402
28516
  if (this.disposed) return;
28403
28517
  this.syncEngine.syncAll().catch((err2) => {
28404
- log6.warn("[ConfigRepo] post-delete sync failed:", err2);
28518
+ log7.warn("[ConfigRepo] post-delete sync failed:", err2);
28405
28519
  });
28406
28520
  }, 500);
28407
28521
  }
@@ -28413,32 +28527,7 @@ var ZenFSConfig = (() => {
28413
28527
  if (this.tombstoneCache !== null) {
28414
28528
  return this.tombstoneCache;
28415
28529
  }
28416
- const byPath = /* @__PURE__ */ new Map();
28417
- for (const dir of [TOMBSTONES_DIR, LEGACY_TOMBSTONES_DIR]) {
28418
- let entries2;
28419
- try {
28420
- entries2 = await this.cachedFS.readdir(dir);
28421
- } catch {
28422
- continue;
28423
- }
28424
- for (const entry of entries2) {
28425
- if (!entry.endsWith(".json")) continue;
28426
- try {
28427
- const raw = await this.cachedFS.readFile(`${dir}/${entry}`);
28428
- const data = JSON.parse(new TextDecoder().decode(toUint8Array2(raw)));
28429
- const prev = byPath.get(data.path);
28430
- if (prev) {
28431
- for (const id of data.confirmedBy ?? []) {
28432
- if (!prev.confirmedBy.includes(id)) prev.confirmedBy.push(id);
28433
- }
28434
- } else {
28435
- byPath.set(data.path, data);
28436
- }
28437
- } catch {
28438
- }
28439
- }
28440
- }
28441
- this.tombstoneCache = Array.from(byPath.values());
28530
+ this.tombstoneCache = await readTombstonesFromFs(this.cachedFS, (message) => log7.warn(message));
28442
28531
  return this.tombstoneCache;
28443
28532
  }
28444
28533
  /** Invalidate the tombstone cache — call after tombstones are modified. */
@@ -28463,11 +28552,11 @@ var ZenFSConfig = (() => {
28463
28552
  for (const tombstone of tombstones) {
28464
28553
  const forceDelete = isMtimeSidecar(tombstone.path);
28465
28554
  const tVersionPath = forceDelete ? null : versionPathFor(tombstone.path);
28466
- log6.log(`[TOMB-TRACE] processing tombstone: path=${tombstone.path} versionPath=${tVersionPath ?? "null"} forceDelete=${forceDelete}`);
28555
+ log7.log(`[TOMB-TRACE] processing tombstone: path=${tombstone.path} versionPath=${tVersionPath ?? "null"} forceDelete=${forceDelete}`);
28467
28556
  const existedOnPrimary = forceDelete || await this.safeExists(this.cachedFS, tombstone.path);
28468
- log6.log(`[TOMB-TRACE] primary safeExists(${tombstone.path}) \u2192 ${existedOnPrimary}`);
28557
+ log7.log(`[TOMB-TRACE] primary safeExists(${tombstone.path}) \u2192 ${existedOnPrimary}`);
28469
28558
  if (existedOnPrimary) {
28470
- log6.log(`[TOMB-TRACE] tombstone check: ${tombstone.path} on primary \u2192 EXISTS`);
28559
+ log7.log(`[TOMB-TRACE] tombstone check: ${tombstone.path} on primary \u2192 EXISTS`);
28471
28560
  }
28472
28561
  if (existedOnPrimary) {
28473
28562
  try {
@@ -28478,7 +28567,7 @@ var ZenFSConfig = (() => {
28478
28567
  }
28479
28568
  if (tVersionPath) {
28480
28569
  const vExistedOnPrimary = await this.safeExists(this.cachedFS, tVersionPath);
28481
- log6.log(`[TOMB-TRACE] primary safeExists(${tVersionPath}) \u2192 ${vExistedOnPrimary}`);
28570
+ log7.log(`[TOMB-TRACE] primary safeExists(${tVersionPath}) \u2192 ${vExistedOnPrimary}`);
28482
28571
  if (vExistedOnPrimary) {
28483
28572
  try {
28484
28573
  await this.cachedFS.unlink(tVersionPath);
@@ -28487,40 +28576,40 @@ var ZenFSConfig = (() => {
28487
28576
  }
28488
28577
  }
28489
28578
  for (const [replicaId, replica] of this.replicaBackends) {
28490
- log6.log(`[TOMB-TRACE] checking replica: ${replicaId} for ${tombstone.path}`);
28579
+ log7.log(`[TOMB-TRACE] checking replica: ${replicaId} for ${tombstone.path}`);
28491
28580
  const existed = forceDelete || await this.safeExists(replica.instance, tombstone.path);
28492
- log6.log(`[TOMB-TRACE] replica ${replicaId} safeExists(${tombstone.path}) \u2192 ${existed}`);
28581
+ log7.log(`[TOMB-TRACE] replica ${replicaId} safeExists(${tombstone.path}) \u2192 ${existed}`);
28493
28582
  if (existed) {
28494
- log6.log(`[TOMB-TRACE] tombstone check: ${tombstone.path} on ${replicaId} \u2192 EXISTS`);
28583
+ log7.log(`[TOMB-TRACE] tombstone check: ${tombstone.path} on ${replicaId} \u2192 EXISTS`);
28495
28584
  try {
28496
- log6.log(`[TOMB-TRACE] calling unlink(${tombstone.path}) on ${replicaId}`);
28585
+ log7.log(`[TOMB-TRACE] calling unlink(${tombstone.path}) on ${replicaId}`);
28497
28586
  await replica.instance.unlink(tombstone.path);
28498
- log6.log(`[TOMB-TRACE] tombstone ${tombstone.path}: deleted on ${replicaId}`);
28587
+ log7.log(`[TOMB-TRACE] tombstone ${tombstone.path}: deleted on ${replicaId}`);
28499
28588
  processed++;
28500
28589
  } catch (err2) {
28501
- log6.log(`[TOMB-TRACE] unlink(${tombstone.path}) on ${replicaId} FAILED: ${err2}`);
28590
+ log7.log(`[TOMB-TRACE] unlink(${tombstone.path}) on ${replicaId} FAILED: ${err2}`);
28502
28591
  alreadyDeleted++;
28503
28592
  }
28504
28593
  } else {
28505
- log6.log(`[TOMB-TRACE] replica ${replicaId}: already gone, skipping unlink`);
28594
+ log7.log(`[TOMB-TRACE] replica ${replicaId}: already gone, skipping unlink`);
28506
28595
  alreadyDeleted++;
28507
28596
  }
28508
28597
  if (tVersionPath) {
28509
28598
  const vExisted = await this.safeExists(replica.instance, tVersionPath);
28510
- log6.log(`[TOMB-TRACE] replica ${replicaId} safeExists(${tVersionPath}) \u2192 ${vExisted}`);
28599
+ log7.log(`[TOMB-TRACE] replica ${replicaId} safeExists(${tVersionPath}) \u2192 ${vExisted}`);
28511
28600
  if (vExisted) {
28512
28601
  try {
28513
- log6.log(`[TOMB-TRACE] calling unlink(${tVersionPath}) on ${replicaId}`);
28602
+ log7.log(`[TOMB-TRACE] calling unlink(${tVersionPath}) on ${replicaId}`);
28514
28603
  await replica.instance.unlink(tVersionPath);
28515
28604
  } catch (err2) {
28516
- log6.log(`[TOMB-TRACE] unlink(${tVersionPath}) on ${replicaId} FAILED: ${err2}`);
28605
+ log7.log(`[TOMB-TRACE] unlink(${tVersionPath}) on ${replicaId} FAILED: ${err2}`);
28517
28606
  }
28518
28607
  }
28519
28608
  }
28520
28609
  }
28521
28610
  }
28522
28611
  if (processed > 0 || alreadyDeleted > 0) {
28523
- log6.log(`[TOMB-TRACE] processTombstones: ${tombstones.length} tombstone(s), ${processed} deleted, ${alreadyDeleted} already gone`);
28612
+ log7.log(`[TOMB-TRACE] processTombstones: ${tombstones.length} tombstone(s), ${processed} deleted, ${alreadyDeleted} already gone`);
28524
28613
  }
28525
28614
  }
28526
28615
  /**
@@ -28536,21 +28625,21 @@ var ZenFSConfig = (() => {
28536
28625
  const innerBackendName = fs?.inner?.backendName;
28537
28626
  const directBackendName = fs?.backendName;
28538
28627
  const backendLabel = innerBackendName ?? directBackendName ?? innerBackend ?? ctorName;
28539
- log6.log(`[TOMB-TRACE] safeExists(${path}): fs type=${ctorName} backend=${backendLabel} hasExists=${hasExists} hasStat=${hasStat} inner=${innerBackend ?? "N/A"}`);
28628
+ log7.log(`[TOMB-TRACE] safeExists(${path}): fs type=${ctorName} backend=${backendLabel} hasExists=${hasExists} hasStat=${hasStat} inner=${innerBackend ?? "N/A"}`);
28540
28629
  if (hasExists) {
28541
- log6.log(`[TOMB-TRACE] safeExists(${path}): \u2192 calling fs.exists() [backend=${backendLabel}]`);
28630
+ log7.log(`[TOMB-TRACE] safeExists(${path}): \u2192 calling fs.exists() [backend=${backendLabel}]`);
28542
28631
  const result = await fs.exists(path);
28543
- log6.log(`[TOMB-TRACE] safeExists(${path}): \u2190 fs.exists() [backend=${backendLabel}] \u2192 ${result}`);
28632
+ log7.log(`[TOMB-TRACE] safeExists(${path}): \u2190 fs.exists() [backend=${backendLabel}] \u2192 ${result}`);
28544
28633
  return result;
28545
28634
  }
28546
- log6.log(`[TOMB-TRACE] safeExists(${path}): no exists(), calling fs.stat() [backend=${backendLabel}]`);
28635
+ log7.log(`[TOMB-TRACE] safeExists(${path}): no exists(), calling fs.stat() [backend=${backendLabel}]`);
28547
28636
  await fs.stat(path);
28548
- log6.log(`[TOMB-TRACE] safeExists(${path}): \u2190 fs.stat() [backend=${backendLabel}] \u2192 OK (exists)`);
28637
+ log7.log(`[TOMB-TRACE] safeExists(${path}): \u2190 fs.stat() [backend=${backendLabel}] \u2192 OK (exists)`);
28549
28638
  return true;
28550
28639
  } catch (err2) {
28551
28640
  const errCode = err2?.code ?? err2?.status ?? "";
28552
28641
  const errName = err2?.constructor?.name ?? "";
28553
- log6.log(`[TOMB-TRACE] safeExists(${path}): \u2190 ERROR ${errName} ${errCode} ${err2?.message ?? err2}`);
28642
+ log7.log(`[TOMB-TRACE] safeExists(${path}): \u2190 ERROR ${errName} ${errCode} ${err2?.message ?? err2}`);
28554
28643
  return false;
28555
28644
  }
28556
28645
  }
@@ -28577,13 +28666,13 @@ var ZenFSConfig = (() => {
28577
28666
  this.assertNotDisposed();
28578
28667
  const result = await purgeMtimeSidecars(this.cachedFS, options);
28579
28668
  if (result.removed.length > 0) {
28580
- log6.log(
28669
+ log7.log(
28581
28670
  `[ConfigRepo] purged ${result.removed.length} .mtime sidecar(s) from local primary` + (options?.dryRun ? " (dry run)" : ""),
28582
28671
  result.removed
28583
28672
  );
28584
28673
  }
28585
28674
  if (result.failed.length > 0) {
28586
- log6.warn(`[ConfigRepo] failed to purge ${result.failed.length} .mtime sidecar(s):`, result.failed);
28675
+ log7.warn(`[ConfigRepo] failed to purge ${result.failed.length} .mtime sidecar(s):`, result.failed);
28587
28676
  }
28588
28677
  return result;
28589
28678
  }
@@ -28603,13 +28692,13 @@ var ZenFSConfig = (() => {
28603
28692
  this.assertNotDisposed();
28604
28693
  const result = await purgeKeepFiles(this.cachedFS, options);
28605
28694
  if (result.removed.length > 0) {
28606
- log6.log(
28695
+ log7.log(
28607
28696
  `[ConfigRepo] purged ${result.removed.length} .keep placeholder(s) from local primary` + (options?.dryRun ? " (dry run)" : ""),
28608
28697
  result.removed
28609
28698
  );
28610
28699
  }
28611
28700
  if (result.failed.length > 0) {
28612
- log6.warn(`[ConfigRepo] failed to purge ${result.failed.length} .keep placeholder(s):`, result.failed);
28701
+ log7.warn(`[ConfigRepo] failed to purge ${result.failed.length} .keep placeholder(s):`, result.failed);
28613
28702
  }
28614
28703
  return result;
28615
28704
  }
@@ -28628,24 +28717,24 @@ var ZenFSConfig = (() => {
28628
28717
  }));
28629
28718
  const result = await migrateVersionSidecars(this.cachedFS, { replicas });
28630
28719
  if (result.renamed.length > 0) {
28631
- log6.log(
28720
+ log7.log(
28632
28721
  `[ConfigRepo] migrated ${result.renamed.length} legacy version sidecar(s) to new naming`,
28633
28722
  result.renamed
28634
28723
  );
28635
28724
  }
28636
28725
  if (result.deleted.length > 0) {
28637
- log6.log(
28726
+ log7.log(
28638
28727
  `[ConfigRepo] removed ${result.deleted.length} orphaned legacy version sidecar(s)`,
28639
28728
  result.deleted
28640
28729
  );
28641
28730
  }
28642
28731
  if (result.remoteDeleted.length > 0) {
28643
- log6.log(
28732
+ log7.log(
28644
28733
  `[ConfigRepo] removed ${result.remoteDeleted.length} remote residual legacy version sidecar(s)`
28645
28734
  );
28646
28735
  }
28647
28736
  if (result.failed.length > 0) {
28648
- log6.warn(`[ConfigRepo] failed to migrate ${result.failed.length} legacy version sidecar(s):`, result.failed);
28737
+ log7.warn(`[ConfigRepo] failed to migrate ${result.failed.length} legacy version sidecar(s):`, result.failed);
28649
28738
  }
28650
28739
  return result;
28651
28740
  }
@@ -28668,9 +28757,9 @@ var ZenFSConfig = (() => {
28668
28757
  */
28669
28758
  startBackgroundSync() {
28670
28759
  this.initialSyncPromise = this.initialSyncAndDedup().then(() => {
28671
- log6.log("[ConfigRepo] Background initial sync complete");
28760
+ log7.log("[ConfigRepo] Background initial sync complete");
28672
28761
  }).catch((err2) => {
28673
- log6.error("[ConfigRepo] Background initial sync failed:", err2);
28762
+ log7.error("[ConfigRepo] Background initial sync failed:", err2);
28674
28763
  }).finally(() => {
28675
28764
  this.initialSyncPromise = null;
28676
28765
  });
@@ -28704,7 +28793,7 @@ var ZenFSConfig = (() => {
28704
28793
  }
28705
28794
  }
28706
28795
  }
28707
- log6.log(`[ConfigRepo] updateTombstoneConfirmations: ${modified} tombstone(s) updated`);
28796
+ log7.log(`[ConfigRepo] updateTombstoneConfirmations: ${modified} tombstone(s) updated`);
28708
28797
  if (modified > 0) this.invalidateTombstoneCache();
28709
28798
  }
28710
28799
  /**
@@ -28736,7 +28825,7 @@ var ZenFSConfig = (() => {
28736
28825
  }
28737
28826
  }
28738
28827
  }
28739
- log6.log(`[ConfigRepo] gcTombstones: removed ${tombstonePath} (all ${allBackendIds.length} backends confirmed)`);
28828
+ log7.log(`[ConfigRepo] gcTombstones: removed ${tombstonePath} (all ${allBackendIds.length} backends confirmed)`);
28740
28829
  }
28741
28830
  }
28742
28831
  }
@@ -28753,7 +28842,7 @@ var ZenFSConfig = (() => {
28753
28842
  this.assertNotDisposed();
28754
28843
  const results = await this.flush();
28755
28844
  for (const result of results) {
28756
- log6.log(
28845
+ log7.log(
28757
28846
  `[ConfigRepo] syncMetaToReplicas: ${result.pairId} +${result.filesCreated}/~${result.filesUpdated}/-${result.filesDeleted} skip:${result.filesSkipped} ${result.durationMs}ms`
28758
28847
  );
28759
28848
  }
@@ -28770,6 +28859,32 @@ var ZenFSConfig = (() => {
28770
28859
  this.assertNotDisposed();
28771
28860
  return new Map(this.backendStates);
28772
28861
  }
28862
+ /**
28863
+ * Mirror per-pair `sync:error` into `getBackendSyncStates()`.
28864
+ *
28865
+ * `SyncEngine.syncAll()` catches per-pair exceptions and substitutes an empty
28866
+ * result, so a failed replica otherwise only shows up as a missing
28867
+ * `lastResult`. Recording the real error lets callers report the actual
28868
+ * status (401/403/404/timeout) instead of guessing "remote unreachable or
28869
+ * invalid credentials".
28870
+ */
28871
+ trackSyncErrors(backendId, pairId) {
28872
+ this.syncEngine.on(pairId, "sync:error", (event) => {
28873
+ const error = event.error;
28874
+ this.backendStates.set(backendId, {
28875
+ backendId,
28876
+ pairId,
28877
+ error: {
28878
+ message: error instanceof Error ? error.message : String(error ?? "sync failed"),
28879
+ timestamp: Date.now()
28880
+ }
28881
+ });
28882
+ });
28883
+ this.syncEngine.on(pairId, "sync:end", () => {
28884
+ const current = this.backendStates.get(backendId);
28885
+ if (current?.error) this.backendStates.set(backendId, { backendId, pairId });
28886
+ });
28887
+ }
28773
28888
  /** Registered replica backend descriptors (excludes the implicit local primary). */
28774
28889
  listBackends() {
28775
28890
  this.assertNotDisposed();
@@ -28900,21 +29015,21 @@ var ZenFSConfig = (() => {
28900
29015
  // Internal — Setup
28901
29016
  // -----------------------------------------------------------------------
28902
29017
  async setupSync(backends, primaryBackendId, pollIntervalMs) {
28903
- log6.log(`[ConfigRepo] setupSync: ${backends.length} backends, primary=${primaryBackendId} pollInterval=${pollIntervalMs ?? "default"}ms`);
29018
+ log7.log(`[ConfigRepo] setupSync: ${backends.length} backends, primary=${primaryBackendId} pollInterval=${pollIntervalMs ?? "default"}ms`);
28904
29019
  for (const desc of backends) {
28905
29020
  if (desc.id === primaryBackendId) continue;
28906
29021
  if (desc.enabled === false) {
28907
- log6.log(`[ConfigRepo] Skipping disabled replica: ${desc.id}`);
29022
+ log7.log(`[ConfigRepo] Skipping disabled replica: ${desc.id}`);
28908
29023
  continue;
28909
29024
  }
28910
- log6.log(`[ConfigRepo] Creating replica backend: id=${desc.id}, type=${desc.type}`);
29025
+ log7.log(`[ConfigRepo] Creating replica backend: id=${desc.id}, type=${desc.type}`);
28911
29026
  try {
28912
29027
  const instance = await createBackend(desc);
28913
29028
  let fsInstance = instance;
28914
29029
  if (this.cacheOptions) {
28915
29030
  const { wrapWithCache: wrapWithCache2 } = await Promise.resolve().then(() => (init_cache_wrapper(), cache_wrapper_exports));
28916
29031
  fsInstance = wrapWithCache2(instance, desc.id, this.cacheOptions);
28917
- log6.log(`[ConfigRepo] Replica ${desc.id} wrapped with CachedFileSystem (store=${this.cacheOptions.storeType ?? "IdbCacheStore"})`);
29032
+ log7.log(`[ConfigRepo] Replica ${desc.id} wrapped with CachedFileSystem (store=${this.cacheOptions.storeType ?? "IdbCacheStore"})`);
28918
29033
  }
28919
29034
  const syncable = backendToSyncableFS(fsInstance, `${desc.type}(${desc.id})`);
28920
29035
  const pair = this.syncEngine.addPair(
@@ -28929,7 +29044,7 @@ var ZenFSConfig = (() => {
28929
29044
  this.invalidateTombstoneCache();
28930
29045
  await this.processTombstones();
28931
29046
  } catch (err2) {
28932
- log6.warn("[ConfigRepo] preSyncHook processTombstones failed:", err2);
29047
+ log7.warn("[ConfigRepo] preSyncHook processTombstones failed:", err2);
28933
29048
  }
28934
29049
  },
28935
29050
  postSyncHook: async () => {
@@ -28938,7 +29053,7 @@ var ZenFSConfig = (() => {
28938
29053
  await this.processTombstones();
28939
29054
  await this.updateTombstoneConfirmations();
28940
29055
  } catch (err2) {
28941
- log6.warn("[ConfigRepo] postSyncHook tombstone processing failed:", err2);
29056
+ log7.warn("[ConfigRepo] postSyncHook tombstone processing failed:", err2);
28942
29057
  }
28943
29058
  }
28944
29059
  },
@@ -28950,9 +29065,10 @@ var ZenFSConfig = (() => {
28950
29065
  this.handleConflict(event);
28951
29066
  };
28952
29067
  this.syncEngine.on(pair.pairId, "conflict", conflictHandler);
28953
- log6.log(`[ConfigRepo] Replica ${desc.id} created, sync pair=${pair.pairId}`);
29068
+ this.trackSyncErrors(desc.id, pair.pairId);
29069
+ log7.log(`[ConfigRepo] Replica ${desc.id} created, sync pair=${pair.pairId}`);
28954
29070
  } catch (err2) {
28955
- log6.error(`[ConfigRepo] Failed to create replica ${desc.id} (${desc.type}):`, err2);
29071
+ log7.error(`[ConfigRepo] Failed to create replica ${desc.id} (${desc.type}):`, err2);
28956
29072
  this.backendStates.set(desc.id, {
28957
29073
  backendId: desc.id,
28958
29074
  error: {
@@ -28962,8 +29078,8 @@ var ZenFSConfig = (() => {
28962
29078
  });
28963
29079
  }
28964
29080
  }
28965
- log6.log(`[ConfigRepo] setupSync complete. Replicas:`, Array.from(this.replicaBackends.keys()));
28966
- log6.log(`[ConfigRepo] Sync statuses:`, this.getSyncStatuses());
29081
+ log7.log(`[ConfigRepo] setupSync complete. Replicas:`, Array.from(this.replicaBackends.keys()));
29082
+ log7.log(`[ConfigRepo] Sync statuses:`, this.getSyncStatuses());
28967
29083
  }
28968
29084
  // -----------------------------------------------------------------------
28969
29085
  // Internal — Persistence
@@ -28975,12 +29091,12 @@ var ZenFSConfig = (() => {
28975
29091
  try {
28976
29092
  const existing = await readVersion(this.fullFS, vPath);
28977
29093
  if (existing && existing.hash === version2.hash) {
28978
- log6.log("[ConfigRepo] skip version sidecar (hash unchanged):", vPath);
29094
+ log7.log("[ConfigRepo] skip version sidecar (hash unchanged):", vPath);
28979
29095
  return;
28980
29096
  }
28981
29097
  } catch {
28982
29098
  }
28983
- log6.log("[ConfigRepo] write version sidecar:", vPath, "v" + version2.version);
29099
+ log7.log("[ConfigRepo] write version sidecar:", vPath, "v" + version2.version);
28984
29100
  await this.ensureDir(vPath);
28985
29101
  await writeVersion(this.fullFS, vPath, version2);
28986
29102
  }
@@ -29084,7 +29200,7 @@ var ZenFSConfig = (() => {
29084
29200
  await this.resolveConflict(`${conflictId}/meta.json`, customMerge);
29085
29201
  }
29086
29202
  } catch (err2) {
29087
- log6.error("[zen-fs-config] Conflict handler error:", err2);
29203
+ log7.error("[zen-fs-config] Conflict handler error:", err2);
29088
29204
  }
29089
29205
  }
29090
29206
  }
@@ -29196,11 +29312,11 @@ var ZenFSConfig = (() => {
29196
29312
  }
29197
29313
  return { kind: "ok", desc, mtime };
29198
29314
  } else {
29199
- log6.warn(`[ConfigRepo] Backend descriptor ${entry} is missing id/type fields, marking for cleanup`);
29315
+ log7.warn(`[ConfigRepo] Backend descriptor ${entry} is missing id/type fields, marking for cleanup`);
29200
29316
  return { kind: "corrupt", filePath };
29201
29317
  }
29202
29318
  } catch (parseErr) {
29203
- log6.warn(`[ConfigRepo] Backend descriptor ${entry} has corrupted JSON: ${parseErr}. Marking for cleanup.`);
29319
+ log7.warn(`[ConfigRepo] Backend descriptor ${entry} has corrupted JSON: ${parseErr}. Marking for cleanup.`);
29204
29320
  return { kind: "corrupt", filePath };
29205
29321
  }
29206
29322
  })
@@ -29271,7 +29387,7 @@ var ZenFSConfig = (() => {
29271
29387
  }
29272
29388
  }
29273
29389
  if (duplicates.length > 0) {
29274
- log6.log(
29390
+ log7.log(
29275
29391
  `[ConfigRepo] readAllBackendDescriptors: removing ${duplicates.length} duplicate(s): ${duplicates.join(", ")}`
29276
29392
  );
29277
29393
  for (const dupId of duplicates) {
@@ -29402,7 +29518,7 @@ var ZenFSConfig = (() => {
29402
29518
  * Shared by addBackend() and replaceBackend().
29403
29519
  */
29404
29520
  async setupReplica(id, type, options, description) {
29405
- log6.log(`[ConfigRepo] addBackend: creating ${id} (${type})...`);
29521
+ log7.log(`[ConfigRepo] addBackend: creating ${id} (${type})...`);
29406
29522
  const instance = await createBackend({ type, options });
29407
29523
  const syncable = backendToSyncableFS(instance, `${type}(${id})`);
29408
29524
  const desc = { id, type, options, description };
@@ -29418,7 +29534,7 @@ var ZenFSConfig = (() => {
29418
29534
  this.invalidateTombstoneCache();
29419
29535
  await this.processTombstones();
29420
29536
  } catch (err2) {
29421
- log6.warn("[ConfigRepo] preSyncHook processTombstones failed:", err2);
29537
+ log7.warn("[ConfigRepo] preSyncHook processTombstones failed:", err2);
29422
29538
  }
29423
29539
  },
29424
29540
  postSyncHook: async () => {
@@ -29427,7 +29543,7 @@ var ZenFSConfig = (() => {
29427
29543
  await this.processTombstones();
29428
29544
  await this.updateTombstoneConfirmations();
29429
29545
  } catch (err2) {
29430
- log6.warn("[ConfigRepo] postSyncHook tombstone processing failed:", err2);
29546
+ log7.warn("[ConfigRepo] postSyncHook tombstone processing failed:", err2);
29431
29547
  }
29432
29548
  }
29433
29549
  },
@@ -29439,7 +29555,8 @@ var ZenFSConfig = (() => {
29439
29555
  this.handleConflict(event);
29440
29556
  };
29441
29557
  this.syncEngine.on(pair.pairId, "conflict", conflictHandler);
29442
- log6.log(`[ConfigRepo] addBackend: ${id} (${type}) added, sync pair=${pair.pairId}`);
29558
+ this.trackSyncErrors(id, pair.pairId);
29559
+ log7.log(`[ConfigRepo] addBackend: ${id} (${type}) added, sync pair=${pair.pairId}`);
29443
29560
  await this.syncMetaToReplicas();
29444
29561
  this.syncEngine.watch(pair.pairId);
29445
29562
  return pair.pairId;
@@ -29465,13 +29582,13 @@ var ZenFSConfig = (() => {
29465
29582
  }
29466
29583
  }
29467
29584
  this.syncEngine.removePair(replica.pairId);
29468
- log6.log(`[ConfigRepo] removeBackend: sync pair ${replica.pairId} removed`);
29585
+ log7.log(`[ConfigRepo] removeBackend: sync pair ${replica.pairId} removed`);
29469
29586
  this.replicaBackends.delete(id);
29470
29587
  if (replica.instance?.dispose) {
29471
29588
  await replica.instance.dispose();
29472
29589
  }
29473
29590
  } else {
29474
- log6.log(`[ConfigRepo] removeBackend: "${id}" not in replicaBackends, cleaning up descriptor only`);
29591
+ log7.log(`[ConfigRepo] removeBackend: "${id}" not in replicaBackends, cleaning up descriptor only`);
29475
29592
  for (const descPath of descPaths) {
29476
29593
  try {
29477
29594
  await this.deleteFile(descPath);
@@ -29482,7 +29599,7 @@ var ZenFSConfig = (() => {
29482
29599
  }
29483
29600
  this.backendStates.delete(id);
29484
29601
  this.schedulePostDeleteSync();
29485
- log6.log(`[ConfigRepo] removeBackend: ${id} removed (tombstone written, remote cleaned)`);
29602
+ log7.log(`[ConfigRepo] removeBackend: ${id} removed (tombstone written, remote cleaned)`);
29486
29603
  }
29487
29604
  /**
29488
29605
  * Replace a config-sync backend's parameters in place (same id).
@@ -29529,11 +29646,11 @@ var ZenFSConfig = (() => {
29529
29646
  await this.setupReplica(id, type, options, description ?? before.description);
29530
29647
  } catch (err2) {
29531
29648
  const reason = err2 instanceof Error ? err2.message : String(err2);
29532
- log6.warn(`[ConfigRepo] replaceBackend: "${id}" failed, rolling back old options:`, err2);
29649
+ log7.warn(`[ConfigRepo] replaceBackend: "${id}" failed, rolling back old options:`, err2);
29533
29650
  try {
29534
29651
  await this.setupReplica(id, before.type, before.options, before.description);
29535
29652
  } catch (rollbackErr) {
29536
- log6.error(`[ConfigRepo] replaceBackend: rollback for "${id}" ALSO failed:`, rollbackErr);
29653
+ log7.error(`[ConfigRepo] replaceBackend: rollback for "${id}" ALSO failed:`, rollbackErr);
29537
29654
  }
29538
29655
  throw new Error(`\u66F4\u65B0\u540E\u7AEF\u53C2\u6570\u5931\u8D25\uFF1A${reason}\uFF08\u5DF2\u5C1D\u8BD5\u56DE\u6EDA\u65E7\u53C2\u6570\uFF09`);
29539
29656
  }
@@ -29549,7 +29666,7 @@ var ZenFSConfig = (() => {
29549
29666
  const existing = await this.cachedFS.readFile(path, "utf-8");
29550
29667
  const current = existing.trim();
29551
29668
  if (current && current !== type) {
29552
- log6.warn(`[ConfigRepo] group-type already set to "${current}" at ${path}, ignoring request to set "${type}"`);
29669
+ log7.warn(`[ConfigRepo] group-type already set to "${current}" at ${path}, ignoring request to set "${type}"`);
29553
29670
  return;
29554
29671
  }
29555
29672
  } catch {
@@ -29580,7 +29697,7 @@ var ZenFSConfig = (() => {
29580
29697
  features: existingDescriptor.features ?? CONFIG_GROUP_FEATURES
29581
29698
  });
29582
29699
  }
29583
- log6.log(`[ConfigRepo] group-type set to "${type}"`);
29700
+ log7.log(`[ConfigRepo] group-type set to "${type}"`);
29584
29701
  }
29585
29702
  /** Read the group-type marker. Returns null if not set (new path, then legacy). */
29586
29703
  async getGroupType() {
@@ -29675,7 +29792,7 @@ var ZenFSConfig = (() => {
29675
29792
  if (this.appDataGroups.has(id)) {
29676
29793
  throw new Error(`App data group "${id}" already exists. Use removeAppDataGroup() first.`);
29677
29794
  }
29678
- log6.log(`[ConfigRepo] createAppDataGroup: creating "${id}" with ${backends.length} backend(s)`);
29795
+ log7.log(`[ConfigRepo] createAppDataGroup: creating "${id}" with ${backends.length} backend(s)`);
29679
29796
  const resolvedBackends = [];
29680
29797
  for (const desc of backends) {
29681
29798
  assertValidBackendId(desc.id);
@@ -29702,7 +29819,7 @@ var ZenFSConfig = (() => {
29702
29819
  };
29703
29820
  await this.writeAppDataGroupDescriptorFile(id, descriptor);
29704
29821
  this.appDataGroups.set(id, group);
29705
- log6.log(`[ConfigRepo] createAppDataGroup: "${id}" created`);
29822
+ log7.log(`[ConfigRepo] createAppDataGroup: "${id}" created`);
29706
29823
  return group;
29707
29824
  }
29708
29825
  /**
@@ -29745,7 +29862,7 @@ var ZenFSConfig = (() => {
29745
29862
  try {
29746
29863
  await live.writeOwnGroupDescriptor();
29747
29864
  } catch (err2) {
29748
- log6.warn(`[ConfigRepo] updateAppDataGroupName: "${id}" group.json update failed:`, err2);
29865
+ log7.warn(`[ConfigRepo] updateAppDataGroupName: "${id}" group.json update failed:`, err2);
29749
29866
  }
29750
29867
  }
29751
29868
  const descriptor = {
@@ -29808,7 +29925,7 @@ var ZenFSConfig = (() => {
29808
29925
  return group;
29809
29926
  } catch (err2) {
29810
29927
  const reason = err2 instanceof Error ? err2.message : String(err2);
29811
- log6.warn(`[ConfigRepo] replaceAppDataGroupBackend: "${backendId}" failed, rolling back:`, err2);
29928
+ log7.warn(`[ConfigRepo] replaceAppDataGroupBackend: "${backendId}" failed, rolling back:`, err2);
29812
29929
  try {
29813
29930
  const restored = new AppDataGroupImpl(
29814
29931
  groupId,
@@ -29822,7 +29939,7 @@ var ZenFSConfig = (() => {
29822
29939
  await this.updateAppDataGroupDescriptor(groupId, restored.listDeclaredBackends());
29823
29940
  this.appDataGroups.set(groupId, restored);
29824
29941
  } catch (rollbackErr) {
29825
- log6.error("[ConfigRepo] replaceAppDataGroupBackend: rollback ALSO failed:", rollbackErr);
29942
+ log7.error("[ConfigRepo] replaceAppDataGroupBackend: rollback ALSO failed:", rollbackErr);
29826
29943
  }
29827
29944
  throw new Error(`\u66F4\u65B0\u540E\u7AEF\u53C2\u6570\u5931\u8D25\uFF1A${reason}\uFF08\u5DF2\u5C1D\u8BD5\u56DE\u6EDA\u65E7\u53C2\u6570\uFF09`);
29828
29945
  }
@@ -29940,7 +30057,7 @@ var ZenFSConfig = (() => {
29940
30057
  try {
29941
30058
  await this.deleteFile(descPath);
29942
30059
  } catch (err2) {
29943
- log6.log(`[ConfigRepo] removeAppDataGroup: deleteFile failed for "${id}" at ${descPath}:`, err2);
30060
+ log7.log(`[ConfigRepo] removeAppDataGroup: deleteFile failed for "${id}" at ${descPath}:`, err2);
29944
30061
  try {
29945
30062
  await this.cachedFS.unlink(descPath);
29946
30063
  } catch {
@@ -29948,7 +30065,7 @@ var ZenFSConfig = (() => {
29948
30065
  await this.unlinkVersionSidecar(this.cachedFS, descPath);
29949
30066
  }
29950
30067
  }
29951
- log6.log(`[ConfigRepo] removeAppDataGroup: "${id}" removed`);
30068
+ log7.log(`[ConfigRepo] removeAppDataGroup: "${id}" removed`);
29952
30069
  }
29953
30070
  async listAccountBackends() {
29954
30071
  this.assertNotDisposed();
@@ -30123,24 +30240,24 @@ var ZenFSConfig = (() => {
30123
30240
  try {
30124
30241
  const purged = await purgeMtimeSidecars(this.localFS);
30125
30242
  if (purged.removed.length > 0) {
30126
- log6.warn(
30243
+ log7.warn(
30127
30244
  `[AppDataGroup:${this.groupId}] purged ${purged.removed.length} leaked .mtime sidecar(s):`,
30128
30245
  purged.removed
30129
30246
  );
30130
30247
  }
30131
30248
  } catch (err2) {
30132
- log6.warn(`[AppDataGroup:${this.groupId}] .mtime purge failed:`, err2?.message ?? err2);
30249
+ log7.warn(`[AppDataGroup:${this.groupId}] .mtime purge failed:`, err2?.message ?? err2);
30133
30250
  }
30134
30251
  try {
30135
30252
  const purgedKeep = await purgeKeepFiles(this.localFS);
30136
30253
  if (purgedKeep.removed.length > 0) {
30137
- log6.warn(
30254
+ log7.warn(
30138
30255
  `[AppDataGroup:${this.groupId}] purged ${purgedKeep.removed.length} leaked .keep placeholder(s):`,
30139
30256
  purgedKeep.removed
30140
30257
  );
30141
30258
  }
30142
30259
  } catch (err2) {
30143
- log6.warn(`[AppDataGroup:${this.groupId}] .keep purge failed:`, err2?.message ?? err2);
30260
+ log7.warn(`[AppDataGroup:${this.groupId}] .keep purge failed:`, err2?.message ?? err2);
30144
30261
  }
30145
30262
  const localSyncable = backendToSyncableFS(this.localFS, `local(${this.groupId})`);
30146
30263
  this.tombstones = new TombstoneStore(this.localFS, this.localBackendId);
@@ -30150,13 +30267,13 @@ var ZenFSConfig = (() => {
30150
30267
  try {
30151
30268
  backendsChanged = await this.loadBackendDescriptors();
30152
30269
  } catch (err2) {
30153
- log6.warn(`[AppDataGroup:${this.groupId}] failed to load .meta/backends:`, err2);
30270
+ log7.warn(`[AppDataGroup:${this.groupId}] failed to load .meta/backends:`, err2);
30154
30271
  this._backends = this._backends ?? [];
30155
30272
  }
30156
30273
  try {
30157
30274
  await this.writeOwnGroupDescriptor();
30158
30275
  } catch (err2) {
30159
- log6.warn(`[AppDataGroup:${this.groupId}] failed to write .meta/group.json:`, err2);
30276
+ log7.warn(`[AppDataGroup:${this.groupId}] failed to write .meta/group.json:`, err2);
30160
30277
  }
30161
30278
  this.fs = createChrootFS(this.localFS, "/", {
30162
30279
  hiddenPrefixes: [META_DIR, CONFIG_DIR],
@@ -30166,7 +30283,7 @@ var ZenFSConfig = (() => {
30166
30283
  });
30167
30284
  const { kept, removed } = dedupeAppDataBackends(this._backends);
30168
30285
  if (removed.length > 0) {
30169
- log6.warn(
30286
+ log7.warn(
30170
30287
  `[AppDataGroup:${this.groupId}] dedupe: removing ${removed.length} duplicate backend(s) (${removed.map((b) => b.id).join(", ")}) \u2014 keeping ${kept.map((b) => b.id).join(", ")}`
30171
30288
  );
30172
30289
  this._backends = kept;
@@ -30180,7 +30297,7 @@ var ZenFSConfig = (() => {
30180
30297
  features: this._declaredFeatures
30181
30298
  });
30182
30299
  } catch (err2) {
30183
- log6.warn(`[AppDataGroup:${this.groupId}] failed to persist backend topology:`, err2);
30300
+ log7.warn(`[AppDataGroup:${this.groupId}] failed to persist backend topology:`, err2);
30184
30301
  }
30185
30302
  }
30186
30303
  for (const desc of this._backends) {
@@ -30212,25 +30329,26 @@ var ZenFSConfig = (() => {
30212
30329
  if (this.features.conflicts) {
30213
30330
  const conflictHandler = (event) => {
30214
30331
  this.archiveConflict(event).catch((err2) => {
30215
- log6.warn(`[AppDataGroup:${this.groupId}] conflict archive failed:`, err2);
30332
+ log7.warn(`[AppDataGroup:${this.groupId}] conflict archive failed:`, err2);
30216
30333
  });
30217
30334
  };
30218
30335
  this.syncEngine.on(pair.pairId, "conflict", conflictHandler);
30219
30336
  }
30220
- log6.log(`[AppDataGroup:${this.groupId}] backend ${desc.id} (${desc.type}) connected, pair=${pair.pairId}`);
30337
+ this.trackSyncErrors(desc.id, pair.pairId);
30338
+ log7.log(`[AppDataGroup:${this.groupId}] backend ${desc.id} (${desc.type}) connected, pair=${pair.pairId}`);
30221
30339
  } catch (err2) {
30222
30340
  const message = err2 instanceof Error ? err2.message : String(err2);
30223
30341
  this.backendStates.set(desc.id, {
30224
30342
  backendId: desc.id,
30225
30343
  error: { message, timestamp: Date.now() }
30226
30344
  });
30227
- log6.error(`[AppDataGroup:${this.groupId}] Failed to create backend ${desc.id} (${desc.type}):`, err2);
30345
+ log7.error(`[AppDataGroup:${this.groupId}] Failed to create backend ${desc.id} (${desc.type}):`, err2);
30228
30346
  }
30229
30347
  }
30230
30348
  try {
30231
30349
  await this.syncEngine.syncAll();
30232
30350
  } catch (err2) {
30233
- log6.warn(`[AppDataGroup:${this.groupId}] Initial sync failed:`, err2);
30351
+ log7.warn(`[AppDataGroup:${this.groupId}] Initial sync failed:`, err2);
30234
30352
  }
30235
30353
  this.syncEngine.watchAll();
30236
30354
  }
@@ -30245,13 +30363,31 @@ var ZenFSConfig = (() => {
30245
30363
  try {
30246
30364
  await this.tombstones.gc(this.allBackendIds(), this.tombstoneTargets());
30247
30365
  } catch (err2) {
30248
- log6.warn(`[AppDataGroup:${this.groupId}] tombstone GC failed:`, err2);
30366
+ log7.warn(`[AppDataGroup:${this.groupId}] tombstone GC failed:`, err2);
30249
30367
  }
30250
30368
  return Array.from(results.values());
30251
30369
  }
30252
30370
  getBackendSyncStates() {
30253
30371
  return new Map(this.backendStates);
30254
30372
  }
30373
+ /** Mirror per-pair `sync:error` into `getBackendSyncStates()` (see ConfigRepo). */
30374
+ trackSyncErrors(backendId, pairId) {
30375
+ this.syncEngine.on(pairId, "sync:error", (event) => {
30376
+ const error = event.error;
30377
+ this.backendStates.set(backendId, {
30378
+ backendId,
30379
+ pairId,
30380
+ error: {
30381
+ message: error instanceof Error ? error.message : String(error ?? "sync failed"),
30382
+ timestamp: Date.now()
30383
+ }
30384
+ });
30385
+ });
30386
+ this.syncEngine.on(pairId, "sync:end", () => {
30387
+ const current = this.backendStates.get(backendId);
30388
+ if (current?.error) this.backendStates.set(backendId, { backendId, pairId });
30389
+ });
30390
+ }
30255
30391
  // -----------------------------------------------------------------------
30256
30392
  // Unified SyncGroupHandle — deletion & metadata (data groups)
30257
30393
  // -----------------------------------------------------------------------
@@ -30262,7 +30398,7 @@ var ZenFSConfig = (() => {
30262
30398
  const bytes = typeof data === "string" ? new TextEncoder().encode(data) : toUint8Array2(data);
30263
30399
  await this.versions.record(path, bytes);
30264
30400
  } catch (err2) {
30265
- log6.warn(`[AppDataGroup:${this.groupId}] version record failed for ${path}:`, err2);
30401
+ log7.warn(`[AppDataGroup:${this.groupId}] version record failed for ${path}:`, err2);
30266
30402
  }
30267
30403
  }
30268
30404
  /** Delete tombstoned files on local + every connected backend before/after sync. */
@@ -30270,14 +30406,14 @@ var ZenFSConfig = (() => {
30270
30406
  try {
30271
30407
  await this.tombstones.process(this.tombstoneTargets());
30272
30408
  } catch (err2) {
30273
- log6.warn(`[AppDataGroup:${this.groupId}] ${stage} tombstone pass failed:`, err2);
30409
+ log7.warn(`[AppDataGroup:${this.groupId}] ${stage} tombstone pass failed:`, err2);
30274
30410
  }
30275
30411
  }
30276
30412
  async confirmTombstones() {
30277
30413
  try {
30278
30414
  await this.tombstones.confirm(this.allBackendIds());
30279
30415
  } catch (err2) {
30280
- log6.warn(`[AppDataGroup:${this.groupId}] tombstone confirmations failed:`, err2);
30416
+ log7.warn(`[AppDataGroup:${this.groupId}] tombstone confirmations failed:`, err2);
30281
30417
  }
30282
30418
  }
30283
30419
  /** Write a tombstone for `filePath`. Records metadata only — it never creates the file. */
@@ -30310,7 +30446,7 @@ var ZenFSConfig = (() => {
30310
30446
  }
30311
30447
  await removeDirectoryTree(this.localFS, normalized);
30312
30448
  this.schedulePostDeleteSync();
30313
- log6.log(`[AppDataGroup:${this.groupId}] deleteFile(directory): ${normalized} (${files.length} file(s))`);
30449
+ log7.log(`[AppDataGroup:${this.groupId}] deleteFile(directory): ${normalized} (${files.length} file(s))`);
30314
30450
  return;
30315
30451
  }
30316
30452
  await this.writeTombstoneFor(normalized);
@@ -30349,7 +30485,7 @@ var ZenFSConfig = (() => {
30349
30485
  try {
30350
30486
  await this.syncEngine.syncAll();
30351
30487
  } catch (err2) {
30352
- log6.warn(`[AppDataGroup:${this.groupId}] sync after conflict resolve failed:`, err2);
30488
+ log7.warn(`[AppDataGroup:${this.groupId}] sync after conflict resolve failed:`, err2);
30353
30489
  }
30354
30490
  }
30355
30491
  readConflictBackup(conflictId, fileType) {
@@ -30384,7 +30520,7 @@ var ZenFSConfig = (() => {
30384
30520
  if (this.dataBackends.has(id)) {
30385
30521
  throw new Error(`Backend "${id}" already exists in data group "${this.groupId}"`);
30386
30522
  }
30387
- log6.log(`[AppDataGroup:${this.groupId}] addBackend: creating ${id} (${type})...`);
30523
+ log7.log(`[AppDataGroup:${this.groupId}] addBackend: creating ${id} (${type})...`);
30388
30524
  const instance = await createBackend({ type, options });
30389
30525
  const syncable = backendToSyncableFS(instance, `${type}(${id})`);
30390
30526
  const localSyncable = backendToSyncableFS(this.localFS, `local(${this.groupId})`);
@@ -30412,12 +30548,13 @@ var ZenFSConfig = (() => {
30412
30548
  if (this.features.conflicts) {
30413
30549
  this.syncEngine.on(pair.pairId, "conflict", (event) => {
30414
30550
  this.archiveConflict(event).catch((err2) => {
30415
- log6.warn(`[AppDataGroup:${this.groupId}] conflict archive failed:`, err2);
30551
+ log7.warn(`[AppDataGroup:${this.groupId}] conflict archive failed:`, err2);
30416
30552
  });
30417
30553
  });
30418
30554
  }
30555
+ this.trackSyncErrors(id, pair.pairId);
30419
30556
  this._backends = [...this._backends.filter((b) => b.id !== id), desc];
30420
- log6.log(`[AppDataGroup:${this.groupId}] addBackend: ${id} (${type}) connected, pair=${pair.pairId}`);
30557
+ log7.log(`[AppDataGroup:${this.groupId}] addBackend: ${id} (${type}) connected, pair=${pair.pairId}`);
30421
30558
  try {
30422
30559
  const stale = (await this.tombstones.list()).find(
30423
30560
  (t) => t.path === backendMetaFilePath(id)
@@ -30425,12 +30562,12 @@ var ZenFSConfig = (() => {
30425
30562
  if (stale) await this.tombstones.remove(stale);
30426
30563
  await writeBackendMetaDescriptor(this.localFS, desc);
30427
30564
  } catch (err2) {
30428
- log6.warn(`[AppDataGroup:${this.groupId}] addBackend: failed to write .meta/backends/${id}.json:`, err2);
30565
+ log7.warn(`[AppDataGroup:${this.groupId}] addBackend: failed to write .meta/backends/${id}.json:`, err2);
30429
30566
  }
30430
30567
  try {
30431
30568
  await this.syncEngine.sync(pair.pairId);
30432
30569
  } catch (err2) {
30433
- log6.warn(`[AppDataGroup:${this.groupId}] addBackend: initial sync failed for ${id}:`, err2);
30570
+ log7.warn(`[AppDataGroup:${this.groupId}] addBackend: initial sync failed for ${id}:`, err2);
30434
30571
  }
30435
30572
  this.syncEngine.watch(pair.pairId);
30436
30573
  await this.parent.updateAppDataGroupDescriptor(this.groupId, this._backends, {
@@ -30461,7 +30598,7 @@ var ZenFSConfig = (() => {
30461
30598
  if (backend?.instance?.dispose) {
30462
30599
  await backend.instance.dispose();
30463
30600
  }
30464
- log6.log(`[AppDataGroup:${this.groupId}] removeBackend: ${id} removed`);
30601
+ log7.log(`[AppDataGroup:${this.groupId}] removeBackend: ${id} removed`);
30465
30602
  }
30466
30603
  listBackends() {
30467
30604
  return Array.from(this.dataBackends.values()).map((b) => b.desc);
@@ -30503,44 +30640,44 @@ var ZenFSConfig = (() => {
30503
30640
  idbStoreName: options.idbStoreName,
30504
30641
  folderPath: options.folderPath
30505
30642
  });
30506
- log6.log(`[createConfigRepo] Creating local primary (type: ${localPrimary.type})...`);
30643
+ log7.log(`[createConfigRepo] Creating local primary (type: ${localPrimary.type})...`);
30507
30644
  const primaryInstance = await createBackend(localPrimary);
30508
30645
  const cachedFS = primaryInstance;
30509
30646
  if (options.purgeMtimeSidecars !== false) {
30510
30647
  try {
30511
30648
  const purged = await purgeMtimeSidecars(cachedFS);
30512
30649
  if (purged.removed.length > 0) {
30513
- log6.warn(
30650
+ log7.warn(
30514
30651
  `[createConfigRepo] purged ${purged.removed.length} leaked .mtime sidecar(s) from local primary:`,
30515
30652
  purged.removed
30516
30653
  );
30517
30654
  }
30518
30655
  } catch (err2) {
30519
- log6.warn(`[createConfigRepo] .mtime purge failed:`, err2?.message ?? err2);
30656
+ log7.warn(`[createConfigRepo] .mtime purge failed:`, err2?.message ?? err2);
30520
30657
  }
30521
30658
  }
30522
30659
  if (options.purgeKeepFiles !== false) {
30523
30660
  try {
30524
30661
  const purged = await purgeKeepFiles(cachedFS);
30525
30662
  if (purged.removed.length > 0) {
30526
- log6.warn(
30663
+ log7.warn(
30527
30664
  `[createConfigRepo] purged ${purged.removed.length} leaked .keep placeholder(s) from local primary:`,
30528
30665
  purged.removed
30529
30666
  );
30530
30667
  }
30531
30668
  } catch (err2) {
30532
- log6.warn(`[createConfigRepo] .keep purge failed:`, err2?.message ?? err2);
30669
+ log7.warn(`[createConfigRepo] .keep purge failed:`, err2?.message ?? err2);
30533
30670
  }
30534
30671
  }
30535
30672
  const cacheOptions = options.cache === false ? void 0 : options.cache ?? {};
30536
30673
  try {
30537
30674
  await primaryInstance.mkdir(META_DIR);
30538
- log6.log(`[createConfigRepo] /.meta/ ready`);
30675
+ log7.log(`[createConfigRepo] /.meta/ ready`);
30539
30676
  } catch (err2) {
30540
30677
  const msg = err2.message || "";
30541
30678
  if (msg.includes("File exists") || msg.includes("EEXIST") || err2.code === "EEXIST") {
30542
30679
  } else {
30543
- log6.error(`[createConfigRepo] Failed to ensure /.meta/:`, err2.message);
30680
+ log7.error(`[createConfigRepo] Failed to ensure /.meta/:`, err2.message);
30544
30681
  }
30545
30682
  }
30546
30683
  try {
@@ -30551,7 +30688,7 @@ var ZenFSConfig = (() => {
30551
30688
  } catch {
30552
30689
  await ensureParentDir2(primaryInstance, path);
30553
30690
  await primaryInstance.writeFile(path, groupTypeBytes);
30554
- log6.log(`[createConfigRepo] group-type set to "config-sync" at ${path}`);
30691
+ log7.log(`[createConfigRepo] group-type set to "config-sync" at ${path}`);
30555
30692
  }
30556
30693
  }
30557
30694
  if (!await readGroupDescriptor(primaryInstance)) {
@@ -30563,7 +30700,7 @@ var ZenFSConfig = (() => {
30563
30700
  });
30564
30701
  }
30565
30702
  } catch (err2) {
30566
- log6.warn(`[createConfigRepo] Failed to write group metadata:`, err2.message);
30703
+ log7.warn(`[createConfigRepo] Failed to write group metadata:`, err2.message);
30567
30704
  }
30568
30705
  const tempRepo = new ConfigRepo(
30569
30706
  appId,
@@ -30577,11 +30714,11 @@ var ZenFSConfig = (() => {
30577
30714
  );
30578
30715
  const oldBackendsMeta = await tempRepo.readMetaFile(BACKENDS_FILE);
30579
30716
  if (oldBackendsMeta && oldBackendsMeta.backends?.length > 0) {
30580
- log6.log(`[createConfigRepo] Migrating ${oldBackendsMeta.backends.length} backend(s) from backends.json to individual files...`);
30717
+ log7.log(`[createConfigRepo] Migrating ${oldBackendsMeta.backends.length} backend(s) from backends.json to individual files...`);
30581
30718
  await tempRepo.ensureDir(`${BACKENDS_DIR}/.keep`);
30582
30719
  for (const desc of oldBackendsMeta.backends) {
30583
30720
  if (desc.id === LOCAL_IDB_BACKEND_ID) {
30584
- log6.log(`[createConfigRepo] Skipping local backend ${desc.id} during migration`);
30721
+ log7.log(`[createConfigRepo] Skipping local backend ${desc.id} during migration`);
30585
30722
  continue;
30586
30723
  }
30587
30724
  await tempRepo.writeBackendDescriptor(desc);
@@ -30599,7 +30736,7 @@ var ZenFSConfig = (() => {
30599
30736
  }
30600
30737
  }
30601
30738
  }
30602
- log6.log(`[createConfigRepo] Migration complete`);
30739
+ log7.log(`[createConfigRepo] Migration complete`);
30603
30740
  }
30604
30741
  let allBackends = await tempRepo.readAllBackendDescriptors();
30605
30742
  if (options.backendInfo) {
@@ -30617,19 +30754,19 @@ var ZenFSConfig = (() => {
30617
30754
  type: options.backendInfo.type,
30618
30755
  options: options.backendInfo.options
30619
30756
  });
30620
- log6.log(`[createConfigRepo] Added replica backend: ${replicaId} (${options.backendInfo.type})`);
30757
+ log7.log(`[createConfigRepo] Added replica backend: ${replicaId} (${options.backendInfo.type})`);
30621
30758
  allBackends = [...allBackends, { id: replicaId, type: options.backendInfo.type, options: options.backendInfo.options }];
30622
30759
  } else if (dupConfig) {
30623
- log6.log(`[createConfigRepo] Replica with same config already registered as "${dupConfig.id}", skipping`);
30760
+ log7.log(`[createConfigRepo] Replica with same config already registered as "${dupConfig.id}", skipping`);
30624
30761
  } else {
30625
- log6.log(`[createConfigRepo] Replica ${replicaId} already registered`);
30762
+ log7.log(`[createConfigRepo] Replica ${replicaId} already registered`);
30626
30763
  }
30627
30764
  }
30628
- log6.log(`[createConfigRepo] Replica backends: ${allBackends.map((b) => b.id).join(", ") || "(none)"}`);
30765
+ log7.log(`[createConfigRepo] Replica backends: ${allBackends.map((b) => b.id).join(", ") || "(none)"}`);
30629
30766
  let nodeId = options.nodeId;
30630
30767
  if (!nodeId) {
30631
30768
  nodeId = `node-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
30632
- log6.log(`[createConfigRepo] Generated nodeId: ${nodeId}`);
30769
+ log7.log(`[createConfigRepo] Generated nodeId: ${nodeId}`);
30633
30770
  }
30634
30771
  const serializer = createSerializerChain(options.serializer);
30635
30772
  const repo = new ConfigRepo(
@@ -30652,30 +30789,30 @@ var ZenFSConfig = (() => {
30652
30789
  try {
30653
30790
  const mig = await repo.migrateLegacyVersionSidecars();
30654
30791
  if (mig.renamed.length === 0 && mig.deleted.length === 0 && mig.remoteDeleted.length === 0) {
30655
- log6.log("[createConfigRepo] no legacy version sidecars to migrate");
30792
+ log7.log("[createConfigRepo] no legacy version sidecars to migrate");
30656
30793
  }
30657
30794
  } catch (err2) {
30658
- log6.warn(`[createConfigRepo] version sidecar migration failed:`, err2?.message ?? err2);
30795
+ log7.warn(`[createConfigRepo] version sidecar migration failed:`, err2?.message ?? err2);
30659
30796
  }
30660
30797
  }
30661
30798
  await repo.load();
30662
30799
  if (repo.replicaCount > 0) {
30663
- log6.log("[createConfigRepo] Starting background initial sync + dedup...");
30800
+ log7.log("[createConfigRepo] Starting background initial sync + dedup...");
30664
30801
  repo.startBackgroundSync();
30665
30802
  }
30666
30803
  repo.syncMetaToReplicas().catch((err2) => {
30667
- log6.error("[createConfigRepo] background syncMetaToReplicas failed:", err2);
30804
+ log7.error("[createConfigRepo] background syncMetaToReplicas failed:", err2);
30668
30805
  });
30669
30806
  return repo;
30670
30807
  }
30671
30808
 
30672
30809
  // src/connect.ts
30673
30810
  init_backend_registry();
30674
- var log7 = createLogger3("connect");
30811
+ var log8 = createLogger3("connect");
30675
30812
  var GROUP_TYPE_FILE2 = "/.config/group-type";
30676
30813
  var LEGACY_GROUP_TYPE_FILE2 = "/.meta/group-type";
30677
30814
  async function detectGroupType(type, options) {
30678
- log7(`detectGroupType: connecting to ${type}...`);
30815
+ log8(`detectGroupType: connecting to ${type}...`);
30679
30816
  const tempBackend = await createBackend({ type, options });
30680
30817
  try {
30681
30818
  for (const path of [GROUP_TYPE_FILE2, LEGACY_GROUP_TYPE_FILE2]) {
@@ -30683,15 +30820,15 @@ var ZenFSConfig = (() => {
30683
30820
  const raw = await tempBackend.readFile(path, "utf-8");
30684
30821
  const groupType = raw.trim();
30685
30822
  if (groupType === "config-sync" || groupType === "data-sync") {
30686
- log7(`detectGroupType: detected "${groupType}" at ${path}`);
30823
+ log8(`detectGroupType: detected "${groupType}" at ${path}`);
30687
30824
  return groupType;
30688
30825
  }
30689
- log7(`detectGroupType: unknown group-type value "${groupType}" at ${path}, treating as null`);
30826
+ log8(`detectGroupType: unknown group-type value "${groupType}" at ${path}, treating as null`);
30690
30827
  return null;
30691
30828
  } catch {
30692
30829
  }
30693
30830
  }
30694
- log7(`detectGroupType: no group-type file found (new backend)`);
30831
+ log8(`detectGroupType: no group-type file found (new backend)`);
30695
30832
  return null;
30696
30833
  } finally {
30697
30834
  if (tempBackend?.dispose) {
@@ -30700,7 +30837,7 @@ var ZenFSConfig = (() => {
30700
30837
  }
30701
30838
  }
30702
30839
  async function connect(appId, options = {}) {
30703
- log7(`connect: appId=${appId}`);
30840
+ log8(`connect: appId=${appId}`);
30704
30841
  if (!options.backendInfo) {
30705
30842
  const repo2 = await createConfigRepo(appId, {
30706
30843
  idbStoreName: options.idbStoreName,
@@ -30718,7 +30855,7 @@ var ZenFSConfig = (() => {
30718
30855
  try {
30719
30856
  appDataGroups2.push(await repo2.getAppDataGroup(d.id));
30720
30857
  } catch (err2) {
30721
- log7(`connect: failed to load app data group "${d.id}":`, err2);
30858
+ log8(`connect: failed to load app data group "${d.id}":`, err2);
30722
30859
  }
30723
30860
  }
30724
30861
  let dataGroup2 = appDataGroups2[0];
@@ -30747,7 +30884,7 @@ var ZenFSConfig = (() => {
30747
30884
  groupType = detectedType;
30748
30885
  } else {
30749
30886
  groupType = options.groupType ?? "config-sync";
30750
- log7(`connect: new backend, using groupType="${groupType}"`);
30887
+ log8(`connect: new backend, using groupType="${groupType}"`);
30751
30888
  }
30752
30889
  const repo = await createConfigRepo(
30753
30890
  appId,
@@ -30776,7 +30913,7 @@ var ZenFSConfig = (() => {
30776
30913
  try {
30777
30914
  appDataGroups.push(await repo.getAppDataGroup(d.id));
30778
30915
  } catch (err2) {
30779
- log7(`connect: failed to load app data group "${d.id}":`, err2);
30916
+ log8(`connect: failed to load app data group "${d.id}":`, err2);
30780
30917
  }
30781
30918
  }
30782
30919
  let dataGroup = appDataGroups[0];