@vrtmrz/livesync-commonlib 0.7.0 → 0.8.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 (93) hide show
  1. package/README.md +4 -0
  2. package/dist/common/models/diff.definition.d.ts +4 -0
  3. package/dist/common/utils.d.ts +1 -1
  4. package/dist/common/utils.doc.d.ts +5 -0
  5. package/dist/common/utils.doc.js +8 -0
  6. package/dist/common/utils.js +1 -3
  7. package/dist/conflicts/filenameCaseConflict.d.ts +8 -0
  8. package/dist/conflicts/filenameCaseConflict.js +26 -0
  9. package/dist/conflicts.d.ts +1 -0
  10. package/dist/conflicts.js +9 -1
  11. package/dist/interfaces/DatabaseFileAccess.d.ts +12 -1
  12. package/dist/interfaces/FileReflectionProvenance.js +1 -0
  13. package/dist/interfaces/KeyValueDatabase.d.ts +1 -1
  14. package/dist/managers/ConflictManager.d.ts +6 -2
  15. package/dist/managers/ConflictManager.js +73 -22
  16. package/dist/managers/EntryManager/EntryManager.d.ts +5 -0
  17. package/dist/managers/EntryManager/EntryManager.js +5 -0
  18. package/dist/managers/EntryManager/EntryManagerImpls.d.ts +5 -1
  19. package/dist/managers/EntryManager/EntryManagerImpls.js +92 -6
  20. package/dist/managers/LiveSyncManagers.js +2 -1
  21. package/dist/managers/StorageEventManager/admission.d.ts +15 -3
  22. package/dist/managers/StorageEventManager/admission.js +13 -3
  23. package/dist/managers/StorageEventManager/processing.d.ts +2 -2
  24. package/dist/managers/StorageEventManager/processing.js +3 -3
  25. package/dist/managers/StorageEventManager/queue.d.ts +23 -14
  26. package/dist/managers/StorageEventManager/queue.js +70 -30
  27. package/dist/managers/StorageEventManager/snapshot.d.ts +12 -1
  28. package/dist/managers/StorageEventManager/snapshot.js +74 -0
  29. package/dist/managers/StorageEventManager/state.d.ts +27 -5
  30. package/dist/managers/StorageEventManager/state.js +9 -7
  31. package/dist/managers/StorageEventManager.d.ts +6 -0
  32. package/dist/managers/StorageEventManager.js +135 -18
  33. package/dist/managers/adapters/IStorageEventManagerAdapter.d.ts +3 -1
  34. package/dist/managers/adapters/IStorageEventPersistenceAdapter.d.ts +16 -0
  35. package/dist/managers/adapters/index.d.ts +1 -1
  36. package/dist/pouchdb/LiveSyncLocalDB.js +3 -4
  37. package/dist/replication/index.d.ts +2 -0
  38. package/dist/replication/index.js +2 -0
  39. package/dist/replication/replicationResultQueueStore.d.ts +101 -0
  40. package/dist/replication/replicationResultQueueStore.js +140 -0
  41. package/dist/serviceFeatures/offlineScanner/files.js +15 -3
  42. package/dist/serviceFeatures/offlineScanner/scan.js +1 -4
  43. package/dist/serviceModules/ServiceDatabaseFileAccessBase.d.ts +5 -4
  44. package/dist/serviceModules/ServiceDatabaseFileAccessBase.js +28 -7
  45. package/dist/serviceModules/ServiceFileHandlerBase/protection.d.ts +8 -2
  46. package/dist/serviceModules/ServiceFileHandlerBase/protection.js +52 -9
  47. package/dist/serviceModules/ServiceFileHandlerBase/provenance.d.ts +30 -0
  48. package/dist/serviceModules/ServiceFileHandlerBase/provenance.js +82 -10
  49. package/dist/serviceModules/ServiceFileHandlerBase/reflection.js +118 -12
  50. package/dist/serviceModules/ServiceFileHandlerBase/saving.js +32 -8
  51. package/dist/serviceModules/ServiceFileHandlerBase/storage.d.ts +2 -8
  52. package/dist/serviceModules/ServiceFileHandlerBase/storage.js +4 -5
  53. package/dist/services/base/KeyValueDBService.d.ts +6 -6
  54. package/dist/worker/WorkerPushStreamProducer.d.ts +45 -0
  55. package/dist/worker/WorkerPushStreamProducer.js +299 -0
  56. package/dist/worker/WorkerPushStreamReader.d.ts +28 -0
  57. package/dist/worker/WorkerPushStreamReader.js +179 -0
  58. package/dist/worker/backgroundWorkerRpcContract.d.ts +18 -0
  59. package/dist/worker/backgroundWorkerRpcContract.js +24 -0
  60. package/dist/worker/bg.worker.js +2 -16
  61. package/dist/worker/bg.worker.splitting.d.ts +3 -7
  62. package/dist/worker/bg.worker.splitting.js +46 -47
  63. package/dist/worker/bgWorker.d.ts +8 -14
  64. package/dist/worker/bgWorker.direct.d.ts +5 -28
  65. package/dist/worker/bgWorker.direct.js +32 -2
  66. package/dist/worker/bgWorker.errors.d.ts +1 -0
  67. package/dist/worker/bgWorker.errors.js +12 -0
  68. package/dist/worker/bgWorker.js +716 -296
  69. package/dist/worker/bgWorker.splitting.d.ts +12 -26
  70. package/dist/worker/bgWorker.splitting.js +115 -107
  71. package/dist/worker/outOfBandCancelIterator.d.ts +2 -0
  72. package/dist/worker/outOfBandCancelIterator.js +8 -0
  73. package/dist/worker/serveBackgroundWorker.d.ts +3 -0
  74. package/dist/worker/serveBackgroundWorker.js +35 -0
  75. package/dist/worker/splitConnectionTracker.d.ts +25 -0
  76. package/dist/worker/splitConnectionTracker.js +73 -0
  77. package/dist/worker/splitGate.d.ts +19 -0
  78. package/dist/worker/splitGate.js +71 -0
  79. package/dist/worker/universalTypes.d.ts +0 -30
  80. package/dist/worker/universalTypes.js +0 -4
  81. package/dist/worker/workerPushStreamProtocol.d.ts +68 -0
  82. package/dist/worker/workerPushStreamProtocol.js +143 -0
  83. package/docs/conflict-resolution.md +22 -8
  84. package/docs/development.md +6 -0
  85. package/docs/offline-scanner.md +2 -0
  86. package/docs/storage-events-and-reflection.md +171 -2
  87. package/package.json +1 -1
  88. package/dist/worker/bg.common.d.ts +0 -2
  89. package/dist/worker/bg.common.js +0 -6
  90. package/dist/worker/bg.worker.encryption.d.ts +0 -7
  91. package/dist/worker/bg.worker.encryption.js +0 -30
  92. package/dist/worker/bgWorker.encryption.d.ts +0 -22
  93. package/dist/worker/bgWorker.encryption.js +0 -40
