zen-fs-config 0.9.2 → 0.9.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.
@@ -25454,13 +25454,24 @@ var ZenFSConfig = (() => {
25454
25454
  // src/index.ts
25455
25455
  var src_exports = {};
25456
25456
  __export(src_exports, {
25457
+ BackendAlreadyExistsError: () => BackendAlreadyExistsError,
25458
+ BackendEndpointConflictError: () => BackendEndpointConflictError,
25459
+ BackendIdentityError: () => BackendIdentityError,
25457
25460
  CONFIG_DIR: () => CONFIG_DIR,
25458
25461
  CONFLICTS_DIR: () => CONFLICTS_DIR,
25462
+ ConfigNotReadyError: () => ConfigNotReadyError,
25459
25463
  ConfigRepo: () => ConfigRepo,
25460
25464
  ConflictStore: () => ConflictStore,
25465
+ ConnectFailedError: () => ConnectFailedError,
25466
+ ConnectV2Error: () => ConnectV2Error,
25461
25467
  DATA_GROUP_DEFAULT_FEATURES: () => DATA_GROUP_DEFAULT_FEATURES,
25468
+ DataGroupBackendError: () => DataGroupBackendError,
25469
+ DataGroupCreateError: () => DataGroupCreateError,
25470
+ DataGroupNotFoundError: () => DataGroupNotFoundError,
25471
+ DataGroupOperationError: () => DataGroupOperationError,
25462
25472
  FolderStore: () => FolderStore,
25463
25473
  GROUP_DESCRIPTOR_FILE: () => GROUP_DESCRIPTOR_FILE2,
25474
+ InvalidBackendError: () => InvalidBackendError,
25464
25475
  LEGACY_CONFLICTS_DIR: () => LEGACY_CONFLICTS_DIR,
25465
25476
  LEGACY_TOMBSTONES_DIR: () => LEGACY_TOMBSTONES_DIR,
25466
25477
  LOCAL_IDB_BACKEND_ID: () => LOCAL_IDB_BACKEND_ID,
@@ -25477,6 +25488,8 @@ var ZenFSConfig = (() => {
25477
25488
  bindRemoteGroupIdentityDetailed: () => bindRemoteGroupIdentityDetailed,
25478
25489
  configKeyToFilePath: () => configKeyToFilePath,
25479
25490
  connect: () => connect,
25491
+ connectV2: () => connectV2,
25492
+ connectionToAppRepo: () => connectionToAppRepo,
25480
25493
  createBackend: () => createBackend,
25481
25494
  createConfigRepo: () => createConfigRepo,
25482
25495
  createSerializerChain: () => createSerializerChain,
@@ -25487,6 +25500,7 @@ var ZenFSConfig = (() => {
25487
25500
  getAccountFields: () => getAccountFields,
25488
25501
  getBackendMetadata: () => getBackendMetadata,
25489
25502
  getExtension: () => getExtension,
25503
+ getUiConnection: () => getUiConnection,
25490
25504
  hasBackend: () => hasBackend,
25491
25505
  incrementVersion: () => incrementVersion,
25492
25506
  isBrowserEnv: () => isBrowserEnv,
@@ -28869,6 +28883,11 @@ var ZenFSConfig = (() => {
28869
28883
  }
28870
28884
  }
28871
28885
  var log9 = createLogger("zen-fs-config:config-repo");
28886
+ function isMissingDescriptorError(err2) {
28887
+ if (isNotFoundError2(err2)) return true;
28888
+ const message = String(err2?.message ?? err2 ?? "");
28889
+ return /(^|\W)404(\W|$)|not found|no such file|不存在/i.test(message);
28890
+ }
28872
28891
  var GROUP_DESCRIPTOR_FILE3 = `${META_DIR}/group.json`;
28873
28892
  var GROUP_TYPE_FILE = `${CONFIG_DIR}/group-type`;
28874
28893
  var LEGACY_GROUP_TYPE_FILE = `${META_DIR}/group-type`;
@@ -29080,6 +29099,14 @@ var ZenFSConfig = (() => {
29080
29099
  __publicField(this, "backendConflicts", /* @__PURE__ */ new Map());
29081
29100
  /** Last known backend descriptors, for the synchronous unified handle API. */
29082
29101
  __publicField(this, "backendDescriptorCache", []);
29102
+ /**
29103
+ * 本会话内被用户**显式**清空后端的数据组 id。
29104
+ *
29105
+ * 只有这类组允许把「0 个后端」的引导副本推给远端;启动时读到的空副本
29106
+ * (历史脏数据、或「清空本页配置」后本地新建的空组)绝不覆盖远端既有拓扑,
29107
+ * 见 `healEmptyBootstrapDescriptors()`。
29108
+ */
29109
+ __publicField(this, "explicitEmptyDescriptors", /* @__PURE__ */ new Set());
29083
29110
  /**
29084
29111
  * Tracks the background initial sync started by createConfigRepo().
29085
29112
  * `flush()` and `dispose()` will await this if it hasn't completed yet,
@@ -29268,6 +29295,7 @@ var ZenFSConfig = (() => {
29268
29295
  this.initialSyncPromise = null;
29269
29296
  }
29270
29297
  await this.processTombstones();
29298
+ await this.healEmptyBootstrapDescriptors();
29271
29299
  const resultsMap = await this.syncEngine.syncAll();
29272
29300
  this.invalidateTombstoneCache();
29273
29301
  await this.readAllBackendDescriptors();
@@ -29769,6 +29797,7 @@ var ZenFSConfig = (() => {
29769
29797
  */
29770
29798
  async initialSyncAndDedup() {
29771
29799
  this.syncEngine.unwatchAll();
29800
+ await this.healEmptyBootstrapDescriptors();
29772
29801
  await this.syncEngine.syncAll();
29773
29802
  await this.readAllBackendDescriptors();
29774
29803
  await this.processTombstones();
@@ -31331,6 +31360,41 @@ var ZenFSConfig = (() => {
31331
31360
  }
31332
31361
  return mergeAccountFields(desc.type, accountBackend.options, desc.options);
31333
31362
  }
31363
+ /**
31364
+ * 读一个数据组后端根上的 `.meta/group.json`(只读,不写、不建同步对)。
31365
+ *
31366
+ * `null` = 空仓库(可以认领);抛错 = 读不到(调用方必须 fail-closed)。
31367
+ * 复用的实例由调用方负责 dispose。
31368
+ */
31369
+ async readRemoteGroupDescriptor(desc, instance) {
31370
+ const own = instance ?? await createBackend({ type: desc.type, options: desc.options });
31371
+ try {
31372
+ return await withTimeout(
31373
+ readGroupDescriptorStrict(own),
31374
+ REPLICA_SETUP_TIMEOUT_MS,
31375
+ `\u6570\u636E\u7EC4\u540E\u7AEF ${desc.id} \u8BFB group.json`
31376
+ );
31377
+ } finally {
31378
+ if (!instance) {
31379
+ try {
31380
+ await own?.dispose?.();
31381
+ } catch {
31382
+ }
31383
+ }
31384
+ }
31385
+ }
31386
+ /**
31387
+ * 同一个远端目录只能归一个组。`.meta/group.json` 里的 `kind`/`id` 就是归属
31388
+ * 记录 —— 它与「本地方知不知道这个组」无关,描述符丢了也照样能判定。
31389
+ */
31390
+ assertRemoteNotOwnedByOthers(remote, backendId, ownerId) {
31391
+ if (!remote) return;
31392
+ if (remote.kind === "data" && remote.id === ownerId) return;
31393
+ const who = remote.kind === "data" ? `\u6570\u636E\u7EC4\u300C${remote.id}\u300D${remote.instanceId ? `\uFF08instanceId=${remote.instanceId}\uFF09` : ""}` : `\u914D\u7F6E\u540C\u6B65\u7EC4\uFF08kind=${remote.kind ?? "\u672A\u77E5"}${remote.id ? `\uFF0Cid=${remote.id}` : ""}\uFF09`;
31394
+ throw new Error(
31395
+ `\u540E\u7AEF\u300C${backendId}\u300D\u6307\u5411\u7684\u8FDC\u7AEF\u76EE\u5F55\u5DF2\u88AB${who}\u5360\u7528\uFF1A\u540C\u4E00\u4E2A\u8FDC\u7AEF\u76EE\u5F55\u4E0D\u80FD\u5F52\u4E24\u4E2A\u7EC4\uFF08\u5426\u5219\u4E24\u6761\u540C\u6B65\u94FE\u4F1A\u4E92\u76F8\u6539\u5199\u8EAB\u4EFD\u3001\u7248\u672C\u4E0E\u5893\u7891\uFF09\u3002\u8BF7\u76F4\u63A5\u52A0\u8F7D\u8BE5\u7EC4\uFF0C\u6216\u4E3A\u5B83\u6539\u7528\u4E0D\u540C\u7684 basePath/repo`
31396
+ );
31397
+ }
31334
31398
  /**
31335
31399
  * Reject two groups pointing at the exact same remote endpoint. Two groups
31336
31400
  * syncing the same files independently would fight over deletions and
@@ -31356,6 +31420,37 @@ var ZenFSConfig = (() => {
31356
31420
  }
31357
31421
  }
31358
31422
  }
31423
+ for (const backend of backends) {
31424
+ if (backend.type === localPrimaryType()) continue;
31425
+ let instance;
31426
+ try {
31427
+ instance = await withTimeout(
31428
+ createBackend({ type: backend.type, options: backend.options }),
31429
+ REPLICA_SETUP_TIMEOUT_MS,
31430
+ `\u6570\u636E\u7EC4\u540E\u7AEF ${backend.id} \u521B\u5EFA\u5B9E\u4F8B\uFF08\u5F52\u5C5E\u63A2\u6D4B\uFF09`
31431
+ );
31432
+ } catch (err2) {
31433
+ log9.warn(
31434
+ `[ConfigRepo] assertNoSharedRemote: \u65E0\u6CD5\u521B\u5EFA\u540E\u7AEF\u300C${backend.id}\u300D\uFF08${err2?.message ?? String(err2)}\uFF09\uFF0C\u8DF3\u8FC7\u8FDC\u7AEF\u5F52\u5C5E\u63A2\u6D4B`
31435
+ );
31436
+ continue;
31437
+ }
31438
+ let remote;
31439
+ try {
31440
+ remote = await this.readRemoteGroupDescriptor(backend, instance);
31441
+ } catch (err2) {
31442
+ if (isMissingDescriptorError(err2)) continue;
31443
+ throw new Error(
31444
+ `\u65E0\u6CD5\u8BFB\u53D6\u540E\u7AEF\u300C${backend.id}\u300D\u7684\u8FDC\u7AEF .meta/group.json\uFF08${err2?.message ?? String(err2)}\uFF09\uFF1A\u65E0\u6CD5\u5224\u65AD\u8BE5\u8FDC\u7AEF\u76EE\u5F55\u662F\u5426\u5DF2\u88AB\u5176\u5B83\u540C\u6B65\u7EC4\u5360\u7528\uFF0C\u5DF2\u62D2\u7EDD\u521B\u5EFA\u6570\u636E\u7EC4\u300C${ownerId}\u300D\u3002\u8BF7\u68C0\u67E5\u540E\u7AEF\u53C2\u6570\u4E0E\u7F51\u7EDC\u540E\u91CD\u8BD5`
31445
+ );
31446
+ } finally {
31447
+ try {
31448
+ await instance.dispose?.();
31449
+ } catch {
31450
+ }
31451
+ }
31452
+ this.assertRemoteNotOwnedByOthers(remote, backend.id, ownerId);
31453
+ }
31359
31454
  }
31360
31455
  async createAppDataGroup(id, backends, options = {}) {
31361
31456
  this.assertNotDisposed();
@@ -31425,6 +31520,8 @@ var ZenFSConfig = (() => {
31425
31520
  ...features ? { features } : {},
31426
31521
  backends
31427
31522
  };
31523
+ if (backends.length === 0) this.explicitEmptyDescriptors.add(id);
31524
+ else this.explicitEmptyDescriptors.delete(id);
31428
31525
  await this.writeAppDataGroupDescriptorFile(id, descriptor);
31429
31526
  this.scheduleDescriptorPush();
31430
31527
  }
@@ -31499,10 +31596,29 @@ var ZenFSConfig = (() => {
31499
31596
  const candidate = { ...declared[index], type, options, description: description ?? declared[index].description };
31500
31597
  const mergedOptions = await this.resolveAppDataBackendOptions(candidate);
31501
31598
  const probe = await createBackend({ type, options: mergedOptions });
31599
+ let probeRemote = null;
31600
+ let probeError = null;
31502
31601
  try {
31503
- await probe.dispose?.();
31504
- } catch {
31602
+ if (type !== localPrimaryType()) {
31603
+ probeRemote = await this.readRemoteGroupDescriptor(
31604
+ { id: backendId, type, options: mergedOptions },
31605
+ probe
31606
+ );
31607
+ }
31608
+ } catch (err2) {
31609
+ probeError = err2;
31610
+ } finally {
31611
+ try {
31612
+ await probe.dispose?.();
31613
+ } catch {
31614
+ }
31505
31615
  }
31616
+ if (probeError && !isMissingDescriptorError(probeError)) {
31617
+ throw new Error(
31618
+ `\u65E0\u6CD5\u8BFB\u53D6\u540E\u7AEF\u300C${backendId}\u300D\u7684\u8FDC\u7AEF .meta/group.json\uFF08${probeError?.message ?? String(probeError)}\uFF09\uFF1A\u65E0\u6CD5\u5224\u65AD\u8BE5\u8FDC\u7AEF\u76EE\u5F55\u662F\u5426\u5DF2\u88AB\u5176\u5B83\u540C\u6B65\u7EC4\u5360\u7528\uFF0C\u5DF2\u4FDD\u7559\u539F\u53C2\u6570\u3002\u8BF7\u68C0\u67E5\u540E\u7AEF\u53C2\u6570\u4E0E\u7F51\u7EDC\u540E\u91CD\u8BD5`
31619
+ );
31620
+ }
31621
+ this.assertRemoteNotOwnedByOthers(probeRemote, backendId, groupId);
31506
31622
  const oldBackends = declared.map((b) => ({ ...b }));
31507
31623
  const nextBackends = declared.map(
31508
31624
  (b, i) => i === index ? { ...candidate, options: mergedOptions } : b
@@ -31673,6 +31789,59 @@ var ZenFSConfig = (() => {
31673
31789
  }
31674
31790
  return Array.from(byId.values());
31675
31791
  }
31792
+ /**
31793
+ * 「引导副本只升不降」:本地 `.config/app-data-groups/{appId}/{id}.json` 若声明
31794
+ * **0 个后端**,而任何副本上同一路径还带着非空后端列表,就采用远端那份。
31795
+ *
31796
+ * 为什么必须做:本页「清除同步组配置」后本地库被重建,应用会先建一个只有隐式
31797
+ * 本地存储的空 default 组并写下 `backends: []`;配置组后端一接上,首轮双向同步
31798
+ * 以本地为准,这份空副本就会把远端登记的真实拓扑抹平(2026-11-24 线上实际发生)。
31799
+ *
31800
+ * 例外:本会话内用户显式清空后端(`updateAppDataGroupDescriptor(id, [])`)是
31801
+ * 真实意图,允许推送空副本,不参与自愈。
31802
+ */
31803
+ async healEmptyBootstrapDescriptors() {
31804
+ if (this.replicaBackends.size === 0) return;
31805
+ let localDescriptors;
31806
+ try {
31807
+ localDescriptors = await this.listAppDataGroups();
31808
+ } catch {
31809
+ return;
31810
+ }
31811
+ for (const descriptor of localDescriptors) {
31812
+ if ((descriptor.backends?.length ?? 0) > 0) continue;
31813
+ if (this.explicitEmptyDescriptors.has(descriptor.id)) continue;
31814
+ const descPath = this.appDataGroupFilePath(descriptor.id);
31815
+ for (const [replicaId, replica] of this.replicaBackends) {
31816
+ let remote;
31817
+ try {
31818
+ const raw = await withTimeout(
31819
+ replica.instance.readFile(descPath),
31820
+ REPLICA_SETUP_TIMEOUT_MS,
31821
+ `${replicaId} \u8BFB\u53D6\u5F15\u5BFC\u526F\u672C`
31822
+ );
31823
+ remote = JSON.parse(new TextDecoder().decode(toUint8Array2(raw)));
31824
+ } catch {
31825
+ continue;
31826
+ }
31827
+ if (!remote || remote.id !== descriptor.id || remote.groupType !== "data-sync") continue;
31828
+ const remoteBackends = Array.isArray(remote.backends) ? remote.backends : [];
31829
+ if (remoteBackends.length === 0) continue;
31830
+ await this.writeAppDataGroupDescriptorFile(descriptor.id, {
31831
+ id: descriptor.id,
31832
+ groupType: "data-sync",
31833
+ ...remote.instanceId ? { instanceId: remote.instanceId } : {},
31834
+ ...remote.name ? { name: remote.name } : {},
31835
+ ...remote.features ? { features: remote.features } : {},
31836
+ backends: remoteBackends
31837
+ });
31838
+ log9.warn(
31839
+ `[ConfigRepo] ${descriptor.id}: \u672C\u5730\u5F15\u5BFC\u526F\u672C\u4E3A\u7A7A\uFF0C\u91C7\u7528\u8FDC\u7AEF\u62D3\u6251\uFF08${remoteBackends.length} \u4E2A\u540E\u7AEF\uFF09\uFF0C\u907F\u514D\u8986\u76D6\u8FDC\u7AEF\u8BBE\u7F6E`
31840
+ );
31841
+ break;
31842
+ }
31843
+ }
31844
+ }
31676
31845
  async removeAppDataGroup(id) {
31677
31846
  this.assertNotDisposed();
31678
31847
  const group = this.appDataGroups.get(id);
@@ -32458,14 +32627,6 @@ var ZenFSConfig = (() => {
32458
32627
  );
32459
32628
  this.dataBackends.set(desc.id, { instance, syncable, pairId: pair.pairId, desc });
32460
32629
  this.backendStates.set(desc.id, { backendId: desc.id, pairId: pair.pairId });
32461
- if (this.features.conflicts) {
32462
- const conflictHandler = (event) => {
32463
- this.archiveConflict(event).catch((err2) => {
32464
- log9.warn(`[AppDataGroup:${this.groupId}] conflict archive failed:`, err2);
32465
- });
32466
- };
32467
- this.syncEngine.on(pair.pairId, "conflict", conflictHandler);
32468
- }
32469
32630
  this.trackSyncErrors(desc.id, pair.pairId);
32470
32631
  log9.log(`[AppDataGroup:${this.groupId}] backend ${desc.id} (${desc.type}) connected, pair=${pair.pairId}`);
32471
32632
  } catch (err2) {
@@ -32523,6 +32684,32 @@ var ZenFSConfig = (() => {
32523
32684
  }
32524
32685
  /** Mirror per-pair `sync:error` into `getBackendSyncStates()` (see ConfigRepo). */
32525
32686
  trackSyncErrors(backendId, pairId) {
32687
+ this.syncEngine.on(pairId, "sync:start", (event) => {
32688
+ this.emitSyncEvent({
32689
+ type: "sync:start",
32690
+ groupKind: "data",
32691
+ groupId: this.groupId,
32692
+ backendId,
32693
+ pairId,
32694
+ timestamp: event.timestamp ?? Date.now()
32695
+ });
32696
+ });
32697
+ this.syncEngine.on(pairId, "conflict", (event) => {
32698
+ if (this.features.conflicts) {
32699
+ this.archiveConflict(event).catch((err2) => {
32700
+ log9.warn(`[AppDataGroup:${this.groupId}] conflict archive failed:`, err2);
32701
+ });
32702
+ }
32703
+ this.emitSyncEvent({
32704
+ type: "conflict",
32705
+ groupKind: "data",
32706
+ groupId: this.groupId,
32707
+ backendId,
32708
+ pairId,
32709
+ timestamp: event.timestamp ?? Date.now(),
32710
+ conflict: event.conflict
32711
+ });
32712
+ });
32526
32713
  this.syncEngine.on(pairId, "sync:error", (event) => {
32527
32714
  const error = event.error;
32528
32715
  const message = error instanceof Error ? error.message : String(error ?? "sync failed");
@@ -32753,13 +32940,6 @@ var ZenFSConfig = (() => {
32753
32940
  const desc = { id, type, options, description, createdAt: Date.now() };
32754
32941
  this.dataBackends.set(id, { instance, syncable, pairId: pair.pairId, desc });
32755
32942
  this.backendStates.set(id, { backendId: id, pairId: pair.pairId });
32756
- if (this.features.conflicts) {
32757
- this.syncEngine.on(pair.pairId, "conflict", (event) => {
32758
- this.archiveConflict(event).catch((err2) => {
32759
- log9.warn(`[AppDataGroup:${this.groupId}] conflict archive failed:`, err2);
32760
- });
32761
- });
32762
- }
32763
32943
  this.trackSyncErrors(id, pair.pairId);
32764
32944
  this._backends = [...this._backends.filter((b) => b.id !== id), desc];
32765
32945
  log9.log(`[AppDataGroup:${this.groupId}] addBackend: ${id} (${type}) connected, pair=${pair.pairId}`);
@@ -33433,6 +33613,526 @@ var ZenFSConfig = (() => {
33433
33613
  };
33434
33614
  }
33435
33615
 
33616
+ // src/api-v2.ts
33617
+ init_backend_registry();
33618
+ var ConnectV2Error = class extends Error {
33619
+ constructor(message, code) {
33620
+ super(message);
33621
+ __publicField(this, "code", code);
33622
+ this.name = new.target.name;
33623
+ }
33624
+ };
33625
+ var ConnectFailedError = class extends ConnectV2Error {
33626
+ constructor(message) {
33627
+ super(message, "CONNECT_FAILED");
33628
+ }
33629
+ };
33630
+ var ConfigNotReadyError = class extends ConnectV2Error {
33631
+ constructor(message) {
33632
+ super(message, "CONFIG_NOT_READY");
33633
+ }
33634
+ };
33635
+ var InvalidBackendError = class extends ConnectV2Error {
33636
+ constructor(message) {
33637
+ super(message, "INVALID_BACKEND");
33638
+ }
33639
+ };
33640
+ var BackendAlreadyExistsError = class extends ConnectV2Error {
33641
+ constructor(message) {
33642
+ super(message, "BACKEND_ALREADY_EXISTS");
33643
+ }
33644
+ };
33645
+ var BackendEndpointConflictError = class extends ConnectV2Error {
33646
+ constructor(message) {
33647
+ super(message, "BACKEND_ENDPOINT_CONFLICT");
33648
+ }
33649
+ };
33650
+ var BackendIdentityError = class extends ConnectV2Error {
33651
+ constructor(message) {
33652
+ super(message, "BACKEND_IDENTITY_ERROR");
33653
+ }
33654
+ };
33655
+ var DataGroupCreateError = class extends ConnectV2Error {
33656
+ constructor(message) {
33657
+ super(message, "DATA_GROUP_CREATE_FAILED");
33658
+ }
33659
+ };
33660
+ var DataGroupBackendError = class extends ConnectV2Error {
33661
+ constructor(message) {
33662
+ super(message, "DATA_GROUP_BACKEND_FAILED");
33663
+ }
33664
+ };
33665
+ var DataGroupNotFoundError = class extends ConnectV2Error {
33666
+ constructor(message) {
33667
+ super(message, "DATA_GROUP_NOT_FOUND");
33668
+ }
33669
+ };
33670
+ var DataGroupOperationError = class extends ConnectV2Error {
33671
+ constructor(message) {
33672
+ super(message, "DATA_GROUP_OPERATION_FAILED");
33673
+ }
33674
+ };
33675
+ var connectionToRepo = /* @__PURE__ */ new WeakMap();
33676
+ var repoToConnection = /* @__PURE__ */ new WeakMap();
33677
+ function connectionToAppRepo(connection) {
33678
+ const existing = connectionToRepo.get(connection);
33679
+ if (existing) return existing;
33680
+ const repo = new AppRepoImpl(connection);
33681
+ connectionToRepo.set(connection, repo);
33682
+ repoToConnection.set(repo, connection);
33683
+ return repo;
33684
+ }
33685
+ function getUiConnection(repo) {
33686
+ const connection = repoToConnection.get(repo);
33687
+ if (!connection) {
33688
+ throw new ConnectV2Error(
33689
+ "getUiConnection() received an AppRepo that was not created by connectV2()",
33690
+ "UNKNOWN_APP_REPO"
33691
+ );
33692
+ }
33693
+ return connection;
33694
+ }
33695
+ var AppRepoImpl = class {
33696
+ constructor(connection) {
33697
+ __publicField(this, "appId");
33698
+ __publicField(this, "repo");
33699
+ __publicField(this, "defaultGroupPromise", null);
33700
+ __publicField(this, "groups", /* @__PURE__ */ new Map());
33701
+ __publicField(this, "groupPromises", /* @__PURE__ */ new Map());
33702
+ if (!connection.repo) {
33703
+ throw new ConnectV2Error(
33704
+ "connectV2() requires a config-sync connection; no repo was returned",
33705
+ "CONNECT_FAILED"
33706
+ );
33707
+ }
33708
+ this.appId = connection.appId;
33709
+ this.repo = connection.repo;
33710
+ }
33711
+ async getDefaultDataGroup() {
33712
+ if (this.defaultGroupPromise) {
33713
+ try {
33714
+ const current = await this.defaultGroupPromise;
33715
+ if (await this.stillExists(current.id)) return current;
33716
+ this.groups.delete(current.id);
33717
+ this.groupPromises.delete(current.id);
33718
+ } catch {
33719
+ }
33720
+ this.defaultGroupPromise = null;
33721
+ }
33722
+ this.defaultGroupPromise = this.resolveDefaultGroup();
33723
+ try {
33724
+ return await this.defaultGroupPromise;
33725
+ } catch (err2) {
33726
+ this.defaultGroupPromise = null;
33727
+ throw err2;
33728
+ }
33729
+ }
33730
+ async getDataGroup(id) {
33731
+ const groupId = id?.trim();
33732
+ if (!groupId) {
33733
+ throw new DataGroupNotFoundError("Data group id is required");
33734
+ }
33735
+ const groups = await this.repo.listAppDataGroups();
33736
+ const descriptor = groups.find((group) => group.id === groupId);
33737
+ if (!descriptor) {
33738
+ throw new DataGroupNotFoundError(`Data group "${groupId}" does not exist`);
33739
+ }
33740
+ return this.loadGroup(descriptor);
33741
+ }
33742
+ async listDataGroups() {
33743
+ const groups = await this.repo.listAppDataGroups();
33744
+ return groups.map((group) => ({
33745
+ id: group.id,
33746
+ name: group.name?.trim() || group.id,
33747
+ hasRemote: (group.backends ?? []).length > 0
33748
+ }));
33749
+ }
33750
+ async stillExists(id) {
33751
+ try {
33752
+ const groups = await this.repo.listAppDataGroups();
33753
+ return groups.some((group) => group.id === id);
33754
+ } catch {
33755
+ return true;
33756
+ }
33757
+ }
33758
+ async resolveDefaultGroup() {
33759
+ let groups = await this.repo.listAppDataGroups();
33760
+ if (groups.length > 0) {
33761
+ return this.loadGroup(selectDefaultDescriptor(groups));
33762
+ }
33763
+ await this.waitForConfigPull();
33764
+ groups = await this.repo.listAppDataGroups();
33765
+ if (groups.length > 0) {
33766
+ return this.loadGroup(selectDefaultDescriptor(groups));
33767
+ }
33768
+ return this.createDefaultGroup();
33769
+ }
33770
+ async waitForConfigPull() {
33771
+ let remoteCount = 0;
33772
+ try {
33773
+ const meta = await this.repo.getBackends();
33774
+ remoteCount = (meta?.backends ?? []).filter(
33775
+ (backend) => backend.id !== LOCAL_IDB_BACKEND_ID
33776
+ ).length;
33777
+ } catch {
33778
+ throw new ConfigNotReadyError(
33779
+ "Cannot read config-sync backends; refusing to create a local default data group"
33780
+ );
33781
+ }
33782
+ if (remoteCount === 0) return;
33783
+ let summary;
33784
+ try {
33785
+ summary = await this.repo.whenReplicasReady?.();
33786
+ } catch (err2) {
33787
+ throw new ConfigNotReadyError(
33788
+ `Config replicas failed before initial pull: ${errorMessage(err2)}`
33789
+ );
33790
+ }
33791
+ if (summary && (summary.failed.length > 0 || summary.skipped.length > 0)) {
33792
+ const details = [
33793
+ ...summary.failed.map((item) => `${item.backendId}: ${item.error}`),
33794
+ ...summary.skipped.map((item) => `${item.backendId}: ${item.reason}`)
33795
+ ].join("; ");
33796
+ throw new ConfigNotReadyError(
33797
+ `Config group is not ready; refusing to create a local default data group (${details})`
33798
+ );
33799
+ }
33800
+ try {
33801
+ await this.repo.flush();
33802
+ } catch (err2) {
33803
+ throw new ConfigNotReadyError(
33804
+ `Initial config pull did not complete: ${errorMessage(err2)}`
33805
+ );
33806
+ }
33807
+ }
33808
+ async loadGroup(descriptor) {
33809
+ const cached = this.groups.get(descriptor.id);
33810
+ if (cached) return cached;
33811
+ const pending = this.groupPromises.get(descriptor.id);
33812
+ if (pending) return pending;
33813
+ const promise = (async () => {
33814
+ try {
33815
+ const live = await this.repo.getAppDataGroup(descriptor.id);
33816
+ const group = new DataGroupImpl(this.repo, live, descriptor.id);
33817
+ this.groups.set(descriptor.id, group);
33818
+ return group;
33819
+ } catch (err2) {
33820
+ throw new DataGroupCreateError(
33821
+ `Failed to load data group "${descriptor.id}": ${errorMessage(err2)}`
33822
+ );
33823
+ }
33824
+ })();
33825
+ this.groupPromises.set(descriptor.id, promise);
33826
+ try {
33827
+ return await promise;
33828
+ } finally {
33829
+ this.groupPromises.delete(descriptor.id);
33830
+ }
33831
+ }
33832
+ async createDefaultGroup() {
33833
+ try {
33834
+ const live = await this.repo.createAppDataGroup("default", []);
33835
+ const group = new DataGroupImpl(this.repo, live, "default");
33836
+ this.groups.set("default", group);
33837
+ return group;
33838
+ } catch (err2) {
33839
+ let groups = [];
33840
+ try {
33841
+ groups = await this.repo.listAppDataGroups();
33842
+ } catch {
33843
+ }
33844
+ if (groups.length > 0) {
33845
+ return this.loadGroup(selectDefaultDescriptor(groups));
33846
+ }
33847
+ throw new DataGroupCreateError(
33848
+ `Failed to create local default data group: ${errorMessage(err2)}`
33849
+ );
33850
+ }
33851
+ }
33852
+ };
33853
+ function selectDefaultDescriptor(groups) {
33854
+ return groups.find((group) => group.id === "default") ?? groups[0];
33855
+ }
33856
+ function errorMessage(err2) {
33857
+ return err2 instanceof Error ? err2.message : String(err2);
33858
+ }
33859
+ var DataGroupImpl = class {
33860
+ constructor(repo, group, id) {
33861
+ __publicField(this, "id");
33862
+ __publicField(this, "fs");
33863
+ __publicField(this, "repo");
33864
+ __publicField(this, "group");
33865
+ this.repo = repo;
33866
+ this.group = group;
33867
+ this.id = id;
33868
+ this.fs = group.fs;
33869
+ }
33870
+ async addBackend(input) {
33871
+ const type = input.type?.trim();
33872
+ if (!type) throw new InvalidBackendError("Backend type is required");
33873
+ if (!hasBackend(type)) {
33874
+ throw new InvalidBackendError(`Backend type "${type}" is not registered`);
33875
+ }
33876
+ if (!input.options || typeof input.options !== "object") {
33877
+ throw new InvalidBackendError("Backend options must be an object");
33878
+ }
33879
+ if (input.id) {
33880
+ if (input.id === LOCAL_IDB_BACKEND_ID) {
33881
+ throw new InvalidBackendError(
33882
+ `"${LOCAL_IDB_BACKEND_ID}" is the implicit local primary and cannot be added`
33883
+ );
33884
+ }
33885
+ assertValidBackendId(input.id);
33886
+ }
33887
+ const declared = this.listDeclaredBackends();
33888
+ const byId = input.id ? declared.find((backend) => backend.id === input.id) : void 0;
33889
+ if (byId) {
33890
+ return { backendId: byId.id, addedBackend: false };
33891
+ }
33892
+ const endpointKey = backendEndpointKey(type, input.options);
33893
+ const sameEndpoint = declared.find(
33894
+ (backend) => backendEndpointKey(backend.type, backend.options) === endpointKey
33895
+ );
33896
+ if (sameEndpoint) {
33897
+ return { backendId: sameEndpoint.id, addedBackend: false };
33898
+ }
33899
+ await this.assertEndpointUnusedElsewhere(type, input.options);
33900
+ const id = input.id ?? generateBackendId(type, declared);
33901
+ try {
33902
+ await this.group.addBackend(id, type, input.options, input.description);
33903
+ } catch (err2) {
33904
+ throw new DataGroupBackendError(
33905
+ `Failed to add backend "${id}" to data group "${this.id}": ${errorMessage(err2)}`
33906
+ );
33907
+ }
33908
+ return { backendId: id, addedBackend: true };
33909
+ }
33910
+ async flush() {
33911
+ try {
33912
+ const results = await this.group.flush();
33913
+ return (results ?? []).map((result) => ({
33914
+ pairId: result.pairId,
33915
+ ...normalizeSyncResult(result)
33916
+ }));
33917
+ } catch (err2) {
33918
+ throw new DataGroupOperationError(
33919
+ `Failed to flush data group "${this.id}": ${errorMessage(err2)}`
33920
+ );
33921
+ }
33922
+ }
33923
+ async deleteFile(path) {
33924
+ try {
33925
+ await this.group.deleteFile(path);
33926
+ } catch (err2) {
33927
+ throw new DataGroupOperationError(
33928
+ `Failed to delete "${path}" from data group "${this.id}": ${errorMessage(err2)}`
33929
+ );
33930
+ }
33931
+ }
33932
+ onSyncEvent(handler) {
33933
+ const subscribe = this.group.onSyncEvent;
33934
+ if (typeof subscribe !== "function") {
33935
+ return () => {
33936
+ };
33937
+ }
33938
+ return subscribe.call(this.group, (event) => {
33939
+ const mapped = mapSyncEvent(event, this.id);
33940
+ if (mapped) handler(mapped);
33941
+ });
33942
+ }
33943
+ listDeclaredBackends() {
33944
+ const list2 = this.group.listDeclaredBackends;
33945
+ if (typeof list2 === "function") {
33946
+ return list2.call(this.group);
33947
+ }
33948
+ return [];
33949
+ }
33950
+ async assertEndpointUnusedElsewhere(type, options) {
33951
+ const key = backendEndpointKey(type, options);
33952
+ const configMeta = await this.repo.getBackends().catch(() => null);
33953
+ for (const backend of configMeta?.backends ?? []) {
33954
+ if (backend.id === LOCAL_IDB_BACKEND_ID) continue;
33955
+ if (backendEndpointKey(backend.type, backend.options) === key) {
33956
+ throw new BackendEndpointConflictError(
33957
+ `Backend endpoint is already used by config group backend "${backend.id}"`
33958
+ );
33959
+ }
33960
+ }
33961
+ const groups = await this.repo.listAppDataGroups().catch(() => []);
33962
+ for (const descriptor of groups) {
33963
+ if (descriptor.id === this.id) continue;
33964
+ for (const backend of descriptor.backends ?? []) {
33965
+ if (backendEndpointKey(backend.type, backend.options) === key) {
33966
+ throw new BackendEndpointConflictError(
33967
+ `Backend endpoint is already used by data group "${descriptor.id}" backend "${backend.id}"`
33968
+ );
33969
+ }
33970
+ }
33971
+ }
33972
+ }
33973
+ };
33974
+ function mapSyncEvent(event, groupId) {
33975
+ const base = {
33976
+ groupId,
33977
+ backendId: event.backendId,
33978
+ pairId: event.pairId,
33979
+ timestamp: event.timestamp
33980
+ };
33981
+ switch (event.type) {
33982
+ case "sync:start":
33983
+ return { type: "sync:start", ...base };
33984
+ case "sync:progress":
33985
+ if (!event.progress) return null;
33986
+ return { type: "sync:progress", ...base, progress: event.progress };
33987
+ case "sync:end":
33988
+ return {
33989
+ type: "sync:end",
33990
+ ...base,
33991
+ result: normalizeSyncResult(event.result)
33992
+ };
33993
+ case "sync:error":
33994
+ return {
33995
+ type: "sync:error",
33996
+ ...base,
33997
+ error: event.error ?? "sync failed"
33998
+ };
33999
+ case "conflict":
34000
+ return { type: "conflict", ...base, conflict: event.conflict };
34001
+ default:
34002
+ return null;
34003
+ }
34004
+ }
34005
+ function normalizeSyncResult(result) {
34006
+ return {
34007
+ filesCreated: result?.filesCreated ?? 0,
34008
+ filesUpdated: result?.filesUpdated ?? 0,
34009
+ filesDeleted: result?.filesDeleted ?? 0,
34010
+ filesSkipped: result?.filesSkipped ?? 0,
34011
+ conflicts: result?.conflicts ?? [],
34012
+ errors: result?.errors ?? [],
34013
+ durationMs: result?.durationMs ?? 0
34014
+ };
34015
+ }
34016
+ function backendEndpointKey(type, options) {
34017
+ const identityFields = getBackendMetadata(type)?.identityFields;
34018
+ const picked = {};
34019
+ if (identityFields && identityFields.length > 0) {
34020
+ for (const field2 of identityFields) picked[field2] = options[field2];
34021
+ } else {
34022
+ Object.assign(picked, options);
34023
+ }
34024
+ return `${type}:${stableStringify(picked)}`;
34025
+ }
34026
+ function stableStringify(value, seen = /* @__PURE__ */ new WeakSet()) {
34027
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
34028
+ if (seen.has(value)) return '"[circular]"';
34029
+ seen.add(value);
34030
+ if (Array.isArray(value)) {
34031
+ return `[${value.map((item) => stableStringify(item, seen)).join(",")}]`;
34032
+ }
34033
+ const entries2 = Object.entries(value).filter(([, item]) => item !== void 0).sort(([a], [b]) => a.localeCompare(b));
34034
+ return `{${entries2.map(([key, item]) => `${JSON.stringify(key)}:${stableStringify(item, seen)}`).join(",")}}`;
34035
+ }
34036
+ function generateBackendId(type, existing) {
34037
+ const prefix = type.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "backend";
34038
+ let id = `${prefix}-${Date.now().toString(36)}`;
34039
+ let suffix = 1;
34040
+ while (existing.some((backend) => backend.id === id)) {
34041
+ id = `${prefix}-${Date.now().toString(36)}-${suffix++}`;
34042
+ }
34043
+ return id;
34044
+ }
34045
+ var connectCache = /* @__PURE__ */ new Map();
34046
+ async function connectV2(appId, options = {}) {
34047
+ const normalized = normalizeOptions2(options);
34048
+ const key = `${appId}\0${stableStringify(normalized)}`;
34049
+ const cached = connectCache.get(key);
34050
+ if (cached) return cached;
34051
+ const pending = createConnection(appId, normalized).catch((err2) => {
34052
+ connectCache.delete(key);
34053
+ throw err2 instanceof ConnectV2Error ? err2 : new ConnectFailedError(errorMessage(err2));
34054
+ });
34055
+ connectCache.set(key, pending);
34056
+ return pending;
34057
+ }
34058
+ async function createConnection(appId, options) {
34059
+ const { configBackends, connectOptions } = options;
34060
+ let result;
34061
+ try {
34062
+ result = await connect(appId, connectOptions);
34063
+ } catch (err2) {
34064
+ throw new ConnectFailedError(
34065
+ `connectV2("${appId}") failed: ${errorMessage(err2)}`
34066
+ );
34067
+ }
34068
+ if (!result.repo) {
34069
+ throw new ConnectFailedError(
34070
+ `connectV2("${appId}") did not return a config-sync repo`
34071
+ );
34072
+ }
34073
+ await addExtraConfigBackends(result.repo, configBackends);
34074
+ return connectionToAppRepo({ ...result, appId });
34075
+ }
34076
+ async function addExtraConfigBackends(repo, backends) {
34077
+ if (backends.length === 0) return;
34078
+ let existing = [];
34079
+ try {
34080
+ const meta = await repo.getBackends();
34081
+ existing = meta?.backends ?? [];
34082
+ } catch {
34083
+ }
34084
+ for (const backend of backends) {
34085
+ const id = backend.id ?? generateBackendId(backend.type, existing);
34086
+ const byId = existing.find((item) => item.id === id);
34087
+ if (byId) continue;
34088
+ const key = backendEndpointKey(backend.type, backend.options);
34089
+ if (existing.some(
34090
+ (item) => backendEndpointKey(item.type, item.options) === key
34091
+ )) {
34092
+ continue;
34093
+ }
34094
+ try {
34095
+ await repo.addBackend(id, backend.type, backend.options, backend.description);
34096
+ existing = [
34097
+ ...existing,
34098
+ {
34099
+ id,
34100
+ type: backend.type,
34101
+ options: backend.options,
34102
+ description: backend.description
34103
+ }
34104
+ ];
34105
+ } catch (err2) {
34106
+ throw new DataGroupBackendError(
34107
+ `Failed to add config backend "${id}": ${errorMessage(err2)}`
34108
+ );
34109
+ }
34110
+ }
34111
+ }
34112
+ function normalizeOptions2(options) {
34113
+ const {
34114
+ configBackends = [],
34115
+ backendInfo,
34116
+ dataBackends: _ignored,
34117
+ ...rest
34118
+ } = options;
34119
+ void _ignored;
34120
+ const extra = configBackends.map((backend) => ({ ...backend }));
34121
+ let primary = backendInfo;
34122
+ if (!primary && extra.length > 0) {
34123
+ const first = extra.shift();
34124
+ primary = { type: first.type, options: first.options };
34125
+ if (!rest.primaryBackendId && first.id) rest.primaryBackendId = first.id;
34126
+ }
34127
+ return {
34128
+ connectOptions: {
34129
+ ...rest,
34130
+ ...primary ? { backendInfo: primary } : {}
34131
+ },
34132
+ configBackends: extra
34133
+ };
34134
+ }
34135
+
33436
34136
  // src/index.ts
33437
34137
  init_backend_registry();
33438
34138
  return __toCommonJS(src_exports);