@jr2804/livesync-cli 1.0.29-cli.1 → 1.0.30-cli.1

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.
Files changed (2) hide show
  1. package/dist/index.cjs +549 -123
  2. package/package.json +1 -1
package/dist/index.cjs CHANGED
@@ -86,6 +86,16 @@ function validateCloudflareTurnConfiguration(value) {
86
86
  if (typeof apiToken !== "string" || apiToken.length === 0) return "Enter a TURN Key API Token.";
87
87
  if (apiToken.length > MAX_BEARER_TOKEN_LENGTH || !BEARER_TOKEN_PATTERN.test(apiToken)) return "TURN Key API Token must use Bearer token syntax.";
88
88
  }
89
+ //#endregion
90
+ //#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/common/coreEnvFunctions.js
91
+ var _getLanguage = () => "en";
92
+ function getLanguage() {
93
+ return _getLanguage();
94
+ }
95
+ var compatGlobal = typeof window !== "undefined" ? window : globalThis;
96
+ var _fetch = compatGlobal.fetch.bind(compatGlobal);
97
+ var activeDocumentWindow = compatGlobal;
98
+ var _activeDocument = activeDocumentWindow.activeDocument ?? activeDocumentWindow.document;
89
99
  var FAILURE_MESSAGES = {
90
100
  configuration: "The Cloudflare TURN configuration is invalid.",
91
101
  authentication: "The Cloudflare TURN credential request was not authorised.",
@@ -284,14 +294,14 @@ async function acquireCloudflareTurnCredentials(configuration, dependencies, sig
284
294
  }
285
295
  let timeoutId;
286
296
  const deadline = new Promise((_resolve, reject) => {
287
- timeoutId = globalThis.setTimeout(() => {
297
+ timeoutId = compatGlobal.setTimeout(() => {
288
298
  timedOut = true;
289
299
  requestController.abort();
290
300
  reject(credentialFailure("unavailable", true));
291
301
  }, requestDeadlineMs);
292
302
  });
293
303
  const cleanup = () => {
294
- if (timeoutId !== void 0) globalThis.clearTimeout(timeoutId);
304
+ if (timeoutId !== void 0) compatGlobal.clearTimeout(timeoutId);
295
305
  signal.removeEventListener("abort", onAbort);
296
306
  };
297
307
  const endpoint = `${CLOUDFLARE_TURN_CREDENTIAL_ENDPOINT}/${configuration.turnKeyId}/credentials/generate-ice-servers`;
@@ -4284,16 +4294,6 @@ minimatch.Minimatch = Minimatch;
4284
4294
  minimatch.escape = escape;
4285
4295
  minimatch.unescape = unescape;
4286
4296
  //#endregion
4287
- //#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/common/coreEnvFunctions.js
4288
- var _getLanguage = () => "en";
4289
- function getLanguage() {
4290
- return _getLanguage();
4291
- }
4292
- var compatGlobal = typeof window !== "undefined" ? window : globalThis;
4293
- var _fetch = compatGlobal.fetch.bind(compatGlobal);
4294
- var activeDocumentWindow = compatGlobal;
4295
- var _activeDocument = activeDocumentWindow.activeDocument ?? activeDocumentWindow.document;
4296
- //#endregion
4297
4297
  //#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/mods.js
4298
4298
  var webcrypto$5;
4299
4299
  async function getWebCrypto() {
@@ -7453,6 +7453,7 @@ var REPLICATION_PROGRESS_PRESENTATIONS = Object.freeze({
7453
7453
  var REPLICATION_COMPLETED = Object.freeze({ status: "completed" });
7454
7454
  var REPLICATION_CANCELLED = Object.freeze({ status: "cancelled" });
7455
7455
  var CENTRAL_REMOTE_REPLICATION_READINESS = Object.freeze({ centralRemotePreparation: "required" });
7456
+ var PROVIDER_OWNED_CENTRAL_REMOTE_REPLICATION_READINESS = Object.freeze({ centralRemotePreparation: "provider-owned" });
7456
7457
  var PEER_REPLICATION_READINESS = Object.freeze({ centralRemotePreparation: "not-applicable" });
7457
7458
  function isReplicationCompleted(outcome) {
7458
7459
  return outcome.status === "completed";
@@ -11890,10 +11891,10 @@ var HeadlessAPIService = class extends InjectableAPIService {
11890
11891
  return "headless-app";
11891
11892
  }
11892
11893
  getAppVersion() {
11893
- return `1.0.29`;
11894
+ return `1.0.30`;
11894
11895
  }
11895
11896
  getPluginVersion() {
11896
- return `1.0.29`;
11897
+ return `1.0.30`;
11897
11898
  }
11898
11899
  getPlatform() {
11899
11900
  return "server";
@@ -16159,6 +16160,9 @@ async function putDBEntryWithLiveBaseRevision(host, managers, note, baseRevision
16159
16160
  throw ex;
16160
16161
  }
16161
16162
  }
16163
+ async function putDBEntryAsIndependentRoot(host, managers, note) {
16164
+ return await putDBEntryInternal(host, managers, note, false, { mode: "independent-root" });
16165
+ }
16162
16166
  async function putDBEntryInternal(host, managers, note, onlyChunks, revisionTarget) {
16163
16167
  const { localDatabase, chunkManager, splitter } = managers;
16164
16168
  const filename = host.services.path.id2path(note._id, note);
@@ -16192,12 +16196,30 @@ async function putDBEntryInternal(host, managers, note, onlyChunks, revisionTarg
16192
16196
  eden: {}
16193
16197
  };
16194
16198
  return await serialized("file:" + filename, async () => {
16195
- if (revisionTarget.mode !== "latest") newDoc._rev = revisionTarget.baseRevision;
16196
- else try {
16199
+ if (revisionTarget.mode === "force-base" || revisionTarget.mode === "live-base") newDoc._rev = revisionTarget.baseRevision;
16200
+ else if (revisionTarget.mode === "latest") try {
16197
16201
  newDoc._rev = (await localDatabase.get(newDoc._id))._rev;
16198
16202
  } catch (ex) {
16199
16203
  if (isErrorOfMissingDoc(ex)) {} else throw ex;
16200
16204
  }
16205
+ if (revisionTarget.mode === "independent-root") {
16206
+ const randomBytes = compatGlobal.crypto.getRandomValues(new Uint8Array(16));
16207
+ const rootId = Array.from(randomBytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
16208
+ newDoc._rev = `1-${rootId}`;
16209
+ const imported = {
16210
+ ...newDoc,
16211
+ _revisions: {
16212
+ start: 1,
16213
+ ids: [rootId]
16214
+ }
16215
+ };
16216
+ await localDatabase.bulkDocs([imported], { new_edits: false });
16217
+ return (await localDatabase.get(newDoc._id, { rev: newDoc._rev }))._rev === newDoc._rev ? {
16218
+ id: newDoc._id,
16219
+ ok: true,
16220
+ rev: newDoc._rev
16221
+ } : false;
16222
+ }
16201
16223
  const r = revisionTarget.mode === "live-base" ? await localDatabase.put(newDoc) : await localDatabase.put(newDoc, { force: true });
16202
16224
  if (r.ok) return r;
16203
16225
  else return false;
@@ -16323,7 +16345,11 @@ function canFetchRemotely(settings) {
16323
16345
  if (settings.remoteType === RemoteTypes.REMOTE_MINIO) return false;
16324
16346
  return true;
16325
16347
  }
16326
- function computeChunkRetrievalMethod(waitForReady, settings) {
16348
+ function computeChunkRetrievalMethod(waitForReady, settings, localOnly = false) {
16349
+ if (localOnly) return {
16350
+ waitForDelivery: false,
16351
+ preventRemoteRequest: true
16352
+ };
16327
16353
  const isOnDemandFetchEnabled = canFetchRemotely(settings);
16328
16354
  if (!waitForReady) {
16329
16355
  if (isOnDemandFetchEnabled) return {
@@ -16340,7 +16366,7 @@ function computeChunkRetrievalMethod(waitForReady, settings) {
16340
16366
  preventRemoteRequest: !isOnDemandFetchEnabled
16341
16367
  };
16342
16368
  }
16343
- async function respondEntryFromMeta({ localDatabase, chunkManager }, settings, filename, meta, dump, waitForReady) {
16369
+ async function respondEntryFromMeta({ localDatabase, chunkManager }, settings, filename, meta, dump, waitForReady, localOnly = false) {
16344
16370
  const dispFilename = stripAllPrefixes(filename);
16345
16371
  const deleted = meta.deleted ?? meta._deleted ?? void 0;
16346
16372
  if (dump) {
@@ -16368,7 +16394,7 @@ async function respondEntryFromMeta({ localDatabase, chunkManager }, settings, f
16368
16394
  }));
16369
16395
  edenChunks = Object.fromEntries(chunks2.map((e) => [e._id, e]));
16370
16396
  }
16371
- const { waitForDelivery, preventRemoteRequest } = computeChunkRetrievalMethod(waitForReady, settings);
16397
+ const { waitForDelivery, preventRemoteRequest } = computeChunkRetrievalMethod(waitForReady, settings, localOnly);
16372
16398
  const childrenKeys = [...meta.children];
16373
16399
  const chunks = await chunkManager.read(childrenKeys, {
16374
16400
  skipCache: false,
@@ -16406,7 +16432,7 @@ async function respondEntryFromMeta({ localDatabase, chunkManager }, settings, f
16406
16432
  }
16407
16433
  return false;
16408
16434
  }
16409
- async function getDBEntryFromMeta(host, { localDatabase, chunkManager }, meta, dump = false, waitForReady = true) {
16435
+ async function getDBEntryFromMeta(host, { localDatabase, chunkManager }, meta, dump = false, waitForReady = true, localOnly = false) {
16410
16436
  const filename = host.services.path.id2path(meta._id, meta);
16411
16437
  if (!isTargetFile(host, filename)) return false;
16412
16438
  const settings = host.services.setting.currentSettings();
@@ -16414,12 +16440,12 @@ async function getDBEntryFromMeta(host, { localDatabase, chunkManager }, meta, d
16414
16440
  if (meta.type == "newnote" || meta.type == "plain") return await respondEntryFromMeta({
16415
16441
  localDatabase,
16416
16442
  chunkManager
16417
- }, settings, filename, meta, dump, waitForReady);
16443
+ }, settings, filename, meta, dump, waitForReady, localOnly);
16418
16444
  return false;
16419
16445
  }
16420
- async function getDBEntryByPath(host, managers, path, opt, dump = false, waitForReady = true, includeDeleted = false) {
16446
+ async function getDBEntryByPath(host, managers, path, opt, dump = false, waitForReady = true, includeDeleted = false, localOnly = false) {
16421
16447
  const meta = await getDBEntryMetaByPath(host, managers, path, opt, includeDeleted);
16422
- if (meta) return await getDBEntryFromMeta(host, managers, meta, dump, waitForReady);
16448
+ if (meta) return await getDBEntryFromMeta(host, managers, meta, dump, waitForReady, localOnly);
16423
16449
  else return false;
16424
16450
  }
16425
16451
  async function deleteDBEntryByPath(host, { localDatabase }, path, opt) {
@@ -16518,11 +16544,11 @@ var EntryManager = class {
16518
16544
  async getDBEntryMeta(path, opt, includeDeleted = false) {
16519
16545
  return await getDBEntryMetaByPath(this.serviceHost, this, path, opt, includeDeleted);
16520
16546
  }
16521
- async getDBEntry(path, opt, dump = false, waitForReady = true, includeDeleted = false) {
16522
- return await getDBEntryByPath(this.serviceHost, this, path, opt, dump, waitForReady, includeDeleted);
16547
+ async getDBEntry(path, opt, dump = false, waitForReady = true, includeDeleted = false, localOnly = false) {
16548
+ return await getDBEntryByPath(this.serviceHost, this, path, opt, dump, waitForReady, includeDeleted, localOnly);
16523
16549
  }
16524
- async getDBEntryFromMeta(meta, dump = false, waitForReady = true) {
16525
- return await getDBEntryFromMeta(this.serviceHost, this, meta, dump, waitForReady);
16550
+ async getDBEntryFromMeta(meta, dump = false, waitForReady = true, localOnly = false) {
16551
+ return await getDBEntryFromMeta(this.serviceHost, this, meta, dump, waitForReady, localOnly);
16526
16552
  }
16527
16553
  async deleteDBEntry(path, opt) {
16528
16554
  return await deleteDBEntryByPath(this.serviceHost, this, path, opt);
@@ -16536,6 +16562,10 @@ var EntryManager = class {
16536
16562
  async putDBEntryWithLiveBaseRevision(note, baseRevision, onlyChunks) {
16537
16563
  return await putDBEntryWithLiveBaseRevision(this.serviceHost, this, note, baseRevision, onlyChunks);
16538
16564
  }
16565
+ /** Store unknown ancestry as a fresh root; return the Metadata write result or `false`. */
16566
+ async putDBEntryAsIndependentRoot(note) {
16567
+ return await putDBEntryAsIndependentRoot(this.serviceHost, this, note);
16568
+ }
16539
16569
  };
16540
16570
  //#endregion
16541
16571
  //#region ../../../node_modules/octagonal-wheels/dist/hash/purejs.js
@@ -20752,11 +20782,11 @@ var LiveSyncLocalDB = class {
20752
20782
  async getDBEntryMeta(path, opt, includeDeleted = false) {
20753
20783
  return await this.managers.entryManager.getDBEntryMeta(path, opt, includeDeleted);
20754
20784
  }
20755
- async getDBEntry(path, opt, dump = false, waitForReady = true, includeDeleted = false) {
20756
- return await this.managers.entryManager.getDBEntry(path, opt, dump, waitForReady, includeDeleted);
20785
+ async getDBEntry(path, opt, dump = false, waitForReady = true, includeDeleted = false, localOnly = false) {
20786
+ return await this.managers.entryManager.getDBEntry(path, opt, dump, waitForReady, includeDeleted, localOnly);
20757
20787
  }
20758
- async getDBEntryFromMeta(meta, dump = false, waitForReady = true) {
20759
- return await this.managers.entryManager.getDBEntryFromMeta(meta, dump, waitForReady);
20788
+ async getDBEntryFromMeta(meta, dump = false, waitForReady = true, localOnly = false) {
20789
+ return await this.managers.entryManager.getDBEntryFromMeta(meta, dump, waitForReady, localOnly);
20760
20790
  }
20761
20791
  async deleteDBEntry(path, opt) {
20762
20792
  return await this.managers.entryManager.deleteDBEntry(path, opt);
@@ -20770,6 +20800,10 @@ var LiveSyncLocalDB = class {
20770
20800
  async putDBEntryWithLiveBaseRevision(note, baseRevision, onlyChunks) {
20771
20801
  return await this.managers.entryManager.putDBEntryWithLiveBaseRevision(note, baseRevision, onlyChunks);
20772
20802
  }
20803
+ /** Preserve existing branches and delegate a fresh root write to the entry manager. */
20804
+ async putDBEntryAsIndependentRoot(note) {
20805
+ return await this.managers.entryManager.putDBEntryAsIndependentRoot(note);
20806
+ }
20773
20807
  async getConflictedDoc(path, rev) {
20774
20808
  return await this.managers.conflictManager.getConflictedDoc(path, rev);
20775
20809
  }
@@ -34735,8 +34769,8 @@ var ModuleResolvingMismatchedTweaks = class extends AbstractModule {
34735
34769
  };
34736
34770
  //#endregion
34737
34771
  //#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/common/coreEnvVars.js
34738
- var manifestVersion = "1.0.29";
34739
- var packageVersion = "1.0.29";
34772
+ var manifestVersion = "1.0.30";
34773
+ var packageVersion = "1.0.30";
34740
34774
  //#endregion
34741
34775
  //#region ../../../node_modules/octagonal-wheels/dist/iterable/map.js
34742
34776
  /**
@@ -37645,6 +37679,7 @@ var JournalSyncCore = class {
37645
37679
  env;
37646
37680
  store;
37647
37681
  requestedStop = false;
37682
+ syncParamsHandler;
37648
37683
  getInitialSyncParameters() {
37649
37684
  return Promise.resolve({
37650
37685
  ...DEFAULT_SYNC_PARAMETERS,
@@ -37688,7 +37723,6 @@ var JournalSyncCore = class {
37688
37723
  this.store = store;
37689
37724
  this.hash = this.getHash(settings);
37690
37725
  this.storage = storage;
37691
- clearHandlers();
37692
37726
  }
37693
37727
  async downloadJson(key) {
37694
37728
  try {
@@ -37735,7 +37769,7 @@ var JournalSyncCore = class {
37735
37769
  this.store = store;
37736
37770
  this.hash = this.getHash(settings);
37737
37771
  this.storage.applyNewConfig(settings);
37738
- clearHandlers();
37772
+ this.resetAllCaches();
37739
37773
  }
37740
37774
  updateInfo(info) {
37741
37775
  const old = this.env.services.replicator.replicationStatics.value;
@@ -37786,23 +37820,18 @@ var JournalSyncCore = class {
37786
37820
  return this._currentCheckPointInfo;
37787
37821
  }
37788
37822
  resetAllCaches() {
37789
- clearHandlers();
37823
+ this.syncParamsHandler = void 0;
37790
37824
  }
37791
37825
  async resetCheckpointInfo() {
37792
37826
  await this.updateCheckPointInfo((info) => ({ ...CheckPointInfoDefault }));
37793
- clearHandlers();
37794
37827
  }
37795
37828
  getJournalEpochFromSyncParams(params) {
37796
37829
  return `${params.protocolVersion}:${params.pbkdf2salt}`;
37797
37830
  }
37798
37831
  async ensureCheckpointCachesAreFresh() {
37799
- let journalEpoch = "";
37800
- try {
37801
- const params = await this.getSyncParameters();
37802
- journalEpoch = this.getJournalEpochFromSyncParams(params);
37803
- } catch {
37804
- return;
37805
- }
37832
+ const params = await this.getSyncParamsHandler().fetch(true);
37833
+ if (!params) throw new SyncParamsFetchError("Could not prepare Journal synchronisation parameters");
37834
+ const journalEpoch = this.getJournalEpochFromSyncParams(params);
37806
37835
  const current = await this.getCheckpointInfo();
37807
37836
  if (current.journalEpoch === journalEpoch) return;
37808
37837
  const lastSentFile = [...current.sentFiles].sort().pop();
@@ -37836,12 +37865,12 @@ var JournalSyncCore = class {
37836
37865
  receivedFiles: /* @__PURE__ */ new Set(),
37837
37866
  sentFiles: /* @__PURE__ */ new Set()
37838
37867
  }));
37839
- clearHandlers();
37840
37868
  }
37841
37869
  async isAvailable() {
37842
37870
  return await this.storage.isAvailable();
37843
37871
  }
37844
37872
  async resetBucket() {
37873
+ this.resetAllCaches();
37845
37874
  let files = [];
37846
37875
  try {
37847
37876
  do {
@@ -37849,7 +37878,6 @@ var JournalSyncCore = class {
37849
37878
  if (files.length == 0) break;
37850
37879
  if (!await this.storage.deleteFiles(files)) return false;
37851
37880
  } while (files.length != 0);
37852
- clearHandlers();
37853
37881
  } catch (ex) {
37854
37882
  Logger(`WARNING! Could not delete files.`, 64, "reset-bucket");
37855
37883
  Logger(ex, 16);
@@ -37869,11 +37897,14 @@ var JournalSyncCore = class {
37869
37897
  return this.getHash(this._settings);
37870
37898
  }
37871
37899
  async getReplicationPBKDF2Salt(refresh) {
37872
- return await createSyncParamsHanderForServer(this.getRemoteKey(), {
37900
+ return await this.getSyncParamsHandler().getPBKDF2Salt(refresh);
37901
+ }
37902
+ getSyncParamsHandler() {
37903
+ return this.syncParamsHandler ??= createSyncParamsHandler({
37873
37904
  put: (params) => this.putSyncParameters(params),
37874
37905
  get: () => this.getSyncParameters(),
37875
37906
  create: () => this.getInitialSyncParameters()
37876
- }).getPBKDF2Salt(refresh);
37907
+ });
37877
37908
  }
37878
37909
  isEncryptionPrevented(fileName) {
37879
37910
  if (fileName.endsWith("_obsidian_livesync_journal_sync_parameters.json")) return true;
@@ -38283,6 +38314,7 @@ var JournalSyncCore = class {
38283
38314
  /** Stop this Journal operation owner and release its storage transport. */
38284
38315
  dispose() {
38285
38316
  this.requestStop();
38317
+ this.resetAllCaches();
38286
38318
  this.storage.dispose?.();
38287
38319
  }
38288
38320
  };
@@ -56521,11 +56553,15 @@ var LiveSyncJournalReplicator = class extends LiveSyncAbstractReplicator {
56521
56553
  async openReplication(setting, _, showResult, ignoreCleanLock = false, recordCompatibilityDecision) {
56522
56554
  return await this.runJournalTransfer(async (stopGeneration) => {
56523
56555
  const client = this.setupJournalSyncClient(setting);
56524
- stopGeneration = this.journalTransferStopGeneration;
56525
- if (!await this.checkReplicationConnectivity(false, ignoreCleanLock, showResult, setting, client, recordCompatibilityDecision)) return false;
56526
- if (stopGeneration !== this.journalTransferStopGeneration) return false;
56527
- this.hasEnteredReplication = true;
56528
- return await client.sync(showResult);
56556
+ try {
56557
+ stopGeneration = this.journalTransferStopGeneration;
56558
+ if (!await this.checkReplicationConnectivity(false, ignoreCleanLock, showResult, setting, client, recordCompatibilityDecision)) return false;
56559
+ if (stopGeneration !== this.journalTransferStopGeneration) return false;
56560
+ this.hasEnteredReplication = true;
56561
+ return await client.sync(showResult);
56562
+ } finally {
56563
+ client.resetAllCaches();
56564
+ }
56529
56565
  });
56530
56566
  }
56531
56567
  /**
@@ -56548,11 +56584,15 @@ var LiveSyncJournalReplicator = class extends LiveSyncAbstractReplicator {
56548
56584
  async runDirectionalReplication(setting, showingNotice, transfer, recordCompatibilityDecision) {
56549
56585
  return await this.runJournalTransfer(async (stopGeneration) => {
56550
56586
  const client = this.setupJournalSyncClient(setting);
56551
- stopGeneration = this.journalTransferStopGeneration;
56552
- if (!await this.checkReplicationConnectivity(false, false, !!showingNotice, setting, client, recordCompatibilityDecision)) return false;
56553
- if (stopGeneration !== this.journalTransferStopGeneration) return false;
56554
- this.hasEnteredReplication = true;
56555
- return await transfer(client);
56587
+ try {
56588
+ stopGeneration = this.journalTransferStopGeneration;
56589
+ if (!await this.checkReplicationConnectivity(false, false, !!showingNotice, setting, client, recordCompatibilityDecision)) return false;
56590
+ if (stopGeneration !== this.journalTransferStopGeneration) return false;
56591
+ this.hasEnteredReplication = true;
56592
+ return await transfer(client);
56593
+ } finally {
56594
+ client.resetAllCaches();
56595
+ }
56556
56596
  });
56557
56597
  }
56558
56598
  /** Capture only the compatibility decision made by this exact borrowed client. */
@@ -56638,7 +56678,6 @@ var LiveSyncJournalReplicator = class extends LiveSyncAbstractReplicator {
56638
56678
  this.closeReplication();
56639
56679
  try {
56640
56680
  if (!await this.client.resetBucket()) throw new Error("Could not reset remote bucket");
56641
- clearHandlers();
56642
56681
  Logger("Remote Bucket Cleared", 64);
56643
56682
  await this.tryCreateRemoteDatabase(setting);
56644
56683
  } catch (ex) {
@@ -56650,7 +56689,6 @@ var LiveSyncJournalReplicator = class extends LiveSyncAbstractReplicator {
56650
56689
  async tryCreateRemoteDatabase(setting) {
56651
56690
  this.closeReplication();
56652
56691
  Logger("Remote Database Created or Connected", 64);
56653
- clearHandlers();
56654
56692
  if (!await this.ensurePBKDF2Salt(setting, true, false)) throw new Error("Could not ensure PBKDF2 salt (Security Seed)");
56655
56693
  return await Promise.resolve();
56656
56694
  }
@@ -56989,8 +57027,18 @@ function createSecuritySeedResourceFactory(createReplicator) {
56989
57027
  return (setting) => {
56990
57028
  const snapshot = snapshotRemoteSettings(setting);
56991
57029
  const replicator = createReplicator();
57030
+ let readPromise;
57031
+ const read = () => {
57032
+ if (readPromise) return readPromise;
57033
+ const pending = Promise.resolve().then(() => replicator.getReplicationPBKDF2Salt(snapshot, true));
57034
+ readPromise = pending;
57035
+ pending.catch(() => {
57036
+ if (readPromise === pending) readPromise = void 0;
57037
+ });
57038
+ return pending;
57039
+ };
56992
57040
  return Promise.resolve({
56993
- read: () => replicator.getReplicationPBKDF2Salt(snapshot, true),
57041
+ read,
56994
57042
  dispose: createReplicatorDisposer(replicator)
56995
57043
  });
56996
57044
  };
@@ -57212,7 +57260,7 @@ function createCentralReplicatorProviderDefinitions(host) {
57212
57260
  [REMOTE_MINIO]: {
57213
57261
  kind: REMOTE_MINIO,
57214
57262
  diagnosticName: "Object Storage",
57215
- readiness: CENTRAL_REMOTE_REPLICATION_READINESS,
57263
+ readiness: PROVIDER_OWNED_CENTRAL_REMOTE_REPLICATION_READINESS,
57216
57264
  isConfigured: (settings) => settings.remoteType === REMOTE_MINIO && !!settings.endpoint?.trim() && !!settings.bucket?.trim(),
57217
57265
  configurationIdentity: getObjectStorageReplicatorConfigurationIdentity,
57218
57266
  create: () => Promise.resolve(new LiveSyncJournalReplicator(host)),
@@ -59620,14 +59668,6 @@ Total bytes fetched: ${sizeToHumanReadable(progress.totalBytes)}`, 64, "fetch-in
59620
59668
  };
59621
59669
  //#endregion
59622
59670
  //#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/serviceModules/ServiceFileHandlerBase.js
59623
- async function isIncomingTextClearExtension(incomingContent, localContent) {
59624
- const incomingBlob = createBlob(incomingContent);
59625
- const localBlob = createBlob(localContent);
59626
- if (!isTextBlob$1(incomingBlob) || !isTextBlob$1(localBlob)) return false;
59627
- const incomingText = await incomingBlob.text();
59628
- const localText = await localBlob.text();
59629
- return incomingText.startsWith(localText) || incomingText.endsWith(localText);
59630
- }
59631
59671
  async function serializedByKeys(keys, callback) {
59632
59672
  const [key, ...remainingKeys] = keys;
59633
59673
  if (key === void 0) return await callback();
@@ -59649,6 +59689,7 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59649
59689
  setting;
59650
59690
  vault;
59651
59691
  fileReflectionProvenance;
59692
+ deferredConflictChecks = /* @__PURE__ */ new Map();
59652
59693
  constructor(services) {
59653
59694
  super(services);
59654
59695
  this.events = services.events;
@@ -59722,6 +59763,93 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59722
59763
  return matched;
59723
59764
  }
59724
59765
  }
59766
+ /**
59767
+ * Classify a storage read against its displayed database branch.
59768
+ *
59769
+ * A recorded revision identifies the branch and therefore takes precedence
59770
+ * over byte matches. Without a readable base, only current live leaves are
59771
+ * considered. Any match avoids a duplicate write, but only a unique match
59772
+ * identifies provenance; no match is `unknown`.
59773
+ * `preferredPath` selects the provenance key during a rename, and
59774
+ * `currentLoaded` supplies an already decoded candidate body when available.
59775
+ * Missing chunks do not clear provenance unless their metadata is also
59776
+ * missing or deleted.
59777
+ */
59778
+ async classifyStorageContent(file, currentEntry, preferredPath, recordedRevision, currentLoaded) {
59779
+ const path = preferredPath ?? file.path;
59780
+ if (recordedRevision) {
59781
+ const loadedContentIsDecoded = currentLoaded?._rev === recordedRevision;
59782
+ const base = loadedContentIsDecoded ? currentLoaded : await this.db.fetchEntry(file, recordedRevision, true, true, true);
59783
+ if (base && base._rev === recordedRevision && !("deleted" in base && base.deleted) && !("_deleted" in base && base._deleted)) return await isDocContentSame(loadedContentIsDecoded ? base.data : readContent(base), file.body) ? {
59784
+ kind: "unchanged",
59785
+ revision: recordedRevision
59786
+ } : {
59787
+ kind: "edited",
59788
+ revision: recordedRevision
59789
+ };
59790
+ if (!base) {
59791
+ const meta = await this.db.fetchEntryMeta(file, recordedRevision, true);
59792
+ if (!meta || meta.deleted || meta._deleted) await this.deleteProvenance(path);
59793
+ }
59794
+ }
59795
+ const matches = currentEntry ? await this.db.findLiveContentRevisions(file, file.body) : [];
59796
+ if (matches.length) return {
59797
+ kind: "matching-leaf",
59798
+ revision: matches.length === 1 ? matches[0] : void 0
59799
+ };
59800
+ return { kind: "unknown" };
59801
+ }
59802
+ /** Record provenance only when storage matches one unambiguous live leaf. */
59803
+ async rememberMatchingLeaf(path, revision, mtime) {
59804
+ if (revision) await this.setProvenance(path, revision, mtime);
59805
+ }
59806
+ /**
59807
+ * Read the raw provenance value used by an optimistic storage snapshot.
59808
+ * Unlike `getProvenance`, this does not validate or remove the referenced
59809
+ * database revision; an unreadable value is represented as `undefined`.
59810
+ */
59811
+ async readProvenanceSnapshot(path) {
59812
+ try {
59813
+ return (await this.fileReflectionProvenance?.get(path))?.revision;
59814
+ } catch {
59815
+ return;
59816
+ }
59817
+ }
59818
+ /**
59819
+ * Check that storage still has the same path, bytes, timestamp, and
59820
+ * provenance as a previously captured snapshot.
59821
+ */
59822
+ async currentStorageSnapshotMatches(file, revision) {
59823
+ const current = await this.storage.getStub(file.path);
59824
+ if (!current || isFolderInfo(current) || current.path !== file.path) return false;
59825
+ const readCurrent = await this.readFileFromStub(current);
59826
+ return readCurrent.stat.mtime === file.stat.mtime && await isDocContentSame(readCurrent.body, file.body) && await this.readProvenanceSnapshot(file.path) === revision;
59827
+ }
59828
+ /**
59829
+ * Publish provenance after a durable database write if storage is unchanged.
59830
+ * A failed revalidation leaves the database revision stored and asks the
59831
+ * caller to reread storage before proceeding.
59832
+ */
59833
+ async finaliseStoredRevision(file, observedProvenance, storedRevision) {
59834
+ if (await this.currentStorageSnapshotMatches(file, observedProvenance)) {
59835
+ await this.setProvenance(file.path, storedRevision, file.stat.mtime);
59836
+ return true;
59837
+ } else return false;
59838
+ }
59839
+ /**
59840
+ * Reread storage after a restored startup snapshot changed and retry a save.
59841
+ * The bounded counter prevents an unstable file from causing an endless
59842
+ * startup loop; the next event or scan can reconcile a final refusal.
59843
+ */
59844
+ async retryCurrentStorage(path, preferredBasePath, snapshotRetry) {
59845
+ if (snapshotRetry >= 2) {
59846
+ this._log(`Storage kept changing while saving ${path}; a fresh event is required`, 64);
59847
+ return false;
59848
+ }
59849
+ const fresh = await this.storage.getStub(path);
59850
+ if (!fresh || isFolderInfo(fresh)) return false;
59851
+ return await this.storeFileToDBFromRevision(fresh, false, false, preferredBasePath, true, snapshotRetry + 1);
59852
+ }
59725
59853
  getPath(entry) {
59726
59854
  return this.path.getPath(entry);
59727
59855
  }
@@ -59739,9 +59867,17 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59739
59867
  return typeof info === "string" ? await this.storage.getFileStub(info) : info;
59740
59868
  }
59741
59869
  async storeFileToDB(info, force = false, onlyChunks = false) {
59742
- return await this.storeFileToDBFromRevision(info, force, onlyChunks);
59870
+ return await this.serializedByFileEventPaths([getStoragePathFromUXFileInfo(info)], () => this.storeFileToDBFromRevision(info, force, onlyChunks));
59743
59871
  }
59744
59872
  async storeFileToDBWithBaseRevision(info, baseRevision, createIfDifferent = true) {
59873
+ return await this.serializedByFileEventPaths([getStoragePathFromUXFileInfo(info)], () => this.storeFileToDBWithBaseRevisionCore(info, baseRevision, createIfDifferent));
59874
+ }
59875
+ /**
59876
+ * Store current storage content below an exact live revision. A differing
59877
+ * body is rejected when `createIfDifferent` is false; callers hold the
59878
+ * document lock for this core operation.
59879
+ */
59880
+ async storeFileToDBWithBaseRevisionCore(info, baseRevision, createIfDifferent) {
59745
59881
  const file = await this.infoToStub(info);
59746
59882
  if (file == null) {
59747
59883
  this._log(`File ${tryGetFilePath(info)} is not exist on the storage`, 16);
@@ -59766,7 +59902,7 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59766
59902
  const loadedBase = await this.db.fetchEntry(file, baseRevision, true, true);
59767
59903
  if (loadedBase && await isDocContentSame(getDocDataAsArray(loadedBase.data), readFile.body)) {
59768
59904
  await this.setProvenance(file.path, baseRevision, readFile.stat.mtime);
59769
- await this.conflict.queueCheckFor(file.path);
59905
+ await this.queueConflictCheckFor(file.path);
59770
59906
  return true;
59771
59907
  }
59772
59908
  }
@@ -59777,10 +59913,16 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59777
59913
  const storedRevision = await this.db.storeWithBaseRevision(readFile, baseRevision, true);
59778
59914
  if (storedRevision === false) return false;
59779
59915
  await this.setProvenance(file.path, storedRevision, readFile.stat.mtime);
59780
- await this.conflict.queueCheckFor(file.path);
59916
+ await this.queueConflictCheckFor(file.path);
59781
59917
  return true;
59782
59918
  }
59783
- async storeFileToDBFromRevision(info, force = false, onlyChunks = false, preferredBasePath) {
59919
+ /**
59920
+ * Save one storage snapshot while the caller holds its document lock.
59921
+ * Ordinary saves read once inside the lock and leave retries disabled.
59922
+ * Restored startup events retain bounded rereads because file watching has
59923
+ * not yet started and cannot supply a new event for a concurrent edit.
59924
+ */
59925
+ async storeFileToDBFromRevision(info, force = false, onlyChunks = false, preferredBasePath, retryIfStorageChanges = false, snapshotRetry = 0) {
59784
59926
  const file = await this.infoToStub(info);
59785
59927
  if (file == null) {
59786
59928
  this._log(`File ${tryGetFilePath(info)} is not exist on the storage`, 16);
@@ -59794,9 +59936,39 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59794
59936
  const readFile2 = await this.readFileFromStub(file);
59795
59937
  return await this.db.createChunks(readFile2, force, true);
59796
59938
  }
59939
+ const observedProvenance = await this.readProvenanceSnapshot(preferredBasePath ?? file.path);
59797
59940
  const readFile = await this.readFileFromStub(file);
59798
- const entry = await this.db.fetchEntry(file, void 0, true, true);
59799
- if ((await this.db.getConflictedRevs(file)).length > 0) {
59941
+ const entry = await this.db.fetchEntry(file, void 0, true, true, true);
59942
+ const currentEntry = entry || await this.db.fetchEntryMeta(file, void 0, true);
59943
+ const isConflicted = (await this.db.getConflictedRevs(file)).length > 0;
59944
+ if (!force && currentEntry && !currentEntry.deleted && !currentEntry._deleted) {
59945
+ const classification = await this.classifyStorageContent(readFile, currentEntry, preferredBasePath, observedProvenance, entry ? {
59946
+ _rev: entry._rev,
59947
+ data: readContent(entry)
59948
+ } : void 0);
59949
+ if (retryIfStorageChanges && !await this.currentStorageSnapshotMatches(readFile, observedProvenance)) return await this.retryCurrentStorage(file.path, preferredBasePath, snapshotRetry);
59950
+ if (classification.kind === "unchanged") {
59951
+ if (isConflicted) await this.queueConflictCheckFor(file.path);
59952
+ else if (classification.revision !== currentEntry._rev) {
59953
+ if (!entry) return false;
59954
+ return await this.dbToStorageCore(file.path, file);
59955
+ } else this.path.markChangesAreSame(readFile, readFile.stat.mtime, currentEntry.mtime);
59956
+ return true;
59957
+ }
59958
+ if (classification.kind === "matching-leaf") {
59959
+ await this.rememberMatchingLeaf(file.path, classification.revision, readFile.stat.mtime);
59960
+ if (isConflicted) await this.queueConflictCheckFor(file.path);
59961
+ return true;
59962
+ }
59963
+ const storedRevision2 = classification.kind === "edited" ? await this.db.storeWithBaseRevision(readFile, classification.revision, true) : await this.db.storeIndependentRevision(readFile, true);
59964
+ if (storedRevision2 === false) return false;
59965
+ if (preferredBasePath && preferredBasePath !== file.path) await this.deleteProvenance(preferredBasePath);
59966
+ if (retryIfStorageChanges && !await this.finaliseStoredRevision(readFile, observedProvenance, storedRevision2)) return await this.retryCurrentStorage(file.path, preferredBasePath, snapshotRetry);
59967
+ if (!retryIfStorageChanges) await this.setProvenance(file.path, storedRevision2, readFile.stat.mtime);
59968
+ if (isConflicted || classification.kind === "unknown") await this.queueConflictCheckFor(file.path);
59969
+ return true;
59970
+ }
59971
+ if (isConflicted) {
59800
59972
  const baseRevision = await this.getProvenBaseRevision(readFile, preferredBasePath);
59801
59973
  if (baseRevision) {
59802
59974
  const baseEntry = await this.db.fetchEntry(file, baseRevision, true, true);
@@ -59809,28 +59981,28 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59809
59981
  if (storedRevision3 === false) return false;
59810
59982
  if (preferredBasePath && preferredBasePath !== file.path) await this.deleteProvenance(preferredBasePath);
59811
59983
  await this.setProvenance(file.path, storedRevision3, readFile.stat.mtime);
59812
- await this.conflict.queueCheckFor(file.path);
59984
+ await this.queueConflictCheckFor(file.path);
59813
59985
  return true;
59814
59986
  }
59815
- const currentEntry = entry || await this.db.fetchEntryMeta(file, void 0, true);
59816
- const currentRevision = currentEntry && currentEntry._rev;
59987
+ const currentEntry2 = entry || await this.db.fetchEntryMeta(file, void 0, true);
59988
+ const currentRevision = currentEntry2 && currentEntry2._rev;
59817
59989
  if (!currentRevision) {
59818
59990
  this._log(`Could not preserve the unknown conflict branch for ${file.path}; no current revision is available`, 64);
59819
- await this.conflict.queueCheckFor(file.path);
59991
+ await this.queueConflictCheckFor(file.path);
59820
59992
  return false;
59821
59993
  }
59822
59994
  const storedRevision2 = await this.db.storeAsConflictedRevisionWithResult(readFile, currentRevision, true);
59823
59995
  if (storedRevision2 === false) {
59824
59996
  this._log(`Could not preserve the unknown conflict branch for ${file.path}`, 64);
59825
- await this.conflict.queueCheckFor(file.path);
59997
+ await this.queueConflictCheckFor(file.path);
59826
59998
  return false;
59827
59999
  }
59828
60000
  if (preferredBasePath && preferredBasePath !== file.path) await this.deleteProvenance(preferredBasePath);
59829
60001
  await this.setProvenance(file.path, storedRevision2, readFile.stat.mtime);
59830
- await this.conflict.queueCheckFor(file.path);
60002
+ await this.queueConflictCheckFor(file.path);
59831
60003
  return true;
59832
60004
  }
59833
- if (!entry || entry.deleted || entry._deleted) {
60005
+ if (!currentEntry || currentEntry.deleted || currentEntry._deleted) {
59834
60006
  const storedRevision2 = await this.db.storeWithBaseRevision(readFile, entry && entry._rev, true);
59835
60007
  if (storedRevision2 === false) return false;
59836
60008
  if (preferredBasePath && preferredBasePath !== file.path) await this.deleteProvenance(preferredBasePath);
@@ -59838,7 +60010,7 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59838
60010
  return true;
59839
60011
  }
59840
60012
  let shouldApplied = false;
59841
- if (!force && !onlyChunks) {
60013
+ if (!force && !onlyChunks && entry) {
59842
60014
  if (this.path.compareFileFreshness(file, entry) !== EVEN) shouldApplied = true;
59843
60015
  if (!shouldApplied) if (await isDocContentSame(getDocDataAsArray(entry.data), readFile.body)) this.path.markChangesAreSame(readFile, readFile.stat.mtime, entry.mtime);
59844
60016
  else shouldApplied = true;
@@ -59848,13 +60020,20 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59848
60020
  return true;
59849
60021
  }
59850
60022
  }
59851
- const storedRevision = await this.db.storeWithBaseRevision(readFile, entry._rev, true);
60023
+ const storedRevision = await this.db.storeWithBaseRevision(readFile, currentEntry._rev, true);
59852
60024
  if (storedRevision === false) return false;
59853
60025
  if (preferredBasePath && preferredBasePath !== file.path) await this.deleteProvenance(preferredBasePath);
59854
60026
  await this.setProvenance(file.path, storedRevision, readFile.stat.mtime);
59855
60027
  return true;
59856
60028
  }
59857
60029
  async deleteFileFromDB(info) {
60030
+ return await this.serializedByFileEventPaths([getStoragePathFromUXFileInfo(info)], () => this.deleteFileFromDBCore(info));
60031
+ }
60032
+ /**
60033
+ * Record a storage deletion under the caller's document lock, preserving
60034
+ * the displayed conflict branch when its provenance is known.
60035
+ */
60036
+ async deleteFileFromDBCore(info) {
59858
60037
  const file = await this.infoToStub(info);
59859
60038
  const path = typeof info === "string" ? info : tryGetFilePath(info);
59860
60039
  if (file == null) {
@@ -59871,12 +60050,12 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59871
60050
  const provenance = await this.getProvenance(path);
59872
60051
  if (!provenance) {
59873
60052
  this._log(`The deleted storage file ${path} has conflicts, but its displayed revision is unknown; preserving every database branch`, 64);
59874
- await this.conflict.queueCheckFor(path);
60053
+ await this.queueConflictCheckFor(path);
59875
60054
  return true;
59876
60055
  }
59877
60056
  if (await this.db.storeDeletionWithBaseRevision(path, provenance.revision) === false) return false;
59878
60057
  await this.deleteProvenance(path);
59879
- await this.conflict.queueCheckFor(path);
60058
+ await this.queueConflictCheckFor(path);
59880
60059
  return true;
59881
60060
  }
59882
60061
  this._log(`File ${path} is missing on storage; deleting from the database by path`, 32);
@@ -59901,12 +60080,12 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59901
60080
  } catch {}
59902
60081
  if (!baseRevision) {
59903
60082
  this._log(`The deleted storage file ${file.path} has conflicts, but its displayed revision is unknown; preserving every database branch`, 64);
59904
- await this.conflict.queueCheckFor(file.path);
60083
+ await this.queueConflictCheckFor(file.path);
59905
60084
  return true;
59906
60085
  }
59907
60086
  if (await this.db.storeDeletionWithBaseRevision(file.path, baseRevision) === false) return false;
59908
60087
  await this.deleteProvenance(file.path);
59909
- await this.conflict.queueCheckFor(file.path);
60088
+ await this.queueConflictCheckFor(file.path);
59910
60089
  return true;
59911
60090
  }
59912
60091
  const deleted = await this.db.delete(file);
@@ -59914,11 +60093,20 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59914
60093
  return deleted;
59915
60094
  }
59916
60095
  async renameFileInDB(info, oldPath) {
60096
+ const newPath = getStoragePathFromUXFileInfo(info);
60097
+ return await this.serializedByFileEventPaths([oldPath, newPath], () => this.renameFileInDBCore(info, oldPath));
60098
+ }
60099
+ /**
60100
+ * Record a rename under the caller's source and target locks. Case-only
60101
+ * renames retain the source provenance while other renames handle the
60102
+ * source conflict before deleting its old path.
60103
+ */
60104
+ async renameFileInDBCore(info, oldPath, retryIfStorageChanges = false) {
59917
60105
  const newPath = getStoragePathFromUXFileInfo(info);
59918
60106
  const [oldDocumentId, newDocumentId] = await Promise.all([this.path.path2id(oldPath), this.path.path2id(newPath)]);
59919
60107
  if (oldDocumentId === newDocumentId) {
59920
60108
  this._log(`Updating the stored path for case-only rename: ${oldPath} -> ${newPath}`, 16);
59921
- return await this.storeFileToDBFromRevision(info, true, false, oldPath);
60109
+ return await this.storeFileToDBFromRevision(info, true, false, oldPath, retryIfStorageChanges);
59922
60110
  }
59923
60111
  const oldEntry = await this.db.fetchEntryMeta(oldPath, void 0, true);
59924
60112
  const newEntry = await this.db.fetchEntryMeta(newPath, void 0, true);
@@ -59926,7 +60114,7 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59926
60114
  this._log(`Refusing to overwrite the existing database entry while renaming ${oldPath} to ${newPath}`, 64);
59927
60115
  return false;
59928
60116
  }
59929
- if (!await this.storeFileToDB(info, true)) {
60117
+ if (!await this.storeFileToDBFromRevision(info, true, false, void 0, retryIfStorageChanges)) {
59930
60118
  this._log(`Failed to store rename target; preserving source in the database: ${oldPath}`, 64);
59931
60119
  return false;
59932
60120
  }
@@ -59943,12 +60131,12 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59943
60131
  }
59944
60132
  if (!baseRevision) {
59945
60133
  this._log(`Renamed ${oldPath} to ${newPath}, but preserved every conflicted source branch because the displayed source revision is unknown`, 64);
59946
- await this.conflict.queueCheckFor(oldPath);
60134
+ await this.queueConflictCheckFor(oldPath);
59947
60135
  return true;
59948
60136
  }
59949
60137
  if (await this.db.storeDeletionWithBaseRevision(oldPath, baseRevision) === false) return false;
59950
60138
  await this.deleteProvenance(oldPath);
59951
- await this.conflict.queueCheckFor(oldPath);
60139
+ await this.queueConflictCheckFor(oldPath);
59952
60140
  return true;
59953
60141
  }
59954
60142
  const deleted = await this.db.delete(oldPath);
@@ -59956,6 +60144,10 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59956
60144
  return deleted;
59957
60145
  }
59958
60146
  async deleteRevisionFromDB(info, rev) {
60147
+ return await this.serializedByFileEventPaths([getStoragePathFromUXFileInfo(info)], () => this.deleteRevisionFromDBCore(info, rev));
60148
+ }
60149
+ /** Delete one selected revision and clear matching provenance under the caller's document lock. */
60150
+ async deleteRevisionFromDBCore(info, rev) {
59959
60151
  const path = getStoragePathFromUXFileInfo(info);
59960
60152
  const provenance = await this.getProvenance(path);
59961
60153
  const deleted = await this.db.delete(info, rev);
@@ -59963,6 +60155,13 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59963
60155
  return deleted;
59964
60156
  }
59965
60157
  async resolveConflictedByDeletingRevision(info, rev) {
60158
+ return await this.serializedByFileEventPaths([getStoragePathFromUXFileInfo(info)], () => this.resolveConflictedByDeletingRevisionCore(info, rev));
60159
+ }
60160
+ /**
60161
+ * Apply the legacy resolve-by-delete sequence while holding one document
60162
+ * lock; metadata is captured before the selected revision is removed.
60163
+ */
60164
+ async resolveConflictedByDeletingRevisionCore(info, rev) {
59966
60165
  const path = getStoragePathFromUXFileInfo(info);
59967
60166
  const file = await this.infoToStub(info);
59968
60167
  const docEntry = await this.db.fetchEntryMeta(file ?? info, rev, true);
@@ -59970,7 +60169,7 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59970
60169
  this._log(`Failed to read the conflicted revision ${rev} of ${path}`, 16);
59971
60170
  return false;
59972
60171
  }
59973
- if (!await this.deleteRevisionFromDB(info, rev)) {
60172
+ if (!await this.deleteRevisionFromDBCore(info, rev)) {
59974
60173
  this._log(`Failed to delete the conflicted revision ${rev} of ${path}`, 16);
59975
60174
  return false;
59976
60175
  }
@@ -59985,6 +60184,13 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59985
60184
  this._log(`Cannot select database revision ${rev} without a file path`, 16);
59986
60185
  return false;
59987
60186
  }
60187
+ return await this.serializedByFileEventPaths([getStoragePathFromUXFileInfo(info)], () => this.dbToStorageWithSpecificRevCore(info, rev, force));
60188
+ }
60189
+ /**
60190
+ * Reflect a selected live revision under the caller's document lock.
60191
+ * The public wrapper performs the same lock acquisition before entering here.
60192
+ */
60193
+ async dbToStorageWithSpecificRevCore(info, rev, force) {
59988
60194
  const file = await this.infoToStub(info);
59989
60195
  const databaseTarget = file ?? info;
59990
60196
  const [docEntry, currentEntry, conflictedRevisions] = await Promise.all([
@@ -60003,6 +60209,11 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
60003
60209
  return await this.applyDatabaseEntryToStorage(docEntry, file, force, true);
60004
60210
  }
60005
60211
  async dbToStorage(entryInfo, info, force) {
60212
+ const pathFromEntryInfo = typeof entryInfo === "string" ? entryInfo : this.getPath(entryInfo);
60213
+ return await this.serializedByFileEventPaths([pathFromEntryInfo], () => this.dbToStorageCore(entryInfo, info, force));
60214
+ }
60215
+ /** Fetch the current metadata and reflect it while the caller holds its lock. */
60216
+ async dbToStorageCore(entryInfo, info, force) {
60006
60217
  const file = await this.infoToStub(info);
60007
60218
  const pathFromEntryInfo = typeof entryInfo === "string" ? entryInfo : this.getPath(entryInfo);
60008
60219
  const docEntry = await this.db.fetchEntryMeta(pathFromEntryInfo, void 0, true);
@@ -60012,12 +60223,18 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
60012
60223
  }
60013
60224
  return await this.applyDatabaseEntryToStorage(docEntry, file, force);
60014
60225
  }
60015
- async applyDatabaseEntryToStorage(docEntry, file, force, allowExistingConflicts = false) {
60226
+ /**
60227
+ * Reflect one database revision while protecting concurrent storage edits.
60228
+ * Overwrite and deletion paths preserve changed bytes first, then revalidate
60229
+ * their snapshot and the current database revision immediately before the
60230
+ * destructive operation.
60231
+ */
60232
+ async applyDatabaseEntryToStorage(docEntry, file, force, allowExistingConflicts = false, incomingRetry = 0) {
60016
60233
  const mode = file == null ? "create" : "modify";
60017
60234
  const path = this.getPath(docEntry);
60018
60235
  const settings = this.setting.currentSettings();
60019
60236
  if ((await this.db.getConflictedRevs(path)).length > 0 && !allowExistingConflicts) if (settings.writeDocumentsIfConflicted) {} else {
60020
- await this.conflict.queueCheckForIfOpen(path);
60237
+ await this.queueConflictCheckFor(path, true);
60021
60238
  return true;
60022
60239
  }
60023
60240
  let existDoc = await this.storage.getStub(path);
@@ -60032,7 +60249,28 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
60032
60249
  return true;
60033
60250
  }
60034
60251
  if (!existOnDB && existDoc) {
60035
- if (!force && !settings.writeDocumentsIfConflicted && await this.preserveUnsyncedStorageAsConflict(path, existDoc, docEntry)) return true;
60252
+ let safeDeletionSnapshot;
60253
+ if (!force && !settings.writeDocumentsIfConflicted) {
60254
+ let protection = await this.preserveUnsyncedStorageAsConflict(path, existDoc, docEntry);
60255
+ if (protection.preserved) return true;
60256
+ if (!protection.snapshot || !await this.currentStorageSnapshotMatches(protection.snapshot.file, protection.snapshot.revision)) {
60257
+ protection = await this.recheckIncomingStorage(path, docEntry, void 0, allowExistingConflicts);
60258
+ if (protection.preserved) return true;
60259
+ if (!protection.snapshot || !await this.currentStorageSnapshotMatches(protection.snapshot.file, protection.snapshot.revision)) return false;
60260
+ }
60261
+ safeDeletionSnapshot = protection.snapshot;
60262
+ }
60263
+ let latest2 = await this.reconcileAdvancedIncomingRevision(docEntry, path, force, allowExistingConflicts, incomingRetry);
60264
+ if (latest2 !== void 0) return latest2;
60265
+ if (safeDeletionSnapshot && !await this.currentStorageSnapshotMatches(safeDeletionSnapshot.file, safeDeletionSnapshot.revision)) {
60266
+ const protection = await this.recheckIncomingStorage(path, docEntry, void 0, allowExistingConflicts);
60267
+ if (protection.preserved) return true;
60268
+ if (!protection.snapshot || !await this.currentStorageSnapshotMatches(protection.snapshot.file, protection.snapshot.revision)) return false;
60269
+ safeDeletionSnapshot = protection.snapshot;
60270
+ latest2 = await this.reconcileAdvancedIncomingRevision(docEntry, path, force, allowExistingConflicts, incomingRetry);
60271
+ if (latest2 !== void 0) return latest2;
60272
+ if (!await this.currentStorageSnapshotMatches(safeDeletionSnapshot.file, safeDeletionSnapshot.revision)) return false;
60273
+ }
60036
60274
  await this.storage.deleteVaultItem(path);
60037
60275
  await this.deleteProvenance(path);
60038
60276
  return true;
@@ -60074,6 +60312,7 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
60074
60312
  return true;
60075
60313
  }
60076
60314
  }
60315
+ let safeSnapshot;
60077
60316
  if (existDoc && !force) {
60078
60317
  let shouldApplied = false;
60079
60318
  if (this.path.compareFileFreshness(existDoc, docEntry) !== EVEN) shouldApplied = true;
@@ -60086,9 +60325,27 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
60086
60325
  this._log(`File ${docRead.path} is not changed`, 16);
60087
60326
  return true;
60088
60327
  }
60089
- if (!force && !settings.writeDocumentsIfConflicted && await this.preserveUnsyncedStorageAsConflict(path, existDoc, docEntry, docData)) return true;
60328
+ if (!force && !settings.writeDocumentsIfConflicted) {
60329
+ let protection = await this.preserveUnsyncedStorageAsConflict(path, existDoc, docEntry, docData);
60330
+ if (protection.preserved) return true;
60331
+ if (!protection.snapshot) {
60332
+ protection = await this.recheckIncomingStorage(path, docEntry, docData, allowExistingConflicts);
60333
+ if (protection.preserved) return true;
60334
+ if (!protection.snapshot) return false;
60335
+ }
60336
+ safeSnapshot = protection.snapshot;
60337
+ }
60090
60338
  } else this._log(`File ${docRead.path} ${existDoc ? "(new) " : ""} ${force ? " (forced)" : ""}`, 16);
60091
60339
  await this.storage.ensureDir(path);
60340
+ if (safeSnapshot && !await this.currentStorageSnapshotMatches(safeSnapshot.file, safeSnapshot.revision)) {
60341
+ const protection = await this.recheckIncomingStorage(path, docEntry, docData, allowExistingConflicts);
60342
+ if (protection.preserved) return true;
60343
+ if (!protection.snapshot || !await this.currentStorageSnapshotMatches(protection.snapshot.file, protection.snapshot.revision)) return false;
60344
+ safeSnapshot = protection.snapshot;
60345
+ }
60346
+ const latest = await this.reconcileAdvancedIncomingRevision(docEntry, path, force, allowExistingConflicts, incomingRetry);
60347
+ if (latest !== void 0) return latest;
60348
+ if (safeSnapshot && !await this.currentStorageSnapshotMatches(safeSnapshot.file, safeSnapshot.revision)) return false;
60092
60349
  const ret = await this.storage.writeFileAuto(path, docData, {
60093
60350
  ctime: docRead.ctime,
60094
60351
  mtime: docRead.mtime
@@ -60097,32 +60354,97 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
60097
60354
  this.storage.triggerFileEvent(mode, path);
60098
60355
  if (ret && this.fileReflectionProvenance) {
60099
60356
  const storedStat = await this.storage.stat(path);
60357
+ if (safeSnapshot && await this.readProvenanceSnapshot(path) !== safeSnapshot.revision) return ret;
60100
60358
  await this.setProvenance(path, docEntry._rev, storedStat?.mtime);
60101
60359
  }
60102
60360
  return ret;
60103
60361
  }
60362
+ /**
60363
+ * Preserve storage bytes before an incoming reflection can replace them.
60364
+ *
60365
+ * The initial read and provenance form one candidate snapshot. Classification
60366
+ * gives a recorded branch priority, deduplicates matching live leaves, or
60367
+ * creates an independent root for unknown origin. Optional `incomingContent` avoids
60368
+ * re-reading an already loaded incoming body. Storage is revalidated before
60369
+ * and after the database write; `preserved: true` stops the incoming write,
60370
+ * while a returned `snapshot` lets the caller continue only after revalidation.
60371
+ */
60104
60372
  async preserveUnsyncedStorageAsConflict(path, existDoc, incomingEntry, incomingContent) {
60373
+ const observedProvenance = await this.readProvenanceSnapshot(path);
60105
60374
  const readFile = await this.readFileFromStub(existDoc);
60106
- if (incomingContent && await isDocContentSame(incomingContent, readFile.body)) return false;
60107
- if (incomingContent && await isIncomingTextClearExtension(incomingContent, readFile.body)) return false;
60108
- if (!incomingEntry._rev) return false;
60109
- if (await this.db.hasContentInRevisionHistory(path, readFile.body, incomingEntry._rev)) return false;
60110
- const storedRevision = await this.db.storeAsConflictedRevisionWithResult(readFile, incomingEntry._rev, true);
60375
+ const snapshot = {
60376
+ file: readFile,
60377
+ revision: observedProvenance
60378
+ };
60379
+ if (incomingContent && await isDocContentSame(incomingContent, readFile.body)) return await this.currentStorageSnapshotMatches(readFile, observedProvenance) ? {
60380
+ preserved: false,
60381
+ snapshot
60382
+ } : { preserved: false };
60383
+ if (!incomingEntry._rev) return { preserved: false };
60384
+ const classification = await this.classifyStorageContent(readFile, incomingEntry, void 0, observedProvenance, incomingContent ? {
60385
+ _rev: incomingEntry._rev,
60386
+ data: incomingContent
60387
+ } : void 0);
60388
+ if (!await this.currentStorageSnapshotMatches(readFile, observedProvenance)) return { preserved: false };
60389
+ if (classification.kind === "unchanged") return {
60390
+ preserved: false,
60391
+ snapshot
60392
+ };
60393
+ if (classification.kind === "matching-leaf") {
60394
+ await this.rememberMatchingLeaf(path, classification.revision, readFile.stat.mtime);
60395
+ await this.queueConflictCheckFor(path);
60396
+ return { preserved: true };
60397
+ }
60398
+ const storedRevision = classification.kind === "edited" ? await this.db.storeWithBaseRevision(readFile, classification.revision, true) : await this.db.storeIndependentRevision(readFile, true);
60111
60399
  if (storedRevision === false) {
60112
60400
  this._log(`Prevented overwriting unsynchronised local changes for ${path}`, 64);
60113
- return true;
60401
+ return { preserved: true };
60114
60402
  }
60115
- await this.setProvenance(path, storedRevision, readFile.stat.mtime);
60403
+ if (!await this.finaliseStoredRevision(readFile, observedProvenance, storedRevision)) return { preserved: false };
60116
60404
  this._log(`Preserved unsynchronised local changes as a conflict for ${path}`, 64);
60117
- await this.conflict.queueCheckFor(path);
60118
- return true;
60405
+ await this.queueConflictCheckFor(path);
60406
+ return { preserved: true };
60407
+ }
60408
+ /**
60409
+ * Repeat overwrite protection from a fresh storage read after a snapshot
60410
+ * becomes stale. Existing conflicts may defer reflection and request an
60411
+ * open-only check while leaving the current storage untouched.
60412
+ */
60413
+ async recheckIncomingStorage(path, incomingEntry, incomingContent, allowExistingConflicts) {
60414
+ const current = await this.storage.getStub(path);
60415
+ if (!current || isFolderInfo(current)) return { preserved: false };
60416
+ const protection = await this.preserveUnsyncedStorageAsConflict(path, current, incomingEntry, incomingContent);
60417
+ if (protection.preserved || !protection.snapshot) return protection;
60418
+ if (!allowExistingConflicts && !this.setting.currentSettings().writeDocumentsIfConflicted && (await this.db.getConflictedRevs(path)).length > 0) {
60419
+ await this.queueConflictCheckFor(path, true);
60420
+ return { preserved: true };
60421
+ }
60422
+ return protection;
60423
+ }
60424
+ /**
60425
+ * Re-read database metadata immediately before reflecting an incoming entry.
60426
+ * If the current revision advanced, recurse with fresh storage; force and
60427
+ * explicitly allowed conflict writes retain the caller's selected entry.
60428
+ * `incomingRetry` bounds repeated database churn.
60429
+ */
60430
+ async reconcileAdvancedIncomingRevision(incomingEntry, path, force, allowExistingConflicts, incomingRetry) {
60431
+ if (force || allowExistingConflicts) return void 0;
60432
+ const current = await this.db.fetchEntryMeta(path, void 0, true);
60433
+ if (!current) return false;
60434
+ if (current._rev === incomingEntry._rev) return void 0;
60435
+ if (incomingRetry >= 2) {
60436
+ this._log(`Database kept changing while reflecting ${path}`, 64);
60437
+ return false;
60438
+ }
60439
+ const storage = await this.storage.getStub(path);
60440
+ if (isFolderInfo(storage)) return false;
60441
+ return await this.applyDatabaseEntryToStorage(current, storage, force, allowExistingConflicts, incomingRetry + 1);
60119
60442
  }
60120
60443
  async _anyHandlerProcessesFileEvent(item) {
60121
60444
  if (item.restoredFromPreviousRuntime) return await this._processRestoredFileEvent(item);
60122
60445
  const eventItem = item.args;
60123
60446
  const type = item.type;
60124
60447
  const path = eventItem.file.path;
60125
- if (!await this.isCurrentPathSelected(path)) return false;
60126
60448
  if (type === "RENAME" && !eventItem.oldPath) {
60127
60449
  this._log(`Rename event for ${path} has no source path`, 16);
60128
60450
  return false;
@@ -60130,13 +60452,14 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
60130
60452
  const relatedPath = type === "RENAME" ? eventItem.oldPath : type === "DELETE" ? eventItem.renameTarget : void 0;
60131
60453
  const eventPaths = relatedPath === void 0 ? [path] : [path, relatedPath];
60132
60454
  return await this.serializedByFileEventPaths(eventPaths, async () => {
60455
+ if (!await this.isCurrentPathSelected(path)) return false;
60133
60456
  switch (type) {
60134
60457
  case "CREATE":
60135
- case "CHANGED": return await this.storeFileToDB(item.args.file);
60458
+ case "CHANGED": return await this.storeFileToDBFromRevision(item.args.file);
60136
60459
  case "DELETE":
60137
60460
  if (!await this.canRecordStorageDeletion(item)) return true;
60138
- return await this.deleteFileFromDB(item.args.file);
60139
- case "RENAME": return await this.renameFileInDB(item.args.file, item.args.oldPath);
60461
+ return await this.deleteFileFromDBCore(item.args.file);
60462
+ case "RENAME": return await this.renameFileInDBCore(item.args.file, item.args.oldPath);
60140
60463
  case "INTERNAL": return false;
60141
60464
  default:
60142
60465
  this._log(`Unsupported event type: ${type}`, 16);
@@ -60177,9 +60500,62 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
60177
60500
  return false;
60178
60501
  }
60179
60502
  }
60503
+ /**
60504
+ * Serialise work by every document ID represented by the supplied paths.
60505
+ * IDs are deduplicated and sorted so aliases take one lock and cross-document renames have one order.
60506
+ * The callback runs under those locks and must use core methods; conflict
60507
+ * hooks requested inside it are deferred until all locks have been released.
60508
+ */
60180
60509
  async serializedByFileEventPaths(eventPaths, callback) {
60181
60510
  const documentIds = await Promise.all(eventPaths.map((eventPath) => this.path.path2id(eventPath)));
60182
- return await serializedByKeys([...new Set(documentIds)].sort().map((documentId) => `processFileEvent-${documentId}`), () => callback(documentIds.length === 2 && documentIds[0] === documentIds[1]));
60511
+ const uniqueIds = [...new Set(documentIds)].sort();
60512
+ const lockKeys = uniqueIds.map((documentId) => `processFileEvent-${documentId}`);
60513
+ const pending = [];
60514
+ let result;
60515
+ let failed = false;
60516
+ let failure;
60517
+ try {
60518
+ result = await serializedByKeys(lockKeys, async () => {
60519
+ for (const id of uniqueIds) this.deferredConflictChecks.set(id, pending);
60520
+ try {
60521
+ return await callback(documentIds.length === 2 && documentIds[0] === documentIds[1]);
60522
+ } finally {
60523
+ for (const id of uniqueIds) this.deferredConflictChecks.delete(id);
60524
+ }
60525
+ });
60526
+ } catch (ex) {
60527
+ failed = true;
60528
+ failure = ex;
60529
+ }
60530
+ for (const check of pending) try {
60531
+ if (check.ifOpen) await this.conflict.queueCheckForIfOpen(check.path);
60532
+ else await this.conflict.queueCheckFor(check.path);
60533
+ } catch (ex) {
60534
+ if (!failed) {
60535
+ failed = true;
60536
+ failure = ex;
60537
+ }
60538
+ break;
60539
+ }
60540
+ if (failed) throw failure;
60541
+ return result;
60542
+ }
60543
+ /**
60544
+ * Queue a conflict hook while its document lock is held, or run it directly
60545
+ * when no matching lock is active. Preserve `ifOpen` across deferral.
60546
+ */
60547
+ async queueConflictCheckFor(path, ifOpen = false) {
60548
+ const documentId = await this.path.path2id(path);
60549
+ const pending = this.deferredConflictChecks.get(documentId);
60550
+ if (pending) {
60551
+ pending.push({
60552
+ path,
60553
+ ifOpen
60554
+ });
60555
+ return;
60556
+ }
60557
+ if (ifOpen) await this.conflict.queueCheckForIfOpen(path);
60558
+ else await this.conflict.queueCheckFor(path);
60183
60559
  }
60184
60560
  /**
60185
60561
  * Revalidate a persisted storage operation against the current storage state.
@@ -60187,7 +60563,9 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
60187
60563
  * Snapshot entries preserve operation intent and ordering only. Their file
60188
60564
  * stub, timestamps, and existence assumptions can be stale after a restart.
60189
60565
  * Current inclusion is therefore read from storage, while destructive work
60190
- * is allowed only after current absence has been observed.
60566
+ * is allowed only after current absence has been observed. Store and rename
60567
+ * actions use the fresh reread with bounded retry because no later watcher
60568
+ * event is guaranteed after startup reconciliation.
60191
60569
  */
60192
60570
  async _processRestoredFileEvent(item) {
60193
60571
  const eventItem = item.args;
@@ -60209,9 +60587,9 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
60209
60587
  }
60210
60588
  switch (action.kind) {
60211
60589
  case "none": return true;
60212
- case "store": return await this.storeFileToDB(action.file);
60213
- case "delete": return await this.deleteFileFromDB(action.path);
60214
- case "rename": return await this.renameFileInDB(action.file, action.oldPath);
60590
+ case "store": return await this.storeFileToDBFromRevision(action.file, false, false, void 0, true);
60591
+ case "delete": return await this.deleteFileFromDBCore(action.path);
60592
+ case "rename": return await this.renameFileInDBCore(action.file, action.oldPath, true);
60215
60593
  }
60216
60594
  });
60217
60595
  }
@@ -60316,7 +60694,7 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
60316
60694
  this._log(ex, 16);
60317
60695
  }
60318
60696
  async _anyProcessReplicatedDoc(entry) {
60319
- return await serialized(`processReplicatedDoc-${entry._id}`, async () => {
60697
+ return await this.serializedByFileEventPaths([this.getPath(entry)], async () => {
60320
60698
  if (!await this.vault.isTargetFile(entry.path)) {
60321
60699
  this._log(`File ${entry.path} is not the target file`, 16);
60322
60700
  return false;
@@ -60341,7 +60719,7 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
60341
60719
  }
60342
60720
  this._log(`Processing ${path} (${entry._id.substring(0, 8)} :${entry._rev?.substring(0, 5)}) : Started...`, 16);
60343
60721
  this.events.emitEvent(EVENT_CONFLICT_CANCELLED, path);
60344
- const ret = await this.dbToStorage(entry, targetFile);
60722
+ const ret = await this.dbToStorageCore(entry, targetFile);
60345
60723
  this._log(`Processing ${path} (${entry._id.substring(0, 8)} :${entry._rev?.substring(0, 5)}) : Done`);
60346
60724
  return ret;
60347
60725
  }
@@ -61214,6 +61592,7 @@ var ServiceDatabaseFileAccessBase = class extends ServiceModuleBase {
61214
61592
  async store(file, force = false, skipCheck) {
61215
61593
  return await this.__store(file, force, skipCheck, false) !== false;
61216
61594
  }
61595
+ /** Force a child below the supplied base, even if advanced; an undefined base uses the winner. */
61217
61596
  async storeWithBaseRevision(file, baseRevision, skipCheck) {
61218
61597
  const result = await this.__store(file, true, skipCheck, false, {
61219
61598
  mode: "force-base",
@@ -61221,6 +61600,7 @@ var ServiceDatabaseFileAccessBase = class extends ServiceModuleBase {
61221
61600
  });
61222
61601
  return result !== null && typeof result === "object" && "rev" in result ? result.rev : false;
61223
61602
  }
61603
+ /** Extend a current leaf with ordinary MVCC; an advanced base returns `false`. */
61224
61604
  async storeWithLiveBaseRevision(file, baseRevision, skipCheck) {
61225
61605
  const result = await this.__store(file, true, skipCheck, false, {
61226
61606
  mode: "live-base",
@@ -61228,9 +61608,18 @@ var ServiceDatabaseFileAccessBase = class extends ServiceModuleBase {
61228
61608
  });
61229
61609
  return result !== null && typeof result === "object" && "rev" in result ? result.rev : false;
61230
61610
  }
61611
+ /**
61612
+ * Store Chunks and a fresh Metadata root for content with unknown ancestry.
61613
+ * Return its exact revision for provenance, or `false` if no Metadata write succeeded.
61614
+ */
61615
+ async storeIndependentRevision(file, skipCheck) {
61616
+ const result = await this.__store(file, true, skipCheck, false, { mode: "independent-root" });
61617
+ return result !== null && typeof result === "object" && "rev" in result ? result.rev : false;
61618
+ }
61231
61619
  async storeAsConflictedRevision(file, currentRev, skipCheck) {
61232
61620
  return await this.storeAsConflictedRevisionWithResult(file, currentRev, skipCheck) !== false;
61233
61621
  }
61622
+ /** Create a sibling of the selected revision; refuse when its parent cannot be found. */
61234
61623
  async storeAsConflictedRevisionWithResult(file, currentRev, skipCheck) {
61235
61624
  const conflictBaseRev = await this.getParentRev(file, currentRev);
61236
61625
  if (!conflictBaseRev) {
@@ -61239,6 +61628,7 @@ var ServiceDatabaseFileAccessBase = class extends ServiceModuleBase {
61239
61628
  }
61240
61629
  return await this.storeWithBaseRevision(file, conflictBaseRev, skipCheck);
61241
61630
  }
61631
+ /** Record a logical deletion below the displayed branch and return its exact revision. */
61242
61632
  async storeDeletionWithBaseRevision(file, baseRevision) {
61243
61633
  if (!await this.checkIsTargetFile(file)) return false;
61244
61634
  const fullPath = getDatabasePathFromUXFileInfo(file);
@@ -61342,13 +61732,14 @@ var ServiceDatabaseFileAccessBase = class extends ServiceModuleBase {
61342
61732
  this._log(msg + " Skip " + fullPath, 16);
61343
61733
  return true;
61344
61734
  }
61345
- const ret = revisionTarget.mode === "live-base" ? await this.database.localDatabase.putDBEntryWithLiveBaseRevision(d, revisionTarget.baseRevision, onlyChunks) : await this.database.localDatabase.putDBEntry(d, onlyChunks, revisionTarget.mode === "force-base" ? revisionTarget.baseRevision : void 0);
61735
+ const ret = revisionTarget.mode === "independent-root" ? await this.database.localDatabase.putDBEntryAsIndependentRoot(d) : revisionTarget.mode === "live-base" ? await this.database.localDatabase.putDBEntryWithLiveBaseRevision(d, revisionTarget.baseRevision, onlyChunks) : await this.database.localDatabase.putDBEntry(d, onlyChunks, revisionTarget.mode === "force-base" ? revisionTarget.baseRevision : void 0);
61346
61736
  if (ret !== false) {
61347
61737
  this._log(msg + fullPath);
61348
61738
  this.events.emitEvent(EVENT_FILE_SAVED$1);
61349
61739
  }
61350
61740
  return ret;
61351
61741
  }
61742
+ /** Reconstruct the immediate parent ID from revision history, or return `false` if unavailable. */
61352
61743
  async getParentRev(file, rev) {
61353
61744
  const filename = getDatabasePathFromUXFileInfo(file);
61354
61745
  try {
@@ -61366,6 +61757,11 @@ var ServiceDatabaseFileAccessBase = class extends ServiceModuleBase {
61366
61757
  return false;
61367
61758
  }
61368
61759
  }
61760
+ /**
61761
+ * Search available revision bodies across branches and their ancestors.
61762
+ * `stopAfterFirstMatch` serves existence checks without decoding the remaining candidates.
61763
+ * Historical matches alone do not establish the origin of current storage content.
61764
+ */
61369
61765
  async findContentRevisionsInternal(file, content, currentRev, stopAfterFirstMatch = false) {
61370
61766
  const filename = getDatabasePathFromUXFileInfo(file);
61371
61767
  try {
@@ -61405,10 +61801,40 @@ var ServiceDatabaseFileAccessBase = class extends ServiceModuleBase {
61405
61801
  }
61406
61802
  return [];
61407
61803
  }
61804
+ /** Find matching content throughout available history, including non-leaf revisions. */
61408
61805
  async findContentRevisions(file, content, currentRev) {
61409
61806
  if (!await this.checkIsTargetFile(file)) return [];
61410
61807
  return await this.findContentRevisionsInternal(file, content, currentRev);
61411
61808
  }
61809
+ /**
61810
+ * Find live leaves which already represent these bytes, for deduplication when provenance
61811
+ * is unknown. `open_revs` includes conflicting branches; both deletion markers are excluded.
61812
+ * Unlike the historical search, ancestors cannot match and missing Chunks are not fetched.
61813
+ * A read failure yields no confirmed match. Callers decide whether the result identifies a
61814
+ * unique origin; this method does not mutate provenance or hold the revision tree stable.
61815
+ */
61816
+ async findLiveContentRevisions(file, content) {
61817
+ if (!await this.checkIsTargetFile(file)) return [];
61818
+ const filename = getDatabasePathFromUXFileInfo(file);
61819
+ try {
61820
+ const current = await this.database.localDatabase.getDBEntryMeta(filename, void 0, true);
61821
+ if (current === false) return [];
61822
+ const leaves = await this.database.localDatabase.getRaw(current._id, { open_revs: "all" });
61823
+ if (!Array.isArray(leaves)) return [];
61824
+ const matches = [];
61825
+ for (const leaf of leaves) {
61826
+ const rev = leaf.ok?._rev;
61827
+ if (!rev || leaf.ok?.deleted || leaf.ok?._deleted) continue;
61828
+ const entry = await this.database.localDatabase.getDBEntry(filename, { rev }, false, true, true, true);
61829
+ if (entry !== false && !entry.deleted && !entry._deleted && await isDocContentSame(readContent(entry), content)) matches.push(rev);
61830
+ }
61831
+ return matches;
61832
+ } catch (ex) {
61833
+ this._log(`Could not check live revision content for ${filename}`, 16);
61834
+ this._log(ex, 16);
61835
+ return [];
61836
+ }
61837
+ }
61412
61838
  async hasContentInRevisionHistory(file, content, currentRev) {
61413
61839
  if (!await this.checkIsTargetFile(file)) return true;
61414
61840
  return (await this.findContentRevisionsInternal(file, content, currentRev, true)).length > 0;
@@ -61448,17 +61874,17 @@ var ServiceDatabaseFileAccessBase = class extends ServiceModuleBase {
61448
61874
  if (doc === false) return false;
61449
61875
  return doc;
61450
61876
  }
61451
- async fetchEntryFromMeta(meta, waitForReady = true, skipCheck = false) {
61877
+ async fetchEntryFromMeta(meta, waitForReady = true, skipCheck = false, localOnly = false) {
61452
61878
  if (skipCheck && !await this.checkIsTargetFile(meta.path)) return false;
61453
- const doc = await this.database.localDatabase.getDBEntryFromMeta(meta, false, waitForReady);
61879
+ const doc = await this.database.localDatabase.getDBEntryFromMeta(meta, false, waitForReady, localOnly);
61454
61880
  if (doc === false) return false;
61455
61881
  return doc;
61456
61882
  }
61457
- async fetchEntry(file, rev, waitForReady = true, skipCheck = false) {
61883
+ async fetchEntry(file, rev, waitForReady = true, skipCheck = false, localOnly = false) {
61458
61884
  if (skipCheck && !await this.checkIsTargetFile(file)) return false;
61459
61885
  const entry = await this.fetchEntryMeta(file, rev, true);
61460
61886
  if (entry === false) return false;
61461
- return await this.fetchEntryFromMeta(entry, waitForReady, true);
61887
+ return await this.fetchEntryFromMeta(entry, waitForReady, true, localOnly);
61462
61888
  }
61463
61889
  async deleteFromDBbyPath(fullPath, rev) {
61464
61890
  if (!await this.checkIsTargetFile(fullPath)) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jr2804/livesync-cli",
3
- "version": "1.0.29-cli.1",
3
+ "version": "1.0.30-cli.1",
4
4
  "description": "SEA-packaged livesync-cli from vrtmrz/obsidian-livesync — multiplatform binaries + npm",
5
5
  "type": "module",
6
6
  "bin": {