@jr2804/livesync-cli 1.0.29-cli.1 → 1.0.32-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 +641 -172
  2. package/package.json +2 -2
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() {
@@ -6222,6 +6222,9 @@ var globalConcurrencyController = Semaphore(50);
6222
6222
  function determineTypeFromBlob(data) {
6223
6223
  return isTextBlob$1(data) ? "plain" : "newnote";
6224
6224
  }
6225
+ function isRemediationModeActive(settings) {
6226
+ return (settings.maxMTimeForReflectEvents ?? 0) > 0;
6227
+ }
6225
6228
  function isAnyNote(doc) {
6226
6229
  return "type" in doc && (doc.type == "newnote" || doc.type == "plain");
6227
6230
  }
@@ -6333,34 +6336,24 @@ function isValidFilenameInWidows(filename) {
6333
6336
  if (/(\\|\/)(COM\d|LPT\d|CON|PRN|AUX|NUL|CLOCK$)($|\.)/gi.test(filename)) return false;
6334
6337
  return true;
6335
6338
  }
6336
- function isFilePath(path) {
6337
- if (path.indexOf(":") === -1) return true;
6338
- return false;
6339
- }
6340
6339
  function stripAllPrefixes(prefixedPath) {
6341
- if (isFilePath(prefixedPath)) return prefixedPath;
6342
- const [, body] = expandFilePathPrefix(prefixedPath);
6343
- return stripAllPrefixes(body);
6340
+ return stripPrefix(prefixedPath);
6344
6341
  }
6345
6342
  function addPrefix(path, prefix) {
6346
6343
  if (prefix && path.startsWith(prefix)) return path;
6347
6344
  return `${prefix ?? ""}${path}`;
6348
6345
  }
6349
6346
  function expandFilePathPrefix(path) {
6350
- let [prefix, body] = path.split(":", 2);
6351
- if (!body) {
6352
- body = prefix;
6353
- prefix = "";
6354
- } else prefix = prefix + ":";
6355
- return [prefix, body];
6347
+ for (const prefix of [
6348
+ "i:",
6349
+ "ix:",
6350
+ "ps:"
6351
+ ]) if (path.startsWith(prefix)) return [prefix, path.substring(prefix.length)];
6352
+ return ["", path];
6356
6353
  }
6357
6354
  function expandDocumentIDPrefix(id) {
6358
- let [prefix, body] = id.split(":", 2);
6359
- if (!body) {
6360
- body = prefix;
6361
- prefix = "";
6362
- } else prefix = prefix + ":";
6363
- return [prefix, body];
6355
+ for (const prefix of ["h:", "f:"]) if (id.startsWith(prefix)) return [prefix, id.substring(prefix.length)];
6356
+ return expandFilePathPrefix(id);
6364
6357
  }
6365
6358
  var _hashString = memorizeFuncWithLRUCache(async (key) => {
6366
6359
  const buff = writeString(key);
@@ -6394,6 +6387,9 @@ function id2path_base(id, entry) {
6394
6387
  function getPath(entry) {
6395
6388
  return id2path_base(entry._id, entry);
6396
6389
  }
6390
+ function stripPrefix(prefixedPath) {
6391
+ return expandFilePathPrefix(prefixedPath)[1];
6392
+ }
6397
6393
  function shouldBeIgnored(filename) {
6398
6394
  if (filename == FLAGMD_REDFLAG) return true;
6399
6395
  if (filename == FLAGMD_REDFLAG2) return true;
@@ -6515,18 +6511,12 @@ var PathService = class extends ServiceBase {
6515
6511
  this.getPathObfuscationPassphrase = dependencies.getPathObfuscationPassphrase;
6516
6512
  }
6517
6513
  _id2path(id, entry) {
6518
- const temp = id2path_base(id, entry).split(":");
6519
- const path = temp.pop();
6520
- const normalizedPath = this.normalizePath(path);
6521
- temp.push(normalizedPath);
6522
- return temp.join(":");
6514
+ const [prefix, path] = expandFilePathPrefix(id2path_base(id, entry));
6515
+ return prefix + this.normalizePath(path);
6523
6516
  }
6524
6517
  async _path2id(filename, obfuscatePassphrase, caseInsensitive) {
6525
- const temp = filename.split(":");
6526
- const path = temp.pop();
6527
- const normalizedPath = this.normalizePath(path);
6528
- temp.push(normalizedPath);
6529
- return await path2id_base(temp.join(":"), obfuscatePassphrase, caseInsensitive);
6518
+ const [prefix, path] = expandFilePathPrefix(filename);
6519
+ return await path2id_base(prefix + this.normalizePath(path), obfuscatePassphrase, caseInsensitive);
6530
6520
  }
6531
6521
  /**
6532
6522
  * Convert a document ID or entry to a virtual file path.
@@ -7453,6 +7443,7 @@ var REPLICATION_PROGRESS_PRESENTATIONS = Object.freeze({
7453
7443
  var REPLICATION_COMPLETED = Object.freeze({ status: "completed" });
7454
7444
  var REPLICATION_CANCELLED = Object.freeze({ status: "cancelled" });
7455
7445
  var CENTRAL_REMOTE_REPLICATION_READINESS = Object.freeze({ centralRemotePreparation: "required" });
7446
+ var PROVIDER_OWNED_CENTRAL_REMOTE_REPLICATION_READINESS = Object.freeze({ centralRemotePreparation: "provider-owned" });
7456
7447
  var PEER_REPLICATION_READINESS = Object.freeze({ centralRemotePreparation: "not-applicable" });
7457
7448
  function isReplicationCompleted(outcome) {
7458
7449
  return outcome.status === "completed";
@@ -11100,19 +11091,19 @@ async function outgoingDecryptHKDF(doc, migrationDecrypt, decrypted, passphrase,
11100
11091
  Logger(ex);
11101
11092
  throw ex;
11102
11093
  }
11103
- if (isObfuscatedEntry(loadDoc)) {
11094
+ if (isObfuscatedEntry(loadDoc)) if (isEncryptedMeta(loadDoc)) {
11095
+ const pbkdf2salt = await getPBKDF2Salt();
11096
+ try {
11097
+ const metadata = await decryptMetaWithHKDF(loadDoc.path, passphrase, pbkdf2salt);
11098
+ for (const key of Object.keys(metadata)) loadDoc[key] = metadata[key];
11099
+ } catch (ex) {
11100
+ Logger(`${DECRYPTION_HKDF_FAILED} on Path`, 64);
11101
+ Logger(ex);
11102
+ throw ex;
11103
+ }
11104
+ } else {
11104
11105
  const path = getPath(loadDoc);
11105
- if (isEncryptedMeta(loadDoc)) {
11106
- const pbkdf2salt = await getPBKDF2Salt();
11107
- try {
11108
- const metadata = await decryptMetaWithHKDF(path, passphrase, pbkdf2salt);
11109
- for (const key of Object.keys(metadata)) loadDoc[key] = metadata[key];
11110
- } catch (ex) {
11111
- Logger(`${DECRYPTION_HKDF_FAILED} on Path`, 64);
11112
- Logger(ex);
11113
- throw ex;
11114
- }
11115
- } else if (isPathProbablyObfuscated(path)) {
11106
+ if (isPathProbablyObfuscated(path)) {
11116
11107
  const decryptedPath = await tryDecryptV1AsFallback(path, passphrase, useDynamicIterationCount);
11117
11108
  if (decryptedPath === false) {
11118
11109
  Logger(`${MESSAGE_FALLBACK_DECRYPT_FAILED} on Path`, 64);
@@ -11890,10 +11881,10 @@ var HeadlessAPIService = class extends InjectableAPIService {
11890
11881
  return "headless-app";
11891
11882
  }
11892
11883
  getAppVersion() {
11893
- return `1.0.29`;
11884
+ return `1.0.32`;
11894
11885
  }
11895
11886
  getPluginVersion() {
11896
- return `1.0.29`;
11887
+ return `1.0.32`;
11897
11888
  }
11898
11889
  getPlatform() {
11899
11890
  return "server";
@@ -16159,6 +16150,9 @@ async function putDBEntryWithLiveBaseRevision(host, managers, note, baseRevision
16159
16150
  throw ex;
16160
16151
  }
16161
16152
  }
16153
+ async function putDBEntryAsIndependentRoot(host, managers, note) {
16154
+ return await putDBEntryInternal(host, managers, note, false, { mode: "independent-root" });
16155
+ }
16162
16156
  async function putDBEntryInternal(host, managers, note, onlyChunks, revisionTarget) {
16163
16157
  const { localDatabase, chunkManager, splitter } = managers;
16164
16158
  const filename = host.services.path.id2path(note._id, note);
@@ -16192,12 +16186,30 @@ async function putDBEntryInternal(host, managers, note, onlyChunks, revisionTarg
16192
16186
  eden: {}
16193
16187
  };
16194
16188
  return await serialized("file:" + filename, async () => {
16195
- if (revisionTarget.mode !== "latest") newDoc._rev = revisionTarget.baseRevision;
16196
- else try {
16189
+ if (revisionTarget.mode === "force-base" || revisionTarget.mode === "live-base") newDoc._rev = revisionTarget.baseRevision;
16190
+ else if (revisionTarget.mode === "latest") try {
16197
16191
  newDoc._rev = (await localDatabase.get(newDoc._id))._rev;
16198
16192
  } catch (ex) {
16199
16193
  if (isErrorOfMissingDoc(ex)) {} else throw ex;
16200
16194
  }
16195
+ if (revisionTarget.mode === "independent-root") {
16196
+ const randomBytes = compatGlobal.crypto.getRandomValues(new Uint8Array(16));
16197
+ const rootId = Array.from(randomBytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
16198
+ newDoc._rev = `1-${rootId}`;
16199
+ const imported = {
16200
+ ...newDoc,
16201
+ _revisions: {
16202
+ start: 1,
16203
+ ids: [rootId]
16204
+ }
16205
+ };
16206
+ await localDatabase.bulkDocs([imported], { new_edits: false });
16207
+ return (await localDatabase.get(newDoc._id, { rev: newDoc._rev }))._rev === newDoc._rev ? {
16208
+ id: newDoc._id,
16209
+ ok: true,
16210
+ rev: newDoc._rev
16211
+ } : false;
16212
+ }
16201
16213
  const r = revisionTarget.mode === "live-base" ? await localDatabase.put(newDoc) : await localDatabase.put(newDoc, { force: true });
16202
16214
  if (r.ok) return r;
16203
16215
  else return false;
@@ -16215,7 +16227,7 @@ function isTargetFile(host, filenameSrc) {
16215
16227
  const file = filenameSrc.startsWith("i:") ? filenameSrc.substring(2) : filenameSrc;
16216
16228
  if (file.startsWith("ix:")) return true;
16217
16229
  if (file.startsWith("ps:")) return true;
16218
- if (file.includes(":")) return false;
16230
+ if (file.startsWith(IDPrefixes.Chunk) || file.startsWith(IDPrefixes.Obfuscated)) return false;
16219
16231
  if (!settings.syncInternalFiles) {
16220
16232
  if (file.startsWith(".")) return false;
16221
16233
  }
@@ -16323,7 +16335,11 @@ function canFetchRemotely(settings) {
16323
16335
  if (settings.remoteType === RemoteTypes.REMOTE_MINIO) return false;
16324
16336
  return true;
16325
16337
  }
16326
- function computeChunkRetrievalMethod(waitForReady, settings) {
16338
+ function computeChunkRetrievalMethod(waitForReady, settings, localOnly = false) {
16339
+ if (localOnly) return {
16340
+ waitForDelivery: false,
16341
+ preventRemoteRequest: true
16342
+ };
16327
16343
  const isOnDemandFetchEnabled = canFetchRemotely(settings);
16328
16344
  if (!waitForReady) {
16329
16345
  if (isOnDemandFetchEnabled) return {
@@ -16340,7 +16356,7 @@ function computeChunkRetrievalMethod(waitForReady, settings) {
16340
16356
  preventRemoteRequest: !isOnDemandFetchEnabled
16341
16357
  };
16342
16358
  }
16343
- async function respondEntryFromMeta({ localDatabase, chunkManager }, settings, filename, meta, dump, waitForReady) {
16359
+ async function respondEntryFromMeta({ localDatabase, chunkManager }, settings, filename, meta, dump, waitForReady, localOnly = false) {
16344
16360
  const dispFilename = stripAllPrefixes(filename);
16345
16361
  const deleted = meta.deleted ?? meta._deleted ?? void 0;
16346
16362
  if (dump) {
@@ -16368,7 +16384,7 @@ async function respondEntryFromMeta({ localDatabase, chunkManager }, settings, f
16368
16384
  }));
16369
16385
  edenChunks = Object.fromEntries(chunks2.map((e) => [e._id, e]));
16370
16386
  }
16371
- const { waitForDelivery, preventRemoteRequest } = computeChunkRetrievalMethod(waitForReady, settings);
16387
+ const { waitForDelivery, preventRemoteRequest } = computeChunkRetrievalMethod(waitForReady, settings, localOnly);
16372
16388
  const childrenKeys = [...meta.children];
16373
16389
  const chunks = await chunkManager.read(childrenKeys, {
16374
16390
  skipCache: false,
@@ -16406,7 +16422,7 @@ async function respondEntryFromMeta({ localDatabase, chunkManager }, settings, f
16406
16422
  }
16407
16423
  return false;
16408
16424
  }
16409
- async function getDBEntryFromMeta(host, { localDatabase, chunkManager }, meta, dump = false, waitForReady = true) {
16425
+ async function getDBEntryFromMeta(host, { localDatabase, chunkManager }, meta, dump = false, waitForReady = true, localOnly = false) {
16410
16426
  const filename = host.services.path.id2path(meta._id, meta);
16411
16427
  if (!isTargetFile(host, filename)) return false;
16412
16428
  const settings = host.services.setting.currentSettings();
@@ -16414,12 +16430,12 @@ async function getDBEntryFromMeta(host, { localDatabase, chunkManager }, meta, d
16414
16430
  if (meta.type == "newnote" || meta.type == "plain") return await respondEntryFromMeta({
16415
16431
  localDatabase,
16416
16432
  chunkManager
16417
- }, settings, filename, meta, dump, waitForReady);
16433
+ }, settings, filename, meta, dump, waitForReady, localOnly);
16418
16434
  return false;
16419
16435
  }
16420
- async function getDBEntryByPath(host, managers, path, opt, dump = false, waitForReady = true, includeDeleted = false) {
16436
+ async function getDBEntryByPath(host, managers, path, opt, dump = false, waitForReady = true, includeDeleted = false, localOnly = false) {
16421
16437
  const meta = await getDBEntryMetaByPath(host, managers, path, opt, includeDeleted);
16422
- if (meta) return await getDBEntryFromMeta(host, managers, meta, dump, waitForReady);
16438
+ if (meta) return await getDBEntryFromMeta(host, managers, meta, dump, waitForReady, localOnly);
16423
16439
  else return false;
16424
16440
  }
16425
16441
  async function deleteDBEntryByPath(host, { localDatabase }, path, opt) {
@@ -16518,11 +16534,11 @@ var EntryManager = class {
16518
16534
  async getDBEntryMeta(path, opt, includeDeleted = false) {
16519
16535
  return await getDBEntryMetaByPath(this.serviceHost, this, path, opt, includeDeleted);
16520
16536
  }
16521
- async getDBEntry(path, opt, dump = false, waitForReady = true, includeDeleted = false) {
16522
- return await getDBEntryByPath(this.serviceHost, this, path, opt, dump, waitForReady, includeDeleted);
16537
+ async getDBEntry(path, opt, dump = false, waitForReady = true, includeDeleted = false, localOnly = false) {
16538
+ return await getDBEntryByPath(this.serviceHost, this, path, opt, dump, waitForReady, includeDeleted, localOnly);
16523
16539
  }
16524
- async getDBEntryFromMeta(meta, dump = false, waitForReady = true) {
16525
- return await getDBEntryFromMeta(this.serviceHost, this, meta, dump, waitForReady);
16540
+ async getDBEntryFromMeta(meta, dump = false, waitForReady = true, localOnly = false) {
16541
+ return await getDBEntryFromMeta(this.serviceHost, this, meta, dump, waitForReady, localOnly);
16526
16542
  }
16527
16543
  async deleteDBEntry(path, opt) {
16528
16544
  return await deleteDBEntryByPath(this.serviceHost, this, path, opt);
@@ -16536,6 +16552,10 @@ var EntryManager = class {
16536
16552
  async putDBEntryWithLiveBaseRevision(note, baseRevision, onlyChunks) {
16537
16553
  return await putDBEntryWithLiveBaseRevision(this.serviceHost, this, note, baseRevision, onlyChunks);
16538
16554
  }
16555
+ /** Store unknown ancestry as a fresh root; return the Metadata write result or `false`. */
16556
+ async putDBEntryAsIndependentRoot(note) {
16557
+ return await putDBEntryAsIndependentRoot(this.serviceHost, this, note);
16558
+ }
16539
16559
  };
16540
16560
  //#endregion
16541
16561
  //#region ../../../node_modules/octagonal-wheels/dist/hash/purejs.js
@@ -20752,11 +20772,11 @@ var LiveSyncLocalDB = class {
20752
20772
  async getDBEntryMeta(path, opt, includeDeleted = false) {
20753
20773
  return await this.managers.entryManager.getDBEntryMeta(path, opt, includeDeleted);
20754
20774
  }
20755
- async getDBEntry(path, opt, dump = false, waitForReady = true, includeDeleted = false) {
20756
- return await this.managers.entryManager.getDBEntry(path, opt, dump, waitForReady, includeDeleted);
20775
+ async getDBEntry(path, opt, dump = false, waitForReady = true, includeDeleted = false, localOnly = false) {
20776
+ return await this.managers.entryManager.getDBEntry(path, opt, dump, waitForReady, includeDeleted, localOnly);
20757
20777
  }
20758
- async getDBEntryFromMeta(meta, dump = false, waitForReady = true) {
20759
- return await this.managers.entryManager.getDBEntryFromMeta(meta, dump, waitForReady);
20778
+ async getDBEntryFromMeta(meta, dump = false, waitForReady = true, localOnly = false) {
20779
+ return await this.managers.entryManager.getDBEntryFromMeta(meta, dump, waitForReady, localOnly);
20760
20780
  }
20761
20781
  async deleteDBEntry(path, opt) {
20762
20782
  return await this.managers.entryManager.deleteDBEntry(path, opt);
@@ -20770,6 +20790,10 @@ var LiveSyncLocalDB = class {
20770
20790
  async putDBEntryWithLiveBaseRevision(note, baseRevision, onlyChunks) {
20771
20791
  return await this.managers.entryManager.putDBEntryWithLiveBaseRevision(note, baseRevision, onlyChunks);
20772
20792
  }
20793
+ /** Preserve existing branches and delegate a fresh root write to the entry manager. */
20794
+ async putDBEntryAsIndependentRoot(note) {
20795
+ return await this.managers.entryManager.putDBEntryAsIndependentRoot(note);
20796
+ }
20773
20797
  async getConflictedDoc(path, rev) {
20774
20798
  return await this.managers.conflictManager.getConflictedDoc(path, rev);
20775
20799
  }
@@ -34735,8 +34759,8 @@ var ModuleResolvingMismatchedTweaks = class extends AbstractModule {
34735
34759
  };
34736
34760
  //#endregion
34737
34761
  //#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/common/coreEnvVars.js
34738
- var manifestVersion = "1.0.29";
34739
- var packageVersion = "1.0.29";
34762
+ var manifestVersion = "1.0.32";
34763
+ var packageVersion = "1.0.32";
34740
34764
  //#endregion
34741
34765
  //#region ../../../node_modules/octagonal-wheels/dist/iterable/map.js
34742
34766
  /**
@@ -34914,6 +34938,7 @@ async function syncFileBetweenDBandStorage(host, log, file, doc) {
34914
34938
  return FilePairProcessResults.SKIPPED;
34915
34939
  }
34916
34940
  case EVEN:
34941
+ if (doc._rev) await host.serviceModules.fileHandler.tryRecordUntrackedFileRevision(file, doc._rev);
34917
34942
  log("STORAGE == DB :" + file.path, -1);
34918
34943
  return FilePairProcessResults.COMPLETED;
34919
34944
  default:
@@ -34936,7 +34961,7 @@ function canProceedScan(host, errorManager, log, showingNotice = false, ignoreSu
34936
34961
  }
34937
34962
  errorManager.clearError(ERR_SUSPENDING);
34938
34963
  const MSG_IN_REMEDIATION = `Started in remediation Mode! (Max mtime for reflect events is set). Synchronising between the storage and the local database is now prevented.`;
34939
- if (settings.maxMTimeForReflectEvents > 0) {
34964
+ if (isRemediationModeActive(settings)) {
34940
34965
  errorManager.showError(MSG_IN_REMEDIATION, 64);
34941
34966
  return false;
34942
34967
  }
@@ -37645,6 +37670,7 @@ var JournalSyncCore = class {
37645
37670
  env;
37646
37671
  store;
37647
37672
  requestedStop = false;
37673
+ syncParamsHandler;
37648
37674
  getInitialSyncParameters() {
37649
37675
  return Promise.resolve({
37650
37676
  ...DEFAULT_SYNC_PARAMETERS,
@@ -37688,7 +37714,6 @@ var JournalSyncCore = class {
37688
37714
  this.store = store;
37689
37715
  this.hash = this.getHash(settings);
37690
37716
  this.storage = storage;
37691
- clearHandlers();
37692
37717
  }
37693
37718
  async downloadJson(key) {
37694
37719
  try {
@@ -37735,7 +37760,7 @@ var JournalSyncCore = class {
37735
37760
  this.store = store;
37736
37761
  this.hash = this.getHash(settings);
37737
37762
  this.storage.applyNewConfig(settings);
37738
- clearHandlers();
37763
+ this.resetAllCaches();
37739
37764
  }
37740
37765
  updateInfo(info) {
37741
37766
  const old = this.env.services.replicator.replicationStatics.value;
@@ -37786,23 +37811,18 @@ var JournalSyncCore = class {
37786
37811
  return this._currentCheckPointInfo;
37787
37812
  }
37788
37813
  resetAllCaches() {
37789
- clearHandlers();
37814
+ this.syncParamsHandler = void 0;
37790
37815
  }
37791
37816
  async resetCheckpointInfo() {
37792
37817
  await this.updateCheckPointInfo((info) => ({ ...CheckPointInfoDefault }));
37793
- clearHandlers();
37794
37818
  }
37795
37819
  getJournalEpochFromSyncParams(params) {
37796
37820
  return `${params.protocolVersion}:${params.pbkdf2salt}`;
37797
37821
  }
37798
37822
  async ensureCheckpointCachesAreFresh() {
37799
- let journalEpoch = "";
37800
- try {
37801
- const params = await this.getSyncParameters();
37802
- journalEpoch = this.getJournalEpochFromSyncParams(params);
37803
- } catch {
37804
- return;
37805
- }
37823
+ const params = await this.getSyncParamsHandler().fetch(true);
37824
+ if (!params) throw new SyncParamsFetchError("Could not prepare Journal synchronisation parameters");
37825
+ const journalEpoch = this.getJournalEpochFromSyncParams(params);
37806
37826
  const current = await this.getCheckpointInfo();
37807
37827
  if (current.journalEpoch === journalEpoch) return;
37808
37828
  const lastSentFile = [...current.sentFiles].sort().pop();
@@ -37836,12 +37856,12 @@ var JournalSyncCore = class {
37836
37856
  receivedFiles: /* @__PURE__ */ new Set(),
37837
37857
  sentFiles: /* @__PURE__ */ new Set()
37838
37858
  }));
37839
- clearHandlers();
37840
37859
  }
37841
37860
  async isAvailable() {
37842
37861
  return await this.storage.isAvailable();
37843
37862
  }
37844
37863
  async resetBucket() {
37864
+ this.resetAllCaches();
37845
37865
  let files = [];
37846
37866
  try {
37847
37867
  do {
@@ -37849,7 +37869,6 @@ var JournalSyncCore = class {
37849
37869
  if (files.length == 0) break;
37850
37870
  if (!await this.storage.deleteFiles(files)) return false;
37851
37871
  } while (files.length != 0);
37852
- clearHandlers();
37853
37872
  } catch (ex) {
37854
37873
  Logger(`WARNING! Could not delete files.`, 64, "reset-bucket");
37855
37874
  Logger(ex, 16);
@@ -37869,11 +37888,14 @@ var JournalSyncCore = class {
37869
37888
  return this.getHash(this._settings);
37870
37889
  }
37871
37890
  async getReplicationPBKDF2Salt(refresh) {
37872
- return await createSyncParamsHanderForServer(this.getRemoteKey(), {
37891
+ return await this.getSyncParamsHandler().getPBKDF2Salt(refresh);
37892
+ }
37893
+ getSyncParamsHandler() {
37894
+ return this.syncParamsHandler ??= createSyncParamsHandler({
37873
37895
  put: (params) => this.putSyncParameters(params),
37874
37896
  get: () => this.getSyncParameters(),
37875
37897
  create: () => this.getInitialSyncParameters()
37876
- }).getPBKDF2Salt(refresh);
37898
+ });
37877
37899
  }
37878
37900
  isEncryptionPrevented(fileName) {
37879
37901
  if (fileName.endsWith("_obsidian_livesync_journal_sync_parameters.json")) return true;
@@ -38283,6 +38305,7 @@ var JournalSyncCore = class {
38283
38305
  /** Stop this Journal operation owner and release its storage transport. */
38284
38306
  dispose() {
38285
38307
  this.requestStop();
38308
+ this.resetAllCaches();
38286
38309
  this.storage.dispose?.();
38287
38310
  }
38288
38311
  };
@@ -56521,11 +56544,15 @@ var LiveSyncJournalReplicator = class extends LiveSyncAbstractReplicator {
56521
56544
  async openReplication(setting, _, showResult, ignoreCleanLock = false, recordCompatibilityDecision) {
56522
56545
  return await this.runJournalTransfer(async (stopGeneration) => {
56523
56546
  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);
56547
+ try {
56548
+ stopGeneration = this.journalTransferStopGeneration;
56549
+ if (!await this.checkReplicationConnectivity(false, ignoreCleanLock, showResult, setting, client, recordCompatibilityDecision)) return false;
56550
+ if (stopGeneration !== this.journalTransferStopGeneration) return false;
56551
+ this.hasEnteredReplication = true;
56552
+ return await client.sync(showResult);
56553
+ } finally {
56554
+ client.resetAllCaches();
56555
+ }
56529
56556
  });
56530
56557
  }
56531
56558
  /**
@@ -56548,11 +56575,15 @@ var LiveSyncJournalReplicator = class extends LiveSyncAbstractReplicator {
56548
56575
  async runDirectionalReplication(setting, showingNotice, transfer, recordCompatibilityDecision) {
56549
56576
  return await this.runJournalTransfer(async (stopGeneration) => {
56550
56577
  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);
56578
+ try {
56579
+ stopGeneration = this.journalTransferStopGeneration;
56580
+ if (!await this.checkReplicationConnectivity(false, false, !!showingNotice, setting, client, recordCompatibilityDecision)) return false;
56581
+ if (stopGeneration !== this.journalTransferStopGeneration) return false;
56582
+ this.hasEnteredReplication = true;
56583
+ return await transfer(client);
56584
+ } finally {
56585
+ client.resetAllCaches();
56586
+ }
56556
56587
  });
56557
56588
  }
56558
56589
  /** Capture only the compatibility decision made by this exact borrowed client. */
@@ -56638,7 +56669,6 @@ var LiveSyncJournalReplicator = class extends LiveSyncAbstractReplicator {
56638
56669
  this.closeReplication();
56639
56670
  try {
56640
56671
  if (!await this.client.resetBucket()) throw new Error("Could not reset remote bucket");
56641
- clearHandlers();
56642
56672
  Logger("Remote Bucket Cleared", 64);
56643
56673
  await this.tryCreateRemoteDatabase(setting);
56644
56674
  } catch (ex) {
@@ -56650,7 +56680,6 @@ var LiveSyncJournalReplicator = class extends LiveSyncAbstractReplicator {
56650
56680
  async tryCreateRemoteDatabase(setting) {
56651
56681
  this.closeReplication();
56652
56682
  Logger("Remote Database Created or Connected", 64);
56653
- clearHandlers();
56654
56683
  if (!await this.ensurePBKDF2Salt(setting, true, false)) throw new Error("Could not ensure PBKDF2 salt (Security Seed)");
56655
56684
  return await Promise.resolve();
56656
56685
  }
@@ -56989,8 +57018,18 @@ function createSecuritySeedResourceFactory(createReplicator) {
56989
57018
  return (setting) => {
56990
57019
  const snapshot = snapshotRemoteSettings(setting);
56991
57020
  const replicator = createReplicator();
57021
+ let readPromise;
57022
+ const read = () => {
57023
+ if (readPromise) return readPromise;
57024
+ const pending = Promise.resolve().then(() => replicator.getReplicationPBKDF2Salt(snapshot, true));
57025
+ readPromise = pending;
57026
+ pending.catch(() => {
57027
+ if (readPromise === pending) readPromise = void 0;
57028
+ });
57029
+ return pending;
57030
+ };
56992
57031
  return Promise.resolve({
56993
- read: () => replicator.getReplicationPBKDF2Salt(snapshot, true),
57032
+ read,
56994
57033
  dispose: createReplicatorDisposer(replicator)
56995
57034
  });
56996
57035
  };
@@ -57212,7 +57251,7 @@ function createCentralReplicatorProviderDefinitions(host) {
57212
57251
  [REMOTE_MINIO]: {
57213
57252
  kind: REMOTE_MINIO,
57214
57253
  diagnosticName: "Object Storage",
57215
- readiness: CENTRAL_REMOTE_REPLICATION_READINESS,
57254
+ readiness: PROVIDER_OWNED_CENTRAL_REMOTE_REPLICATION_READINESS,
57216
57255
  isConfigured: (settings) => settings.remoteType === REMOTE_MINIO && !!settings.endpoint?.trim() && !!settings.bucket?.trim(),
57217
57256
  configurationIdentity: getObjectStorageReplicatorConfigurationIdentity,
57218
57257
  create: () => Promise.resolve(new LiveSyncJournalReplicator(host)),
@@ -57736,8 +57775,21 @@ var ReplicateResultProcessor = class {
57736
57775
  this.updateProcessingActivity();
57737
57776
  fireAndForget(() => this.runProcessQueue());
57738
57777
  }
57778
+ /**
57779
+ * Whether the application accepts replicated documents being applied.
57780
+ *
57781
+ * Remediation mode refuses the reconciliation scan which readiness depends upon, so the
57782
+ * application stays unready for as long as the modification-time limit is configured.
57783
+ * Applying the received documents is what that mode exists for, and `parseDocumentChange` keeps
57784
+ * each one within the limit, so readiness is not required while the mode is active.
57785
+ */
57786
+ get acceptsResultApplication() {
57787
+ if (this.services.appLifecycle.isReady()) return true;
57788
+ if (this.context.currentSettings().maxMTimeForReflectEvents <= 0) return false;
57789
+ return this.services.database.isDatabaseReady();
57790
+ }
57739
57791
  get isSuspended() {
57740
- return this._suspended || !this.services.appLifecycle.isReady() || this.context.currentSettings().suspendParseReplicationResult || this.services.appLifecycle.isSuspended();
57792
+ return this._suspended || !this.acceptsResultApplication || this.context.currentSettings().suspendParseReplicationResult || this.services.appLifecycle.isSuspended();
57741
57793
  }
57742
57794
  /**
57743
57795
  * Take a snapshot of the current processing state.
@@ -58084,6 +58136,7 @@ function useReplicationFeature(core) {
58084
58136
  runLocalApplicationActivity: async (task, options) => localApplicationActivityOwner ? await localApplicationActivityOwner.runBoundedLocalApplicationActivity(task, options) : await task(),
58085
58137
  services: {
58086
58138
  appLifecycle: services.appLifecycle,
58139
+ database: services.database,
58087
58140
  path: services.path,
58088
58141
  replication: services.replication,
58089
58142
  vault: services.vault
@@ -59274,6 +59327,10 @@ Please enable them from the settings screen after setup is complete.`, ["OK"]);
59274
59327
  await this.informOptionalFeatures();
59275
59328
  }
59276
59329
  async performRebuildEverything() {
59330
+ if (isRemediationModeActive(this.setting.currentSettings())) {
59331
+ this._log(`Rebuilding has been refused: remediation mode is active. Clear the modification-time limit to rebuild.`, 64);
59332
+ throw new Error("Rebuilding is not available while remediation mode is active. Clear the modification-time limit first.");
59333
+ }
59277
59334
  this.appLifecycle.resetIsReady();
59278
59335
  await this.setting.suspendExtraSync();
59279
59336
  await this.setting.applyPartial({
@@ -59395,7 +59452,7 @@ Please enable them from the settings screen after setup is complete.`, ["OK"]);
59395
59452
  suspendParseReplicationResult: false,
59396
59453
  suspendFileWatching: false
59397
59454
  });
59398
- if (!await this.vault.scanVault(true)) return false;
59455
+ if (!isRemediationModeActive(this.setting.currentSettings()) && !await this.vault.scanVault(true)) return false;
59399
59456
  if (!await this.replication.onBeforeReplicate(false)) return false;
59400
59457
  return true;
59401
59458
  }
@@ -59419,7 +59476,7 @@ Please enable them from the settings screen after setup is complete.`, ["OK"]);
59419
59476
  notifyThresholdOfRemoteStorageSize: DEFAULT_SETTINGS.notifyThresholdOfRemoteStorageSize
59420
59477
  });
59421
59478
  const settings = this.setting.currentSettings();
59422
- if (settings.maxMTimeForReflectEvents > 0) {
59479
+ if (isRemediationModeActive(settings)) {
59423
59480
  const ask = `Your settings restrict file reflection times to no later than ${new Date(settings.maxMTimeForReflectEvents).toLocaleString()}.
59424
59481
 
59425
59482
  **This is a recovery configuration.**
@@ -59454,7 +59511,8 @@ Are you sure you wish to proceed?`;
59454
59511
  await this.resetLocalDatabase();
59455
59512
  this.clearFastFetchCheckpoint();
59456
59513
  await delay$1(1e3);
59457
- if (makeLocalChunkBeforeSync) await this.fileHandler.createAllChunks(true);
59514
+ if (isRemediationModeActive(this.setting.currentSettings())) this._log(`Remediation mode: the files in storage are not stored in the database before fetching.`, 64);
59515
+ else if (makeLocalChunkBeforeSync) await this.fileHandler.createAllChunks(true);
59458
59516
  else if (!preventMakeLocalFilesBeforeSync) await this.prepareLocalDatabaseForRebuild();
59459
59517
  await this.replication.markResolved();
59460
59518
  await delay$1(500);
@@ -59567,7 +59625,7 @@ Total bytes fetched: ${sizeToHumanReadable(progress.totalBytes)}`, 64, "fetch-in
59567
59625
  if (!await this.resumeReflectingDatabase(ignoreMinIO)) return false;
59568
59626
  if (!await this.fileProcessing.commitPendingFileEvents()) return false;
59569
59627
  if (controlsReflection) await this.setting.saveSettingData();
59570
- this.appLifecycle.markIsReady();
59628
+ if (!isRemediationModeActive(this.setting.currentSettings())) this.appLifecycle.markIsReady();
59571
59629
  completed = true;
59572
59630
  return true;
59573
59631
  } finally {
@@ -59620,14 +59678,6 @@ Total bytes fetched: ${sizeToHumanReadable(progress.totalBytes)}`, 64, "fetch-in
59620
59678
  };
59621
59679
  //#endregion
59622
59680
  //#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
59681
  async function serializedByKeys(keys, callback) {
59632
59682
  const [key, ...remainingKeys] = keys;
59633
59683
  if (key === void 0) return await callback();
@@ -59649,6 +59699,7 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59649
59699
  setting;
59650
59700
  vault;
59651
59701
  fileReflectionProvenance;
59702
+ deferredConflictChecks = /* @__PURE__ */ new Map();
59652
59703
  constructor(services) {
59653
59704
  super(services);
59654
59705
  this.events = services.events;
@@ -59722,6 +59773,93 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59722
59773
  return matched;
59723
59774
  }
59724
59775
  }
59776
+ /**
59777
+ * Classify a storage read against its displayed database branch.
59778
+ *
59779
+ * A recorded revision identifies the branch and therefore takes precedence
59780
+ * over byte matches. Without a readable base, only current live leaves are
59781
+ * considered. Any match avoids a duplicate write, but only a unique match
59782
+ * identifies provenance; no match is `unknown`.
59783
+ * `preferredPath` selects the provenance key during a rename, and
59784
+ * `currentLoaded` supplies an already decoded candidate body when available.
59785
+ * Missing chunks do not clear provenance unless their metadata is also
59786
+ * missing or deleted.
59787
+ */
59788
+ async classifyStorageContent(file, currentEntry, preferredPath, recordedRevision, currentLoaded) {
59789
+ const path = preferredPath ?? file.path;
59790
+ if (recordedRevision) {
59791
+ const loadedContentIsDecoded = currentLoaded?._rev === recordedRevision;
59792
+ const base = loadedContentIsDecoded ? currentLoaded : await this.db.fetchEntry(file, recordedRevision, true, true, true);
59793
+ 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) ? {
59794
+ kind: "unchanged",
59795
+ revision: recordedRevision
59796
+ } : {
59797
+ kind: "edited",
59798
+ revision: recordedRevision
59799
+ };
59800
+ if (!base) {
59801
+ const meta = await this.db.fetchEntryMeta(file, recordedRevision, true);
59802
+ if (!meta || meta.deleted || meta._deleted) await this.deleteProvenance(path);
59803
+ }
59804
+ }
59805
+ const matches = currentEntry ? await this.db.findLiveContentRevisions(file, file.body) : [];
59806
+ if (matches.length) return {
59807
+ kind: "matching-leaf",
59808
+ revision: matches.length === 1 ? matches[0] : void 0
59809
+ };
59810
+ return { kind: "unknown" };
59811
+ }
59812
+ /** Record provenance only when storage matches one unambiguous live leaf. */
59813
+ async rememberMatchingLeaf(path, revision, mtime) {
59814
+ if (revision) await this.setProvenance(path, revision, mtime);
59815
+ }
59816
+ /**
59817
+ * Read the raw provenance value used by an optimistic storage snapshot.
59818
+ * Unlike `getProvenance`, this does not validate or remove the referenced
59819
+ * database revision; an unreadable value is represented as `undefined`.
59820
+ */
59821
+ async readProvenanceSnapshot(path) {
59822
+ try {
59823
+ return (await this.fileReflectionProvenance?.get(path))?.revision;
59824
+ } catch {
59825
+ return;
59826
+ }
59827
+ }
59828
+ /**
59829
+ * Check that storage still has the same path, bytes, timestamp, and
59830
+ * provenance as a previously captured snapshot.
59831
+ */
59832
+ async currentStorageSnapshotMatches(file, revision) {
59833
+ const current = await this.storage.getStub(file.path);
59834
+ if (!current || isFolderInfo(current) || current.path !== file.path) return false;
59835
+ const readCurrent = await this.readFileFromStub(current);
59836
+ return readCurrent.stat.mtime === file.stat.mtime && await isDocContentSame(readCurrent.body, file.body) && await this.readProvenanceSnapshot(file.path) === revision;
59837
+ }
59838
+ /**
59839
+ * Publish provenance after a durable database write if storage is unchanged.
59840
+ * A failed revalidation leaves the database revision stored and asks the
59841
+ * caller to reread storage before proceeding.
59842
+ */
59843
+ async finaliseStoredRevision(file, observedProvenance, storedRevision) {
59844
+ if (await this.currentStorageSnapshotMatches(file, observedProvenance)) {
59845
+ await this.setProvenance(file.path, storedRevision, file.stat.mtime);
59846
+ return true;
59847
+ } else return false;
59848
+ }
59849
+ /**
59850
+ * Reread storage after a restored startup snapshot changed and retry a save.
59851
+ * The bounded counter prevents an unstable file from causing an endless
59852
+ * startup loop; the next event or scan can reconcile a final refusal.
59853
+ */
59854
+ async retryCurrentStorage(path, preferredBasePath, snapshotRetry) {
59855
+ if (snapshotRetry >= 2) {
59856
+ this._log(`Storage kept changing while saving ${path}; a fresh event is required`, 64);
59857
+ return false;
59858
+ }
59859
+ const fresh = await this.storage.getStub(path);
59860
+ if (!fresh || isFolderInfo(fresh)) return false;
59861
+ return await this.storeFileToDBFromRevision(fresh, false, false, preferredBasePath, true, snapshotRetry + 1);
59862
+ }
59725
59863
  getPath(entry) {
59726
59864
  return this.path.getPath(entry);
59727
59865
  }
@@ -59734,14 +59872,55 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59734
59872
  if (!readFile) throw new Error(`File ${file.path} is not exist on the storage`);
59735
59873
  return readFile;
59736
59874
  }
59875
+ async tryRecordUntrackedFileRevision(info, expectedRevision) {
59876
+ if (!this.fileReflectionProvenance || !expectedRevision) return false;
59877
+ const path = getStoragePathFromUXFileInfo(info);
59878
+ try {
59879
+ return await this.serializedByFileEventPaths([path], async () => {
59880
+ const provenance = this.fileReflectionProvenance;
59881
+ if (await provenance.get(path)) return false;
59882
+ const stub = await this.storage.getStub(path);
59883
+ if (!stub || isFolderInfo(stub) || stub.path !== path) return false;
59884
+ const file = await this.readFileFromStub(stub);
59885
+ const current = await this.db.fetchEntryMeta(path, void 0, true);
59886
+ if (!current || current._rev !== expectedRevision || current.deleted || current._deleted) return false;
59887
+ if ((await this.db.getConflictedRevs(path)).length > 0) return false;
59888
+ const entry = await this.db.fetchEntry(path, expectedRevision, true, true, true);
59889
+ if (!entry || entry._rev !== expectedRevision || entry.deleted || entry._deleted) return false;
59890
+ if (!await isDocContentSame(readContent(entry), file.body)) return false;
59891
+ const latest = await this.db.fetchEntryMeta(path, void 0, true);
59892
+ if (!latest || latest._rev !== expectedRevision || latest.deleted || latest._deleted) return false;
59893
+ if ((await this.db.getConflictedRevs(path)).length > 0) return false;
59894
+ if (!await this.currentStorageSnapshotMatches(file, void 0)) return false;
59895
+ if (await provenance.get(path)) return false;
59896
+ await provenance.set(path, {
59897
+ revision: expectedRevision,
59898
+ observedStorageMtime: file.stat.mtime
59899
+ });
59900
+ return true;
59901
+ });
59902
+ } catch (ex) {
59903
+ this._log(`Could not record unchanged file provenance for ${path}`, 16);
59904
+ this._log(ex, 16);
59905
+ return false;
59906
+ }
59907
+ }
59737
59908
  async infoToStub(info) {
59738
59909
  if (info == null) return null;
59739
59910
  return typeof info === "string" ? await this.storage.getFileStub(info) : info;
59740
59911
  }
59741
59912
  async storeFileToDB(info, force = false, onlyChunks = false) {
59742
- return await this.storeFileToDBFromRevision(info, force, onlyChunks);
59913
+ return await this.serializedByFileEventPaths([getStoragePathFromUXFileInfo(info)], () => this.storeFileToDBFromRevision(info, force, onlyChunks));
59743
59914
  }
59744
59915
  async storeFileToDBWithBaseRevision(info, baseRevision, createIfDifferent = true) {
59916
+ return await this.serializedByFileEventPaths([getStoragePathFromUXFileInfo(info)], () => this.storeFileToDBWithBaseRevisionCore(info, baseRevision, createIfDifferent));
59917
+ }
59918
+ /**
59919
+ * Store current storage content below an exact live revision. A differing
59920
+ * body is rejected when `createIfDifferent` is false; callers hold the
59921
+ * document lock for this core operation.
59922
+ */
59923
+ async storeFileToDBWithBaseRevisionCore(info, baseRevision, createIfDifferent) {
59745
59924
  const file = await this.infoToStub(info);
59746
59925
  if (file == null) {
59747
59926
  this._log(`File ${tryGetFilePath(info)} is not exist on the storage`, 16);
@@ -59766,7 +59945,7 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59766
59945
  const loadedBase = await this.db.fetchEntry(file, baseRevision, true, true);
59767
59946
  if (loadedBase && await isDocContentSame(getDocDataAsArray(loadedBase.data), readFile.body)) {
59768
59947
  await this.setProvenance(file.path, baseRevision, readFile.stat.mtime);
59769
- await this.conflict.queueCheckFor(file.path);
59948
+ await this.queueConflictCheckFor(file.path);
59770
59949
  return true;
59771
59950
  }
59772
59951
  }
@@ -59777,10 +59956,16 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59777
59956
  const storedRevision = await this.db.storeWithBaseRevision(readFile, baseRevision, true);
59778
59957
  if (storedRevision === false) return false;
59779
59958
  await this.setProvenance(file.path, storedRevision, readFile.stat.mtime);
59780
- await this.conflict.queueCheckFor(file.path);
59959
+ await this.queueConflictCheckFor(file.path);
59781
59960
  return true;
59782
59961
  }
59783
- async storeFileToDBFromRevision(info, force = false, onlyChunks = false, preferredBasePath) {
59962
+ /**
59963
+ * Save one storage snapshot while the caller holds its document lock.
59964
+ * Ordinary saves read once inside the lock and leave retries disabled.
59965
+ * Restored startup events retain bounded rereads because file watching has
59966
+ * not yet started and cannot supply a new event for a concurrent edit.
59967
+ */
59968
+ async storeFileToDBFromRevision(info, force = false, onlyChunks = false, preferredBasePath, retryIfStorageChanges = false, snapshotRetry = 0) {
59784
59969
  const file = await this.infoToStub(info);
59785
59970
  if (file == null) {
59786
59971
  this._log(`File ${tryGetFilePath(info)} is not exist on the storage`, 16);
@@ -59794,9 +59979,39 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59794
59979
  const readFile2 = await this.readFileFromStub(file);
59795
59980
  return await this.db.createChunks(readFile2, force, true);
59796
59981
  }
59982
+ const observedProvenance = await this.readProvenanceSnapshot(preferredBasePath ?? file.path);
59797
59983
  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) {
59984
+ const entry = await this.db.fetchEntry(file, void 0, true, true, true);
59985
+ const currentEntry = entry || await this.db.fetchEntryMeta(file, void 0, true);
59986
+ const isConflicted = (await this.db.getConflictedRevs(file)).length > 0;
59987
+ if (!force && currentEntry && !currentEntry.deleted && !currentEntry._deleted) {
59988
+ const classification = await this.classifyStorageContent(readFile, currentEntry, preferredBasePath, observedProvenance, entry ? {
59989
+ _rev: entry._rev,
59990
+ data: readContent(entry)
59991
+ } : void 0);
59992
+ if (retryIfStorageChanges && !await this.currentStorageSnapshotMatches(readFile, observedProvenance)) return await this.retryCurrentStorage(file.path, preferredBasePath, snapshotRetry);
59993
+ if (classification.kind === "unchanged") {
59994
+ if (isConflicted) await this.queueConflictCheckFor(file.path);
59995
+ else if (classification.revision !== currentEntry._rev) {
59996
+ if (!entry) return false;
59997
+ return await this.dbToStorageCore(file.path, file);
59998
+ } else this.path.markChangesAreSame(readFile, readFile.stat.mtime, currentEntry.mtime);
59999
+ return true;
60000
+ }
60001
+ if (classification.kind === "matching-leaf") {
60002
+ await this.rememberMatchingLeaf(file.path, classification.revision, readFile.stat.mtime);
60003
+ if (isConflicted) await this.queueConflictCheckFor(file.path);
60004
+ return true;
60005
+ }
60006
+ const storedRevision2 = classification.kind === "edited" ? await this.db.storeWithBaseRevision(readFile, classification.revision, true) : await this.db.storeIndependentRevision(readFile, true);
60007
+ if (storedRevision2 === false) return false;
60008
+ if (preferredBasePath && preferredBasePath !== file.path) await this.deleteProvenance(preferredBasePath);
60009
+ if (retryIfStorageChanges && !await this.finaliseStoredRevision(readFile, observedProvenance, storedRevision2)) return await this.retryCurrentStorage(file.path, preferredBasePath, snapshotRetry);
60010
+ if (!retryIfStorageChanges) await this.setProvenance(file.path, storedRevision2, readFile.stat.mtime);
60011
+ if (isConflicted || classification.kind === "unknown") await this.queueConflictCheckFor(file.path);
60012
+ return true;
60013
+ }
60014
+ if (isConflicted) {
59800
60015
  const baseRevision = await this.getProvenBaseRevision(readFile, preferredBasePath);
59801
60016
  if (baseRevision) {
59802
60017
  const baseEntry = await this.db.fetchEntry(file, baseRevision, true, true);
@@ -59809,28 +60024,28 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59809
60024
  if (storedRevision3 === false) return false;
59810
60025
  if (preferredBasePath && preferredBasePath !== file.path) await this.deleteProvenance(preferredBasePath);
59811
60026
  await this.setProvenance(file.path, storedRevision3, readFile.stat.mtime);
59812
- await this.conflict.queueCheckFor(file.path);
60027
+ await this.queueConflictCheckFor(file.path);
59813
60028
  return true;
59814
60029
  }
59815
- const currentEntry = entry || await this.db.fetchEntryMeta(file, void 0, true);
59816
- const currentRevision = currentEntry && currentEntry._rev;
60030
+ const currentEntry2 = entry || await this.db.fetchEntryMeta(file, void 0, true);
60031
+ const currentRevision = currentEntry2 && currentEntry2._rev;
59817
60032
  if (!currentRevision) {
59818
60033
  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);
60034
+ await this.queueConflictCheckFor(file.path);
59820
60035
  return false;
59821
60036
  }
59822
60037
  const storedRevision2 = await this.db.storeAsConflictedRevisionWithResult(readFile, currentRevision, true);
59823
60038
  if (storedRevision2 === false) {
59824
60039
  this._log(`Could not preserve the unknown conflict branch for ${file.path}`, 64);
59825
- await this.conflict.queueCheckFor(file.path);
60040
+ await this.queueConflictCheckFor(file.path);
59826
60041
  return false;
59827
60042
  }
59828
60043
  if (preferredBasePath && preferredBasePath !== file.path) await this.deleteProvenance(preferredBasePath);
59829
60044
  await this.setProvenance(file.path, storedRevision2, readFile.stat.mtime);
59830
- await this.conflict.queueCheckFor(file.path);
60045
+ await this.queueConflictCheckFor(file.path);
59831
60046
  return true;
59832
60047
  }
59833
- if (!entry || entry.deleted || entry._deleted) {
60048
+ if (!currentEntry || currentEntry.deleted || currentEntry._deleted) {
59834
60049
  const storedRevision2 = await this.db.storeWithBaseRevision(readFile, entry && entry._rev, true);
59835
60050
  if (storedRevision2 === false) return false;
59836
60051
  if (preferredBasePath && preferredBasePath !== file.path) await this.deleteProvenance(preferredBasePath);
@@ -59838,7 +60053,7 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59838
60053
  return true;
59839
60054
  }
59840
60055
  let shouldApplied = false;
59841
- if (!force && !onlyChunks) {
60056
+ if (!force && !onlyChunks && entry) {
59842
60057
  if (this.path.compareFileFreshness(file, entry) !== EVEN) shouldApplied = true;
59843
60058
  if (!shouldApplied) if (await isDocContentSame(getDocDataAsArray(entry.data), readFile.body)) this.path.markChangesAreSame(readFile, readFile.stat.mtime, entry.mtime);
59844
60059
  else shouldApplied = true;
@@ -59848,13 +60063,20 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59848
60063
  return true;
59849
60064
  }
59850
60065
  }
59851
- const storedRevision = await this.db.storeWithBaseRevision(readFile, entry._rev, true);
60066
+ const storedRevision = await this.db.storeWithBaseRevision(readFile, currentEntry._rev, true);
59852
60067
  if (storedRevision === false) return false;
59853
60068
  if (preferredBasePath && preferredBasePath !== file.path) await this.deleteProvenance(preferredBasePath);
59854
60069
  await this.setProvenance(file.path, storedRevision, readFile.stat.mtime);
59855
60070
  return true;
59856
60071
  }
59857
60072
  async deleteFileFromDB(info) {
60073
+ return await this.serializedByFileEventPaths([getStoragePathFromUXFileInfo(info)], () => this.deleteFileFromDBCore(info));
60074
+ }
60075
+ /**
60076
+ * Record a storage deletion under the caller's document lock, preserving
60077
+ * the displayed conflict branch when its provenance is known.
60078
+ */
60079
+ async deleteFileFromDBCore(info) {
59858
60080
  const file = await this.infoToStub(info);
59859
60081
  const path = typeof info === "string" ? info : tryGetFilePath(info);
59860
60082
  if (file == null) {
@@ -59871,12 +60093,12 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59871
60093
  const provenance = await this.getProvenance(path);
59872
60094
  if (!provenance) {
59873
60095
  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);
60096
+ await this.queueConflictCheckFor(path);
59875
60097
  return true;
59876
60098
  }
59877
60099
  if (await this.db.storeDeletionWithBaseRevision(path, provenance.revision) === false) return false;
59878
60100
  await this.deleteProvenance(path);
59879
- await this.conflict.queueCheckFor(path);
60101
+ await this.queueConflictCheckFor(path);
59880
60102
  return true;
59881
60103
  }
59882
60104
  this._log(`File ${path} is missing on storage; deleting from the database by path`, 32);
@@ -59901,12 +60123,12 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59901
60123
  } catch {}
59902
60124
  if (!baseRevision) {
59903
60125
  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);
60126
+ await this.queueConflictCheckFor(file.path);
59905
60127
  return true;
59906
60128
  }
59907
60129
  if (await this.db.storeDeletionWithBaseRevision(file.path, baseRevision) === false) return false;
59908
60130
  await this.deleteProvenance(file.path);
59909
- await this.conflict.queueCheckFor(file.path);
60131
+ await this.queueConflictCheckFor(file.path);
59910
60132
  return true;
59911
60133
  }
59912
60134
  const deleted = await this.db.delete(file);
@@ -59914,11 +60136,20 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59914
60136
  return deleted;
59915
60137
  }
59916
60138
  async renameFileInDB(info, oldPath) {
60139
+ const newPath = getStoragePathFromUXFileInfo(info);
60140
+ return await this.serializedByFileEventPaths([oldPath, newPath], () => this.renameFileInDBCore(info, oldPath));
60141
+ }
60142
+ /**
60143
+ * Record a rename under the caller's source and target locks. Case-only
60144
+ * renames retain the source provenance while other renames handle the
60145
+ * source conflict before deleting its old path.
60146
+ */
60147
+ async renameFileInDBCore(info, oldPath, retryIfStorageChanges = false) {
59917
60148
  const newPath = getStoragePathFromUXFileInfo(info);
59918
60149
  const [oldDocumentId, newDocumentId] = await Promise.all([this.path.path2id(oldPath), this.path.path2id(newPath)]);
59919
60150
  if (oldDocumentId === newDocumentId) {
59920
60151
  this._log(`Updating the stored path for case-only rename: ${oldPath} -> ${newPath}`, 16);
59921
- return await this.storeFileToDBFromRevision(info, true, false, oldPath);
60152
+ return await this.storeFileToDBFromRevision(info, true, false, oldPath, retryIfStorageChanges);
59922
60153
  }
59923
60154
  const oldEntry = await this.db.fetchEntryMeta(oldPath, void 0, true);
59924
60155
  const newEntry = await this.db.fetchEntryMeta(newPath, void 0, true);
@@ -59926,7 +60157,7 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59926
60157
  this._log(`Refusing to overwrite the existing database entry while renaming ${oldPath} to ${newPath}`, 64);
59927
60158
  return false;
59928
60159
  }
59929
- if (!await this.storeFileToDB(info, true)) {
60160
+ if (!await this.storeFileToDBFromRevision(info, true, false, void 0, retryIfStorageChanges)) {
59930
60161
  this._log(`Failed to store rename target; preserving source in the database: ${oldPath}`, 64);
59931
60162
  return false;
59932
60163
  }
@@ -59943,12 +60174,12 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59943
60174
  }
59944
60175
  if (!baseRevision) {
59945
60176
  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);
60177
+ await this.queueConflictCheckFor(oldPath);
59947
60178
  return true;
59948
60179
  }
59949
60180
  if (await this.db.storeDeletionWithBaseRevision(oldPath, baseRevision) === false) return false;
59950
60181
  await this.deleteProvenance(oldPath);
59951
- await this.conflict.queueCheckFor(oldPath);
60182
+ await this.queueConflictCheckFor(oldPath);
59952
60183
  return true;
59953
60184
  }
59954
60185
  const deleted = await this.db.delete(oldPath);
@@ -59956,6 +60187,10 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59956
60187
  return deleted;
59957
60188
  }
59958
60189
  async deleteRevisionFromDB(info, rev) {
60190
+ return await this.serializedByFileEventPaths([getStoragePathFromUXFileInfo(info)], () => this.deleteRevisionFromDBCore(info, rev));
60191
+ }
60192
+ /** Delete one selected revision and clear matching provenance under the caller's document lock. */
60193
+ async deleteRevisionFromDBCore(info, rev) {
59959
60194
  const path = getStoragePathFromUXFileInfo(info);
59960
60195
  const provenance = await this.getProvenance(path);
59961
60196
  const deleted = await this.db.delete(info, rev);
@@ -59963,6 +60198,13 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59963
60198
  return deleted;
59964
60199
  }
59965
60200
  async resolveConflictedByDeletingRevision(info, rev) {
60201
+ return await this.serializedByFileEventPaths([getStoragePathFromUXFileInfo(info)], () => this.resolveConflictedByDeletingRevisionCore(info, rev));
60202
+ }
60203
+ /**
60204
+ * Apply the legacy resolve-by-delete sequence while holding one document
60205
+ * lock; metadata is captured before the selected revision is removed.
60206
+ */
60207
+ async resolveConflictedByDeletingRevisionCore(info, rev) {
59966
60208
  const path = getStoragePathFromUXFileInfo(info);
59967
60209
  const file = await this.infoToStub(info);
59968
60210
  const docEntry = await this.db.fetchEntryMeta(file ?? info, rev, true);
@@ -59970,7 +60212,7 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59970
60212
  this._log(`Failed to read the conflicted revision ${rev} of ${path}`, 16);
59971
60213
  return false;
59972
60214
  }
59973
- if (!await this.deleteRevisionFromDB(info, rev)) {
60215
+ if (!await this.deleteRevisionFromDBCore(info, rev)) {
59974
60216
  this._log(`Failed to delete the conflicted revision ${rev} of ${path}`, 16);
59975
60217
  return false;
59976
60218
  }
@@ -59985,6 +60227,13 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59985
60227
  this._log(`Cannot select database revision ${rev} without a file path`, 16);
59986
60228
  return false;
59987
60229
  }
60230
+ return await this.serializedByFileEventPaths([getStoragePathFromUXFileInfo(info)], () => this.dbToStorageWithSpecificRevCore(info, rev, force));
60231
+ }
60232
+ /**
60233
+ * Reflect a selected live revision under the caller's document lock.
60234
+ * The public wrapper performs the same lock acquisition before entering here.
60235
+ */
60236
+ async dbToStorageWithSpecificRevCore(info, rev, force) {
59988
60237
  const file = await this.infoToStub(info);
59989
60238
  const databaseTarget = file ?? info;
59990
60239
  const [docEntry, currentEntry, conflictedRevisions] = await Promise.all([
@@ -60003,6 +60252,11 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
60003
60252
  return await this.applyDatabaseEntryToStorage(docEntry, file, force, true);
60004
60253
  }
60005
60254
  async dbToStorage(entryInfo, info, force) {
60255
+ const pathFromEntryInfo = typeof entryInfo === "string" ? entryInfo : this.getPath(entryInfo);
60256
+ return await this.serializedByFileEventPaths([pathFromEntryInfo], () => this.dbToStorageCore(entryInfo, info, force));
60257
+ }
60258
+ /** Fetch the current metadata and reflect it while the caller holds its lock. */
60259
+ async dbToStorageCore(entryInfo, info, force) {
60006
60260
  const file = await this.infoToStub(info);
60007
60261
  const pathFromEntryInfo = typeof entryInfo === "string" ? entryInfo : this.getPath(entryInfo);
60008
60262
  const docEntry = await this.db.fetchEntryMeta(pathFromEntryInfo, void 0, true);
@@ -60012,12 +60266,18 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
60012
60266
  }
60013
60267
  return await this.applyDatabaseEntryToStorage(docEntry, file, force);
60014
60268
  }
60015
- async applyDatabaseEntryToStorage(docEntry, file, force, allowExistingConflicts = false) {
60269
+ /**
60270
+ * Reflect one database revision while protecting concurrent storage edits.
60271
+ * Overwrite and deletion paths preserve changed bytes first, then revalidate
60272
+ * their snapshot and the current database revision immediately before the
60273
+ * destructive operation.
60274
+ */
60275
+ async applyDatabaseEntryToStorage(docEntry, file, force, allowExistingConflicts = false, incomingRetry = 0) {
60016
60276
  const mode = file == null ? "create" : "modify";
60017
60277
  const path = this.getPath(docEntry);
60018
60278
  const settings = this.setting.currentSettings();
60019
60279
  if ((await this.db.getConflictedRevs(path)).length > 0 && !allowExistingConflicts) if (settings.writeDocumentsIfConflicted) {} else {
60020
- await this.conflict.queueCheckForIfOpen(path);
60280
+ await this.queueConflictCheckFor(path, true);
60021
60281
  return true;
60022
60282
  }
60023
60283
  let existDoc = await this.storage.getStub(path);
@@ -60032,7 +60292,28 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
60032
60292
  return true;
60033
60293
  }
60034
60294
  if (!existOnDB && existDoc) {
60035
- if (!force && !settings.writeDocumentsIfConflicted && await this.preserveUnsyncedStorageAsConflict(path, existDoc, docEntry)) return true;
60295
+ let safeDeletionSnapshot;
60296
+ if (!force && !settings.writeDocumentsIfConflicted) {
60297
+ let protection = await this.preserveUnsyncedStorageAsConflict(path, existDoc, docEntry);
60298
+ if (protection.preserved) return true;
60299
+ if (!protection.snapshot || !await this.currentStorageSnapshotMatches(protection.snapshot.file, protection.snapshot.revision)) {
60300
+ protection = await this.recheckIncomingStorage(path, docEntry, void 0, allowExistingConflicts);
60301
+ if (protection.preserved) return true;
60302
+ if (!protection.snapshot || !await this.currentStorageSnapshotMatches(protection.snapshot.file, protection.snapshot.revision)) return false;
60303
+ }
60304
+ safeDeletionSnapshot = protection.snapshot;
60305
+ }
60306
+ let latest2 = await this.reconcileAdvancedIncomingRevision(docEntry, path, force, allowExistingConflicts, incomingRetry);
60307
+ if (latest2 !== void 0) return latest2;
60308
+ if (safeDeletionSnapshot && !await this.currentStorageSnapshotMatches(safeDeletionSnapshot.file, safeDeletionSnapshot.revision)) {
60309
+ const protection = await this.recheckIncomingStorage(path, docEntry, void 0, allowExistingConflicts);
60310
+ if (protection.preserved) return true;
60311
+ if (!protection.snapshot || !await this.currentStorageSnapshotMatches(protection.snapshot.file, protection.snapshot.revision)) return false;
60312
+ safeDeletionSnapshot = protection.snapshot;
60313
+ latest2 = await this.reconcileAdvancedIncomingRevision(docEntry, path, force, allowExistingConflicts, incomingRetry);
60314
+ if (latest2 !== void 0) return latest2;
60315
+ if (!await this.currentStorageSnapshotMatches(safeDeletionSnapshot.file, safeDeletionSnapshot.revision)) return false;
60316
+ }
60036
60317
  await this.storage.deleteVaultItem(path);
60037
60318
  await this.deleteProvenance(path);
60038
60319
  return true;
@@ -60074,6 +60355,7 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
60074
60355
  return true;
60075
60356
  }
60076
60357
  }
60358
+ let safeSnapshot;
60077
60359
  if (existDoc && !force) {
60078
60360
  let shouldApplied = false;
60079
60361
  if (this.path.compareFileFreshness(existDoc, docEntry) !== EVEN) shouldApplied = true;
@@ -60086,9 +60368,27 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
60086
60368
  this._log(`File ${docRead.path} is not changed`, 16);
60087
60369
  return true;
60088
60370
  }
60089
- if (!force && !settings.writeDocumentsIfConflicted && await this.preserveUnsyncedStorageAsConflict(path, existDoc, docEntry, docData)) return true;
60371
+ if (!force && !settings.writeDocumentsIfConflicted) {
60372
+ let protection = await this.preserveUnsyncedStorageAsConflict(path, existDoc, docEntry, docData);
60373
+ if (protection.preserved) return true;
60374
+ if (!protection.snapshot) {
60375
+ protection = await this.recheckIncomingStorage(path, docEntry, docData, allowExistingConflicts);
60376
+ if (protection.preserved) return true;
60377
+ if (!protection.snapshot) return false;
60378
+ }
60379
+ safeSnapshot = protection.snapshot;
60380
+ }
60090
60381
  } else this._log(`File ${docRead.path} ${existDoc ? "(new) " : ""} ${force ? " (forced)" : ""}`, 16);
60091
60382
  await this.storage.ensureDir(path);
60383
+ if (safeSnapshot && !await this.currentStorageSnapshotMatches(safeSnapshot.file, safeSnapshot.revision)) {
60384
+ const protection = await this.recheckIncomingStorage(path, docEntry, docData, allowExistingConflicts);
60385
+ if (protection.preserved) return true;
60386
+ if (!protection.snapshot || !await this.currentStorageSnapshotMatches(protection.snapshot.file, protection.snapshot.revision)) return false;
60387
+ safeSnapshot = protection.snapshot;
60388
+ }
60389
+ const latest = await this.reconcileAdvancedIncomingRevision(docEntry, path, force, allowExistingConflicts, incomingRetry);
60390
+ if (latest !== void 0) return latest;
60391
+ if (safeSnapshot && !await this.currentStorageSnapshotMatches(safeSnapshot.file, safeSnapshot.revision)) return false;
60092
60392
  const ret = await this.storage.writeFileAuto(path, docData, {
60093
60393
  ctime: docRead.ctime,
60094
60394
  mtime: docRead.mtime
@@ -60097,32 +60397,97 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
60097
60397
  this.storage.triggerFileEvent(mode, path);
60098
60398
  if (ret && this.fileReflectionProvenance) {
60099
60399
  const storedStat = await this.storage.stat(path);
60400
+ if (safeSnapshot && await this.readProvenanceSnapshot(path) !== safeSnapshot.revision) return ret;
60100
60401
  await this.setProvenance(path, docEntry._rev, storedStat?.mtime);
60101
60402
  }
60102
60403
  return ret;
60103
60404
  }
60405
+ /**
60406
+ * Preserve storage bytes before an incoming reflection can replace them.
60407
+ *
60408
+ * The initial read and provenance form one candidate snapshot. Classification
60409
+ * gives a recorded branch priority, deduplicates matching live leaves, or
60410
+ * creates an independent root for unknown origin. Optional `incomingContent` avoids
60411
+ * re-reading an already loaded incoming body. Storage is revalidated before
60412
+ * and after the database write; `preserved: true` stops the incoming write,
60413
+ * while a returned `snapshot` lets the caller continue only after revalidation.
60414
+ */
60104
60415
  async preserveUnsyncedStorageAsConflict(path, existDoc, incomingEntry, incomingContent) {
60416
+ const observedProvenance = await this.readProvenanceSnapshot(path);
60105
60417
  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);
60418
+ const snapshot = {
60419
+ file: readFile,
60420
+ revision: observedProvenance
60421
+ };
60422
+ if (incomingContent && await isDocContentSame(incomingContent, readFile.body)) return await this.currentStorageSnapshotMatches(readFile, observedProvenance) ? {
60423
+ preserved: false,
60424
+ snapshot
60425
+ } : { preserved: false };
60426
+ if (!incomingEntry._rev) return { preserved: false };
60427
+ const classification = await this.classifyStorageContent(readFile, incomingEntry, void 0, observedProvenance, incomingContent ? {
60428
+ _rev: incomingEntry._rev,
60429
+ data: incomingContent
60430
+ } : void 0);
60431
+ if (!await this.currentStorageSnapshotMatches(readFile, observedProvenance)) return { preserved: false };
60432
+ if (classification.kind === "unchanged") return {
60433
+ preserved: false,
60434
+ snapshot
60435
+ };
60436
+ if (classification.kind === "matching-leaf") {
60437
+ await this.rememberMatchingLeaf(path, classification.revision, readFile.stat.mtime);
60438
+ await this.queueConflictCheckFor(path);
60439
+ return { preserved: true };
60440
+ }
60441
+ const storedRevision = classification.kind === "edited" ? await this.db.storeWithBaseRevision(readFile, classification.revision, true) : await this.db.storeIndependentRevision(readFile, true);
60111
60442
  if (storedRevision === false) {
60112
60443
  this._log(`Prevented overwriting unsynchronised local changes for ${path}`, 64);
60113
- return true;
60444
+ return { preserved: true };
60114
60445
  }
60115
- await this.setProvenance(path, storedRevision, readFile.stat.mtime);
60446
+ if (!await this.finaliseStoredRevision(readFile, observedProvenance, storedRevision)) return { preserved: false };
60116
60447
  this._log(`Preserved unsynchronised local changes as a conflict for ${path}`, 64);
60117
- await this.conflict.queueCheckFor(path);
60118
- return true;
60448
+ await this.queueConflictCheckFor(path);
60449
+ return { preserved: true };
60450
+ }
60451
+ /**
60452
+ * Repeat overwrite protection from a fresh storage read after a snapshot
60453
+ * becomes stale. Existing conflicts may defer reflection and request an
60454
+ * open-only check while leaving the current storage untouched.
60455
+ */
60456
+ async recheckIncomingStorage(path, incomingEntry, incomingContent, allowExistingConflicts) {
60457
+ const current = await this.storage.getStub(path);
60458
+ if (!current || isFolderInfo(current)) return { preserved: false };
60459
+ const protection = await this.preserveUnsyncedStorageAsConflict(path, current, incomingEntry, incomingContent);
60460
+ if (protection.preserved || !protection.snapshot) return protection;
60461
+ if (!allowExistingConflicts && !this.setting.currentSettings().writeDocumentsIfConflicted && (await this.db.getConflictedRevs(path)).length > 0) {
60462
+ await this.queueConflictCheckFor(path, true);
60463
+ return { preserved: true };
60464
+ }
60465
+ return protection;
60466
+ }
60467
+ /**
60468
+ * Re-read database metadata immediately before reflecting an incoming entry.
60469
+ * If the current revision advanced, recurse with fresh storage; force and
60470
+ * explicitly allowed conflict writes retain the caller's selected entry.
60471
+ * `incomingRetry` bounds repeated database churn.
60472
+ */
60473
+ async reconcileAdvancedIncomingRevision(incomingEntry, path, force, allowExistingConflicts, incomingRetry) {
60474
+ if (force || allowExistingConflicts) return void 0;
60475
+ const current = await this.db.fetchEntryMeta(path, void 0, true);
60476
+ if (!current) return false;
60477
+ if (current._rev === incomingEntry._rev) return void 0;
60478
+ if (incomingRetry >= 2) {
60479
+ this._log(`Database kept changing while reflecting ${path}`, 64);
60480
+ return false;
60481
+ }
60482
+ const storage = await this.storage.getStub(path);
60483
+ if (isFolderInfo(storage)) return false;
60484
+ return await this.applyDatabaseEntryToStorage(current, storage, force, allowExistingConflicts, incomingRetry + 1);
60119
60485
  }
60120
60486
  async _anyHandlerProcessesFileEvent(item) {
60121
60487
  if (item.restoredFromPreviousRuntime) return await this._processRestoredFileEvent(item);
60122
60488
  const eventItem = item.args;
60123
60489
  const type = item.type;
60124
60490
  const path = eventItem.file.path;
60125
- if (!await this.isCurrentPathSelected(path)) return false;
60126
60491
  if (type === "RENAME" && !eventItem.oldPath) {
60127
60492
  this._log(`Rename event for ${path} has no source path`, 16);
60128
60493
  return false;
@@ -60130,13 +60495,14 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
60130
60495
  const relatedPath = type === "RENAME" ? eventItem.oldPath : type === "DELETE" ? eventItem.renameTarget : void 0;
60131
60496
  const eventPaths = relatedPath === void 0 ? [path] : [path, relatedPath];
60132
60497
  return await this.serializedByFileEventPaths(eventPaths, async () => {
60498
+ if (!await this.isCurrentPathSelected(path)) return false;
60133
60499
  switch (type) {
60134
60500
  case "CREATE":
60135
- case "CHANGED": return await this.storeFileToDB(item.args.file);
60501
+ case "CHANGED": return await this.storeFileToDBFromRevision(item.args.file);
60136
60502
  case "DELETE":
60137
60503
  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);
60504
+ return await this.deleteFileFromDBCore(item.args.file);
60505
+ case "RENAME": return await this.renameFileInDBCore(item.args.file, item.args.oldPath);
60140
60506
  case "INTERNAL": return false;
60141
60507
  default:
60142
60508
  this._log(`Unsupported event type: ${type}`, 16);
@@ -60177,9 +60543,62 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
60177
60543
  return false;
60178
60544
  }
60179
60545
  }
60546
+ /**
60547
+ * Serialise work by every document ID represented by the supplied paths.
60548
+ * IDs are deduplicated and sorted so aliases take one lock and cross-document renames have one order.
60549
+ * The callback runs under those locks and must use core methods; conflict
60550
+ * hooks requested inside it are deferred until all locks have been released.
60551
+ */
60180
60552
  async serializedByFileEventPaths(eventPaths, callback) {
60181
60553
  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]));
60554
+ const uniqueIds = [...new Set(documentIds)].sort();
60555
+ const lockKeys = uniqueIds.map((documentId) => `processFileEvent-${documentId}`);
60556
+ const pending = [];
60557
+ let result;
60558
+ let failed = false;
60559
+ let failure;
60560
+ try {
60561
+ result = await serializedByKeys(lockKeys, async () => {
60562
+ for (const id of uniqueIds) this.deferredConflictChecks.set(id, pending);
60563
+ try {
60564
+ return await callback(documentIds.length === 2 && documentIds[0] === documentIds[1]);
60565
+ } finally {
60566
+ for (const id of uniqueIds) this.deferredConflictChecks.delete(id);
60567
+ }
60568
+ });
60569
+ } catch (ex) {
60570
+ failed = true;
60571
+ failure = ex;
60572
+ }
60573
+ for (const check of pending) try {
60574
+ if (check.ifOpen) await this.conflict.queueCheckForIfOpen(check.path);
60575
+ else await this.conflict.queueCheckFor(check.path);
60576
+ } catch (ex) {
60577
+ if (!failed) {
60578
+ failed = true;
60579
+ failure = ex;
60580
+ }
60581
+ break;
60582
+ }
60583
+ if (failed) throw failure;
60584
+ return result;
60585
+ }
60586
+ /**
60587
+ * Queue a conflict hook while its document lock is held, or run it directly
60588
+ * when no matching lock is active. Preserve `ifOpen` across deferral.
60589
+ */
60590
+ async queueConflictCheckFor(path, ifOpen = false) {
60591
+ const documentId = await this.path.path2id(path);
60592
+ const pending = this.deferredConflictChecks.get(documentId);
60593
+ if (pending) {
60594
+ pending.push({
60595
+ path,
60596
+ ifOpen
60597
+ });
60598
+ return;
60599
+ }
60600
+ if (ifOpen) await this.conflict.queueCheckForIfOpen(path);
60601
+ else await this.conflict.queueCheckFor(path);
60183
60602
  }
60184
60603
  /**
60185
60604
  * Revalidate a persisted storage operation against the current storage state.
@@ -60187,7 +60606,9 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
60187
60606
  * Snapshot entries preserve operation intent and ordering only. Their file
60188
60607
  * stub, timestamps, and existence assumptions can be stale after a restart.
60189
60608
  * Current inclusion is therefore read from storage, while destructive work
60190
- * is allowed only after current absence has been observed.
60609
+ * is allowed only after current absence has been observed. Store and rename
60610
+ * actions use the fresh reread with bounded retry because no later watcher
60611
+ * event is guaranteed after startup reconciliation.
60191
60612
  */
60192
60613
  async _processRestoredFileEvent(item) {
60193
60614
  const eventItem = item.args;
@@ -60209,9 +60630,9 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
60209
60630
  }
60210
60631
  switch (action.kind) {
60211
60632
  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);
60633
+ case "store": return await this.storeFileToDBFromRevision(action.file, false, false, void 0, true);
60634
+ case "delete": return await this.deleteFileFromDBCore(action.path);
60635
+ case "rename": return await this.renameFileInDBCore(action.file, action.oldPath, true);
60215
60636
  }
60216
60637
  });
60217
60638
  }
