@vrtmrz/livesync-commonlib 0.4.3 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/README.md +2 -2
  2. package/dist/common/LSError.d.ts +13 -0
  3. package/dist/common/LSError.js +19 -1
  4. package/dist/diagnostics/local.d.ts +7 -2
  5. package/dist/interfaces/DatabaseFileAccess.d.ts +20 -4
  6. package/dist/interfaces/FileHandler.d.ts +67 -1
  7. package/dist/interfaces/FileHandler.js +16 -0
  8. package/dist/interfaces/StorageAccess.d.ts +8 -2
  9. package/dist/interfaces/StorageEventManager.d.ts +7 -0
  10. package/dist/managers/ChunkFetcher.d.ts +16 -0
  11. package/dist/managers/ChunkFetcher.js +190 -112
  12. package/dist/managers/EntryManager/EntryManager.d.ts +7 -0
  13. package/dist/managers/EntryManager/EntryManager.js +6 -0
  14. package/dist/managers/EntryManager/EntryManagerImpls.d.ts +9 -5
  15. package/dist/managers/EntryManager/EntryManagerImpls.js +103 -76
  16. package/dist/managers/LayeredChunkManager/ArrivalWaitLayer.d.ts +7 -3
  17. package/dist/managers/LayeredChunkManager/ArrivalWaitLayer.js +83 -16
  18. package/dist/managers/LayeredChunkManager/DatabaseReadLayer.d.ts +3 -2
  19. package/dist/managers/LayeredChunkManager/DatabaseReadLayer.js +38 -36
  20. package/dist/managers/LayeredChunkManager/types.d.ts +15 -1
  21. package/dist/managers/LayeredChunkManager.d.ts +4 -0
  22. package/dist/managers/LayeredChunkManager.js +19 -6
  23. package/dist/managers/LiveSyncManagers.d.ts +2 -0
  24. package/dist/managers/LiveSyncManagers.js +6 -0
  25. package/dist/managers/StorageEventManager.d.ts +22 -0
  26. package/dist/managers/StorageEventManager.js +48 -1
  27. package/dist/platform/FilePathIndex.d.ts +110 -0
  28. package/dist/platform/FilePathIndex.js +146 -0
  29. package/dist/pouchdb/LiveSyncLocalDB.d.ts +32 -0
  30. package/dist/pouchdb/LiveSyncLocalDB.js +72 -18
  31. package/dist/pouchdb/LocalDatabaseReadScope.d.ts +24 -0
  32. package/dist/pouchdb/LocalDatabaseReadScope.js +62 -0
  33. package/dist/pouchdb/pathIdentityCompatibility.d.ts +6 -2
  34. package/dist/pouchdb/pathIdentityCompatibility.js +15 -10
  35. package/dist/replication/contentRead.d.ts +3 -0
  36. package/dist/replication/contentRead.js +4 -0
  37. package/dist/replication/couchdb/LiveSyncReplicator.d.ts +8 -1
  38. package/dist/replication/couchdb/LiveSyncReplicator.js +187 -119
  39. package/dist/replication/index.d.ts +5 -1
  40. package/dist/replication/index.js +18 -1
  41. package/dist/replication/trystero/LiveSyncTrysteroReplicator.d.ts +3 -3
  42. package/dist/replication/trystero/P2PAutomationCoordinator.d.ts +1 -1
  43. package/dist/replication/trystero/P2PReplicationWire.d.ts +1 -1
  44. package/dist/replication/trystero/TrysteroReplicator/changeRelay.d.ts +133 -0
  45. package/dist/replication/trystero/TrysteroReplicator/changeRelay.js +176 -0
  46. package/dist/replication/trystero/TrysteroReplicator/configurationExchange.d.ts +55 -0
  47. package/dist/replication/trystero/TrysteroReplicator/configurationExchange.js +99 -0
  48. package/dist/replication/trystero/TrysteroReplicator/configuredTargets.d.ts +83 -0
  49. package/dist/replication/trystero/TrysteroReplicator/configuredTargets.js +121 -0
  50. package/dist/replication/trystero/TrysteroReplicator/peerAgreement.d.ts +75 -0
  51. package/dist/replication/trystero/TrysteroReplicator/peerAgreement.js +131 -0
  52. package/dist/replication/trystero/TrysteroReplicator/progress.d.ts +57 -0
  53. package/dist/replication/trystero/TrysteroReplicator/progress.js +84 -0
  54. package/dist/replication/trystero/TrysteroReplicator/relayControl.d.ts +20 -0
  55. package/dist/replication/trystero/TrysteroReplicator/relayControl.js +25 -0
  56. package/dist/replication/trystero/TrysteroReplicator/transfers.d.ts +125 -0
  57. package/dist/replication/trystero/TrysteroReplicator/transfers.js +278 -0
  58. package/dist/replication/trystero/TrysteroReplicator.d.ts +65 -483
  59. package/dist/replication/trystero/TrysteroReplicator.js +240 -673
  60. package/dist/replication/trystero/TrysteroReplicatorP2PClient.d.ts +19 -6
  61. package/dist/replication/trystero/TrysteroReplicatorP2PClient.js +29 -25
  62. package/dist/replication/trystero/TrysteroReplicatorP2PServer/peerAdmission.d.ts +66 -0
  63. package/dist/replication/trystero/TrysteroReplicatorP2PServer/peerAdmission.js +142 -0
  64. package/dist/replication/trystero/TrysteroReplicatorP2PServer.d.ts +19 -16
  65. package/dist/replication/trystero/TrysteroReplicatorP2PServer.js +33 -93
  66. package/dist/replication/trystero/p2pReplicationDiagnostics.d.ts +1 -1
  67. package/dist/replication/trystero/p2pReplicationProgress.d.ts +2 -11
  68. package/dist/replication/trystero/replicationTypes.d.ts +88 -0
  69. package/dist/replication/trystero/replicationTypes.js +0 -0
  70. package/dist/replication/trystero/rpcSessionProvider.d.ts +13 -0
  71. package/dist/replication/trystero/rpcSessionProvider.js +0 -0
  72. package/dist/rpc/RpcRoom/pendingInvocations.d.ts +141 -0
  73. package/dist/rpc/RpcRoom/pendingInvocations.js +225 -0
  74. package/dist/rpc/RpcRoom.d.ts +9 -4
  75. package/dist/rpc/RpcRoom.js +73 -118
  76. package/dist/rpc/RpcSession.d.ts +6 -0
  77. package/dist/rpc/RpcSession.js +11 -0
  78. package/dist/rpc/types.d.ts +2 -0
  79. package/dist/serviceFeatures/offlineScanner/files.d.ts +1 -1
  80. package/dist/serviceFeatures/offlineScanner/files.js +27 -7
  81. package/dist/serviceFeatures/offlineScanner/scan.d.ts +5 -1
  82. package/dist/serviceFeatures/offlineScanner/scan.js +2 -1
  83. package/dist/serviceFeatures/offlineScanner.d.ts +1 -1
  84. package/dist/serviceFeatures/offlineScanner.js +10 -2
  85. package/dist/serviceFeatures/targetFilter.d.ts +1 -1
  86. package/dist/serviceFeatures/targetFilter.js +8 -38
  87. package/dist/serviceModules/FileAccessBase.d.ts +4 -0
  88. package/dist/serviceModules/FileAccessBase.js +10 -0
  89. package/dist/serviceModules/Rebuilder.js +1 -1
  90. package/dist/serviceModules/ServiceDatabaseFileAccessBase.d.ts +13 -0
  91. package/dist/serviceModules/ServiceDatabaseFileAccessBase.js +190 -123
  92. package/dist/serviceModules/ServiceFileAccessBase/fileNames.d.ts +54 -0
  93. package/dist/serviceModules/ServiceFileAccessBase/fileNames.js +57 -0
  94. package/dist/serviceModules/ServiceFileAccessBase.d.ts +5 -1
  95. package/dist/serviceModules/ServiceFileAccessBase.js +18 -3
  96. package/dist/serviceModules/ServiceFileHandlerBase/deletion.js +17 -7
  97. package/dist/serviceModules/ServiceFileHandlerBase/events.d.ts +3 -2
  98. package/dist/serviceModules/ServiceFileHandlerBase/events.js +9 -9
  99. package/dist/serviceModules/ServiceFileHandlerBase/protection.js +24 -9
  100. package/dist/serviceModules/ServiceFileHandlerBase/provenance.d.ts +10 -0
  101. package/dist/serviceModules/ServiceFileHandlerBase/provenance.js +28 -4
  102. package/dist/serviceModules/ServiceFileHandlerBase/reflection.d.ts +11 -5
  103. package/dist/serviceModules/ServiceFileHandlerBase/reflection.js +144 -58
  104. package/dist/serviceModules/ServiceFileHandlerBase/saving.js +16 -2
  105. package/dist/serviceModules/ServiceFileHandlerBase/scanning.js +1 -0
  106. package/dist/serviceModules/ServiceFileHandlerBase.d.ts +7 -2
  107. package/dist/serviceModules/ServiceFileHandlerBase.js +13 -4
  108. package/dist/serviceModules/adapters/IFileSystemAdapter.d.ts +3 -0
  109. package/dist/services/base/ControlService.js +1 -5
  110. package/dist/services/base/DatabaseEventService.d.ts +3 -0
  111. package/dist/services/base/DatabaseEventService.js +3 -0
  112. package/dist/services/base/DatabaseService.d.ts +15 -0
  113. package/dist/services/base/DatabaseService.js +85 -4
  114. package/dist/services/base/IService.d.ts +18 -1
  115. package/dist/services/base/KeyValueDBService.d.ts +5 -4
  116. package/dist/services/base/KeyValueDBService.js +46 -48
  117. package/dist/services/base/ReplicationService.d.ts +3 -1
  118. package/dist/services/base/ReplicationService.js +3 -1
  119. package/dist/services/base/VaultScanResult.d.ts +5 -0
  120. package/dist/services/lib/HandlerUtils.d.ts +40 -5
  121. package/dist/services/lib/HandlerUtils.js +52 -4
  122. package/dist/storage.d.ts +2 -0
  123. package/dist/storage.js +2 -0
  124. package/docs/development.md +111 -0
  125. package/docs/offline-scanner.md +46 -0
  126. package/docs/p2p-transport-lifecycle.md +24 -0
  127. package/docs/platform-storage.md +22 -0
  128. package/docs/releasing.md +48 -0
  129. package/docs/settings-lifecycle.md +4 -2
  130. package/package.json +1 -1
