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.
package/dist/index.mjs CHANGED
@@ -2147,6 +2147,11 @@ function describeConflict(result) {
2147
2147
  }
2148
2148
  }
2149
2149
  var log5 = createLogger5("zen-fs-config:config-repo");
2150
+ function isMissingDescriptorError(err) {
2151
+ if (isNotFoundError2(err)) return true;
2152
+ const message = String(err?.message ?? err ?? "");
2153
+ return /(^|\W)404(\W|$)|not found|no such file|不存在/i.test(message);
2154
+ }
2150
2155
  var GROUP_DESCRIPTOR_FILE3 = `${META_DIR}/group.json`;
2151
2156
  var GROUP_TYPE_FILE = `${CONFIG_DIR}/group-type`;
2152
2157
  var LEGACY_GROUP_TYPE_FILE = `${META_DIR}/group-type`;
@@ -2375,6 +2380,14 @@ var ConfigRepo = class _ConfigRepo {
2375
2380
  backendConflicts = /* @__PURE__ */ new Map();
2376
2381
  /** Last known backend descriptors, for the synchronous unified handle API. */
2377
2382
  backendDescriptorCache = [];
2383
+ /**
2384
+ * 本会话内被用户**显式**清空后端的数据组 id。
2385
+ *
2386
+ * 只有这类组允许把「0 个后端」的引导副本推给远端;启动时读到的空副本
2387
+ * (历史脏数据、或「清空本页配置」后本地新建的空组)绝不覆盖远端既有拓扑,
2388
+ * 见 `healEmptyBootstrapDescriptors()`。
2389
+ */
2390
+ explicitEmptyDescriptors = /* @__PURE__ */ new Set();
2378
2391
  /**
2379
2392
  * Tracks the background initial sync started by createConfigRepo().
2380
2393
  * `flush()` and `dispose()` will await this if it hasn't completed yet,
@@ -2554,6 +2567,7 @@ var ConfigRepo = class _ConfigRepo {
2554
2567
  this.initialSyncPromise = null;
2555
2568
  }
2556
2569
  await this.processTombstones();
2570
+ await this.healEmptyBootstrapDescriptors();
2557
2571
  const resultsMap = await this.syncEngine.syncAll();
2558
2572
  this.invalidateTombstoneCache();
2559
2573
  await this.readAllBackendDescriptors();
@@ -3061,6 +3075,7 @@ var ConfigRepo = class _ConfigRepo {
3061
3075
  */
3062
3076
  async initialSyncAndDedup() {
3063
3077
  this.syncEngine.unwatchAll();
3078
+ await this.healEmptyBootstrapDescriptors();
3064
3079
  await this.syncEngine.syncAll();
3065
3080
  await this.readAllBackendDescriptors();
3066
3081
  await this.processTombstones();
@@ -4627,6 +4642,41 @@ var ConfigRepo = class _ConfigRepo {
4627
4642
  }
4628
4643
  return mergeAccountFields(desc.type, accountBackend.options, desc.options);
4629
4644
  }
4645
+ /**
4646
+ * 读一个数据组后端根上的 `.meta/group.json`(只读,不写、不建同步对)。
4647
+ *
4648
+ * `null` = 空仓库(可以认领);抛错 = 读不到(调用方必须 fail-closed)。
4649
+ * 复用的实例由调用方负责 dispose。
4650
+ */
4651
+ async readRemoteGroupDescriptor(desc, instance) {
4652
+ const own = instance ?? await createBackend({ type: desc.type, options: desc.options });
4653
+ try {
4654
+ return await withTimeout(
4655
+ readGroupDescriptorStrict(own),
4656
+ REPLICA_SETUP_TIMEOUT_MS,
4657
+ `\u6570\u636E\u7EC4\u540E\u7AEF ${desc.id} \u8BFB group.json`
4658
+ );
4659
+ } finally {
4660
+ if (!instance) {
4661
+ try {
4662
+ await own?.dispose?.();
4663
+ } catch {
4664
+ }
4665
+ }
4666
+ }
4667
+ }
4668
+ /**
4669
+ * 同一个远端目录只能归一个组。`.meta/group.json` 里的 `kind`/`id` 就是归属
4670
+ * 记录 —— 它与「本地方知不知道这个组」无关,描述符丢了也照样能判定。
4671
+ */
4672
+ assertRemoteNotOwnedByOthers(remote, backendId, ownerId) {
4673
+ if (!remote) return;
4674
+ if (remote.kind === "data" && remote.id === ownerId) return;
4675
+ 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`;
4676
+ throw new Error(
4677
+ `\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`
4678
+ );
4679
+ }
4630
4680
  /**
4631
4681
  * Reject two groups pointing at the exact same remote endpoint. Two groups
4632
4682
  * syncing the same files independently would fight over deletions and
@@ -4652,6 +4702,37 @@ var ConfigRepo = class _ConfigRepo {
4652
4702
  }
4653
4703
  }
4654
4704
  }
4705
+ for (const backend of backends) {
4706
+ if (backend.type === localPrimaryType()) continue;
4707
+ let instance;
4708
+ try {
4709
+ instance = await withTimeout(
4710
+ createBackend({ type: backend.type, options: backend.options }),
4711
+ REPLICA_SETUP_TIMEOUT_MS,
4712
+ `\u6570\u636E\u7EC4\u540E\u7AEF ${backend.id} \u521B\u5EFA\u5B9E\u4F8B\uFF08\u5F52\u5C5E\u63A2\u6D4B\uFF09`
4713
+ );
4714
+ } catch (err) {
4715
+ log5.warn(
4716
+ `[ConfigRepo] assertNoSharedRemote: \u65E0\u6CD5\u521B\u5EFA\u540E\u7AEF\u300C${backend.id}\u300D\uFF08${err?.message ?? String(err)}\uFF09\uFF0C\u8DF3\u8FC7\u8FDC\u7AEF\u5F52\u5C5E\u63A2\u6D4B`
4717
+ );
4718
+ continue;
4719
+ }
4720
+ let remote;
4721
+ try {
4722
+ remote = await this.readRemoteGroupDescriptor(backend, instance);
4723
+ } catch (err) {
4724
+ if (isMissingDescriptorError(err)) continue;
4725
+ throw new Error(
4726
+ `\u65E0\u6CD5\u8BFB\u53D6\u540E\u7AEF\u300C${backend.id}\u300D\u7684\u8FDC\u7AEF .meta/group.json\uFF08${err?.message ?? String(err)}\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`
4727
+ );
4728
+ } finally {
4729
+ try {
4730
+ await instance.dispose?.();
4731
+ } catch {
4732
+ }
4733
+ }
4734
+ this.assertRemoteNotOwnedByOthers(remote, backend.id, ownerId);
4735
+ }
4655
4736
  }
4656
4737
  async createAppDataGroup(id, backends, options = {}) {
4657
4738
  this.assertNotDisposed();
@@ -4721,6 +4802,8 @@ var ConfigRepo = class _ConfigRepo {
4721
4802
  ...features ? { features } : {},
4722
4803
  backends
4723
4804
  };
4805
+ if (backends.length === 0) this.explicitEmptyDescriptors.add(id);
4806
+ else this.explicitEmptyDescriptors.delete(id);
4724
4807
  await this.writeAppDataGroupDescriptorFile(id, descriptor);
4725
4808
  this.scheduleDescriptorPush();
4726
4809
  }
@@ -4795,10 +4878,29 @@ var ConfigRepo = class _ConfigRepo {
4795
4878
  const candidate = { ...declared[index], type, options, description: description ?? declared[index].description };
4796
4879
  const mergedOptions = await this.resolveAppDataBackendOptions(candidate);
4797
4880
  const probe = await createBackend({ type, options: mergedOptions });
4881
+ let probeRemote = null;
4882
+ let probeError = null;
4798
4883
  try {
4799
- await probe.dispose?.();
4800
- } catch {
4884
+ if (type !== localPrimaryType()) {
4885
+ probeRemote = await this.readRemoteGroupDescriptor(
4886
+ { id: backendId, type, options: mergedOptions },
4887
+ probe
4888
+ );
4889
+ }
4890
+ } catch (err) {
4891
+ probeError = err;
4892
+ } finally {
4893
+ try {
4894
+ await probe.dispose?.();
4895
+ } catch {
4896
+ }
4897
+ }
4898
+ if (probeError && !isMissingDescriptorError(probeError)) {
4899
+ throw new Error(
4900
+ `\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`
4901
+ );
4801
4902
  }
4903
+ this.assertRemoteNotOwnedByOthers(probeRemote, backendId, groupId);
4802
4904
  const oldBackends = declared.map((b) => ({ ...b }));
4803
4905
  const nextBackends = declared.map(
4804
4906
  (b, i) => i === index ? { ...candidate, options: mergedOptions } : b
@@ -4969,6 +5071,59 @@ var ConfigRepo = class _ConfigRepo {
4969
5071
  }
4970
5072
  return Array.from(byId.values());
4971
5073
  }
5074
+ /**
5075
+ * 「引导副本只升不降」:本地 `.config/app-data-groups/{appId}/{id}.json` 若声明
5076
+ * **0 个后端**,而任何副本上同一路径还带着非空后端列表,就采用远端那份。
5077
+ *
5078
+ * 为什么必须做:本页「清除同步组配置」后本地库被重建,应用会先建一个只有隐式
5079
+ * 本地存储的空 default 组并写下 `backends: []`;配置组后端一接上,首轮双向同步
5080
+ * 以本地为准,这份空副本就会把远端登记的真实拓扑抹平(2026-11-24 线上实际发生)。
5081
+ *
5082
+ * 例外:本会话内用户显式清空后端(`updateAppDataGroupDescriptor(id, [])`)是
5083
+ * 真实意图,允许推送空副本,不参与自愈。
5084
+ */
5085
+ async healEmptyBootstrapDescriptors() {
5086
+ if (this.replicaBackends.size === 0) return;
5087
+ let localDescriptors;
5088
+ try {
5089
+ localDescriptors = await this.listAppDataGroups();
5090
+ } catch {
5091
+ return;
5092
+ }
5093
+ for (const descriptor of localDescriptors) {
5094
+ if ((descriptor.backends?.length ?? 0) > 0) continue;
5095
+ if (this.explicitEmptyDescriptors.has(descriptor.id)) continue;
5096
+ const descPath = this.appDataGroupFilePath(descriptor.id);
5097
+ for (const [replicaId, replica] of this.replicaBackends) {
5098
+ let remote;
5099
+ try {
5100
+ const raw = await withTimeout(
5101
+ replica.instance.readFile(descPath),
5102
+ REPLICA_SETUP_TIMEOUT_MS,
5103
+ `${replicaId} \u8BFB\u53D6\u5F15\u5BFC\u526F\u672C`
5104
+ );
5105
+ remote = JSON.parse(new TextDecoder().decode(toUint8Array2(raw)));
5106
+ } catch {
5107
+ continue;
5108
+ }
5109
+ if (!remote || remote.id !== descriptor.id || remote.groupType !== "data-sync") continue;
5110
+ const remoteBackends = Array.isArray(remote.backends) ? remote.backends : [];
5111
+ if (remoteBackends.length === 0) continue;
5112
+ await this.writeAppDataGroupDescriptorFile(descriptor.id, {
5113
+ id: descriptor.id,
5114
+ groupType: "data-sync",
5115
+ ...remote.instanceId ? { instanceId: remote.instanceId } : {},
5116
+ ...remote.name ? { name: remote.name } : {},
5117
+ ...remote.features ? { features: remote.features } : {},
5118
+ backends: remoteBackends
5119
+ });
5120
+ log5.warn(
5121
+ `[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`
5122
+ );
5123
+ break;
5124
+ }
5125
+ }
5126
+ }
4972
5127
  async removeAppDataGroup(id) {
4973
5128
  this.assertNotDisposed();
4974
5129
  const group = this.appDataGroups.get(id);
@@ -5746,14 +5901,6 @@ var AppDataGroupImpl = class _AppDataGroupImpl {
5746
5901
  );
5747
5902
  this.dataBackends.set(desc.id, { instance, syncable, pairId: pair.pairId, desc });
5748
5903
  this.backendStates.set(desc.id, { backendId: desc.id, pairId: pair.pairId });
5749
- if (this.features.conflicts) {
5750
- const conflictHandler = (event) => {
5751
- this.archiveConflict(event).catch((err) => {
5752
- log5.warn(`[AppDataGroup:${this.groupId}] conflict archive failed:`, err);
5753
- });
5754
- };
5755
- this.syncEngine.on(pair.pairId, "conflict", conflictHandler);
5756
- }
5757
5904
  this.trackSyncErrors(desc.id, pair.pairId);
5758
5905
  log5.log(`[AppDataGroup:${this.groupId}] backend ${desc.id} (${desc.type}) connected, pair=${pair.pairId}`);
5759
5906
  } catch (err) {
@@ -5811,6 +5958,32 @@ var AppDataGroupImpl = class _AppDataGroupImpl {
5811
5958
  }
5812
5959
  /** Mirror per-pair `sync:error` into `getBackendSyncStates()` (see ConfigRepo). */
5813
5960
  trackSyncErrors(backendId, pairId) {
5961
+ this.syncEngine.on(pairId, "sync:start", (event) => {
5962
+ this.emitSyncEvent({
5963
+ type: "sync:start",
5964
+ groupKind: "data",
5965
+ groupId: this.groupId,
5966
+ backendId,
5967
+ pairId,
5968
+ timestamp: event.timestamp ?? Date.now()
5969
+ });
5970
+ });
5971
+ this.syncEngine.on(pairId, "conflict", (event) => {
5972
+ if (this.features.conflicts) {
5973
+ this.archiveConflict(event).catch((err) => {
5974
+ log5.warn(`[AppDataGroup:${this.groupId}] conflict archive failed:`, err);
5975
+ });
5976
+ }
5977
+ this.emitSyncEvent({
5978
+ type: "conflict",
5979
+ groupKind: "data",
5980
+ groupId: this.groupId,
5981
+ backendId,
5982
+ pairId,
5983
+ timestamp: event.timestamp ?? Date.now(),
5984
+ conflict: event.conflict
5985
+ });
5986
+ });
5814
5987
  this.syncEngine.on(pairId, "sync:error", (event) => {
5815
5988
  const error = event.error;
5816
5989
  const message = error instanceof Error ? error.message : String(error ?? "sync failed");
@@ -6041,13 +6214,6 @@ var AppDataGroupImpl = class _AppDataGroupImpl {
6041
6214
  const desc = { id, type, options, description, createdAt: Date.now() };
6042
6215
  this.dataBackends.set(id, { instance, syncable, pairId: pair.pairId, desc });
6043
6216
  this.backendStates.set(id, { backendId: id, pairId: pair.pairId });
6044
- if (this.features.conflicts) {
6045
- this.syncEngine.on(pair.pairId, "conflict", (event) => {
6046
- this.archiveConflict(event).catch((err) => {
6047
- log5.warn(`[AppDataGroup:${this.groupId}] conflict archive failed:`, err);
6048
- });
6049
- });
6050
- }
6051
6217
  this.trackSyncErrors(id, pair.pairId);
6052
6218
  this._backends = [...this._backends.filter((b) => b.id !== id), desc];
6053
6219
  log5.log(`[AppDataGroup:${this.groupId}] addBackend: ${id} (${type}) connected, pair=${pair.pairId}`);
@@ -6711,14 +6877,545 @@ async function connect(appId, options = {}) {
6711
6877
  whenReplicasReady
6712
6878
  };
6713
6879
  }
6880
+
6881
+ // src/api-v2.ts
6882
+ var ConnectV2Error = class extends Error {
6883
+ constructor(message, code) {
6884
+ super(message);
6885
+ this.code = code;
6886
+ this.name = new.target.name;
6887
+ }
6888
+ code;
6889
+ };
6890
+ var ConnectFailedError = class extends ConnectV2Error {
6891
+ constructor(message) {
6892
+ super(message, "CONNECT_FAILED");
6893
+ }
6894
+ };
6895
+ var ConfigNotReadyError = class extends ConnectV2Error {
6896
+ constructor(message) {
6897
+ super(message, "CONFIG_NOT_READY");
6898
+ }
6899
+ };
6900
+ var InvalidBackendError = class extends ConnectV2Error {
6901
+ constructor(message) {
6902
+ super(message, "INVALID_BACKEND");
6903
+ }
6904
+ };
6905
+ var BackendAlreadyExistsError = class extends ConnectV2Error {
6906
+ constructor(message) {
6907
+ super(message, "BACKEND_ALREADY_EXISTS");
6908
+ }
6909
+ };
6910
+ var BackendEndpointConflictError = class extends ConnectV2Error {
6911
+ constructor(message) {
6912
+ super(message, "BACKEND_ENDPOINT_CONFLICT");
6913
+ }
6914
+ };
6915
+ var BackendIdentityError = class extends ConnectV2Error {
6916
+ constructor(message) {
6917
+ super(message, "BACKEND_IDENTITY_ERROR");
6918
+ }
6919
+ };
6920
+ var DataGroupCreateError = class extends ConnectV2Error {
6921
+ constructor(message) {
6922
+ super(message, "DATA_GROUP_CREATE_FAILED");
6923
+ }
6924
+ };
6925
+ var DataGroupBackendError = class extends ConnectV2Error {
6926
+ constructor(message) {
6927
+ super(message, "DATA_GROUP_BACKEND_FAILED");
6928
+ }
6929
+ };
6930
+ var DataGroupNotFoundError = class extends ConnectV2Error {
6931
+ constructor(message) {
6932
+ super(message, "DATA_GROUP_NOT_FOUND");
6933
+ }
6934
+ };
6935
+ var DataGroupOperationError = class extends ConnectV2Error {
6936
+ constructor(message) {
6937
+ super(message, "DATA_GROUP_OPERATION_FAILED");
6938
+ }
6939
+ };
6940
+ var connectionToRepo = /* @__PURE__ */ new WeakMap();
6941
+ var repoToConnection = /* @__PURE__ */ new WeakMap();
6942
+ function connectionToAppRepo(connection) {
6943
+ const existing = connectionToRepo.get(connection);
6944
+ if (existing) return existing;
6945
+ const repo = new AppRepoImpl(connection);
6946
+ connectionToRepo.set(connection, repo);
6947
+ repoToConnection.set(repo, connection);
6948
+ return repo;
6949
+ }
6950
+ function getUiConnection(repo) {
6951
+ const connection = repoToConnection.get(repo);
6952
+ if (!connection) {
6953
+ throw new ConnectV2Error(
6954
+ "getUiConnection() received an AppRepo that was not created by connectV2()",
6955
+ "UNKNOWN_APP_REPO"
6956
+ );
6957
+ }
6958
+ return connection;
6959
+ }
6960
+ var AppRepoImpl = class {
6961
+ appId;
6962
+ repo;
6963
+ defaultGroupPromise = null;
6964
+ groups = /* @__PURE__ */ new Map();
6965
+ groupPromises = /* @__PURE__ */ new Map();
6966
+ constructor(connection) {
6967
+ if (!connection.repo) {
6968
+ throw new ConnectV2Error(
6969
+ "connectV2() requires a config-sync connection; no repo was returned",
6970
+ "CONNECT_FAILED"
6971
+ );
6972
+ }
6973
+ this.appId = connection.appId;
6974
+ this.repo = connection.repo;
6975
+ }
6976
+ async getDefaultDataGroup() {
6977
+ if (this.defaultGroupPromise) {
6978
+ try {
6979
+ const current = await this.defaultGroupPromise;
6980
+ if (await this.stillExists(current.id)) return current;
6981
+ this.groups.delete(current.id);
6982
+ this.groupPromises.delete(current.id);
6983
+ } catch {
6984
+ }
6985
+ this.defaultGroupPromise = null;
6986
+ }
6987
+ this.defaultGroupPromise = this.resolveDefaultGroup();
6988
+ try {
6989
+ return await this.defaultGroupPromise;
6990
+ } catch (err) {
6991
+ this.defaultGroupPromise = null;
6992
+ throw err;
6993
+ }
6994
+ }
6995
+ async getDataGroup(id) {
6996
+ const groupId = id?.trim();
6997
+ if (!groupId) {
6998
+ throw new DataGroupNotFoundError("Data group id is required");
6999
+ }
7000
+ const groups = await this.repo.listAppDataGroups();
7001
+ const descriptor = groups.find((group) => group.id === groupId);
7002
+ if (!descriptor) {
7003
+ throw new DataGroupNotFoundError(`Data group "${groupId}" does not exist`);
7004
+ }
7005
+ return this.loadGroup(descriptor);
7006
+ }
7007
+ async listDataGroups() {
7008
+ const groups = await this.repo.listAppDataGroups();
7009
+ return groups.map((group) => ({
7010
+ id: group.id,
7011
+ name: group.name?.trim() || group.id,
7012
+ hasRemote: (group.backends ?? []).length > 0
7013
+ }));
7014
+ }
7015
+ async stillExists(id) {
7016
+ try {
7017
+ const groups = await this.repo.listAppDataGroups();
7018
+ return groups.some((group) => group.id === id);
7019
+ } catch {
7020
+ return true;
7021
+ }
7022
+ }
7023
+ async resolveDefaultGroup() {
7024
+ let groups = await this.repo.listAppDataGroups();
7025
+ if (groups.length > 0) {
7026
+ return this.loadGroup(selectDefaultDescriptor(groups));
7027
+ }
7028
+ await this.waitForConfigPull();
7029
+ groups = await this.repo.listAppDataGroups();
7030
+ if (groups.length > 0) {
7031
+ return this.loadGroup(selectDefaultDescriptor(groups));
7032
+ }
7033
+ return this.createDefaultGroup();
7034
+ }
7035
+ async waitForConfigPull() {
7036
+ let remoteCount = 0;
7037
+ try {
7038
+ const meta = await this.repo.getBackends();
7039
+ remoteCount = (meta?.backends ?? []).filter(
7040
+ (backend) => backend.id !== LOCAL_IDB_BACKEND_ID
7041
+ ).length;
7042
+ } catch {
7043
+ throw new ConfigNotReadyError(
7044
+ "Cannot read config-sync backends; refusing to create a local default data group"
7045
+ );
7046
+ }
7047
+ if (remoteCount === 0) return;
7048
+ let summary;
7049
+ try {
7050
+ summary = await this.repo.whenReplicasReady?.();
7051
+ } catch (err) {
7052
+ throw new ConfigNotReadyError(
7053
+ `Config replicas failed before initial pull: ${errorMessage(err)}`
7054
+ );
7055
+ }
7056
+ if (summary && (summary.failed.length > 0 || summary.skipped.length > 0)) {
7057
+ const details = [
7058
+ ...summary.failed.map((item) => `${item.backendId}: ${item.error}`),
7059
+ ...summary.skipped.map((item) => `${item.backendId}: ${item.reason}`)
7060
+ ].join("; ");
7061
+ throw new ConfigNotReadyError(
7062
+ `Config group is not ready; refusing to create a local default data group (${details})`
7063
+ );
7064
+ }
7065
+ try {
7066
+ await this.repo.flush();
7067
+ } catch (err) {
7068
+ throw new ConfigNotReadyError(
7069
+ `Initial config pull did not complete: ${errorMessage(err)}`
7070
+ );
7071
+ }
7072
+ }
7073
+ async loadGroup(descriptor) {
7074
+ const cached = this.groups.get(descriptor.id);
7075
+ if (cached) return cached;
7076
+ const pending = this.groupPromises.get(descriptor.id);
7077
+ if (pending) return pending;
7078
+ const promise = (async () => {
7079
+ try {
7080
+ const live = await this.repo.getAppDataGroup(descriptor.id);
7081
+ const group = new DataGroupImpl(this.repo, live, descriptor.id);
7082
+ this.groups.set(descriptor.id, group);
7083
+ return group;
7084
+ } catch (err) {
7085
+ throw new DataGroupCreateError(
7086
+ `Failed to load data group "${descriptor.id}": ${errorMessage(err)}`
7087
+ );
7088
+ }
7089
+ })();
7090
+ this.groupPromises.set(descriptor.id, promise);
7091
+ try {
7092
+ return await promise;
7093
+ } finally {
7094
+ this.groupPromises.delete(descriptor.id);
7095
+ }
7096
+ }
7097
+ async createDefaultGroup() {
7098
+ try {
7099
+ const live = await this.repo.createAppDataGroup("default", []);
7100
+ const group = new DataGroupImpl(this.repo, live, "default");
7101
+ this.groups.set("default", group);
7102
+ return group;
7103
+ } catch (err) {
7104
+ let groups = [];
7105
+ try {
7106
+ groups = await this.repo.listAppDataGroups();
7107
+ } catch {
7108
+ }
7109
+ if (groups.length > 0) {
7110
+ return this.loadGroup(selectDefaultDescriptor(groups));
7111
+ }
7112
+ throw new DataGroupCreateError(
7113
+ `Failed to create local default data group: ${errorMessage(err)}`
7114
+ );
7115
+ }
7116
+ }
7117
+ };
7118
+ function selectDefaultDescriptor(groups) {
7119
+ return groups.find((group) => group.id === "default") ?? groups[0];
7120
+ }
7121
+ function errorMessage(err) {
7122
+ return err instanceof Error ? err.message : String(err);
7123
+ }
7124
+ var DataGroupImpl = class {
7125
+ id;
7126
+ fs;
7127
+ repo;
7128
+ group;
7129
+ constructor(repo, group, id) {
7130
+ this.repo = repo;
7131
+ this.group = group;
7132
+ this.id = id;
7133
+ this.fs = group.fs;
7134
+ }
7135
+ async addBackend(input) {
7136
+ const type = input.type?.trim();
7137
+ if (!type) throw new InvalidBackendError("Backend type is required");
7138
+ if (!hasBackend(type)) {
7139
+ throw new InvalidBackendError(`Backend type "${type}" is not registered`);
7140
+ }
7141
+ if (!input.options || typeof input.options !== "object") {
7142
+ throw new InvalidBackendError("Backend options must be an object");
7143
+ }
7144
+ if (input.id) {
7145
+ if (input.id === LOCAL_IDB_BACKEND_ID) {
7146
+ throw new InvalidBackendError(
7147
+ `"${LOCAL_IDB_BACKEND_ID}" is the implicit local primary and cannot be added`
7148
+ );
7149
+ }
7150
+ assertValidBackendId(input.id);
7151
+ }
7152
+ const declared = this.listDeclaredBackends();
7153
+ const byId = input.id ? declared.find((backend) => backend.id === input.id) : void 0;
7154
+ if (byId) {
7155
+ return { backendId: byId.id, addedBackend: false };
7156
+ }
7157
+ const endpointKey = backendEndpointKey(type, input.options);
7158
+ const sameEndpoint = declared.find(
7159
+ (backend) => backendEndpointKey(backend.type, backend.options) === endpointKey
7160
+ );
7161
+ if (sameEndpoint) {
7162
+ return { backendId: sameEndpoint.id, addedBackend: false };
7163
+ }
7164
+ await this.assertEndpointUnusedElsewhere(type, input.options);
7165
+ const id = input.id ?? generateBackendId(type, declared);
7166
+ try {
7167
+ await this.group.addBackend(id, type, input.options, input.description);
7168
+ } catch (err) {
7169
+ throw new DataGroupBackendError(
7170
+ `Failed to add backend "${id}" to data group "${this.id}": ${errorMessage(err)}`
7171
+ );
7172
+ }
7173
+ return { backendId: id, addedBackend: true };
7174
+ }
7175
+ async flush() {
7176
+ try {
7177
+ const results = await this.group.flush();
7178
+ return (results ?? []).map((result) => ({
7179
+ pairId: result.pairId,
7180
+ ...normalizeSyncResult(result)
7181
+ }));
7182
+ } catch (err) {
7183
+ throw new DataGroupOperationError(
7184
+ `Failed to flush data group "${this.id}": ${errorMessage(err)}`
7185
+ );
7186
+ }
7187
+ }
7188
+ async deleteFile(path) {
7189
+ try {
7190
+ await this.group.deleteFile(path);
7191
+ } catch (err) {
7192
+ throw new DataGroupOperationError(
7193
+ `Failed to delete "${path}" from data group "${this.id}": ${errorMessage(err)}`
7194
+ );
7195
+ }
7196
+ }
7197
+ onSyncEvent(handler) {
7198
+ const subscribe = this.group.onSyncEvent;
7199
+ if (typeof subscribe !== "function") {
7200
+ return () => {
7201
+ };
7202
+ }
7203
+ return subscribe.call(this.group, (event) => {
7204
+ const mapped = mapSyncEvent(event, this.id);
7205
+ if (mapped) handler(mapped);
7206
+ });
7207
+ }
7208
+ listDeclaredBackends() {
7209
+ const list = this.group.listDeclaredBackends;
7210
+ if (typeof list === "function") {
7211
+ return list.call(this.group);
7212
+ }
7213
+ return [];
7214
+ }
7215
+ async assertEndpointUnusedElsewhere(type, options) {
7216
+ const key = backendEndpointKey(type, options);
7217
+ const configMeta = await this.repo.getBackends().catch(() => null);
7218
+ for (const backend of configMeta?.backends ?? []) {
7219
+ if (backend.id === LOCAL_IDB_BACKEND_ID) continue;
7220
+ if (backendEndpointKey(backend.type, backend.options) === key) {
7221
+ throw new BackendEndpointConflictError(
7222
+ `Backend endpoint is already used by config group backend "${backend.id}"`
7223
+ );
7224
+ }
7225
+ }
7226
+ const groups = await this.repo.listAppDataGroups().catch(() => []);
7227
+ for (const descriptor of groups) {
7228
+ if (descriptor.id === this.id) continue;
7229
+ for (const backend of descriptor.backends ?? []) {
7230
+ if (backendEndpointKey(backend.type, backend.options) === key) {
7231
+ throw new BackendEndpointConflictError(
7232
+ `Backend endpoint is already used by data group "${descriptor.id}" backend "${backend.id}"`
7233
+ );
7234
+ }
7235
+ }
7236
+ }
7237
+ }
7238
+ };
7239
+ function mapSyncEvent(event, groupId) {
7240
+ const base = {
7241
+ groupId,
7242
+ backendId: event.backendId,
7243
+ pairId: event.pairId,
7244
+ timestamp: event.timestamp
7245
+ };
7246
+ switch (event.type) {
7247
+ case "sync:start":
7248
+ return { type: "sync:start", ...base };
7249
+ case "sync:progress":
7250
+ if (!event.progress) return null;
7251
+ return { type: "sync:progress", ...base, progress: event.progress };
7252
+ case "sync:end":
7253
+ return {
7254
+ type: "sync:end",
7255
+ ...base,
7256
+ result: normalizeSyncResult(event.result)
7257
+ };
7258
+ case "sync:error":
7259
+ return {
7260
+ type: "sync:error",
7261
+ ...base,
7262
+ error: event.error ?? "sync failed"
7263
+ };
7264
+ case "conflict":
7265
+ return { type: "conflict", ...base, conflict: event.conflict };
7266
+ default:
7267
+ return null;
7268
+ }
7269
+ }
7270
+ function normalizeSyncResult(result) {
7271
+ return {
7272
+ filesCreated: result?.filesCreated ?? 0,
7273
+ filesUpdated: result?.filesUpdated ?? 0,
7274
+ filesDeleted: result?.filesDeleted ?? 0,
7275
+ filesSkipped: result?.filesSkipped ?? 0,
7276
+ conflicts: result?.conflicts ?? [],
7277
+ errors: result?.errors ?? [],
7278
+ durationMs: result?.durationMs ?? 0
7279
+ };
7280
+ }
7281
+ function backendEndpointKey(type, options) {
7282
+ const identityFields = getBackendMetadata(type)?.identityFields;
7283
+ const picked = {};
7284
+ if (identityFields && identityFields.length > 0) {
7285
+ for (const field of identityFields) picked[field] = options[field];
7286
+ } else {
7287
+ Object.assign(picked, options);
7288
+ }
7289
+ return `${type}:${stableStringify(picked)}`;
7290
+ }
7291
+ function stableStringify(value, seen = /* @__PURE__ */ new WeakSet()) {
7292
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
7293
+ if (seen.has(value)) return '"[circular]"';
7294
+ seen.add(value);
7295
+ if (Array.isArray(value)) {
7296
+ return `[${value.map((item) => stableStringify(item, seen)).join(",")}]`;
7297
+ }
7298
+ const entries = Object.entries(value).filter(([, item]) => item !== void 0).sort(([a], [b]) => a.localeCompare(b));
7299
+ return `{${entries.map(([key, item]) => `${JSON.stringify(key)}:${stableStringify(item, seen)}`).join(",")}}`;
7300
+ }
7301
+ function generateBackendId(type, existing) {
7302
+ const prefix = type.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "backend";
7303
+ let id = `${prefix}-${Date.now().toString(36)}`;
7304
+ let suffix = 1;
7305
+ while (existing.some((backend) => backend.id === id)) {
7306
+ id = `${prefix}-${Date.now().toString(36)}-${suffix++}`;
7307
+ }
7308
+ return id;
7309
+ }
7310
+ var connectCache = /* @__PURE__ */ new Map();
7311
+ async function connectV2(appId, options = {}) {
7312
+ const normalized = normalizeOptions(options);
7313
+ const key = `${appId}\0${stableStringify(normalized)}`;
7314
+ const cached = connectCache.get(key);
7315
+ if (cached) return cached;
7316
+ const pending = createConnection(appId, normalized).catch((err) => {
7317
+ connectCache.delete(key);
7318
+ throw err instanceof ConnectV2Error ? err : new ConnectFailedError(errorMessage(err));
7319
+ });
7320
+ connectCache.set(key, pending);
7321
+ return pending;
7322
+ }
7323
+ async function createConnection(appId, options) {
7324
+ const { configBackends, connectOptions } = options;
7325
+ let result;
7326
+ try {
7327
+ result = await connect(appId, connectOptions);
7328
+ } catch (err) {
7329
+ throw new ConnectFailedError(
7330
+ `connectV2("${appId}") failed: ${errorMessage(err)}`
7331
+ );
7332
+ }
7333
+ if (!result.repo) {
7334
+ throw new ConnectFailedError(
7335
+ `connectV2("${appId}") did not return a config-sync repo`
7336
+ );
7337
+ }
7338
+ await addExtraConfigBackends(result.repo, configBackends);
7339
+ return connectionToAppRepo({ ...result, appId });
7340
+ }
7341
+ async function addExtraConfigBackends(repo, backends) {
7342
+ if (backends.length === 0) return;
7343
+ let existing = [];
7344
+ try {
7345
+ const meta = await repo.getBackends();
7346
+ existing = meta?.backends ?? [];
7347
+ } catch {
7348
+ }
7349
+ for (const backend of backends) {
7350
+ const id = backend.id ?? generateBackendId(backend.type, existing);
7351
+ const byId = existing.find((item) => item.id === id);
7352
+ if (byId) continue;
7353
+ const key = backendEndpointKey(backend.type, backend.options);
7354
+ if (existing.some(
7355
+ (item) => backendEndpointKey(item.type, item.options) === key
7356
+ )) {
7357
+ continue;
7358
+ }
7359
+ try {
7360
+ await repo.addBackend(id, backend.type, backend.options, backend.description);
7361
+ existing = [
7362
+ ...existing,
7363
+ {
7364
+ id,
7365
+ type: backend.type,
7366
+ options: backend.options,
7367
+ description: backend.description
7368
+ }
7369
+ ];
7370
+ } catch (err) {
7371
+ throw new DataGroupBackendError(
7372
+ `Failed to add config backend "${id}": ${errorMessage(err)}`
7373
+ );
7374
+ }
7375
+ }
7376
+ }
7377
+ function normalizeOptions(options) {
7378
+ const {
7379
+ configBackends = [],
7380
+ backendInfo,
7381
+ dataBackends: _ignored,
7382
+ ...rest
7383
+ } = options;
7384
+ void _ignored;
7385
+ const extra = configBackends.map((backend) => ({ ...backend }));
7386
+ let primary = backendInfo;
7387
+ if (!primary && extra.length > 0) {
7388
+ const first = extra.shift();
7389
+ primary = { type: first.type, options: first.options };
7390
+ if (!rest.primaryBackendId && first.id) rest.primaryBackendId = first.id;
7391
+ }
7392
+ return {
7393
+ connectOptions: {
7394
+ ...rest,
7395
+ ...primary ? { backendInfo: primary } : {}
7396
+ },
7397
+ configBackends: extra
7398
+ };
7399
+ }
6714
7400
  export {
7401
+ BackendAlreadyExistsError,
7402
+ BackendEndpointConflictError,
7403
+ BackendIdentityError,
6715
7404
  CONFIG_DIR,
6716
7405
  CONFLICTS_DIR,
7406
+ ConfigNotReadyError,
6717
7407
  ConfigRepo,
6718
7408
  ConflictStore,
7409
+ ConnectFailedError,
7410
+ ConnectV2Error,
6719
7411
  DATA_GROUP_DEFAULT_FEATURES,
7412
+ DataGroupBackendError,
7413
+ DataGroupCreateError,
7414
+ DataGroupNotFoundError,
7415
+ DataGroupOperationError,
6720
7416
  FolderStore,
6721
7417
  GROUP_DESCRIPTOR_FILE2 as GROUP_DESCRIPTOR_FILE,
7418
+ InvalidBackendError,
6722
7419
  LEGACY_CONFLICTS_DIR,
6723
7420
  LEGACY_TOMBSTONES_DIR,
6724
7421
  LOCAL_IDB_BACKEND_ID,
@@ -6735,6 +7432,8 @@ export {
6735
7432
  bindRemoteGroupIdentityDetailed,
6736
7433
  configKeyToFilePath,
6737
7434
  connect,
7435
+ connectV2,
7436
+ connectionToAppRepo,
6738
7437
  createBackend,
6739
7438
  createConfigRepo,
6740
7439
  createSerializerChain,
@@ -6745,6 +7444,7 @@ export {
6745
7444
  getAccountFields,
6746
7445
  getBackendMetadata,
6747
7446
  getExtension,
7447
+ getUiConnection,
6748
7448
  hasBackend,
6749
7449
  incrementVersion,
6750
7450
  isBrowserEnv,