@@ -60316,7 +60737,7 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
60316
60737
  this._log(ex, 16);
60317
60738
  }
60318
60739
  async _anyProcessReplicatedDoc(entry) {
60319
- return await serialized(`processReplicatedDoc-${entry._id}`, async () => {
60740
+ return await this.serializedByFileEventPaths([this.getPath(entry)], async () => {
60320
60741
  if (!await this.vault.isTargetFile(entry.path)) {
60321
60742
  this._log(`File ${entry.path} is not the target file`, 16);
60322
60743
  return false;
@@ -60341,7 +60762,7 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
60341
60762
  }
60342
60763
  this._log(`Processing ${path} (${entry._id.substring(0, 8)} :${entry._rev?.substring(0, 5)}) : Started...`, 16);
60343
60764
  this.events.emitEvent(EVENT_CONFLICT_CANCELLED, path);
60344
- const ret = await this.dbToStorage(entry, targetFile);
60765
+ const ret = await this.dbToStorageCore(entry, targetFile);
60345
60766
  this._log(`Processing ${path} (${entry._id.substring(0, 8)} :${entry._rev?.substring(0, 5)}) : Done`);
60346
60767
  return ret;
60347
60768
  }
@@ -61214,6 +61635,7 @@ var ServiceDatabaseFileAccessBase = class extends ServiceModuleBase {
61214
61635
  async store(file, force = false, skipCheck) {
61215
61636
  return await this.__store(file, force, skipCheck, false) !== false;
61216
61637
  }
61638
+ /** Force a child below the supplied base, even if advanced; an undefined base uses the winner. */
61217
61639
  async storeWithBaseRevision(file, baseRevision, skipCheck) {
61218
61640
  const result = await this.__store(file, true, skipCheck, false, {
61219
61641
  mode: "force-base",
@@ -61221,6 +61643,7 @@ var ServiceDatabaseFileAccessBase = class extends ServiceModuleBase {
61221
61643
  });
61222
61644
  return result !== null && typeof result === "object" && "rev" in result ? result.rev : false;
61223
61645
  }
61646
+ /** Extend a current leaf with ordinary MVCC; an advanced base returns `false`. */
61224
61647
  async storeWithLiveBaseRevision(file, baseRevision, skipCheck) {
61225
61648
  const result = await this.__store(file, true, skipCheck, false, {
61226
61649
  mode: "live-base",
@@ -61228,9 +61651,18 @@ var ServiceDatabaseFileAccessBase = class extends ServiceModuleBase {
61228
61651
  });
61229
61652
  return result !== null && typeof result === "object" && "rev" in result ? result.rev : false;
61230
61653
  }
61654
+ /**
61655
+ * Store Chunks and a fresh Metadata root for content with unknown ancestry.
61656
+ * Return its exact revision for provenance, or `false` if no Metadata write succeeded.
61657
+ */
61658
+ async storeIndependentRevision(file, skipCheck) {
61659
+ const result = await this.__store(file, true, skipCheck, false, { mode: "independent-root" });
61660
+ return result !== null && typeof result === "object" && "rev" in result ? result.rev : false;
61661
+ }
61231
61662
  async storeAsConflictedRevision(file, currentRev, skipCheck) {
61232
61663
  return await this.storeAsConflictedRevisionWithResult(file, currentRev, skipCheck) !== false;
61233
61664
  }
61665
+ /** Create a sibling of the selected revision; refuse when its parent cannot be found. */
61234
61666
  async storeAsConflictedRevisionWithResult(file, currentRev, skipCheck) {
61235
61667
  const conflictBaseRev = await this.getParentRev(file, currentRev);
61236
61668
  if (!conflictBaseRev) {
@@ -61239,6 +61671,7 @@ var ServiceDatabaseFileAccessBase = class extends ServiceModuleBase {
61239
61671
  }
61240
61672
  return await this.storeWithBaseRevision(file, conflictBaseRev, skipCheck);
61241
61673
  }
61674
+ /** Record a logical deletion below the displayed branch and return its exact revision. */
61242
61675
  async storeDeletionWithBaseRevision(file, baseRevision) {
61243
61676
  if (!await this.checkIsTargetFile(file)) return false;
61244
61677
  const fullPath = getDatabasePathFromUXFileInfo(file);
@@ -61342,13 +61775,14 @@ var ServiceDatabaseFileAccessBase = class extends ServiceModuleBase {
61342
61775
  this._log(msg + " Skip " + fullPath, 16);
61343
61776
  return true;
61344
61777
  }
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);
61778
+ 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
61779
  if (ret !== false) {
61347
61780
  this._log(msg + fullPath);
61348
61781
  this.events.emitEvent(EVENT_FILE_SAVED$1);
61349
61782
  }
61350
61783
  return ret;
61351
61784
  }
61785
+ /** Reconstruct the immediate parent ID from revision history, or return `false` if unavailable. */
61352
61786
  async getParentRev(file, rev) {
61353
61787
  const filename = getDatabasePathFromUXFileInfo(file);
61354
61788
  try {
@@ -61366,6 +61800,11 @@ var ServiceDatabaseFileAccessBase = class extends ServiceModuleBase {
61366
61800
  return false;
61367
61801
  }
61368
61802
  }
61803
+ /**
61804
+ * Search available revision bodies across branches and their ancestors.
61805
+ * `stopAfterFirstMatch` serves existence checks without decoding the remaining candidates.
61806
+ * Historical matches alone do not establish the origin of current storage content.
61807
+ */
61369
61808
  async findContentRevisionsInternal(file, content, currentRev, stopAfterFirstMatch = false) {
61370
61809
  const filename = getDatabasePathFromUXFileInfo(file);
61371
61810
  try {
@@ -61405,10 +61844,40 @@ var ServiceDatabaseFileAccessBase = class extends ServiceModuleBase {
61405
61844
  }
61406
61845
  return [];
61407
61846
  }
61847
+ /** Find matching content throughout available history, including non-leaf revisions. */
61408
61848
  async findContentRevisions(file, content, currentRev) {
61409
61849
  if (!await this.checkIsTargetFile(file)) return [];
61410
61850
  return await this.findContentRevisionsInternal(file, content, currentRev);
61411
61851
  }
61852
+ /**
61853
+ * Find live leaves which already represent these bytes, for deduplication when provenance
61854
+ * is unknown. `open_revs` includes conflicting branches; both deletion markers are excluded.
61855
+ * Unlike the historical search, ancestors cannot match and missing Chunks are not fetched.
61856
+ * A read failure yields no confirmed match. Callers decide whether the result identifies a
61857
+ * unique origin; this method does not mutate provenance or hold the revision tree stable.
61858
+ */
61859
+ async findLiveContentRevisions(file, content) {
61860
+ if (!await this.checkIsTargetFile(file)) return [];
61861
+ const filename = getDatabasePathFromUXFileInfo(file);
61862
+ try {
61863
+ const current = await this.database.localDatabase.getDBEntryMeta(filename, void 0, true);
61864
+ if (current === false) return [];
61865
+ const leaves = await this.database.localDatabase.getRaw(current._id, { open_revs: "all" });
61866
+ if (!Array.isArray(leaves)) return [];
61867
+ const matches = [];
61868
+ for (const leaf of leaves) {
61869
+ const rev = leaf.ok?._rev;
61870
+ if (!rev || leaf.ok?.deleted || leaf.ok?._deleted) continue;
61871
+ const entry = await this.database.localDatabase.getDBEntry(filename, { rev }, false, true, true, true);
61872
+ if (entry !== false && !entry.deleted && !entry._deleted && await isDocContentSame(readContent(entry), content)) matches.push(rev);
61873
+ }
61874
+ return matches;
61875
+ } catch (ex) {
61876
+ this._log(`Could not check live revision content for ${filename}`, 16);
61877
+ this._log(ex, 16);
61878
+ return [];
61879
+ }
61880
+ }
61412
61881
  async hasContentInRevisionHistory(file, content, currentRev) {
61413
61882
  if (!await this.checkIsTargetFile(file)) return true;
61414
61883
  return (await this.findContentRevisionsInternal(file, content, currentRev, true)).length > 0;
@@ -61448,17 +61917,17 @@ var ServiceDatabaseFileAccessBase = class extends ServiceModuleBase {
61448
61917
  if (doc === false) return false;
61449
61918
  return doc;
61450
61919
  }
61451
- async fetchEntryFromMeta(meta, waitForReady = true, skipCheck = false) {
61920
+ async fetchEntryFromMeta(meta, waitForReady = true, skipCheck = false, localOnly = false) {
61452
61921
  if (skipCheck && !await this.checkIsTargetFile(meta.path)) return false;
61453
- const doc = await this.database.localDatabase.getDBEntryFromMeta(meta, false, waitForReady);
61922
+ const doc = await this.database.localDatabase.getDBEntryFromMeta(meta, false, waitForReady, localOnly);
61454
61923
  if (doc === false) return false;
61455
61924
  return doc;
61456
61925
  }
61457
- async fetchEntry(file, rev, waitForReady = true, skipCheck = false) {
61926
+ async fetchEntry(file, rev, waitForReady = true, skipCheck = false, localOnly = false) {
61458
61927
  if (skipCheck && !await this.checkIsTargetFile(file)) return false;
61459
61928
  const entry = await this.fetchEntryMeta(file, rev, true);
61460
61929
  if (entry === false) return false;
61461
- return await this.fetchEntryFromMeta(entry, waitForReady, true);
61930
+ return await this.fetchEntryFromMeta(entry, waitForReady, true, localOnly);
61462
61931
  }
61463
61932
  async deleteFromDBbyPath(fullPath, rev) {
61464
61933
  if (!await this.checkIsTargetFile(fullPath)) {
@@ -61551,7 +62020,7 @@ var StorageEventManagerBase = class extends StorageEventManager {
61551
62020
  const settings = this.settings;
61552
62021
  if (!settings.isConfigured) return;
61553
62022
  if (settings.suspendFileWatching) return;
61554
- if (settings.maxMTimeForReflectEvents > 0) return;
62023
+ if (isRemediationModeActive(settings)) return;
61555
62024
  this.fileProcessing.onStorageFileEvent();
61556
62025
  for (const param of params) {
61557
62026
  const atomicKey = [