zen-fs-config 0.8.0 → 0.9.0

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/DESIGN.md CHANGED
@@ -90,13 +90,17 @@ A **sync group** is a set of backends that synchronize with each other. There ar
90
90
  - Backends: full credentials + storage location, but typically reusing the same account as a config-sync backend with a different storage target (e.g., same token/owner, different repo/branch)
91
91
  - Can be referenced by a config-sync group as an app's data storage (via `ConfigRepo.createAppDataGroup`)
92
92
 
93
- **Group type detection**: When connecting to a backend, the library reads `.meta/group-type` to determine the group type. If the file is absent, the backend is treated as a new empty group and the caller decides which type to create.
93
+ **Group type detection**: When connecting to a backend, the library reads `.meta/group.json` first and takes its `kind` as the group type. Only when no descriptor exists does it fall back to the legacy `group-type` markers (`/.config/group-type`, `/.meta/group-type`). If neither exists, the backend is treated as a new empty group and the caller decides which type to create.
94
94
 
95
- | `.meta/group-type` | Behavior |
95
+ | `.meta/group.json` `kind` (legacy marker) | Behavior |
96
96
  |---|---|
97
- | `config-sync` | Full system: IndexedDB primary + config replicas + optional data-sync groups |
98
- | `data-sync` | Lightweight: data backends only, direct read/write, no config meta layer |
99
- | absent | New empty backend; caller decides group type at creation time |
97
+ | `config` (`config-sync`) | Full system: IndexedDB primary + config replicas + optional data-sync groups |
98
+ | `data` (`data-sync`) | Lightweight: data backends only, direct read/write, no config meta layer |
99
+ | absent (no marker either) | New empty backend; caller decides group type at creation time |
100
+
101
+ Since 0.9.0 the library **no longer writes** any `group-type` marker; `kind` is the only
102
+ source of truth. Markers remain read-compatible for remotes created by older versions and
103
+ are deleted on sight.
100
104
 
101
105
  **Group type is write-once, and sync may not change it**: besides the connect-time