package/README.md CHANGED
@@ -59,6 +59,10 @@ remote objects remain available and readable. See the
59
59
  [Journal receive failures and recovery](docs/journal-receive-recovery.md) for
60
60
  the receive, skip, and replay boundaries.
61
61
 
62
+ Commonlib 0.8.1 adds a host-backed result queue store to the `/replication` entry.
63
+ See [saving replication results in a CLI host](docs/storage-events-and-reflection.md#saving-replication-results-in-a-cli-host)
64
+ for SQLite integration, legacy queue migration, and reset handling.
65
+
62
66
  ## Package entry points
63
67
 
64
68
  | Entry point | Intended use | Current contract status |
@@ -1,10 +1,14 @@
1
1
  import type { AUTO_MERGED, CANCELLED, MISSING_OR_ERROR, NOT_CONFLICTED } from "./shared.const.symbols.js";
2
+ import type { EntryTypeNotes, FilePathWithPrefix } from "./db.type.js";
2
3
  export type diff_result_leaf = {
3
4
  rev: string;
4
5
  data: string;
5
6
  ctime: number;
6
7
  mtime: number;
7
8
  deleted?: boolean;
9
+ /** The path recorded on this revision, when available. */
10
+ path?: FilePathWithPrefix;
11
+ datatype?: EntryTypeNotes;
8
12
  };
9
13
  export type dmp_result = Array<[number, string]>;
10
14
  export type diff_result = {
@@ -113,7 +113,7 @@ export declare function isRemediationModeActive(settings: Pick<ObsidianLiveSyncS
113
113
  export declare function determineType(path: string, data: string | string[] | Uint8Array | ArrayBuffer | Blob): "newnote" | "plain";
114
114
  export declare function isAnyNote(doc: DatabaseEntry): doc is NewEntry | PlainEntry;
115
115
  export declare function isLoadedEntry(doc: DatabaseEntry): doc is LoadedEntry;
116
- export declare function isDeletedEntry(doc: LoadedEntry): boolean;
116
+ export { isDeletedEntry } from "./utils.doc.js";
117
117
  export declare function createSavingEntryFromLoadedEntry(doc: LoadedEntry): SavingEntry;
118
118
  export declare function setAllItems<T>(set: Set<T>, items: T[]): Set<T>;
119
119
  export declare function escapeNewLineFromString(str: string): string;
@@ -1,3 +1,8 @@
1
+ import type { DatabaseEntry, LoadedEntry } from "./models/db.type.js";
2
+ /** Check the CouchDB tombstone marker on a raw revision. */
3
+ export declare function isTombstoneRevision(revision: Pick<DatabaseEntry, "_deleted">): boolean;
4
+ /** Check whether CouchDB marked the revision as a tombstone or LiveSync marked the file as deleted. */
5
+ export declare function isDeletedEntry(entry: Pick<LoadedEntry, "_deleted" | "deleted">): boolean;
1
6
  export declare function isErrorOf(ex: unknown, statusCode: number): boolean;
2
7
  /**
3
8
  * Checks if the error is effectively a 404 error from CouchDB or PouchDB.
@@ -1,3 +1,9 @@
1
+ function isTombstoneRevision(revision) {
2
+ return !!revision._deleted;
3
+ }
4
+ function isDeletedEntry(entry) {
5
+ return isTombstoneRevision(entry) || entry.deleted || false;
6
+ }
1
7
  function isErrorOf(ex, statusCode) {
2
8
  if (!ex || typeof ex !== "object") {
3
9
  throw new Error(`Expected an object error, but got ${typeof ex}`);
@@ -28,8 +34,10 @@ function tryGetFilePath(entry) {
28
34
  }
29
35
  export {
30
36
  isConflictError,
37
+ isDeletedEntry,
31
38
  isErrorOf,
32
39
  isNotFoundError,
40
+ isTombstoneRevision,
33
41
  isUnauthorizedError,
34
42
  tryGetFilePath
35
43
  };
@@ -204,9 +204,7 @@ function isAnyNote(doc) {
204
204
  function isLoadedEntry(doc) {
205
205
  return "type" in doc && (doc.type == "newnote" || doc.type == "plain") && "data" in doc;
206
206
  }
207
- function isDeletedEntry(doc) {
208
- return doc._deleted || doc.deleted || false;
209
- }
207
+ import { isDeletedEntry } from "./utils.doc.js";
210
208
  function createSavingEntryFromLoadedEntry(doc) {
211
209
  const data = readAsBlob(doc);
212
210
  const type = determineType(doc.path, data);
@@ -0,0 +1,8 @@
1
+ /** Check whether both revisions record the same case-preserving path under the configured normalisation. */
2
+ export declare function haveMatchingRevisionPaths(leftPath: string | undefined, rightPath: string | undefined, version?: number): boolean;
3
+ /** Check whether two recorded paths differ only in case under the configured normalisation. */
4
+ export declare function hasFilenameCaseConflict(leftPath: string | undefined, rightPath: string | undefined, version?: number): boolean;
5
+ /** Return the parent directory of a Vault path, or the empty string for the Vault root. */
6
+ export declare function getParentPath(path: string): string;
7
+ /** Check for a filename casing difference within the same normalised parent directory. */
8
+ export declare function hasSameParentFilenameCaseConflict(left: string | undefined, right: string | undefined, version?: number): boolean;
@@ -0,0 +1,26 @@
1
+ import { normalisePathForIdentity } from "../common/pathNormalization.js";
2
+ function haveMatchingRevisionPaths(leftPath, rightPath, version) {
3
+ return !!leftPath && !!rightPath && normalisePathForIdentity(leftPath, version) === normalisePathForIdentity(rightPath, version);
4
+ }
5
+ function hasFilenameCaseConflict(leftPath, rightPath, version) {
6
+ if (!leftPath || !rightPath) {
7
+ return false;
8
+ }
9
+ const left = normalisePathForIdentity(leftPath, version);
10
+ const right = normalisePathForIdentity(rightPath, version);
11
+ return left !== right && left.toLowerCase() === right.toLowerCase();
12
+ }
13
+ function getParentPath(path) {
14
+ const lastSeparator = path.lastIndexOf("/");
15
+ return lastSeparator < 0 ? "" : path.slice(0, lastSeparator);
16
+ }
17
+ function hasSameParentFilenameCaseConflict(left, right, version) {
18
+ if (!left || !right || !hasFilenameCaseConflict(left, right, version)) return false;
19
+ return normalisePathForIdentity(getParentPath(left), version) === normalisePathForIdentity(getParentPath(right), version);
20
+ }
21
+ export {
22
+ getParentPath,
23
+ hasFilenameCaseConflict,
24
+ hasSameParentFilenameCaseConflict,
25
+ haveMatchingRevisionPaths
26
+ };
@@ -1,3 +1,4 @@
1
1
  export { createConflictCheckQueue } from "./conflicts/conflictCheckQueue.js";
2
2
  export type { ConflictCheckQueue, ConflictCheckQueueOptions } from "./conflicts/conflictCheckQueue.js";
3
3
  export type { FilePathWithPrefix } from "./common/types.js";
4
+ export { haveMatchingRevisionPaths, hasFilenameCaseConflict, hasSameParentFilenameCaseConflict, } from "./conflicts/filenameCaseConflict.js";
package/dist/conflicts.js CHANGED
@@ -1,4 +1,12 @@
1
1
  import { createConflictCheckQueue } from "./conflicts/conflictCheckQueue.js";
2
+ import {
3
+ haveMatchingRevisionPaths,
4
+ hasFilenameCaseConflict,
5
+ hasSameParentFilenameCaseConflict
6
+ } from "./conflicts/filenameCaseConflict.js";
2
7
  export {
3
- createConflictCheckQueue
8
+ createConflictCheckQueue,
9
+ hasFilenameCaseConflict,
10
+ hasSameParentFilenameCaseConflict,
11
+ haveMatchingRevisionPaths
4
12
  };
@@ -9,6 +9,11 @@ export interface ContentReadFailure {
9
9
  /** Original runtime diagnostics, which must not be persisted or inspected to choose recovery. */
10
10
  cause: unknown;
11
11
  }
12
+ /** Restrict live-content matching to an observed, case-preserving filename. */
13
+ export interface LiveContentFilename {
14
+ path: FilePathWithPrefix;
15
+ normalizationVersion: number;
16
+ }
12
17
  export interface DatabaseFileAccess {
13
18
  /** Strict reads preserve ordinary absence but reject failed I/O or incomplete content. */
14
19
  readEntryMeta: DatabaseFileAccess["fetchEntryMeta"];
@@ -16,6 +21,11 @@ export interface DatabaseFileAccess {
16
21
  readEntry: DatabaseFileAccess["fetchEntry"];
17
22
  readConflictedRevs: DatabaseFileAccess["getConflictedRevs"];
18
23
  readLiveContentRevisions: DatabaseFileAccess["findLiveContentRevisions"];
24
+ /**
25
+ * Read the spelling stored on an exact revision of a known document, without loading Chunks.
26
+ * Missing revisions and unrecorded names return undefined. Other read failures reject.
27
+ */
28
+ readRevisionPath?(documentId: DocumentID, revision: string): Promise<string | undefined>;
19
29
  delete: (file: UXFileInfoStub | FilePathWithPrefix, rev?: string) => Promise<boolean>;
20
30
  store: (file: UXFileInfo, force?: boolean, skipCheck?: boolean) => Promise<boolean>;
21
31
  /**
@@ -57,12 +67,13 @@ export interface DatabaseFileAccess {
57
67
  * Return current, non-deleted leaf revisions whose decoded content matches the supplied bytes.
58
68
  * Include the winning and conflicting leaves, but never their ancestors. Read only locally
59
69
  * available Chunks, without requesting remote data or waiting for missing Chunks to arrive.
70
+ * When a filename is supplied, inspect only leaves with that recorded case-preserving path.
60
71
  *
61
72
  * A unique match can recover provenance; several matches avoid a duplicate write but leave
62
73
  * its origin ambiguous. An empty result means no match was confirmed. The strict read rejects
63
74
  * failed I/O; this compatibility facade returns no matches on failure. This read neither records provenance nor reserves a leaf for a later write.
64
75
  */
65
- findLiveContentRevisions: (file: UXFileInfoStub | FilePathWithPrefix, content: string | string[] | Blob | ArrayBuffer) => Promise<string[]>;
76
+ findLiveContentRevisions: (file: UXFileInfoStub | FilePathWithPrefix, content: string | string[] | Blob | ArrayBuffer, filename?: LiveContentFilename) => Promise<string[]>;
66
77
  fetch: (file: UXFileInfoStub | FilePathWithPrefix, rev?: string, waitForReady?: boolean, skipCheck?: boolean) => Promise<UXFileInfo | false>;
67
78
  fetchEntryFromMeta: (meta: MetaEntry, waitForReady?: boolean, skipCheck?: boolean, localOnly?: boolean) => Promise<LoadedEntry | false>;
68
79
  fetchEntryMeta: (file: UXFileInfoStub | FilePathWithPrefix, rev?: string, skipCheck?: boolean) => Promise<MetaEntry | false>;
@@ -23,6 +23,7 @@ class StoredFileReflectionProvenance {
23
23
  await this.store.delete(path);
24
24
  }
25
25
  async move(from, to) {
26
+ if (from === to) return;
26
27
  const record = await this.get(from);
27
28
  if (record) {
28
29
  await this.set(to, record);
@@ -8,4 +8,4 @@ export interface KeyValueDatabase {
8
8
  destroy(): Promise<void>;
9
9
  }
10
10
  /** Opens the key-value database owned by one service composition. */
11
- export type KeyValueDatabaseFactory = (databaseKey: string) => Promise<KeyValueDatabase>;
11
+ export type KeyValueDatabaseFactory<TDatabase extends KeyValueDatabase = KeyValueDatabase> = (databaseKey: string) => Promise<TDatabase>;
@@ -1,13 +1,14 @@
1
1
  import { type Diff } from "diff-match-patch";
2
2
  import { type EntryDoc, type FilePathWithPrefix, type diff_result_leaf, type LoadedEntry, type DIFF_CHECK_RESULT_AUTO } from "../common/types.js";
3
3
  import type { EntryManager } from "./EntryManager/EntryManager.js";
4
- import type { IPathService } from "../services/base/IService.js";
4
+ import type { IPathService, ISettingService } from "../services/base/IService.js";
5
5
  type AutoMergeOutcomeOK = {
6
6
  ok: DIFF_CHECK_RESULT_AUTO;
7
7
  };
8
8
  type AutoMergeCanBeDoneByDeletingRev = {
9
9
  result: string;
10
10
  conflictedRev: string;
11
+ path: FilePathWithPrefix;
11
12
  };
12
13
  type UserActionRequired = {
13
14
  leftRev: string;
@@ -17,20 +18,23 @@ type UserActionRequired = {
17
18
  };
18
19
  export type AutoMergeResult = Promise<AutoMergeOutcomeOK | AutoMergeCanBeDoneByDeletingRev | UserActionRequired>;
19
20
  export interface ConflictManagerOptions {
20
- entryManager: EntryManager;
21
+ entryManager: Pick<EntryManager, "getDBEntry" | "getConflictEntryMeta" | "getDBEntryFromMeta">;
21
22
  pathService: IPathService;
23
+ settingService: Pick<ISettingService, "currentSettings">;
22
24
  database: PouchDB.Database<EntryDoc>;
23
25
  }
24
26
  export declare class ConflictManager {
25
27
  options: ConflictManagerOptions;
26
28
  constructor(options: ConflictManagerOptions);
27
29
  get database(): PouchDB.Database<EntryDoc>;
30
+ private areRecordedRevisionPathsEqual;
28
31
  getConflictedDoc(path: FilePathWithPrefix, rev: string): Promise<false | diff_result_leaf>;
29
32
  mergeSensibly(path: FilePathWithPrefix, baseRev: string, currentRev: string, conflictedRev: string): Promise<Diff[] | false>;
30
33
  mergeObject(path: FilePathWithPrefix, baseRev: string, currentRev: string, conflictedRev: string): Promise<string | false>;
31
34
  tryAutoMergeSensibly(path: FilePathWithPrefix, test: LoadedEntry, conflicts: string[]): Promise<false | {
32
35
  result: string;
33
36
  conflictedRev: string;
37
+ path: FilePathWithPrefix;
34
38
  }>;
35
39
  tryAutoMerge(path: FilePathWithPrefix, enableMarkdownAutoMerge: boolean): AutoMergeResult;
36
40
  }
@@ -14,7 +14,8 @@ import {
14
14
  isSensibleMargeApplicable,
15
15
  isObjectMargeApplicable
16
16
  } from "../common/utils.js";
17
- import { isErrorOfMissingDoc } from "../pouchdb/utils_couchdb.js";
17
+ import { tryGetFilePath } from "../common/utils.doc.js";
18
+ import { haveMatchingRevisionPaths } from "../conflicts/filenameCaseConflict.js";
18
19
  function revisionGeneration(revision) {
19
20
  const generation = Number(revision.split("-", 1)[0]);
20
21
  return Number.isFinite(generation) ? generation : Number.MAX_SAFE_INTEGER;
@@ -30,6 +31,25 @@ function compareConflictCandidates(left, right) {
30
31
  if (left.revision > right.revision) return 1;
31
32
  return 0;
32
33
  }
34
+ function describeRevisionPathMismatch(currentPath, conflictedPath) {
35
+ const reason = currentPath && conflictedPath ? "the recorded paths differ" : "a recorded path is missing";
36
+ return `Skipping automatic merge because ${reason} (current=${JSON.stringify(currentPath)}, conflicted=${JSON.stringify(conflictedPath)}).`;
37
+ }
38
+ function createDiffResultLeafFromLoadedEntry(doc, { rev, recordedPath }) {
39
+ let data = getDocData(doc.data);
40
+ if (doc.datatype === "newnote") {
41
+ data = readString(new Uint8Array(decodeBinary(doc.data)));
42
+ }
43
+ return {
44
+ deleted: doc.deleted || doc._deleted,
45
+ ctime: doc.ctime,
46
+ mtime: doc.mtime,
47
+ rev,
48
+ data,
49
+ datatype: doc.datatype,
50
+ ...recordedPath ? { path: recordedPath } : {}
51
+ };
52
+ }
33
53
  class ConflictManager {
34
54
  options;
35
55
  constructor(options) {
@@ -38,28 +58,24 @@ class ConflictManager {
38
58
  get database() {
39
59
  return this.options.database;
40
60
  }
61
+ areRecordedRevisionPathsEqual(leftRecordedPath, rightRecordedPath) {
62
+ const { pathNormalizationVersion } = this.options.settingService.currentSettings();
63
+ return haveMatchingRevisionPaths(leftRecordedPath, rightRecordedPath, pathNormalizationVersion);
64
+ }
41
65
  async getConflictedDoc(path, rev) {
42
66
  try {
43
- const doc = await this.options.entryManager.getDBEntry(path, { rev }, false, true, true);
44
- if (doc === false) return false;
45
- let data = getDocData(doc.data);
46
- if (doc.datatype == "newnote") {
47
- data = readString(new Uint8Array(decodeBinary(doc.data)));
48
- } else if (doc.datatype == "plain") {
67
+ const entry = await this.options.entryManager.getConflictEntryMeta(path, { rev });
68
+ if (!entry) {
69
+ return false;
49
70
  }
50
- return {
51
- deleted: doc.deleted || doc._deleted,
52
- ctime: doc.ctime,
53
- mtime: doc.mtime,
54
- rev,
55
- data
56
- };
57
- } catch (ex) {
58
- if (isErrorOfMissingDoc(ex)) {
71
+ const doc = await this.options.entryManager.getDBEntryFromMeta(entry.metadata);
72
+ if (!doc) {
59
73
  return false;
60
74
  }
75
+ return createDiffResultLeafFromLoadedEntry(doc, { rev, recordedPath: entry.path });
76
+ } catch {
77
+ return false;
61
78
  }
62
- return false;
63
79
  }
64
80
  async mergeSensibly(path, baseRev, currentRev, conflictedRev) {
65
81
  const baseLeaf = await this.getConflictedDoc(path, baseRev);
@@ -72,6 +88,10 @@ class ConflictManager {
72
88
  if (leftLeaf.deleted || rightLeaf.deleted) {
73
89
  return false;
74
90
  }
91
+ if (!this.areRecordedRevisionPathsEqual(leftLeaf.path, rightLeaf.path)) {
92
+ Logger(describeRevisionPathMismatch(leftLeaf.path, rightLeaf.path), LOG_LEVEL_VERBOSE);
93
+ return false;
94
+ }
75
95
  const dmp = new diff_match_patch();
76
96
  const mapLeft = dmp.diff_linesToChars_(baseLeaf.data, leftLeaf.data);
77
97
  const diffLeftSrc = dmp.diff_main(mapLeft.chars1, mapLeft.chars2, false);
@@ -235,6 +255,10 @@ class ConflictManager {
235
255
  Logger(`Either is deleted`, LOG_LEVEL_VERBOSE);
236
256
  return false;
237
257
  }
258
+ if (!this.areRecordedRevisionPathsEqual(leftLeaf.path, rightLeaf.path)) {
259
+ Logger(describeRevisionPathMismatch(leftLeaf.path, rightLeaf.path), LOG_LEVEL_VERBOSE);
260
+ return false;
261
+ }
238
262
  const baseObj = { data: tryParseJSON(baseLeaf.data, {}) };
239
263
  const leftObj = { data: tryParseJSON(leftLeaf.data, {}) };
240
264
  const rightObj = { data: tryParseJSON(rightLeaf.data, {}) };
@@ -274,12 +298,27 @@ class ConflictManager {
274
298
  async tryAutoMergeSensibly(path, test, conflicts) {
275
299
  const conflictedRev = conflicts[0];
276
300
  let commonBase = "";
301
+ let mergePath;
302
+ const documentId = test._id;
277
303
  try {
278
- const documentId = await this.options.pathService.path2id(path);
279
304
  const [currentBranch, conflictedBranch] = await Promise.all([
280
305
  this.database.get(documentId, { rev: test._rev, revs_info: true }),
281
306
  this.database.get(documentId, { rev: conflictedRev, revs_info: true })
282
307
  ]);
308
+ const currentPath = tryGetFilePath(currentBranch);
309
+ if (!currentPath) {
310
+ Logger(
311
+ `Skipping automatic merge for ${JSON.stringify(path)} because the current revision has no recorded path.`,
312
+ LOG_LEVEL_VERBOSE
313
+ );
314
+ return false;
315
+ }
316
+ const conflictedPath = tryGetFilePath(conflictedBranch);
317
+ if (!this.areRecordedRevisionPathsEqual(currentPath, conflictedPath)) {
318
+ Logger(describeRevisionPathMismatch(currentPath, conflictedPath), LOG_LEVEL_VERBOSE);
319
+ return false;
320
+ }
321
+ mergePath = currentPath;
283
322
  const currentAvailable = new Set(
284
323
  (currentBranch._revs_info || []).filter((revision) => revision.status === "available").map((revision) => revision.rev)
285
324
  );
@@ -309,7 +348,10 @@ class ConflictManager {
309
348
  }
310
349
  }
311
350
  if (p !== void 0) {
312
- return { result: p, conflictedRev };
351
+ if (mergePath !== path && await this.options.pathService.path2id(mergePath) !== documentId) {
352
+ mergePath = path;
353
+ }
354
+ return { result: p, conflictedRev, path: mergePath };
313
355
  }
314
356
  }
315
357
  return false;
@@ -338,8 +380,17 @@ class ConflictManager {
338
380
  const conflicts = conflictCandidates.map(({ revision }) => revision);
339
381
  const leftLeaf = await this.getConflictedDoc(path, test._rev);
340
382
  const rightLeaf = conflictCandidates[0].leaf;
341
- if (leftLeaf !== false && rightLeaf !== false && leftLeaf.data == rightLeaf.data && leftLeaf.deleted == rightLeaf.deleted) {
342
- return { leftRev: test._rev, rightRev: conflicts[0], leftLeaf, rightLeaf };
383
+ const conflict = { leftRev: test._rev, rightRev: conflicts[0], leftLeaf, rightLeaf };
384
+ if (!leftLeaf || !rightLeaf) {
385
+ return conflict;
386
+ }
387
+ if (!this.areRecordedRevisionPathsEqual(leftLeaf.path, rightLeaf.path)) {
388
+ Logger(describeRevisionPathMismatch(leftLeaf.path, rightLeaf.path), LOG_LEVEL_VERBOSE);
389
+ return conflict;
390
+ }
391
+ const sameContentAndDeletionState = leftLeaf.data === rightLeaf.data && leftLeaf.deleted === rightLeaf.deleted;
392
+ if (sameContentAndDeletionState) {
393
+ return conflict;
343
394
  }
344
395
  if ((isSensibleMargeApplicable(path) || isObjectMargeApplicable(path)) && enableMarkdownAutoMerge) {
345
396
  const autoMergeResult = await this.tryAutoMergeSensibly(path, test, conflicts);
@@ -347,7 +398,7 @@ class ConflictManager {
347
398
  return autoMergeResult;
348
399
  }
349
400
  }
350
- return { leftRev: test._rev, rightRev: conflicts[0], leftLeaf, rightLeaf };
401
+ return conflict;
351
402
  }
352
403
  }
353
404
  export {
@@ -37,6 +37,11 @@ export declare class EntryManager {
37
37
  isTargetFile(filenameSrc: string, internalFileEvent?: boolean): boolean;
38
38
  prepareChunk(piece: string): Promise<GeneratedChunk>;
39
39
  getDBEntryMeta(path: FilePathWithPrefix | FilePath, opt?: PouchDB.Core.GetOptions, includeDeleted?: boolean): Promise<false | LoadedEntry>;
40
+ /** Read a conflict candidate's metadata and its recorded path, including deleted revisions. */
41
+ getConflictEntryMeta(path: FilePathWithPrefix, opt: PouchDB.Core.GetOptions): Promise<false | {
42
+ metadata: LoadedEntry & PouchDB.Core.GetMeta;
43
+ path: FilePathWithPrefix | undefined;
44
+ }>;
40
45
  getDBEntry(path: FilePathWithPrefix | FilePath, opt?: PouchDB.Core.GetOptions, dump?: boolean, waitForReady?: boolean, includeDeleted?: boolean, localOnly?: boolean): Promise<false | LoadedEntry>;
41
46
  getDBEntryFromMeta(meta: LoadedEntry | MetaEntry, dump?: boolean, waitForReady?: boolean, localOnly?: boolean): Promise<false | LoadedEntry>;
42
47
  deleteDBEntry(path: FilePathWithPrefix | FilePath, opt?: PouchDB.Core.GetOptions): Promise<boolean>;
@@ -8,6 +8,7 @@ import {
8
8
  getDBEntryByPath,
9
9
  getDBEntryFromMeta,
10
10
  getDBEntryMetaByPath,
11
+ getConflictEntryMetaByPath,
11
12
  isTargetFile,
12
13
  prepareChunk,
13
14
  putDBEntry,
@@ -65,6 +66,10 @@ class EntryManager {
65
66
  async getDBEntryMeta(path, opt, includeDeleted = false) {
66
67
  return await getDBEntryMetaByPath(this.serviceHost, this, path, opt, includeDeleted);
67
68
  }
69
+ /** Read a conflict candidate's metadata and its recorded path, including deleted revisions. */
70
+ async getConflictEntryMeta(path, opt) {
71
+ return await getConflictEntryMetaByPath(this.serviceHost, this, path, opt);
72
+ }
68
73
  async getDBEntry(path, opt, dump = false, waitForReady = true, includeDeleted = false, localOnly = false) {
69
74
  return await getDBEntryByPath(this.serviceHost, this, path, opt, dump, waitForReady, includeDeleted, localOnly);
70
75
  }
@@ -33,7 +33,11 @@ export declare function putDBEntryWithLiveBaseRevision(host: NecessaryServicesIn
33
33
  export declare function putDBEntryAsIndependentRoot(host: NecessaryServicesInterfaces<"path" | "setting", never>, managers: NecessaryManagers<"localDatabase" | "chunkManager" | "hashManager" | "splitter">, note: SavingEntry): Promise<false | PouchDB.Core.Response>;
34
34
  export declare function isTargetFile(host: NecessaryServicesInterfaces<"setting", never>, filenameSrc: string, internalFileEvent?: boolean): boolean;
35
35
  export declare function prepareChunk({ chunkManager, hashManager }: NecessaryManagers<"chunkManager" | "hashManager">, piece: string): Promise<GeneratedChunk>;
36
- export declare function getDBEntryMetaByPath(host: NecessaryServicesInterfaces<"path" | "setting", never>, { localDatabase, readScope }: NecessaryManagers<"localDatabase">, path: FilePathWithPrefix | FilePath, opt?: PouchDB.Core.GetOptions, includeDeleted?: boolean): Promise<false | LoadedEntry>;
36
+ export declare function getDBEntryMetaByPath(host: NecessaryServicesInterfaces<"path" | "setting", never>, managers: NecessaryManagers<"localDatabase">, path: FilePathWithPrefix | FilePath, opt?: PouchDB.Core.GetOptions, includeDeleted?: boolean): Promise<false | LoadedEntry>;
37
+ export declare function getConflictEntryMetaByPath(host: NecessaryServicesInterfaces<"path" | "setting", never>, managers: NecessaryManagers<"localDatabase">, path: FilePathWithPrefix, opt: PouchDB.Core.GetOptions): Promise<false | {
38
+ metadata: LoadedEntry & PouchDB.Core.GetMeta;
39
+ path: FilePathWithPrefix | undefined;
40
+ }>;
37
41
  export declare function isLegacyNote(meta: LoadedEntry | MetaEntry): boolean;
38
42
  export declare function canUseOnDemandChunking(settings: ObsidianLiveSyncSettings): boolean;
39
43
  /**
@@ -6,14 +6,63 @@ import {
6
6
  } from "../../common/types.js";
7
7
  import { serialized } from "octagonal-wheels/concurrency/lock";
8
8
  import { createTextBlob, getFileRegExp, isTextBlob } from "../../common/utils.js";
9
+ import { tryGetFilePath } from "../../common/utils.doc.js";
9
10
  import { compatGlobal } from "../../common/coreEnvFunctions.js";
10
11
  import { isErrorOfMissingDoc } from "../../pouchdb/utils_couchdb.js";
11
12
  import { stripAllPrefixes } from "../../string_and_binary/path.js";
12
13
  import { ICHeader, ICXHeader, PSCHeader } from "../../common/models/fileaccess.const.js";
13
14
  import { ContentReadError } from "../../common/LSError.js";
15
+ import { isOutOfBandCancellableIterator } from "../../worker/outOfBandCancelIterator.js";
16
+ const MAX_WRITE_SIZE = 2048e3;
14
17
  function readFromDatabase(readScope, operation) {
15
18
  return readScope ? readScope.run(operation) : operation();
16
19
  }
20
+ function createChunkWritePipeline(pieces, flushBufferedChunks, onWriteError) {
21
+ let pendingWrite;
22
+ let writeFailure = false;
23
+ let closing;
24
+ function closePieces() {
25
+ closing ??= (async () => {
26
+ try {
27
+ await pieces.return?.();
28
+ } catch {
29
+ }
30
+ })();
31
+ return closing;
32
+ }
33
+ function failWrite(rejected, error) {
34
+ if (!writeFailure) {
35
+ writeFailure = true;
36
+ if (rejected) {
37
+ onWriteError(error);
38
+ }
39
+ }
40
+ void closePieces();
41
+ return false;
42
+ }
43
+ async function waitForWrite() {
44
+ if (pendingWrite !== void 0) {
45
+ const ok = await pendingWrite;
46
+ pendingWrite = void 0;
47
+ return ok && !writeFailure;
48
+ }
49
+ return !writeFailure;
50
+ }
51
+ async function startWrite() {
52
+ if (pendingWrite !== void 0 && !await waitForWrite()) {
53
+ return false;
54
+ }
55
+ if (writeFailure) {
56
+ return false;
57
+ }
58
+ pendingWrite = flushBufferedChunks().then(
59
+ (ok) => ok ? true : failWrite(false),
60
+ (error) => failWrite(true, error)
61
+ );
62
+ return true;
63
+ }
64
+ return { startWrite, waitForWrite, closePieces, failed: () => writeFailure };
65
+ }
17
66
  async function createChunks(managers, dispFilename, note) {
18
67
  const { chunkManager, splitter, log = Logger } = managers;
19
68
  let bufferedChunk = [];
@@ -25,7 +74,6 @@ async function createChunks(managers, dispFilename, note) {
25
74
  let duplicatedCount = 0;
26
75
  let totalWritingCount = 0;
27
76
  let createChunkCount = 0;
28
- const MAX_WRITE_SIZE = 1e3 * 1024 * 2;
29
77
  const chunks = [];
30
78
  let writeChars = 0;
31
79
  const flushBufferedChunks = async () => {
@@ -56,9 +104,15 @@ async function createChunks(managers, dispFilename, note) {
56
104
  log(`Flushed ${writeBuf.length} (${writeChars}) chunks for ${dispFilename}`, LOG_LEVEL_VERBOSE);
57
105
  return true;
58
106
  };
107
+ const pieces = await splitter.splitContent(note);
108
+ const pipeline = isOutOfBandCancellableIterator(pieces) ? createChunkWritePipeline(pieces, flushBufferedChunks, (error) => {
109
+ log(`Error processing pieces for ${dispFilename}`);
110
+ log(error, LOG_LEVEL_VERBOSE);
111
+ }) : void 0;
59
112
  const flushIfNeeded = async () => {
60
113
  if (bufferedSize > MAX_WRITE_SIZE) {
61
- if (!await flushBufferedChunks()) {
114
+ const ok = pipeline ? await pipeline.startWrite() : await flushBufferedChunks();
115
+ if (!ok) {
62
116
  log(`Failed to flush buffered chunks for ${dispFilename}`, LOG_LEVEL_NOTICE);
63
117
  return false;
64
118
  }
@@ -76,28 +130,47 @@ async function createChunks(managers, dispFilename, note) {
76
130
  bufferedSize += chunk.data.length;
77
131
  return await flushIfNeeded();
78
132
  };
79
- const pieces = await splitter.splitContent(note);
80
133
  let totalChunkCount = 0;
134
+ let complete = false;
81
135
  try {
82
136
  for await (const piece of pieces) {
137
+ if (pipeline?.failed()) {
138
+ break;
139
+ }
83
140
  totalChunkCount++;
84
141
  if (piece.length === 0) {
85
142
  continue;
86
143
  }
87
144
  createChunkCount++;
88
145
  const chunk = await prepareChunk(managers, piece);
146
+ if (pipeline?.failed()) {
147
+ break;
148
+ }
89
149
  cachedCount += chunk.isNew ? 0 : 1;
90
150
  newCount += chunk.isNew ? 1 : 0;
91
151
  if (!await addBuffer(chunk.id, chunk.piece)) {
92
152
  return false;
93
153
  }
94
154
  }
155
+ if (pipeline && (!await pipeline.startWrite() || !await pipeline.waitForWrite())) {
156
+ return false;
157
+ }
158
+ complete = true;
95
159
  } catch (ex) {
96
160
  log(`Error processing pieces for ${dispFilename}`);
97
161
  log(ex, LOG_LEVEL_VERBOSE);
98
162
  return false;
163
+ } finally {
164
+ if (pipeline) {
165
+ if (!complete) {
166
+ bufferedChunk = [];
167
+ bufferedSize = 0;
168
+ await pipeline.closePieces();
169
+ }
170
+ await pipeline.waitForWrite();
171
+ }
99
172
  }
100
- if (!await flushBufferedChunks()) {
173
+ if (!pipeline && !await flushBufferedChunks()) {
101
174
  return false;
102
175
  }
103
176
  const dataSize = note.data.size;
@@ -248,7 +321,19 @@ async function prepareChunk({ chunkManager, hashManager }, piece) {
248
321
  const chunkId = await hashManager.computeHash(piece);
249
322
  return { isNew: true, id: `${IDPrefixes.Chunk}${chunkId}`, piece };
250
323
  }
251
- async function getDBEntryMetaByPath(host, { localDatabase, readScope }, path, opt, includeDeleted = false) {
324
+ async function getDBEntryMetaByPath(host, managers, path, opt, includeDeleted = false) {
325
+ const result = await readDBEntryMeta(host, managers, path, opt, includeDeleted);
326
+ return result && result.metadata;
327
+ }
328
+ async function getConflictEntryMetaByPath(host, managers, path, opt) {
329
+ const result = await readDBEntryMeta(host, managers, path, opt, true);
330
+ if (!result) {
331
+ return false;
332
+ }
333
+ const recordedPath = tryGetFilePath(result.document);
334
+ return { metadata: result.metadata, path: recordedPath || void 0 };
335
+ }
336
+ async function readDBEntryMeta(host, { localDatabase, readScope }, path, opt, includeDeleted = false) {
252
337
  if (!isTargetFile(host, path)) {
253
338
  return false;
254
339
  }
@@ -311,7 +396,7 @@ async function getDBEntryMetaByPath(host, { localDatabase, readScope }, path, op
311
396
  type,
312
397
  eden: "eden" in obj ? obj.eden : {}
313
398
  };
314
- return doc;
399
+ return { metadata: doc, document: obj };
315
400
  }
316
401
  } catch (ex) {
317
402
  if (isErrorOfMissingDoc(ex)) {
@@ -604,6 +689,7 @@ export {
604
689
  computeChunkRetrievalMethod,
605
690
  createChunks,
606
691
  deleteDBEntryByPath,
692
+ getConflictEntryMetaByPath,
607
693
  getDBEntryByPath,
608
694
  getDBEntryFromMeta,
609
695
  getDBEntryMetaByPath,
@@ -97,7 +97,8 @@ class LiveSyncManagers {
97
97
  const conflictManager = new ConflictManager({
98
98
  entryManager,
99
99
  database,
100
- pathService: this._pathService
100
+ pathService: this._pathService,
101
+ settingService: this.options.settingService
101
102
  });
102
103
  this.log("LiveSync Managers have been created");
103
104
  return {