zen-fs-config 0.5.45 → 0.5.47

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -345,8 +345,16 @@ interface AppDataBackendDescriptor {
345
345
  interface AppDataGroupDescriptor {
346
346
  id: string;
347
347
  groupType: 'data-sync';
348
+ /** User-editable display name. `id` is the stable identifier. */
349
+ name?: string;
348
350
  backends: AppDataBackendDescriptor[];
349
351
  }
352
+ /** Descriptor for the config-sync group itself (display metadata only). */
353
+ interface ConfigSyncGroupDescriptor {
354
+ groupType: 'config-sync';
355
+ /** User-editable display name. The group has no separate id. */
356
+ name?: string;
357
+ }
350
358
  /** Per-backend sync state of a data group. */
351
359
  interface BackendSyncState {
352
360
  backendId: string;
@@ -555,6 +563,35 @@ interface IConfigRepo {
555
563
  getAppDataGroup(id: string): Promise<AppDataGroup>;
556
564
  /** List all data-sync group descriptors for this app. */
557
565
  listAppDataGroups(): Promise<AppDataGroupDescriptor[]>;
566
+ /**
567
+ * Update a data-sync group's display name (descriptor-only; id, backends,
568
+ * local and remote data are untouched). Empty/oversized names are rejected.
569
+ */
570
+ updateAppDataGroupName(id: string, name: string): Promise<void>;
571
+ /** Read the config-sync group's display descriptor (may be absent). */
572
+ getConfigSyncGroupDescriptor(): Promise<ConfigSyncGroupDescriptor | null>;
573
+ /**
574
+ * Update the config-sync group's display name (descriptor-only; backends,
575
+ * local store and remote data are untouched).
576
+ */
577
+ updateConfigSyncGroupDescriptor(patch: {
578
+ name: string;
579
+ }): Promise<ConfigSyncGroupDescriptor>;
580
+ /**
581
+ * Replace a backend's parameters while keeping its id.
582
+ *
583
+ * Changing parameters means switching to a different remote target:
584
+ * the old sync pair is torn down, the new backend is instantiated, paired
585
+ * and initially synced. Old remote data is NOT migrated. If the new
586
+ * parameters cannot be instantiated, the old backend/pair is left intact
587
+ * and the error is rethrown.
588
+ */
589
+ replaceBackend(id: string, type: string, options: Record<string, unknown>, description?: string): Promise<void>;
590
+ /**
591
+ * Replace a data-sync backend's parameters (same semantics as
592
+ * replaceBackend: old pair is rebuilt against the new target).
593
+ */
594
+ replaceAppDataGroupBackend(groupId: string, backendId: string, type: string, options: Record<string, unknown>, description?: string): Promise<AppDataGroup>;
558
595
  /** Remove a data-sync group (stops sync, removes descriptor). */
559
596
  removeAppDataGroup(id: string): Promise<void>;
560
597
  /**
@@ -986,7 +1023,24 @@ declare class ConfigRepo implements IConfigRepo {
986
1023
  getBackends(): Promise<BackendsMeta | null>;
987
1024
  updateBackends(meta: BackendsMeta): Promise<void>;
988
1025
  addBackend(id: string, type: string, options: Record<string, unknown>, description?: string): Promise<void>;
1026
+ /**
1027
+ * Instantiate a config-sync replica, persist its descriptor, create its
1028
+ * sync pair, register lifecycle hooks and run the initial sync/watch.
1029
+ * Shared by addBackend() and replaceBackend().
1030
+ */
1031
+ private setupReplica;
989
1032
  removeBackend(id: string): Promise<void>;
1033
+ /**
1034
+ * Replace a config-sync backend's parameters in place (same id).
1035
+ *
1036
+ * Probe the new parameters first: if the backend cannot even be created
1037
+ * (e.g. missing token), nothing is touched and the error is rethrown.
1038
+ * Otherwise the old pair is removed, the descriptor rewritten, and a new
1039
+ * pair created against the new target with an initial sync. If that fails,
1040
+ * the old descriptor and pair are restored. The descriptor file is never
1041
+ * tombstoned, so this never delete-then-recreates it.
1042
+ */
1043
+ replaceBackend(id: string, type: string, options: Record<string, unknown>, description?: string): Promise<void>;
990
1044
  /** Write the group-type marker file if it doesn't exist. */
991
1045
  ensureGroupType(type: SyncGroupType): Promise<void>;
992
1046
  /** Read the group-type marker. Returns null if not set. */
@@ -1005,6 +1059,30 @@ declare class ConfigRepo implements IConfigRepo {
1005
1059
  * authoritative source of the data group's backend topology (FR2.3).
1006
1060
  */
1007
1061
  updateAppDataGroupDescriptor(id: string, backends: AppDataBackendDescriptor[]): Promise<void>;
1062
+ /**
1063
+ * Change a data-sync group's display name only. `id`, backends, local stores
1064
+ * and remote data are untouched, so existing sync pairs keep working.
1065
+ */
1066
+ updateAppDataGroupName(id: string, name: string): Promise<void>;
1067
+ /**
1068
+ * Replace a data-sync backend's parameters in place (same backend id).
1069
+ *
1070
+ * Changing parameters means switching to a different remote target: the live
1071
+ * group is disposed (old pairs torn down), the descriptor is rewritten, and a
1072
+ * fresh group instance creates pairs + performs the initial sync. Old remote
1073
+ * data is NOT migrated. If the new options cannot be instantiated, nothing is
1074
+ * touched; if re-initialisation fails, the old descriptor is restored.
1075
+ */
1076
+ replaceAppDataGroupBackend(groupId: string, backendId: string, type: string, options: Record<string, unknown>, description?: string): Promise<AppDataGroup>;
1077
+ getConfigSyncGroupDescriptor(): Promise<ConfigSyncGroupDescriptor | null>;
1078
+ /**
1079
+ * Change the config-sync group's display name only. Backends, the local
1080
+ * store and remote data are untouched.
1081
+ */
1082
+ updateConfigSyncGroupDescriptor(patch: {
1083
+ name: string;
1084
+ }): Promise<ConfigSyncGroupDescriptor>;
1085
+ private readAppDataGroupDescriptor;
1008
1086
  getAppDataGroup(id: string): Promise<AppDataGroup>;
1009
1087
  listAppDataGroups(): Promise<AppDataGroupDescriptor[]>;
1010
1088
  removeAppDataGroup(id: string): Promise<void>;
@@ -1160,4 +1238,4 @@ declare function incrementVersion(fs: SyncableFS, configFilePath: string, newCon
1160
1238
  */
1161
1239
  declare function verifyOrRepairVersion(fs: SyncableFS, configFilePath: string, author: string): Promise<VersionMeta | null>;
1162
1240
 
1163
- export { type AppDataBackendDescriptor, type AppDataGroup, type AppDataGroupDescriptor, type BackendDescriptor, type BackendFactory, type BackendInstance, type BackendMetadata, type BackendParamDef, type BackendSyncState, type BackendsMeta, type CacheOptions, ConfigRepo, type ConfigRepoOptions, type ConfigSerializer, type ConflictArchive, type ConflictInfo, type ConnectOptions, type ConnectResult, FolderStore, type IConfigRepo, type KeepPurgeResult, LOCAL_IDB_BACKEND_ID, type MigrateLocalFS, type MigrateReplicaFS, type MtimePurgeResult, type PurgeKeepOptions, type PurgeMtimeOptions, type PurgeableFS$1 as PurgeableFS, type SyncGroupType, type TombstoneMeta, type VersionMeta, type VersionMigrationOptions, type VersionMigrationResult, configKeyToFilePath, connect, createBackend, createConfigRepo, createSerializerChain, getAccountFields, getBackendMetadata, getExtension, hasBackend, incrementVersion, isBrowserEnv, isKeepFile, isMtimeSidecar, legacyVersionPathFor, listBackendMetadata, listBackends, localPrimaryType, mergeAccountFields, migrateVersionSidecars, purgeKeepFiles, purgeMtimeSidecars, readVersion, registerBackend, registerFolderBackend, resolveLocalPrimary, sha256, unregisterBackend, verifyOrRepairVersion, versionPathFor, wrapZenFSFileSystem, writeVersion };
1241
+ export { type AppDataBackendDescriptor, type AppDataGroup, type AppDataGroupDescriptor, type BackendDescriptor, type BackendFactory, type BackendInstance, type BackendMetadata, type BackendParamDef, type BackendSyncState, type BackendsMeta, type CacheOptions, ConfigRepo, type ConfigRepoOptions, type ConfigSerializer, type ConfigSyncGroupDescriptor, type ConflictArchive, type ConflictInfo, type ConnectOptions, type ConnectResult, FolderStore, type IConfigRepo, type KeepPurgeResult, LOCAL_IDB_BACKEND_ID, type MigrateLocalFS, type MigrateReplicaFS, type MtimePurgeResult, type PurgeKeepOptions, type PurgeMtimeOptions, type PurgeableFS$1 as PurgeableFS, type SyncGroupType, type TombstoneMeta, type VersionMeta, type VersionMigrationOptions, type VersionMigrationResult, configKeyToFilePath, connect, createBackend, createConfigRepo, createSerializerChain, getAccountFields, getBackendMetadata, getExtension, hasBackend, incrementVersion, isBrowserEnv, isKeepFile, isMtimeSidecar, legacyVersionPathFor, listBackendMetadata, listBackends, localPrimaryType, mergeAccountFields, migrateVersionSidecars, purgeKeepFiles, purgeMtimeSidecars, readVersion, registerBackend, registerFolderBackend, resolveLocalPrimary, sha256, unregisterBackend, verifyOrRepairVersion, versionPathFor, wrapZenFSFileSystem, writeVersion };
package/dist/index.d.ts CHANGED
@@ -345,8 +345,16 @@ interface AppDataBackendDescriptor {
345
345
  interface AppDataGroupDescriptor {
346
346
  id: string;
347
347
  groupType: 'data-sync';
348
+ /** User-editable display name. `id` is the stable identifier. */
349
+ name?: string;
348
350
  backends: AppDataBackendDescriptor[];
349
351
  }
352
+ /** Descriptor for the config-sync group itself (display metadata only). */
353
+ interface ConfigSyncGroupDescriptor {
354
+ groupType: 'config-sync';
355
+ /** User-editable display name. The group has no separate id. */
356
+ name?: string;
357
+ }
350
358
  /** Per-backend sync state of a data group. */
351
359
  interface BackendSyncState {
352
360
  backendId: string;
@@ -555,6 +563,35 @@ interface IConfigRepo {
555
563
  getAppDataGroup(id: string): Promise<AppDataGroup>;
556
564
  /** List all data-sync group descriptors for this app. */
557
565
  listAppDataGroups(): Promise<AppDataGroupDescriptor[]>;
566
+ /**
567
+ * Update a data-sync group's display name (descriptor-only; id, backends,
568
+ * local and remote data are untouched). Empty/oversized names are rejected.
569
+ */
570
+ updateAppDataGroupName(id: string, name: string): Promise<void>;
571
+ /** Read the config-sync group's display descriptor (may be absent). */
572
+ getConfigSyncGroupDescriptor(): Promise<ConfigSyncGroupDescriptor | null>;
573
+ /**
574
+ * Update the config-sync group's display name (descriptor-only; backends,
575
+ * local store and remote data are untouched).
576
+ */
577
+ updateConfigSyncGroupDescriptor(patch: {
578
+ name: string;
579
+ }): Promise<ConfigSyncGroupDescriptor>;
580
+ /**
581
+ * Replace a backend's parameters while keeping its id.
582
+ *
583
+ * Changing parameters means switching to a different remote target:
584
+ * the old sync pair is torn down, the new backend is instantiated, paired
585
+ * and initially synced. Old remote data is NOT migrated. If the new
586
+ * parameters cannot be instantiated, the old backend/pair is left intact
587
+ * and the error is rethrown.
588
+ */
589
+ replaceBackend(id: string, type: string, options: Record<string, unknown>, description?: string): Promise<void>;
590
+ /**
591
+ * Replace a data-sync backend's parameters (same semantics as
592
+ * replaceBackend: old pair is rebuilt against the new target).
593
+ */
594
+ replaceAppDataGroupBackend(groupId: string, backendId: string, type: string, options: Record<string, unknown>, description?: string): Promise<AppDataGroup>;
558
595
  /** Remove a data-sync group (stops sync, removes descriptor). */
559
596
  removeAppDataGroup(id: string): Promise<void>;
560
597
  /**
@@ -986,7 +1023,24 @@ declare class ConfigRepo implements IConfigRepo {
986
1023
  getBackends(): Promise<BackendsMeta | null>;
987
1024
  updateBackends(meta: BackendsMeta): Promise<void>;
988
1025
  addBackend(id: string, type: string, options: Record<string, unknown>, description?: string): Promise<void>;
1026
+ /**
1027
+ * Instantiate a config-sync replica, persist its descriptor, create its
1028
+ * sync pair, register lifecycle hooks and run the initial sync/watch.
1029
+ * Shared by addBackend() and replaceBackend().
1030
+ */
1031
+ private setupReplica;
989
1032
  removeBackend(id: string): Promise<void>;
1033
+ /**
1034
+ * Replace a config-sync backend's parameters in place (same id).
1035
+ *
1036
+ * Probe the new parameters first: if the backend cannot even be created
1037
+ * (e.g. missing token), nothing is touched and the error is rethrown.
1038
+ * Otherwise the old pair is removed, the descriptor rewritten, and a new
1039
+ * pair created against the new target with an initial sync. If that fails,
1040
+ * the old descriptor and pair are restored. The descriptor file is never
1041
+ * tombstoned, so this never delete-then-recreates it.
1042
+ */
1043
+ replaceBackend(id: string, type: string, options: Record<string, unknown>, description?: string): Promise<void>;
990
1044
  /** Write the group-type marker file if it doesn't exist. */
991
1045
  ensureGroupType(type: SyncGroupType): Promise<void>;
992
1046
  /** Read the group-type marker. Returns null if not set. */
@@ -1005,6 +1059,30 @@ declare class ConfigRepo implements IConfigRepo {
1005
1059
  * authoritative source of the data group's backend topology (FR2.3).
1006
1060
  */
1007
1061
  updateAppDataGroupDescriptor(id: string, backends: AppDataBackendDescriptor[]): Promise<void>;
1062
+ /**
1063
+ * Change a data-sync group's display name only. `id`, backends, local stores
1064
+ * and remote data are untouched, so existing sync pairs keep working.
1065
+ */
1066
+ updateAppDataGroupName(id: string, name: string): Promise<void>;
1067
+ /**
1068
+ * Replace a data-sync backend's parameters in place (same backend id).
1069
+ *
1070
+ * Changing parameters means switching to a different remote target: the live
1071
+ * group is disposed (old pairs torn down), the descriptor is rewritten, and a
1072
+ * fresh group instance creates pairs + performs the initial sync. Old remote
1073
+ * data is NOT migrated. If the new options cannot be instantiated, nothing is
1074
+ * touched; if re-initialisation fails, the old descriptor is restored.
1075
+ */
1076
+ replaceAppDataGroupBackend(groupId: string, backendId: string, type: string, options: Record<string, unknown>, description?: string): Promise<AppDataGroup>;
1077
+ getConfigSyncGroupDescriptor(): Promise<ConfigSyncGroupDescriptor | null>;
1078
+ /**
1079
+ * Change the config-sync group's display name only. Backends, the local
1080
+ * store and remote data are untouched.
1081
+ */
1082
+ updateConfigSyncGroupDescriptor(patch: {
1083
+ name: string;
1084
+ }): Promise<ConfigSyncGroupDescriptor>;
1085
+ private readAppDataGroupDescriptor;
1008
1086
  getAppDataGroup(id: string): Promise<AppDataGroup>;
1009
1087
  listAppDataGroups(): Promise<AppDataGroupDescriptor[]>;
1010
1088
  removeAppDataGroup(id: string): Promise<void>;
@@ -1160,4 +1238,4 @@ declare function incrementVersion(fs: SyncableFS, configFilePath: string, newCon
1160
1238
  */
1161
1239
  declare function verifyOrRepairVersion(fs: SyncableFS, configFilePath: string, author: string): Promise<VersionMeta | null>;
1162
1240
 
1163
- export { type AppDataBackendDescriptor, type AppDataGroup, type AppDataGroupDescriptor, type BackendDescriptor, type BackendFactory, type BackendInstance, type BackendMetadata, type BackendParamDef, type BackendSyncState, type BackendsMeta, type CacheOptions, ConfigRepo, type ConfigRepoOptions, type ConfigSerializer, type ConflictArchive, type ConflictInfo, type ConnectOptions, type ConnectResult, FolderStore, type IConfigRepo, type KeepPurgeResult, LOCAL_IDB_BACKEND_ID, type MigrateLocalFS, type MigrateReplicaFS, type MtimePurgeResult, type PurgeKeepOptions, type PurgeMtimeOptions, type PurgeableFS$1 as PurgeableFS, type SyncGroupType, type TombstoneMeta, type VersionMeta, type VersionMigrationOptions, type VersionMigrationResult, configKeyToFilePath, connect, createBackend, createConfigRepo, createSerializerChain, getAccountFields, getBackendMetadata, getExtension, hasBackend, incrementVersion, isBrowserEnv, isKeepFile, isMtimeSidecar, legacyVersionPathFor, listBackendMetadata, listBackends, localPrimaryType, mergeAccountFields, migrateVersionSidecars, purgeKeepFiles, purgeMtimeSidecars, readVersion, registerBackend, registerFolderBackend, resolveLocalPrimary, sha256, unregisterBackend, verifyOrRepairVersion, versionPathFor, wrapZenFSFileSystem, writeVersion };
1241
+ export { type AppDataBackendDescriptor, type AppDataGroup, type AppDataGroupDescriptor, type BackendDescriptor, type BackendFactory, type BackendInstance, type BackendMetadata, type BackendParamDef, type BackendSyncState, type BackendsMeta, type CacheOptions, ConfigRepo, type ConfigRepoOptions, type ConfigSerializer, type ConfigSyncGroupDescriptor, type ConflictArchive, type ConflictInfo, type ConnectOptions, type ConnectResult, FolderStore, type IConfigRepo, type KeepPurgeResult, LOCAL_IDB_BACKEND_ID, type MigrateLocalFS, type MigrateReplicaFS, type MtimePurgeResult, type PurgeKeepOptions, type PurgeMtimeOptions, type PurgeableFS$1 as PurgeableFS, type SyncGroupType, type TombstoneMeta, type VersionMeta, type VersionMigrationOptions, type VersionMigrationResult, configKeyToFilePath, connect, createBackend, createConfigRepo, createSerializerChain, getAccountFields, getBackendMetadata, getExtension, hasBackend, incrementVersion, isBrowserEnv, isKeepFile, isMtimeSidecar, legacyVersionPathFor, listBackendMetadata, listBackends, localPrimaryType, mergeAccountFields, migrateVersionSidecars, purgeKeepFiles, purgeMtimeSidecars, readVersion, registerBackend, registerFolderBackend, resolveLocalPrimary, sha256, unregisterBackend, verifyOrRepairVersion, versionPathFor, wrapZenFSFileSystem, writeVersion };
package/dist/index.js CHANGED
@@ -1424,10 +1424,25 @@ var GROUP_TYPE_FILE = `${META_DIR}/group-type`;
1424
1424
  var BACKENDS_FILE = `${META_DIR}/backends.json`;
1425
1425
  var BACKENDS_DIR = `${META_DIR}/backends`;
1426
1426
  var APP_DATA_GROUPS_DIR = `${META_DIR}/app-data-groups`;
1427
+ var CONFIG_SYNC_GROUP_FILE = `${META_DIR}/config-sync-group.json`;
1428
+ var GROUP_NAME_MAX_LENGTH = 40;
1427
1429
  var CONFLICTS_DIR = `${META_DIR}/.conflicts`;
1428
1430
  var DELETIONS_DIR = `${META_DIR}/.deleted`;
1429
1431
  var NODES_DIR = "/nodes";
1430
1432
  var SHARED_DIR = "/shared";
1433
+ function normalizeGroupName(value) {
1434
+ if (typeof value !== "string") {
1435
+ throw new Error("Group name must be a string");
1436
+ }
1437
+ const name = value.trim();
1438
+ if (!name) {
1439
+ throw new Error("Group name must not be empty");
1440
+ }
1441
+ if (name.length > GROUP_NAME_MAX_LENGTH) {
1442
+ throw new Error(`Group name must be at most ${GROUP_NAME_MAX_LENGTH} characters`);
1443
+ }
1444
+ return name;
1445
+ }
1431
1446
  var CONFIG_ONLY_PREFIXES = [META_DIR, NODES_DIR, SHARED_DIR];
1432
1447
  var LOCAL_IDB_BACKEND_ID = "local-idb";
1433
1448
  function tombstoneFileName(filePath) {
@@ -2613,6 +2628,14 @@ var ConfigRepo = class {
2613
2628
  `Backend "${id}" has the same configuration as existing backend "${dup.id}" (type=${type}). Use removeBackend("${dup.id}") first, or connect with the existing backend's ID.`
2614
2629
  );
2615
2630
  }
2631
+ await this.setupReplica(id, type, options, description);
2632
+ }
2633
+ /**
2634
+ * Instantiate a config-sync replica, persist its descriptor, create its
2635
+ * sync pair, register lifecycle hooks and run the initial sync/watch.
2636
+ * Shared by addBackend() and replaceBackend().
2637
+ */
2638
+ async setupReplica(id, type, options, description) {
2616
2639
  log2.log(`[ConfigRepo] addBackend: creating ${id} (${type})...`);
2617
2640
  const instance = await createBackend({ type, options });
2618
2641
  const syncable = backendToSyncableFS(instance, `${type}(${id})`);
@@ -2652,6 +2675,7 @@ var ConfigRepo = class {
2652
2675
  log2.log(`[ConfigRepo] addBackend: ${id} (${type}) added, sync pair=${pair.pairId}`);
2653
2676
  await this.syncMetaToReplicas();
2654
2677
  this.syncEngine.watch(pair.pairId);
2678
+ return pair.pairId;
2655
2679
  }
2656
2680
  async removeBackend(id) {
2657
2681
  this.assertNotDisposed();
@@ -2688,6 +2712,60 @@ var ConfigRepo = class {
2688
2712
  this.schedulePostDeleteSync();
2689
2713
  log2.log(`[ConfigRepo] removeBackend: ${id} removed (tombstone written, remote cleaned)`);
2690
2714
  }
2715
+ /**
2716
+ * Replace a config-sync backend's parameters in place (same id).
2717
+ *
2718
+ * Probe the new parameters first: if the backend cannot even be created
2719
+ * (e.g. missing token), nothing is touched and the error is rethrown.
2720
+ * Otherwise the old pair is removed, the descriptor rewritten, and a new
2721
+ * pair created against the new target with an initial sync. If that fails,
2722
+ * the old descriptor and pair are restored. The descriptor file is never
2723
+ * tombstoned, so this never delete-then-recreates it.
2724
+ */
2725
+ async replaceBackend(id, type, options, description) {
2726
+ this.assertNotDisposed();
2727
+ if (id === LOCAL_IDB_BACKEND_ID) {
2728
+ throw new Error("Cannot edit the local IndexedDB primary backend");
2729
+ }
2730
+ const all = await this.readAllBackendDescriptors();
2731
+ const before = all.find((b) => b.id === id);
2732
+ if (!before) {
2733
+ throw new Error(`Backend "${id}" not found`);
2734
+ }
2735
+ const probe = await createBackend({ type, options });
2736
+ try {
2737
+ await probe.dispose?.();
2738
+ } catch {
2739
+ }
2740
+ const newKey = backendDedupKey({ id, type, options });
2741
+ const dup = all.find((b) => b.id !== id && backendDedupKey(b) === newKey);
2742
+ if (dup) {
2743
+ throw new Error(
2744
+ `\u65B0\u53C2\u6570\u4E0E\u5DF2\u6709\u540E\u7AEF\u300C${dup.id}\u300D\u6307\u5411\u540C\u4E00\u8FDC\u7AEF\uFF08\u7C7B\u578B\u4E0E\u53C2\u6570\u5B8C\u5168\u76F8\u540C\uFF09\uFF0C\u8BF7\u5148\u5220\u9664\u91CD\u590D\u540E\u7AEF\u300C${dup.id}\u300D\u6216\u6539\u7528\u4E0D\u540C\u53C2\u6570`
2745
+ );
2746
+ }
2747
+ const oldReplica = this.replicaBackends.get(id);
2748
+ if (oldReplica) {
2749
+ this.syncEngine.removePair(oldReplica.pairId);
2750
+ this.replicaBackends.delete(id);
2751
+ try {
2752
+ await oldReplica.instance?.dispose?.();
2753
+ } catch {
2754
+ }
2755
+ }
2756
+ try {
2757
+ await this.setupReplica(id, type, options, description ?? before.description);
2758
+ } catch (err) {
2759
+ const reason = err instanceof Error ? err.message : String(err);
2760
+ log2.warn(`[ConfigRepo] replaceBackend: "${id}" failed, rolling back old options:`, err);
2761
+ try {
2762
+ await this.setupReplica(id, before.type, before.options, before.description);
2763
+ } catch (rollbackErr) {
2764
+ log2.error(`[ConfigRepo] replaceBackend: rollback for "${id}" ALSO failed:`, rollbackErr);
2765
+ }
2766
+ throw new Error(`\u66F4\u65B0\u540E\u7AEF\u53C2\u6570\u5931\u8D25\uFF1A${reason}\uFF08\u5DF2\u5C1D\u8BD5\u56DE\u6EDA\u65E7\u53C2\u6570\uFF09`);
2767
+ }
2768
+ }
2691
2769
  // -----------------------------------------------------------------------
2692
2770
  // IConfigRepo — Group Type
2693
2771
  // -----------------------------------------------------------------------
@@ -2783,9 +2861,11 @@ var ConfigRepo = class {
2783
2861
  */
2784
2862
  async updateAppDataGroupDescriptor(id, backends) {
2785
2863
  this.assertNotDisposed();
2864
+ const existing = await this.readAppDataGroupDescriptor(id);
2786
2865
  const descriptor = {
2787
2866
  id,
2788
2867
  groupType: "data-sync",
2868
+ ...existing?.name ? { name: existing.name } : {},
2789
2869
  backends
2790
2870
  };
2791
2871
  const descPath = this.appDataGroupFilePath(id);
@@ -2796,6 +2876,140 @@ var ConfigRepo = class {
2796
2876
  const version = await incrementVersion(this.fullFS, descPath, bytes, author);
2797
2877
  await this.writeVersionSidecar(descPath, version);
2798
2878
  }
2879
+ /**
2880
+ * Change a data-sync group's display name only. `id`, backends, local stores
2881
+ * and remote data are untouched, so existing sync pairs keep working.
2882
+ */
2883
+ async updateAppDataGroupName(id, name) {
2884
+ this.assertNotDisposed();
2885
+ const normalized = normalizeGroupName(name);
2886
+ const existing = await this.readAppDataGroupDescriptor(id);
2887
+ if (!existing) {
2888
+ throw new Error(`App data group "${id}" not found`);
2889
+ }
2890
+ const descriptor = {
2891
+ ...existing,
2892
+ id,
2893
+ groupType: "data-sync",
2894
+ name: normalized
2895
+ };
2896
+ const descPath = this.appDataGroupFilePath(id);
2897
+ await this.ensureDir(descPath);
2898
+ const bytes = new TextEncoder().encode(JSON.stringify(descriptor, null, 2));
2899
+ await this.cachedFS.writeFile(descPath, bytes);
2900
+ const author = `${this.appId}/${this.nodeId}`;
2901
+ const version = await incrementVersion(this.fullFS, descPath, bytes, author);
2902
+ await this.writeVersionSidecar(descPath, version);
2903
+ }
2904
+ /**
2905
+ * Replace a data-sync backend's parameters in place (same backend id).
2906
+ *
2907
+ * Changing parameters means switching to a different remote target: the live
2908
+ * group is disposed (old pairs torn down), the descriptor is rewritten, and a
2909
+ * fresh group instance creates pairs + performs the initial sync. Old remote
2910
+ * data is NOT migrated. If the new options cannot be instantiated, nothing is
2911
+ * touched; if re-initialisation fails, the old descriptor is restored.
2912
+ */
2913
+ async replaceAppDataGroupBackend(groupId, backendId, type, options, description) {
2914
+ this.assertNotDisposed();
2915
+ const descriptor = await this.readAppDataGroupDescriptor(groupId);
2916
+ if (!descriptor) {
2917
+ throw new Error(`App data group "${groupId}" not found`);
2918
+ }
2919
+ const index = descriptor.backends.findIndex((b) => b.id === backendId);
2920
+ if (index < 0) {
2921
+ throw new Error(`Backend "${backendId}" not found in data group "${groupId}"`);
2922
+ }
2923
+ const candidate = { ...descriptor.backends[index], type, options, description: description ?? descriptor.backends[index].description };
2924
+ const mergedOptions = await this.resolveAppDataBackendOptions(candidate);
2925
+ const probe = await createBackend({ type, options: mergedOptions });
2926
+ try {
2927
+ await probe.dispose?.();
2928
+ } catch {
2929
+ }
2930
+ const oldBackends = descriptor.backends.map((b) => ({ ...b }));
2931
+ const nextBackends = descriptor.backends.map(
2932
+ (b, i) => i === index ? { ...candidate, options: mergedOptions } : b
2933
+ );
2934
+ const live = this.appDataGroups.get(groupId);
2935
+ if (live) {
2936
+ await live.dispose();
2937
+ this.appDataGroups.delete(groupId);
2938
+ }
2939
+ await this.updateAppDataGroupDescriptor(groupId, nextBackends);
2940
+ try {
2941
+ const group = new AppDataGroupImpl(
2942
+ groupId,
2943
+ this.appId,
2944
+ nextBackends,
2945
+ this.pollIntervalMs,
2946
+ this
2947
+ );
2948
+ await group.init();
2949
+ this.appDataGroups.set(groupId, group);
2950
+ return group;
2951
+ } catch (err) {
2952
+ const reason = err instanceof Error ? err.message : String(err);
2953
+ log2.warn(`[ConfigRepo] replaceAppDataGroupBackend: "${backendId}" failed, rolling back:`, err);
2954
+ try {
2955
+ await this.updateAppDataGroupDescriptor(groupId, oldBackends);
2956
+ const restored = new AppDataGroupImpl(
2957
+ groupId,
2958
+ this.appId,
2959
+ oldBackends,
2960
+ this.pollIntervalMs,
2961
+ this
2962
+ );
2963
+ await restored.init();
2964
+ this.appDataGroups.set(groupId, restored);
2965
+ } catch (rollbackErr) {
2966
+ log2.error("[ConfigRepo] replaceAppDataGroupBackend: rollback ALSO failed:", rollbackErr);
2967
+ }
2968
+ throw new Error(`\u66F4\u65B0\u540E\u7AEF\u53C2\u6570\u5931\u8D25\uFF1A${reason}\uFF08\u5DF2\u5C1D\u8BD5\u56DE\u6EDA\u65E7\u53C2\u6570\uFF09`);
2969
+ }
2970
+ }
2971
+ async getConfigSyncGroupDescriptor() {
2972
+ this.assertNotDisposed();
2973
+ try {
2974
+ const raw = await this.cachedFS.readFile(CONFIG_SYNC_GROUP_FILE);
2975
+ const parsed = JSON.parse(new TextDecoder().decode(toUint8Array2(raw)));
2976
+ if (parsed && parsed.groupType === "config-sync") {
2977
+ return parsed;
2978
+ }
2979
+ } catch {
2980
+ }
2981
+ return null;
2982
+ }
2983
+ /**
2984
+ * Change the config-sync group's display name only. Backends, the local
2985
+ * store and remote data are untouched.
2986
+ */
2987
+ async updateConfigSyncGroupDescriptor(patch) {
2988
+ this.assertNotDisposed();
2989
+ const normalized = normalizeGroupName(patch?.name);
2990
+ const descriptor = {
2991
+ groupType: "config-sync",
2992
+ name: normalized
2993
+ };
2994
+ await this.ensureDir(CONFIG_SYNC_GROUP_FILE);
2995
+ const bytes = new TextEncoder().encode(JSON.stringify(descriptor, null, 2));
2996
+ await this.cachedFS.writeFile(CONFIG_SYNC_GROUP_FILE, bytes);
2997
+ const author = `${this.appId}/${this.nodeId}`;
2998
+ const version = await incrementVersion(this.fullFS, CONFIG_SYNC_GROUP_FILE, bytes, author);
2999
+ await this.writeVersionSidecar(CONFIG_SYNC_GROUP_FILE, version);
3000
+ return descriptor;
3001
+ }
3002
+ async readAppDataGroupDescriptor(id) {
3003
+ try {
3004
+ const raw = await this.cachedFS.readFile(this.appDataGroupFilePath(id));
3005
+ const parsed = JSON.parse(new TextDecoder().decode(toUint8Array2(raw)));
3006
+ if (parsed && parsed.id === id && parsed.groupType === "data-sync") {
3007
+ return parsed;
3008
+ }
3009
+ } catch {
3010
+ }
3011
+ return null;
3012
+ }
2799
3013
  async getAppDataGroup(id) {
2800
3014
  this.assertNotDisposed();
2801
3015
  const cached = this.appDataGroups.get(id);
package/dist/index.mjs CHANGED
@@ -884,10 +884,25 @@ var GROUP_TYPE_FILE = `${META_DIR}/group-type`;
884
884
  var BACKENDS_FILE = `${META_DIR}/backends.json`;
885
885
  var BACKENDS_DIR = `${META_DIR}/backends`;
886
886
  var APP_DATA_GROUPS_DIR = `${META_DIR}/app-data-groups`;
887
+ var CONFIG_SYNC_GROUP_FILE = `${META_DIR}/config-sync-group.json`;
888
+ var GROUP_NAME_MAX_LENGTH = 40;
887
889
  var CONFLICTS_DIR = `${META_DIR}/.conflicts`;
888
890
  var DELETIONS_DIR = `${META_DIR}/.deleted`;
889
891
  var NODES_DIR = "/nodes";
890
892
  var SHARED_DIR = "/shared";
893
+ function normalizeGroupName(value) {
894
+ if (typeof value !== "string") {
895
+ throw new Error("Group name must be a string");
896
+ }
897
+ const name = value.trim();
898
+ if (!name) {
899
+ throw new Error("Group name must not be empty");
900
+ }
901
+ if (name.length > GROUP_NAME_MAX_LENGTH) {
902
+ throw new Error(`Group name must be at most ${GROUP_NAME_MAX_LENGTH} characters`);
903
+ }
904
+ return name;
905
+ }
891
906
  var CONFIG_ONLY_PREFIXES = [META_DIR, NODES_DIR, SHARED_DIR];
892
907
  var LOCAL_IDB_BACKEND_ID = "local-idb";
893
908
  function tombstoneFileName(filePath) {
@@ -2073,6 +2088,14 @@ var ConfigRepo = class {
2073
2088
  `Backend "${id}" has the same configuration as existing backend "${dup.id}" (type=${type}). Use removeBackend("${dup.id}") first, or connect with the existing backend's ID.`
2074
2089
  );
2075
2090
  }
2091
+ await this.setupReplica(id, type, options, description);
2092
+ }
2093
+ /**
2094
+ * Instantiate a config-sync replica, persist its descriptor, create its
2095
+ * sync pair, register lifecycle hooks and run the initial sync/watch.
2096
+ * Shared by addBackend() and replaceBackend().
2097
+ */
2098
+ async setupReplica(id, type, options, description) {
2076
2099
  log2.log(`[ConfigRepo] addBackend: creating ${id} (${type})...`);
2077
2100
  const instance = await createBackend({ type, options });
2078
2101
  const syncable = backendToSyncableFS(instance, `${type}(${id})`);
@@ -2112,6 +2135,7 @@ var ConfigRepo = class {
2112
2135
  log2.log(`[ConfigRepo] addBackend: ${id} (${type}) added, sync pair=${pair.pairId}`);
2113
2136
  await this.syncMetaToReplicas();
2114
2137
  this.syncEngine.watch(pair.pairId);
2138
+ return pair.pairId;
2115
2139
  }
2116
2140
  async removeBackend(id) {
2117
2141
  this.assertNotDisposed();
@@ -2148,6 +2172,60 @@ var ConfigRepo = class {
2148
2172
  this.schedulePostDeleteSync();
2149
2173
  log2.log(`[ConfigRepo] removeBackend: ${id} removed (tombstone written, remote cleaned)`);
2150
2174
  }
2175
+ /**
2176
+ * Replace a config-sync backend's parameters in place (same id).
2177
+ *
2178
+ * Probe the new parameters first: if the backend cannot even be created
2179
+ * (e.g. missing token), nothing is touched and the error is rethrown.
2180
+ * Otherwise the old pair is removed, the descriptor rewritten, and a new
2181
+ * pair created against the new target with an initial sync. If that fails,
2182
+ * the old descriptor and pair are restored. The descriptor file is never
2183
+ * tombstoned, so this never delete-then-recreates it.
2184
+ */
2185
+ async replaceBackend(id, type, options, description) {
2186
+ this.assertNotDisposed();
2187
+ if (id === LOCAL_IDB_BACKEND_ID) {
2188
+ throw new Error("Cannot edit the local IndexedDB primary backend");
2189
+ }
2190
+ const all = await this.readAllBackendDescriptors();
2191
+ const before = all.find((b) => b.id === id);
2192
+ if (!before) {
2193
+ throw new Error(`Backend "${id}" not found`);
2194
+ }
2195
+ const probe = await createBackend({ type, options });
2196
+ try {
2197
+ await probe.dispose?.();
2198
+ } catch {
2199
+ }
2200
+ const newKey = backendDedupKey({ id, type, options });
2201
+ const dup = all.find((b) => b.id !== id && backendDedupKey(b) === newKey);
2202
+ if (dup) {
2203
+ throw new Error(
2204
+ `\u65B0\u53C2\u6570\u4E0E\u5DF2\u6709\u540E\u7AEF\u300C${dup.id}\u300D\u6307\u5411\u540C\u4E00\u8FDC\u7AEF\uFF08\u7C7B\u578B\u4E0E\u53C2\u6570\u5B8C\u5168\u76F8\u540C\uFF09\uFF0C\u8BF7\u5148\u5220\u9664\u91CD\u590D\u540E\u7AEF\u300C${dup.id}\u300D\u6216\u6539\u7528\u4E0D\u540C\u53C2\u6570`
2205
+ );
2206
+ }
2207
+ const oldReplica = this.replicaBackends.get(id);
2208
+ if (oldReplica) {
2209
+ this.syncEngine.removePair(oldReplica.pairId);
2210
+ this.replicaBackends.delete(id);
2211
+ try {
2212
+ await oldReplica.instance?.dispose?.();
2213
+ } catch {
2214
+ }
2215
+ }
2216
+ try {
2217
+ await this.setupReplica(id, type, options, description ?? before.description);
2218
+ } catch (err) {
2219
+ const reason = err instanceof Error ? err.message : String(err);
2220
+ log2.warn(`[ConfigRepo] replaceBackend: "${id}" failed, rolling back old options:`, err);
2221
+ try {
2222
+ await this.setupReplica(id, before.type, before.options, before.description);
2223
+ } catch (rollbackErr) {
2224
+ log2.error(`[ConfigRepo] replaceBackend: rollback for "${id}" ALSO failed:`, rollbackErr);
2225
+ }
2226
+ throw new Error(`\u66F4\u65B0\u540E\u7AEF\u53C2\u6570\u5931\u8D25\uFF1A${reason}\uFF08\u5DF2\u5C1D\u8BD5\u56DE\u6EDA\u65E7\u53C2\u6570\uFF09`);
2227
+ }
2228
+ }
2151
2229
  // -----------------------------------------------------------------------
2152
2230
  // IConfigRepo — Group Type
2153
2231
  // -----------------------------------------------------------------------
@@ -2243,9 +2321,11 @@ var ConfigRepo = class {
2243
2321
  */
2244
2322
  async updateAppDataGroupDescriptor(id, backends) {
2245
2323
  this.assertNotDisposed();
2324
+ const existing = await this.readAppDataGroupDescriptor(id);
2246
2325
  const descriptor = {
2247
2326
  id,
2248
2327
  groupType: "data-sync",
2328
+ ...existing?.name ? { name: existing.name } : {},
2249
2329
  backends
2250
2330
  };
2251
2331
  const descPath = this.appDataGroupFilePath(id);
@@ -2256,6 +2336,140 @@ var ConfigRepo = class {
2256
2336
  const version = await incrementVersion(this.fullFS, descPath, bytes, author);
2257
2337
  await this.writeVersionSidecar(descPath, version);
2258
2338
  }
2339
+ /**
2340
+ * Change a data-sync group's display name only. `id`, backends, local stores
2341
+ * and remote data are untouched, so existing sync pairs keep working.
2342
+ */
2343
+ async updateAppDataGroupName(id, name) {
2344
+ this.assertNotDisposed();
2345
+ const normalized = normalizeGroupName(name);
2346
+ const existing = await this.readAppDataGroupDescriptor(id);
2347
+ if (!existing) {
2348
+ throw new Error(`App data group "${id}" not found`);
2349
+ }
2350
+ const descriptor = {
2351
+ ...existing,
2352
+ id,
2353
+ groupType: "data-sync",
2354
+ name: normalized
2355
+ };
2356
+ const descPath = this.appDataGroupFilePath(id);
2357
+ await this.ensureDir(descPath);
2358
+ const bytes = new TextEncoder().encode(JSON.stringify(descriptor, null, 2));
2359
+ await this.cachedFS.writeFile(descPath, bytes);
2360
+ const author = `${this.appId}/${this.nodeId}`;
2361
+ const version = await incrementVersion(this.fullFS, descPath, bytes, author);
2362
+ await this.writeVersionSidecar(descPath, version);
2363
+ }
2364
+ /**
2365
+ * Replace a data-sync backend's parameters in place (same backend id).
2366
+ *
2367
+ * Changing parameters means switching to a different remote target: the live
2368
+ * group is disposed (old pairs torn down), the descriptor is rewritten, and a
2369
+ * fresh group instance creates pairs + performs the initial sync. Old remote
2370
+ * data is NOT migrated. If the new options cannot be instantiated, nothing is
2371
+ * touched; if re-initialisation fails, the old descriptor is restored.
2372
+ */
2373
+ async replaceAppDataGroupBackend(groupId, backendId, type, options, description) {
2374
+ this.assertNotDisposed();
2375
+ const descriptor = await this.readAppDataGroupDescriptor(groupId);
2376
+ if (!descriptor) {
2377
+ throw new Error(`App data group "${groupId}" not found`);
2378
+ }
2379
+ const index = descriptor.backends.findIndex((b) => b.id === backendId);
2380
+ if (index < 0) {
2381
+ throw new Error(`Backend "${backendId}" not found in data group "${groupId}"`);
2382
+ }
2383
+ const candidate = { ...descriptor.backends[index], type, options, description: description ?? descriptor.backends[index].description };
2384
+ const mergedOptions = await this.resolveAppDataBackendOptions(candidate);
2385
+ const probe = await createBackend({ type, options: mergedOptions });
2386
+ try {
2387
+ await probe.dispose?.();
2388
+ } catch {
2389
+ }
2390
+ const oldBackends = descriptor.backends.map((b) => ({ ...b }));
2391
+ const nextBackends = descriptor.backends.map(
2392
+ (b, i) => i === index ? { ...candidate, options: mergedOptions } : b
2393
+ );
2394
+ const live = this.appDataGroups.get(groupId);
2395
+ if (live) {
2396
+ await live.dispose();
2397
+ this.appDataGroups.delete(groupId);
2398
+ }
2399
+ await this.updateAppDataGroupDescriptor(groupId, nextBackends);
2400
+ try {
2401
+ const group = new AppDataGroupImpl(
2402
+ groupId,
2403
+ this.appId,
2404
+ nextBackends,
2405
+ this.pollIntervalMs,
2406
+ this
2407
+ );
2408
+ await group.init();
2409
+ this.appDataGroups.set(groupId, group);
2410
+ return group;
2411
+ } catch (err) {
2412
+ const reason = err instanceof Error ? err.message : String(err);
2413
+ log2.warn(`[ConfigRepo] replaceAppDataGroupBackend: "${backendId}" failed, rolling back:`, err);
2414
+ try {
2415
+ await this.updateAppDataGroupDescriptor(groupId, oldBackends);
2416
+ const restored = new AppDataGroupImpl(
2417
+ groupId,
2418
+ this.appId,
2419
+ oldBackends,
2420
+ this.pollIntervalMs,
2421
+ this
2422
+ );
2423
+ await restored.init();
2424
+ this.appDataGroups.set(groupId, restored);
2425
+ } catch (rollbackErr) {
2426
+ log2.error("[ConfigRepo] replaceAppDataGroupBackend: rollback ALSO failed:", rollbackErr);
2427
+ }
2428
+ throw new Error(`\u66F4\u65B0\u540E\u7AEF\u53C2\u6570\u5931\u8D25\uFF1A${reason}\uFF08\u5DF2\u5C1D\u8BD5\u56DE\u6EDA\u65E7\u53C2\u6570\uFF09`);
2429
+ }
2430
+ }
2431
+ async getConfigSyncGroupDescriptor() {
2432
+ this.assertNotDisposed();
2433
+ try {
2434
+ const raw = await this.cachedFS.readFile(CONFIG_SYNC_GROUP_FILE);
2435
+ const parsed = JSON.parse(new TextDecoder().decode(toUint8Array2(raw)));
2436
+ if (parsed && parsed.groupType === "config-sync") {
2437
+ return parsed;
2438
+ }
2439
+ } catch {
2440
+ }
2441
+ return null;
2442
+ }
2443
+ /**
2444
+ * Change the config-sync group's display name only. Backends, the local
2445
+ * store and remote data are untouched.
2446
+ */
2447
+ async updateConfigSyncGroupDescriptor(patch) {
2448
+ this.assertNotDisposed();
2449
+ const normalized = normalizeGroupName(patch?.name);
2450
+ const descriptor = {
2451
+ groupType: "config-sync",
2452
+ name: normalized
2453
+ };
2454
+ await this.ensureDir(CONFIG_SYNC_GROUP_FILE);
2455
+ const bytes = new TextEncoder().encode(JSON.stringify(descriptor, null, 2));
2456
+ await this.cachedFS.writeFile(CONFIG_SYNC_GROUP_FILE, bytes);
2457
+ const author = `${this.appId}/${this.nodeId}`;
2458
+ const version = await incrementVersion(this.fullFS, CONFIG_SYNC_GROUP_FILE, bytes, author);
2459
+ await this.writeVersionSidecar(CONFIG_SYNC_GROUP_FILE, version);
2460
+ return descriptor;
2461
+ }
2462
+ async readAppDataGroupDescriptor(id) {
2463
+ try {
2464
+ const raw = await this.cachedFS.readFile(this.appDataGroupFilePath(id));
2465
+ const parsed = JSON.parse(new TextDecoder().decode(toUint8Array2(raw)));
2466
+ if (parsed && parsed.id === id && parsed.groupType === "data-sync") {
2467
+ return parsed;
2468
+ }
2469
+ } catch {
2470
+ }
2471
+ return null;
2472
+ }
2259
2473
  async getAppDataGroup(id) {
2260
2474
  this.assertNotDisposed();
2261
2475
  const cached = this.appDataGroups.get(id);
@@ -27449,10 +27449,25 @@ var ZenFSConfig = (() => {
27449
27449
  var BACKENDS_FILE = `${META_DIR}/backends.json`;
27450
27450
  var BACKENDS_DIR = `${META_DIR}/backends`;
27451
27451
  var APP_DATA_GROUPS_DIR = `${META_DIR}/app-data-groups`;
27452
+ var CONFIG_SYNC_GROUP_FILE = `${META_DIR}/config-sync-group.json`;
27453
+ var GROUP_NAME_MAX_LENGTH = 40;
27452
27454
  var CONFLICTS_DIR = `${META_DIR}/.conflicts`;
27453
27455
  var DELETIONS_DIR = `${META_DIR}/.deleted`;
27454
27456
  var NODES_DIR = "/nodes";
27455
27457
  var SHARED_DIR = "/shared";
27458
+ function normalizeGroupName(value) {
27459
+ if (typeof value !== "string") {
27460
+ throw new Error("Group name must be a string");
27461
+ }
27462
+ const name = value.trim();
27463
+ if (!name) {
27464
+ throw new Error("Group name must not be empty");
27465
+ }
27466
+ if (name.length > GROUP_NAME_MAX_LENGTH) {
27467
+ throw new Error(`Group name must be at most ${GROUP_NAME_MAX_LENGTH} characters`);
27468
+ }
27469
+ return name;
27470
+ }
27456
27471
  var CONFIG_ONLY_PREFIXES = [META_DIR, NODES_DIR, SHARED_DIR];
27457
27472
  var LOCAL_IDB_BACKEND_ID = "local-idb";
27458
27473
  function tombstoneFileName(filePath) {
@@ -28638,6 +28653,14 @@ var ZenFSConfig = (() => {
28638
28653
  `Backend "${id}" has the same configuration as existing backend "${dup.id}" (type=${type}). Use removeBackend("${dup.id}") first, or connect with the existing backend's ID.`
28639
28654
  );
28640
28655
  }
28656
+ await this.setupReplica(id, type, options, description);
28657
+ }
28658
+ /**
28659
+ * Instantiate a config-sync replica, persist its descriptor, create its
28660
+ * sync pair, register lifecycle hooks and run the initial sync/watch.
28661
+ * Shared by addBackend() and replaceBackend().
28662
+ */
28663
+ async setupReplica(id, type, options, description) {
28641
28664
  log6.log(`[ConfigRepo] addBackend: creating ${id} (${type})...`);
28642
28665
  const instance = await createBackend({ type, options });
28643
28666
  const syncable = backendToSyncableFS(instance, `${type}(${id})`);
@@ -28677,6 +28700,7 @@ var ZenFSConfig = (() => {
28677
28700
  log6.log(`[ConfigRepo] addBackend: ${id} (${type}) added, sync pair=${pair.pairId}`);
28678
28701
  await this.syncMetaToReplicas();
28679
28702
  this.syncEngine.watch(pair.pairId);
28703
+ return pair.pairId;
28680
28704
  }
28681
28705
  async removeBackend(id) {
28682
28706
  this.assertNotDisposed();
@@ -28713,6 +28737,60 @@ var ZenFSConfig = (() => {
28713
28737
  this.schedulePostDeleteSync();
28714
28738
  log6.log(`[ConfigRepo] removeBackend: ${id} removed (tombstone written, remote cleaned)`);
28715
28739
  }
28740
+ /**
28741
+ * Replace a config-sync backend's parameters in place (same id).
28742
+ *
28743
+ * Probe the new parameters first: if the backend cannot even be created
28744
+ * (e.g. missing token), nothing is touched and the error is rethrown.
28745
+ * Otherwise the old pair is removed, the descriptor rewritten, and a new
28746
+ * pair created against the new target with an initial sync. If that fails,
28747
+ * the old descriptor and pair are restored. The descriptor file is never
28748
+ * tombstoned, so this never delete-then-recreates it.
28749
+ */
28750
+ async replaceBackend(id, type, options, description) {
28751
+ this.assertNotDisposed();
28752
+ if (id === LOCAL_IDB_BACKEND_ID) {
28753
+ throw new Error("Cannot edit the local IndexedDB primary backend");
28754
+ }
28755
+ const all = await this.readAllBackendDescriptors();
28756
+ const before = all.find((b) => b.id === id);
28757
+ if (!before) {
28758
+ throw new Error(`Backend "${id}" not found`);
28759
+ }
28760
+ const probe = await createBackend({ type, options });
28761
+ try {
28762
+ await probe.dispose?.();
28763
+ } catch {
28764
+ }
28765
+ const newKey = backendDedupKey({ id, type, options });
28766
+ const dup = all.find((b) => b.id !== id && backendDedupKey(b) === newKey);
28767
+ if (dup) {
28768
+ throw new Error(
28769
+ `\u65B0\u53C2\u6570\u4E0E\u5DF2\u6709\u540E\u7AEF\u300C${dup.id}\u300D\u6307\u5411\u540C\u4E00\u8FDC\u7AEF\uFF08\u7C7B\u578B\u4E0E\u53C2\u6570\u5B8C\u5168\u76F8\u540C\uFF09\uFF0C\u8BF7\u5148\u5220\u9664\u91CD\u590D\u540E\u7AEF\u300C${dup.id}\u300D\u6216\u6539\u7528\u4E0D\u540C\u53C2\u6570`
28770
+ );
28771
+ }
28772
+ const oldReplica = this.replicaBackends.get(id);
28773
+ if (oldReplica) {
28774
+ this.syncEngine.removePair(oldReplica.pairId);
28775
+ this.replicaBackends.delete(id);
28776
+ try {
28777
+ await oldReplica.instance?.dispose?.();
28778
+ } catch {
28779
+ }
28780
+ }
28781
+ try {
28782
+ await this.setupReplica(id, type, options, description ?? before.description);
28783
+ } catch (err2) {
28784
+ const reason = err2 instanceof Error ? err2.message : String(err2);
28785
+ log6.warn(`[ConfigRepo] replaceBackend: "${id}" failed, rolling back old options:`, err2);
28786
+ try {
28787
+ await this.setupReplica(id, before.type, before.options, before.description);
28788
+ } catch (rollbackErr) {
28789
+ log6.error(`[ConfigRepo] replaceBackend: rollback for "${id}" ALSO failed:`, rollbackErr);
28790
+ }
28791
+ throw new Error(`\u66F4\u65B0\u540E\u7AEF\u53C2\u6570\u5931\u8D25\uFF1A${reason}\uFF08\u5DF2\u5C1D\u8BD5\u56DE\u6EDA\u65E7\u53C2\u6570\uFF09`);
28792
+ }
28793
+ }
28716
28794
  // -----------------------------------------------------------------------
28717
28795
  // IConfigRepo — Group Type
28718
28796
  // -----------------------------------------------------------------------
@@ -28808,9 +28886,11 @@ var ZenFSConfig = (() => {
28808
28886
  */
28809
28887
  async updateAppDataGroupDescriptor(id, backends) {
28810
28888
  this.assertNotDisposed();
28889
+ const existing = await this.readAppDataGroupDescriptor(id);
28811
28890
  const descriptor = {
28812
28891
  id,
28813
28892
  groupType: "data-sync",
28893
+ ...existing?.name ? { name: existing.name } : {},
28814
28894
  backends
28815
28895
  };
28816
28896
  const descPath = this.appDataGroupFilePath(id);
@@ -28821,6 +28901,140 @@ var ZenFSConfig = (() => {
28821
28901
  const version2 = await incrementVersion(this.fullFS, descPath, bytes, author);
28822
28902
  await this.writeVersionSidecar(descPath, version2);
28823
28903
  }
28904
+ /**
28905
+ * Change a data-sync group's display name only. `id`, backends, local stores
28906
+ * and remote data are untouched, so existing sync pairs keep working.
28907
+ */
28908
+ async updateAppDataGroupName(id, name) {
28909
+ this.assertNotDisposed();
28910
+ const normalized = normalizeGroupName(name);
28911
+ const existing = await this.readAppDataGroupDescriptor(id);
28912
+ if (!existing) {
28913
+ throw new Error(`App data group "${id}" not found`);
28914
+ }
28915
+ const descriptor = {
28916
+ ...existing,
28917
+ id,
28918
+ groupType: "data-sync",
28919
+ name: normalized
28920
+ };
28921
+ const descPath = this.appDataGroupFilePath(id);
28922
+ await this.ensureDir(descPath);
28923
+ const bytes = new TextEncoder().encode(JSON.stringify(descriptor, null, 2));
28924
+ await this.cachedFS.writeFile(descPath, bytes);
28925
+ const author = `${this.appId}/${this.nodeId}`;
28926
+ const version2 = await incrementVersion(this.fullFS, descPath, bytes, author);
28927
+ await this.writeVersionSidecar(descPath, version2);
28928
+ }
28929
+ /**
28930
+ * Replace a data-sync backend's parameters in place (same backend id).
28931
+ *
28932
+ * Changing parameters means switching to a different remote target: the live
28933
+ * group is disposed (old pairs torn down), the descriptor is rewritten, and a
28934
+ * fresh group instance creates pairs + performs the initial sync. Old remote
28935
+ * data is NOT migrated. If the new options cannot be instantiated, nothing is
28936
+ * touched; if re-initialisation fails, the old descriptor is restored.
28937
+ */
28938
+ async replaceAppDataGroupBackend(groupId, backendId, type, options, description) {
28939
+ this.assertNotDisposed();
28940
+ const descriptor = await this.readAppDataGroupDescriptor(groupId);
28941
+ if (!descriptor) {
28942
+ throw new Error(`App data group "${groupId}" not found`);
28943
+ }
28944
+ const index = descriptor.backends.findIndex((b) => b.id === backendId);
28945
+ if (index < 0) {
28946
+ throw new Error(`Backend "${backendId}" not found in data group "${groupId}"`);
28947
+ }
28948
+ const candidate = { ...descriptor.backends[index], type, options, description: description ?? descriptor.backends[index].description };
28949
+ const mergedOptions = await this.resolveAppDataBackendOptions(candidate);
28950
+ const probe = await createBackend({ type, options: mergedOptions });
28951
+ try {
28952
+ await probe.dispose?.();
28953
+ } catch {
28954
+ }
28955
+ const oldBackends = descriptor.backends.map((b) => ({ ...b }));
28956
+ const nextBackends = descriptor.backends.map(
28957
+ (b, i) => i === index ? { ...candidate, options: mergedOptions } : b
28958
+ );
28959
+ const live = this.appDataGroups.get(groupId);
28960
+ if (live) {
28961
+ await live.dispose();
28962
+ this.appDataGroups.delete(groupId);
28963
+ }
28964
+ await this.updateAppDataGroupDescriptor(groupId, nextBackends);
28965
+ try {
28966
+ const group = new AppDataGroupImpl(
28967
+ groupId,
28968
+ this.appId,
28969
+ nextBackends,
28970
+ this.pollIntervalMs,
28971
+ this
28972
+ );
28973
+ await group.init();
28974
+ this.appDataGroups.set(groupId, group);
28975
+ return group;
28976
+ } catch (err2) {
28977
+ const reason = err2 instanceof Error ? err2.message : String(err2);
28978
+ log6.warn(`[ConfigRepo] replaceAppDataGroupBackend: "${backendId}" failed, rolling back:`, err2);
28979
+ try {
28980
+ await this.updateAppDataGroupDescriptor(groupId, oldBackends);
28981
+ const restored = new AppDataGroupImpl(
28982
+ groupId,
28983
+ this.appId,
28984
+ oldBackends,
28985
+ this.pollIntervalMs,
28986
+ this
28987
+ );
28988
+ await restored.init();
28989
+ this.appDataGroups.set(groupId, restored);
28990
+ } catch (rollbackErr) {
28991
+ log6.error("[ConfigRepo] replaceAppDataGroupBackend: rollback ALSO failed:", rollbackErr);
28992
+ }
28993
+ throw new Error(`\u66F4\u65B0\u540E\u7AEF\u53C2\u6570\u5931\u8D25\uFF1A${reason}\uFF08\u5DF2\u5C1D\u8BD5\u56DE\u6EDA\u65E7\u53C2\u6570\uFF09`);
28994
+ }
28995
+ }
28996
+ async getConfigSyncGroupDescriptor() {
28997
+ this.assertNotDisposed();
28998
+ try {
28999
+ const raw = await this.cachedFS.readFile(CONFIG_SYNC_GROUP_FILE);
29000
+ const parsed = JSON.parse(new TextDecoder().decode(toUint8Array2(raw)));
29001
+ if (parsed && parsed.groupType === "config-sync") {
29002
+ return parsed;
29003
+ }
29004
+ } catch {
29005
+ }
29006
+ return null;
29007
+ }
29008
+ /**
29009
+ * Change the config-sync group's display name only. Backends, the local
29010
+ * store and remote data are untouched.
29011
+ */
29012
+ async updateConfigSyncGroupDescriptor(patch) {
29013
+ this.assertNotDisposed();
29014
+ const normalized = normalizeGroupName(patch?.name);
29015
+ const descriptor = {
29016
+ groupType: "config-sync",
29017
+ name: normalized
29018
+ };
29019
+ await this.ensureDir(CONFIG_SYNC_GROUP_FILE);
29020
+ const bytes = new TextEncoder().encode(JSON.stringify(descriptor, null, 2));
29021
+ await this.cachedFS.writeFile(CONFIG_SYNC_GROUP_FILE, bytes);
29022
+ const author = `${this.appId}/${this.nodeId}`;
29023
+ const version2 = await incrementVersion(this.fullFS, CONFIG_SYNC_GROUP_FILE, bytes, author);
29024
+ await this.writeVersionSidecar(CONFIG_SYNC_GROUP_FILE, version2);
29025
+ return descriptor;
29026
+ }
29027
+ async readAppDataGroupDescriptor(id) {
29028
+ try {
29029
+ const raw = await this.cachedFS.readFile(this.appDataGroupFilePath(id));
29030
+ const parsed = JSON.parse(new TextDecoder().decode(toUint8Array2(raw)));
29031
+ if (parsed && parsed.id === id && parsed.groupType === "data-sync") {
29032
+ return parsed;
29033
+ }
29034
+ } catch {
29035
+ }
29036
+ return null;
29037
+ }
28824
29038
  async getAppDataGroup(id) {
28825
29039
  this.assertNotDisposed();
28826
29040
  const cached = this.appDataGroups.get(id);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zen-fs-config",
3
- "version": "0.5.45",
3
+ "version": "0.5.47",
4
4
  "description": "Distributed config management library built on ZenFS, zen-fs-cache, and zen-fs-sync",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",