102
106
  check (`connect()` throws when `options.groupType` disagrees with the detected
@@ -125,7 +129,7 @@ group wiring instead of syncing the marker.
125
129
  ```
126
130
  /
127
131
  ├─ .meta/ [synced to replicas]
128
- │ ├─ group-type Group type marker: "config-sync"
132
+ │ ├─ group.json Unified descriptor { schemaVersion, kind, id, instanceId?, name?, features }
129
133
  │ ├─ backends/ Backend topology (one file per backend)
130
134
  │ │ ├─ local-idb.json { id, type, options, description }
131
135
  │ │ ├─ gitee-prod.json
@@ -162,8 +166,8 @@ group wiring instead of syncing the marker.
162
166
 
163
167
  ```
164
168
  /
165
- ├─ .meta/ [synced to replicas]
166
- │ ├─ group-type Group type marker: "data-sync"
169
+ ├─ .meta/ [group.json excluded from sync]
170
+ │ ├─ group.json Descriptor { schemaVersion:2, kind:"data", id, instanceId?, name?, features }
167
171
  │ └─ backends/ Data backend topology (one file per backend)
168
172
  │ ├─ gitee-data-1.json { id, type, options, description }
169
173
  │ └─ gitee-data-2.json
@@ -712,9 +716,11 @@ createConfigRepo('my-app', options?)
712
716
  ├─ 1. Create IndexedDB backend (always, ID = 'local-idb')
713
717
  │ storeName = options.idbStoreName || `zen-fs-config-${appId}`
714
718
  │
715
- ├─ 2. Ensure /.meta/ directory exists
719
+ ├─ 2. Ensure /.meta/ and /.config/ directories exist
716
720
  │
717
- ├─ 3. Write /.meta/group-type = "config-sync" (if not exists)
721
+ ├─ 3. Delete stale group-type markers (/.config/group-type, /.meta/group-type)
722
+ │ └─ No marker is written since 0.9.0: type lives in .meta/group.json's kind
723
+ │ markers stay readable for old remotes (getGroupType / probe fallback)
718
724
  │
719
725
  ├─ 4. Migrate legacy .meta/backends.json → .meta/backends/*.json (if exists)
720
726
  │
@@ -934,18 +940,19 @@ connect('my-app', options?)
934
940
  │
935
941
  ├─ 1. Determine config-sync repo (create or reuse) — this always hosts the data groups
936
942
  │
937
- ├─ 2. If options.backendInfo provided, read /.meta/group-type
943
+ ├─ 2. If options.backendInfo provided, read /.meta/group.json's kind
944
+ │ (fall back to the legacy .config/group-type or .meta/group-type marker)
938
945
  │
939
- ├─ "config-sync" → connect the repo to that backend; then load every app
946
+ ├─ kind=config / "config-sync" → connect the repo to that backend; then load every app
940
947
  │ data group from .meta/app-data-groups/{appId}/*.json (UC2)
941
948
  │ return { groupType: "config-sync", repo, appDataGroups }
942
949
  │
943
- ├─ "data-sync" → keep the config repo local-only; ensure the default data
950
+ ├─ kind=data / "data-sync" → keep the config repo local-only; ensure the default data
944
951
  │ group exists and attach the backend to it (UC3). The backend
945
952
  │ info is written back into app-data-groups by addBackend.
946
953
  │ return { groupType: "data-sync", repo, dataGroup }
947
954
  │
948
- └─ absent (no backendInfo) → local-only config repo + a default data group
955
+ └─ absent (no descriptor, no marker, no backendInfo) → local-only config repo + a default data group
949
956
  └─ return { groupType: "config-sync" (or options.groupType), repo, dataGroup }
950
957
  ```
951
958
 
package/README.md CHANGED
@@ -193,7 +193,8 @@ if (result.groupType === 'data-sync') {
193
193
  Detection & dispatch rules:
194
194
 
195
195
  - Always creates (or reuses) a **config-sync `ConfigRepo`** as the anchor.
196
- - Probes the backend before creating anything local: it reads `/.meta/group.json` strictly (only a genuine "not found" counts as empty — a 401/403 is surfaced, not swallowed) and then the legacy `/.meta/group-type` marker. The probe yields one of `unreachable | empty | marked | occupied`.
196
+ - Probes the backend before creating anything local: it reads `/.meta/group.json` strictly (only a genuine "not found" counts as empty — a 401/403 is surfaced, not swallowed) and then the legacy `.config/group-type` / `.meta/group-type` markers. The probe yields one of `unreachable | empty | marked | occupied`.
197
+ - **The library no longer writes any `group-type` marker** (since 0.9.0): the group type lives only in `group.json`'s `kind`; legacy markers stay readable and are deleted on sight. `getGroupType()` therefore returns `null` on new deployments — use the descriptor's `kind` (or the `groupType` returned by `connect()`) instead.
197
198
  - `unreachable` → throws `RemoteUnreachableError` (`code: 'REMOTE_UNREACHABLE'`); no local group is created.
198
199
  - `empty` (no descriptor and no marker) → throws `NeedsInitError` (`code: 'NEEDS_INIT'`, `requiresInit: true`) unless you pass `initGroupType` (or the older `groupType`). **The library never guesses a group type for a brand-new backend** — ask the user and retry.
199
200
  - `marked` → `config-sync` connects the repo to that backend; `data-sync` attaches the backend to the default app data group inside the config-sync repo.
@@ -209,7 +210,7 @@ Detection & dispatch rules:
209
210
 
210
211
  ### Deferred replica setup: two signals
211
212
 
212
- `connect()` normally verifies every remote backend's group identity (a network round-trip per replica) before it returns. With `deferReplicaSetup: true` it stops doing that inline:
213
+ `connect()` no longer verifies every remote backend's group identity (a network round-trip per replica) before returning — that is deferred to the background by default. Pass `deferReplicaSetup: false` to restore the old blocking behaviour (where one unresponsive backend could stall `connect()` indefinitely):
213
214
 
214
215
  ```typescript
215
216
  const result = await connect('my-app', {
package/README.zh-CN.md CHANGED
@@ -186,7 +186,8 @@ if (result.groupType === 'data-sync') {
186
186
  探测与分发规则:
187
187
 
188
188
  - 始终创建(或复用)一个**配置同步组 `ConfigRepo`** 作为锚点。
189
- - 建任何本地东西之前先探测后端:严格读 `/.meta/group.json`(只有真正的「不存在」才算空,401/403 会照实报错而不是被吞成空库),没有描述符时再读旧标记 `/.meta/group-type`。探测结果是 `unreachable | empty | marked | occupied` 四态之一。
189
+ - 建任何本地东西之前先探测后端:严格读 `/.meta/group.json`(只有真正的「不存在」才算空,401/403 会照实报错而不是被吞成空库),没有描述符时再读旧标记 `/.config/group-type`、`/.meta/group-type`。探测结果是 `unreachable | empty | marked | occupied` 四态之一。
190
+ - **库不再生成任何 `group-type` 标记**(0.9.0 起):组类型只由 `group.json` 的 `kind` 表达,旧标记仅作读取兼容,遇到就删除。所以 `getGroupType()` 在新部署上返回 `null`,判断类型请读描述符的 `kind`(或直接看 `connect()` 返回的 `groupType`)。
190
191
  - `unreachable` → 抛 `RemoteUnreachableError`(`code: 'REMOTE_UNREACHABLE'`),不创建本地组。
191
192
  - `empty`(无描述符也无标记)→ 抛 `NeedsInitError`(`code: 'NEEDS_INIT'`,`requiresInit: true`),除非你传了 `initGroupType`(或旧选项 `groupType`)。**库不会替全新后端猜组类型** —— 先问用户,再带类型重连。
192
193
  - `marked` → `config-sync` 把该后端连到配置同步组;`data-sync` 把它挂到配置同步组下的默认数据组。
@@ -202,7 +203,7 @@ if (result.groupType === 'data-sync') {
202
203
 
203
204
  ### deferReplicaSetup:两个信号
204
205
 
205
- 默认情况下,`connect()` 要逐个校验远端后端的组身份(每个副本一次网络往返)才能返回。传 `deferReplicaSetup: true` 后这段挪到后台:
206
+ **默认就是本地优先**:`connect()` 不再逐个校验远端后端(每个副本一次网络往返)才返回,这段直接挪到后台;传 `deferReplicaSetup: false` 才恢复「等所有副本校验完再返回」的旧行为(此时一个不响应的后端会把 `connect()` 挂住):
206
207
 
207
208
  ```typescript
208
209
  const result = await connect('my-app', {
package/dist/index.d.mts CHANGED
@@ -275,9 +275,10 @@ interface ConfigRepoOptions {
275
275
  descriptor: GroupDescriptor | null;
276
276
  };
277
277
  /**
278
- * 把副本建对推迟到后台(默认 false)。开启后 `createConfigRepo` 先返回本地
279
- * 可用的 repo,副本校验与建对由 `whenReplicasReady()` 通知;校验完成前不会
280
- * 建任何 pair,也不会启动首同步。
278
+ * 把副本建对推迟到后台(默认 true)。`createConfigRepo` 先用本地缓存可用,
279
+ * 副本校验与建对由 `whenReplicasReady()` 通知;校验完成前不会建任何 pair,
280
+ * 也不会启动首同步。传 `false` 恢复旧行为(逐个校验远端后再返回,任一后端
281
+ * 不响应会一直等下去)。
281
282
  */
282
283
  deferReplicaSetup?: boolean;
283
284
  /** IndexedDB store name for the local primary backend. Default: `zen-fs-config-{appId}` */
@@ -650,6 +651,14 @@ interface SyncGroupHandle {
650
651
  /** Handle to a data-sync group, providing direct fs access. */
651
652
  interface AppDataGroup extends SyncGroupHandle {
652
653
  readonly kind: 'data';
654
+ /**
655
+ * 远端阶段(建实例 → 定身份 → 建同步对 → 首同步 → watch)的完成信号。
656
+ *
657
+ * 组实例在本地就绪后即返回,远端后端在后台逐个(并发 + 超时)探测;调用方可以
658
+ * 先渲染组的本地状态,再等这个 Promise 结束后刷新为真实的同步对计数 / 错误。
659
+ * 未启动时立即 resolve,永不 reject。旧版本没有该方法,调用方按可选处理。
660
+ */
661
+ whenBackendsReady?: () => Promise<void>;
653
662
  }
654
663
  /** Options for the unified connect() entry point. */
655
664
  interface ConnectOptions {
@@ -699,7 +708,8 @@ interface ConnectOptions {
699
708
  syncPollIntervalMs?: number;
700
709
  /**
701
710
  * 把「建副本同步对」整体推迟到后台:`connect()` 只做探测 + 本地仓初始化,
702
- * 返回后由 `whenReplicasReady` 通知结果。默认 false(保持旧行为)。
711
+ * 返回后由 `whenReplicasReady` 通知结果。默认 true(本地缓存优先启动);
712
+ * 传 false 恢复旧行为(等待所有副本校验完成才返回)。
703
713
  * 校验完成前不建任何 pair,因此不存在「建了又拆」的冲突窗口。
704
714
  */
705
715
  deferReplicaSetup?: boolean;
@@ -935,9 +945,18 @@ interface IConfigRepo {
935
945
  * primary). Unified handle method shared with data groups.
936
946
  */
937
947
  listBackends(): AppDataBackendDescriptor[];
938
- /** Write the group-type marker file if it doesn't exist. */
948
+ /**
949
+ * Ensure the unified group descriptor (`.meta/group.json`) exists.
950
+ *
951
+ * No longer writes any `group-type` marker (since 0.9.0); `type` is kept for
952
+ * API compatibility only. Stale markers are deleted when encountered.
953
+ */
939
954
  ensureGroupType(type: SyncGroupType): Promise<void>;
940
- /** Read the group-type marker. Returns null if not set. */
955
+ /**
956
+ * Read the legacy `group-type` marker (`/.config/group-type`, then
957
+ * `/.meta/group-type`). Returns null when neither exists — which is now the
958
+ * normal case, since type is carried by `.meta/group.json`'s `kind`.
959
+ */
941
960
  getGroupType(): Promise<SyncGroupType | null>;
942
961
  /** Dispose: stop all sync, release cache FS and resources. */
943
962
  dispose(): Promise<void>;
@@ -1633,7 +1652,14 @@ declare class ConfigRepo implements IConfigRepo {
1633
1652
  listBackendConflicts(): BackendConflictInfo[];
1634
1653
  /** 用户确认后解决配置组某个后端的归属冲突。 */
1635
1654
  resolveBackendConflict(backendId: string, mode: BackendConflictResolution): Promise<BackendConflictResolutionResult>;
1636
- /** Write the group-type marker file if it doesn't exist. */
1655
+ /**
1656
+ * 确保统一组描述符(`.meta/group.json`)就位。
1657
+ *
1658
+ * **已停写 `group-type` 标记**:`/.config/group-type` 与 `/.meta/group-type`
1659
+ * 都不再生成。组类型现在只由描述符的 `kind` 表达,标记仅作旧部署的读取兼容
1660
+ * (`getGroupType()`、`probeGroupTypeDetailed()` 的 legacy 分支),遗留文件会被顺手清掉。
1661
+ * `type` 参数只为兼容既有调用方保留,不再决定任何写入内容。
1662
+ */
1637
1663
  ensureGroupType(type: SyncGroupType): Promise<void>;
1638
1664
  /** Read the group-type marker. Returns null if not set (new path, then legacy). */
1639
1665
  getGroupType(): Promise<SyncGroupType | null>;
package/dist/index.d.ts CHANGED
@@ -275,9 +275,10 @@ interface ConfigRepoOptions {
275
275
  descriptor: GroupDescriptor | null;
276
276
  };
277
277
  /**
278
- * 把副本建对推迟到后台(默认 false)。开启后 `createConfigRepo` 先返回本地
279
- * 可用的 repo,副本校验与建对由 `whenReplicasReady()` 通知;校验完成前不会
280
- * 建任何 pair,也不会启动首同步。
278
+ * 把副本建对推迟到后台(默认 true)。`createConfigRepo` 先用本地缓存可用,
279
+ * 副本校验与建对由 `whenReplicasReady()` 通知;校验完成前不会建任何 pair,
280
+ * 也不会启动首同步。传 `false` 恢复旧行为(逐个校验远端后再返回,任一后端
281
+ * 不响应会一直等下去)。
281
282
  */
282
283
  deferReplicaSetup?: boolean;
283
284
  /** IndexedDB store name for the local primary backend. Default: `zen-fs-config-{appId}` */
@@ -650,6 +651,14 @@ interface SyncGroupHandle {
650
651
  /** Handle to a data-sync group, providing direct fs access. */
651
652
  interface AppDataGroup extends SyncGroupHandle {
652
653
  readonly kind: 'data';
654
+ /**
655
+ * 远端阶段(建实例 → 定身份 → 建同步对 → 首同步 → watch)的完成信号。
656
+ *
657
+ * 组实例在本地就绪后即返回,远端后端在后台逐个(并发 + 超时)探测;调用方可以
658
+ * 先渲染组的本地状态,再等这个 Promise 结束后刷新为真实的同步对计数 / 错误。
659
+ * 未启动时立即 resolve,永不 reject。旧版本没有该方法,调用方按可选处理。
660
+ */
661
+ whenBackendsReady?: () => Promise<void>;
653
662
  }
654
663
  /** Options for the unified connect() entry point. */
655
664
  interface ConnectOptions {
@@ -699,7 +708,8 @@ interface ConnectOptions {
699
708
  syncPollIntervalMs?: number;
700
709
  /**
701
710
  * 把「建副本同步对」整体推迟到后台:`connect()` 只做探测 + 本地仓初始化,
702
- * 返回后由 `whenReplicasReady` 通知结果。默认 false(保持旧行为)。
711
+ * 返回后由 `whenReplicasReady` 通知结果。默认 true(本地缓存优先启动);
712
+ * 传 false 恢复旧行为(等待所有副本校验完成才返回)。
703
713
  * 校验完成前不建任何 pair,因此不存在「建了又拆」的冲突窗口。
704
714
  */
705
715
  deferReplicaSetup?: boolean;
@@ -935,9 +945,18 @@ interface IConfigRepo {
935
945
  * primary). Unified handle method shared with data groups.
936
946
  */
937
947
  listBackends(): AppDataBackendDescriptor[];
938
- /** Write the group-type marker file if it doesn't exist. */
948
+ /**
949
+ * Ensure the unified group descriptor (`.meta/group.json`) exists.
950
+ *
951
+ * No longer writes any `group-type` marker (since 0.9.0); `type` is kept for
952
+ * API compatibility only. Stale markers are deleted when encountered.
953
+ */
939
954
  ensureGroupType(type: SyncGroupType): Promise<void>;
940
- /** Read the group-type marker. Returns null if not set. */
955
+ /**
956
+ * Read the legacy `group-type` marker (`/.config/group-type`, then
957
+ * `/.meta/group-type`). Returns null when neither exists — which is now the
958
+ * normal case, since type is carried by `.meta/group.json`'s `kind`.
959
+ */
941
960
  getGroupType(): Promise<SyncGroupType | null>;
942
961
  /** Dispose: stop all sync, release cache FS and resources. */
943
962
  dispose(): Promise<void>;
@@ -1633,7 +1652,14 @@ declare class ConfigRepo implements IConfigRepo {
1633
1652
  listBackendConflicts(): BackendConflictInfo[];
1634
1653
  /** 用户确认后解决配置组某个后端的归属冲突。 */
1635
1654
  resolveBackendConflict(backendId: string, mode: BackendConflictResolution): Promise<BackendConflictResolutionResult>;
1636
- /** Write the group-type marker file if it doesn't exist. */
1655
+ /**
1656
+ * 确保统一组描述符(`.meta/group.json`)就位。
1657
+ *
1658
+ * **已停写 `group-type` 标记**:`/.config/group-type` 与 `/.meta/group-type`
1659
+ * 都不再生成。组类型现在只由描述符的 `kind` 表达,标记仅作旧部署的读取兼容
1660
+ * (`getGroupType()`、`probeGroupTypeDetailed()` 的 legacy 分支),遗留文件会被顺手清掉。
1661
+ * `type` 参数只为兼容既有调用方保留,不再决定任何写入内容。
1662
+ */
1637
1663
  ensureGroupType(type: SyncGroupType): Promise<void>;
1638
1664
  /** Read the group-type marker. Returns null if not set (new path, then legacy). */
1639
1665
  getGroupType(): Promise<SyncGroupType | null>;
package/dist/index.js CHANGED
@@ -2949,6 +2949,16 @@ function isNotFoundError2(err) {
2949
2949
  const message = String(err?.message ?? err);
2950
2950
  return /ENOENT|not found|does not exist|\b404\b/i.test(message);
2951
2951
  }
2952
+ var REPLICA_SETUP_TIMEOUT_MS = 15e3;
2953
+ function withTimeout(promise, ms, what) {
2954
+ let timer;
2955
+ const timeout = new Promise((_, reject) => {
2956
+ timer = setTimeout(() => reject(new Error(`${what} \u8D85\u65F6\uFF08${Math.round(ms / 1e3)}s\uFF09`)), ms);
2957
+ });
2958
+ return Promise.race([promise, timeout]).finally(() => {
2959
+ if (timer !== void 0) clearTimeout(timer);
2960
+ });
2961
+ }
2952
2962
  function normalizeGroupName(value) {
2953
2963
  if (typeof value !== "string") {
2954
2964
  throw new Error("Group name must be a string");
@@ -4229,10 +4239,19 @@ var ConfigRepo = class _ConfigRepo {
4229
4239
  const prepared = /* @__PURE__ */ new Map();
4230
4240
  await Promise.all(wanted.map(async (desc) => {
4231
4241
  log5.log(`[ConfigRepo] Creating replica backend: id=${desc.id}, type=${desc.type}`);
4242
+ let instance;
4232
4243
  try {
4233
- const instance = await createBackend(desc);
4244
+ instance = await withTimeout(
4245
+ createBackend(desc),
4246
+ REPLICA_SETUP_TIMEOUT_MS,
4247
+ `\u526F\u672C ${desc.id} \u521B\u5EFA\u5B9E\u4F8B`
4248
+ );
4234
4249
  const prefetched = prefetchedDescriptorFor(desc, prefetchedRemote);
4235
- const owner = await this.bindBackendIdentity(instance, desc.id, prefetched);
4250
+ const owner = await withTimeout(
4251
+ this.bindBackendIdentity(instance, desc.id, prefetched),
4252
+ REPLICA_SETUP_TIMEOUT_MS,
4253
+ `\u526F\u672C ${desc.id} \u5F52\u5C5E\u6821\u9A8C`
4254
+ );
4236
4255
  if (owner === "conflict") {
4237
4256
  try {
4238
4257
  await instance.dispose?.();
@@ -4242,6 +4261,10 @@ var ConfigRepo = class _ConfigRepo {
4242
4261
  }
4243
4262
  prepared.set(desc.id, { instance });
4244
4263
  } catch (err) {
4264
+ try {
4265
+ await instance?.dispose?.();
4266
+ } catch {
4267
+ }
4245
4268
  log5.error(`[ConfigRepo] Failed to create replica ${desc.id} (${desc.type}):`, err);
4246
4269
  this.backendStates.set(desc.id, {
4247
4270
  backendId: desc.id,
@@ -5196,25 +5219,17 @@ var ConfigRepo = class _ConfigRepo {
5196
5219
  }
5197
5220
  }
5198
5221
  }
5199
- /** Write the group-type marker file if it doesn't exist. */
5222
+ /**
5223
+ * 确保统一组描述符(`.meta/group.json`)就位。
5224
+ *
5225
+ * **已停写 `group-type` 标记**:`/.config/group-type` 与 `/.meta/group-type`
5226
+ * 都不再生成。组类型现在只由描述符的 `kind` 表达,标记仅作旧部署的读取兼容
5227
+ * (`getGroupType()`、`probeGroupTypeDetailed()` 的 legacy 分支),遗留文件会被顺手清掉。
5228
+ * `type` 参数只为兼容既有调用方保留,不再决定任何写入内容。
5229
+ */
5200
5230
  async ensureGroupType(type) {
5201
5231
  this.assertNotDisposed();
5202
- for (const path of [GROUP_TYPE_FILE, LEGACY_GROUP_TYPE_FILE]) {
5203
- try {
5204
- const existing = await this.cachedFS.readFile(path, "utf-8");
5205
- const current = existing.trim();
5206
- if (current && current !== type) {
5207
- log5.warn(`[ConfigRepo] group-type already set to "${current}" at ${path}, ignoring request to set "${type}"`);
5208
- return;
5209
- }
5210
- } catch {
5211
- }
5212
- }
5213
- const bytes = new TextEncoder().encode(type);
5214
- if (!await this.safeExists(this.cachedFS, GROUP_TYPE_FILE)) {
5215
- await this.ensureDir(GROUP_TYPE_FILE);
5216
- await this.cachedFS.writeFile(GROUP_TYPE_FILE, bytes);
5217
- }
5232
+ log5.log(`[ConfigRepo] ensureGroupType(${type}): \u53EA\u786E\u4FDD group.json\uFF0C\u4E0D\u5199 group-type \u6807\u8BB0`);
5218
5233
  const existingDescriptor = await readGroupDescriptor(this.cachedFS);
5219
5234
  if (!existingDescriptor) {
5220
5235
  this.instanceId = newGroupInstanceId();
@@ -5251,7 +5266,7 @@ var ConfigRepo = class _ConfigRepo {
5251
5266
  });
5252
5267
  log5.log(`[ConfigRepo] assigned group instanceId ${this.instanceId} (kind=${existingDescriptor?.kind ?? "config"})`);
5253
5268
  }
5254
- log5.log(`[ConfigRepo] group-type set to "${type}"`);
5269
+ log5.log("[ConfigRepo] group descriptor ensured");
5255
5270
  if (await this.safeExists(this.cachedFS, LEGACY_GROUP_TYPE_FILE)) {
5256
5271
  try {
5257
5272
  await this.cachedFS.unlink(LEGACY_GROUP_TYPE_FILE);
@@ -5594,7 +5609,7 @@ var ConfigRepo = class _ConfigRepo {
5594
5609
  this,
5595
5610
  descriptor
5596
5611
  );
5597
- await group.init();
5612
+ await group.init({ deferRemote: true });
5598
5613
  this.appDataGroups.set(id, group);
5599
5614
  return group;
5600
5615
  }
@@ -5673,6 +5688,16 @@ var AppDataGroupImpl = class _AppDataGroupImpl {
5673
5688
  fs;
5674
5689
  syncEngine;
5675
5690
  localFS;
5691
+ /** 本地主存储的可同步视图;建对外阶段复用,避免重复包裹。 */
5692
+ localSyncable = null;
5693
+ /**
5694
+ * 后台「建实例 → 定身份 → 建同步对 → 首同步 → watch」的完成信号。
5695
+ *
5696
+ * `init()` 只做本地部分就返回(本地 fs、墓碑、后端清单、本地身份),远端探测与
5697
+ * 建对全部挪到这里:一个不响应的后端不能再把 `getAppDataGroup()` / `connect()`
5698
+ * 挂住,UI 打开即可列出组与后端清单。
5699
+ */
5700
+ remoteSetupPromise = null;
5676
5701
  dataBackends = /* @__PURE__ */ new Map();
5677
5702
  backendStates = /* @__PURE__ */ new Map();
5678
5703
  disposed = false;
@@ -6162,7 +6187,14 @@ var AppDataGroupImpl = class _AppDataGroupImpl {
6162
6187
  }
6163
6188
  }
6164
6189
  }
6165
- async init() {
6190
+ /**
6191
+ * 初始化组实例。
6192
+ *
6193
+ * - 默认(`deferRemote: false`):本地 + 远端全部就绪才返回,语义与旧版一致。
6194
+ * - `deferRemote: true`:本地 fs / 墓碑 / 后端清单就绪即返回,远端探测、定身份、
6195
+ * 建对、首同步交给 `whenBackendsReady()`;用于「打开页面先看到组」的加载路径。
6196
+ */
6197
+ async init(opts = {}) {
6166
6198
  const storeName = dataGroupLocalStoreName(this.appId, this.groupId);
6167
6199
  try {
6168
6200
  const localPrimary = await resolveLocalPrimary(this.appId, "data", {
@@ -6208,7 +6240,7 @@ var AppDataGroupImpl = class _AppDataGroupImpl {
6208
6240
  } catch (err) {
6209
6241
  log5.warn(`[AppDataGroup:${this.groupId}] .keep purge failed:`, err?.message ?? err);
6210
6242
  }
6211
- const localSyncable = backendToSyncableFS(this.localFS, `local(${this.groupId})`);
6243
+ this.localSyncable = backendToSyncableFS(this.localFS, `local(${this.groupId})`);
6212
6244
  this.tombstones = new TombstoneStore(this.localFS, this.localBackendId);
6213
6245
  this.versions = new VersionStore(this.localFS, `${this.appId}/${this.groupId}`);
6214
6246
  this.conflicts = new ConflictStore(this.localFS, this.appId, `${this.groupId}`, this.versions);
@@ -6271,20 +6303,52 @@ var AppDataGroupImpl = class _AppDataGroupImpl {
6271
6303
  log5.warn(`[AppDataGroup:${this.groupId}] failed to persist backend topology:`, err);
6272
6304
  }
6273
6305
  }
6306
+ this.remoteSetupPromise = this.runRemoteSetup().catch((err) => {
6307
+ log5.error(`[AppDataGroup:${this.groupId}] background remote setup failed:`, err);
6308
+ });
6309
+ if (opts.deferRemote) return;
6310
+ await this.remoteSetupPromise;
6311
+ }
6312
+ /** 远端身份校验 / 建对 / 首同步的完成信号。未启动时用缓存的已 resolve promise,
6313
+ * 保证同一个组多次调用返回同一实例(调用方可以用 Promise 相等判断是否已登记)。 */
6314
+ whenBackendsReady() {
6315
+ if (!this.remoteSetupPromise) this.remoteSetupPromise = Promise.resolve();
6316
+ return this.remoteSetupPromise;
6317
+ }
6318
+ /**
6319
+ * 后台远端阶段:建实例(并发 + 逐项超时)→ 定身份 → 写 group.json → 建同步对 →
6320
+ * 首同步 → watch。内部兜住所有错误(失败落 backendStates),不会 reject。
6321
+ */
6322
+ async runRemoteSetup() {
6323
+ const localSyncable = this.localSyncable;
6324
+ if (this.disposed || !localSyncable) return;
6274
6325
  const prepared = [];
6275
- for (const desc of this._backends) {
6326
+ await Promise.all(this._backends.map(async (desc) => {
6327
+ let instance;
6276
6328
  try {
6277
- const instance = await createBackend({ type: desc.type, options: desc.options });
6329
+ instance = await withTimeout(
6330
+ createBackend({ type: desc.type, options: desc.options }),
6331
+ REPLICA_SETUP_TIMEOUT_MS,
6332
+ `\u6570\u636E\u7EC4\u540E\u7AEF ${desc.id} \u521B\u5EFA\u5B9E\u4F8B`
6333
+ );
6278
6334
  let remote = null;
6279
6335
  let readError;
6280
6336
  try {
6281
- remote = await readGroupDescriptorStrict(instance);
6337
+ remote = await withTimeout(
6338
+ readGroupDescriptorStrict(instance),
6339
+ REPLICA_SETUP_TIMEOUT_MS,
6340
+ `\u6570\u636E\u7EC4\u540E\u7AEF ${desc.id} \u8BFB group.json`
6341
+ );
6282
6342
  } catch (err) {
6283
6343
  readError = err?.message ?? String(err);
6284
6344
  log5.warn(`[AppDataGroup:${this.groupId}] failed to read remote group.json of "${desc.id}":`, err);
6285
6345
  }
6286
6346
  prepared.push({ desc, instance, remote, readError });
6287
6347
  } catch (err) {
6348
+ try {
6349
+ await instance?.dispose?.();
6350
+ } catch {
6351
+ }
6288
6352
  const message = err instanceof Error ? err.message : String(err);
6289
6353
  this.backendStates.set(desc.id, {
6290
6354
  backendId: desc.id,
@@ -6292,6 +6356,15 @@ var AppDataGroupImpl = class _AppDataGroupImpl {
6292
6356
  });
6293
6357
  log5.error(`[AppDataGroup:${this.groupId}] Failed to create backend ${desc.id} (${desc.type}):`, err);
6294
6358
  }
6359
+ }));
6360
+ if (this.disposed) {
6361
+ for (const item of prepared) {
6362
+ try {
6363
+ await item.instance.dispose?.();
6364
+ } catch {
6365
+ }
6366
+ }
6367
+ return;
6295
6368
  }
6296
6369
  this.finalizeIdentity(prepared);
6297
6370
  try {
@@ -6299,6 +6372,15 @@ var AppDataGroupImpl = class _AppDataGroupImpl {
6299
6372
  } catch (err) {
6300
6373
  log5.warn(`[AppDataGroup:${this.groupId}] failed to write .meta/group.json:`, err);
6301
6374
  }
6375
+ if (this.disposed) {
6376
+ for (const item of prepared) {
6377
+ try {
6378
+ await item.instance.dispose?.();
6379
+ } catch {
6380
+ }
6381
+ }
6382
+ return;
6383
+ }
6302
6384
  for (const item of prepared) {
6303
6385
  const desc = item.desc;
6304
6386
  const instance = item.instance;
@@ -6354,11 +6436,13 @@ var AppDataGroupImpl = class _AppDataGroupImpl {
6354
6436
  log5.error(`[AppDataGroup:${this.groupId}] Failed to create backend ${desc.id} (${desc.type}):`, err);
6355
6437
  }
6356
6438
  }
6439
+ if (this.disposed) return;
6357
6440
  try {
6358
6441
  await this.syncEngine.syncAll();
6359
6442
  } catch (err) {
6360
6443
  log5.warn(`[AppDataGroup:${this.groupId}] Initial sync failed:`, err);
6361
6444
  }
6445
+ if (this.disposed) return;
6362
6446
  this.syncEngine.watchAll();
6363
6447
  }
6364
6448
  getSyncStatuses() {
@@ -6381,6 +6465,7 @@ var AppDataGroupImpl = class _AppDataGroupImpl {
6381
6465
  }
6382
6466
  }
6383
6467
  async flush() {
6468
+ await this.whenBackendsReady();
6384
6469
  await this.runTombstonePass("flush-pre");
6385
6470
  const results = await this.syncEngine.syncAll();
6386
6471
  await this.runTombstonePass("flush-post");
@@ -6597,6 +6682,7 @@ var AppDataGroupImpl = class _AppDataGroupImpl {
6597
6682
  }
6598
6683
  async addBackend(id, type, options, description) {
6599
6684
  if (this.disposed) throw new Error("DataSyncGroup has been disposed");
6685
+ await this.whenBackendsReady();
6600
6686
  assertValidBackendId(id);
6601
6687
  if (this.dataBackends.has(id)) {
6602
6688
  throw new Error(`Backend "${id}" already exists in data group "${this.groupId}"`);
@@ -6658,6 +6744,7 @@ var AppDataGroupImpl = class _AppDataGroupImpl {
6658
6744
  }
6659
6745
  async removeBackend(id) {
6660
6746
  if (this.disposed) throw new Error("DataSyncGroup has been disposed");
6747
+ await this.whenBackendsReady();
6661
6748
  const backend = this.dataBackends.get(id);
6662
6749
  const desc = this._backends.find((b) => b.id === id);
6663
6750
  if (!backend && !desc) {
@@ -6694,6 +6781,10 @@ var AppDataGroupImpl = class _AppDataGroupImpl {
6694
6781
  async dispose() {
6695
6782
  if (this.disposed) return;
6696
6783
  this.disposed = true;
6784
+ try {
6785
+ await this.remoteSetupPromise;
6786
+ } catch {
6787
+ }
6697
6788
  this.syncEventHandlers.clear();
6698
6789
  if (this.postDeleteTimer) {
6699
6790
  clearTimeout(this.postDeleteTimer);
@@ -6788,19 +6879,16 @@ async function createConfigRepo(appId, options = {}) {
6788
6879
  });
6789
6880
  }
6790
6881
  try {
6791
- const groupTypeBytes = new TextEncoder().encode("config-sync");
6792
- const markerPath = `${CONFIG_DIR}/group-type`;
6793
- try {
6794
- await primaryInstance.readFile(markerPath);
6795
- } catch {
6796
- await ensureParentDir2(primaryInstance, markerPath);
6797
- await primaryInstance.writeFile(markerPath, groupTypeBytes);
6798
- log5.log(`[createConfigRepo] group-type set to "config-sync" at ${markerPath}`);
6799
- }
6800
- try {
6801
- await primaryInstance.unlink(`${META_DIR}/group-type`);
6802
- log5.log("[createConfigRepo] removed stale legacy .meta/group-type");
6803
- } catch {
6882
+ await primaryInstance.mkdir(CONFIG_DIR);
6883
+ } catch {
6884
+ }
6885
+ try {
6886
+ for (const stale of [`${CONFIG_DIR}/group-type`, `${META_DIR}/group-type`]) {
6887
+ try {
6888
+ await primaryInstance.unlink(stale);
6889
+ log5.log(`[createConfigRepo] removed stale ${stale}`);
6890
+ } catch {
6891
+ }
6804
6892
  }
6805
6893
  } catch (err) {
6806
6894
  log5.warn(`[createConfigRepo] Failed to write group metadata:`, err.message);
@@ -6891,7 +6979,7 @@ async function createConfigRepo(appId, options = {}) {
6891
6979
  }
6892
6980
  await repo.load();
6893
6981
  phase("load");
6894
- if (options.deferReplicaSetup) {
6982
+ if (options.deferReplicaSetup !== false) {
6895
6983
  repo.startReplicaSetupInBackground(
6896
6984
  allBackends,
6897
6985
  LOCAL_IDB_BACKEND_ID,
@@ -7165,6 +7253,7 @@ async function probeGroupTypeDetailed(type, options) {
7165
7253
  }
7166
7254
  async function connect(appId, options = {}) {
7167
7255
  log6(`connect: appId=${appId}`);
7256
+ const deferReplicaSetup = options.deferReplicaSetup !== false;
7168
7257
  if (!options.backendInfo) {
7169
7258
  const repo2 = await createConfigRepo(appId, {
7170
7259
  idbStoreName: options.idbStoreName,
@@ -7174,7 +7263,8 @@ async function connect(appId, options = {}) {
7174
7263
  cache: options.cache,
7175
7264
  serializer: options.serializer,
7176
7265
  onConflict: options.onConflict,
7177
- syncPollIntervalMs: options.syncPollIntervalMs
7266
+ syncPollIntervalMs: options.syncPollIntervalMs,
7267
+ deferReplicaSetup
7178
7268
  });
7179
7269
  const appDataGroups2 = [];
7180
7270
  const descriptors2 = await repo2.listAppDataGroups();
@@ -7197,7 +7287,9 @@ async function connect(appId, options = {}) {
7197
7287
  configGroup: repo2,
7198
7288
  groups: [repo2, ...appDataGroups2],
7199
7289
  dataGroup: dataGroup2,
7200
- appDataGroups: appDataGroups2
7290
+ appDataGroups: appDataGroups2,
7291
+ replicasPending: deferReplicaSetup,
7292
+ whenReplicasReady: typeof repo2.whenReplicasReady === "function" ? repo2.whenReplicasReady() : void 0
7201
7293
  };
7202
7294
  }
7203
7295
  const { type, options: backendOptions } = options.backendInfo;
@@ -7234,7 +7326,7 @@ async function connect(appId, options = {}) {
7234
7326
  options: backendOptions,
7235
7327
  descriptor: probe.descriptor ?? null
7236
7328
  },
7237
- deferReplicaSetup: options.deferReplicaSetup,
7329
+ deferReplicaSetup,
7238
7330
  idbStoreName: options.idbStoreName,
7239
7331
  nodeId: options.nodeId,
7240
7332
  primaryBackendId: options.primaryBackendId,
@@ -7278,7 +7370,7 @@ async function connect(appId, options = {}) {
7278
7370
  await dataGroup.addBackend(backendId, type, backendOptions);
7279
7371
  }
7280
7372
  }
7281
- const replicasPending = !!options.deferReplicaSetup && groupType === "config-sync" && !!options.backendInfo;
7373
+ const replicasPending = deferReplicaSetup && groupType === "config-sync" && !!options.backendInfo;
7282
7374
  const whenReplicasReady = typeof repo.whenReplicasReady === "function" ? repo.whenReplicasReady() : void 0;
7283
7375
  return {
7284
7376
  groupType,