@@ -123,36 +123,36 @@ async function planRestoredRename(ctx, newPath, oldPath, isSameDocument) {
123
123
  if (isSameDocument) return await planSameDocumentRename(ctx, newPath, oldPath);
124
124
  return await planCrossDocumentRename(ctx, newPath, oldPath);
125
125
  }
126
- async function processReplicatedDocument(ctx, entry) {
126
+ async function processReplicatedDocument(ctx, entry, operation) {
127
127
  return await withFileEventPaths(ctx, [ctx.host.getPath(entry)], async () => {
128
128
  if (!await ctx.vault.isTargetFile(entry.path)) {
129
129
  ctx.host.log(`File ${entry.path} is not the target file`, LOG_LEVEL_VERBOSE);
130
- return false;
130
+ return { status: "policy" };
131
131
  }
132
132
  if (ctx.vault.isFileSizeTooLarge(entry.size)) {
133
133
  ctx.host.log(`File ${entry.path} is too large (on database) to be processed`, LOG_LEVEL_VERBOSE);
134
- return false;
134
+ return { status: "policy" };
135
135
  }
136
136
  if (shouldBeIgnored(entry.path)) {
137
137
  ctx.host.log(`File ${entry.path} should be ignored`, LOG_LEVEL_VERBOSE);
138
- return false;
138
+ return { status: "policy" };
139
139
  }
140
140
  const path = ctx.host.getPath(entry);
141
141
  const targetFile = await ctx.host.storage().getStub(ctx.host.getPathWithoutPrefix(entry));
142
142
  if (isFolderInfo(targetFile)) {
143
143
  ctx.host.log(`${path} is already exist as the folder`);
144
- return true;
144
+ return { status: "policy" };
145
145
  } else {
146
146
  if (targetFile && ctx.vault.isFileSizeTooLarge(targetFile.stat.size)) {
147
147
  ctx.host.log(`File ${targetFile.path} is too large (on storage) to be processed`, LOG_LEVEL_VERBOSE);
148
- return false;
148
+ return { status: "policy" };
149
149
  }
150
150
  ctx.host.log(
151
151
  `Processing ${path} (${entry._id.substring(0, 8)} :${entry._rev?.substring(0, 5)}) : Started...`,
152
152
  LOG_LEVEL_VERBOSE
153
153
  );
154
154
  ctx.events.emitEvent(EVENT_CONFLICT_CANCELLED, path);
155
- const ret = await dbToStorageCore(ctx, entry, targetFile);
155
+ const ret = await dbToStorageCore(ctx, entry, targetFile, void 0, operation);
156
156
  ctx.host.log(`Processing ${path} (${entry._id.substring(0, 8)} :${entry._rev?.substring(0, 5)}) : Done`);
157
157
  return ret;
158
158
  }
@@ -163,7 +163,7 @@ async function planSameDocumentRename(ctx, newPath, oldPath) {
163
163
  if (!currentTarget || !await isCurrentFileSelected(ctx, currentTarget)) {
164
164
  return { kind: "none" };
165
165
  }
166
- const entry = await ctx.host.db().fetchEntryMeta(newPath, void 0, true);
166
+ const entry = await ctx.host.db().readEntryMeta(newPath, void 0, true);
167
167
  if (entry && !entry.deleted && !entry._deleted && ctx.host.storage().normalisePath(ctx.host.getPath(entry)) === ctx.host.storage().normalisePath(newPath)) {
168
168
  return { kind: "store", file: currentTarget };
169
169
  }
@@ -187,7 +187,7 @@ async function planCrossDocumentRename(ctx, newPath, oldPath) {
187
187
  if (!sourceWasInspected || currentSourceItem !== null || !await canApplyRestoredDeletion(ctx, oldPath)) {
188
188
  return { kind: "store", file: currentTarget, complete: sourceWasInspected };
189
189
  }
190
- const sourceEntry = await ctx.host.db().fetchEntryMeta(oldPath, void 0, true);
190
+ const sourceEntry = await ctx.host.db().readEntryMeta(oldPath, void 0, true);
191
191
  if (!sourceEntry || sourceEntry.deleted || sourceEntry._deleted) {
192
192
  return { kind: "store", file: currentTarget };
193
193
  }
@@ -1,3 +1,4 @@
1
+ import { ContentReadError } from "../../common/LSError.js";
1
2
  import {
2
3
  readProvenanceSnapshot,
3
4
  currentStorageSnapshotMatches,
@@ -19,14 +20,25 @@ async function preserveUnsyncedStorageAsConflict(ctx, path, existDoc, incomingEn
19
20
  if (!incomingEntry._rev) {
20
21
  return { preserved: false };
21
22
  }
22
- const classification = await classifyStorageContent(
23
- ctx,
24
- readFile,
25
- incomingEntry,
26
- void 0,
27
- observedProvenance,
28
- incomingContent ? { _rev: incomingEntry._rev, data: incomingContent } : void 0
29
- );
23
+ let classification;
24
+ let unavailableRead;
25
+ try {
26
+ classification = await classifyStorageContent(
27
+ ctx,
28
+ readFile,
29
+ incomingEntry,
30
+ void 0,
31
+ observedProvenance,
32
+ incomingContent ? { _rev: incomingEntry._rev, data: incomingContent } : void 0,
33
+ false
34
+ );
35
+ } catch (error) {
36
+ if (!(error instanceof ContentReadError)) {
37
+ throw error;
38
+ }
39
+ unavailableRead = error;
40
+ classification = { kind: "unknown" };
41
+ }
30
42
  if (!await currentStorageSnapshotMatches(ctx, readFile, observedProvenance)) {
31
43
  return { preserved: false };
32
44
  }
@@ -40,6 +52,9 @@ async function preserveUnsyncedStorageAsConflict(ctx, path, existDoc, incomingEn
40
52
  }
41
53
  const storedRevision = classification.kind === "edited" ? await ctx.host.db().storeWithBaseRevision(readFile, classification.revision, true) : await ctx.host.db().storeIndependentRevision(readFile, true);
42
54
  if (storedRevision === false) {
55
+ if (unavailableRead) {
56
+ throw unavailableRead;
57
+ }
43
58
  ctx.host.log(`Prevented overwriting unsynchronised local changes for ${path}`, LOG_LEVEL_NOTICE);
44
59
  return { preserved: true };
45
60
  }
@@ -55,7 +70,7 @@ async function recheckIncomingStorage(ctx, path, incomingEntry, incomingContent,
55
70
  if (!current || isFolderInfo(current)) return { preserved: false };
56
71
  const protection = await preserveUnsyncedStorageAsConflict(ctx, path, current, incomingEntry, incomingContent);
57
72
  if (protection.preserved || !protection.snapshot) return protection;
58
- if (!allowExistingConflicts && !ctx.setting.currentSettings().writeDocumentsIfConflicted && (await ctx.host.db().getConflictedRevs(path)).length > 0) {
73
+ if (!allowExistingConflicts && !ctx.setting.currentSettings().writeDocumentsIfConflicted && (await ctx.host.db().readConflictedRevs(path)).length > 0) {
59
74
  await queueConflictCheckFor(ctx, path, true);
60
75
  return { preserved: true };
61
76
  }
@@ -171,4 +171,14 @@ export type StorageContentClassification = RecordedStorageClassification | {
171
171
  } | {
172
172
  kind: "unknown";
173
173
  };
174
+ /**
175
+ * Confirm the exact displayed revision from current bytes and device-local evidence.
176
+ * @param ctx - Borrowed file-handler capabilities and provenance.
177
+ * @param path - Current Vault path of the retained reflection target.
178
+ * @param revision - Exact Metadata revision whose reflection is being checked.
179
+ * @returns True only when current bytes, provenance, and current Metadata agree.
180
+ * @remarks Uses existing document locking and snapshot validation. It fetches no
181
+ * Chunks and writes no records. Failed inspection rejects; missing evidence returns false.
182
+ */
183
+ export declare function inspectCurrentFileProvenance(ctx: FileHandlerContext, path: FilePathWithPrefix, revision: string): Promise<boolean>;
174
184
  export {};
@@ -1,3 +1,4 @@
1
+ import { withFileEventPaths } from "./locking.js";
1
2
  import { isFolderInfo } from "./storage.js";
2
3
  import { LOG_LEVEL_VERBOSE } from "octagonal-wheels/common/logger";
3
4
  import { displayRev, isDocContentSame, readContent } from "../../common/utils.js";
@@ -14,7 +15,7 @@ async function getProvenance(ctx, path) {
14
15
  try {
15
16
  const record = await ctx.provenance.get(getProvenancePath(ctx, path));
16
17
  if (!record) return void 0;
17
- const entry = await ctx.host.db().fetchEntryMeta(path, record.revision, true);
18
+ const entry = await ctx.host.db().readEntryMeta(path, record.revision, true);
18
19
  if (entry && !entry._deleted && !entry.deleted) {
19
20
  return record;
20
21
  }
@@ -141,13 +142,13 @@ async function classifyRecordedStorageContent(ctx, file, path, recorded, recorde
141
142
  return { kind: "unchanged", revision: recordedRevision };
142
143
  }
143
144
  const loadedContentIsDecoded = currentLoaded?._rev === recordedRevision;
144
- const base = loadedContentIsDecoded ? currentLoaded : await ctx.host.db().fetchEntry(file, recordedRevision, true, true, !requireReadableContent);
145
+ const base = loadedContentIsDecoded ? currentLoaded : await ctx.host.db().readEntry(file, recordedRevision, true, true, !requireReadableContent);
145
146
  if (base && base._rev === recordedRevision && !("deleted" in base && base.deleted) && !("_deleted" in base && base._deleted)) {
146
147
  const baseContent = loadedContentIsDecoded ? base.data : readContent(base);
147
148
  return await isDocContentSame(baseContent, file.body) ? { kind: "unchanged", revision: recordedRevision } : { kind: "edited", revision: recordedRevision };
148
149
  }
149
150
  if (!base) {
150
- const meta = await ctx.host.db().fetchEntryMeta(file, recordedRevision, true);
151
+ const meta = await ctx.host.db().readEntryMeta(file, recordedRevision, true);
151
152
  if (requireReadableContent && meta && !meta.deleted && !meta._deleted) {
152
153
  throw new Error(
153
154
  `Could not read the recorded file revision ${displayRev(recordedRevision)} for ${file.path}`
@@ -158,12 +159,34 @@ async function classifyRecordedStorageContent(ctx, file, path, recorded, recorde
158
159
  return void 0;
159
160
  }
160
161
  async function classifyLiveStorageContent(ctx, file, currentEntry) {
161
- const matches = currentEntry ? await ctx.host.db().findLiveContentRevisions(file, file.body) : [];
162
+ const matches = currentEntry ? await ctx.host.db().readLiveContentRevisions(file, file.body) : [];
162
163
  if (matches.length) {
163
164
  return { kind: "matching-leaf", revision: matches.length === 1 ? matches[0] : void 0 };
164
165
  }
165
166
  return { kind: "unknown" };
166
167
  }
168
+ async function inspectCurrentFileProvenance(ctx, path, revision) {
169
+ if (!ctx.provenance || !revision) {
170
+ return false;
171
+ }
172
+ return await withFileEventPaths(ctx, [path], async () => {
173
+ const recorded = await readProvenanceSnapshot(ctx, path, true);
174
+ if (!hasContentHash(recorded) || recorded.revision !== revision) {
175
+ return false;
176
+ }
177
+ const stub = await ctx.host.storage().getStub(path);
178
+ if (!stub || isFolderInfo(stub)) {
179
+ return false;
180
+ }
181
+ const file = await ctx.host.readFileFromStub(stub);
182
+ const evidence = { contentHash: await computeFileContentHash(file.body), contentSize: file.body.size };
183
+ if (evidence.contentHash !== recorded.contentHash || evidence.contentSize !== recorded.contentSize) {
184
+ return false;
185
+ }
186
+ const current = await ctx.host.db().readEntryMeta(path, void 0, true);
187
+ return !!current && current._rev === revision && !current.deleted && !current._deleted && await currentStorageSnapshotMatches(ctx, file, recorded, true);
188
+ });
189
+ }
167
190
  export {
168
191
  classifyStorageContent,
169
192
  contentEvidence,
@@ -175,6 +198,7 @@ export {
175
198
  getProvenance,
176
199
  getProvenancePath,
177
200
  hasContentHash,
201
+ inspectCurrentFileProvenance,
178
202
  readProvenanceSnapshot,
179
203
  rememberMatchingLeaf,
180
204
  sameProvenance,
@@ -1,5 +1,9 @@
1
+ import { type FileReflectionResult, type ReflectionOperationContext } from "../../interfaces/FileHandler.js";
1
2
  import type { FilePath, FilePathWithPrefix, MetaEntry, UXFileInfo, UXFileInfoStub } from "../../common/types.js";
2
3
  import type { FileHandlerContext } from "./context.js";
4
+ /** An incomplete attempt without a failed I/O boundary; its owner retains the target. */
5
+ export declare class IncompleteFileReflectionError extends Error {
6
+ }
3
7
  /**
4
8
  * Reflect one selected live revision under the storage document lock.
5
9
  *
@@ -7,7 +11,7 @@ import type { FileHandlerContext } from "./context.js";
7
11
  * @param info - The supplied file observation or path.
8
12
  * @param rev - The exact selected database revision.
9
13
  * @param force - Whether the existing force policy bypasses ordinary unchanged-content checks.
10
- * @returns The selected live leaf reflection result, or false if the selected revision is no longer live.
14
+ * @returns The selected live leaf reflection result, or false if the selected revision is no longer live or its content is unreadable.
11
15
  * @remarks Core operations run under the caller's document lock. Storage protection and database advancement are revalidated at their established await boundaries.
12
16
  */
13
17
  export declare function dbToStorageWithSpecificRev(ctx: FileHandlerContext, info: UXFileInfoStub | UXFileInfo | FilePath | FilePathWithPrefix | null, rev: string, force?: boolean): Promise<boolean>;
@@ -22,6 +26,8 @@ export declare function dbToStorageWithSpecificRev(ctx: FileHandlerContext, info
22
26
  * @remarks Core operations run under the caller's document lock. Storage protection and database advancement are revalidated at their established await boundaries.
23
27
  */
24
28
  export declare function dbToStorage(ctx: FileHandlerContext, entryInfo: MetaEntry | FilePathWithPrefix, info: UXFileInfoStub | UXFileInfo | FilePath | null, force?: boolean): Promise<boolean>;
29
+ /** Run one reflection using the target owner's immutable operation premises. */
30
+ export declare function reflectDatabaseEntry(ctx: FileHandlerContext, entryInfo: MetaEntry | FilePathWithPrefix, info: UXFileInfoStub | UXFileInfo | FilePath | null, force?: boolean, operation?: ReflectionOperationContext): Promise<FileReflectionResult>;
25
31
  /**
26
32
  * Fetch current metadata and apply its storage reflection without reacquiring the lock.
27
33
  *
@@ -29,10 +35,10 @@ export declare function dbToStorage(ctx: FileHandlerContext, entryInfo: MetaEntr
29
35
  * @param entryInfo - Current metadata or a path from which metadata is loaded.
30
36
  * @param info - The supplied file observation or path.
31
37
  * @param force - Whether the existing force policy bypasses ordinary unchanged-content checks.
32
- * @returns True after reflection or a safe conflict/absence skip; false on unreadable or unsafe observations.
38
+ * @returns The ordinary completion, policy hand-off, or owner cancellation outcome; failed reads reject.
33
39
  * @remarks Core operations run under the caller's document lock. Storage protection and database advancement are revalidated at their established await boundaries.
34
40
  */
35
- export declare function dbToStorageCore(ctx: FileHandlerContext, entryInfo: MetaEntry | FilePathWithPrefix, info: UXFileInfoStub | UXFileInfo | FilePath | null, force?: boolean): Promise<boolean>;
41
+ export declare function dbToStorageCore(ctx: FileHandlerContext, entryInfo: MetaEntry | FilePathWithPrefix, info: UXFileInfoStub | UXFileInfo | FilePath | null, force?: boolean, operation?: ReflectionOperationContext): Promise<FileReflectionResult>;
36
42
  /**
37
43
  * Reflect database content while protecting current storage and its provenance.
38
44
  *
@@ -42,7 +48,7 @@ export declare function dbToStorageCore(ctx: FileHandlerContext, entryInfo: Meta
42
48
  * @param force - Whether the existing force policy bypasses ordinary unchanged-content checks.
43
49
  * @param allowExistingConflicts - Whether the caller explicitly selected an existing live conflict leaf.
44
50
  * @param incomingRetry - The number of database-advancement rereads already consumed.
45
- * @returns True after reflection or a policy skip; false when content, path, or current-state validation refuses the effect.
51
+ * @returns The completed or policy outcome; incomplete content or unsafe observations reject.
46
52
  * @remarks Core operations run under the caller's document lock. Storage protection and database advancement are revalidated at their established await boundaries.
47
53
  */
48
- export declare function applyDatabaseEntryToStorage(ctx: FileHandlerContext, docEntry: MetaEntry, file: UXFileInfoStub | UXFileInfo | null, force?: boolean, allowExistingConflicts?: boolean, incomingRetry?: number): Promise<boolean>;
54
+ export declare function applyDatabaseEntryToStorage(ctx: FileHandlerContext, docEntry: MetaEntry, file: UXFileInfoStub | UXFileInfo | null, force?: boolean, allowExistingConflicts?: boolean, incomingRetry?: number, operation?: ReflectionOperationContext): Promise<FileReflectionResult>;
@@ -1,3 +1,10 @@
1
+ import { ContentReadError } from "../../common/LSError.js";
2
+ import {
3
+ FILE_REFLECTION_COMPLETED,
4
+ FILE_REFLECTION_POLICY,
5
+ FILE_REFLECTION_CANCELLED,
6
+ isReflectionCancelled
7
+ } from "../../interfaces/FileHandler.js";
1
8
  import { withFileEventPaths, queueConflictCheckFor } from "./locking.js";
2
9
  import { infoToStub, isFolderInfo, getParentPath } from "./storage.js";
3
10
  import {
@@ -15,24 +22,35 @@ import { getStoragePathFromUXFileInfo } from "../../common/typeUtils.js";
15
22
  import { EVEN } from "../../common/models/shared.const.symbols.js";
16
23
  import { tryGetFilePath } from "../../common/utils.doc.js";
17
24
  import { getPathNormalizationVersion, normalisePathForIdentity } from "../../common/pathNormalization.js";
25
+ class IncompleteFileReflectionError extends Error {
26
+ }
18
27
  async function dbToStorageWithSpecificRev(ctx, info, rev, force) {
19
28
  if (info == null) {
20
29
  ctx.host.log(`Cannot select database revision ${rev} without a file path`, LOG_LEVEL_VERBOSE);
21
30
  return false;
22
31
  }
23
- return await withFileEventPaths(
24
- ctx,
25
- [getStoragePathFromUXFileInfo(info)],
26
- () => dbToStorageWithSpecificRevCore(ctx, info, rev, force)
27
- );
32
+ let operationReturned = false;
33
+ try {
34
+ return await withFileEventPaths(ctx, [getStoragePathFromUXFileInfo(info)], async () => {
35
+ const result = await dbToStorageWithSpecificRevCore(ctx, info, rev, force);
36
+ operationReturned = true;
37
+ return result;
38
+ });
39
+ } catch (error) {
40
+ if (!operationReturned && (error instanceof ContentReadError || error instanceof IncompleteFileReflectionError)) {
41
+ ctx.host.log(error, LOG_LEVEL_VERBOSE);
42
+ return false;
43
+ }
44
+ throw error;
45
+ }
28
46
  }
29
47
  async function dbToStorageWithSpecificRevCore(ctx, info, rev, force) {
30
48
  const file = await infoToStub(ctx, info);
31
49
  const databaseTarget = file ?? info;
32
50
  const [docEntry, currentEntry, conflictedRevisions] = await Promise.all([
33
- ctx.host.db().fetchEntryMeta(databaseTarget, rev, true),
34
- ctx.host.db().fetchEntryMeta(databaseTarget, void 0, true),
35
- ctx.host.db().getConflictedRevs(databaseTarget)
51
+ ctx.host.db().readEntryMeta(databaseTarget, rev, true),
52
+ ctx.host.db().readEntryMeta(databaseTarget, void 0, true),
53
+ ctx.host.db().readConflictedRevs(databaseTarget)
36
54
  ]);
37
55
  if (!docEntry) {
38
56
  ctx.host.log(`File ${tryGetFilePath(info)} is not exist on the database`, LOG_LEVEL_VERBOSE);
@@ -49,46 +67,67 @@ async function dbToStorageWithSpecificRevCore(ctx, info, rev, force) {
49
67
  );
50
68
  return false;
51
69
  }
52
- return await applyDatabaseEntryToStorage(ctx, docEntry, file, force, true);
70
+ return !isReflectionCancelled(await applyDatabaseEntryToStorage(ctx, docEntry, file, force, true));
53
71
  }
54
72
  async function dbToStorage(ctx, entryInfo, info, force) {
55
- const pathFromEntryInfo = typeof entryInfo === "string" ? entryInfo : ctx.host.getPath(entryInfo);
56
- return await withFileEventPaths(ctx, [pathFromEntryInfo], () => dbToStorageCore(ctx, entryInfo, info, force));
73
+ const path = typeof entryInfo === "string" ? entryInfo : ctx.host.getPath(entryInfo);
74
+ let operationReturned = false;
75
+ try {
76
+ const result = await withFileEventPaths(ctx, [path], async () => {
77
+ const outcome = await dbToStorageCore(ctx, entryInfo, info, force);
78
+ operationReturned = true;
79
+ return outcome;
80
+ });
81
+ return !isReflectionCancelled(result);
82
+ } catch (error) {
83
+ if (!operationReturned && (error instanceof ContentReadError || error instanceof IncompleteFileReflectionError)) {
84
+ ctx.host.log(error, LOG_LEVEL_VERBOSE);
85
+ return false;
86
+ }
87
+ throw error;
88
+ }
57
89
  }
58
- async function dbToStorageCore(ctx, entryInfo, info, force) {
90
+ async function reflectDatabaseEntry(ctx, entryInfo, info, force, operation) {
91
+ const path = typeof entryInfo === "string" ? entryInfo : ctx.host.getPath(entryInfo);
92
+ return await withFileEventPaths(ctx, [path], () => dbToStorageCore(ctx, entryInfo, info, force, operation));
93
+ }
94
+ async function dbToStorageCore(ctx, entryInfo, info, force, operation) {
95
+ if (operation?.checkpoint?.() === false) {
96
+ return FILE_REFLECTION_CANCELLED;
97
+ }
59
98
  const file = await infoToStub(ctx, info);
60
99
  const pathFromEntryInfo = typeof entryInfo === "string" ? entryInfo : ctx.host.getPath(entryInfo);
61
- const docEntry = await ctx.host.db().fetchEntryMeta(pathFromEntryInfo, void 0, true);
100
+ const docEntry = await ctx.host.db().readEntryMeta(pathFromEntryInfo, void 0, true);
62
101
  if (!docEntry) {
63
102
  ctx.host.log(`File ${pathFromEntryInfo} is not exist on the database`, LOG_LEVEL_VERBOSE);
64
- return false;
103
+ throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
65
104
  }
66
- return await applyDatabaseEntryToStorage(ctx, docEntry, file, force);
105
+ return await applyDatabaseEntryToStorage(ctx, docEntry, file, force, false, 0, operation);
67
106
  }
68
- async function applyDatabaseEntryToStorage(ctx, docEntry, file, force, allowExistingConflicts = false, incomingRetry = 0) {
107
+ async function applyDatabaseEntryToStorage(ctx, docEntry, file, force, allowExistingConflicts = false, incomingRetry = 0, operation) {
69
108
  const mode = file == null ? "create" : "modify";
70
109
  const path = ctx.host.getPath(docEntry);
71
110
  const settings = ctx.setting.currentSettings();
72
- const revs = await ctx.host.db().getConflictedRevs(path);
111
+ const revs = await ctx.host.db().readConflictedRevs(path);
73
112
  if (revs.length > 0 && !allowExistingConflicts) {
74
113
  if (settings.writeDocumentsIfConflicted) {
75
114
  } else {
76
115
  await queueConflictCheckFor(ctx, path, true);
77
- return true;
116
+ return FILE_REFLECTION_POLICY;
78
117
  }
79
118
  }
80
119
  let existDoc = await ctx.host.storage().getStub(path);
81
120
  if (isFolderInfo(existDoc)) {
82
121
  ctx.host.log(`Folder ${path} is already exist on the storage as a folder`, LOG_LEVEL_VERBOSE);
83
- return true;
122
+ return FILE_REFLECTION_POLICY;
84
123
  }
85
124
  const existOnDB = !(docEntry._deleted || docEntry.deleted || false);
86
125
  if (!existOnDB && !existDoc) {
87
126
  ctx.host.log(`File ${path} seems to be deleted, but already not on storage`, LOG_LEVEL_VERBOSE);
88
127
  await deleteProvenance(ctx, path);
89
- return true;
128
+ return FILE_REFLECTION_COMPLETED;
90
129
  }
91
- if (!existOnDB && existDoc)
130
+ if (!existOnDB && existDoc) {
92
131
  return await applyIncomingDeletion(
93
132
  ctx,
94
133
  docEntry,
@@ -97,17 +136,21 @@ async function applyDatabaseEntryToStorage(ctx, docEntry, file, force, allowExis
97
136
  settings,
98
137
  force,
99
138
  allowExistingConflicts,
100
- incomingRetry
139
+ incomingRetry,
140
+ operation
101
141
  );
142
+ }
102
143
  if (existDoc && existDoc.path !== path) {
103
144
  const current = await reconcileStoragePath(ctx, existDoc, path, settings);
104
- if (current === false) return false;
145
+ if (current === false) {
146
+ throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
147
+ }
105
148
  existDoc = current;
106
149
  }
107
- const docRead = await ctx.host.db().fetchEntryFromMeta(docEntry);
150
+ const docRead = await ctx.host.db().readEntryFromMeta(docEntry);
108
151
  if (!docRead) {
109
152
  ctx.host.log(`File ${path} is not exist on the database`, LOG_LEVEL_VERBOSE);
110
- return false;
153
+ throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
111
154
  }
112
155
  const docData = readContent(docRead);
113
156
  const reflectedContent = createBlob(docData);
@@ -117,7 +160,7 @@ async function applyDatabaseEntryToStorage(ctx, docEntry, file, force, allowExis
117
160
  `File ${path} seems to be corrupted! Writing prevented. (${docRead.size} != ${reflectedContent.size})`,
118
161
  LOG_LEVEL_NOTICE
119
162
  );
120
- return false;
163
+ throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
121
164
  }
122
165
  }
123
166
  const reflectedEvidence = await contentEvidence(ctx, reflectedContent);
@@ -133,35 +176,52 @@ async function applyDatabaseEntryToStorage(ctx, docEntry, file, force, allowExis
133
176
  mode,
134
177
  force,
135
178
  allowExistingConflicts,
136
- incomingRetry
179
+ incomingRetry,
180
+ operation
137
181
  };
138
182
  const preparation = await prepareIncomingStorageWrite(ctx, write);
139
183
  if (preparation.kind === "complete") return preparation.result;
140
184
  return await commitIncomingStorageWrite(ctx, write, preparation.snapshot);
141
185
  }
142
- async function reconcileAdvancedIncomingRevision(ctx, incomingEntry, path, force, allowExistingConflicts, incomingRetry) {
186
+ async function reconcileAdvancedIncomingRevision(ctx, incomingEntry, path, force, allowExistingConflicts, incomingRetry, operation) {
143
187
  if (force || allowExistingConflicts) return void 0;
144
- const current = await ctx.host.db().fetchEntryMeta(path, void 0, true);
145
- if (!current) return false;
188
+ const current = await ctx.host.db().readEntryMeta(path, void 0, true);
189
+ if (!current) {
190
+ throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
191
+ }
146
192
  if (current._rev === incomingEntry._rev) return void 0;
147
193
  if (incomingRetry >= 2) {
148
194
  ctx.host.log(`Database kept changing while reflecting ${path}`, LOG_LEVEL_NOTICE);
149
- return false;
195
+ throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
150
196
  }
151
197
  const storage = await ctx.host.storage().getStub(path);
152
- if (isFolderInfo(storage)) return false;
153
- return await applyDatabaseEntryToStorage(ctx, current, storage, force, allowExistingConflicts, incomingRetry + 1);
198
+ if (isFolderInfo(storage)) {
199
+ throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
200
+ }
201
+ return await applyDatabaseEntryToStorage(
202
+ ctx,
203
+ current,
204
+ storage,
205
+ force,
206
+ allowExistingConflicts,
207
+ incomingRetry + 1,
208
+ operation
209
+ );
154
210
  }
155
- async function applyIncomingDeletion(ctx, docEntry, existDoc, path, settings, force, allowExistingConflicts, incomingRetry) {
211
+ async function applyIncomingDeletion(ctx, docEntry, existDoc, path, settings, force, allowExistingConflicts, incomingRetry, operation) {
156
212
  let safeDeletionSnapshot;
157
213
  if (!force && !settings.writeDocumentsIfConflicted) {
158
- let protection = await preserveUnsyncedStorageAsConflict(ctx, path, existDoc, docEntry);
159
- if (protection.preserved) return true;
214
+ let protection = await preserveUnsyncedStorageAsConflict(ctx, path, existDoc, docEntry, void 0);
215
+ if (protection.preserved) {
216
+ return FILE_REFLECTION_POLICY;
217
+ }
160
218
  if (!protection.snapshot || !await currentStorageSnapshotMatches(ctx, protection.snapshot.file, protection.snapshot.revision)) {
161
219
  protection = await recheckIncomingStorage(ctx, path, docEntry, void 0, allowExistingConflicts);
162
- if (protection.preserved) return true;
220
+ if (protection.preserved) {
221
+ return FILE_REFLECTION_POLICY;
222
+ }
163
223
  if (!protection.snapshot || !await currentStorageSnapshotMatches(ctx, protection.snapshot.file, protection.snapshot.revision)) {
164
- return false;
224
+ throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
165
225
  }
166
226
  }
167
227
  safeDeletionSnapshot = protection.snapshot;
@@ -172,14 +232,17 @@ async function applyIncomingDeletion(ctx, docEntry, existDoc, path, settings, fo
172
232
  path,
173
233
  force,
174
234
  allowExistingConflicts,
175
- incomingRetry
235
+ incomingRetry,
236
+ operation
176
237
  );
177
238
  if (latest !== void 0) return latest;
178
239
  if (safeDeletionSnapshot && !await currentStorageSnapshotMatches(ctx, safeDeletionSnapshot.file, safeDeletionSnapshot.revision)) {
179
240
  const protection = await recheckIncomingStorage(ctx, path, docEntry, void 0, allowExistingConflicts);
180
- if (protection.preserved) return true;
241
+ if (protection.preserved) {
242
+ return FILE_REFLECTION_POLICY;
243
+ }
181
244
  if (!protection.snapshot || !await currentStorageSnapshotMatches(ctx, protection.snapshot.file, protection.snapshot.revision)) {
182
- return false;
245
+ throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
183
246
  }
184
247
  safeDeletionSnapshot = protection.snapshot;
185
248
  latest = await reconcileAdvancedIncomingRevision(
@@ -188,16 +251,20 @@ async function applyIncomingDeletion(ctx, docEntry, existDoc, path, settings, fo
188
251
  path,
189
252
  force,
190
253
  allowExistingConflicts,
191
- incomingRetry
254
+ incomingRetry,
255
+ operation
192
256
  );
193
257
  if (latest !== void 0) return latest;
194
258
  if (!await currentStorageSnapshotMatches(ctx, safeDeletionSnapshot.file, safeDeletionSnapshot.revision)) {
195
- return false;
259
+ throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
196
260
  }
197
261
  }
262
+ if (operation?.checkpoint?.() === false) {
263
+ return FILE_REFLECTION_CANCELLED;
264
+ }
198
265
  await ctx.host.storage().deleteVaultItem(path);
199
266
  await deleteProvenance(ctx, path);
200
- return true;
267
+ return FILE_REFLECTION_COMPLETED;
201
268
  }
202
269
  async function reconcileStoragePath(ctx, existDoc, path, settings) {
203
270
  const [existingDocumentId, targetDocumentId] = await Promise.all([
@@ -236,8 +303,9 @@ async function reconcileStoragePath(ctx, existDoc, path, settings) {
236
303
  }
237
304
  async function prepareIncomingStorageWrite(ctx, write) {
238
305
  const { existDoc, force, allowExistingConflicts, docRead } = write;
239
- if (allowExistingConflicts && existDoc && !force && await acceptMatchingSelectedContent(ctx, write, existDoc))
240
- return { kind: "complete", result: true };
306
+ if (allowExistingConflicts && existDoc && !force && await acceptMatchingSelectedContent(ctx, write, existDoc)) {
307
+ return { kind: "complete", result: FILE_REFLECTION_COMPLETED };
308
+ }
241
309
  if (existDoc && !force) return await prepareExistingStorageWrite(ctx, write, existDoc);
242
310
  ctx.host.log(`File ${docRead.path} ${existDoc ? "(new) " : ""} ${force ? " (forced)" : ""}`, LOG_LEVEL_VERBOSE);
243
311
  return { kind: "write", snapshot: void 0 };
@@ -253,14 +321,17 @@ async function commitIncomingStorageWrite(ctx, write, safeSnapshot) {
253
321
  mode,
254
322
  force,
255
323
  allowExistingConflicts,
256
- incomingRetry
324
+ incomingRetry,
325
+ operation
257
326
  } = write;
258
327
  await ctx.host.storage().ensureDir(path);
259
328
  if (safeSnapshot && !await currentStorageSnapshotMatches(ctx, safeSnapshot.file, safeSnapshot.revision)) {
260
329
  const protection = await recheckIncomingStorage(ctx, path, docEntry, docData, allowExistingConflicts);
261
- if (protection.preserved) return true;
330
+ if (protection.preserved) {
331
+ return FILE_REFLECTION_POLICY;
332
+ }
262
333
  if (!protection.snapshot || !await currentStorageSnapshotMatches(ctx, protection.snapshot.file, protection.snapshot.revision)) {
263
- return false;
334
+ throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
264
335
  }
265
336
  safeSnapshot = protection.snapshot;
266
337
  }
@@ -270,11 +341,15 @@ async function commitIncomingStorageWrite(ctx, write, safeSnapshot) {
270
341
  path,
271
342
  force,
272
343
  allowExistingConflicts,
273
- incomingRetry
344
+ incomingRetry,
345
+ operation
274
346
  );
275
347
  if (latest !== void 0) return latest;
276
348
  if (safeSnapshot && !await currentStorageSnapshotMatches(ctx, safeSnapshot.file, safeSnapshot.revision)) {
277
- return false;
349
+ throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
350
+ }
351
+ if (operation?.checkpoint?.() === false) {
352
+ return FILE_REFLECTION_CANCELLED;
278
353
  }
279
354
  const ret = await ctx.host.storage().writeFileAuto(path, docData, { ctime: docRead.ctime, mtime: docRead.mtime });
280
355
  await ctx.host.storage().touched(path);
@@ -282,11 +357,14 @@ async function commitIncomingStorageWrite(ctx, write, safeSnapshot) {
282
357
  if (ret && ctx.provenance) {
283
358
  const storedStat = await ctx.host.storage().stat(path);
284
359
  if (safeSnapshot && !sameProvenance(await readProvenanceSnapshot(ctx, path), safeSnapshot.revision)) {
285
- return ret;
360
+ return FILE_REFLECTION_COMPLETED;
286
361
  }
287
362
  await setProvenance(ctx, path, docEntry._rev, storedStat?.mtime, reflectedContent, reflectedEvidence);
288
363
  }
289
- return ret;
364
+ if (!ret) {
365
+ throw new IncompleteFileReflectionError("Storage rejected the reflected write");
366
+ }
367
+ return FILE_REFLECTION_COMPLETED;
290
368
  }
291
369
  async function acceptMatchingSelectedContent(ctx, write, current) {
292
370
  const { docEntry, docRead, docData, reflectedContent, reflectedEvidence, path } = write;
@@ -319,7 +397,7 @@ async function prepareExistingStorageWrite(ctx, write, current) {
319
397
  if (!shouldApplied) {
320
398
  await setProvenance(ctx, path, docEntry._rev, existDoc.stat.mtime, reflectedContent, reflectedEvidence);
321
399
  ctx.host.log(`File ${docRead.path} is not changed`, LOG_LEVEL_VERBOSE);
322
- return { kind: "complete", result: true };
400
+ return { kind: "complete", result: FILE_REFLECTION_COMPLETED };
323
401
  }
324
402
  return await prepareIncomingStorageProtection(ctx, write, current);
325
403
  }
@@ -328,17 +406,25 @@ async function prepareIncomingStorageProtection(ctx, write, current) {
328
406
  const existDoc = current;
329
407
  if (force || settings.writeDocumentsIfConflicted) return { kind: "write", snapshot: void 0 };
330
408
  let protection = await preserveUnsyncedStorageAsConflict(ctx, path, existDoc, docEntry, docData);
331
- if (protection.preserved) return { kind: "complete", result: true };
409
+ if (protection.preserved) {
410
+ return { kind: "complete", result: FILE_REFLECTION_POLICY };
411
+ }
332
412
  if (!protection.snapshot) {
333
413
  protection = await recheckIncomingStorage(ctx, path, docEntry, docData, allowExistingConflicts);
334
- if (protection.preserved) return { kind: "complete", result: true };
335
- if (!protection.snapshot) return { kind: "complete", result: false };
414
+ if (protection.preserved) {
415
+ return { kind: "complete", result: FILE_REFLECTION_POLICY };
416
+ }
417
+ if (!protection.snapshot) {
418
+ throw new IncompleteFileReflectionError("Storage changed during overwrite protection");
419
+ }
336
420
  }
337
421
  return { kind: "write", snapshot: protection.snapshot };
338
422
  }
339
423
  export {
424
+ IncompleteFileReflectionError,
340
425
  applyDatabaseEntryToStorage,
341
426
  dbToStorage,
342
427
  dbToStorageCore,
343
- dbToStorageWithSpecificRev
428
+ dbToStorageWithSpecificRev,
429
+ reflectDatabaseEntry
344
430
  };