obsidian-sync-mcp 0.3.0 → 0.4.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.
- package/README.md +24 -10
- package/dist/{chunk-TFJDIQK4.js → chunk-GK3PAZZJ.js} +43 -2
- package/dist/chunk-GK3PAZZJ.js.map +1 -0
- package/dist/main.js +507 -103
- package/dist/main.js.map +1 -1
- package/dist/vault-H5LOSSPH.js +11124 -0
- package/dist/vault-H5LOSSPH.js.map +1 -0
- package/dist/{vault-local-3C2JVBRO.js → vault-local-NFQ7FPNH.js} +22 -6
- package/dist/vault-local-NFQ7FPNH.js.map +1 -0
- package/package.json +2 -2
- package/dist/chunk-TFJDIQK4.js.map +0 -1
- package/dist/vault-J2V2D3HA.js +0 -4869
- package/dist/vault-J2V2D3HA.js.map +0 -1
- package/dist/vault-local-3C2JVBRO.js.map +0 -1
package/dist/vault-J2V2D3HA.js
DELETED
|
@@ -1,4869 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
// Node polyfills for livesync-commonlib browser globals
|
|
3
|
-
if(!("navigator" in globalThis)){globalThis.navigator={language:"en"};}
|
|
4
|
-
import {
|
|
5
|
-
__reExport,
|
|
6
|
-
parseFrontmatterAndLinks
|
|
7
|
-
} from "./chunk-TFJDIQK4.js";
|
|
8
|
-
|
|
9
|
-
// lib/livesync-commonlib/src/string_and_binary/path.ts
|
|
10
|
-
import { minimatch } from "minimatch";
|
|
11
|
-
|
|
12
|
-
// lib/livesync-commonlib/src/mods.ts
|
|
13
|
-
var webcrypto;
|
|
14
|
-
async function getWebCrypto() {
|
|
15
|
-
if (webcrypto) {
|
|
16
|
-
return webcrypto;
|
|
17
|
-
}
|
|
18
|
-
if (globalThis.crypto) {
|
|
19
|
-
webcrypto = globalThis.crypto;
|
|
20
|
-
return webcrypto;
|
|
21
|
-
} else {
|
|
22
|
-
const module = await import("crypto");
|
|
23
|
-
webcrypto = module.webcrypto;
|
|
24
|
-
return webcrypto;
|
|
25
|
-
}
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
// lib/livesync-commonlib/src/common/types.ts
|
|
29
|
-
import {
|
|
30
|
-
LOG_LEVEL_DEBUG,
|
|
31
|
-
LOG_LEVEL_INFO,
|
|
32
|
-
LOG_LEVEL_NOTICE,
|
|
33
|
-
LOG_LEVEL_URGENT,
|
|
34
|
-
LOG_LEVEL_VERBOSE
|
|
35
|
-
} from "octagonal-wheels/common/logger";
|
|
36
|
-
import { RESULT_NOT_FOUND, RESULT_TIMED_OUT } from "octagonal-wheels/common/const";
|
|
37
|
-
var MAX_DOC_SIZE_BIN = 102400;
|
|
38
|
-
var LEAF_WAIT_TIMEOUT = 3e4;
|
|
39
|
-
var LEAF_WAIT_ONLY_REMOTE = 5e3;
|
|
40
|
-
var LEAF_WAIT_TIMEOUT_SEQUENTIAL_REPLICATOR = 5e3;
|
|
41
|
-
var NOT_CONFLICTED = /* @__PURE__ */ Symbol("not_conflicted");
|
|
42
|
-
var MISSING_OR_ERROR = /* @__PURE__ */ Symbol("missing_or_error");
|
|
43
|
-
var VERSIONING_DOCID = "obsydian_livesync_version";
|
|
44
|
-
var SETTING_VERSION_SUPPORT_CASE_INSENSITIVE = 10;
|
|
45
|
-
var CURRENT_SETTING_VERSION = SETTING_VERSION_SUPPORT_CASE_INSENSITIVE;
|
|
46
|
-
var RemoteTypes = {
|
|
47
|
-
REMOTE_COUCHDB: "",
|
|
48
|
-
REMOTE_MINIO: "MINIO",
|
|
49
|
-
REMOTE_P2P: "ONLY_P2P"
|
|
50
|
-
};
|
|
51
|
-
var REMOTE_COUCHDB = RemoteTypes.REMOTE_COUCHDB;
|
|
52
|
-
var REMOTE_MINIO = RemoteTypes.REMOTE_MINIO;
|
|
53
|
-
var REMOTE_P2P = RemoteTypes.REMOTE_P2P;
|
|
54
|
-
var P2P_DEFAULT_SETTINGS = {
|
|
55
|
-
P2P_Enabled: false,
|
|
56
|
-
P2P_AutoAccepting: 0 /* NONE */,
|
|
57
|
-
P2P_AppID: "self-hosted-livesync",
|
|
58
|
-
P2P_roomID: "",
|
|
59
|
-
P2P_passphrase: "",
|
|
60
|
-
P2P_relays: "wss://exp-relay.vrtmrz.net/",
|
|
61
|
-
P2P_AutoBroadcast: false,
|
|
62
|
-
P2P_AutoStart: false,
|
|
63
|
-
P2P_AutoSyncPeers: "",
|
|
64
|
-
P2P_AutoWatchPeers: "",
|
|
65
|
-
P2P_SyncOnReplication: "",
|
|
66
|
-
P2P_RebuildFrom: "",
|
|
67
|
-
P2P_AutoAcceptingPeers: "",
|
|
68
|
-
P2P_AutoDenyingPeers: "",
|
|
69
|
-
P2P_IsHeadless: false
|
|
70
|
-
};
|
|
71
|
-
var E2EEAlgorithms = {
|
|
72
|
-
V1: "",
|
|
73
|
-
V2: "v2",
|
|
74
|
-
ForceV1: "forceV1"
|
|
75
|
-
};
|
|
76
|
-
var HashAlgorithms = {
|
|
77
|
-
XXHASH32: "xxhash32",
|
|
78
|
-
XXHASH64: "xxhash64",
|
|
79
|
-
MIXED_PUREJS: "mixed-purejs",
|
|
80
|
-
SHA1: "sha1",
|
|
81
|
-
LEGACY: ""
|
|
82
|
-
};
|
|
83
|
-
var ChunkAlgorithms = {
|
|
84
|
-
V1: "v1",
|
|
85
|
-
V2: "v2",
|
|
86
|
-
V2Segmenter: "v2-segmenter",
|
|
87
|
-
RabinKarp: "v3-rabin-karp"
|
|
88
|
-
};
|
|
89
|
-
var DEFAULT_SETTINGS = {
|
|
90
|
-
remoteType: REMOTE_COUCHDB,
|
|
91
|
-
useCustomRequestHandler: false,
|
|
92
|
-
couchDB_URI: "",
|
|
93
|
-
couchDB_USER: "",
|
|
94
|
-
couchDB_PASSWORD: "",
|
|
95
|
-
couchDB_DBNAME: "",
|
|
96
|
-
liveSync: false,
|
|
97
|
-
syncOnSave: false,
|
|
98
|
-
syncOnStart: false,
|
|
99
|
-
savingDelay: 200,
|
|
100
|
-
lessInformationInLog: false,
|
|
101
|
-
gcDelay: 300,
|
|
102
|
-
versionUpFlash: "",
|
|
103
|
-
minimumChunkSize: 20,
|
|
104
|
-
longLineThreshold: 250,
|
|
105
|
-
showVerboseLog: false,
|
|
106
|
-
suspendFileWatching: false,
|
|
107
|
-
trashInsteadDelete: true,
|
|
108
|
-
periodicReplication: false,
|
|
109
|
-
periodicReplicationInterval: 60,
|
|
110
|
-
syncOnFileOpen: false,
|
|
111
|
-
encrypt: false,
|
|
112
|
-
passphrase: "",
|
|
113
|
-
usePathObfuscation: false,
|
|
114
|
-
doNotDeleteFolder: false,
|
|
115
|
-
resolveConflictsByNewerFile: false,
|
|
116
|
-
batchSave: false,
|
|
117
|
-
batchSaveMinimumDelay: 5,
|
|
118
|
-
batchSaveMaximumDelay: 60,
|
|
119
|
-
deviceAndVaultName: "",
|
|
120
|
-
usePluginSettings: false,
|
|
121
|
-
showOwnPlugins: false,
|
|
122
|
-
showStatusOnEditor: true,
|
|
123
|
-
showStatusOnStatusbar: true,
|
|
124
|
-
showOnlyIconsOnEditor: false,
|
|
125
|
-
hideFileWarningNotice: false,
|
|
126
|
-
usePluginSync: false,
|
|
127
|
-
autoSweepPlugins: false,
|
|
128
|
-
autoSweepPluginsPeriodic: false,
|
|
129
|
-
notifyPluginOrSettingUpdated: false,
|
|
130
|
-
checkIntegrityOnSave: false,
|
|
131
|
-
batch_size: 25,
|
|
132
|
-
batches_limit: 25,
|
|
133
|
-
useHistory: false,
|
|
134
|
-
disableRequestURI: false,
|
|
135
|
-
skipOlderFilesOnSync: true,
|
|
136
|
-
checkConflictOnlyOnOpen: false,
|
|
137
|
-
showMergeDialogOnlyOnActive: false,
|
|
138
|
-
syncInternalFiles: false,
|
|
139
|
-
syncInternalFilesBeforeReplication: false,
|
|
140
|
-
syncInternalFilesIgnorePatterns: "\\/node_modules\\/, \\/\\.git\\/, \\/obsidian-livesync\\/",
|
|
141
|
-
syncInternalFilesTargetPatterns: "",
|
|
142
|
-
syncInternalFilesInterval: 60,
|
|
143
|
-
additionalSuffixOfDatabaseName: "",
|
|
144
|
-
ignoreVersionCheck: false,
|
|
145
|
-
lastReadUpdates: 0,
|
|
146
|
-
deleteMetadataOfDeletedFiles: false,
|
|
147
|
-
syncIgnoreRegEx: "",
|
|
148
|
-
syncOnlyRegEx: "",
|
|
149
|
-
customChunkSize: 0,
|
|
150
|
-
readChunksOnline: true,
|
|
151
|
-
watchInternalFileChanges: true,
|
|
152
|
-
automaticallyDeleteMetadataOfDeletedFiles: 0,
|
|
153
|
-
disableMarkdownAutoMerge: false,
|
|
154
|
-
writeDocumentsIfConflicted: false,
|
|
155
|
-
useDynamicIterationCount: false,
|
|
156
|
-
syncAfterMerge: false,
|
|
157
|
-
configPassphraseStore: "",
|
|
158
|
-
encryptedPassphrase: "",
|
|
159
|
-
encryptedCouchDBConnection: "",
|
|
160
|
-
permitEmptyPassphrase: false,
|
|
161
|
-
useIndexedDBAdapter: true,
|
|
162
|
-
useTimeouts: false,
|
|
163
|
-
writeLogToTheFile: false,
|
|
164
|
-
doNotPaceReplication: false,
|
|
165
|
-
hashCacheMaxCount: 300,
|
|
166
|
-
hashCacheMaxAmount: 50,
|
|
167
|
-
concurrencyOfReadChunksOnline: 40,
|
|
168
|
-
minimumIntervalOfReadChunksOnline: 50,
|
|
169
|
-
hashAlg: "xxhash64",
|
|
170
|
-
suspendParseReplicationResult: false,
|
|
171
|
-
doNotSuspendOnFetching: false,
|
|
172
|
-
useIgnoreFiles: false,
|
|
173
|
-
ignoreFiles: ".gitignore",
|
|
174
|
-
syncOnEditorSave: false,
|
|
175
|
-
pluginSyncExtendedSetting: {},
|
|
176
|
-
syncMaxSizeInMB: 50,
|
|
177
|
-
settingSyncFile: "",
|
|
178
|
-
writeCredentialsForSettingSync: false,
|
|
179
|
-
notifyAllSettingSyncFile: false,
|
|
180
|
-
isConfigured: void 0,
|
|
181
|
-
settingVersion: CURRENT_SETTING_VERSION,
|
|
182
|
-
enableCompression: false,
|
|
183
|
-
accessKey: "",
|
|
184
|
-
bucket: "",
|
|
185
|
-
endpoint: "",
|
|
186
|
-
region: "auto",
|
|
187
|
-
secretKey: "",
|
|
188
|
-
useEden: false,
|
|
189
|
-
maxChunksInEden: 10,
|
|
190
|
-
maxTotalLengthInEden: 1024,
|
|
191
|
-
maxAgeInEden: 10,
|
|
192
|
-
disableCheckingConfigMismatch: false,
|
|
193
|
-
displayLanguage: "",
|
|
194
|
-
/**
|
|
195
|
-
* @deprecated
|
|
196
|
-
*/
|
|
197
|
-
enableChunkSplitterV2: false,
|
|
198
|
-
disableWorkerForGeneratingChunks: false,
|
|
199
|
-
processSmallFilesInUIThread: false,
|
|
200
|
-
notifyThresholdOfRemoteStorageSize: -1,
|
|
201
|
-
usePluginSyncV2: false,
|
|
202
|
-
usePluginEtc: false,
|
|
203
|
-
handleFilenameCaseSensitive: void 0,
|
|
204
|
-
doNotUseFixedRevisionForChunks: true,
|
|
205
|
-
showLongerLogInsideEditor: false,
|
|
206
|
-
sendChunksBulk: false,
|
|
207
|
-
sendChunksBulkMaxSize: 1,
|
|
208
|
-
/**
|
|
209
|
-
* @deprecated
|
|
210
|
-
* This setting is no longer used and will be removed in the future.
|
|
211
|
-
*/
|
|
212
|
-
useSegmenter: false,
|
|
213
|
-
useAdvancedMode: false,
|
|
214
|
-
usePowerUserMode: false,
|
|
215
|
-
useEdgeCaseMode: false,
|
|
216
|
-
enableDebugTools: false,
|
|
217
|
-
suppressNotifyHiddenFilesChange: false,
|
|
218
|
-
syncMinimumInterval: 2e3,
|
|
219
|
-
...P2P_DEFAULT_SETTINGS,
|
|
220
|
-
doctorProcessedVersion: "",
|
|
221
|
-
bucketCustomHeaders: "",
|
|
222
|
-
couchDB_CustomHeaders: "",
|
|
223
|
-
useJWT: false,
|
|
224
|
-
jwtAlgorithm: "",
|
|
225
|
-
jwtKey: "",
|
|
226
|
-
jwtKid: "",
|
|
227
|
-
jwtSub: "",
|
|
228
|
-
jwtExpDuration: 5,
|
|
229
|
-
useRequestAPI: false,
|
|
230
|
-
bucketPrefix: "",
|
|
231
|
-
chunkSplitterVersion: "",
|
|
232
|
-
E2EEAlgorithm: E2EEAlgorithms.V1,
|
|
233
|
-
processSizeMismatchedFiles: false,
|
|
234
|
-
forcePathStyle: true
|
|
235
|
-
};
|
|
236
|
-
var PREFERRED_BASE = {
|
|
237
|
-
syncMaxSizeInMB: 50,
|
|
238
|
-
chunkSplitterVersion: "v3-rabin-karp",
|
|
239
|
-
doNotUseFixedRevisionForChunks: false,
|
|
240
|
-
usePluginSyncV2: true,
|
|
241
|
-
handleFilenameCaseSensitive: false,
|
|
242
|
-
E2EEAlgorithm: E2EEAlgorithms.V2
|
|
243
|
-
};
|
|
244
|
-
var PREFERRED_SETTING_CLOUDANT = {
|
|
245
|
-
...PREFERRED_BASE,
|
|
246
|
-
customChunkSize: 0,
|
|
247
|
-
sendChunksBulkMaxSize: 1,
|
|
248
|
-
concurrencyOfReadChunksOnline: 100,
|
|
249
|
-
minimumIntervalOfReadChunksOnline: 333
|
|
250
|
-
};
|
|
251
|
-
var PREFERRED_SETTING_SELF_HOSTED = {
|
|
252
|
-
...PREFERRED_BASE,
|
|
253
|
-
customChunkSize: 50,
|
|
254
|
-
sendChunksBulkMaxSize: 1,
|
|
255
|
-
concurrencyOfReadChunksOnline: 30,
|
|
256
|
-
minimumIntervalOfReadChunksOnline: 25
|
|
257
|
-
};
|
|
258
|
-
var PREFERRED_JOURNAL_SYNC = {
|
|
259
|
-
...PREFERRED_BASE,
|
|
260
|
-
customChunkSize: 10,
|
|
261
|
-
concurrencyOfReadChunksOnline: 30,
|
|
262
|
-
minimumIntervalOfReadChunksOnline: 25
|
|
263
|
-
};
|
|
264
|
-
var EntryTypes = {
|
|
265
|
-
NOTE_LEGACY: "notes",
|
|
266
|
-
NOTE_BINARY: "newnote",
|
|
267
|
-
NOTE_PLAIN: "plain",
|
|
268
|
-
INTERNAL_FILE: "internalfile",
|
|
269
|
-
CHUNK: "leaf",
|
|
270
|
-
CHUNK_PACK: "chunkpack",
|
|
271
|
-
VERSION_INFO: "versioninfo",
|
|
272
|
-
SYNC_INFO: "syncinfo",
|
|
273
|
-
SYNC_PARAMETERS: "sync-parameters",
|
|
274
|
-
MILESTONE_INFO: "milestoneinfo",
|
|
275
|
-
NODE_INFO: "nodeinfo"
|
|
276
|
-
};
|
|
277
|
-
var NoteTypes = [EntryTypes.NOTE_LEGACY, EntryTypes.NOTE_BINARY, EntryTypes.NOTE_PLAIN];
|
|
278
|
-
var ChunkTypes = [EntryTypes.CHUNK, EntryTypes.CHUNK_PACK];
|
|
279
|
-
function isMetaEntry(entry) {
|
|
280
|
-
return "children" in entry;
|
|
281
|
-
}
|
|
282
|
-
var TweakValuesShouldMatchedTemplate = {
|
|
283
|
-
minimumChunkSize: 20,
|
|
284
|
-
longLineThreshold: 250,
|
|
285
|
-
encrypt: false,
|
|
286
|
-
usePathObfuscation: false,
|
|
287
|
-
enableCompression: false,
|
|
288
|
-
useEden: false,
|
|
289
|
-
customChunkSize: 0,
|
|
290
|
-
useDynamicIterationCount: false,
|
|
291
|
-
hashAlg: "xxhash64",
|
|
292
|
-
enableChunkSplitterV2: true,
|
|
293
|
-
maxChunksInEden: 10,
|
|
294
|
-
maxTotalLengthInEden: 1024,
|
|
295
|
-
maxAgeInEden: 10,
|
|
296
|
-
usePluginSyncV2: false,
|
|
297
|
-
handleFilenameCaseSensitive: false,
|
|
298
|
-
doNotUseFixedRevisionForChunks: true,
|
|
299
|
-
useSegmenter: false,
|
|
300
|
-
E2EEAlgorithm: E2EEAlgorithms.V2,
|
|
301
|
-
chunkSplitterVersion: ChunkAlgorithms.RabinKarp
|
|
302
|
-
};
|
|
303
|
-
var TweakValuesRecommendedTemplate = {
|
|
304
|
-
useIgnoreFiles: false,
|
|
305
|
-
useCustomRequestHandler: false,
|
|
306
|
-
batch_size: 25,
|
|
307
|
-
batches_limit: 25,
|
|
308
|
-
useIndexedDBAdapter: true,
|
|
309
|
-
useTimeouts: false,
|
|
310
|
-
readChunksOnline: true,
|
|
311
|
-
hashCacheMaxCount: 300,
|
|
312
|
-
hashCacheMaxAmount: 50,
|
|
313
|
-
concurrencyOfReadChunksOnline: 40,
|
|
314
|
-
minimumIntervalOfReadChunksOnline: 50,
|
|
315
|
-
ignoreFiles: ".gitignore",
|
|
316
|
-
syncMaxSizeInMB: 50,
|
|
317
|
-
enableChunkSplitterV2: true,
|
|
318
|
-
usePluginSyncV2: true,
|
|
319
|
-
handleFilenameCaseSensitive: false,
|
|
320
|
-
doNotUseFixedRevisionForChunks: false,
|
|
321
|
-
E2EEAlgorithm: E2EEAlgorithms.V2,
|
|
322
|
-
chunkSplitterVersion: ChunkAlgorithms.RabinKarp
|
|
323
|
-
};
|
|
324
|
-
var TweakValuesDefault = {
|
|
325
|
-
usePluginSyncV2: false,
|
|
326
|
-
E2EEAlgorithm: DEFAULT_SETTINGS.E2EEAlgorithm,
|
|
327
|
-
chunkSplitterVersion: DEFAULT_SETTINGS.chunkSplitterVersion
|
|
328
|
-
};
|
|
329
|
-
var TweakValuesTemplate = { ...TweakValuesRecommendedTemplate, ...TweakValuesShouldMatchedTemplate };
|
|
330
|
-
var FlagFilesOriginal = {
|
|
331
|
-
SUSPEND_ALL: "redflag.md",
|
|
332
|
-
REBUILD_ALL: "redflag2.md",
|
|
333
|
-
FETCH_ALL: "redflag3.md"
|
|
334
|
-
};
|
|
335
|
-
var FlagFilesHumanReadable = {
|
|
336
|
-
REBUILD_ALL: "flag_rebuild.md",
|
|
337
|
-
FETCH_ALL: "flag_fetch.md"
|
|
338
|
-
};
|
|
339
|
-
var FLAGMD_REDFLAG = FlagFilesOriginal.SUSPEND_ALL;
|
|
340
|
-
var FLAGMD_REDFLAG2 = FlagFilesOriginal.REBUILD_ALL;
|
|
341
|
-
var FLAGMD_REDFLAG2_HR = FlagFilesHumanReadable.REBUILD_ALL;
|
|
342
|
-
var FLAGMD_REDFLAG3 = FlagFilesOriginal.FETCH_ALL;
|
|
343
|
-
var FLAGMD_REDFLAG3_HR = FlagFilesHumanReadable.FETCH_ALL;
|
|
344
|
-
var SYNCINFO_ID = "syncinfo";
|
|
345
|
-
var SALT_OF_ID = "a83hrf7fy7sa8g31";
|
|
346
|
-
var SEED_MURMURHASH = 305419896;
|
|
347
|
-
var IDPrefixes = {
|
|
348
|
-
Obfuscated: "f:",
|
|
349
|
-
Chunk: "h:",
|
|
350
|
-
EncryptedChunk: "h:+"
|
|
351
|
-
};
|
|
352
|
-
var PREFIX_OBFUSCATED = "f:";
|
|
353
|
-
var PREFIX_ENCRYPTED_CHUNK = "h:+";
|
|
354
|
-
var ProtocolVersions = {
|
|
355
|
-
UNSET: void 0,
|
|
356
|
-
LEGACY: 1,
|
|
357
|
-
ADVANCED_E2EE: 2
|
|
358
|
-
};
|
|
359
|
-
var DOCID_SYNC_PARAMETERS = "_local/obsidian_livesync_sync_parameters";
|
|
360
|
-
var DEFAULT_SYNC_PARAMETERS = {
|
|
361
|
-
_id: DOCID_SYNC_PARAMETERS,
|
|
362
|
-
type: EntryTypes["SYNC_PARAMETERS"],
|
|
363
|
-
protocolVersion: ProtocolVersions.ADVANCED_E2EE,
|
|
364
|
-
pbkdf2salt: ""
|
|
365
|
-
};
|
|
366
|
-
|
|
367
|
-
// lib/livesync-commonlib/src/memory/LRUCache.ts
|
|
368
|
-
var LRUCache_exports = {};
|
|
369
|
-
__reExport(LRUCache_exports, LRUCache_star);
|
|
370
|
-
import * as LRUCache_star from "octagonal-wheels/memory/LRUCache";
|
|
371
|
-
|
|
372
|
-
// lib/livesync-commonlib/src/common/utils.ts
|
|
373
|
-
import { Semaphore } from "octagonal-wheels/concurrency/semaphore";
|
|
374
|
-
|
|
375
|
-
// lib/livesync-commonlib/src/string_and_binary/convert.ts
|
|
376
|
-
import {
|
|
377
|
-
arrayBufferToBase64,
|
|
378
|
-
base64ToArrayBuffer,
|
|
379
|
-
base64ToArrayBufferInternalBrowser,
|
|
380
|
-
arrayBufferToBase64Single,
|
|
381
|
-
readString,
|
|
382
|
-
writeString,
|
|
383
|
-
tryConvertBase64ToArrayBuffer
|
|
384
|
-
} from "octagonal-wheels/binary";
|
|
385
|
-
import { uint8ArrayToHexString, hexStringToUint8Array } from "octagonal-wheels/binary/hex";
|
|
386
|
-
import { encodeBinaryEach, decodeToArrayBuffer } from "octagonal-wheels/binary/encodedUTF16";
|
|
387
|
-
import { decodeBinary, encodeBinary } from "octagonal-wheels/binary";
|
|
388
|
-
import { escapeStringToHTML } from "octagonal-wheels/string";
|
|
389
|
-
|
|
390
|
-
// lib/livesync-commonlib/src/pouchdb/utils_couchdb.ts
|
|
391
|
-
function isErrorOfMissingDoc(ex) {
|
|
392
|
-
return (ex && ex?.status) == 404;
|
|
393
|
-
}
|
|
394
|
-
|
|
395
|
-
// lib/livesync-commonlib/src/common/utils.ts
|
|
396
|
-
import { replaceAll, replaceAllPairs } from "octagonal-wheels/string";
|
|
397
|
-
import { concatUInt8Array } from "octagonal-wheels/binary";
|
|
398
|
-
import { delay, fireAndForget } from "octagonal-wheels/promises";
|
|
399
|
-
import { arrayToChunkedArray, unique } from "octagonal-wheels/collection";
|
|
400
|
-
import { extractObject, isObjectDifferent } from "octagonal-wheels/object";
|
|
401
|
-
import { sendValue, sendSignal, waitForSignal, waitForValue } from "octagonal-wheels/messagepassing/signal";
|
|
402
|
-
import { throttle } from "octagonal-wheels/function";
|
|
403
|
-
import { sizeToHumanReadable } from "octagonal-wheels/number";
|
|
404
|
-
function getDocData(doc) {
|
|
405
|
-
return typeof doc == "string" ? doc : doc.join("");
|
|
406
|
-
}
|
|
407
|
-
function isTextBlob(blob) {
|
|
408
|
-
return blob.type === "text/plain";
|
|
409
|
-
}
|
|
410
|
-
function createTextBlob(data) {
|
|
411
|
-
const d = Array.isArray(data) ? data : [data];
|
|
412
|
-
return new Blob(d, { endings: "transparent", type: "text/plain" });
|
|
413
|
-
}
|
|
414
|
-
function createBinaryBlob(data) {
|
|
415
|
-
return new Blob([data], { endings: "transparent", type: "application/octet-stream" });
|
|
416
|
-
}
|
|
417
|
-
function createBlob(data) {
|
|
418
|
-
if (data instanceof Blob) return data;
|
|
419
|
-
if (data instanceof Uint8Array || data instanceof ArrayBuffer) return createBinaryBlob(data);
|
|
420
|
-
return createTextBlob(data);
|
|
421
|
-
}
|
|
422
|
-
var isIndexDBCmpExist = typeof globalThis?.indexedDB?.cmp !== "undefined";
|
|
423
|
-
function isObfuscatedEntry(doc) {
|
|
424
|
-
if (doc._id.startsWith(PREFIX_OBFUSCATED)) {
|
|
425
|
-
return true;
|
|
426
|
-
}
|
|
427
|
-
return false;
|
|
428
|
-
}
|
|
429
|
-
function isEncryptedChunkEntry(doc) {
|
|
430
|
-
if (doc._id.startsWith(PREFIX_ENCRYPTED_CHUNK)) {
|
|
431
|
-
return true;
|
|
432
|
-
}
|
|
433
|
-
return false;
|
|
434
|
-
}
|
|
435
|
-
function isSyncInfoEntry(doc) {
|
|
436
|
-
if (doc._id == SYNCINFO_ID) {
|
|
437
|
-
return true;
|
|
438
|
-
}
|
|
439
|
-
return false;
|
|
440
|
-
}
|
|
441
|
-
function memorizeFuncWithLRUCache(func) {
|
|
442
|
-
const cache = new LRUCache_exports.LRUCache(100, 1e5, true);
|
|
443
|
-
return (key) => {
|
|
444
|
-
const isExists = cache.has(key);
|
|
445
|
-
if (isExists) return cache.get(key);
|
|
446
|
-
const value = func(key);
|
|
447
|
-
cache.set(key, value);
|
|
448
|
-
return value;
|
|
449
|
-
};
|
|
450
|
-
}
|
|
451
|
-
var globalConcurrencyController = Semaphore(50);
|
|
452
|
-
function determineTypeFromBlob(data) {
|
|
453
|
-
return isTextBlob(data) ? "plain" : "newnote";
|
|
454
|
-
}
|
|
455
|
-
function isSensibleMargeApplicable(path) {
|
|
456
|
-
if (path.endsWith(".md")) return true;
|
|
457
|
-
return false;
|
|
458
|
-
}
|
|
459
|
-
function isObjectMargeApplicable(path) {
|
|
460
|
-
if (path.endsWith(".canvas")) return true;
|
|
461
|
-
if (path.endsWith(".json")) return true;
|
|
462
|
-
return false;
|
|
463
|
-
}
|
|
464
|
-
function tryParseJSON(str, fallbackValue) {
|
|
465
|
-
try {
|
|
466
|
-
return JSON.parse(str);
|
|
467
|
-
} catch {
|
|
468
|
-
return fallbackValue;
|
|
469
|
-
}
|
|
470
|
-
}
|
|
471
|
-
var MARK_OPERATOR = ``;
|
|
472
|
-
var MARK_DELETED = `${MARK_OPERATOR}__DELETED`;
|
|
473
|
-
var MARK_ISARRAY = `${MARK_OPERATOR}__ARRAY`;
|
|
474
|
-
var MARK_SWAPPED = `${MARK_OPERATOR}__SWAP`;
|
|
475
|
-
function unorderedArrayToObject(obj) {
|
|
476
|
-
return obj.map((e) => ({ [e.id]: e })).reduce((p, c) => ({ ...p, ...c }), {});
|
|
477
|
-
}
|
|
478
|
-
function objectToUnorderedArray(obj) {
|
|
479
|
-
const entries = Object.entries(obj);
|
|
480
|
-
if (entries.some((e) => e[0] != e[1]?.id)) throw new Error("Item looks like not unordered array");
|
|
481
|
-
return entries.map((e) => e[1]);
|
|
482
|
-
}
|
|
483
|
-
function generatePatchUnorderedArray(from, to) {
|
|
484
|
-
if (from.every((e) => typeof e == "object" && "id" in e) && to.every((e) => typeof e == "object" && "id" in e)) {
|
|
485
|
-
const fObj = unorderedArrayToObject(from);
|
|
486
|
-
const tObj = unorderedArrayToObject(to);
|
|
487
|
-
const diff = generatePatchObj(fObj, tObj);
|
|
488
|
-
if (Object.keys(diff).length > 0) {
|
|
489
|
-
return { [MARK_ISARRAY]: diff };
|
|
490
|
-
} else {
|
|
491
|
-
return {};
|
|
492
|
-
}
|
|
493
|
-
}
|
|
494
|
-
return { [MARK_SWAPPED]: to };
|
|
495
|
-
}
|
|
496
|
-
function generatePatchObj(from, to) {
|
|
497
|
-
const entries = Object.entries(from);
|
|
498
|
-
const tempMap = new Map(entries);
|
|
499
|
-
const ret = {};
|
|
500
|
-
const newEntries = Object.entries(to);
|
|
501
|
-
for (const [key, value] of newEntries) {
|
|
502
|
-
if (!tempMap.has(key)) {
|
|
503
|
-
ret[key] = value;
|
|
504
|
-
tempMap.delete(key);
|
|
505
|
-
} else {
|
|
506
|
-
const v = tempMap.get(key);
|
|
507
|
-
if (typeof v !== typeof value || Array.isArray(v) !== Array.isArray(value)) {
|
|
508
|
-
ret[key] = { [MARK_SWAPPED]: value };
|
|
509
|
-
} else {
|
|
510
|
-
if (v === null && value === null) {
|
|
511
|
-
} else if (v === null && value !== null) {
|
|
512
|
-
ret[key] = { [MARK_SWAPPED]: value };
|
|
513
|
-
} else if (v !== null && value === null) {
|
|
514
|
-
ret[key] = { [MARK_SWAPPED]: value };
|
|
515
|
-
} else if (typeof v == "object" && typeof value == "object" && !Array.isArray(v) && !Array.isArray(value)) {
|
|
516
|
-
const wk = generatePatchObj(v, value);
|
|
517
|
-
if (Object.keys(wk).length > 0) ret[key] = wk;
|
|
518
|
-
} else if (typeof v == "object" && typeof value == "object" && Array.isArray(v) && Array.isArray(value)) {
|
|
519
|
-
const wk = generatePatchUnorderedArray(v, value);
|
|
520
|
-
if (Object.keys(wk).length > 0) ret[key] = wk;
|
|
521
|
-
} else if (typeof v != "object" && typeof value != "object") {
|
|
522
|
-
if (JSON.stringify(tempMap.get(key)) !== JSON.stringify(value)) {
|
|
523
|
-
ret[key] = value;
|
|
524
|
-
}
|
|
525
|
-
} else {
|
|
526
|
-
if (JSON.stringify(tempMap.get(key)) !== JSON.stringify(value)) {
|
|
527
|
-
ret[key] = { [MARK_SWAPPED]: value };
|
|
528
|
-
}
|
|
529
|
-
}
|
|
530
|
-
}
|
|
531
|
-
tempMap.delete(key);
|
|
532
|
-
}
|
|
533
|
-
}
|
|
534
|
-
for (const [key] of tempMap) {
|
|
535
|
-
ret[key] = MARK_DELETED;
|
|
536
|
-
}
|
|
537
|
-
return ret;
|
|
538
|
-
}
|
|
539
|
-
function applyPatch(from, patch) {
|
|
540
|
-
const ret = from;
|
|
541
|
-
const patches = Object.entries(patch);
|
|
542
|
-
for (const [key, value] of patches) {
|
|
543
|
-
if (value == MARK_DELETED) {
|
|
544
|
-
delete ret[key];
|
|
545
|
-
continue;
|
|
546
|
-
}
|
|
547
|
-
if (value === null) {
|
|
548
|
-
ret[key] = null;
|
|
549
|
-
continue;
|
|
550
|
-
}
|
|
551
|
-
if (typeof value == "object") {
|
|
552
|
-
if (MARK_SWAPPED in value) {
|
|
553
|
-
ret[key] = value[MARK_SWAPPED];
|
|
554
|
-
continue;
|
|
555
|
-
}
|
|
556
|
-
if (MARK_ISARRAY in value) {
|
|
557
|
-
if (!(key in ret)) ret[key] = [];
|
|
558
|
-
if (!Array.isArray(ret[key])) {
|
|
559
|
-
throw new Error("Patch target type is mismatched (array to something)");
|
|
560
|
-
}
|
|
561
|
-
const orgArrayObject = unorderedArrayToObject(ret[key]);
|
|
562
|
-
const appliedObject = applyPatch(orgArrayObject, value[MARK_ISARRAY]);
|
|
563
|
-
const appliedArray = objectToUnorderedArray(appliedObject);
|
|
564
|
-
ret[key] = [...appliedArray];
|
|
565
|
-
} else {
|
|
566
|
-
if (!(key in ret)) {
|
|
567
|
-
ret[key] = value;
|
|
568
|
-
continue;
|
|
569
|
-
}
|
|
570
|
-
ret[key] = applyPatch(ret[key], value);
|
|
571
|
-
}
|
|
572
|
-
} else {
|
|
573
|
-
ret[key] = value;
|
|
574
|
-
}
|
|
575
|
-
}
|
|
576
|
-
return ret;
|
|
577
|
-
}
|
|
578
|
-
function flattenObject(obj, path = []) {
|
|
579
|
-
if (typeof obj != "object") return [[path.join("."), obj]];
|
|
580
|
-
if (obj === null) return [[path.join("."), null]];
|
|
581
|
-
if (Array.isArray(obj)) return [[path.join("."), JSON.stringify(obj)]];
|
|
582
|
-
const e = Object.entries(obj);
|
|
583
|
-
const ret = [];
|
|
584
|
-
for (const [key, value] of e) {
|
|
585
|
-
const p = flattenObject(value, [...path, key]);
|
|
586
|
-
ret.push(...p);
|
|
587
|
-
}
|
|
588
|
-
return ret;
|
|
589
|
-
}
|
|
590
|
-
function parseCustomRegExp(regexp) {
|
|
591
|
-
if (regexp.startsWith("!!")) {
|
|
592
|
-
return [true, regexp.slice(2)];
|
|
593
|
-
}
|
|
594
|
-
return [false, regexp];
|
|
595
|
-
}
|
|
596
|
-
function parseCustomRegExpList(list, flags, delimiter) {
|
|
597
|
-
const d = delimiter ?? ",";
|
|
598
|
-
const items = list.replace(/\n| /g, "").split(d).filter((e) => e);
|
|
599
|
-
return items.map((e) => new CustomRegExp(e, flags));
|
|
600
|
-
}
|
|
601
|
-
var CustomRegExp = class {
|
|
602
|
-
regexp;
|
|
603
|
-
negate;
|
|
604
|
-
pattern;
|
|
605
|
-
constructor(regexp, flags) {
|
|
606
|
-
const [negate, exp] = parseCustomRegExp(regexp);
|
|
607
|
-
this.pattern = exp;
|
|
608
|
-
this.regexp = new RegExp(exp, flags);
|
|
609
|
-
this.negate = negate;
|
|
610
|
-
}
|
|
611
|
-
test(str) {
|
|
612
|
-
return this.negate ? !this.regexp.test(str) : this.regexp.test(str);
|
|
613
|
-
}
|
|
614
|
-
};
|
|
615
|
-
function getFileRegExp(settings, key) {
|
|
616
|
-
const flagCase = settings.handleFilenameCaseSensitive ? "" : "i";
|
|
617
|
-
if (key === "syncInternalFilesIgnorePatterns" || key === "syncInternalFilesTargetPatterns") {
|
|
618
|
-
const regExp2 = settings[key];
|
|
619
|
-
return parseCustomRegExpList(regExp2, flagCase, ",");
|
|
620
|
-
}
|
|
621
|
-
const regExp = settings[key];
|
|
622
|
-
return parseCustomRegExpList(regExp, flagCase, "|[]|");
|
|
623
|
-
}
|
|
624
|
-
|
|
625
|
-
// lib/livesync-commonlib/src/string_and_binary/path.ts
|
|
626
|
-
import { unique as unique2 } from "octagonal-wheels/collection.js";
|
|
627
|
-
function isFilePath(path) {
|
|
628
|
-
if (path.indexOf(":") === -1) return true;
|
|
629
|
-
return false;
|
|
630
|
-
}
|
|
631
|
-
function stripAllPrefixes(prefixedPath) {
|
|
632
|
-
if (isFilePath(prefixedPath)) return prefixedPath;
|
|
633
|
-
const [, body] = expandFilePathPrefix(prefixedPath);
|
|
634
|
-
return stripAllPrefixes(body);
|
|
635
|
-
}
|
|
636
|
-
function addPrefix(path, prefix) {
|
|
637
|
-
if (prefix && path.startsWith(prefix)) return path;
|
|
638
|
-
return `${prefix ?? ""}${path}`;
|
|
639
|
-
}
|
|
640
|
-
function expandFilePathPrefix(path) {
|
|
641
|
-
let [prefix, body] = path.split(":", 2);
|
|
642
|
-
if (!body) {
|
|
643
|
-
body = prefix;
|
|
644
|
-
prefix = "";
|
|
645
|
-
} else {
|
|
646
|
-
prefix = prefix + ":";
|
|
647
|
-
}
|
|
648
|
-
return [prefix, body];
|
|
649
|
-
}
|
|
650
|
-
function expandDocumentIDPrefix(id) {
|
|
651
|
-
let [prefix, body] = id.split(":", 2);
|
|
652
|
-
if (!body) {
|
|
653
|
-
body = prefix;
|
|
654
|
-
prefix = "";
|
|
655
|
-
} else {
|
|
656
|
-
prefix = prefix + ":";
|
|
657
|
-
}
|
|
658
|
-
return [prefix, body];
|
|
659
|
-
}
|
|
660
|
-
var _hashString = memorizeFuncWithLRUCache(async (key) => {
|
|
661
|
-
const buff = writeString(key);
|
|
662
|
-
const webcrypto2 = await getWebCrypto();
|
|
663
|
-
let digest = await webcrypto2.subtle.digest("SHA-256", buff);
|
|
664
|
-
const len = key.length;
|
|
665
|
-
for (let i = 0; i < len; i++) {
|
|
666
|
-
digest = await webcrypto2.subtle.digest("SHA-256", buff);
|
|
667
|
-
}
|
|
668
|
-
return uint8ArrayToHexString(new Uint8Array(digest));
|
|
669
|
-
});
|
|
670
|
-
function hashString(key) {
|
|
671
|
-
return _hashString(key);
|
|
672
|
-
}
|
|
673
|
-
async function path2id_base(filenameSrc, obfuscatePassphrase, caseInsensitive) {
|
|
674
|
-
if (filenameSrc.startsWith(PREFIX_OBFUSCATED)) return `${filenameSrc}`;
|
|
675
|
-
let filename = `${filenameSrc}`;
|
|
676
|
-
const newPrefix = obfuscatePassphrase ? PREFIX_OBFUSCATED : "";
|
|
677
|
-
if (caseInsensitive) {
|
|
678
|
-
filename = filename.toLowerCase();
|
|
679
|
-
}
|
|
680
|
-
let x = filename;
|
|
681
|
-
if (x.startsWith("_")) x = "/" + x;
|
|
682
|
-
if (!obfuscatePassphrase) {
|
|
683
|
-
return newPrefix + x;
|
|
684
|
-
}
|
|
685
|
-
const [prefix, body] = expandFilePathPrefix(x);
|
|
686
|
-
if (body.startsWith(PREFIX_OBFUSCATED)) return newPrefix + x;
|
|
687
|
-
const hashedPassphrase = await hashString(obfuscatePassphrase);
|
|
688
|
-
const out = await hashString(`${hashedPassphrase}:${filename}`);
|
|
689
|
-
return prefix + newPrefix + out;
|
|
690
|
-
}
|
|
691
|
-
function id2path_base(id, entry) {
|
|
692
|
-
if (entry && entry?.path) {
|
|
693
|
-
return id2path_base(entry.path);
|
|
694
|
-
}
|
|
695
|
-
if (id.startsWith(PREFIX_OBFUSCATED)) throw new Error("Entry has been obfuscated!");
|
|
696
|
-
const [prefix, body] = expandDocumentIDPrefix(id);
|
|
697
|
-
if (body.startsWith(PREFIX_OBFUSCATED)) throw new Error("Entry has been obfuscated!");
|
|
698
|
-
if (body.startsWith("/")) {
|
|
699
|
-
return body.substring(1);
|
|
700
|
-
}
|
|
701
|
-
return prefix + body;
|
|
702
|
-
}
|
|
703
|
-
function getPath(entry) {
|
|
704
|
-
return id2path_base(entry._id, entry);
|
|
705
|
-
}
|
|
706
|
-
function shouldSplitAsPlainText(filename) {
|
|
707
|
-
if (filename.endsWith(".md")) return true;
|
|
708
|
-
if (filename.endsWith(".txt")) return true;
|
|
709
|
-
if (filename.endsWith(".canvas")) return true;
|
|
710
|
-
return false;
|
|
711
|
-
}
|
|
712
|
-
|
|
713
|
-
// lib/livesync-commonlib/src/pouchdb/pouchdb-http.ts
|
|
714
|
-
import PouchDB from "pouchdb-core";
|
|
715
|
-
import HttpPouch from "pouchdb-adapter-http";
|
|
716
|
-
import mapreduce from "pouchdb-mapreduce";
|
|
717
|
-
import replication from "pouchdb-replication";
|
|
718
|
-
import find from "pouchdb-find";
|
|
719
|
-
import transform from "transform-pouch";
|
|
720
|
-
import { findPathToLeaf } from "pouchdb-merge";
|
|
721
|
-
import { adapterFun } from "pouchdb-utils";
|
|
722
|
-
import { createError, MISSING_DOC, UNKNOWN_ERROR } from "pouchdb-errors";
|
|
723
|
-
import { mapAllTasksWithConcurrencyLimit, unwrapTaskResult } from "octagonal-wheels/concurrency/task";
|
|
724
|
-
PouchDB.plugin(HttpPouch).plugin(mapreduce).plugin(replication).plugin(find).plugin(transform);
|
|
725
|
-
function appendPurgeSeqs(db, docs) {
|
|
726
|
-
return db.get("_local/purges").then(function(doc) {
|
|
727
|
-
for (const [docId, rev$$1] of docs) {
|
|
728
|
-
const purgeSeq = doc.purgeSeq + 1;
|
|
729
|
-
doc.purges.push({
|
|
730
|
-
docId,
|
|
731
|
-
rev: rev$$1,
|
|
732
|
-
purgeSeq
|
|
733
|
-
});
|
|
734
|
-
if (doc.purges.length > db.purged_infos_limit) {
|
|
735
|
-
doc.purges.splice(0, doc.purges.length - db.purged_infos_limit);
|
|
736
|
-
}
|
|
737
|
-
doc.purgeSeq = purgeSeq;
|
|
738
|
-
}
|
|
739
|
-
return doc;
|
|
740
|
-
}).catch(function(err) {
|
|
741
|
-
if (err.status !== 404) {
|
|
742
|
-
throw err;
|
|
743
|
-
}
|
|
744
|
-
return {
|
|
745
|
-
_id: "_local/purges",
|
|
746
|
-
purges: docs.map(([docId, rev$$1], idx) => ({
|
|
747
|
-
docId,
|
|
748
|
-
rev: rev$$1,
|
|
749
|
-
purgeSeq: idx
|
|
750
|
-
})),
|
|
751
|
-
purgeSeq: docs.length
|
|
752
|
-
};
|
|
753
|
-
}).then(function(doc) {
|
|
754
|
-
return db.put(doc);
|
|
755
|
-
});
|
|
756
|
-
}
|
|
757
|
-
PouchDB.prototype.purgeMulti = adapterFun(
|
|
758
|
-
"_purgeMulti",
|
|
759
|
-
function(docs, callback) {
|
|
760
|
-
if (typeof this._purge === "undefined") {
|
|
761
|
-
return callback(
|
|
762
|
-
//@ts-ignore: this ts-ignore might be hiding a `this` bug where we don't have "this" conext.
|
|
763
|
-
createError(UNKNOWN_ERROR, "Purge is not implemented in the " + this.adapter + " adapter.")
|
|
764
|
-
);
|
|
765
|
-
}
|
|
766
|
-
const self = this;
|
|
767
|
-
const tasks = docs.map(
|
|
768
|
-
(param) => () => new Promise((res, rej) => {
|
|
769
|
-
const [docId, rev$$1] = param;
|
|
770
|
-
self._getRevisionTree(docId, (error, revs) => {
|
|
771
|
-
if (error) {
|
|
772
|
-
return res([param, error]);
|
|
773
|
-
}
|
|
774
|
-
if (!revs) {
|
|
775
|
-
return res([param, createError(MISSING_DOC)]);
|
|
776
|
-
}
|
|
777
|
-
let path;
|
|
778
|
-
try {
|
|
779
|
-
path = findPathToLeaf(revs, rev$$1);
|
|
780
|
-
} catch (error2) {
|
|
781
|
-
return res([param, error2.message || error2]);
|
|
782
|
-
}
|
|
783
|
-
self._purge(docId, path, (error2, result) => {
|
|
784
|
-
if (error2) {
|
|
785
|
-
return res([param, error2]);
|
|
786
|
-
} else {
|
|
787
|
-
return res([param, result]);
|
|
788
|
-
}
|
|
789
|
-
});
|
|
790
|
-
});
|
|
791
|
-
})
|
|
792
|
-
);
|
|
793
|
-
(async () => {
|
|
794
|
-
const ret = await mapAllTasksWithConcurrencyLimit(1, tasks);
|
|
795
|
-
const retAll = ret.map((e) => unwrapTaskResult(e));
|
|
796
|
-
await appendPurgeSeqs(
|
|
797
|
-
self,
|
|
798
|
-
retAll.filter((e) => "ok" in e[1]).map((e) => e[0])
|
|
799
|
-
);
|
|
800
|
-
const result = Object.fromEntries(retAll.map((e) => [e[0][0], e[1]]));
|
|
801
|
-
return result;
|
|
802
|
-
})().then((result) => callback(void 0, result)).catch((error) => callback(error));
|
|
803
|
-
}
|
|
804
|
-
);
|
|
805
|
-
|
|
806
|
-
// lib/livesync-commonlib/src/common/logger.ts
|
|
807
|
-
var logger_exports = {};
|
|
808
|
-
__reExport(logger_exports, logger_star);
|
|
809
|
-
import * as logger_star from "octagonal-wheels/common/logger";
|
|
810
|
-
|
|
811
|
-
// lib/livesync-commonlib/src/managers/ChunkManager.ts
|
|
812
|
-
import { FallbackWeakRef } from "octagonal-wheels/common/polyfill";
|
|
813
|
-
import { promiseWithResolver } from "octagonal-wheels/promises";
|
|
814
|
-
|
|
815
|
-
// lib/livesync-commonlib/src/common/LSError.ts
|
|
816
|
-
var LiveSyncError = class _LiveSyncError extends Error {
|
|
817
|
-
name = this.constructor.name;
|
|
818
|
-
cause;
|
|
819
|
-
overrideStatus;
|
|
820
|
-
/**
|
|
821
|
-
* Returns the HTTP status code associated with the error, if available.
|
|
822
|
-
* If the error has a status property, it returns that; otherwise, it defaults to 500 (Internal Server Error).
|
|
823
|
-
* @returns {number} The HTTP status code.
|
|
824
|
-
*/
|
|
825
|
-
get status() {
|
|
826
|
-
if (this.overrideStatus !== void 0) {
|
|
827
|
-
return this.overrideStatus;
|
|
828
|
-
}
|
|
829
|
-
if (this.cause && "status" in this.cause) {
|
|
830
|
-
return this.cause.status;
|
|
831
|
-
}
|
|
832
|
-
return 500;
|
|
833
|
-
}
|
|
834
|
-
/**
|
|
835
|
-
* Constructs a new LiveSyncError instance.
|
|
836
|
-
* @param message The error message to be displayed.
|
|
837
|
-
*/
|
|
838
|
-
constructor(message, options) {
|
|
839
|
-
super(message);
|
|
840
|
-
if (options?.cause) {
|
|
841
|
-
this.cause = options.cause instanceof Error ? options.cause : new Error(`${options.cause}`);
|
|
842
|
-
}
|
|
843
|
-
if (options?.status !== void 0) {
|
|
844
|
-
this.overrideStatus = options.status;
|
|
845
|
-
}
|
|
846
|
-
}
|
|
847
|
-
/**
|
|
848
|
-
* Determines whether an error is caused by a specific error class.
|
|
849
|
-
* @param error The error to examine.
|
|
850
|
-
* @param errorClass The error class to compare against.
|
|
851
|
-
* @returns True if the error is caused by the specified error class; otherwise, false.
|
|
852
|
-
* @example
|
|
853
|
-
* LiveSyncError.isCausedBy(someSyncParamsFetchError, SyncParamsNotFoundError); // Returns true if the error is caused by SyncParamsNotFoundError; this is usually represented as SyncParamsFetchError at the uppermost layer.
|
|
854
|
-
*/
|
|
855
|
-
static isCausedBy(error, errorClass) {
|
|
856
|
-
if (!error) {
|
|
857
|
-
return false;
|
|
858
|
-
}
|
|
859
|
-
if (error instanceof errorClass) {
|
|
860
|
-
return true;
|
|
861
|
-
}
|
|
862
|
-
if (error.cause) {
|
|
863
|
-
return _LiveSyncError.isCausedBy(error.cause, errorClass);
|
|
864
|
-
}
|
|
865
|
-
return false;
|
|
866
|
-
}
|
|
867
|
-
/**
|
|
868
|
-
* Creates a new instance of the error class from an existing error.
|
|
869
|
-
* @param error The error to wrap.
|
|
870
|
-
* @returns A new instance of the error class with the original error's message and stack trace.
|
|
871
|
-
*/
|
|
872
|
-
static fromError(error) {
|
|
873
|
-
if (error instanceof this) {
|
|
874
|
-
return error;
|
|
875
|
-
}
|
|
876
|
-
const instance = new this(`${this.name}: ${error?.message}`, { cause: error });
|
|
877
|
-
if (error?.stack) {
|
|
878
|
-
instance.stack = error.stack;
|
|
879
|
-
} else {
|
|
880
|
-
instance.stack = new Error().stack;
|
|
881
|
-
}
|
|
882
|
-
return instance;
|
|
883
|
-
}
|
|
884
|
-
};
|
|
885
|
-
var LiveSyncFatalError = class extends LiveSyncError {
|
|
886
|
-
};
|
|
887
|
-
|
|
888
|
-
// lib/livesync-commonlib/src/managers/ChunkFetcher.ts
|
|
889
|
-
import { delay as delay2 } from "octagonal-wheels/promises";
|
|
890
|
-
import { unique as unique3 } from "octagonal-wheels/collection";
|
|
891
|
-
var EVENT_MISSING_CHUNKS = "missingChunks";
|
|
892
|
-
var EVENT_MISSING_CHUNK_REMOTE = "missingChunkRemote";
|
|
893
|
-
var BATCH_SIZE = 100;
|
|
894
|
-
var ChunkFetcher = class {
|
|
895
|
-
options;
|
|
896
|
-
get chunkManager() {
|
|
897
|
-
return this.options.chunkManager;
|
|
898
|
-
}
|
|
899
|
-
queue = [];
|
|
900
|
-
get interval() {
|
|
901
|
-
return this.options.settings.minimumIntervalOfReadChunksOnline || DEFAULT_SETTINGS.minimumIntervalOfReadChunksOnline;
|
|
902
|
-
}
|
|
903
|
-
get concurrency() {
|
|
904
|
-
return this.options.settings.concurrencyOfReadChunksOnline || DEFAULT_SETTINGS.concurrencyOfReadChunksOnline;
|
|
905
|
-
}
|
|
906
|
-
abort = new AbortController();
|
|
907
|
-
constructor(options) {
|
|
908
|
-
this.options = options;
|
|
909
|
-
this.chunkManager.addListener(EVENT_MISSING_CHUNKS, this.onEventHandler, {
|
|
910
|
-
signal: this.abort.signal
|
|
911
|
-
});
|
|
912
|
-
}
|
|
913
|
-
destroy() {
|
|
914
|
-
this.abort.abort();
|
|
915
|
-
this.queue = [];
|
|
916
|
-
}
|
|
917
|
-
onEventHandler = this.onEvent.bind(this);
|
|
918
|
-
onEvent(ids) {
|
|
919
|
-
this.queue = unique3([...this.queue, ...ids]);
|
|
920
|
-
if (this.canRequestMore()) {
|
|
921
|
-
setTimeout(() => void this.requestMissingChunks(), 1);
|
|
922
|
-
}
|
|
923
|
-
}
|
|
924
|
-
/**
|
|
925
|
-
* Processing requests
|
|
926
|
-
*/
|
|
927
|
-
currentProcessing = 0;
|
|
928
|
-
/**
|
|
929
|
-
* Time of the last request to the remote server.
|
|
930
|
-
* This is used to manage the interval between requests.
|
|
931
|
-
* Even if concurrency allows, every start of a request will ensure that the interval is respected.
|
|
932
|
-
*/
|
|
933
|
-
previousRequestTime = 0;
|
|
934
|
-
canRequestMore() {
|
|
935
|
-
return this.currentProcessing < this.concurrency && this.queue.length > 0;
|
|
936
|
-
}
|
|
937
|
-
async requestMissingChunks() {
|
|
938
|
-
if (!this.canRequestMore()) {
|
|
939
|
-
return;
|
|
940
|
-
}
|
|
941
|
-
try {
|
|
942
|
-
this.currentProcessing++;
|
|
943
|
-
const requestIDs = this.queue.splice(0, BATCH_SIZE);
|
|
944
|
-
const now = Date.now();
|
|
945
|
-
const timeSinceLastRequest = now - this.previousRequestTime;
|
|
946
|
-
this.previousRequestTime = now;
|
|
947
|
-
const timeToWait = Math.max(this.interval - timeSinceLastRequest, 0);
|
|
948
|
-
if (timeToWait > 0) await delay2(timeToWait);
|
|
949
|
-
const replicator = this.options.getActiveReplicator();
|
|
950
|
-
if (!replicator) {
|
|
951
|
-
(0, logger_exports.Logger)("No active replicator was found to request missing chunks.");
|
|
952
|
-
return;
|
|
953
|
-
}
|
|
954
|
-
const chunks = await replicator.fetchRemoteChunks(requestIDs, false);
|
|
955
|
-
if (!chunks) {
|
|
956
|
-
(0, logger_exports.Logger)(`No chunks were found for the following IDs: ${requestIDs.join(", ")}`);
|
|
957
|
-
for (const chunkID of requestIDs) {
|
|
958
|
-
this.chunkManager.emitEvent(EVENT_MISSING_CHUNK_REMOTE, chunkID);
|
|
959
|
-
}
|
|
960
|
-
return;
|
|
961
|
-
}
|
|
962
|
-
try {
|
|
963
|
-
(0, logger_exports.Logger)(`Writing fetched chunks (${chunks.length}) to the database...`);
|
|
964
|
-
const result = await this.chunkManager.write(
|
|
965
|
-
chunks,
|
|
966
|
-
{
|
|
967
|
-
skipCache: true,
|
|
968
|
-
force: true
|
|
969
|
-
// Force writing to ensure the chunks with existing _rev.
|
|
970
|
-
},
|
|
971
|
-
"ChunkFetcher"
|
|
972
|
-
);
|
|
973
|
-
if (result.result === true) {
|
|
974
|
-
for (const chunk of chunks) {
|
|
975
|
-
this.chunkManager.emitEvent(EVENT_CHUNK_FETCHED, chunk);
|
|
976
|
-
}
|
|
977
|
-
} else {
|
|
978
|
-
(0, logger_exports.Logger)(
|
|
979
|
-
`The fetched chunks could not be stored: ${chunks.map((chunk) => chunk._id).join(", ")}`,
|
|
980
|
-
logger_exports.LOG_LEVEL_VERBOSE
|
|
981
|
-
);
|
|
982
|
-
for (const chunkID of requestIDs) {
|
|
983
|
-
this.chunkManager.emitEvent(EVENT_MISSING_CHUNK_REMOTE, chunkID);
|
|
984
|
-
}
|
|
985
|
-
}
|
|
986
|
-
} catch (error) {
|
|
987
|
-
(0, logger_exports.Logger)(`An error occurred while storing fetched chunks: ${error}`, logger_exports.LOG_LEVEL_VERBOSE);
|
|
988
|
-
for (const chunkID of requestIDs) {
|
|
989
|
-
this.chunkManager.emitEvent(EVENT_MISSING_CHUNK_REMOTE, chunkID);
|
|
990
|
-
}
|
|
991
|
-
}
|
|
992
|
-
} finally {
|
|
993
|
-
this.currentProcessing--;
|
|
994
|
-
this.previousRequestTime = Date.now();
|
|
995
|
-
if (this.queue.length > 0) {
|
|
996
|
-
setTimeout(() => void this.requestMissingChunks(), 0);
|
|
997
|
-
}
|
|
998
|
-
}
|
|
999
|
-
}
|
|
1000
|
-
};
|
|
1001
|
-
|
|
1002
|
-
// lib/livesync-commonlib/src/managers/ChunkManager.ts
|
|
1003
|
-
var DEFAULT_MAX_CACHE_SIZE = 1e5;
|
|
1004
|
-
function buildChunkMap(chunks) {
|
|
1005
|
-
const map = /* @__PURE__ */ new Map();
|
|
1006
|
-
for (const chunk of chunks) {
|
|
1007
|
-
map.set(chunk._id, chunk);
|
|
1008
|
-
}
|
|
1009
|
-
return map;
|
|
1010
|
-
}
|
|
1011
|
-
var DEFAULT_TIMEOUT = 15e3;
|
|
1012
|
-
function withTimeout(proc, timeout, onTimedOut) {
|
|
1013
|
-
return new Promise((resolve, reject) => {
|
|
1014
|
-
const timer = setTimeout(() => {
|
|
1015
|
-
resolve(onTimedOut());
|
|
1016
|
-
}, timeout);
|
|
1017
|
-
proc.then(resolve).catch(reject).finally(() => {
|
|
1018
|
-
clearTimeout(timer);
|
|
1019
|
-
});
|
|
1020
|
-
});
|
|
1021
|
-
}
|
|
1022
|
-
function getError(error) {
|
|
1023
|
-
if (error instanceof Error) {
|
|
1024
|
-
return error;
|
|
1025
|
-
}
|
|
1026
|
-
if ("error" in error && error.error instanceof Error) {
|
|
1027
|
-
return error.error;
|
|
1028
|
-
}
|
|
1029
|
-
return void 0;
|
|
1030
|
-
}
|
|
1031
|
-
function isMissingError(error) {
|
|
1032
|
-
if ("status" in error && error.status === 404) {
|
|
1033
|
-
return true;
|
|
1034
|
-
}
|
|
1035
|
-
if ("error" in error && error.error === "not_found") {
|
|
1036
|
-
return true;
|
|
1037
|
-
}
|
|
1038
|
-
if ("error" in error) {
|
|
1039
|
-
return isMissingError(error.error);
|
|
1040
|
-
}
|
|
1041
|
-
return false;
|
|
1042
|
-
}
|
|
1043
|
-
function isChunkDoc(doc) {
|
|
1044
|
-
return doc && typeof doc._id === "string" && doc.type === "leaf";
|
|
1045
|
-
}
|
|
1046
|
-
var EVENT_CHUNK_FETCHED = "chunkFetched";
|
|
1047
|
-
var ChunkManager = class {
|
|
1048
|
-
options;
|
|
1049
|
-
eventTarget = new EventTarget();
|
|
1050
|
-
get changeManager() {
|
|
1051
|
-
return this.options.changeManager;
|
|
1052
|
-
}
|
|
1053
|
-
get database() {
|
|
1054
|
-
return this.options.database;
|
|
1055
|
-
}
|
|
1056
|
-
maxCacheSize = DEFAULT_MAX_CACHE_SIZE;
|
|
1057
|
-
// Maximum cache size
|
|
1058
|
-
caches = /* @__PURE__ */ new Map();
|
|
1059
|
-
// Map for cache
|
|
1060
|
-
addListener(type, listener, options) {
|
|
1061
|
-
const callback = (ev) => {
|
|
1062
|
-
listener.call(this, ev.detail);
|
|
1063
|
-
};
|
|
1064
|
-
this.eventTarget.addEventListener(type, callback, options);
|
|
1065
|
-
return () => {
|
|
1066
|
-
this.eventTarget.removeEventListener(type, callback, options);
|
|
1067
|
-
};
|
|
1068
|
-
}
|
|
1069
|
-
emitEvent(type, detail) {
|
|
1070
|
-
const event = new CustomEvent(type, { detail });
|
|
1071
|
-
this.eventTarget.dispatchEvent(event);
|
|
1072
|
-
}
|
|
1073
|
-
waitingMap = /* @__PURE__ */ new Map();
|
|
1074
|
-
// Queue for pending reads
|
|
1075
|
-
allocCount = 0;
|
|
1076
|
-
// Count of allocated chunks
|
|
1077
|
-
derefCount = 0;
|
|
1078
|
-
// Count of dereferenced chunks
|
|
1079
|
-
clearCaches() {
|
|
1080
|
-
this.caches.clear();
|
|
1081
|
-
this.allocCount = 0;
|
|
1082
|
-
this.derefCount = 0;
|
|
1083
|
-
}
|
|
1084
|
-
getCachedChunk(id) {
|
|
1085
|
-
if (!this.caches.has(id)) {
|
|
1086
|
-
return false;
|
|
1087
|
-
}
|
|
1088
|
-
const weakRef = this.caches.get(id);
|
|
1089
|
-
if (weakRef) {
|
|
1090
|
-
const cachedChunk = weakRef.deref();
|
|
1091
|
-
if (cachedChunk) {
|
|
1092
|
-
return cachedChunk;
|
|
1093
|
-
} else {
|
|
1094
|
-
this.derefCount++;
|
|
1095
|
-
this.deleteCachedChunk(id);
|
|
1096
|
-
return false;
|
|
1097
|
-
}
|
|
1098
|
-
}
|
|
1099
|
-
return false;
|
|
1100
|
-
}
|
|
1101
|
-
getChunkIDFromCache(data) {
|
|
1102
|
-
for (const [id, weakRef] of this.caches) {
|
|
1103
|
-
const chunk = weakRef.deref();
|
|
1104
|
-
if (chunk) {
|
|
1105
|
-
if (chunk.data === data) {
|
|
1106
|
-
return id;
|
|
1107
|
-
}
|
|
1108
|
-
} else {
|
|
1109
|
-
this.derefCount++;
|
|
1110
|
-
this.deleteCachedChunk(id);
|
|
1111
|
-
}
|
|
1112
|
-
}
|
|
1113
|
-
return false;
|
|
1114
|
-
}
|
|
1115
|
-
cacheChunk(chunk) {
|
|
1116
|
-
if (this.getCachedChunk(chunk._id)) {
|
|
1117
|
-
this.reorderChunk(chunk._id);
|
|
1118
|
-
return;
|
|
1119
|
-
}
|
|
1120
|
-
this.caches.set(chunk._id, new FallbackWeakRef(chunk));
|
|
1121
|
-
this.allocCount++;
|
|
1122
|
-
const maxCacheSize = this.maxCacheSize ?? DEFAULT_MAX_CACHE_SIZE;
|
|
1123
|
-
if (this.caches.size > maxCacheSize) {
|
|
1124
|
-
do {
|
|
1125
|
-
const firstKey = this.caches.keys().next().value;
|
|
1126
|
-
if (firstKey) {
|
|
1127
|
-
this.caches.delete(firstKey);
|
|
1128
|
-
}
|
|
1129
|
-
} while (this.caches.size > maxCacheSize);
|
|
1130
|
-
}
|
|
1131
|
-
}
|
|
1132
|
-
reorderChunk(id) {
|
|
1133
|
-
const chunk = this.getCachedChunk(id);
|
|
1134
|
-
if (chunk) {
|
|
1135
|
-
this.caches.delete(id);
|
|
1136
|
-
this.caches.set(id, new FallbackWeakRef(chunk));
|
|
1137
|
-
}
|
|
1138
|
-
}
|
|
1139
|
-
deleteCachedChunk(id) {
|
|
1140
|
-
if (this.caches.has(id)) {
|
|
1141
|
-
this.caches.delete(id);
|
|
1142
|
-
}
|
|
1143
|
-
}
|
|
1144
|
-
_enqueueWaiting(id, timeout) {
|
|
1145
|
-
const previous = this.waitingMap.get(id);
|
|
1146
|
-
if (previous) {
|
|
1147
|
-
return previous.resolver.promise;
|
|
1148
|
-
}
|
|
1149
|
-
const resolver = promiseWithResolver();
|
|
1150
|
-
this.waitingMap.set(id, { resolver });
|
|
1151
|
-
return withTimeout(resolver.promise, timeout, () => {
|
|
1152
|
-
const current = this.waitingMap.get(id);
|
|
1153
|
-
if (current && current.resolver === resolver) {
|
|
1154
|
-
this.waitingMap.delete(id);
|
|
1155
|
-
}
|
|
1156
|
-
return false;
|
|
1157
|
-
});
|
|
1158
|
-
}
|
|
1159
|
-
onChunkArrived(doc, deleted = false) {
|
|
1160
|
-
const id = doc._id;
|
|
1161
|
-
if (this.waitingMap.has(id)) {
|
|
1162
|
-
const queue = this.waitingMap.get(id);
|
|
1163
|
-
this.waitingMap.delete(id);
|
|
1164
|
-
if (doc._deleted || deleted) {
|
|
1165
|
-
queue.resolver.resolve(false);
|
|
1166
|
-
} else {
|
|
1167
|
-
queue.resolver.resolve(doc);
|
|
1168
|
-
this.cacheChunk(doc);
|
|
1169
|
-
}
|
|
1170
|
-
} else {
|
|
1171
|
-
}
|
|
1172
|
-
}
|
|
1173
|
-
onChunkArrivedHandler = this.onChunkArrived.bind(this);
|
|
1174
|
-
onChange(change) {
|
|
1175
|
-
const doc = change.doc;
|
|
1176
|
-
if (!doc || !doc._id) {
|
|
1177
|
-
return;
|
|
1178
|
-
}
|
|
1179
|
-
if (doc.type !== "leaf") {
|
|
1180
|
-
return;
|
|
1181
|
-
}
|
|
1182
|
-
this.onChunkArrived(doc, change.deleted);
|
|
1183
|
-
}
|
|
1184
|
-
onChangeHandler = this.onChange.bind(this);
|
|
1185
|
-
onMissingChunkRemote(id) {
|
|
1186
|
-
if (this.waitingMap.has(id)) {
|
|
1187
|
-
const queue = this.waitingMap.get(id);
|
|
1188
|
-
this.waitingMap.delete(id);
|
|
1189
|
-
queue.resolver.resolve(false);
|
|
1190
|
-
}
|
|
1191
|
-
}
|
|
1192
|
-
onMissingChunkRemoteHandler = this.onMissingChunkRemote.bind(this);
|
|
1193
|
-
abort = new AbortController();
|
|
1194
|
-
changeHandler;
|
|
1195
|
-
initialised = Promise.resolve();
|
|
1196
|
-
async _initialise() {
|
|
1197
|
-
(0, logger_exports.Logger)("ChunkManager initialised", logger_exports.LOG_LEVEL_VERBOSE);
|
|
1198
|
-
return await Promise.resolve();
|
|
1199
|
-
}
|
|
1200
|
-
constructor(options) {
|
|
1201
|
-
this.options = options;
|
|
1202
|
-
this.caches = /* @__PURE__ */ new Map();
|
|
1203
|
-
this.changeHandler = this.changeManager.addCallback(this.onChangeHandler);
|
|
1204
|
-
this.addListener(EVENT_CHUNK_FETCHED, this.onChunkArrivedHandler, { signal: this.abort.signal });
|
|
1205
|
-
this.addListener(EVENT_MISSING_CHUNK_REMOTE, this.onMissingChunkRemoteHandler, { signal: this.abort.signal });
|
|
1206
|
-
this.initialised = this._initialise();
|
|
1207
|
-
}
|
|
1208
|
-
destroy() {
|
|
1209
|
-
this.abort.abort();
|
|
1210
|
-
this.changeHandler();
|
|
1211
|
-
this.caches.clear();
|
|
1212
|
-
this.waitingMap.clear();
|
|
1213
|
-
}
|
|
1214
|
-
async readSingle(id, options) {
|
|
1215
|
-
if (!options.skipCache) {
|
|
1216
|
-
const cachedChunk = this.getCachedChunk(id);
|
|
1217
|
-
if (cachedChunk) {
|
|
1218
|
-
this.reorderChunk(id);
|
|
1219
|
-
return cachedChunk;
|
|
1220
|
-
}
|
|
1221
|
-
}
|
|
1222
|
-
try {
|
|
1223
|
-
const result = await this.database.get(id);
|
|
1224
|
-
if (result && isChunkDoc(result)) {
|
|
1225
|
-
this.cacheChunk(result);
|
|
1226
|
-
return result;
|
|
1227
|
-
}
|
|
1228
|
-
} catch (error) {
|
|
1229
|
-
if (!isMissingError(error)) {
|
|
1230
|
-
throw new LiveSyncError(`Failed to read chunk ${id}`, { status: 404, cause: error });
|
|
1231
|
-
}
|
|
1232
|
-
}
|
|
1233
|
-
const timeout = options.timeout ?? DEFAULT_TIMEOUT;
|
|
1234
|
-
if (timeout > 0) {
|
|
1235
|
-
const ret = this._enqueueWaiting(id, timeout);
|
|
1236
|
-
if (!options.preventRemoteRequest) {
|
|
1237
|
-
this.emitEvent(EVENT_MISSING_CHUNKS, [id]);
|
|
1238
|
-
}
|
|
1239
|
-
return ret;
|
|
1240
|
-
}
|
|
1241
|
-
return false;
|
|
1242
|
-
}
|
|
1243
|
-
_readFromCache(readIds, resultMap) {
|
|
1244
|
-
const cachedChunks = [...readIds].map((id) => this.getCachedChunk(id)).filter((chunk) => chunk !== false);
|
|
1245
|
-
for (const chunk of cachedChunks) {
|
|
1246
|
-
this.reorderChunk(chunk._id);
|
|
1247
|
-
resultMap.set(chunk._id, chunk);
|
|
1248
|
-
readIds.delete(chunk._id);
|
|
1249
|
-
}
|
|
1250
|
-
}
|
|
1251
|
-
async _readFromDatabase(readIds, resultMap) {
|
|
1252
|
-
const results = await this.database.allDocs({ keys: [...readIds], include_docs: true });
|
|
1253
|
-
for (const row of results.rows) {
|
|
1254
|
-
if ("doc" in row && row.doc) {
|
|
1255
|
-
const chunk = row.doc;
|
|
1256
|
-
resultMap.set(chunk._id, chunk);
|
|
1257
|
-
readIds.delete(chunk._id);
|
|
1258
|
-
this.cacheChunk(chunk);
|
|
1259
|
-
} else if (!isMissingError(row)) {
|
|
1260
|
-
throw new LiveSyncError(`Failed to read chunk ${row.key}`, { status: 404, cause: getError(row) });
|
|
1261
|
-
}
|
|
1262
|
-
}
|
|
1263
|
-
}
|
|
1264
|
-
async _waitForArrival(options, readIds, resultMap) {
|
|
1265
|
-
const timeout = options.timeout ?? DEFAULT_TIMEOUT;
|
|
1266
|
-
if (timeout > 0) {
|
|
1267
|
-
const tasks = [...readIds].map((id) => {
|
|
1268
|
-
return this._enqueueWaiting(id, timeout);
|
|
1269
|
-
});
|
|
1270
|
-
if (!options.preventRemoteRequest) {
|
|
1271
|
-
this.emitEvent(EVENT_MISSING_CHUNKS, [...readIds]);
|
|
1272
|
-
}
|
|
1273
|
-
const results = await Promise.all(tasks);
|
|
1274
|
-
for (const chunk of results) {
|
|
1275
|
-
if (chunk) {
|
|
1276
|
-
resultMap.set(chunk._id, chunk);
|
|
1277
|
-
readIds.delete(chunk._id);
|
|
1278
|
-
this.cacheChunk(chunk);
|
|
1279
|
-
}
|
|
1280
|
-
}
|
|
1281
|
-
}
|
|
1282
|
-
}
|
|
1283
|
-
_readPreloadedChunks(preloadedChunks, readIds, resultMap) {
|
|
1284
|
-
for (const [id, chunk] of Object.entries(preloadedChunks)) {
|
|
1285
|
-
if (isChunkDoc(chunk)) {
|
|
1286
|
-
this.cacheChunk(chunk);
|
|
1287
|
-
resultMap.set(id, chunk);
|
|
1288
|
-
readIds.delete(id);
|
|
1289
|
-
}
|
|
1290
|
-
}
|
|
1291
|
-
}
|
|
1292
|
-
async read(ids, options, preloadedChunks) {
|
|
1293
|
-
const order = [...ids];
|
|
1294
|
-
const resultMap = new Map(ids.map((id) => [id, false]));
|
|
1295
|
-
const readIds = /* @__PURE__ */ new Set([...resultMap.keys()]);
|
|
1296
|
-
if (preloadedChunks) {
|
|
1297
|
-
this._readPreloadedChunks(preloadedChunks, readIds, resultMap);
|
|
1298
|
-
}
|
|
1299
|
-
if (!options.skipCache) {
|
|
1300
|
-
this._readFromCache(readIds, resultMap);
|
|
1301
|
-
}
|
|
1302
|
-
if (readIds.size > 0) {
|
|
1303
|
-
await this._readFromDatabase(readIds, resultMap);
|
|
1304
|
-
}
|
|
1305
|
-
if (readIds.size > 0) {
|
|
1306
|
-
await this._waitForArrival(options, readIds, resultMap);
|
|
1307
|
-
}
|
|
1308
|
-
return order.map((id) => resultMap.get(id) || false);
|
|
1309
|
-
}
|
|
1310
|
-
async write(chunks, options, origin) {
|
|
1311
|
-
let storeChunks = chunks;
|
|
1312
|
-
const writeResult = {
|
|
1313
|
-
result: true,
|
|
1314
|
-
processed: {
|
|
1315
|
-
cached: 0,
|
|
1316
|
-
hotPack: 0,
|
|
1317
|
-
written: 0,
|
|
1318
|
-
duplicated: 0
|
|
1319
|
-
}
|
|
1320
|
-
};
|
|
1321
|
-
const total = storeChunks.length;
|
|
1322
|
-
if (!options.skipCache) {
|
|
1323
|
-
storeChunks = storeChunks.filter((chunk) => {
|
|
1324
|
-
const cached = this.getCachedChunk(chunk._id);
|
|
1325
|
-
if (cached) {
|
|
1326
|
-
this.reorderChunk(chunk._id);
|
|
1327
|
-
return false;
|
|
1328
|
-
}
|
|
1329
|
-
return true;
|
|
1330
|
-
});
|
|
1331
|
-
}
|
|
1332
|
-
const afterPhase1 = storeChunks.length;
|
|
1333
|
-
writeResult.processed.cached = total - afterPhase1;
|
|
1334
|
-
if (storeChunks.length === 0) {
|
|
1335
|
-
return writeResult;
|
|
1336
|
-
}
|
|
1337
|
-
const result = await this.database.bulkDocs(storeChunks, { new_edits: !options?.force });
|
|
1338
|
-
const failed = result.filter((res) => "error" in res);
|
|
1339
|
-
if (failed.some((res) => res.status !== 409)) {
|
|
1340
|
-
throw new LiveSyncError(`Failed to write chunks: ${failed.map((res) => res.error).join(", ")}`, {
|
|
1341
|
-
status: 500
|
|
1342
|
-
});
|
|
1343
|
-
}
|
|
1344
|
-
const conflictedChunkIDs = failed.filter((res) => typeof res.id === "string").map((res) => res.id);
|
|
1345
|
-
if (conflictedChunkIDs.length > 0) {
|
|
1346
|
-
writeResult.processed.duplicated = conflictedChunkIDs.length;
|
|
1347
|
-
const conflictedChunks = (await this.read(conflictedChunkIDs, { skipCache: false, timeout: 0 })).filter(
|
|
1348
|
-
(chunk) => chunk !== false
|
|
1349
|
-
);
|
|
1350
|
-
const originalChunks = buildChunkMap(chunks);
|
|
1351
|
-
for (const chunk of conflictedChunks) {
|
|
1352
|
-
const originalChunk = originalChunks.get(chunk._id);
|
|
1353
|
-
if (originalChunk && originalChunk.data === chunk.data) {
|
|
1354
|
-
this.cacheChunk(chunk);
|
|
1355
|
-
} else {
|
|
1356
|
-
this.deleteCachedChunk(chunk._id);
|
|
1357
|
-
throw new LiveSyncFatalError(
|
|
1358
|
-
`Inconsistent chunk data for ${chunk._id}: local data differs from remote data. This is a fatal error.`
|
|
1359
|
-
);
|
|
1360
|
-
}
|
|
1361
|
-
}
|
|
1362
|
-
}
|
|
1363
|
-
const writeCount = result.length - failed.length;
|
|
1364
|
-
writeResult.processed.written = writeCount;
|
|
1365
|
-
for (const chunk of storeChunks) {
|
|
1366
|
-
this.cacheChunk(chunk);
|
|
1367
|
-
}
|
|
1368
|
-
return writeResult;
|
|
1369
|
-
}
|
|
1370
|
-
concurrentTransactions = 0;
|
|
1371
|
-
stabilised = Promise.resolve();
|
|
1372
|
-
async transaction(callback) {
|
|
1373
|
-
await this.initialised;
|
|
1374
|
-
await this.stabilised;
|
|
1375
|
-
this.concurrentTransactions++;
|
|
1376
|
-
try {
|
|
1377
|
-
const result = await callback();
|
|
1378
|
-
return result;
|
|
1379
|
-
} finally {
|
|
1380
|
-
this.concurrentTransactions--;
|
|
1381
|
-
if (this.concurrentTransactions === 0) {
|
|
1382
|
-
(0, logger_exports.Logger)(`All transactions completed. Performing stabilisation.`, logger_exports.LOG_LEVEL_VERBOSE);
|
|
1383
|
-
await this._stabilise();
|
|
1384
|
-
} else {
|
|
1385
|
-
(0, logger_exports.Logger)(`Transaction completed. Remaining: ${this.concurrentTransactions}`, logger_exports.LOG_LEVEL_VERBOSE);
|
|
1386
|
-
}
|
|
1387
|
-
}
|
|
1388
|
-
}
|
|
1389
|
-
async _stabilise() {
|
|
1390
|
-
const pr = promiseWithResolver();
|
|
1391
|
-
this.stabilised = pr.promise;
|
|
1392
|
-
try {
|
|
1393
|
-
await this.__stabilise();
|
|
1394
|
-
} finally {
|
|
1395
|
-
pr.resolve();
|
|
1396
|
-
}
|
|
1397
|
-
}
|
|
1398
|
-
__stabilise() {
|
|
1399
|
-
return Promise.resolve();
|
|
1400
|
-
}
|
|
1401
|
-
};
|
|
1402
|
-
|
|
1403
|
-
// lib/livesync-commonlib/src/hub/hub.ts
|
|
1404
|
-
import { EventHub } from "octagonal-wheels/events";
|
|
1405
|
-
var eventHub = new EventHub();
|
|
1406
|
-
|
|
1407
|
-
// lib/livesync-commonlib/src/pouchdb/LiveSyncLocalDB.ts
|
|
1408
|
-
import { FallbackWeakRef as FallbackWeakRef2 } from "octagonal-wheels/common/polyfill";
|
|
1409
|
-
var REMOTE_CHUNK_FETCHED = "remote-chunk-fetched";
|
|
1410
|
-
function getNoFromRev(rev) {
|
|
1411
|
-
if (!rev) return 0;
|
|
1412
|
-
return parseInt(rev.split("-")[0]);
|
|
1413
|
-
}
|
|
1414
|
-
var LiveSyncLocalDB = class {
|
|
1415
|
-
auth;
|
|
1416
|
-
dbname;
|
|
1417
|
-
settings;
|
|
1418
|
-
localDatabase;
|
|
1419
|
-
get managers() {
|
|
1420
|
-
return this.env.managers;
|
|
1421
|
-
}
|
|
1422
|
-
isReady = false;
|
|
1423
|
-
needScanning = false;
|
|
1424
|
-
env;
|
|
1425
|
-
clearCaches() {
|
|
1426
|
-
this.managers.clearCaches();
|
|
1427
|
-
}
|
|
1428
|
-
async _prepareHashFunctions() {
|
|
1429
|
-
await this.managers?.prepareHashFunction();
|
|
1430
|
-
}
|
|
1431
|
-
onunload() {
|
|
1432
|
-
this.env.$allOnDBUnload(this);
|
|
1433
|
-
this.localDatabase.removeAllListeners();
|
|
1434
|
-
}
|
|
1435
|
-
refreshSettings() {
|
|
1436
|
-
const settings = this.env.getSettings();
|
|
1437
|
-
this.settings = settings;
|
|
1438
|
-
void this._prepareHashFunctions();
|
|
1439
|
-
}
|
|
1440
|
-
offRemoteChunkFetchedHandler;
|
|
1441
|
-
constructor(dbname, env) {
|
|
1442
|
-
this.auth = {
|
|
1443
|
-
username: "",
|
|
1444
|
-
password: ""
|
|
1445
|
-
};
|
|
1446
|
-
this.dbname = dbname;
|
|
1447
|
-
this.env = env;
|
|
1448
|
-
this.refreshSettings();
|
|
1449
|
-
}
|
|
1450
|
-
async close() {
|
|
1451
|
-
(0, logger_exports.Logger)("Database closed (by close)");
|
|
1452
|
-
this.isReady = false;
|
|
1453
|
-
this.offRemoteChunkFetchedHandler?.();
|
|
1454
|
-
if (this.localDatabase != null) {
|
|
1455
|
-
await this.localDatabase.close();
|
|
1456
|
-
}
|
|
1457
|
-
this.env.$allOnDBClose(this);
|
|
1458
|
-
}
|
|
1459
|
-
onNewLeaf(chunk) {
|
|
1460
|
-
this.managers.chunkManager?.emitEvent(EVENT_CHUNK_FETCHED, chunk);
|
|
1461
|
-
}
|
|
1462
|
-
async initializeDatabase() {
|
|
1463
|
-
await this._prepareHashFunctions();
|
|
1464
|
-
if (this.localDatabase != null) await this.localDatabase.close();
|
|
1465
|
-
this.localDatabase = null;
|
|
1466
|
-
this.localDatabase = this.env.$$createPouchDBInstance(this.dbname + "-livesync-v2", {
|
|
1467
|
-
auto_compaction: false,
|
|
1468
|
-
revs_limit: 100,
|
|
1469
|
-
deterministic_revs: true
|
|
1470
|
-
});
|
|
1471
|
-
if (!await this.env.$everyOnInitializeDatabase(this)) {
|
|
1472
|
-
(0, logger_exports.Logger)("Initializing Database has been failed on some module", LOG_LEVEL_NOTICE);
|
|
1473
|
-
}
|
|
1474
|
-
(0, logger_exports.Logger)("Opening Database...");
|
|
1475
|
-
(0, logger_exports.Logger)("Database info", LOG_LEVEL_VERBOSE);
|
|
1476
|
-
(0, logger_exports.Logger)(await this.localDatabase.info(), LOG_LEVEL_VERBOSE);
|
|
1477
|
-
await this.managers.initManagers();
|
|
1478
|
-
this.localDatabase.on("close", () => {
|
|
1479
|
-
(0, logger_exports.Logger)("Database closed.");
|
|
1480
|
-
this.isReady = false;
|
|
1481
|
-
this.localDatabase.removeAllListeners();
|
|
1482
|
-
this.env.$$getReplicator()?.closeReplication();
|
|
1483
|
-
void this.managers.teardownManagers();
|
|
1484
|
-
});
|
|
1485
|
-
const _instance = new FallbackWeakRef2(this);
|
|
1486
|
-
const unload = eventHub.onEvent(REMOTE_CHUNK_FETCHED, (chunk) => {
|
|
1487
|
-
if (_instance.deref() == null) {
|
|
1488
|
-
unload();
|
|
1489
|
-
}
|
|
1490
|
-
_instance.deref()?.onNewLeaf(chunk);
|
|
1491
|
-
});
|
|
1492
|
-
this.offRemoteChunkFetchedHandler = unload;
|
|
1493
|
-
this.isReady = true;
|
|
1494
|
-
(0, logger_exports.Logger)("Database is now ready.");
|
|
1495
|
-
return true;
|
|
1496
|
-
}
|
|
1497
|
-
/**
|
|
1498
|
-
* Retrieve all used and existing chunks in the database.
|
|
1499
|
-
* @param includeDeleted include deleted chunks in the result.
|
|
1500
|
-
* @returns {used: Set<string>, existing: Map<string, EntryLeaf>} used: Set of chunk ids that are used in the database. existing: Map of chunk id and EntryLeaf that are existing in the database.
|
|
1501
|
-
*/
|
|
1502
|
-
async allChunks(includeDeleted = false) {
|
|
1503
|
-
const used = /* @__PURE__ */ new Set();
|
|
1504
|
-
const existing = /* @__PURE__ */ new Map();
|
|
1505
|
-
let since = 0;
|
|
1506
|
-
do {
|
|
1507
|
-
const changes = await this.localDatabase.changes({
|
|
1508
|
-
since,
|
|
1509
|
-
limit: 100,
|
|
1510
|
-
include_docs: true,
|
|
1511
|
-
conflicts: true,
|
|
1512
|
-
style: includeDeleted ? "all_docs" : "main_only"
|
|
1513
|
-
});
|
|
1514
|
-
if (changes.results.length == 0) {
|
|
1515
|
-
break;
|
|
1516
|
-
}
|
|
1517
|
-
for (const change of changes.results) {
|
|
1518
|
-
const doc = change.doc;
|
|
1519
|
-
if (doc.type == "leaf") {
|
|
1520
|
-
if (doc._deleted) {
|
|
1521
|
-
if (!includeDeleted) {
|
|
1522
|
-
continue;
|
|
1523
|
-
}
|
|
1524
|
-
}
|
|
1525
|
-
existing.set(doc._id, doc);
|
|
1526
|
-
}
|
|
1527
|
-
if ("children" in doc) {
|
|
1528
|
-
if (change.deleted) {
|
|
1529
|
-
if (!doc._conflicts || doc._conflicts.length == 0) {
|
|
1530
|
-
continue;
|
|
1531
|
-
}
|
|
1532
|
-
}
|
|
1533
|
-
doc.children.forEach((e) => used.add(e));
|
|
1534
|
-
if (doc._conflicts) {
|
|
1535
|
-
const revs = await this.localDatabase.get(doc._id, { revs: true, revs_info: true });
|
|
1536
|
-
const mineRevInfo = revs._revs_info || [];
|
|
1537
|
-
const keepRevs = /* @__PURE__ */ new Set();
|
|
1538
|
-
for (const conflict of doc._conflicts) {
|
|
1539
|
-
const conflictedRevs = await this.localDatabase.get(doc._id, {
|
|
1540
|
-
rev: conflict,
|
|
1541
|
-
revs: true,
|
|
1542
|
-
revs_info: true
|
|
1543
|
-
});
|
|
1544
|
-
const conflictedRevInfo = conflictedRevs._revs_info || [];
|
|
1545
|
-
const diffRevs = mineRevInfo.filter(
|
|
1546
|
-
(e) => !conflictedRevInfo.some((f) => f.rev == e.rev && f.status == e.status)
|
|
1547
|
-
);
|
|
1548
|
-
const diffRevs2 = conflictedRevInfo.filter(
|
|
1549
|
-
(e) => !mineRevInfo.some((f) => f.rev == e.rev && f.status == e.status)
|
|
1550
|
-
);
|
|
1551
|
-
const diffRevs3 = diffRevs.concat(diffRevs2);
|
|
1552
|
-
const sameRevs = mineRevInfo.filter((e) => conflictedRevInfo.some((f) => f.rev == e.rev && f.status == e.status)).filter((e) => e.status == "available").sort((a, b) => getNoFromRev(b.rev) - getNoFromRev(a.rev));
|
|
1553
|
-
const sameRevsTop = sameRevs.length > 0 ? [sameRevs[0].rev] : [];
|
|
1554
|
-
const keepRevList = [
|
|
1555
|
-
...diffRevs3.filter((e) => e.status == "available").map((e) => e.rev),
|
|
1556
|
-
...sameRevsTop
|
|
1557
|
-
];
|
|
1558
|
-
keepRevList.forEach((e) => keepRevs.add(e));
|
|
1559
|
-
}
|
|
1560
|
-
const detail = await this.localDatabase.bulkGet({
|
|
1561
|
-
docs: [...keepRevs.values()].map((e) => ({ id: doc._id, rev: e }))
|
|
1562
|
-
});
|
|
1563
|
-
for (const e of detail.results) {
|
|
1564
|
-
if ("docs" in e) {
|
|
1565
|
-
const docs = e.docs;
|
|
1566
|
-
for (const doc2 of docs) {
|
|
1567
|
-
if ("ok" in doc2) {
|
|
1568
|
-
if ("children" in doc2.ok) {
|
|
1569
|
-
doc2.ok.children.forEach((e2) => used.add(e2));
|
|
1570
|
-
}
|
|
1571
|
-
}
|
|
1572
|
-
}
|
|
1573
|
-
}
|
|
1574
|
-
}
|
|
1575
|
-
}
|
|
1576
|
-
}
|
|
1577
|
-
}
|
|
1578
|
-
since = changes.results[changes.results.length - 1].seq;
|
|
1579
|
-
} while (true);
|
|
1580
|
-
return { used, existing };
|
|
1581
|
-
}
|
|
1582
|
-
async resetDatabase() {
|
|
1583
|
-
await this.managers.teardownManagers();
|
|
1584
|
-
this.env.$$getReplicator().closeReplication();
|
|
1585
|
-
if (!await this.env.$everyOnResetDatabase(this)) {
|
|
1586
|
-
(0, logger_exports.Logger)("Database reset has been prevented or failed on some modules.", LOG_LEVEL_NOTICE);
|
|
1587
|
-
return false;
|
|
1588
|
-
}
|
|
1589
|
-
(0, logger_exports.Logger)("Database closed for reset Database.");
|
|
1590
|
-
this.isReady = false;
|
|
1591
|
-
await this.localDatabase.destroy();
|
|
1592
|
-
this.localDatabase = null;
|
|
1593
|
-
await this.initializeDatabase();
|
|
1594
|
-
(0, logger_exports.Logger)("Local Database Reset", LOG_LEVEL_NOTICE);
|
|
1595
|
-
}
|
|
1596
|
-
async *findEntries(startKey, endKey, opt) {
|
|
1597
|
-
const pageLimit = 100;
|
|
1598
|
-
let nextKey = startKey;
|
|
1599
|
-
if (endKey == "") endKey = "\u{10FFFF}";
|
|
1600
|
-
let req = this.allDocsRaw({ limit: pageLimit, startkey: nextKey, endkey: endKey, include_docs: true, ...opt });
|
|
1601
|
-
do {
|
|
1602
|
-
const docs = await req;
|
|
1603
|
-
if (docs.rows.length === 0) {
|
|
1604
|
-
break;
|
|
1605
|
-
}
|
|
1606
|
-
nextKey = `${docs.rows[docs.rows.length - 1].id}`;
|
|
1607
|
-
req = this.allDocsRaw({
|
|
1608
|
-
limit: pageLimit,
|
|
1609
|
-
skip: 1,
|
|
1610
|
-
startkey: nextKey,
|
|
1611
|
-
endkey: endKey,
|
|
1612
|
-
include_docs: true,
|
|
1613
|
-
...opt
|
|
1614
|
-
});
|
|
1615
|
-
for (const row of docs.rows) {
|
|
1616
|
-
const doc = row.doc;
|
|
1617
|
-
if (!("type" in doc)) {
|
|
1618
|
-
continue;
|
|
1619
|
-
}
|
|
1620
|
-
if (doc.type == "newnote" || doc.type == "plain") {
|
|
1621
|
-
yield doc;
|
|
1622
|
-
}
|
|
1623
|
-
}
|
|
1624
|
-
} while (nextKey != "");
|
|
1625
|
-
}
|
|
1626
|
-
async *findAllDocs(opt) {
|
|
1627
|
-
const targets = [
|
|
1628
|
-
() => this.findEntries("", "_", opt ?? {}),
|
|
1629
|
-
() => this.findEntries("_\u{10FFFF}", "h:", opt ?? {}),
|
|
1630
|
-
() => this.findEntries(`h:\u{10FFFF}`, "", opt ?? {})
|
|
1631
|
-
];
|
|
1632
|
-
for (const targetFun of targets) {
|
|
1633
|
-
yield* targetFun();
|
|
1634
|
-
}
|
|
1635
|
-
}
|
|
1636
|
-
async *findEntryNames(startKey, endKey, opt) {
|
|
1637
|
-
const pageLimit = 100;
|
|
1638
|
-
let nextKey = startKey;
|
|
1639
|
-
if (endKey == "") endKey = "\u{10FFFF}";
|
|
1640
|
-
let req = this.allDocsRaw({ limit: pageLimit, startkey: nextKey, endkey: endKey, ...opt });
|
|
1641
|
-
do {
|
|
1642
|
-
const docs = await req;
|
|
1643
|
-
if (docs.rows.length == 0) {
|
|
1644
|
-
nextKey = "";
|
|
1645
|
-
break;
|
|
1646
|
-
}
|
|
1647
|
-
nextKey = `${docs.rows[docs.rows.length - 1].key}`;
|
|
1648
|
-
req = this.allDocsRaw({ limit: pageLimit, skip: 1, startkey: nextKey, endkey: endKey, ...opt });
|
|
1649
|
-
for (const row of docs.rows) {
|
|
1650
|
-
yield row.id;
|
|
1651
|
-
}
|
|
1652
|
-
} while (nextKey != "");
|
|
1653
|
-
}
|
|
1654
|
-
async *findAllDocNames(opt) {
|
|
1655
|
-
const targets = [
|
|
1656
|
-
() => this.findEntryNames("", "_", opt ?? {}),
|
|
1657
|
-
() => this.findEntryNames("_\u{10FFFF}", "h:", opt ?? {}),
|
|
1658
|
-
() => this.findEntryNames(`h:\u{10FFFF}`, "i:", opt ?? {}),
|
|
1659
|
-
() => this.findEntryNames(`i:\u{10FFFF}`, "ix:", opt ?? {}),
|
|
1660
|
-
() => this.findEntryNames(`ix:\u{10FFFF}`, "ps:", opt ?? {}),
|
|
1661
|
-
() => this.findEntryNames(`ps:\u{10FFFF}`, "", opt ?? {})
|
|
1662
|
-
];
|
|
1663
|
-
for (const targetFun of targets) {
|
|
1664
|
-
const target = targetFun();
|
|
1665
|
-
for await (const f of target) {
|
|
1666
|
-
if (f.startsWith("_")) continue;
|
|
1667
|
-
if (f == VERSIONING_DOCID) continue;
|
|
1668
|
-
yield f;
|
|
1669
|
-
}
|
|
1670
|
-
}
|
|
1671
|
-
}
|
|
1672
|
-
async *findAllNormalDocs(opt) {
|
|
1673
|
-
const targets = [
|
|
1674
|
-
() => this.findEntries("", "_", opt ?? {}),
|
|
1675
|
-
() => this.findEntries("_\u{10FFFF}", "h:", opt ?? {}),
|
|
1676
|
-
() => this.findEntries(`h:\u{10FFFF}`, "i:", opt ?? {}),
|
|
1677
|
-
() => this.findEntries(`i:\u{10FFFF}`, "ix:", opt ?? {}),
|
|
1678
|
-
() => this.findEntries(`ix:\u{10FFFF}`, "ps:", opt ?? {}),
|
|
1679
|
-
() => this.findEntries(`ps:\u{10FFFF}`, "", opt ?? {})
|
|
1680
|
-
];
|
|
1681
|
-
for (const targetFun of targets) {
|
|
1682
|
-
const target = targetFun();
|
|
1683
|
-
for await (const f of target) {
|
|
1684
|
-
if (f._id.startsWith("_")) continue;
|
|
1685
|
-
if (f.type != "newnote" && f.type != "plain") continue;
|
|
1686
|
-
yield f;
|
|
1687
|
-
}
|
|
1688
|
-
}
|
|
1689
|
-
}
|
|
1690
|
-
async removeRevision(docId, revision) {
|
|
1691
|
-
try {
|
|
1692
|
-
const doc = await this.localDatabase.get(docId, { rev: revision });
|
|
1693
|
-
doc._deleted = true;
|
|
1694
|
-
await this.localDatabase.put(doc);
|
|
1695
|
-
return true;
|
|
1696
|
-
} catch (ex) {
|
|
1697
|
-
if (isErrorOfMissingDoc(ex)) {
|
|
1698
|
-
(0, logger_exports.Logger)(`Remove revision: Missing target revision, ${docId}-${revision}`, LOG_LEVEL_VERBOSE);
|
|
1699
|
-
}
|
|
1700
|
-
}
|
|
1701
|
-
return false;
|
|
1702
|
-
}
|
|
1703
|
-
getRaw(docId, options) {
|
|
1704
|
-
return this.localDatabase.get(docId, options || {});
|
|
1705
|
-
}
|
|
1706
|
-
removeRaw(docId, revision, options) {
|
|
1707
|
-
return this.localDatabase.remove(docId, revision, options || {});
|
|
1708
|
-
}
|
|
1709
|
-
putRaw(doc, options) {
|
|
1710
|
-
return this.localDatabase.put(doc, options || {});
|
|
1711
|
-
}
|
|
1712
|
-
allDocsRaw(options) {
|
|
1713
|
-
return this.localDatabase.allDocs(options);
|
|
1714
|
-
}
|
|
1715
|
-
bulkDocsRaw(docs, options) {
|
|
1716
|
-
return this.localDatabase.bulkDocs(docs, options || {});
|
|
1717
|
-
}
|
|
1718
|
-
// For compatibility
|
|
1719
|
-
isTargetFile(filenameSrc) {
|
|
1720
|
-
return this.managers.entryManager.isTargetFile(filenameSrc);
|
|
1721
|
-
}
|
|
1722
|
-
async getDBEntryMeta(path, opt, includeDeleted = false) {
|
|
1723
|
-
return await this.managers.entryManager.getDBEntryMeta(path, opt, includeDeleted);
|
|
1724
|
-
}
|
|
1725
|
-
async getDBEntry(path, opt, dump = false, waitForReady = true, includeDeleted = false) {
|
|
1726
|
-
return await this.managers.entryManager.getDBEntry(path, opt, dump, waitForReady, includeDeleted);
|
|
1727
|
-
}
|
|
1728
|
-
async getDBEntryFromMeta(meta, dump = false, waitForReady = true) {
|
|
1729
|
-
return await this.managers.entryManager.getDBEntryFromMeta(meta, dump, waitForReady);
|
|
1730
|
-
}
|
|
1731
|
-
async deleteDBEntry(path, opt) {
|
|
1732
|
-
return await this.managers.entryManager.deleteDBEntry(path, opt);
|
|
1733
|
-
}
|
|
1734
|
-
async putDBEntry(note, onlyChunks) {
|
|
1735
|
-
return await this.managers.entryManager.putDBEntry(note, onlyChunks);
|
|
1736
|
-
}
|
|
1737
|
-
async getConflictedDoc(path, rev) {
|
|
1738
|
-
return await this.managers.conflictManager.getConflictedDoc(path, rev);
|
|
1739
|
-
}
|
|
1740
|
-
async tryAutoMerge(path, enableMarkdownAutoMerge) {
|
|
1741
|
-
return await this.managers.conflictManager.tryAutoMerge(path, enableMarkdownAutoMerge);
|
|
1742
|
-
}
|
|
1743
|
-
};
|
|
1744
|
-
|
|
1745
|
-
// lib/livesync-commonlib/src/pouchdb/compress.ts
|
|
1746
|
-
import * as fflate from "fflate";
|
|
1747
|
-
async function _compressText(text) {
|
|
1748
|
-
const converted = tryConvertBase64ToArrayBuffer(text);
|
|
1749
|
-
const data = new Uint8Array(
|
|
1750
|
-
converted || await new Blob([text], { type: "application/octet-stream" }).arrayBuffer()
|
|
1751
|
-
);
|
|
1752
|
-
if (data.buffer.byteLength == 0) {
|
|
1753
|
-
return "";
|
|
1754
|
-
}
|
|
1755
|
-
const df = await wrappedDeflate(new Uint8Array(data), { consume: true, level: 8 });
|
|
1756
|
-
const deflateResult = (converted ? "~" : "") + await arrayBufferToBase64Single(df);
|
|
1757
|
-
return deflateResult;
|
|
1758
|
-
}
|
|
1759
|
-
var wrappedInflate = wrapFflateFunc(fflate.inflate);
|
|
1760
|
-
var wrappedDeflate = wrapFflateFunc(fflate.deflate);
|
|
1761
|
-
async function _decompressText(compressed, _useUTF16 = false) {
|
|
1762
|
-
if (compressed.length == 0) {
|
|
1763
|
-
return "";
|
|
1764
|
-
}
|
|
1765
|
-
const converted = compressed[0] == "~";
|
|
1766
|
-
const src = compressed.substring(converted ? 1 : 0);
|
|
1767
|
-
if (src.length == 0) {
|
|
1768
|
-
return "";
|
|
1769
|
-
}
|
|
1770
|
-
const ab = new Uint8Array(base64ToArrayBuffer(src));
|
|
1771
|
-
if (ab.length == 0) {
|
|
1772
|
-
return "";
|
|
1773
|
-
}
|
|
1774
|
-
const ret = await wrappedInflate(new Uint8Array(ab), { consume: true });
|
|
1775
|
-
if (converted) {
|
|
1776
|
-
return await arrayBufferToBase64Single(ret);
|
|
1777
|
-
}
|
|
1778
|
-
const response = new Blob([ret]);
|
|
1779
|
-
const text = await response.text();
|
|
1780
|
-
return text;
|
|
1781
|
-
}
|
|
1782
|
-
async function compressDoc(doc) {
|
|
1783
|
-
if (!("data" in doc)) {
|
|
1784
|
-
return doc;
|
|
1785
|
-
}
|
|
1786
|
-
if (typeof doc.data !== "string") return doc;
|
|
1787
|
-
if (doc.data.startsWith(MARK_SHIFT_COMPRESSED)) return doc;
|
|
1788
|
-
const oldData = doc.data;
|
|
1789
|
-
const compressed = await _compressText(oldData);
|
|
1790
|
-
const newData = MARK_SHIFT_COMPRESSED + compressed;
|
|
1791
|
-
if (doc.data.length > newData.length) doc.data = newData;
|
|
1792
|
-
return doc;
|
|
1793
|
-
}
|
|
1794
|
-
async function decompressDoc(doc) {
|
|
1795
|
-
if (!("data" in doc)) {
|
|
1796
|
-
return doc;
|
|
1797
|
-
}
|
|
1798
|
-
if (typeof doc.data !== "string") return doc;
|
|
1799
|
-
if (doc.data.startsWith(MARK_SHIFT_COMPRESSED)) {
|
|
1800
|
-
doc.data = await _decompressText(doc.data.substring(MARK_SHIFT_COMPRESSED.length));
|
|
1801
|
-
}
|
|
1802
|
-
return doc;
|
|
1803
|
-
}
|
|
1804
|
-
function wrapFflateFunc(func) {
|
|
1805
|
-
return (data, opts) => {
|
|
1806
|
-
return new Promise((res, rej) => {
|
|
1807
|
-
func(data, opts, (err, result) => {
|
|
1808
|
-
if (err) rej(err);
|
|
1809
|
-
else res(result);
|
|
1810
|
-
});
|
|
1811
|
-
});
|
|
1812
|
-
};
|
|
1813
|
-
}
|
|
1814
|
-
var replicationFilter = (db, compress) => {
|
|
1815
|
-
db.transform({
|
|
1816
|
-
//@ts-ignore
|
|
1817
|
-
async incoming(doc) {
|
|
1818
|
-
if (!compress) return doc;
|
|
1819
|
-
return await compressDoc(doc);
|
|
1820
|
-
},
|
|
1821
|
-
//@ts-ignore
|
|
1822
|
-
async outgoing(doc) {
|
|
1823
|
-
return await decompressDoc(doc);
|
|
1824
|
-
}
|
|
1825
|
-
});
|
|
1826
|
-
};
|
|
1827
|
-
var MARK_SHIFT = `L`;
|
|
1828
|
-
var MARK_SHIFT_COMPRESSED = `${MARK_SHIFT}Z`;
|
|
1829
|
-
|
|
1830
|
-
// lib/livesync-commonlib/src/encryption/e2ee_v2.ts
|
|
1831
|
-
var e2ee_v2_exports = {};
|
|
1832
|
-
__reExport(e2ee_v2_exports, encryption_star);
|
|
1833
|
-
__reExport(e2ee_v2_exports, encryptionv3_star);
|
|
1834
|
-
import * as encryption_star from "octagonal-wheels/encryption/encryption";
|
|
1835
|
-
import * as encryptionv3_star from "octagonal-wheels/encryption/encryptionv3";
|
|
1836
|
-
|
|
1837
|
-
// lib/livesync-commonlib/src/worker/bgWorker.mock.ts
|
|
1838
|
-
import { decrypt, encrypt } from "octagonal-wheels/encryption/index.js";
|
|
1839
|
-
import { encrypt as encryptHKDF, decrypt as decryptHKDF } from "octagonal-wheels/encryption/hkdf";
|
|
1840
|
-
|
|
1841
|
-
// lib/livesync-commonlib/src/string_and_binary/chunks.ts
|
|
1842
|
-
function isTextBlob2(blob) {
|
|
1843
|
-
return blob.type === "text/plain";
|
|
1844
|
-
}
|
|
1845
|
-
function* pickPiece(leftData, minimumChunkSize) {
|
|
1846
|
-
let buffer = "";
|
|
1847
|
-
L1: do {
|
|
1848
|
-
const curLine = leftData.shift();
|
|
1849
|
-
if (typeof curLine === "undefined") {
|
|
1850
|
-
yield buffer;
|
|
1851
|
-
break L1;
|
|
1852
|
-
}
|
|
1853
|
-
if (curLine.startsWith("```") || curLine.startsWith(" ```") || curLine.startsWith(" ```") || curLine.startsWith(" ```")) {
|
|
1854
|
-
yield buffer;
|
|
1855
|
-
buffer = curLine + (leftData.length != 0 ? "\n" : "");
|
|
1856
|
-
L2: do {
|
|
1857
|
-
const curPx = leftData.shift();
|
|
1858
|
-
if (typeof curPx === "undefined") {
|
|
1859
|
-
break L2;
|
|
1860
|
-
}
|
|
1861
|
-
buffer += curPx + (leftData.length != 0 ? "\n" : "");
|
|
1862
|
-
} while (leftData.length > 0 && !(leftData[0].startsWith("```") || leftData[0].startsWith(" ```") || leftData[0].startsWith(" ```") || leftData[0].startsWith(" ```")));
|
|
1863
|
-
const isLooksLikeBASE64 = buffer.endsWith("=");
|
|
1864
|
-
const maybeUneditable = buffer.length > 2048;
|
|
1865
|
-
const endOfCodeBlock = leftData.shift();
|
|
1866
|
-
if (typeof endOfCodeBlock !== "undefined") {
|
|
1867
|
-
buffer += endOfCodeBlock;
|
|
1868
|
-
buffer += leftData.length != 0 ? "\n" : "";
|
|
1869
|
-
}
|
|
1870
|
-
if (!isLooksLikeBASE64 && !maybeUneditable) {
|
|
1871
|
-
const splitExpr = /(.*?[;,:<])/g;
|
|
1872
|
-
const sx = buffer.split(splitExpr).filter((e) => e != "");
|
|
1873
|
-
for (const v of sx) {
|
|
1874
|
-
yield v;
|
|
1875
|
-
}
|
|
1876
|
-
} else {
|
|
1877
|
-
yield buffer;
|
|
1878
|
-
}
|
|
1879
|
-
buffer = "";
|
|
1880
|
-
} else {
|
|
1881
|
-
buffer += curLine + (leftData.length != 0 ? "\n" : "");
|
|
1882
|
-
if (buffer.length >= minimumChunkSize || leftData.length == 0 || leftData[0] == "#" || buffer[0] == "#") {
|
|
1883
|
-
yield buffer;
|
|
1884
|
-
buffer = "";
|
|
1885
|
-
}
|
|
1886
|
-
}
|
|
1887
|
-
} while (leftData.length > 0);
|
|
1888
|
-
}
|
|
1889
|
-
var charNewLine = "\n".charCodeAt(0);
|
|
1890
|
-
var segmenter = "Segmenter" in Intl ? new Intl.Segmenter(navigator.language, { granularity: "sentence" }) : void 0;
|
|
1891
|
-
function* splitStringWithinLength(text, pieceSize) {
|
|
1892
|
-
let leftData = text;
|
|
1893
|
-
do {
|
|
1894
|
-
const splitSize = pieceSize;
|
|
1895
|
-
const piece = leftData.substring(0, splitSize);
|
|
1896
|
-
leftData = leftData.substring(splitSize);
|
|
1897
|
-
yield piece;
|
|
1898
|
-
} while (leftData != "");
|
|
1899
|
-
}
|
|
1900
|
-
function* splitTextInSegment(text, pieceSize, minimumChunkSize) {
|
|
1901
|
-
const segments = segmenter.segment(text);
|
|
1902
|
-
let prev = "";
|
|
1903
|
-
let buf = "";
|
|
1904
|
-
for (const seg of segments) {
|
|
1905
|
-
const buffer = seg.segment;
|
|
1906
|
-
if (prev == buffer || buf.length < minimumChunkSize) {
|
|
1907
|
-
buf += buffer;
|
|
1908
|
-
prev = buffer;
|
|
1909
|
-
} else {
|
|
1910
|
-
prev = buffer;
|
|
1911
|
-
if (buf.length > 0) {
|
|
1912
|
-
yield* splitStringWithinLength(buf, pieceSize);
|
|
1913
|
-
}
|
|
1914
|
-
buf = buffer;
|
|
1915
|
-
}
|
|
1916
|
-
}
|
|
1917
|
-
if (buf.length > 0) {
|
|
1918
|
-
yield* splitStringWithinLength(buf, pieceSize);
|
|
1919
|
-
}
|
|
1920
|
-
}
|
|
1921
|
-
function* splitInNewLine(texts) {
|
|
1922
|
-
for (const text of texts) {
|
|
1923
|
-
let start = -1;
|
|
1924
|
-
let end = -1;
|
|
1925
|
-
do {
|
|
1926
|
-
end = text.indexOf("\n", start);
|
|
1927
|
-
if (end == -1) {
|
|
1928
|
-
yield text.substring(start);
|
|
1929
|
-
break;
|
|
1930
|
-
}
|
|
1931
|
-
while (text[end] == "\n") {
|
|
1932
|
-
end++;
|
|
1933
|
-
}
|
|
1934
|
-
yield text.substring(start, end);
|
|
1935
|
-
start = end;
|
|
1936
|
-
} while (end != -1);
|
|
1937
|
-
}
|
|
1938
|
-
return;
|
|
1939
|
-
}
|
|
1940
|
-
function splitPiecesTextV2(dataSrc, pieceSize, minimumChunkSize) {
|
|
1941
|
-
const dataListAllArray = typeof dataSrc == "string" ? [dataSrc] : dataSrc;
|
|
1942
|
-
const dataListAll = splitInNewLine(dataListAllArray);
|
|
1943
|
-
let inCodeBlock = 0;
|
|
1944
|
-
let flush = false;
|
|
1945
|
-
let flushBefore = false;
|
|
1946
|
-
return function* () {
|
|
1947
|
-
const buf = [];
|
|
1948
|
-
for (const line of dataListAll) {
|
|
1949
|
-
if (line.startsWith("````")) {
|
|
1950
|
-
if (inCodeBlock == 0) {
|
|
1951
|
-
inCodeBlock = 4;
|
|
1952
|
-
flushBefore = true;
|
|
1953
|
-
} else if (inCodeBlock == 4) {
|
|
1954
|
-
inCodeBlock = 0;
|
|
1955
|
-
flush = true;
|
|
1956
|
-
}
|
|
1957
|
-
} else if (line.startsWith("```")) {
|
|
1958
|
-
if (inCodeBlock == 0) {
|
|
1959
|
-
inCodeBlock = 3;
|
|
1960
|
-
flushBefore = true;
|
|
1961
|
-
} else if (inCodeBlock == 3) {
|
|
1962
|
-
inCodeBlock = 0;
|
|
1963
|
-
flush = true;
|
|
1964
|
-
}
|
|
1965
|
-
}
|
|
1966
|
-
if (flushBefore) {
|
|
1967
|
-
if (buf.length > 0) {
|
|
1968
|
-
yield* splitTextInSegment(buf.join(""), pieceSize, minimumChunkSize);
|
|
1969
|
-
buf.length = 0;
|
|
1970
|
-
}
|
|
1971
|
-
flushBefore = false;
|
|
1972
|
-
}
|
|
1973
|
-
buf.push(line);
|
|
1974
|
-
if (flush) {
|
|
1975
|
-
if (buf.length > 0) {
|
|
1976
|
-
yield* splitStringWithinLength(buf.join(""), pieceSize);
|
|
1977
|
-
buf.length = 0;
|
|
1978
|
-
}
|
|
1979
|
-
flush = false;
|
|
1980
|
-
}
|
|
1981
|
-
}
|
|
1982
|
-
if (buf.length > 0) {
|
|
1983
|
-
if (inCodeBlock == 0) {
|
|
1984
|
-
yield* splitTextInSegment(buf.join(""), pieceSize, minimumChunkSize);
|
|
1985
|
-
} else {
|
|
1986
|
-
yield* splitStringWithinLength(buf.join(""), pieceSize);
|
|
1987
|
-
}
|
|
1988
|
-
}
|
|
1989
|
-
};
|
|
1990
|
-
}
|
|
1991
|
-
function binaryTextSplit(data, pieceSize, minimumChunkSize) {
|
|
1992
|
-
return function* pieces() {
|
|
1993
|
-
yield* splitStringWithinLength(data, pieceSize);
|
|
1994
|
-
};
|
|
1995
|
-
}
|
|
1996
|
-
function splitPiecesText(dataSrc, pieceSize, plainSplit, minimumChunkSize, useSegmenter) {
|
|
1997
|
-
if (!useSegmenter || !segmenter) {
|
|
1998
|
-
return splitPiecesTextV1(dataSrc, pieceSize, plainSplit, minimumChunkSize);
|
|
1999
|
-
}
|
|
2000
|
-
if (!plainSplit) {
|
|
2001
|
-
return binaryTextSplit(dataSrc, pieceSize, minimumChunkSize);
|
|
2002
|
-
}
|
|
2003
|
-
return splitPiecesTextV2(dataSrc, pieceSize, minimumChunkSize);
|
|
2004
|
-
}
|
|
2005
|
-
function splitPiecesTextV1(dataSrc, pieceSize, plainSplit, minimumChunkSize) {
|
|
2006
|
-
const dataList = typeof dataSrc == "string" ? [dataSrc] : dataSrc;
|
|
2007
|
-
return function* pieces() {
|
|
2008
|
-
for (const data of dataList) {
|
|
2009
|
-
if (plainSplit) {
|
|
2010
|
-
const leftData = data.split("\n");
|
|
2011
|
-
const f = pickPiece(leftData, minimumChunkSize);
|
|
2012
|
-
for (const piece of f) {
|
|
2013
|
-
let buffer = piece;
|
|
2014
|
-
do {
|
|
2015
|
-
let ps = pieceSize;
|
|
2016
|
-
if (buffer.charCodeAt(ps - 1) != buffer.codePointAt(ps - 1)) {
|
|
2017
|
-
ps++;
|
|
2018
|
-
}
|
|
2019
|
-
yield buffer.substring(0, ps);
|
|
2020
|
-
buffer = buffer.substring(ps);
|
|
2021
|
-
} while (buffer != "");
|
|
2022
|
-
}
|
|
2023
|
-
} else {
|
|
2024
|
-
let leftData = data;
|
|
2025
|
-
do {
|
|
2026
|
-
const splitSize = pieceSize;
|
|
2027
|
-
const piece = leftData.substring(0, splitSize);
|
|
2028
|
-
leftData = leftData.substring(splitSize);
|
|
2029
|
-
yield piece;
|
|
2030
|
-
} while (leftData != "");
|
|
2031
|
-
}
|
|
2032
|
-
}
|
|
2033
|
-
};
|
|
2034
|
-
}
|
|
2035
|
-
function* splitByDelimiterWithMinLength(sources, delimiter, minimumChunkLength = 25, splitThreshold) {
|
|
2036
|
-
let buf = "";
|
|
2037
|
-
let last = false;
|
|
2038
|
-
const dl = delimiter.length;
|
|
2039
|
-
for (const source of sources) {
|
|
2040
|
-
const max = source.length;
|
|
2041
|
-
if (splitThreshold && max > splitThreshold) {
|
|
2042
|
-
yield buf + source;
|
|
2043
|
-
last = false;
|
|
2044
|
-
buf = "";
|
|
2045
|
-
continue;
|
|
2046
|
-
}
|
|
2047
|
-
let i = -1;
|
|
2048
|
-
let prev = 0;
|
|
2049
|
-
L1: do {
|
|
2050
|
-
i = source.indexOf(delimiter, prev);
|
|
2051
|
-
if (i == -1) break L1;
|
|
2052
|
-
buf += source.slice(prev, i) + delimiter;
|
|
2053
|
-
if (buf.length > minimumChunkLength) {
|
|
2054
|
-
yield buf;
|
|
2055
|
-
buf = "";
|
|
2056
|
-
last = false;
|
|
2057
|
-
} else {
|
|
2058
|
-
last = true;
|
|
2059
|
-
}
|
|
2060
|
-
prev = i + dl;
|
|
2061
|
-
} while (i < max);
|
|
2062
|
-
if (prev != i || prev == -1 && i == -1) {
|
|
2063
|
-
buf += source.slice(prev);
|
|
2064
|
-
last = true;
|
|
2065
|
-
}
|
|
2066
|
-
}
|
|
2067
|
-
if (last) {
|
|
2068
|
-
yield buf;
|
|
2069
|
-
}
|
|
2070
|
-
}
|
|
2071
|
-
function* chunkStringGenerator(source, maxLength) {
|
|
2072
|
-
const strLen = source.length;
|
|
2073
|
-
if (strLen > maxLength) {
|
|
2074
|
-
let from = 0;
|
|
2075
|
-
do {
|
|
2076
|
-
let end = from + maxLength;
|
|
2077
|
-
if (end > strLen) {
|
|
2078
|
-
yield source.substring(from);
|
|
2079
|
-
break;
|
|
2080
|
-
}
|
|
2081
|
-
while (source.charCodeAt(end - 1) != source.codePointAt(end - 1)) {
|
|
2082
|
-
end++;
|
|
2083
|
-
}
|
|
2084
|
-
yield source.substring(from, end);
|
|
2085
|
-
from = end;
|
|
2086
|
-
} while (from < strLen);
|
|
2087
|
-
} else {
|
|
2088
|
-
yield source;
|
|
2089
|
-
}
|
|
2090
|
-
}
|
|
2091
|
-
function* chunkStringGeneratorFromGenerator(sources, maxLength) {
|
|
2092
|
-
for (const source of sources) {
|
|
2093
|
-
yield* chunkStringGenerator(source, maxLength);
|
|
2094
|
-
}
|
|
2095
|
-
}
|
|
2096
|
-
function* stringGenerator(sources) {
|
|
2097
|
-
for (const str of sources) {
|
|
2098
|
-
yield str;
|
|
2099
|
-
}
|
|
2100
|
-
}
|
|
2101
|
-
var MAX_ITEMS = 100;
|
|
2102
|
-
async function splitPieces2V2(dataSrc, pieceSize, plainSplit, minimumChunkSize, filename, useSegmenter) {
|
|
2103
|
-
if (dataSrc.size == 0) {
|
|
2104
|
-
return function* noItems() {
|
|
2105
|
-
return;
|
|
2106
|
-
};
|
|
2107
|
-
}
|
|
2108
|
-
if (isTextBlob2(dataSrc)) {
|
|
2109
|
-
const text = await dataSrc.text();
|
|
2110
|
-
if (!plainSplit) {
|
|
2111
|
-
const gen2 = chunkStringGenerator(text, pieceSize);
|
|
2112
|
-
return function* pieces() {
|
|
2113
|
-
yield* gen2;
|
|
2114
|
-
};
|
|
2115
|
-
}
|
|
2116
|
-
const textLen = text.length;
|
|
2117
|
-
let xMinimumChunkSize = minimumChunkSize;
|
|
2118
|
-
while (textLen / xMinimumChunkSize > MAX_ITEMS) {
|
|
2119
|
-
xMinimumChunkSize += minimumChunkSize;
|
|
2120
|
-
}
|
|
2121
|
-
const org = stringGenerator([text]);
|
|
2122
|
-
const gen1 = splitByDelimiterWithMinLength(org, "\n", xMinimumChunkSize);
|
|
2123
|
-
const gen = chunkStringGeneratorFromGenerator(gen1, pieceSize);
|
|
2124
|
-
return function* pieces() {
|
|
2125
|
-
yield* gen;
|
|
2126
|
-
};
|
|
2127
|
-
}
|
|
2128
|
-
let canBeSmall = false;
|
|
2129
|
-
let delimiter = 0;
|
|
2130
|
-
if (filename && filename.endsWith(".pdf")) {
|
|
2131
|
-
delimiter = "/".charCodeAt(0);
|
|
2132
|
-
} else if (filename && filename.endsWith(".json")) {
|
|
2133
|
-
canBeSmall = true;
|
|
2134
|
-
delimiter = ",".charCodeAt(0);
|
|
2135
|
-
}
|
|
2136
|
-
const clampMin = canBeSmall ? 100 : 1e5;
|
|
2137
|
-
const clampMax = 1e8;
|
|
2138
|
-
const clampedSize = Math.max(clampMin, Math.min(clampMax, dataSrc.size));
|
|
2139
|
-
let step = 1;
|
|
2140
|
-
let w = clampedSize;
|
|
2141
|
-
while (w > 10) {
|
|
2142
|
-
w /= 12.5;
|
|
2143
|
-
step++;
|
|
2144
|
-
}
|
|
2145
|
-
minimumChunkSize = Math.floor(10 ** (step - 1));
|
|
2146
|
-
return async function* piecesBlob() {
|
|
2147
|
-
const size = dataSrc.size;
|
|
2148
|
-
let i = 0;
|
|
2149
|
-
const buf = new Uint8Array(await dataSrc.arrayBuffer());
|
|
2150
|
-
do {
|
|
2151
|
-
const findStart = i + minimumChunkSize;
|
|
2152
|
-
const defaultSplitEnd = i + pieceSize;
|
|
2153
|
-
let splitEnd;
|
|
2154
|
-
let i1 = buf.indexOf(delimiter, findStart);
|
|
2155
|
-
if (i1 == -1) {
|
|
2156
|
-
i1 = buf.indexOf(charNewLine, findStart);
|
|
2157
|
-
}
|
|
2158
|
-
if (i1 == -1) {
|
|
2159
|
-
splitEnd = defaultSplitEnd;
|
|
2160
|
-
} else {
|
|
2161
|
-
splitEnd = i1 < defaultSplitEnd ? i1 : defaultSplitEnd;
|
|
2162
|
-
}
|
|
2163
|
-
yield await arrayBufferToBase64Single(buf.slice(i, splitEnd));
|
|
2164
|
-
i = splitEnd;
|
|
2165
|
-
} while (i < size);
|
|
2166
|
-
};
|
|
2167
|
-
}
|
|
2168
|
-
async function splitPieces2(dataSrc, pieceSize, plainSplit, minimumChunkSize, filename, useSegmenter) {
|
|
2169
|
-
if (isTextBlob2(dataSrc)) {
|
|
2170
|
-
return splitPiecesText(await dataSrc.text(), pieceSize, plainSplit, minimumChunkSize, useSegmenter ?? false);
|
|
2171
|
-
}
|
|
2172
|
-
let delimiter = 0;
|
|
2173
|
-
let canBeSmall = false;
|
|
2174
|
-
if (filename && filename.endsWith(".pdf")) {
|
|
2175
|
-
delimiter = "/".charCodeAt(0);
|
|
2176
|
-
} else if (filename && filename.endsWith(".json")) {
|
|
2177
|
-
canBeSmall = true;
|
|
2178
|
-
delimiter = ",".charCodeAt(0);
|
|
2179
|
-
}
|
|
2180
|
-
const clampMin = canBeSmall ? 100 : 1e5;
|
|
2181
|
-
const clampMax = 1e8;
|
|
2182
|
-
const clampedSize = Math.max(clampMin, Math.min(clampMax, dataSrc.size));
|
|
2183
|
-
let step = 1;
|
|
2184
|
-
let w = clampedSize;
|
|
2185
|
-
while (w > 10) {
|
|
2186
|
-
w /= 12.5;
|
|
2187
|
-
step++;
|
|
2188
|
-
}
|
|
2189
|
-
minimumChunkSize = Math.floor(10 ** (step - 1));
|
|
2190
|
-
return async function* piecesBlob() {
|
|
2191
|
-
const size = dataSrc.size;
|
|
2192
|
-
let i = 0;
|
|
2193
|
-
do {
|
|
2194
|
-
let splitSize = pieceSize;
|
|
2195
|
-
const currentData = new Uint8Array(await dataSrc.slice(i, i + pieceSize).arrayBuffer());
|
|
2196
|
-
let nextIdx = currentData.indexOf(delimiter, minimumChunkSize);
|
|
2197
|
-
splitSize = nextIdx == -1 ? pieceSize : Math.min(pieceSize, nextIdx);
|
|
2198
|
-
if (nextIdx == -1) nextIdx = currentData.indexOf(charNewLine, minimumChunkSize);
|
|
2199
|
-
const piece = currentData.slice(0, splitSize);
|
|
2200
|
-
i += piece.length;
|
|
2201
|
-
const b64 = await arrayBufferToBase64Single(piece);
|
|
2202
|
-
yield b64;
|
|
2203
|
-
} while (i < size);
|
|
2204
|
-
};
|
|
2205
|
-
}
|
|
2206
|
-
async function splitPiecesRabinKarp(dataSrc, absoluteMaxPieceSize, doPlainSplit, minimumChunkSize, _filename, _useSegmenter) {
|
|
2207
|
-
const plainSplit = doPlainSplit || isTextBlob2(dataSrc);
|
|
2208
|
-
const minPieceSize = plainSplit ? 128 : 1024 * 4;
|
|
2209
|
-
const splitPieceCount = plainSplit ? 20 : 12;
|
|
2210
|
-
const avgChunkSize = Math.max(minPieceSize, Math.floor(dataSrc.size / splitPieceCount));
|
|
2211
|
-
const maxChunkSize = Math.min(absoluteMaxPieceSize, avgChunkSize * 5);
|
|
2212
|
-
const minChunkSize = Math.min(Math.max(Math.floor(avgChunkSize / 4), minimumChunkSize), maxChunkSize);
|
|
2213
|
-
const windowSize = 48;
|
|
2214
|
-
const hashModulus = avgChunkSize;
|
|
2215
|
-
const boundaryPattern = 1;
|
|
2216
|
-
const PRIME = 31;
|
|
2217
|
-
let P_pow_w = 1;
|
|
2218
|
-
for (let i = 0; i < windowSize - 1; i++) {
|
|
2219
|
-
P_pow_w = Math.imul(P_pow_w, PRIME);
|
|
2220
|
-
}
|
|
2221
|
-
const buffer = new Uint8Array(await dataSrc.arrayBuffer());
|
|
2222
|
-
let pos = 0;
|
|
2223
|
-
let hash = 0;
|
|
2224
|
-
let start = 0;
|
|
2225
|
-
const isText = isTextBlob2(dataSrc);
|
|
2226
|
-
const length = buffer.length;
|
|
2227
|
-
return async function* piecesBlob() {
|
|
2228
|
-
while (pos < length) {
|
|
2229
|
-
const byte = buffer[pos];
|
|
2230
|
-
if (pos >= start + windowSize) {
|
|
2231
|
-
const oldByte = buffer[pos - windowSize];
|
|
2232
|
-
const oldByteTerm = Math.imul(oldByte, P_pow_w);
|
|
2233
|
-
hash = hash - oldByteTerm | 0;
|
|
2234
|
-
hash = Math.imul(hash, PRIME);
|
|
2235
|
-
hash = hash + byte | 0;
|
|
2236
|
-
} else {
|
|
2237
|
-
hash = Math.imul(hash, PRIME);
|
|
2238
|
-
hash = hash + byte | 0;
|
|
2239
|
-
}
|
|
2240
|
-
const currentChunkSize = pos - start + 1;
|
|
2241
|
-
let isBoundaryCandidate = false;
|
|
2242
|
-
if (currentChunkSize >= minChunkSize) {
|
|
2243
|
-
if ((hash >>> 0) % hashModulus === boundaryPattern) {
|
|
2244
|
-
isBoundaryCandidate = true;
|
|
2245
|
-
}
|
|
2246
|
-
}
|
|
2247
|
-
if (currentChunkSize >= maxChunkSize) {
|
|
2248
|
-
isBoundaryCandidate = true;
|
|
2249
|
-
}
|
|
2250
|
-
if (isBoundaryCandidate) {
|
|
2251
|
-
let isSafeBoundary = true;
|
|
2252
|
-
if (isText) {
|
|
2253
|
-
if (pos + 1 < length && (buffer[pos + 1] & 192) === 128) {
|
|
2254
|
-
isSafeBoundary = false;
|
|
2255
|
-
}
|
|
2256
|
-
}
|
|
2257
|
-
if (isSafeBoundary) {
|
|
2258
|
-
if (isText) {
|
|
2259
|
-
yield Promise.resolve(readString(buffer.subarray(start, pos + 1)));
|
|
2260
|
-
} else {
|
|
2261
|
-
yield await arrayBufferToBase64Single(buffer.subarray(start, pos + 1));
|
|
2262
|
-
}
|
|
2263
|
-
start = pos + 1;
|
|
2264
|
-
}
|
|
2265
|
-
}
|
|
2266
|
-
pos++;
|
|
2267
|
-
}
|
|
2268
|
-
if (start < length) {
|
|
2269
|
-
if (isText) {
|
|
2270
|
-
yield Promise.resolve(readString(buffer.subarray(start, length)));
|
|
2271
|
-
} else {
|
|
2272
|
-
yield await arrayBufferToBase64Single(buffer.subarray(start, length));
|
|
2273
|
-
}
|
|
2274
|
-
}
|
|
2275
|
-
};
|
|
2276
|
-
}
|
|
2277
|
-
|
|
2278
|
-
// lib/livesync-commonlib/src/worker/bgWorker.mock.ts
|
|
2279
|
-
function splitPieces2Worker(dataSrc, pieceSize, plainSplit, minimumChunkSize, filename, useSegmenter) {
|
|
2280
|
-
return splitPieces2(dataSrc, pieceSize, plainSplit, minimumChunkSize, filename, useSegmenter ?? false);
|
|
2281
|
-
}
|
|
2282
|
-
function splitPieces2WorkerV2(dataSrc, pieceSize, plainSplit, minimumChunkSize, filename, useSegmenter) {
|
|
2283
|
-
return splitPieces2V2(dataSrc, pieceSize, plainSplit, minimumChunkSize, filename, useSegmenter ?? false);
|
|
2284
|
-
}
|
|
2285
|
-
function splitPieces2WorkerRabinKarp(dataSrc, pieceSize, plainSplit, minimumChunkSize, filename, useSegmenter) {
|
|
2286
|
-
return splitPiecesRabinKarp(dataSrc, pieceSize, plainSplit, minimumChunkSize, filename, useSegmenter ?? false);
|
|
2287
|
-
}
|
|
2288
|
-
function encryptWorker(input, passphrase, autoCalculateIterations) {
|
|
2289
|
-
return encrypt(input, passphrase, autoCalculateIterations);
|
|
2290
|
-
}
|
|
2291
|
-
function decryptWorker(input, passphrase, autoCalculateIterations) {
|
|
2292
|
-
return decrypt(input, passphrase, autoCalculateIterations);
|
|
2293
|
-
}
|
|
2294
|
-
function encryptHKDFWorker(input, passphrase, pbkdf2Salt) {
|
|
2295
|
-
return encryptHKDF(input, passphrase, pbkdf2Salt);
|
|
2296
|
-
}
|
|
2297
|
-
function decryptHKDFWorker(input, passphrase, pbkdf2Salt) {
|
|
2298
|
-
return decryptHKDF(input, passphrase, pbkdf2Salt);
|
|
2299
|
-
}
|
|
2300
|
-
|
|
2301
|
-
// lib/livesync-commonlib/src/pouchdb/encryption.ts
|
|
2302
|
-
var encrypt2 = encryptWorker;
|
|
2303
|
-
var decrypt2 = decryptWorker;
|
|
2304
|
-
var encryptHKDF2 = encryptHKDFWorker;
|
|
2305
|
-
var decryptHKDF2 = decryptHKDFWorker;
|
|
2306
|
-
var Encrypt_HKDF_Header = "%=";
|
|
2307
|
-
var Encrypt_OLD_Header = "%";
|
|
2308
|
-
var EncryptionVersions = {
|
|
2309
|
-
UNENCRYPTED: 0,
|
|
2310
|
-
ENCRYPTED: 1,
|
|
2311
|
-
HKDF: 2,
|
|
2312
|
-
UNKNOWN: 99
|
|
2313
|
-
};
|
|
2314
|
-
function getEncryptionVersion(data) {
|
|
2315
|
-
if ("e_" in data && data.e_ === true) {
|
|
2316
|
-
if (data.data.startsWith(Encrypt_HKDF_Header)) {
|
|
2317
|
-
return EncryptionVersions.HKDF;
|
|
2318
|
-
} else if (data.data.startsWith(Encrypt_OLD_Header)) {
|
|
2319
|
-
return EncryptionVersions.ENCRYPTED;
|
|
2320
|
-
}
|
|
2321
|
-
return EncryptionVersions.UNKNOWN;
|
|
2322
|
-
}
|
|
2323
|
-
return EncryptionVersions.UNENCRYPTED;
|
|
2324
|
-
}
|
|
2325
|
-
async function tryDecryptV1AsFallback(encryptedData, passphrase, useDynamicIterationCount) {
|
|
2326
|
-
try {
|
|
2327
|
-
return await decrypt2(encryptedData, passphrase, useDynamicIterationCount);
|
|
2328
|
-
} catch (ex) {
|
|
2329
|
-
try {
|
|
2330
|
-
(0, logger_exports.Logger)(
|
|
2331
|
-
"Failed to decrypt with V1 method. Fallback to disable useDynamicIterationCount.",
|
|
2332
|
-
logger_exports.LOG_LEVEL_VERBOSE
|
|
2333
|
-
);
|
|
2334
|
-
(0, logger_exports.Logger)(ex, logger_exports.LOG_LEVEL_VERBOSE);
|
|
2335
|
-
return await decrypt2(encryptedData, passphrase, false);
|
|
2336
|
-
} catch (ex2) {
|
|
2337
|
-
(0, logger_exports.Logger)("Completely failed to decrypt with V1 method.", logger_exports.LOG_LEVEL_VERBOSE);
|
|
2338
|
-
(0, logger_exports.Logger)(ex2, logger_exports.LOG_LEVEL_VERBOSE);
|
|
2339
|
-
return false;
|
|
2340
|
-
}
|
|
2341
|
-
}
|
|
2342
|
-
}
|
|
2343
|
-
var ENCRYPTED_META_PREFIX = "/\\:";
|
|
2344
|
-
function isEncryptedMeta(doc) {
|
|
2345
|
-
return "path" in doc && doc.path.startsWith(ENCRYPTED_META_PREFIX);
|
|
2346
|
-
}
|
|
2347
|
-
async function encryptMetaWithHKDF(doc, passphrase, pbkdf2Salt) {
|
|
2348
|
-
if (isEncryptedMeta(doc)) {
|
|
2349
|
-
return doc.path;
|
|
2350
|
-
}
|
|
2351
|
-
const props = {
|
|
2352
|
-
path: getPath(doc),
|
|
2353
|
-
mtime: doc.mtime,
|
|
2354
|
-
ctime: doc.ctime,
|
|
2355
|
-
size: doc.size,
|
|
2356
|
-
children: isMetaEntry(doc) ? doc.children : void 0
|
|
2357
|
-
};
|
|
2358
|
-
const propStr = JSON.stringify(props);
|
|
2359
|
-
const encryptedMeta = await encryptHKDFWorker(propStr, passphrase, pbkdf2Salt);
|
|
2360
|
-
return ENCRYPTED_META_PREFIX + encryptedMeta;
|
|
2361
|
-
}
|
|
2362
|
-
async function decryptMetaWithHKDF(meta, passphrase, pbkdf2Salt) {
|
|
2363
|
-
if (!meta.startsWith(ENCRYPTED_META_PREFIX)) {
|
|
2364
|
-
throw new Error("Meta is not encrypted with HKDF.");
|
|
2365
|
-
}
|
|
2366
|
-
const encryptedMeta = meta.slice(ENCRYPTED_META_PREFIX.length);
|
|
2367
|
-
const props = await decryptHKDF2(encryptedMeta, passphrase, pbkdf2Salt);
|
|
2368
|
-
const parsedProps = JSON.parse(props);
|
|
2369
|
-
return parsedProps;
|
|
2370
|
-
}
|
|
2371
|
-
var MESSAGE_FALLBACK_DECRYPT_FAILED = "Failed to decrypt the data with V1 method. Cannot encrypt with HKDF.";
|
|
2372
|
-
var ENCRYPTION_HKDF_FAILED = "Encryption with HKDF failed.";
|
|
2373
|
-
var DECRYPTION_HKDF_FAILED = "Decryption with HKDF failed.";
|
|
2374
|
-
var DECRYPTION_FALLBACK_FAILED = "Decryption with fallback failed.";
|
|
2375
|
-
async function incomingEncryptHKDF(doc, passphrase, useDynamicIterationCount, getPBKDF2Salt) {
|
|
2376
|
-
const saveDoc = {
|
|
2377
|
-
...doc
|
|
2378
|
-
};
|
|
2379
|
-
if (isEncryptedChunkEntry(saveDoc) || isSyncInfoEntry(saveDoc)) {
|
|
2380
|
-
try {
|
|
2381
|
-
const encryptionVersion = getEncryptionVersion(saveDoc);
|
|
2382
|
-
if (encryptionVersion === EncryptionVersions.ENCRYPTED) {
|
|
2383
|
-
const decrypted = await tryDecryptV1AsFallback(saveDoc.data, passphrase, useDynamicIterationCount);
|
|
2384
|
-
if (decrypted === false) {
|
|
2385
|
-
(0, logger_exports.Logger)(MESSAGE_FALLBACK_DECRYPT_FAILED, logger_exports.LOG_LEVEL_NOTICE);
|
|
2386
|
-
throw new Error(MESSAGE_FALLBACK_DECRYPT_FAILED);
|
|
2387
|
-
}
|
|
2388
|
-
const pbkdf2salt = await getPBKDF2Salt();
|
|
2389
|
-
saveDoc.data = await encryptHKDF2(saveDoc.data, passphrase, pbkdf2salt);
|
|
2390
|
-
saveDoc.e_ = true;
|
|
2391
|
-
}
|
|
2392
|
-
if (encryptionVersion === EncryptionVersions.HKDF) {
|
|
2393
|
-
} else if (encryptionVersion === EncryptionVersions.UNENCRYPTED) {
|
|
2394
|
-
const pbkdf2salt = await getPBKDF2Salt();
|
|
2395
|
-
saveDoc.data = await encryptHKDF2(saveDoc.data, passphrase, pbkdf2salt);
|
|
2396
|
-
saveDoc.e_ = true;
|
|
2397
|
-
}
|
|
2398
|
-
} catch (ex) {
|
|
2399
|
-
(0, logger_exports.Logger)(ENCRYPTION_HKDF_FAILED, logger_exports.LOG_LEVEL_NOTICE);
|
|
2400
|
-
(0, logger_exports.Logger)(ex);
|
|
2401
|
-
throw ex;
|
|
2402
|
-
}
|
|
2403
|
-
}
|
|
2404
|
-
if (shouldEncryptEdenHKDF(saveDoc)) {
|
|
2405
|
-
const pbkdf2salt = await getPBKDF2Salt();
|
|
2406
|
-
try {
|
|
2407
|
-
saveDoc.eden = {
|
|
2408
|
-
[EDEN_ENCRYPTED_KEY_HKDF]: {
|
|
2409
|
-
data: await encryptHKDF2(JSON.stringify(saveDoc.eden), passphrase, pbkdf2salt),
|
|
2410
|
-
epoch: 999999
|
|
2411
|
-
}
|
|
2412
|
-
};
|
|
2413
|
-
} catch (ex) {
|
|
2414
|
-
(0, logger_exports.Logger)(`${ENCRYPTION_HKDF_FAILED} on Eden`, logger_exports.LOG_LEVEL_NOTICE);
|
|
2415
|
-
(0, logger_exports.Logger)(ex);
|
|
2416
|
-
throw ex;
|
|
2417
|
-
}
|
|
2418
|
-
}
|
|
2419
|
-
if (isObfuscatedEntry(saveDoc)) {
|
|
2420
|
-
const pbkdf2salt = await getPBKDF2Salt();
|
|
2421
|
-
if (!isEncryptedMeta(saveDoc)) {
|
|
2422
|
-
try {
|
|
2423
|
-
saveDoc.path = await encryptMetaWithHKDF(
|
|
2424
|
-
saveDoc,
|
|
2425
|
-
passphrase,
|
|
2426
|
-
pbkdf2salt
|
|
2427
|
-
);
|
|
2428
|
-
saveDoc.mtime = 0;
|
|
2429
|
-
saveDoc.ctime = 0;
|
|
2430
|
-
saveDoc.size = 0;
|
|
2431
|
-
if ("children" in saveDoc) saveDoc.children = [];
|
|
2432
|
-
} catch (ex) {
|
|
2433
|
-
(0, logger_exports.Logger)(`${ENCRYPTION_HKDF_FAILED} on Metadata`, logger_exports.LOG_LEVEL_NOTICE);
|
|
2434
|
-
(0, logger_exports.Logger)(ex);
|
|
2435
|
-
throw ex;
|
|
2436
|
-
}
|
|
2437
|
-
}
|
|
2438
|
-
}
|
|
2439
|
-
return saveDoc;
|
|
2440
|
-
}
|
|
2441
|
-
async function outgoingDecryptHKDF(doc, migrationDecrypt, decrypted, passphrase, useDynamicIterationCount, getPBKDF2Salt) {
|
|
2442
|
-
const loadDoc = {
|
|
2443
|
-
...doc
|
|
2444
|
-
};
|
|
2445
|
-
if (isEncryptedChunkEntry(loadDoc) || isSyncInfoEntry(loadDoc)) {
|
|
2446
|
-
try {
|
|
2447
|
-
const encryptionVersion = getEncryptionVersion(loadDoc);
|
|
2448
|
-
if (encryptionVersion === EncryptionVersions.HKDF) {
|
|
2449
|
-
const pbkdf2salt = await getPBKDF2Salt();
|
|
2450
|
-
loadDoc.data = await decryptHKDF2(loadDoc.data, passphrase, pbkdf2salt);
|
|
2451
|
-
delete loadDoc.e_;
|
|
2452
|
-
} else if (encryptionVersion === EncryptionVersions.ENCRYPTED) {
|
|
2453
|
-
const decryptedData = await tryDecryptV1AsFallback(loadDoc.data, passphrase, useDynamicIterationCount);
|
|
2454
|
-
if (decryptedData === false) {
|
|
2455
|
-
(0, logger_exports.Logger)(MESSAGE_FALLBACK_DECRYPT_FAILED, logger_exports.LOG_LEVEL_NOTICE);
|
|
2456
|
-
throw new Error(MESSAGE_FALLBACK_DECRYPT_FAILED);
|
|
2457
|
-
}
|
|
2458
|
-
loadDoc.data = decryptedData;
|
|
2459
|
-
delete loadDoc.e_;
|
|
2460
|
-
} else if (encryptionVersion === EncryptionVersions.UNENCRYPTED) {
|
|
2461
|
-
} else {
|
|
2462
|
-
(0, logger_exports.Logger)("Unknown encryption version. Cannot decrypt.", logger_exports.LOG_LEVEL_NOTICE);
|
|
2463
|
-
throw new Error("Unknown encryption version. Cannot decrypt.");
|
|
2464
|
-
}
|
|
2465
|
-
} catch (ex) {
|
|
2466
|
-
(0, logger_exports.Logger)(DECRYPTION_HKDF_FAILED, logger_exports.LOG_LEVEL_NOTICE);
|
|
2467
|
-
(0, logger_exports.Logger)(ex);
|
|
2468
|
-
throw ex;
|
|
2469
|
-
}
|
|
2470
|
-
}
|
|
2471
|
-
if (isObfuscatedEntry(loadDoc)) {
|
|
2472
|
-
const path = getPath(loadDoc);
|
|
2473
|
-
if (isEncryptedMeta(loadDoc)) {
|
|
2474
|
-
const pbkdf2salt = await getPBKDF2Salt();
|
|
2475
|
-
try {
|
|
2476
|
-
const metadata = await decryptMetaWithHKDF(path, passphrase, pbkdf2salt);
|
|
2477
|
-
for (const key of Object.keys(metadata)) {
|
|
2478
|
-
loadDoc[key] = metadata[key];
|
|
2479
|
-
}
|
|
2480
|
-
} catch (ex) {
|
|
2481
|
-
(0, logger_exports.Logger)(`${DECRYPTION_HKDF_FAILED} on Path`, logger_exports.LOG_LEVEL_NOTICE);
|
|
2482
|
-
(0, logger_exports.Logger)(ex);
|
|
2483
|
-
throw ex;
|
|
2484
|
-
}
|
|
2485
|
-
} else if ((0, e2ee_v2_exports.isPathProbablyObfuscated)(path)) {
|
|
2486
|
-
const decryptedPath = await tryDecryptV1AsFallback(path, passphrase, useDynamicIterationCount);
|
|
2487
|
-
if (decryptedPath === false) {
|
|
2488
|
-
(0, logger_exports.Logger)(`${MESSAGE_FALLBACK_DECRYPT_FAILED} on Path`, logger_exports.LOG_LEVEL_NOTICE);
|
|
2489
|
-
throw new Error(MESSAGE_FALLBACK_DECRYPT_FAILED);
|
|
2490
|
-
}
|
|
2491
|
-
loadDoc.path = decryptedPath;
|
|
2492
|
-
}
|
|
2493
|
-
}
|
|
2494
|
-
let readEden = {};
|
|
2495
|
-
let edenDecrypted = false;
|
|
2496
|
-
if (shouldDecryptEden(loadDoc)) {
|
|
2497
|
-
try {
|
|
2498
|
-
const decryptedEden = await tryDecryptV1AsFallback(
|
|
2499
|
-
loadDoc.eden[EDEN_ENCRYPTED_KEY].data,
|
|
2500
|
-
passphrase,
|
|
2501
|
-
useDynamicIterationCount
|
|
2502
|
-
);
|
|
2503
|
-
if (decryptedEden === false) throw new Error(MESSAGE_FALLBACK_DECRYPT_FAILED);
|
|
2504
|
-
readEden = {
|
|
2505
|
-
...readEden,
|
|
2506
|
-
...JSON.parse(decryptedEden)
|
|
2507
|
-
};
|
|
2508
|
-
edenDecrypted = true;
|
|
2509
|
-
} catch (ex) {
|
|
2510
|
-
(0, logger_exports.Logger)(`${DECRYPTION_FALLBACK_FAILED} on Eden`, logger_exports.LOG_LEVEL_NOTICE);
|
|
2511
|
-
(0, logger_exports.Logger)(ex);
|
|
2512
|
-
throw ex;
|
|
2513
|
-
}
|
|
2514
|
-
}
|
|
2515
|
-
if (shouldDecryptEdenHKDF(loadDoc)) {
|
|
2516
|
-
const pbkdf2salt = await getPBKDF2Salt();
|
|
2517
|
-
try {
|
|
2518
|
-
const decryptedEdenData = await decryptHKDF2(
|
|
2519
|
-
loadDoc.eden[EDEN_ENCRYPTED_KEY_HKDF].data,
|
|
2520
|
-
passphrase,
|
|
2521
|
-
pbkdf2salt
|
|
2522
|
-
);
|
|
2523
|
-
readEden = {
|
|
2524
|
-
...readEden,
|
|
2525
|
-
...JSON.parse(decryptedEdenData)
|
|
2526
|
-
};
|
|
2527
|
-
edenDecrypted = true;
|
|
2528
|
-
} catch (ex) {
|
|
2529
|
-
(0, logger_exports.Logger)(`${DECRYPTION_HKDF_FAILED} on Eden`, logger_exports.LOG_LEVEL_NOTICE);
|
|
2530
|
-
(0, logger_exports.Logger)(ex);
|
|
2531
|
-
throw ex;
|
|
2532
|
-
}
|
|
2533
|
-
}
|
|
2534
|
-
if (edenDecrypted) {
|
|
2535
|
-
loadDoc.eden = readEden;
|
|
2536
|
-
} else {
|
|
2537
|
-
}
|
|
2538
|
-
return loadDoc;
|
|
2539
|
-
}
|
|
2540
|
-
async function incomingEncryptV1(doc, passphrase, useDynamicIterationCount) {
|
|
2541
|
-
const saveDoc = {
|
|
2542
|
-
...doc
|
|
2543
|
-
};
|
|
2544
|
-
if (isEncryptedChunkEntry(saveDoc) || isSyncInfoEntry(saveDoc)) {
|
|
2545
|
-
try {
|
|
2546
|
-
if (!("e_" in saveDoc)) {
|
|
2547
|
-
saveDoc.data = await encrypt2(saveDoc.data, passphrase, useDynamicIterationCount);
|
|
2548
|
-
saveDoc.e_ = true;
|
|
2549
|
-
}
|
|
2550
|
-
} catch (ex) {
|
|
2551
|
-
(0, logger_exports.Logger)("Encryption failed.", logger_exports.LOG_LEVEL_NOTICE);
|
|
2552
|
-
(0, logger_exports.Logger)(ex);
|
|
2553
|
-
throw ex;
|
|
2554
|
-
}
|
|
2555
|
-
}
|
|
2556
|
-
if (shouldEncryptEden(saveDoc)) {
|
|
2557
|
-
saveDoc.eden = {
|
|
2558
|
-
[EDEN_ENCRYPTED_KEY]: {
|
|
2559
|
-
data: await encrypt2(JSON.stringify(saveDoc.eden), passphrase, useDynamicIterationCount),
|
|
2560
|
-
epoch: 999999
|
|
2561
|
-
}
|
|
2562
|
-
};
|
|
2563
|
-
}
|
|
2564
|
-
if (isObfuscatedEntry(saveDoc)) {
|
|
2565
|
-
try {
|
|
2566
|
-
const path = getPath(saveDoc);
|
|
2567
|
-
if (!(0, e2ee_v2_exports.isPathProbablyObfuscated)(path)) {
|
|
2568
|
-
saveDoc.path = await (0, e2ee_v2_exports.obfuscatePath)(
|
|
2569
|
-
path,
|
|
2570
|
-
passphrase,
|
|
2571
|
-
useDynamicIterationCount
|
|
2572
|
-
);
|
|
2573
|
-
}
|
|
2574
|
-
} catch (ex) {
|
|
2575
|
-
(0, logger_exports.Logger)("Encryption failed.", logger_exports.LOG_LEVEL_NOTICE);
|
|
2576
|
-
(0, logger_exports.Logger)(ex);
|
|
2577
|
-
throw ex;
|
|
2578
|
-
}
|
|
2579
|
-
}
|
|
2580
|
-
return saveDoc;
|
|
2581
|
-
}
|
|
2582
|
-
async function outgoingDecryptV1(doc, migrationDecrypt, decrypted, passphrase, useDynamicIterationCount) {
|
|
2583
|
-
const loadDoc = {
|
|
2584
|
-
...doc
|
|
2585
|
-
};
|
|
2586
|
-
const _isChunkOrSyncInfo = isEncryptedChunkEntry(loadDoc) || isSyncInfoEntry(loadDoc);
|
|
2587
|
-
const _isObfuscatedEntry = isObfuscatedEntry(loadDoc);
|
|
2588
|
-
const _shouldDecryptEden = shouldDecryptEden(loadDoc);
|
|
2589
|
-
if (_isChunkOrSyncInfo || _isObfuscatedEntry || _shouldDecryptEden) {
|
|
2590
|
-
if (migrationDecrypt && decrypted.has(loadDoc._id)) {
|
|
2591
|
-
return loadDoc;
|
|
2592
|
-
}
|
|
2593
|
-
try {
|
|
2594
|
-
if (_isChunkOrSyncInfo) {
|
|
2595
|
-
loadDoc.data = await decrypt2(loadDoc.data, passphrase, useDynamicIterationCount);
|
|
2596
|
-
delete loadDoc.e_;
|
|
2597
|
-
} else if ("e_" in loadDoc) {
|
|
2598
|
-
loadDoc.data = await decrypt2(loadDoc.data, passphrase, useDynamicIterationCount);
|
|
2599
|
-
delete loadDoc.e_;
|
|
2600
|
-
}
|
|
2601
|
-
if (_isObfuscatedEntry) {
|
|
2602
|
-
const path = getPath(loadDoc);
|
|
2603
|
-
if ((0, e2ee_v2_exports.isPathProbablyObfuscated)(path)) {
|
|
2604
|
-
loadDoc.path = await decrypt2(
|
|
2605
|
-
path,
|
|
2606
|
-
passphrase,
|
|
2607
|
-
useDynamicIterationCount
|
|
2608
|
-
);
|
|
2609
|
-
}
|
|
2610
|
-
}
|
|
2611
|
-
if (_shouldDecryptEden) {
|
|
2612
|
-
loadDoc.eden = JSON.parse(
|
|
2613
|
-
await decrypt2(loadDoc.eden[EDEN_ENCRYPTED_KEY].data, passphrase, useDynamicIterationCount)
|
|
2614
|
-
);
|
|
2615
|
-
}
|
|
2616
|
-
if (migrationDecrypt) {
|
|
2617
|
-
decrypted.set(loadDoc._id, true);
|
|
2618
|
-
}
|
|
2619
|
-
} catch (ex) {
|
|
2620
|
-
if (useDynamicIterationCount) {
|
|
2621
|
-
try {
|
|
2622
|
-
if (_isChunkOrSyncInfo) {
|
|
2623
|
-
loadDoc.data = await decrypt2(loadDoc.data, passphrase, false);
|
|
2624
|
-
}
|
|
2625
|
-
if (_isObfuscatedEntry) {
|
|
2626
|
-
const path = getPath(loadDoc);
|
|
2627
|
-
if ((0, e2ee_v2_exports.isPathProbablyObfuscated)(path)) {
|
|
2628
|
-
loadDoc.path = await decrypt2(path, passphrase, false);
|
|
2629
|
-
}
|
|
2630
|
-
}
|
|
2631
|
-
if (_shouldDecryptEden) {
|
|
2632
|
-
loadDoc.eden = JSON.parse(
|
|
2633
|
-
await decrypt2(loadDoc.eden[EDEN_ENCRYPTED_KEY].data, passphrase, false)
|
|
2634
|
-
);
|
|
2635
|
-
}
|
|
2636
|
-
if (migrationDecrypt) {
|
|
2637
|
-
decrypted.set(loadDoc._id, true);
|
|
2638
|
-
}
|
|
2639
|
-
} catch (ex2) {
|
|
2640
|
-
if (migrationDecrypt && ex2.name == "SyntaxError") {
|
|
2641
|
-
return loadDoc;
|
|
2642
|
-
}
|
|
2643
|
-
(0, logger_exports.Logger)("Decryption failed.", logger_exports.LOG_LEVEL_NOTICE);
|
|
2644
|
-
(0, logger_exports.Logger)(ex2, logger_exports.LOG_LEVEL_VERBOSE);
|
|
2645
|
-
(0, logger_exports.Logger)(`id:${loadDoc._id}-${loadDoc._rev?.substring(0, 10)}`, logger_exports.LOG_LEVEL_VERBOSE);
|
|
2646
|
-
throw ex2;
|
|
2647
|
-
}
|
|
2648
|
-
} else {
|
|
2649
|
-
(0, logger_exports.Logger)("Decryption failed.", logger_exports.LOG_LEVEL_NOTICE);
|
|
2650
|
-
(0, logger_exports.Logger)(ex, logger_exports.LOG_LEVEL_VERBOSE);
|
|
2651
|
-
(0, logger_exports.Logger)(`id:${loadDoc._id}-${loadDoc._rev?.substring(0, 10)}`, logger_exports.LOG_LEVEL_VERBOSE);
|
|
2652
|
-
throw ex;
|
|
2653
|
-
}
|
|
2654
|
-
}
|
|
2655
|
-
}
|
|
2656
|
-
return loadDoc;
|
|
2657
|
-
}
|
|
2658
|
-
var preprocessOutgoing = async (doc) => {
|
|
2659
|
-
return await Promise.resolve(doc);
|
|
2660
|
-
};
|
|
2661
|
-
var preprocessIncoming = async (doc) => {
|
|
2662
|
-
return await Promise.resolve(doc);
|
|
2663
|
-
};
|
|
2664
|
-
var enableEncryption = (db, passphrase, useDynamicIterationCount, migrationDecrypt, getPBKDF2Salt, algorithm) => {
|
|
2665
|
-
const decrypted = /* @__PURE__ */ new Map();
|
|
2666
|
-
const incoming = (doc) => algorithm === E2EEAlgorithms.V2 ? incomingEncryptHKDF(doc, passphrase, useDynamicIterationCount, getPBKDF2Salt) : incomingEncryptV1(doc, passphrase, useDynamicIterationCount);
|
|
2667
|
-
const outgoing = (doc) => algorithm !== E2EEAlgorithms.ForceV1 ? outgoingDecryptHKDF(doc, migrationDecrypt, decrypted, passphrase, useDynamicIterationCount, getPBKDF2Salt) : outgoingDecryptV1(doc, migrationDecrypt, decrypted, passphrase, useDynamicIterationCount);
|
|
2668
|
-
preprocessOutgoing = incoming;
|
|
2669
|
-
preprocessIncoming = outgoing;
|
|
2670
|
-
db.transform({
|
|
2671
|
-
incoming,
|
|
2672
|
-
outgoing
|
|
2673
|
-
});
|
|
2674
|
-
};
|
|
2675
|
-
function disableEncryption() {
|
|
2676
|
-
preprocessOutgoing = async (doc) => {
|
|
2677
|
-
return await Promise.resolve(doc);
|
|
2678
|
-
};
|
|
2679
|
-
preprocessIncoming = async (doc) => {
|
|
2680
|
-
return await Promise.resolve(doc);
|
|
2681
|
-
};
|
|
2682
|
-
}
|
|
2683
|
-
var EDEN_ENCRYPTED_KEY = "h:++encrypted";
|
|
2684
|
-
var EDEN_ENCRYPTED_KEY_HKDF = "h:++encrypted-hkdf";
|
|
2685
|
-
function shouldEncryptEden(doc) {
|
|
2686
|
-
if ("eden" in doc && !(EDEN_ENCRYPTED_KEY in doc.eden)) {
|
|
2687
|
-
return true;
|
|
2688
|
-
}
|
|
2689
|
-
return false;
|
|
2690
|
-
}
|
|
2691
|
-
function shouldEncryptEdenHKDF(doc) {
|
|
2692
|
-
if ("eden" in doc && !(EDEN_ENCRYPTED_KEY_HKDF in doc.eden)) {
|
|
2693
|
-
if (Object.keys(doc.eden).length === 0) {
|
|
2694
|
-
return false;
|
|
2695
|
-
}
|
|
2696
|
-
return true;
|
|
2697
|
-
}
|
|
2698
|
-
return false;
|
|
2699
|
-
}
|
|
2700
|
-
function shouldDecryptEden(doc) {
|
|
2701
|
-
if ("eden" in doc && EDEN_ENCRYPTED_KEY in doc.eden) {
|
|
2702
|
-
return true;
|
|
2703
|
-
}
|
|
2704
|
-
return false;
|
|
2705
|
-
}
|
|
2706
|
-
function shouldDecryptEdenHKDF(doc) {
|
|
2707
|
-
if ("eden" in doc && EDEN_ENCRYPTED_KEY_HKDF in doc.eden) {
|
|
2708
|
-
return true;
|
|
2709
|
-
}
|
|
2710
|
-
return false;
|
|
2711
|
-
}
|
|
2712
|
-
|
|
2713
|
-
// lib/livesync-commonlib/src/API/DirectFileManipulatorV2.ts
|
|
2714
|
-
import {
|
|
2715
|
-
LEVEL_INFO,
|
|
2716
|
-
LEVEL_VERBOSE,
|
|
2717
|
-
LOG_LEVEL_INFO as LOG_LEVEL_INFO4,
|
|
2718
|
-
LOG_LEVEL_NOTICE as LOG_LEVEL_NOTICE4,
|
|
2719
|
-
LOG_LEVEL_VERBOSE as LOG_LEVEL_VERBOSE10,
|
|
2720
|
-
Logger as Logger10
|
|
2721
|
-
} from "octagonal-wheels/common/logger";
|
|
2722
|
-
import { promiseWithResolver as promiseWithResolver2 } from "octagonal-wheels/promises";
|
|
2723
|
-
|
|
2724
|
-
// lib/livesync-commonlib/src/replication/SyncParamsHandler.ts
|
|
2725
|
-
import { createPBKDF2Salt } from "octagonal-wheels/encryption/hkdf";
|
|
2726
|
-
var _handlers = /* @__PURE__ */ new Map();
|
|
2727
|
-
function createSyncParamsHanderForServer(key, options) {
|
|
2728
|
-
if (_handlers.has(key)) {
|
|
2729
|
-
return _handlers.get(key);
|
|
2730
|
-
}
|
|
2731
|
-
const handler = createSyncParamsHandler(options);
|
|
2732
|
-
_handlers.set(key, handler);
|
|
2733
|
-
return handler;
|
|
2734
|
-
}
|
|
2735
|
-
var SyncParamsHandlerError = class extends LiveSyncError {
|
|
2736
|
-
};
|
|
2737
|
-
var SyncParamsFetchError = class extends SyncParamsHandlerError {
|
|
2738
|
-
};
|
|
2739
|
-
var SyncParamsNotFoundError = class extends SyncParamsHandlerError {
|
|
2740
|
-
};
|
|
2741
|
-
var SyncParamsUpdateError = class extends SyncParamsHandlerError {
|
|
2742
|
-
};
|
|
2743
|
-
function createSyncParamsHandler({ put, get, create }) {
|
|
2744
|
-
let taskFetchParameters = void 0;
|
|
2745
|
-
const _fetchSyncParameters = async () => {
|
|
2746
|
-
let syncParams = void 0;
|
|
2747
|
-
try {
|
|
2748
|
-
let shouldRetry = false;
|
|
2749
|
-
do {
|
|
2750
|
-
shouldRetry = false;
|
|
2751
|
-
try {
|
|
2752
|
-
syncParams = await get();
|
|
2753
|
-
(0, logger_exports.Logger)(`Fetched synchronisation parameters`, logger_exports.LOG_LEVEL_INFO);
|
|
2754
|
-
} catch (ex) {
|
|
2755
|
-
if (LiveSyncError.isCausedBy(ex, SyncParamsNotFoundError)) {
|
|
2756
|
-
(0, logger_exports.Logger)(`Synchronisation parameters not found, creating new ones`, logger_exports.LOG_LEVEL_INFO);
|
|
2757
|
-
const newSyncParams = await create();
|
|
2758
|
-
const putResult = await put(newSyncParams);
|
|
2759
|
-
if (!putResult) {
|
|
2760
|
-
(0, logger_exports.Logger)(`Failed to store initial synchronisation parameters`, logger_exports.LOG_LEVEL_INFO);
|
|
2761
|
-
throw new SyncParamsUpdateError(`Failed to store initial synchronisation parameters`);
|
|
2762
|
-
}
|
|
2763
|
-
(0, logger_exports.Logger)(
|
|
2764
|
-
`Initial synchronisation parameters stored successfully, retrying fetch`,
|
|
2765
|
-
logger_exports.LOG_LEVEL_INFO
|
|
2766
|
-
);
|
|
2767
|
-
shouldRetry = true;
|
|
2768
|
-
} else {
|
|
2769
|
-
throw ex;
|
|
2770
|
-
}
|
|
2771
|
-
}
|
|
2772
|
-
} while (shouldRetry);
|
|
2773
|
-
if (!syncParams) {
|
|
2774
|
-
throw new SyncParamsFetchError(`Unexpected empty synchronisation parameters`);
|
|
2775
|
-
}
|
|
2776
|
-
if (!syncParams.pbkdf2salt) {
|
|
2777
|
-
(0, logger_exports.Logger)(`Synchronisation parameters do not have PBKDF2 salt, generating a new salt`, logger_exports.LOG_LEVEL_INFO);
|
|
2778
|
-
const salt = await arrayBufferToBase64Single(createPBKDF2Salt());
|
|
2779
|
-
if (!salt) {
|
|
2780
|
-
(0, logger_exports.Logger)(`Failed to generate PBKDF2 salt`, logger_exports.LOG_LEVEL_INFO);
|
|
2781
|
-
throw new SyncParamsFetchError(`Failed to generate PBKDF2 salt`);
|
|
2782
|
-
}
|
|
2783
|
-
syncParams.pbkdf2salt = salt;
|
|
2784
|
-
const putResult = await put(syncParams);
|
|
2785
|
-
if (!putResult) {
|
|
2786
|
-
(0, logger_exports.Logger)(`Failed to store synchronisation parameters with new PBKDF2 salt`, logger_exports.LOG_LEVEL_INFO);
|
|
2787
|
-
throw new SyncParamsUpdateError(`Failed to store synchronisation parameters with new PBKDF2 salt`);
|
|
2788
|
-
}
|
|
2789
|
-
syncParams = await get();
|
|
2790
|
-
}
|
|
2791
|
-
if (!syncParams) {
|
|
2792
|
-
throw new Error(`Failed to prepare synchronisation key in synchronisation parameters`);
|
|
2793
|
-
}
|
|
2794
|
-
(0, logger_exports.Logger)(`Synchronisation parameters fetched successfully`, logger_exports.LOG_LEVEL_INFO);
|
|
2795
|
-
if (!syncParams.pbkdf2saltDecoded) {
|
|
2796
|
-
const decodedSalt = new Uint8Array(base64ToArrayBufferInternalBrowser(syncParams.pbkdf2salt));
|
|
2797
|
-
if (!decodedSalt) {
|
|
2798
|
-
throw new SyncParamsFetchError(`Failed to decode PBKDF2 salt`);
|
|
2799
|
-
}
|
|
2800
|
-
syncParams.pbkdf2saltDecoded = decodedSalt;
|
|
2801
|
-
}
|
|
2802
|
-
return syncParams;
|
|
2803
|
-
} catch (ex) {
|
|
2804
|
-
(0, logger_exports.Logger)(`Failed to fetch synchronisation parameters`, logger_exports.LOG_LEVEL_INFO);
|
|
2805
|
-
(0, logger_exports.Logger)(ex, logger_exports.LOG_LEVEL_VERBOSE);
|
|
2806
|
-
taskFetchParameters = void 0;
|
|
2807
|
-
return false;
|
|
2808
|
-
}
|
|
2809
|
-
};
|
|
2810
|
-
const fetchSyncParameters = (refresh = false) => {
|
|
2811
|
-
if (taskFetchParameters && !refresh) {
|
|
2812
|
-
return taskFetchParameters;
|
|
2813
|
-
}
|
|
2814
|
-
taskFetchParameters = _fetchSyncParameters();
|
|
2815
|
-
return taskFetchParameters;
|
|
2816
|
-
};
|
|
2817
|
-
return {
|
|
2818
|
-
fetch: fetchSyncParameters,
|
|
2819
|
-
getPBKDF2Salt: async (refresh = false) => {
|
|
2820
|
-
const syncParams = await fetchSyncParameters(refresh);
|
|
2821
|
-
if (!syncParams) {
|
|
2822
|
-
(0, logger_exports.Logger)(`Failed to fetch synchronisation parameters`, logger_exports.LOG_LEVEL_INFO);
|
|
2823
|
-
throw new SyncParamsFetchError(`Failed to fetch synchronisation parameters`);
|
|
2824
|
-
}
|
|
2825
|
-
return syncParams.pbkdf2saltDecoded;
|
|
2826
|
-
}
|
|
2827
|
-
};
|
|
2828
|
-
}
|
|
2829
|
-
|
|
2830
|
-
// lib/livesync-commonlib/src/ContentSplitter/ContentSplitter.ts
|
|
2831
|
-
var MAX_CHUNKS_SIZE_ON_UI = 1024;
|
|
2832
|
-
|
|
2833
|
-
// lib/livesync-commonlib/src/ContentSplitter/ContentSplitterBase.ts
|
|
2834
|
-
var ContentSplitterCore = class {
|
|
2835
|
-
/**
|
|
2836
|
-
* Options for the content splitter.
|
|
2837
|
-
* These settings include the chunk splitter version and other configurations.
|
|
2838
|
-
*/
|
|
2839
|
-
options;
|
|
2840
|
-
/**
|
|
2841
|
-
* Task for initialising the content splitter.
|
|
2842
|
-
* This ensures that the splitter is initialised before any operations are performed.
|
|
2843
|
-
*/
|
|
2844
|
-
initialised;
|
|
2845
|
-
/**
|
|
2846
|
-
* Constructor for the content splitter core.
|
|
2847
|
-
* @param params Content splitter options
|
|
2848
|
-
*/
|
|
2849
|
-
constructor(params) {
|
|
2850
|
-
this.options = params;
|
|
2851
|
-
this.initialised = this.initialise(params);
|
|
2852
|
-
}
|
|
2853
|
-
};
|
|
2854
|
-
var ContentSplitterBase = class extends ContentSplitterCore {
|
|
2855
|
-
initialise(_options) {
|
|
2856
|
-
return Promise.resolve(true);
|
|
2857
|
-
}
|
|
2858
|
-
/**
|
|
2859
|
-
* Check whether the content splitter is available for the given settings.
|
|
2860
|
-
* @param setting Content splitter options
|
|
2861
|
-
* @returns True if the content splitter is available; false otherwise
|
|
2862
|
-
*/
|
|
2863
|
-
static isAvailableFor(setting) {
|
|
2864
|
-
return false;
|
|
2865
|
-
}
|
|
2866
|
-
getParamsFor(entry) {
|
|
2867
|
-
const maxChunkSize = Math.floor(MAX_DOC_SIZE_BIN * ((this.options.settings.customChunkSize || 0) * 1 + 1));
|
|
2868
|
-
const pieceSize = maxChunkSize;
|
|
2869
|
-
const minimumChunkSize = this.options.settings.minimumChunkSize;
|
|
2870
|
-
const path = entry.path;
|
|
2871
|
-
const plainSplit = shouldSplitAsPlainText(path);
|
|
2872
|
-
const maxSize = MAX_CHUNKS_SIZE_ON_UI;
|
|
2873
|
-
const blob = entry.data instanceof Blob ? entry.data : createTextBlob(entry.data);
|
|
2874
|
-
let useWorker = true;
|
|
2875
|
-
if (this.options.settings.disableWorkerForGeneratingChunks) {
|
|
2876
|
-
useWorker = false;
|
|
2877
|
-
}
|
|
2878
|
-
if (useWorker && this.options.settings.processSmallFilesInUIThread) {
|
|
2879
|
-
if (blob.size <= maxSize) {
|
|
2880
|
-
useWorker = false;
|
|
2881
|
-
}
|
|
2882
|
-
}
|
|
2883
|
-
const useSegmenter = this.options.settings.chunkSplitterVersion === ChunkAlgorithms.V2Segmenter;
|
|
2884
|
-
return {
|
|
2885
|
-
blob,
|
|
2886
|
-
path,
|
|
2887
|
-
pieceSize,
|
|
2888
|
-
plainSplit,
|
|
2889
|
-
minimumChunkSize,
|
|
2890
|
-
useWorker,
|
|
2891
|
-
useSegmenter
|
|
2892
|
-
};
|
|
2893
|
-
}
|
|
2894
|
-
/**
|
|
2895
|
-
* Split the content of the loaded entry into chunks.
|
|
2896
|
-
* This method waits for the initialisation task to complete before proceeding.
|
|
2897
|
-
* @param entry The loaded entry to be split into chunks
|
|
2898
|
-
* @returns A generator that yields the split chunks
|
|
2899
|
-
*/
|
|
2900
|
-
async splitContent(entry) {
|
|
2901
|
-
await this.initialised;
|
|
2902
|
-
const options = this.getParamsFor(entry);
|
|
2903
|
-
const generator = await this.processSplit(options);
|
|
2904
|
-
return generator;
|
|
2905
|
-
}
|
|
2906
|
-
};
|
|
2907
|
-
|
|
2908
|
-
// lib/livesync-commonlib/src/ContentSplitter/ContentSplitterRabinKarp.ts
|
|
2909
|
-
var ContentSplitterRabinKarp = class extends ContentSplitterBase {
|
|
2910
|
-
static isAvailableFor(setting) {
|
|
2911
|
-
return setting.settings.chunkSplitterVersion === ChunkAlgorithms.RabinKarp;
|
|
2912
|
-
}
|
|
2913
|
-
async processSplit(options) {
|
|
2914
|
-
if (options.useWorker) {
|
|
2915
|
-
return splitPieces2WorkerRabinKarp(
|
|
2916
|
-
options.blob,
|
|
2917
|
-
options.pieceSize,
|
|
2918
|
-
options.plainSplit,
|
|
2919
|
-
options.minimumChunkSize,
|
|
2920
|
-
options.path
|
|
2921
|
-
)();
|
|
2922
|
-
} else {
|
|
2923
|
-
return (await splitPiecesRabinKarp(
|
|
2924
|
-
options.blob,
|
|
2925
|
-
options.pieceSize,
|
|
2926
|
-
options.plainSplit,
|
|
2927
|
-
options.minimumChunkSize,
|
|
2928
|
-
options.path
|
|
2929
|
-
))();
|
|
2930
|
-
}
|
|
2931
|
-
}
|
|
2932
|
-
};
|
|
2933
|
-
|
|
2934
|
-
// lib/livesync-commonlib/src/ContentSplitter/ContentSplitterV1.ts
|
|
2935
|
-
var ContentSplitterV1 = class extends ContentSplitterBase {
|
|
2936
|
-
static isAvailableFor(setting) {
|
|
2937
|
-
return setting.settings.chunkSplitterVersion === ChunkAlgorithms.V1 || setting.settings.chunkSplitterVersion === "";
|
|
2938
|
-
}
|
|
2939
|
-
async processSplit(options) {
|
|
2940
|
-
if (options.useWorker) {
|
|
2941
|
-
return splitPieces2Worker(
|
|
2942
|
-
options.blob,
|
|
2943
|
-
options.pieceSize,
|
|
2944
|
-
options.plainSplit,
|
|
2945
|
-
options.minimumChunkSize,
|
|
2946
|
-
options.path,
|
|
2947
|
-
options.useSegmenter
|
|
2948
|
-
)();
|
|
2949
|
-
} else {
|
|
2950
|
-
return (await splitPieces2(
|
|
2951
|
-
options.blob,
|
|
2952
|
-
options.pieceSize,
|
|
2953
|
-
options.plainSplit,
|
|
2954
|
-
options.minimumChunkSize,
|
|
2955
|
-
options.path,
|
|
2956
|
-
options.useSegmenter
|
|
2957
|
-
))();
|
|
2958
|
-
}
|
|
2959
|
-
}
|
|
2960
|
-
};
|
|
2961
|
-
|
|
2962
|
-
// lib/livesync-commonlib/src/ContentSplitter/ContentSplitterV2.ts
|
|
2963
|
-
var ContentSplitterV2 = class extends ContentSplitterBase {
|
|
2964
|
-
static isAvailableFor(setting) {
|
|
2965
|
-
return setting.settings.chunkSplitterVersion === ChunkAlgorithms.V2 || setting.settings.chunkSplitterVersion === ChunkAlgorithms.V2Segmenter;
|
|
2966
|
-
}
|
|
2967
|
-
async processSplit(options) {
|
|
2968
|
-
if (options.useWorker) {
|
|
2969
|
-
return splitPieces2WorkerV2(
|
|
2970
|
-
options.blob,
|
|
2971
|
-
options.pieceSize,
|
|
2972
|
-
options.plainSplit,
|
|
2973
|
-
options.minimumChunkSize,
|
|
2974
|
-
options.path,
|
|
2975
|
-
options.useSegmenter
|
|
2976
|
-
)();
|
|
2977
|
-
} else {
|
|
2978
|
-
return (await splitPieces2V2(
|
|
2979
|
-
options.blob,
|
|
2980
|
-
options.pieceSize,
|
|
2981
|
-
options.plainSplit,
|
|
2982
|
-
options.minimumChunkSize,
|
|
2983
|
-
options.path,
|
|
2984
|
-
options.useSegmenter
|
|
2985
|
-
))();
|
|
2986
|
-
}
|
|
2987
|
-
}
|
|
2988
|
-
};
|
|
2989
|
-
|
|
2990
|
-
// lib/livesync-commonlib/src/ContentSplitter/ContentSplitters.ts
|
|
2991
|
-
var ContentSplitters = [ContentSplitterV1, ContentSplitterV2, ContentSplitterRabinKarp];
|
|
2992
|
-
var ContentSplitter = class extends ContentSplitterCore {
|
|
2993
|
-
_activeSplitter;
|
|
2994
|
-
constructor(options) {
|
|
2995
|
-
super(options);
|
|
2996
|
-
}
|
|
2997
|
-
initialise(options) {
|
|
2998
|
-
for (const Splitter of ContentSplitters) {
|
|
2999
|
-
if (Splitter.isAvailableFor(options)) {
|
|
3000
|
-
this._activeSplitter = new Splitter(options);
|
|
3001
|
-
break;
|
|
3002
|
-
}
|
|
3003
|
-
}
|
|
3004
|
-
if (!this._activeSplitter) {
|
|
3005
|
-
throw new Error(`ContentSplitter: No available splitter for settings!!`);
|
|
3006
|
-
}
|
|
3007
|
-
return this._activeSplitter.initialise(options);
|
|
3008
|
-
}
|
|
3009
|
-
async splitContent(entry) {
|
|
3010
|
-
await this.initialised;
|
|
3011
|
-
return this._activeSplitter.splitContent(entry);
|
|
3012
|
-
}
|
|
3013
|
-
};
|
|
3014
|
-
|
|
3015
|
-
// lib/livesync-commonlib/src/managers/ChangeManager.ts
|
|
3016
|
-
import { FallbackWeakRef as FallbackWeakRef3 } from "octagonal-wheels/common/polyfill";
|
|
3017
|
-
var ChangeManager = class {
|
|
3018
|
-
/**
|
|
3019
|
-
* The PouchDB database instance being monitored.
|
|
3020
|
-
*/
|
|
3021
|
-
_database;
|
|
3022
|
-
/**
|
|
3023
|
-
* Creates a new instance of the ChangeManager.
|
|
3024
|
-
*
|
|
3025
|
-
* @param options - Configuration options for the ChangeManager.
|
|
3026
|
-
*/
|
|
3027
|
-
constructor(options) {
|
|
3028
|
-
this._database = options.database;
|
|
3029
|
-
this.setupListener();
|
|
3030
|
-
}
|
|
3031
|
-
/**
|
|
3032
|
-
* A list of registered callbacks wrapped in WeakRefs to avoid memory leaks.
|
|
3033
|
-
*/
|
|
3034
|
-
_callbacks = [];
|
|
3035
|
-
/**
|
|
3036
|
-
* Registers a new callback to be invoked when a change occurs.
|
|
3037
|
-
*
|
|
3038
|
-
* @param callback - The callback function to register.
|
|
3039
|
-
*/
|
|
3040
|
-
addCallback(callback) {
|
|
3041
|
-
const callbackHandler = new FallbackWeakRef3(callback);
|
|
3042
|
-
this._callbacks.push(callbackHandler);
|
|
3043
|
-
return () => {
|
|
3044
|
-
this._callbacks = this._callbacks.filter((cb) => cb !== callbackHandler);
|
|
3045
|
-
};
|
|
3046
|
-
}
|
|
3047
|
-
removeCallback(callback) {
|
|
3048
|
-
this._callbacks = this._callbacks.filter((cb) => cb.deref() !== callback);
|
|
3049
|
-
}
|
|
3050
|
-
/**
|
|
3051
|
-
* The PouchDB changes feed instance, if active.
|
|
3052
|
-
*/
|
|
3053
|
-
_changes;
|
|
3054
|
-
/**
|
|
3055
|
-
* Handles a change event from the PouchDB changes feed.
|
|
3056
|
-
*
|
|
3057
|
-
* @param changeResponse - The change response object from the PouchDB changes feed.
|
|
3058
|
-
*/
|
|
3059
|
-
_onChange(changeResponse) {
|
|
3060
|
-
if (!this._callbacks.length) {
|
|
3061
|
-
return;
|
|
3062
|
-
}
|
|
3063
|
-
this._callbacks = this._callbacks.filter((callback) => callback.deref() !== void 0);
|
|
3064
|
-
for (const callback of this._callbacks) {
|
|
3065
|
-
const cb = callback.deref();
|
|
3066
|
-
if (!cb) {
|
|
3067
|
-
continue;
|
|
3068
|
-
}
|
|
3069
|
-
void cb(changeResponse);
|
|
3070
|
-
}
|
|
3071
|
-
}
|
|
3072
|
-
/**
|
|
3073
|
-
* Sets up the PouchDB changes feed listener to monitor for database changes.
|
|
3074
|
-
*/
|
|
3075
|
-
setupListener() {
|
|
3076
|
-
if (this._changes) {
|
|
3077
|
-
void this._changes?.removeAllListeners();
|
|
3078
|
-
this._changes?.cancel();
|
|
3079
|
-
this._changes = void 0;
|
|
3080
|
-
}
|
|
3081
|
-
const changes = this._database.changes({
|
|
3082
|
-
since: "now",
|
|
3083
|
-
live: true,
|
|
3084
|
-
include_docs: true
|
|
3085
|
-
});
|
|
3086
|
-
void changes.on("change", (change) => {
|
|
3087
|
-
void this._onChange(change);
|
|
3088
|
-
});
|
|
3089
|
-
void changes.on("error", (err) => {
|
|
3090
|
-
(0, logger_exports.Logger)("ChangeManager Error watching changes");
|
|
3091
|
-
(0, logger_exports.Logger)(err, logger_exports.LOG_LEVEL_VERBOSE);
|
|
3092
|
-
});
|
|
3093
|
-
this._changes = changes;
|
|
3094
|
-
}
|
|
3095
|
-
/**
|
|
3096
|
-
* Tears down the PouchDB changes feed listener and cleans up resources.
|
|
3097
|
-
*/
|
|
3098
|
-
teardown() {
|
|
3099
|
-
void this._changes?.removeAllListeners();
|
|
3100
|
-
this._changes?.cancel();
|
|
3101
|
-
this._changes = void 0;
|
|
3102
|
-
}
|
|
3103
|
-
/**
|
|
3104
|
-
* Restarts the PouchDB changes feed listener.
|
|
3105
|
-
*/
|
|
3106
|
-
restartWatch() {
|
|
3107
|
-
void this.teardown();
|
|
3108
|
-
void this.setupListener();
|
|
3109
|
-
}
|
|
3110
|
-
};
|
|
3111
|
-
|
|
3112
|
-
// lib/livesync-commonlib/src/managers/ConflictManager.ts
|
|
3113
|
-
import { diff_match_patch, DIFF_DELETE, DIFF_INSERT, DIFF_EQUAL } from "diff-match-patch";
|
|
3114
|
-
import { readString as readString2, decodeBinary as decodeBinary2 } from "octagonal-wheels/binary";
|
|
3115
|
-
import { Logger as Logger7, LOG_LEVEL_VERBOSE as LOG_LEVEL_VERBOSE7, LOG_LEVEL_INFO as LOG_LEVEL_INFO3 } from "octagonal-wheels/common/logger";
|
|
3116
|
-
var ConflictManager = class {
|
|
3117
|
-
options;
|
|
3118
|
-
constructor(options) {
|
|
3119
|
-
this.options = options;
|
|
3120
|
-
}
|
|
3121
|
-
get database() {
|
|
3122
|
-
return this.options.database;
|
|
3123
|
-
}
|
|
3124
|
-
async getConflictedDoc(path, rev) {
|
|
3125
|
-
try {
|
|
3126
|
-
const doc = await this.options.entryManager.getDBEntry(path, { rev }, false, true, true);
|
|
3127
|
-
if (doc === false) return false;
|
|
3128
|
-
let data = getDocData(doc.data);
|
|
3129
|
-
if (doc.datatype == "newnote") {
|
|
3130
|
-
data = readString2(new Uint8Array(decodeBinary2(doc.data)));
|
|
3131
|
-
} else if (doc.datatype == "plain") {
|
|
3132
|
-
}
|
|
3133
|
-
return {
|
|
3134
|
-
deleted: doc.deleted || doc._deleted,
|
|
3135
|
-
ctime: doc.ctime,
|
|
3136
|
-
mtime: doc.mtime,
|
|
3137
|
-
rev,
|
|
3138
|
-
data
|
|
3139
|
-
};
|
|
3140
|
-
} catch (ex) {
|
|
3141
|
-
if (isErrorOfMissingDoc(ex)) {
|
|
3142
|
-
return false;
|
|
3143
|
-
}
|
|
3144
|
-
}
|
|
3145
|
-
return false;
|
|
3146
|
-
}
|
|
3147
|
-
async mergeSensibly(path, baseRev, currentRev, conflictedRev) {
|
|
3148
|
-
const baseLeaf = await this.getConflictedDoc(path, baseRev);
|
|
3149
|
-
const leftLeaf = await this.getConflictedDoc(path, currentRev);
|
|
3150
|
-
const rightLeaf = await this.getConflictedDoc(path, conflictedRev);
|
|
3151
|
-
let autoMerge = false;
|
|
3152
|
-
if (baseLeaf == false || leftLeaf == false || rightLeaf == false) {
|
|
3153
|
-
return false;
|
|
3154
|
-
}
|
|
3155
|
-
if (leftLeaf.deleted && rightLeaf.deleted) {
|
|
3156
|
-
return false;
|
|
3157
|
-
}
|
|
3158
|
-
const dmp = new diff_match_patch();
|
|
3159
|
-
const mapLeft = dmp.diff_linesToChars_(baseLeaf.data, leftLeaf.data);
|
|
3160
|
-
const diffLeftSrc = dmp.diff_main(mapLeft.chars1, mapLeft.chars2, false);
|
|
3161
|
-
dmp.diff_charsToLines_(diffLeftSrc, mapLeft.lineArray);
|
|
3162
|
-
const mapRight = dmp.diff_linesToChars_(baseLeaf.data, rightLeaf.data);
|
|
3163
|
-
const diffRightSrc = dmp.diff_main(mapRight.chars1, mapRight.chars2, false);
|
|
3164
|
-
dmp.diff_charsToLines_(diffRightSrc, mapRight.lineArray);
|
|
3165
|
-
function splitDiffPiece(src) {
|
|
3166
|
-
const ret = [];
|
|
3167
|
-
do {
|
|
3168
|
-
const d = src.shift();
|
|
3169
|
-
if (d === void 0) {
|
|
3170
|
-
return ret;
|
|
3171
|
-
}
|
|
3172
|
-
const pieces = d[1].split(/([^\n]*\n)/).filter((f) => f != "");
|
|
3173
|
-
if (typeof d == "undefined") {
|
|
3174
|
-
break;
|
|
3175
|
-
}
|
|
3176
|
-
if (d[0] != DIFF_DELETE) {
|
|
3177
|
-
ret.push(...pieces.map((e) => [d[0], e]));
|
|
3178
|
-
}
|
|
3179
|
-
if (d[0] == DIFF_DELETE) {
|
|
3180
|
-
const nd = src.shift();
|
|
3181
|
-
if (typeof nd != "undefined") {
|
|
3182
|
-
const piecesPair = nd[1].split(/([^\n]*\n)/).filter((f) => f != "");
|
|
3183
|
-
if (nd[0] == DIFF_INSERT) {
|
|
3184
|
-
for (const pt of pieces) {
|
|
3185
|
-
ret.push([d[0], pt]);
|
|
3186
|
-
const pairP = piecesPair.shift();
|
|
3187
|
-
if (typeof pairP != "undefined") ret.push([DIFF_INSERT, pairP]);
|
|
3188
|
-
}
|
|
3189
|
-
ret.push(...piecesPair.map((e) => [nd[0], e]));
|
|
3190
|
-
} else {
|
|
3191
|
-
ret.push(...pieces.map((e) => [d[0], e]));
|
|
3192
|
-
ret.push(...piecesPair.map((e) => [nd[0], e]));
|
|
3193
|
-
}
|
|
3194
|
-
} else {
|
|
3195
|
-
ret.push(...pieces.map((e) => [0, e]));
|
|
3196
|
-
}
|
|
3197
|
-
}
|
|
3198
|
-
} while (src.length > 0);
|
|
3199
|
-
return ret;
|
|
3200
|
-
}
|
|
3201
|
-
const diffLeft = splitDiffPiece(diffLeftSrc);
|
|
3202
|
-
const diffRight = splitDiffPiece(diffRightSrc);
|
|
3203
|
-
let rightIdx = 0;
|
|
3204
|
-
let leftIdx = 0;
|
|
3205
|
-
const merged = [];
|
|
3206
|
-
autoMerge = true;
|
|
3207
|
-
LOOP_MERGE: do {
|
|
3208
|
-
if (leftIdx >= diffLeft.length && rightIdx >= diffRight.length) {
|
|
3209
|
-
break LOOP_MERGE;
|
|
3210
|
-
}
|
|
3211
|
-
const leftItem = diffLeft[leftIdx] ?? [0, ""];
|
|
3212
|
-
const rightItem = diffRight[rightIdx] ?? [0, ""];
|
|
3213
|
-
leftIdx++;
|
|
3214
|
-
rightIdx++;
|
|
3215
|
-
if (leftItem[0] == DIFF_EQUAL && rightItem[0] == DIFF_EQUAL && leftItem[1] == rightItem[1]) {
|
|
3216
|
-
merged.push(leftItem);
|
|
3217
|
-
continue;
|
|
3218
|
-
}
|
|
3219
|
-
if (leftItem[0] == DIFF_DELETE && rightItem[0] == DIFF_DELETE && leftItem[1] == rightItem[1]) {
|
|
3220
|
-
const nextLeftIdx = leftIdx;
|
|
3221
|
-
const nextRightIdx = rightIdx;
|
|
3222
|
-
const [nextLeftItem, nextRightItem] = [
|
|
3223
|
-
diffLeft[nextLeftIdx] ?? [0, ""],
|
|
3224
|
-
diffRight[nextRightIdx] ?? [0, ""]
|
|
3225
|
-
];
|
|
3226
|
-
if (nextLeftItem[0] == DIFF_INSERT && nextRightItem[0] == DIFF_INSERT && nextLeftItem[1] != nextRightItem[1]) {
|
|
3227
|
-
autoMerge = false;
|
|
3228
|
-
break;
|
|
3229
|
-
} else {
|
|
3230
|
-
merged.push(leftItem);
|
|
3231
|
-
continue;
|
|
3232
|
-
}
|
|
3233
|
-
}
|
|
3234
|
-
if (leftItem[0] == DIFF_INSERT && rightItem[0] == DIFF_INSERT) {
|
|
3235
|
-
if (leftItem[1] == rightItem[1]) {
|
|
3236
|
-
merged.push(leftItem);
|
|
3237
|
-
continue;
|
|
3238
|
-
} else {
|
|
3239
|
-
if (leftLeaf.mtime <= rightLeaf.mtime) {
|
|
3240
|
-
merged.push(leftItem);
|
|
3241
|
-
merged.push(rightItem);
|
|
3242
|
-
continue;
|
|
3243
|
-
} else {
|
|
3244
|
-
merged.push(rightItem);
|
|
3245
|
-
merged.push(leftItem);
|
|
3246
|
-
continue;
|
|
3247
|
-
}
|
|
3248
|
-
}
|
|
3249
|
-
}
|
|
3250
|
-
if (leftItem[0] == DIFF_INSERT) {
|
|
3251
|
-
rightIdx--;
|
|
3252
|
-
merged.push(leftItem);
|
|
3253
|
-
continue;
|
|
3254
|
-
}
|
|
3255
|
-
if (rightItem[0] == DIFF_INSERT) {
|
|
3256
|
-
leftIdx--;
|
|
3257
|
-
merged.push(rightItem);
|
|
3258
|
-
continue;
|
|
3259
|
-
}
|
|
3260
|
-
if (rightItem[1] != leftItem[1]) {
|
|
3261
|
-
Logger7(
|
|
3262
|
-
`MERGING PANIC:${leftItem[0]},${leftItem[1]} == ${rightItem[0]},${rightItem[1]}`,
|
|
3263
|
-
LOG_LEVEL_VERBOSE7
|
|
3264
|
-
);
|
|
3265
|
-
autoMerge = false;
|
|
3266
|
-
break LOOP_MERGE;
|
|
3267
|
-
}
|
|
3268
|
-
if (leftItem[0] == DIFF_DELETE) {
|
|
3269
|
-
if (rightItem[0] == DIFF_EQUAL) {
|
|
3270
|
-
merged.push(leftItem);
|
|
3271
|
-
continue;
|
|
3272
|
-
} else {
|
|
3273
|
-
autoMerge = false;
|
|
3274
|
-
break LOOP_MERGE;
|
|
3275
|
-
}
|
|
3276
|
-
}
|
|
3277
|
-
if (rightItem[0] == DIFF_DELETE) {
|
|
3278
|
-
if (leftItem[0] == DIFF_EQUAL) {
|
|
3279
|
-
merged.push(rightItem);
|
|
3280
|
-
continue;
|
|
3281
|
-
} else {
|
|
3282
|
-
autoMerge = false;
|
|
3283
|
-
break LOOP_MERGE;
|
|
3284
|
-
}
|
|
3285
|
-
}
|
|
3286
|
-
Logger7(
|
|
3287
|
-
`Weird condition:${leftItem[0]},${leftItem[1]} == ${rightItem[0]},${rightItem[1]}`,
|
|
3288
|
-
LOG_LEVEL_VERBOSE7
|
|
3289
|
-
);
|
|
3290
|
-
break LOOP_MERGE;
|
|
3291
|
-
} while (leftIdx < diffLeft.length || rightIdx < diffRight.length);
|
|
3292
|
-
if (autoMerge) {
|
|
3293
|
-
Logger7(`Sensibly merge available`, LOG_LEVEL_VERBOSE7);
|
|
3294
|
-
return merged;
|
|
3295
|
-
} else {
|
|
3296
|
-
return false;
|
|
3297
|
-
}
|
|
3298
|
-
}
|
|
3299
|
-
async mergeObject(path, baseRev, currentRev, conflictedRev) {
|
|
3300
|
-
try {
|
|
3301
|
-
const baseLeaf = await this.getConflictedDoc(path, baseRev);
|
|
3302
|
-
const leftLeaf = await this.getConflictedDoc(path, currentRev);
|
|
3303
|
-
const rightLeaf = await this.getConflictedDoc(path, conflictedRev);
|
|
3304
|
-
if (baseLeaf == false || leftLeaf == false || rightLeaf == false) {
|
|
3305
|
-
Logger7(`Could not load leafs for merge`, LOG_LEVEL_VERBOSE7);
|
|
3306
|
-
Logger7(
|
|
3307
|
-
`${baseLeaf ? "base" : "missing base"}, ${leftLeaf ? "left" : "missing left"}, ${rightLeaf ? "right" : "missing right"} }`,
|
|
3308
|
-
LOG_LEVEL_VERBOSE7
|
|
3309
|
-
);
|
|
3310
|
-
return false;
|
|
3311
|
-
}
|
|
3312
|
-
if (leftLeaf.deleted && rightLeaf.deleted) {
|
|
3313
|
-
Logger7(`Both are deleted`, LOG_LEVEL_VERBOSE7);
|
|
3314
|
-
return false;
|
|
3315
|
-
}
|
|
3316
|
-
const baseObj = { data: tryParseJSON(baseLeaf.data, {}) };
|
|
3317
|
-
const leftObj = { data: tryParseJSON(leftLeaf.data, {}) };
|
|
3318
|
-
const rightObj = { data: tryParseJSON(rightLeaf.data, {}) };
|
|
3319
|
-
const diffLeft = generatePatchObj(baseObj, leftObj);
|
|
3320
|
-
const diffRight = generatePatchObj(baseObj, rightObj);
|
|
3321
|
-
const diffSetLeft = new Map(flattenObject(diffLeft));
|
|
3322
|
-
const diffSetRight = new Map(flattenObject(diffRight));
|
|
3323
|
-
for (const [key, value] of diffSetLeft) {
|
|
3324
|
-
if (diffSetRight.has(key)) {
|
|
3325
|
-
if (diffSetRight.get(key) == value) {
|
|
3326
|
-
diffSetRight.delete(key);
|
|
3327
|
-
}
|
|
3328
|
-
}
|
|
3329
|
-
}
|
|
3330
|
-
for (const [key, value] of diffSetRight) {
|
|
3331
|
-
if (diffSetLeft.has(key) && diffSetLeft.get(key) != value) {
|
|
3332
|
-
Logger7(`Conflicted key:${key}`, LOG_LEVEL_VERBOSE7);
|
|
3333
|
-
return false;
|
|
3334
|
-
}
|
|
3335
|
-
}
|
|
3336
|
-
const patches = [
|
|
3337
|
-
{ mtime: leftLeaf.mtime, patch: diffLeft },
|
|
3338
|
-
{ mtime: rightLeaf.mtime, patch: diffRight }
|
|
3339
|
-
].sort((a, b) => a.mtime - b.mtime);
|
|
3340
|
-
let newObj = { ...baseObj };
|
|
3341
|
-
for (const patch of patches) {
|
|
3342
|
-
newObj = applyPatch(newObj, patch.patch);
|
|
3343
|
-
}
|
|
3344
|
-
Logger7(`Object merge is applicable!`, LOG_LEVEL_VERBOSE7);
|
|
3345
|
-
return JSON.stringify(newObj.data);
|
|
3346
|
-
} catch (ex) {
|
|
3347
|
-
Logger7("Could not merge object");
|
|
3348
|
-
Logger7(ex, LOG_LEVEL_VERBOSE7);
|
|
3349
|
-
return false;
|
|
3350
|
-
}
|
|
3351
|
-
}
|
|
3352
|
-
async tryAutoMergeSensibly(path, test, conflicts) {
|
|
3353
|
-
const conflictedRev = conflicts[0];
|
|
3354
|
-
const conflictedRevNo = Number(conflictedRev.split("-")[0]);
|
|
3355
|
-
const revFrom = await this.database.get(await this.options.entryManager.path2id(path), {
|
|
3356
|
-
revs_info: true
|
|
3357
|
-
});
|
|
3358
|
-
const commonBase = (revFrom._revs_info || []).filter(
|
|
3359
|
-
(e) => e.status == "available" && Number(e.rev.split("-")[0]) < conflictedRevNo
|
|
3360
|
-
)?.[0]?.rev ?? "";
|
|
3361
|
-
let p = void 0;
|
|
3362
|
-
if (commonBase) {
|
|
3363
|
-
if (isSensibleMargeApplicable(path)) {
|
|
3364
|
-
const result = await this.mergeSensibly(path, commonBase, test._rev, conflictedRev);
|
|
3365
|
-
if (result) {
|
|
3366
|
-
p = result.filter((e) => e[0] != DIFF_DELETE).map((e) => e[1]).join("");
|
|
3367
|
-
Logger7(`Sensible merge:${path}`, LOG_LEVEL_INFO3);
|
|
3368
|
-
} else {
|
|
3369
|
-
Logger7(`Sensible merge is not applicable.`, LOG_LEVEL_VERBOSE7);
|
|
3370
|
-
}
|
|
3371
|
-
} else if (isObjectMargeApplicable(path)) {
|
|
3372
|
-
const result = await this.mergeObject(path, commonBase, test._rev, conflictedRev);
|
|
3373
|
-
if (result) {
|
|
3374
|
-
Logger7(`Object merge:${path}`, LOG_LEVEL_INFO3);
|
|
3375
|
-
p = result;
|
|
3376
|
-
} else {
|
|
3377
|
-
Logger7(`Object merge is not applicable..`, LOG_LEVEL_VERBOSE7);
|
|
3378
|
-
}
|
|
3379
|
-
}
|
|
3380
|
-
if (p !== void 0) {
|
|
3381
|
-
return { result: p, conflictedRev };
|
|
3382
|
-
}
|
|
3383
|
-
}
|
|
3384
|
-
return false;
|
|
3385
|
-
}
|
|
3386
|
-
async tryAutoMerge(path, enableMarkdownAutoMerge) {
|
|
3387
|
-
const test = await this.options.entryManager.getDBEntry(
|
|
3388
|
-
path,
|
|
3389
|
-
{ conflicts: true, revs_info: true },
|
|
3390
|
-
false,
|
|
3391
|
-
false,
|
|
3392
|
-
true
|
|
3393
|
-
);
|
|
3394
|
-
if (test === false) return { ok: MISSING_OR_ERROR };
|
|
3395
|
-
if (test == null) return { ok: MISSING_OR_ERROR };
|
|
3396
|
-
if (!test._conflicts) return { ok: NOT_CONFLICTED };
|
|
3397
|
-
if (test._conflicts.length == 0) return { ok: NOT_CONFLICTED };
|
|
3398
|
-
const conflicts = test._conflicts.sort((a, b) => Number(a.split("-")[0]) - Number(b.split("-")[0]));
|
|
3399
|
-
if ((isSensibleMargeApplicable(path) || isObjectMargeApplicable(path)) && enableMarkdownAutoMerge) {
|
|
3400
|
-
const autoMergeResult = await this.tryAutoMergeSensibly(path, test, conflicts);
|
|
3401
|
-
if (autoMergeResult !== false) {
|
|
3402
|
-
return autoMergeResult;
|
|
3403
|
-
}
|
|
3404
|
-
}
|
|
3405
|
-
const leftLeaf = await this.getConflictedDoc(path, test._rev);
|
|
3406
|
-
const rightLeaf = await this.getConflictedDoc(path, conflicts[0]);
|
|
3407
|
-
return { leftRev: test._rev, rightRev: conflicts[0], leftLeaf, rightLeaf };
|
|
3408
|
-
}
|
|
3409
|
-
};
|
|
3410
|
-
|
|
3411
|
-
// lib/livesync-commonlib/src/managers/EntryManager/EntryManager.ts
|
|
3412
|
-
import { Logger as Logger8, LOG_LEVEL_NOTICE as LOG_LEVEL_NOTICE3, LOG_LEVEL_VERBOSE as LOG_LEVEL_VERBOSE8 } from "octagonal-wheels/common/logger";
|
|
3413
|
-
import { serialized } from "octagonal-wheels/concurrency/lock_v2";
|
|
3414
|
-
var EntryManager = class {
|
|
3415
|
-
options;
|
|
3416
|
-
constructor(options) {
|
|
3417
|
-
this.options = options;
|
|
3418
|
-
}
|
|
3419
|
-
get localDatabase() {
|
|
3420
|
-
return this.options.database;
|
|
3421
|
-
}
|
|
3422
|
-
get hashManager() {
|
|
3423
|
-
return this.options.hashManager;
|
|
3424
|
-
}
|
|
3425
|
-
get chunkManager() {
|
|
3426
|
-
return this.options.chunkManager;
|
|
3427
|
-
}
|
|
3428
|
-
get chunkFetcher() {
|
|
3429
|
-
return this.options.chunkFetcher;
|
|
3430
|
-
}
|
|
3431
|
-
get splitter() {
|
|
3432
|
-
return this.options.splitter;
|
|
3433
|
-
}
|
|
3434
|
-
get settings() {
|
|
3435
|
-
return this.options.settings;
|
|
3436
|
-
}
|
|
3437
|
-
id2path(id, entry, stripPrefix) {
|
|
3438
|
-
return this.options.$$id2path(id, entry, stripPrefix);
|
|
3439
|
-
}
|
|
3440
|
-
async path2id(filename, prefix) {
|
|
3441
|
-
return await this.options.$$path2id(filename, prefix);
|
|
3442
|
-
}
|
|
3443
|
-
get isOnDemandChunkEnabled() {
|
|
3444
|
-
if (this.settings.remoteType !== REMOTE_COUCHDB) {
|
|
3445
|
-
return false;
|
|
3446
|
-
}
|
|
3447
|
-
return this.settings.readChunksOnline;
|
|
3448
|
-
}
|
|
3449
|
-
isTargetFile(filenameSrc) {
|
|
3450
|
-
const file = filenameSrc.startsWith("i:") ? filenameSrc.substring(2) : filenameSrc;
|
|
3451
|
-
if (file.startsWith("ix:")) return true;
|
|
3452
|
-
if (file.startsWith("ps:")) return true;
|
|
3453
|
-
if (file.includes(":")) {
|
|
3454
|
-
return false;
|
|
3455
|
-
}
|
|
3456
|
-
if (this.settings.syncOnlyRegEx) {
|
|
3457
|
-
const syncOnly = getFileRegExp(this.settings, "syncOnlyRegEx");
|
|
3458
|
-
if (syncOnly.length > 0 && !syncOnly.some((e) => e.test(file))) return false;
|
|
3459
|
-
}
|
|
3460
|
-
if (this.settings.syncIgnoreRegEx) {
|
|
3461
|
-
const syncIgnore = getFileRegExp(this.settings, "syncIgnoreRegEx");
|
|
3462
|
-
if (syncIgnore.some((e) => e.test(file))) return false;
|
|
3463
|
-
}
|
|
3464
|
-
return true;
|
|
3465
|
-
}
|
|
3466
|
-
async prepareChunk(piece) {
|
|
3467
|
-
const cachedChunkId = this.chunkManager.getChunkIDFromCache(piece);
|
|
3468
|
-
if (cachedChunkId !== false) {
|
|
3469
|
-
return { isNew: false, id: cachedChunkId, piece };
|
|
3470
|
-
}
|
|
3471
|
-
const chunkId = await this.hashManager.computeHash(piece);
|
|
3472
|
-
return { isNew: true, id: `${IDPrefixes.Chunk}${chunkId}`, piece };
|
|
3473
|
-
}
|
|
3474
|
-
async getDBEntryMeta(path, opt, includeDeleted = false) {
|
|
3475
|
-
if (!this.isTargetFile(path)) {
|
|
3476
|
-
return false;
|
|
3477
|
-
}
|
|
3478
|
-
const id = await this.path2id(path);
|
|
3479
|
-
try {
|
|
3480
|
-
let obj = null;
|
|
3481
|
-
if (opt) {
|
|
3482
|
-
obj = await this.localDatabase.get(id, opt);
|
|
3483
|
-
} else {
|
|
3484
|
-
obj = await this.localDatabase.get(id);
|
|
3485
|
-
}
|
|
3486
|
-
const deleted = obj?.deleted ?? obj._deleted ?? void 0;
|
|
3487
|
-
if (!includeDeleted && deleted) return false;
|
|
3488
|
-
if (obj.type && obj.type == "leaf") {
|
|
3489
|
-
return false;
|
|
3490
|
-
}
|
|
3491
|
-
if (!obj.type || obj.type && obj.type == "notes" || obj.type == "newnote" || obj.type == "plain") {
|
|
3492
|
-
const note = obj;
|
|
3493
|
-
let children = [];
|
|
3494
|
-
let type = "plain";
|
|
3495
|
-
if (obj.type == "newnote" || obj.type == "plain") {
|
|
3496
|
-
children = obj.children;
|
|
3497
|
-
type = obj.type;
|
|
3498
|
-
}
|
|
3499
|
-
const doc = {
|
|
3500
|
-
data: "",
|
|
3501
|
-
_id: note._id,
|
|
3502
|
-
path,
|
|
3503
|
-
ctime: note.ctime,
|
|
3504
|
-
mtime: note.mtime,
|
|
3505
|
-
size: note.size,
|
|
3506
|
-
// _deleted: obj._deleted,
|
|
3507
|
-
_rev: obj._rev,
|
|
3508
|
-
_conflicts: obj._conflicts,
|
|
3509
|
-
children,
|
|
3510
|
-
datatype: type,
|
|
3511
|
-
deleted,
|
|
3512
|
-
type,
|
|
3513
|
-
eden: "eden" in obj ? obj.eden : {}
|
|
3514
|
-
};
|
|
3515
|
-
return doc;
|
|
3516
|
-
}
|
|
3517
|
-
} catch (ex) {
|
|
3518
|
-
if (isErrorOfMissingDoc(ex)) {
|
|
3519
|
-
return false;
|
|
3520
|
-
}
|
|
3521
|
-
throw ex;
|
|
3522
|
-
}
|
|
3523
|
-
return false;
|
|
3524
|
-
}
|
|
3525
|
-
async getDBEntry(path, opt, dump = false, waitForReady = true, includeDeleted = false) {
|
|
3526
|
-
const meta = await this.getDBEntryMeta(path, opt, includeDeleted);
|
|
3527
|
-
if (meta) {
|
|
3528
|
-
return await this.getDBEntryFromMeta(meta, dump, waitForReady);
|
|
3529
|
-
} else {
|
|
3530
|
-
return false;
|
|
3531
|
-
}
|
|
3532
|
-
}
|
|
3533
|
-
async getDBEntryFromMeta(meta, dump = false, waitForReady = true) {
|
|
3534
|
-
const filename = this.id2path(meta._id, meta);
|
|
3535
|
-
if (!this.isTargetFile(filename)) {
|
|
3536
|
-
return false;
|
|
3537
|
-
}
|
|
3538
|
-
const dispFilename = stripAllPrefixes(filename);
|
|
3539
|
-
const deleted = meta.deleted ?? meta._deleted ?? void 0;
|
|
3540
|
-
if (!meta.type || meta.type && meta.type == "notes") {
|
|
3541
|
-
const note = meta;
|
|
3542
|
-
const doc = {
|
|
3543
|
-
data: note.data,
|
|
3544
|
-
path: note.path,
|
|
3545
|
-
_id: note._id,
|
|
3546
|
-
ctime: note.ctime,
|
|
3547
|
-
mtime: note.mtime,
|
|
3548
|
-
size: note.size,
|
|
3549
|
-
// _deleted: obj._deleted,
|
|
3550
|
-
_rev: meta._rev,
|
|
3551
|
-
_conflicts: meta._conflicts,
|
|
3552
|
-
children: [],
|
|
3553
|
-
datatype: "newnote",
|
|
3554
|
-
deleted,
|
|
3555
|
-
type: "newnote",
|
|
3556
|
-
eden: "eden" in meta ? meta.eden : {}
|
|
3557
|
-
};
|
|
3558
|
-
if (dump) {
|
|
3559
|
-
Logger8(`--Old fashioned document--`);
|
|
3560
|
-
Logger8(doc);
|
|
3561
|
-
}
|
|
3562
|
-
return doc;
|
|
3563
|
-
}
|
|
3564
|
-
if (meta.type == "newnote" || meta.type == "plain") {
|
|
3565
|
-
if (dump) {
|
|
3566
|
-
const conflicts = await this.localDatabase.get(meta._id, {
|
|
3567
|
-
rev: meta._rev,
|
|
3568
|
-
conflicts: true,
|
|
3569
|
-
revs_info: true
|
|
3570
|
-
});
|
|
3571
|
-
Logger8("-- Conflicts --");
|
|
3572
|
-
Logger8(conflicts._conflicts ?? "No conflicts");
|
|
3573
|
-
Logger8("-- Revs info -- ");
|
|
3574
|
-
Logger8(conflicts._revs_info);
|
|
3575
|
-
}
|
|
3576
|
-
try {
|
|
3577
|
-
if (dump) {
|
|
3578
|
-
Logger8(`--Bare document--`);
|
|
3579
|
-
Logger8(meta);
|
|
3580
|
-
}
|
|
3581
|
-
let edenChunks = {};
|
|
3582
|
-
if (meta.eden && Object.keys(meta.eden).length > 0) {
|
|
3583
|
-
const chunks2 = Object.entries(meta.eden).map(([id, data]) => ({
|
|
3584
|
-
_id: id,
|
|
3585
|
-
data: data.data,
|
|
3586
|
-
type: "leaf"
|
|
3587
|
-
}));
|
|
3588
|
-
edenChunks = Object.fromEntries(chunks2.map((e) => [e._id, e]));
|
|
3589
|
-
}
|
|
3590
|
-
const isChunksCorrectedIncrementally = this.settings.remoteType !== RemoteTypes.REMOTE_MINIO;
|
|
3591
|
-
const isNetworkEnabled = this.isOnDemandChunkEnabled && this.settings.remoteType !== RemoteTypes.REMOTE_MINIO;
|
|
3592
|
-
const timeout = waitForReady ? isChunksCorrectedIncrementally ? LEAF_WAIT_TIMEOUT : LEAF_WAIT_TIMEOUT_SEQUENTIAL_REPLICATOR : isNetworkEnabled ? LEAF_WAIT_ONLY_REMOTE : 0;
|
|
3593
|
-
const childrenKeys = [...meta.children];
|
|
3594
|
-
const chunks = await this.chunkManager.read(
|
|
3595
|
-
childrenKeys,
|
|
3596
|
-
{
|
|
3597
|
-
skipCache: false,
|
|
3598
|
-
timeout,
|
|
3599
|
-
preventRemoteRequest: !isNetworkEnabled
|
|
3600
|
-
},
|
|
3601
|
-
edenChunks
|
|
3602
|
-
);
|
|
3603
|
-
if (chunks.some((e) => e === false)) {
|
|
3604
|
-
throw new Error("Load failed");
|
|
3605
|
-
}
|
|
3606
|
-
const doc = {
|
|
3607
|
-
data: chunks.map((e) => e.data),
|
|
3608
|
-
path: meta.path,
|
|
3609
|
-
_id: meta._id,
|
|
3610
|
-
ctime: meta.ctime,
|
|
3611
|
-
mtime: meta.mtime,
|
|
3612
|
-
size: meta.size,
|
|
3613
|
-
_rev: meta._rev,
|
|
3614
|
-
children: meta.children,
|
|
3615
|
-
datatype: meta.type,
|
|
3616
|
-
_conflicts: meta._conflicts,
|
|
3617
|
-
eden: meta.eden,
|
|
3618
|
-
deleted,
|
|
3619
|
-
type: meta.type
|
|
3620
|
-
};
|
|
3621
|
-
if (dump) {
|
|
3622
|
-
Logger8(`--Loaded Document--`);
|
|
3623
|
-
Logger8(doc);
|
|
3624
|
-
}
|
|
3625
|
-
return doc;
|
|
3626
|
-
} catch (ex) {
|
|
3627
|
-
if (isErrorOfMissingDoc(ex)) {
|
|
3628
|
-
Logger8(
|
|
3629
|
-
`Missing document content!, could not read ${dispFilename}(${meta._id.substring(0, 8)}) from database.`,
|
|
3630
|
-
LOG_LEVEL_NOTICE3
|
|
3631
|
-
);
|
|
3632
|
-
return false;
|
|
3633
|
-
}
|
|
3634
|
-
Logger8(
|
|
3635
|
-
`Something went wrong on reading ${dispFilename}(${meta._id.substring(0, 8)}) from database:`,
|
|
3636
|
-
LOG_LEVEL_NOTICE3
|
|
3637
|
-
);
|
|
3638
|
-
Logger8(ex);
|
|
3639
|
-
}
|
|
3640
|
-
}
|
|
3641
|
-
return false;
|
|
3642
|
-
}
|
|
3643
|
-
async deleteDBEntry(path, opt) {
|
|
3644
|
-
if (!this.isTargetFile(path)) {
|
|
3645
|
-
return false;
|
|
3646
|
-
}
|
|
3647
|
-
const id = await this.path2id(path);
|
|
3648
|
-
try {
|
|
3649
|
-
return await serialized("file:" + path, async () => {
|
|
3650
|
-
let obj = null;
|
|
3651
|
-
if (opt) {
|
|
3652
|
-
obj = await this.localDatabase.get(id, opt);
|
|
3653
|
-
} else {
|
|
3654
|
-
obj = await this.localDatabase.get(id);
|
|
3655
|
-
}
|
|
3656
|
-
const revDeletion = opt && ("rev" in opt ? opt.rev : "") != "";
|
|
3657
|
-
if (obj.type && obj.type == "leaf") {
|
|
3658
|
-
return false;
|
|
3659
|
-
}
|
|
3660
|
-
if (!obj.type || obj.type && obj.type == "notes") {
|
|
3661
|
-
obj._deleted = true;
|
|
3662
|
-
const r = await this.localDatabase.put(obj, { force: !revDeletion });
|
|
3663
|
-
Logger8(`Entry removed:${path} (${obj._id.substring(0, 8)}-${r.rev})`);
|
|
3664
|
-
return true;
|
|
3665
|
-
}
|
|
3666
|
-
if (obj.type == "newnote" || obj.type == "plain") {
|
|
3667
|
-
if (revDeletion) {
|
|
3668
|
-
obj._deleted = true;
|
|
3669
|
-
} else {
|
|
3670
|
-
obj.deleted = true;
|
|
3671
|
-
obj.mtime = Date.now();
|
|
3672
|
-
if (this.settings.deleteMetadataOfDeletedFiles) {
|
|
3673
|
-
obj._deleted = true;
|
|
3674
|
-
}
|
|
3675
|
-
}
|
|
3676
|
-
const r = await this.localDatabase.put(obj, { force: !revDeletion });
|
|
3677
|
-
Logger8(`Entry removed:${path} (${obj._id.substring(0, 8)}-${r.rev})`);
|
|
3678
|
-
return true;
|
|
3679
|
-
} else {
|
|
3680
|
-
return false;
|
|
3681
|
-
}
|
|
3682
|
-
}) ?? false;
|
|
3683
|
-
} catch (ex) {
|
|
3684
|
-
if (isErrorOfMissingDoc(ex)) {
|
|
3685
|
-
return false;
|
|
3686
|
-
}
|
|
3687
|
-
throw ex;
|
|
3688
|
-
}
|
|
3689
|
-
}
|
|
3690
|
-
async putDBEntry(note, onlyChunks) {
|
|
3691
|
-
const filename = this.id2path(note._id, note);
|
|
3692
|
-
const dispFilename = stripAllPrefixes(filename);
|
|
3693
|
-
if (!note.eden) note.eden = {};
|
|
3694
|
-
if (!this.isTargetFile(filename)) {
|
|
3695
|
-
Logger8(`File skipped:${dispFilename}`, LOG_LEVEL_VERBOSE8);
|
|
3696
|
-
return false;
|
|
3697
|
-
}
|
|
3698
|
-
const data = note.data instanceof Blob ? note.data : createTextBlob(note.data);
|
|
3699
|
-
note.data = data;
|
|
3700
|
-
note.type = isTextBlob(data) ? "plain" : "newnote";
|
|
3701
|
-
note.datatype = note.type;
|
|
3702
|
-
await this.splitter.initialised;
|
|
3703
|
-
const result = await this.chunkManager.transaction(async () => {
|
|
3704
|
-
let bufferedChunk = [];
|
|
3705
|
-
let bufferedSize = 0;
|
|
3706
|
-
let writeCount = 0;
|
|
3707
|
-
let newCount = 0;
|
|
3708
|
-
let cachedCount = 0;
|
|
3709
|
-
let resultCachedCount = 0;
|
|
3710
|
-
let duplicatedCount = 0;
|
|
3711
|
-
let totalWritingCount = 0;
|
|
3712
|
-
let createChunkCount = 0;
|
|
3713
|
-
const MAX_WRITE_SIZE = 1e3 * 1024 * 2;
|
|
3714
|
-
const chunks = [];
|
|
3715
|
-
let writeChars = 0;
|
|
3716
|
-
const flushBufferedChunks = async () => {
|
|
3717
|
-
if (bufferedChunk.length === 0) {
|
|
3718
|
-
Logger8(`No chunks to flush for ${dispFilename}`, LOG_LEVEL_VERBOSE8);
|
|
3719
|
-
return true;
|
|
3720
|
-
}
|
|
3721
|
-
const writeBuf = [...bufferedChunk];
|
|
3722
|
-
bufferedSize = 0;
|
|
3723
|
-
bufferedChunk = [];
|
|
3724
|
-
const result2 = await this.chunkManager.write(
|
|
3725
|
-
writeBuf,
|
|
3726
|
-
{
|
|
3727
|
-
skipCache: false,
|
|
3728
|
-
timeout: 0
|
|
3729
|
-
},
|
|
3730
|
-
note._id
|
|
3731
|
-
);
|
|
3732
|
-
if (result2.result === false) {
|
|
3733
|
-
Logger8(`Failed to write buffered chunks for ${dispFilename}`, LOG_LEVEL_NOTICE3);
|
|
3734
|
-
return false;
|
|
3735
|
-
}
|
|
3736
|
-
totalWritingCount++;
|
|
3737
|
-
writeCount += result2.processed.written;
|
|
3738
|
-
resultCachedCount += result2.processed.cached;
|
|
3739
|
-
duplicatedCount += result2.processed.duplicated;
|
|
3740
|
-
writeChars += writeBuf.map((e) => e.data.length).reduce((a, b) => a + b, 0);
|
|
3741
|
-
Logger8(`Flushed ${writeBuf.length} (${writeChars}) chunks for ${dispFilename}`, LOG_LEVEL_VERBOSE8);
|
|
3742
|
-
return true;
|
|
3743
|
-
};
|
|
3744
|
-
const flushIfNeeded = async () => {
|
|
3745
|
-
if (bufferedSize > MAX_WRITE_SIZE) {
|
|
3746
|
-
if (!await flushBufferedChunks()) {
|
|
3747
|
-
Logger8(`Failed to flush buffered chunks for ${dispFilename}`, LOG_LEVEL_NOTICE3);
|
|
3748
|
-
return false;
|
|
3749
|
-
}
|
|
3750
|
-
}
|
|
3751
|
-
return true;
|
|
3752
|
-
};
|
|
3753
|
-
const addBuffer = async (id, data2) => {
|
|
3754
|
-
const chunk = {
|
|
3755
|
-
_id: id,
|
|
3756
|
-
data: data2,
|
|
3757
|
-
type: "leaf"
|
|
3758
|
-
};
|
|
3759
|
-
bufferedChunk.push(chunk);
|
|
3760
|
-
chunks.push(chunk._id);
|
|
3761
|
-
bufferedSize += chunk.data.length;
|
|
3762
|
-
return await flushIfNeeded();
|
|
3763
|
-
};
|
|
3764
|
-
const pieces = await this.splitter.splitContent(note);
|
|
3765
|
-
let totalChunkCount = 0;
|
|
3766
|
-
try {
|
|
3767
|
-
for await (const piece of pieces) {
|
|
3768
|
-
totalChunkCount++;
|
|
3769
|
-
if (piece.length === 0) {
|
|
3770
|
-
continue;
|
|
3771
|
-
}
|
|
3772
|
-
createChunkCount++;
|
|
3773
|
-
const chunk = await this.prepareChunk(piece);
|
|
3774
|
-
cachedCount += chunk.isNew ? 0 : 1;
|
|
3775
|
-
newCount += chunk.isNew ? 1 : 0;
|
|
3776
|
-
if (!await addBuffer(chunk.id, chunk.piece)) {
|
|
3777
|
-
return false;
|
|
3778
|
-
}
|
|
3779
|
-
}
|
|
3780
|
-
} catch (ex) {
|
|
3781
|
-
Logger8(`Error processing pieces for ${dispFilename}`);
|
|
3782
|
-
Logger8(ex, LOG_LEVEL_VERBOSE8);
|
|
3783
|
-
return false;
|
|
3784
|
-
}
|
|
3785
|
-
if (!await flushBufferedChunks()) {
|
|
3786
|
-
return false;
|
|
3787
|
-
}
|
|
3788
|
-
const dataSize = note.data.size;
|
|
3789
|
-
const stats = `(\u2728: ${newCount}, \u{1F5C3}\uFE0F: ${cachedCount} (${resultCachedCount}) / \u{1F5C4}\uFE0F: ${writeCount}, \u267B:${duplicatedCount})`;
|
|
3790
|
-
Logger8(
|
|
3791
|
-
`Chunks processed for ${dispFilename} (${dataSize}): \u{1F4DA}:${totalChunkCount} (${createChunkCount}) , \u{1F4E5}:${totalWritingCount} ${stats}`,
|
|
3792
|
-
LOG_LEVEL_VERBOSE8
|
|
3793
|
-
);
|
|
3794
|
-
if (dataSize > 0 && totalWritingCount === 0) {
|
|
3795
|
-
Logger8(
|
|
3796
|
-
`No data to save in ${dispFilename}!! This document may be corrupted in the local database! Please back it up immediately, and report an issue!`,
|
|
3797
|
-
LOG_LEVEL_NOTICE3
|
|
3798
|
-
);
|
|
3799
|
-
}
|
|
3800
|
-
if (onlyChunks) {
|
|
3801
|
-
return {
|
|
3802
|
-
id: note._id,
|
|
3803
|
-
ok: true,
|
|
3804
|
-
rev: "dummy"
|
|
3805
|
-
};
|
|
3806
|
-
}
|
|
3807
|
-
const newDoc = {
|
|
3808
|
-
children: chunks,
|
|
3809
|
-
_id: note._id,
|
|
3810
|
-
path: note.path,
|
|
3811
|
-
ctime: note.ctime,
|
|
3812
|
-
mtime: note.mtime,
|
|
3813
|
-
size: note.size,
|
|
3814
|
-
type: note.datatype,
|
|
3815
|
-
eden: {}
|
|
3816
|
-
};
|
|
3817
|
-
return await serialized("file:" + filename, async () => {
|
|
3818
|
-
try {
|
|
3819
|
-
const old = await this.localDatabase.get(newDoc._id);
|
|
3820
|
-
newDoc._rev = old._rev;
|
|
3821
|
-
} catch (ex) {
|
|
3822
|
-
if (isErrorOfMissingDoc(ex)) {
|
|
3823
|
-
} else {
|
|
3824
|
-
throw ex;
|
|
3825
|
-
}
|
|
3826
|
-
}
|
|
3827
|
-
const r = await this.localDatabase.put(newDoc, { force: true });
|
|
3828
|
-
if (r.ok) {
|
|
3829
|
-
return r;
|
|
3830
|
-
} else {
|
|
3831
|
-
return false;
|
|
3832
|
-
}
|
|
3833
|
-
}) ?? false;
|
|
3834
|
-
});
|
|
3835
|
-
if (result === false) {
|
|
3836
|
-
Logger8(`Failed to write document ${dispFilename}`, LOG_LEVEL_NOTICE3);
|
|
3837
|
-
return false;
|
|
3838
|
-
}
|
|
3839
|
-
Logger8(`Document saved: ${dispFilename} (${result.id.substring(0, 8)}-${result.rev})`, LOG_LEVEL_VERBOSE8);
|
|
3840
|
-
return result;
|
|
3841
|
-
}
|
|
3842
|
-
};
|
|
3843
|
-
|
|
3844
|
-
// lib/livesync-commonlib/src/managers/HashManager/HashManagerCore.ts
|
|
3845
|
-
import { fallbackMixedHashEach, mixedHash } from "octagonal-wheels/hash/purejs";
|
|
3846
|
-
var HashEncryptedPrefix = "+";
|
|
3847
|
-
var HashManagerCore = class {
|
|
3848
|
-
/**
|
|
3849
|
-
* Remote database settings.
|
|
3850
|
-
*/
|
|
3851
|
-
settings;
|
|
3852
|
-
/**
|
|
3853
|
-
* Indicates whether encryption is enabled for hash computation.
|
|
3854
|
-
*/
|
|
3855
|
-
useEncryption = false;
|
|
3856
|
-
/**
|
|
3857
|
-
* Hashed passphrase as a string, used for hash operations.
|
|
3858
|
-
*/
|
|
3859
|
-
hashedPassphrase = "";
|
|
3860
|
-
/**
|
|
3861
|
-
* Hashed passphrase as a 32-bit number, used for hash operations.
|
|
3862
|
-
*/
|
|
3863
|
-
hashedPassphrase32 = 0;
|
|
3864
|
-
/**
|
|
3865
|
-
* Options used for initialisation and configuration.
|
|
3866
|
-
*/
|
|
3867
|
-
options;
|
|
3868
|
-
/**
|
|
3869
|
-
* Constructs a new {@link HashManagerCore} instance.
|
|
3870
|
-
*
|
|
3871
|
-
* @param options - Configuration options for hash management.
|
|
3872
|
-
*/
|
|
3873
|
-
constructor(options) {
|
|
3874
|
-
this.options = options;
|
|
3875
|
-
this.settings = options.settings;
|
|
3876
|
-
this.applyOptions(options);
|
|
3877
|
-
}
|
|
3878
|
-
/**
|
|
3879
|
-
* Applies the given options to the hash manager.
|
|
3880
|
-
*
|
|
3881
|
-
* Updates encryption settings and computes passphrase hashes.
|
|
3882
|
-
*
|
|
3883
|
-
* @param options - Optional configuration to apply.
|
|
3884
|
-
*/
|
|
3885
|
-
applyOptions(options) {
|
|
3886
|
-
if (options) {
|
|
3887
|
-
this.options = options;
|
|
3888
|
-
}
|
|
3889
|
-
this.settings = this.options.settings;
|
|
3890
|
-
this.useEncryption = this.settings.encrypt ?? false;
|
|
3891
|
-
const passphrase = this.settings.passphrase || "";
|
|
3892
|
-
const usingLetters = ~~(passphrase.length / 4 * 3);
|
|
3893
|
-
const passphraseForHash = SALT_OF_ID + passphrase.substring(0, usingLetters);
|
|
3894
|
-
this.hashedPassphrase = fallbackMixedHashEach(passphraseForHash);
|
|
3895
|
-
this.hashedPassphrase32 = mixedHash(passphraseForHash, SEED_MURMURHASH)[0];
|
|
3896
|
-
}
|
|
3897
|
-
/**
|
|
3898
|
-
* Task representing the initialisation process.
|
|
3899
|
-
*/
|
|
3900
|
-
initialiseTask;
|
|
3901
|
-
/**
|
|
3902
|
-
* Ensures the hash manager is initialised.
|
|
3903
|
-
*
|
|
3904
|
-
* Returns a promise that resolves when initialisation is complete.
|
|
3905
|
-
*
|
|
3906
|
-
* @returns Promise resolving to true if initialisation succeeds.
|
|
3907
|
-
*/
|
|
3908
|
-
initialise() {
|
|
3909
|
-
if (this.initialiseTask) {
|
|
3910
|
-
return this.initialiseTask;
|
|
3911
|
-
}
|
|
3912
|
-
this.initialiseTask = this.processInitialise();
|
|
3913
|
-
return this.initialiseTask;
|
|
3914
|
-
}
|
|
3915
|
-
/**
|
|
3916
|
-
* Computes a hash for the given string.
|
|
3917
|
-
*
|
|
3918
|
-
* If encryption is enabled, the hash is computed with encryption and prefixed.
|
|
3919
|
-
* Otherwise, a plain hash is computed.
|
|
3920
|
-
*
|
|
3921
|
-
* @param piece - The input string to hash.
|
|
3922
|
-
* @returns Promise resolving to the computed hash string.
|
|
3923
|
-
*/
|
|
3924
|
-
async computeHash(piece) {
|
|
3925
|
-
await this.initialiseTask;
|
|
3926
|
-
if (this.useEncryption) {
|
|
3927
|
-
return HashEncryptedPrefix + await this.computeHashWithEncryption(piece);
|
|
3928
|
-
}
|
|
3929
|
-
return await this.computeHashWithoutEncryption(piece);
|
|
3930
|
-
}
|
|
3931
|
-
/**
|
|
3932
|
-
* Determines whether the hash manager is available for the specified algorithm.
|
|
3933
|
-
*
|
|
3934
|
-
* Subclasses should override this method to indicate supported algorithms.
|
|
3935
|
-
*
|
|
3936
|
-
* @param hashAlg - The hash algorithm to check.
|
|
3937
|
-
* @returns True if available, false otherwise.
|
|
3938
|
-
*/
|
|
3939
|
-
static isAvailableFor(hashAlg) {
|
|
3940
|
-
return false;
|
|
3941
|
-
}
|
|
3942
|
-
};
|
|
3943
|
-
|
|
3944
|
-
// lib/livesync-commonlib/src/string_and_binary/hash.ts
|
|
3945
|
-
var hash_exports = {};
|
|
3946
|
-
__reExport(hash_exports, xxhash_star);
|
|
3947
|
-
import * as xxhash_star from "octagonal-wheels/hash/xxhash.js";
|
|
3948
|
-
|
|
3949
|
-
// lib/livesync-commonlib/src/managers/HashManager/XXHashHashManager.ts
|
|
3950
|
-
var XXHashHashManager = class extends HashManagerCore {
|
|
3951
|
-
/**
|
|
3952
|
-
* Instance of XXHash API used for hashing operations.
|
|
3953
|
-
*/
|
|
3954
|
-
xxhash;
|
|
3955
|
-
/**
|
|
3956
|
-
* Constructs a new XXHashHashManager.
|
|
3957
|
-
* @param options - Options for the hash manager core.
|
|
3958
|
-
*/
|
|
3959
|
-
constructor(options) {
|
|
3960
|
-
super(options);
|
|
3961
|
-
}
|
|
3962
|
-
/**
|
|
3963
|
-
* Initialises the XXHash API instance.
|
|
3964
|
-
* @returns A promise resolving to true when initialisation is complete.
|
|
3965
|
-
*/
|
|
3966
|
-
async processInitialise() {
|
|
3967
|
-
this.xxhash = await (0, hash_exports.xxhashNew)();
|
|
3968
|
-
return true;
|
|
3969
|
-
}
|
|
3970
|
-
};
|
|
3971
|
-
var XXHash32RawHashManager = class extends XXHashHashManager {
|
|
3972
|
-
/**
|
|
3973
|
-
* Determines whether this manager is available for the specified algorithm.
|
|
3974
|
-
* @param hashAlg - The hash algorithm to check.
|
|
3975
|
-
* @returns True if available, false otherwise.
|
|
3976
|
-
*/
|
|
3977
|
-
static isAvailableFor(hashAlg) {
|
|
3978
|
-
return hashAlg === HashAlgorithms.LEGACY;
|
|
3979
|
-
}
|
|
3980
|
-
/**
|
|
3981
|
-
* Computes a hash for the given piece using encryption.
|
|
3982
|
-
* @param piece - The input string to hash.
|
|
3983
|
-
* @returns A promise resolving to the hash string.
|
|
3984
|
-
*/
|
|
3985
|
-
computeHashWithEncryption(piece) {
|
|
3986
|
-
return Promise.resolve(
|
|
3987
|
-
(this.xxhash.h32Raw(new TextEncoder().encode(piece)) ^ this.hashedPassphrase32 ^ piece.length).toString(36)
|
|
3988
|
-
);
|
|
3989
|
-
}
|
|
3990
|
-
/**
|
|
3991
|
-
* Computes a hash for the given piece without encryption.
|
|
3992
|
-
* @param piece - The input string to hash.
|
|
3993
|
-
* @returns A promise resolving to the hash string.
|
|
3994
|
-
*/
|
|
3995
|
-
computeHashWithoutEncryption(piece) {
|
|
3996
|
-
return Promise.resolve((this.xxhash.h32Raw(new TextEncoder().encode(piece)) ^ piece.length).toString(36));
|
|
3997
|
-
}
|
|
3998
|
-
};
|
|
3999
|
-
var XXHash64HashManager = class extends XXHashHashManager {
|
|
4000
|
-
/**
|
|
4001
|
-
* Determines whether this manager is available for the specified algorithm.
|
|
4002
|
-
* @param hashAlg - The hash algorithm to check.
|
|
4003
|
-
* @returns True if available, false otherwise.
|
|
4004
|
-
*/
|
|
4005
|
-
static isAvailableFor(hashAlg) {
|
|
4006
|
-
return hashAlg === HashAlgorithms.XXHASH64;
|
|
4007
|
-
}
|
|
4008
|
-
/**
|
|
4009
|
-
* Computes a hash for the given piece using encryption.
|
|
4010
|
-
* @param piece - The input string to hash.
|
|
4011
|
-
* @returns A promise resolving to the hash string.
|
|
4012
|
-
*/
|
|
4013
|
-
computeHashWithEncryption(piece) {
|
|
4014
|
-
return Promise.resolve(this.xxhash.h64(`${piece}-${this.hashedPassphrase}-${piece.length}`).toString(36));
|
|
4015
|
-
}
|
|
4016
|
-
/**
|
|
4017
|
-
* Computes a hash for the given piece without encryption.
|
|
4018
|
-
* @param piece - The input string to hash.
|
|
4019
|
-
* @returns A promise resolving to the hash string.
|
|
4020
|
-
*/
|
|
4021
|
-
computeHashWithoutEncryption(piece) {
|
|
4022
|
-
return Promise.resolve(this.xxhash.h64(`${piece}-${piece.length}`).toString(36));
|
|
4023
|
-
}
|
|
4024
|
-
};
|
|
4025
|
-
var FallbackWasmHashManager = class extends XXHashHashManager {
|
|
4026
|
-
/**
|
|
4027
|
-
* Determines whether this manager is available for the specified algorithm.
|
|
4028
|
-
* Always returns true as a fallback.
|
|
4029
|
-
* @param hashAlg - The hash algorithm to check.
|
|
4030
|
-
* @returns True.
|
|
4031
|
-
*/
|
|
4032
|
-
static isAvailableFor(hashAlg) {
|
|
4033
|
-
return true;
|
|
4034
|
-
}
|
|
4035
|
-
/**
|
|
4036
|
-
* Computes a hash for the given piece using encryption.
|
|
4037
|
-
* @param piece - The input string to hash.
|
|
4038
|
-
* @returns A promise resolving to the hash string.
|
|
4039
|
-
*/
|
|
4040
|
-
computeHashWithEncryption(piece) {
|
|
4041
|
-
return Promise.resolve(this.xxhash.h32(`${piece}-${this.hashedPassphrase}-${piece.length}`).toString(36));
|
|
4042
|
-
}
|
|
4043
|
-
/**
|
|
4044
|
-
* Computes a hash for the given piece without encryption.
|
|
4045
|
-
* @param piece - The input string to hash.
|
|
4046
|
-
* @returns A promise resolving to the hash string.
|
|
4047
|
-
*/
|
|
4048
|
-
computeHashWithoutEncryption(piece) {
|
|
4049
|
-
return Promise.resolve(this.xxhash.h32(`${piece}-${piece.length}`).toString(36));
|
|
4050
|
-
}
|
|
4051
|
-
};
|
|
4052
|
-
|
|
4053
|
-
// lib/livesync-commonlib/src/managers/HashManager/PureJSHashManager.ts
|
|
4054
|
-
import { fallbackMixedHashEach as fallbackMixedHashEach2, sha1 } from "octagonal-wheels/hash/purejs";
|
|
4055
|
-
var PureJSHashManager = class extends HashManagerCore {
|
|
4056
|
-
/**
|
|
4057
|
-
* Determines whether this manager is available for the specified algorithm.
|
|
4058
|
-
* @param hashAlg The hash algorithm to check.
|
|
4059
|
-
* @returns True if the algorithm is "mixed-purejs".
|
|
4060
|
-
*/
|
|
4061
|
-
static isAvailableFor(hashAlg) {
|
|
4062
|
-
return hashAlg === HashAlgorithms.MIXED_PUREJS;
|
|
4063
|
-
}
|
|
4064
|
-
/**
|
|
4065
|
-
* Initialises the hash manager.
|
|
4066
|
-
* @returns Always resolves to true.
|
|
4067
|
-
*/
|
|
4068
|
-
processInitialise() {
|
|
4069
|
-
return Promise.resolve(true);
|
|
4070
|
-
}
|
|
4071
|
-
/**
|
|
4072
|
-
* Computes a hash for the given input, including encryption.
|
|
4073
|
-
* @param input The input string to hash.
|
|
4074
|
-
* @returns The computed hash as a promise.
|
|
4075
|
-
*/
|
|
4076
|
-
computeHashWithEncryption(input) {
|
|
4077
|
-
return Promise.resolve(fallbackMixedHashEach2(`${input}${this.hashedPassphrase}${input.length}`));
|
|
4078
|
-
}
|
|
4079
|
-
/**
|
|
4080
|
-
* Computes a hash for the given input, without encryption.
|
|
4081
|
-
* @param input The input string to hash.
|
|
4082
|
-
* @returns The computed hash as a promise.
|
|
4083
|
-
*/
|
|
4084
|
-
computeHashWithoutEncryption(input) {
|
|
4085
|
-
return Promise.resolve(fallbackMixedHashEach2(`${input}-${input.length}`));
|
|
4086
|
-
}
|
|
4087
|
-
};
|
|
4088
|
-
var SHA1HashManager = class extends HashManagerCore {
|
|
4089
|
-
/**
|
|
4090
|
-
* Determines whether this manager is available for the specified algorithm.
|
|
4091
|
-
* @param hashAlg The hash algorithm to check.
|
|
4092
|
-
* @returns True if the algorithm is "sha1".
|
|
4093
|
-
*/
|
|
4094
|
-
static isAvailableFor(hashAlg) {
|
|
4095
|
-
return hashAlg === HashAlgorithms.SHA1;
|
|
4096
|
-
}
|
|
4097
|
-
/**
|
|
4098
|
-
* Initialises the hash manager.
|
|
4099
|
-
* @returns Always resolves to true.
|
|
4100
|
-
*/
|
|
4101
|
-
processInitialise() {
|
|
4102
|
-
return Promise.resolve(true);
|
|
4103
|
-
}
|
|
4104
|
-
/**
|
|
4105
|
-
* Computes a SHA-1 hash for the given input, including encryption.
|
|
4106
|
-
* @param input The input string to hash.
|
|
4107
|
-
* @returns The computed SHA-1 hash as a promise.
|
|
4108
|
-
*/
|
|
4109
|
-
computeHashWithEncryption(input) {
|
|
4110
|
-
return sha1(`${input}-${this.hashedPassphrase}-${input.length}`);
|
|
4111
|
-
}
|
|
4112
|
-
/**
|
|
4113
|
-
* Computes a SHA-1 hash for the given input, without encryption.
|
|
4114
|
-
* @param input The input string to hash.
|
|
4115
|
-
* @returns The computed SHA-1 hash as a promise.
|
|
4116
|
-
*/
|
|
4117
|
-
computeHashWithoutEncryption(input) {
|
|
4118
|
-
return sha1(`${input}-${input.length}`);
|
|
4119
|
-
}
|
|
4120
|
-
};
|
|
4121
|
-
var FallbackPureJSHashManager = class extends PureJSHashManager {
|
|
4122
|
-
/**
|
|
4123
|
-
* Always returns true, indicating this manager is available for any algorithm.
|
|
4124
|
-
* @param _hashAlg The hash algorithm (ignored).
|
|
4125
|
-
* @returns True.
|
|
4126
|
-
*/
|
|
4127
|
-
static isAvailableFor(_hashAlg) {
|
|
4128
|
-
return true;
|
|
4129
|
-
}
|
|
4130
|
-
};
|
|
4131
|
-
|
|
4132
|
-
// lib/livesync-commonlib/src/managers/HashManager/HashManager.ts
|
|
4133
|
-
var HashManagers = [
|
|
4134
|
-
XXHash64HashManager,
|
|
4135
|
-
XXHash32RawHashManager,
|
|
4136
|
-
SHA1HashManager,
|
|
4137
|
-
PureJSHashManager,
|
|
4138
|
-
// Please retain these fallback managers, as they are essential for compatibility.
|
|
4139
|
-
FallbackWasmHashManager,
|
|
4140
|
-
FallbackPureJSHashManager
|
|
4141
|
-
];
|
|
4142
|
-
var HashManager = class extends HashManagerCore {
|
|
4143
|
-
/**
|
|
4144
|
-
* Instance of the hash manager currently in use.
|
|
4145
|
-
*/
|
|
4146
|
-
manager = void 0;
|
|
4147
|
-
/**
|
|
4148
|
-
* Checks whether the specified hash algorithm is available.
|
|
4149
|
-
*
|
|
4150
|
-
* @param hashAlg The hash algorithm to check
|
|
4151
|
-
* @returns True if available
|
|
4152
|
-
*/
|
|
4153
|
-
static isAvailableFor(hashAlg) {
|
|
4154
|
-
return HashManagers.some((manager) => manager.isAvailableFor(hashAlg));
|
|
4155
|
-
}
|
|
4156
|
-
/**
|
|
4157
|
-
* Selects and initialises an available hash manager.
|
|
4158
|
-
*
|
|
4159
|
-
* @returns True if initialisation is successful
|
|
4160
|
-
* @throws Throws an error if no available manager exists
|
|
4161
|
-
*/
|
|
4162
|
-
async setManager() {
|
|
4163
|
-
for (const Manager of HashManagers) {
|
|
4164
|
-
if (Manager.isAvailableFor(this.settings.hashAlg)) {
|
|
4165
|
-
this.manager = new Manager(this.options);
|
|
4166
|
-
return await this.manager.initialise();
|
|
4167
|
-
}
|
|
4168
|
-
}
|
|
4169
|
-
throw new Error(`HashManager for ${this.settings.hashAlg} is not available`);
|
|
4170
|
-
}
|
|
4171
|
-
/**
|
|
4172
|
-
* Constructs a new HashManager.
|
|
4173
|
-
*
|
|
4174
|
-
* @param options Initialisation options
|
|
4175
|
-
*/
|
|
4176
|
-
constructor(options) {
|
|
4177
|
-
super(options);
|
|
4178
|
-
}
|
|
4179
|
-
/**
|
|
4180
|
-
* Initialises the hash manager.
|
|
4181
|
-
*
|
|
4182
|
-
* @returns True if initialisation is successful
|
|
4183
|
-
* @throws Throws an error if initialisation fails
|
|
4184
|
-
*/
|
|
4185
|
-
async processInitialise() {
|
|
4186
|
-
if (await this.setManager()) {
|
|
4187
|
-
(0, logger_exports.Logger)(`HashManager for ${this.settings.hashAlg} has been initialised`, logger_exports.LOG_LEVEL_VERBOSE);
|
|
4188
|
-
return true;
|
|
4189
|
-
}
|
|
4190
|
-
(0, logger_exports.Logger)(`HashManager for ${this.settings.hashAlg} failed to initialise`);
|
|
4191
|
-
throw new Error(`HashManager for ${this.settings.hashAlg} failed to initialise`);
|
|
4192
|
-
}
|
|
4193
|
-
/**
|
|
4194
|
-
* Computes the hash value for the specified string.
|
|
4195
|
-
*
|
|
4196
|
-
* @param piece The string to be hashed
|
|
4197
|
-
* @returns The hash value (returned as a Promise)
|
|
4198
|
-
*/
|
|
4199
|
-
computeHash(piece) {
|
|
4200
|
-
return this.manager.computeHash(piece);
|
|
4201
|
-
}
|
|
4202
|
-
/**
|
|
4203
|
-
* Computes the hash value without encryption.
|
|
4204
|
-
*
|
|
4205
|
-
* @param piece The string to be hashed
|
|
4206
|
-
* @returns The hash value (returned as a Promise)
|
|
4207
|
-
*/
|
|
4208
|
-
computeHashWithoutEncryption(piece) {
|
|
4209
|
-
return this.manager.computeHashWithoutEncryption(piece);
|
|
4210
|
-
}
|
|
4211
|
-
/**
|
|
4212
|
-
* Computes the hash value with encryption.
|
|
4213
|
-
*
|
|
4214
|
-
* @param piece The string to be hashed
|
|
4215
|
-
* @returns The hash value (returned as a Promise)
|
|
4216
|
-
*/
|
|
4217
|
-
computeHashWithEncryption(piece) {
|
|
4218
|
-
return this.manager.computeHashWithEncryption(piece);
|
|
4219
|
-
}
|
|
4220
|
-
};
|
|
4221
|
-
|
|
4222
|
-
// lib/livesync-commonlib/src/managers/NetworkManager.ts
|
|
4223
|
-
var NetworkManager = class {
|
|
4224
|
-
};
|
|
4225
|
-
var NetworkManagerBrowser = class extends NetworkManager {
|
|
4226
|
-
get isOnline() {
|
|
4227
|
-
return navigator.onLine;
|
|
4228
|
-
}
|
|
4229
|
-
};
|
|
4230
|
-
|
|
4231
|
-
// lib/livesync-commonlib/src/managers/LiveSyncManagers.ts
|
|
4232
|
-
var LiveSyncManagers = class {
|
|
4233
|
-
hashManager;
|
|
4234
|
-
chunkFetcher;
|
|
4235
|
-
changeManager;
|
|
4236
|
-
chunkManager;
|
|
4237
|
-
splitter;
|
|
4238
|
-
entryManager;
|
|
4239
|
-
conflictManager;
|
|
4240
|
-
networkManager;
|
|
4241
|
-
options;
|
|
4242
|
-
constructor(options) {
|
|
4243
|
-
this.options = options;
|
|
4244
|
-
if (options.networkManager) {
|
|
4245
|
-
this.networkManager = options.networkManager;
|
|
4246
|
-
} else {
|
|
4247
|
-
if ("navigator" in globalThis) {
|
|
4248
|
-
this.networkManager = new NetworkManagerBrowser();
|
|
4249
|
-
} else {
|
|
4250
|
-
throw new LiveSyncError("No NetworkManager available");
|
|
4251
|
-
}
|
|
4252
|
-
}
|
|
4253
|
-
}
|
|
4254
|
-
get settings() {
|
|
4255
|
-
return this.options.settings;
|
|
4256
|
-
}
|
|
4257
|
-
async teardownManagers() {
|
|
4258
|
-
if (this.changeManager) {
|
|
4259
|
-
this.changeManager.teardown();
|
|
4260
|
-
this.changeManager = void 0;
|
|
4261
|
-
}
|
|
4262
|
-
if (this.chunkFetcher) {
|
|
4263
|
-
this.chunkFetcher.destroy();
|
|
4264
|
-
this.chunkFetcher = void 0;
|
|
4265
|
-
}
|
|
4266
|
-
if (this.chunkManager) {
|
|
4267
|
-
this.chunkManager.destroy();
|
|
4268
|
-
this.chunkManager = void 0;
|
|
4269
|
-
}
|
|
4270
|
-
return await Promise.resolve();
|
|
4271
|
-
}
|
|
4272
|
-
getProxy() {
|
|
4273
|
-
const getDB = () => this.options.database;
|
|
4274
|
-
const getChangeManager = () => this.changeManager;
|
|
4275
|
-
const getChunkManager = () => this.chunkManager;
|
|
4276
|
-
const getReplicator = () => this.options.getActiveReplicator();
|
|
4277
|
-
const getSettings = () => this.options.settings;
|
|
4278
|
-
const getEntryManager = () => this.entryManager;
|
|
4279
|
-
const getHashManager = () => this.hashManager;
|
|
4280
|
-
const getChunkFetcher = () => this.chunkFetcher;
|
|
4281
|
-
const getSplitter = () => this.splitter;
|
|
4282
|
-
const proxy = {
|
|
4283
|
-
get database() {
|
|
4284
|
-
return getDB();
|
|
4285
|
-
},
|
|
4286
|
-
get changeManager() {
|
|
4287
|
-
return getChangeManager();
|
|
4288
|
-
},
|
|
4289
|
-
get chunkManager() {
|
|
4290
|
-
return getChunkManager();
|
|
4291
|
-
},
|
|
4292
|
-
getActiveReplicator() {
|
|
4293
|
-
return getReplicator();
|
|
4294
|
-
},
|
|
4295
|
-
get settings() {
|
|
4296
|
-
return getSettings();
|
|
4297
|
-
},
|
|
4298
|
-
get entryManager() {
|
|
4299
|
-
return getEntryManager();
|
|
4300
|
-
},
|
|
4301
|
-
get hashManager() {
|
|
4302
|
-
return getHashManager();
|
|
4303
|
-
},
|
|
4304
|
-
$$path2id: (filename, prefix) => {
|
|
4305
|
-
return this.options.path2id(filename, prefix);
|
|
4306
|
-
},
|
|
4307
|
-
$$id2path: (id, entry, stripPrefix) => {
|
|
4308
|
-
return this.options.id2path(id, entry, stripPrefix);
|
|
4309
|
-
},
|
|
4310
|
-
get chunkFetcher() {
|
|
4311
|
-
return getChunkFetcher();
|
|
4312
|
-
},
|
|
4313
|
-
get splitter() {
|
|
4314
|
-
return getSplitter();
|
|
4315
|
-
}
|
|
4316
|
-
};
|
|
4317
|
-
return proxy;
|
|
4318
|
-
}
|
|
4319
|
-
async initManagers() {
|
|
4320
|
-
await this.teardownManagers();
|
|
4321
|
-
const proxy = this.getProxy();
|
|
4322
|
-
this.hashManager = new HashManager({
|
|
4323
|
-
...proxy
|
|
4324
|
-
});
|
|
4325
|
-
this.splitter = new ContentSplitter({
|
|
4326
|
-
...proxy
|
|
4327
|
-
});
|
|
4328
|
-
await this.splitter.initialise(
|
|
4329
|
-
proxy
|
|
4330
|
-
);
|
|
4331
|
-
await this.hashManager.initialise();
|
|
4332
|
-
this.changeManager = new ChangeManager(proxy);
|
|
4333
|
-
this.chunkManager = new ChunkManager({
|
|
4334
|
-
...proxy,
|
|
4335
|
-
maxCacheSize: this.settings.hashCacheMaxCount * 10
|
|
4336
|
-
});
|
|
4337
|
-
this.chunkFetcher = new ChunkFetcher(proxy);
|
|
4338
|
-
this.entryManager = new EntryManager({
|
|
4339
|
-
...proxy
|
|
4340
|
-
});
|
|
4341
|
-
this.conflictManager = new ConflictManager({
|
|
4342
|
-
...proxy
|
|
4343
|
-
});
|
|
4344
|
-
}
|
|
4345
|
-
clearCaches() {
|
|
4346
|
-
this.chunkManager?.clearCaches();
|
|
4347
|
-
}
|
|
4348
|
-
async prepareHashFunction() {
|
|
4349
|
-
const proxy = this.getProxy();
|
|
4350
|
-
this.hashManager = new HashManager(proxy);
|
|
4351
|
-
await this.hashManager.initialise();
|
|
4352
|
-
}
|
|
4353
|
-
};
|
|
4354
|
-
|
|
4355
|
-
// lib/livesync-commonlib/src/API/DirectFileManipulatorV2.ts
|
|
4356
|
-
function isNoteEntry(doc) {
|
|
4357
|
-
if (!doc) return false;
|
|
4358
|
-
return doc.type == "newnote" || doc.type == "plain";
|
|
4359
|
-
}
|
|
4360
|
-
function isReadyEntry(doc) {
|
|
4361
|
-
if (!doc) return false;
|
|
4362
|
-
return "data" in doc;
|
|
4363
|
-
}
|
|
4364
|
-
var DirectFileManipulator = class {
|
|
4365
|
-
liveSyncLocalDB;
|
|
4366
|
-
managers;
|
|
4367
|
-
options;
|
|
4368
|
-
ready = promiseWithResolver2();
|
|
4369
|
-
constructor(options) {
|
|
4370
|
-
this.options = options;
|
|
4371
|
-
const getDB = () => this.liveSyncLocalDB.localDatabase;
|
|
4372
|
-
const getSettings = () => this.settings;
|
|
4373
|
-
this.managers = new LiveSyncManagers({
|
|
4374
|
-
get database() {
|
|
4375
|
-
return getDB();
|
|
4376
|
-
},
|
|
4377
|
-
getActiveReplicator: () => this.$$getReplicator(),
|
|
4378
|
-
id2path: this.$$id2path.bind(this),
|
|
4379
|
-
path2id: this.$$path2id.bind(this),
|
|
4380
|
-
get settings() {
|
|
4381
|
-
return getSettings();
|
|
4382
|
-
}
|
|
4383
|
-
});
|
|
4384
|
-
this.liveSyncLocalDB = new LiveSyncLocalDB(this.options.url, this);
|
|
4385
|
-
void this.liveSyncLocalDB.initializeDatabase().then(() => {
|
|
4386
|
-
this.ready.resolve();
|
|
4387
|
-
this.liveSyncLocalDB.refreshSettings();
|
|
4388
|
-
});
|
|
4389
|
-
}
|
|
4390
|
-
$$id2path(id, entry, stripPrefix) {
|
|
4391
|
-
const path = id2path_base(id, entry);
|
|
4392
|
-
if (stripPrefix) {
|
|
4393
|
-
return stripAllPrefixes(path);
|
|
4394
|
-
}
|
|
4395
|
-
return path;
|
|
4396
|
-
}
|
|
4397
|
-
async $$path2id(filename, prefix) {
|
|
4398
|
-
const fileName = prefix ? addPrefix(filename, prefix) : filename;
|
|
4399
|
-
const id = await path2id_base(
|
|
4400
|
-
fileName,
|
|
4401
|
-
this.options.obfuscatePassphrase ?? false,
|
|
4402
|
-
!this.options.handleFilenameCaseSensitive
|
|
4403
|
-
);
|
|
4404
|
-
return id;
|
|
4405
|
-
}
|
|
4406
|
-
$$createPouchDBInstance(_name, _options) {
|
|
4407
|
-
return new PouchDB(this.options.url + "/" + this.options.database, {
|
|
4408
|
-
auth: { username: this.options.username, password: this.options.password }
|
|
4409
|
-
});
|
|
4410
|
-
}
|
|
4411
|
-
$allOnDBUnload(_db) {
|
|
4412
|
-
return;
|
|
4413
|
-
}
|
|
4414
|
-
$allOnDBClose(_db) {
|
|
4415
|
-
return;
|
|
4416
|
-
}
|
|
4417
|
-
getInitialSyncParameters(setting) {
|
|
4418
|
-
return Promise.resolve({
|
|
4419
|
-
...DEFAULT_SYNC_PARAMETERS,
|
|
4420
|
-
protocolVersion: ProtocolVersions.ADVANCED_E2EE
|
|
4421
|
-
});
|
|
4422
|
-
}
|
|
4423
|
-
async getSyncParameters(setting) {
|
|
4424
|
-
try {
|
|
4425
|
-
const downloadedSyncParams = await this.rawGet(DOCID_SYNC_PARAMETERS);
|
|
4426
|
-
if (!downloadedSyncParams) {
|
|
4427
|
-
throw new SyncParamsNotFoundError(`Sync parameters have not been found in the database.`);
|
|
4428
|
-
}
|
|
4429
|
-
return downloadedSyncParams;
|
|
4430
|
-
} catch (ex) {
|
|
4431
|
-
Logger10(`Could not retrieve remote sync parameters`, LOG_LEVEL_INFO4);
|
|
4432
|
-
throw SyncParamsFetchError.fromError(ex);
|
|
4433
|
-
}
|
|
4434
|
-
}
|
|
4435
|
-
async putSyncParameters(setting, params) {
|
|
4436
|
-
try {
|
|
4437
|
-
const ret = await this.liveSyncLocalDB.putRaw(params);
|
|
4438
|
-
if (ret.ok) {
|
|
4439
|
-
return true;
|
|
4440
|
-
}
|
|
4441
|
-
throw new SyncParamsUpdateError(`Could not store remote sync parameters`);
|
|
4442
|
-
} catch (ex) {
|
|
4443
|
-
Logger10(`Could not store remote sync parameters`, LOG_LEVEL_INFO4);
|
|
4444
|
-
throw SyncParamsUpdateError.fromError(ex);
|
|
4445
|
-
}
|
|
4446
|
-
}
|
|
4447
|
-
async getReplicationPBKDF2Salt(setting, refresh) {
|
|
4448
|
-
const server = `${setting.couchDB_URI}/${setting.couchDB_DBNAME}`;
|
|
4449
|
-
const manager = createSyncParamsHanderForServer(server, {
|
|
4450
|
-
put: (params) => this.putSyncParameters(setting, params),
|
|
4451
|
-
get: () => this.getSyncParameters(setting),
|
|
4452
|
-
create: () => this.getInitialSyncParameters(setting)
|
|
4453
|
-
});
|
|
4454
|
-
return await manager.getPBKDF2Salt(refresh);
|
|
4455
|
-
}
|
|
4456
|
-
$everyOnInitializeDatabase(db) {
|
|
4457
|
-
replicationFilter(db.localDatabase, this.options.enableCompression ?? false);
|
|
4458
|
-
disableEncryption();
|
|
4459
|
-
if (this.options.passphrase && typeof this.options.passphrase === "string") {
|
|
4460
|
-
enableEncryption(
|
|
4461
|
-
db.localDatabase,
|
|
4462
|
-
this.options.passphrase,
|
|
4463
|
-
this.options.useDynamicIterationCount ?? false,
|
|
4464
|
-
false,
|
|
4465
|
-
async () => await this.getReplicationPBKDF2Salt(this.getSettings()),
|
|
4466
|
-
this.options.E2EEAlgorithm ?? E2EEAlgorithms.V2
|
|
4467
|
-
);
|
|
4468
|
-
}
|
|
4469
|
-
return Promise.resolve(true);
|
|
4470
|
-
}
|
|
4471
|
-
$everyOnResetDatabase(_db) {
|
|
4472
|
-
throw new Error("Method not implemented.");
|
|
4473
|
-
}
|
|
4474
|
-
$$getReplicator = () => {
|
|
4475
|
-
throw new Error("Method not implemented.");
|
|
4476
|
-
};
|
|
4477
|
-
getSettings() {
|
|
4478
|
-
return this.settings;
|
|
4479
|
-
}
|
|
4480
|
-
async close() {
|
|
4481
|
-
await this.liveSyncLocalDB.close();
|
|
4482
|
-
return this.liveSyncLocalDB.onunload();
|
|
4483
|
-
}
|
|
4484
|
-
async path2id(filename, prefix) {
|
|
4485
|
-
const fileName = prefix ? addPrefix(filename, prefix) : filename;
|
|
4486
|
-
const id = await path2id_base(
|
|
4487
|
-
fileName,
|
|
4488
|
-
this.options.obfuscatePassphrase ?? false,
|
|
4489
|
-
!this.options.handleFilenameCaseSensitive
|
|
4490
|
-
);
|
|
4491
|
-
return id;
|
|
4492
|
-
}
|
|
4493
|
-
get settings() {
|
|
4494
|
-
const retObj = {
|
|
4495
|
-
...DEFAULT_SETTINGS,
|
|
4496
|
-
...{
|
|
4497
|
-
minimumChunkSize: this.options.minimumChunkSize ?? DEFAULT_SETTINGS.minimumChunkSize,
|
|
4498
|
-
encrypt: this.options.passphrase ? true : false,
|
|
4499
|
-
passphrase: this.options.passphrase ?? "",
|
|
4500
|
-
deleteMetadataOfDeletedFiles: DEFAULT_SETTINGS.deleteMetadataOfDeletedFiles,
|
|
4501
|
-
customChunkSize: this.options.customChunkSize ?? DEFAULT_SETTINGS.customChunkSize,
|
|
4502
|
-
doNotPaceReplication: DEFAULT_SETTINGS.doNotPaceReplication,
|
|
4503
|
-
hashAlg: this.options.hashAlg ?? DEFAULT_SETTINGS.hashAlg,
|
|
4504
|
-
useEden: this.options.useEden ?? DEFAULT_SETTINGS.useEden,
|
|
4505
|
-
maxChunksInEden: this.options.maxChunksInEden ?? DEFAULT_SETTINGS.maxChunksInEden,
|
|
4506
|
-
maxTotalLengthInEden: this.options.maxTotalLengthInEden ?? DEFAULT_SETTINGS.maxTotalLengthInEden,
|
|
4507
|
-
maxAgeInEden: this.options.maxAgeInEden ?? DEFAULT_SETTINGS.maxAgeInEden,
|
|
4508
|
-
enableChunkSplitterV2: this.options.enableChunkSplitterV2 ?? DEFAULT_SETTINGS.enableChunkSplitterV2,
|
|
4509
|
-
chunkSplitterVersion: this.options.chunkSplitterVersion ?? DEFAULT_SETTINGS.chunkSplitterVersion,
|
|
4510
|
-
disableWorkerForGeneratingChunks: true,
|
|
4511
|
-
processSmallFilesInUIThread: true,
|
|
4512
|
-
doNotUseFixedRevisionForChunks: this.options.doNotUseFixedRevisionForChunks ?? DEFAULT_SETTINGS.doNotUseFixedRevisionForChunks,
|
|
4513
|
-
couchDB_URI: this.options.url,
|
|
4514
|
-
couchDB_DBNAME: this.options.database,
|
|
4515
|
-
couchDB_USER: this.options.username,
|
|
4516
|
-
couchDB_PASSWORD: this.options.password,
|
|
4517
|
-
accessKey: "",
|
|
4518
|
-
secretKey: "",
|
|
4519
|
-
bucket: "",
|
|
4520
|
-
region: "",
|
|
4521
|
-
endpoint: "",
|
|
4522
|
-
enableCompression: this.options.enableCompression ?? DEFAULT_SETTINGS.enableCompression,
|
|
4523
|
-
handleFilenameCaseSensitive: this.options.handleFilenameCaseSensitive ?? DEFAULT_SETTINGS.handleFilenameCaseSensitive,
|
|
4524
|
-
E2EEAlgorithm: this.options.E2EEAlgorithm ?? E2EEAlgorithms.V2
|
|
4525
|
-
}
|
|
4526
|
-
};
|
|
4527
|
-
return retObj;
|
|
4528
|
-
}
|
|
4529
|
-
/**
|
|
4530
|
-
* Get specific document from the Remote Database by path.
|
|
4531
|
-
* @param path
|
|
4532
|
-
* @param metaOnly if it has been enabled, the note does not contains the content.
|
|
4533
|
-
* @returns
|
|
4534
|
-
*/
|
|
4535
|
-
async get(path, metaOnly = false) {
|
|
4536
|
-
if (metaOnly) {
|
|
4537
|
-
return await this.liveSyncLocalDB.getDBEntryMeta(path);
|
|
4538
|
-
} else {
|
|
4539
|
-
return await this.liveSyncLocalDB.getDBEntry(path);
|
|
4540
|
-
}
|
|
4541
|
-
}
|
|
4542
|
-
/**
|
|
4543
|
-
* Get specific document from the Remote Database by ID.
|
|
4544
|
-
* @param path
|
|
4545
|
-
* @param metaOnly if it has been enabled, the note does not contains the content.
|
|
4546
|
-
* @returns
|
|
4547
|
-
*/
|
|
4548
|
-
async getById(id, metaOnly = false) {
|
|
4549
|
-
const meta = await this.liveSyncLocalDB.getRaw(id);
|
|
4550
|
-
if (!isNoteEntry(meta)) return false;
|
|
4551
|
-
if (metaOnly) {
|
|
4552
|
-
return meta;
|
|
4553
|
-
}
|
|
4554
|
-
return this.getByMeta(meta);
|
|
4555
|
-
}
|
|
4556
|
-
async getByMeta(doc) {
|
|
4557
|
-
const docX = await this.liveSyncLocalDB.getDBEntryFromMeta(doc);
|
|
4558
|
-
if (!isReadyEntry(docX)) {
|
|
4559
|
-
throw new Error(`Corrupted document: ${doc.path}`);
|
|
4560
|
-
}
|
|
4561
|
-
return docX;
|
|
4562
|
-
}
|
|
4563
|
-
async rawGet(id) {
|
|
4564
|
-
try {
|
|
4565
|
-
const doc = await this.liveSyncLocalDB.getRaw(id);
|
|
4566
|
-
return doc;
|
|
4567
|
-
} catch (ex) {
|
|
4568
|
-
if (isErrorOfMissingDoc(ex)) {
|
|
4569
|
-
return false;
|
|
4570
|
-
}
|
|
4571
|
-
throw ex;
|
|
4572
|
-
}
|
|
4573
|
-
}
|
|
4574
|
-
/**
|
|
4575
|
-
* Put a note to the remote database
|
|
4576
|
-
* @param path
|
|
4577
|
-
* @param data
|
|
4578
|
-
* @param info
|
|
4579
|
-
* @param type
|
|
4580
|
-
* @returns
|
|
4581
|
-
*/
|
|
4582
|
-
async put(path, data, info, _type = "plain") {
|
|
4583
|
-
const id = await this.path2id(path);
|
|
4584
|
-
const saveData = data instanceof Blob ? data : createBlob(data);
|
|
4585
|
-
const datatype = determineTypeFromBlob(saveData);
|
|
4586
|
-
const putDoc = {
|
|
4587
|
-
_id: id,
|
|
4588
|
-
path,
|
|
4589
|
-
data: saveData,
|
|
4590
|
-
ctime: info.ctime,
|
|
4591
|
-
mtime: info.mtime,
|
|
4592
|
-
size: info.size,
|
|
4593
|
-
type: datatype,
|
|
4594
|
-
eden: {},
|
|
4595
|
-
children: [],
|
|
4596
|
-
datatype
|
|
4597
|
-
};
|
|
4598
|
-
Logger10(`PUT: UPLOADING: ${path}`, LOG_LEVEL_VERBOSE10);
|
|
4599
|
-
const ret = await this.liveSyncLocalDB.putDBEntry(putDoc);
|
|
4600
|
-
if (ret) {
|
|
4601
|
-
Logger10(`PUT: DONE: ${path}`, LOG_LEVEL_INFO4);
|
|
4602
|
-
return true;
|
|
4603
|
-
} else {
|
|
4604
|
-
Logger10(`PUT: FAILED: ${path}`, LOG_LEVEL_NOTICE4);
|
|
4605
|
-
return false;
|
|
4606
|
-
}
|
|
4607
|
-
}
|
|
4608
|
-
async delete(path) {
|
|
4609
|
-
Logger10(`DELETE: START: ${path}`, LOG_LEVEL_VERBOSE10);
|
|
4610
|
-
const ret = await this.liveSyncLocalDB.deleteDBEntry(path);
|
|
4611
|
-
if (ret) {
|
|
4612
|
-
Logger10(`DELETE: DONE: ${path}`, LOG_LEVEL_INFO4);
|
|
4613
|
-
return true;
|
|
4614
|
-
} else {
|
|
4615
|
-
Logger10(`DELETE: FAILED: ${path}`, LOG_LEVEL_INFO4);
|
|
4616
|
-
return false;
|
|
4617
|
-
}
|
|
4618
|
-
}
|
|
4619
|
-
// Untested
|
|
4620
|
-
async *enumerate(_cond) {
|
|
4621
|
-
}
|
|
4622
|
-
async *_enumerate(startKey, endKey, opt) {
|
|
4623
|
-
if (opt.metaOnly) return this.liveSyncLocalDB.findEntries(startKey, endKey, {});
|
|
4624
|
-
for await (const f of this.liveSyncLocalDB.findEntries(startKey, endKey, {})) {
|
|
4625
|
-
yield await this.getByMeta(f);
|
|
4626
|
-
}
|
|
4627
|
-
}
|
|
4628
|
-
async *enumerateAllNormalDocs(opt) {
|
|
4629
|
-
const targets = [
|
|
4630
|
-
this._enumerate("", "h:", opt),
|
|
4631
|
-
this._enumerate(`h:\u{10FFFF}`, "i:", opt),
|
|
4632
|
-
this._enumerate(`i:\u{10FFFF}`, "ix:", opt),
|
|
4633
|
-
this._enumerate(`ix:\u{10FFFF}`, "ps:", opt),
|
|
4634
|
-
this._enumerate(`ps:\u{10FFFF}`, "\u{10FFFF}", opt)
|
|
4635
|
-
];
|
|
4636
|
-
for (const target of targets) {
|
|
4637
|
-
for await (const f of target) {
|
|
4638
|
-
yield f;
|
|
4639
|
-
}
|
|
4640
|
-
}
|
|
4641
|
-
}
|
|
4642
|
-
watching = false;
|
|
4643
|
-
// _abortController?: AbortController;
|
|
4644
|
-
changes;
|
|
4645
|
-
since = "";
|
|
4646
|
-
beginWatch(callback, checkIsInterested) {
|
|
4647
|
-
if (this.watching) return false;
|
|
4648
|
-
this.watching = true;
|
|
4649
|
-
this.changes = this.liveSyncLocalDB.localDatabase.changes({
|
|
4650
|
-
include_docs: true,
|
|
4651
|
-
since: this.since,
|
|
4652
|
-
selector: {
|
|
4653
|
-
type: { $ne: "leaf" }
|
|
4654
|
-
},
|
|
4655
|
-
live: true
|
|
4656
|
-
}).on("change", async (change) => {
|
|
4657
|
-
const doc = change.doc;
|
|
4658
|
-
if (!doc) {
|
|
4659
|
-
return;
|
|
4660
|
-
}
|
|
4661
|
-
if (!isNoteEntry(doc)) {
|
|
4662
|
-
return;
|
|
4663
|
-
}
|
|
4664
|
-
if (checkIsInterested) {
|
|
4665
|
-
if (!checkIsInterested(doc)) {
|
|
4666
|
-
Logger10(`WATCH: SKIP ${doc.path}: OUT OF TARGET FOLDER`, LOG_LEVEL_VERBOSE10, "watch");
|
|
4667
|
-
return;
|
|
4668
|
-
}
|
|
4669
|
-
}
|
|
4670
|
-
Logger10(`WATCH: PROCESSING: ${doc.path}`, LEVEL_VERBOSE, "watch");
|
|
4671
|
-
const docX = await this.getByMeta(doc);
|
|
4672
|
-
try {
|
|
4673
|
-
await callback(docX, change.seq);
|
|
4674
|
-
Logger10(`WATCH: PROCESS DONE: ${doc.path}`, LEVEL_INFO, "watch");
|
|
4675
|
-
} catch (ex) {
|
|
4676
|
-
Logger10(`WATCH: PROCESS FAILED`, LEVEL_INFO, "watch");
|
|
4677
|
-
Logger10(ex, LEVEL_VERBOSE, "watch");
|
|
4678
|
-
}
|
|
4679
|
-
}).on("complete", () => {
|
|
4680
|
-
Logger10(`WATCH: FINISHED`, LEVEL_INFO, "watch");
|
|
4681
|
-
this.watching = false;
|
|
4682
|
-
this.changes = void 0;
|
|
4683
|
-
}).on("error", (err) => {
|
|
4684
|
-
Logger10(`WATCH: ERROR: `, LEVEL_INFO, "watch");
|
|
4685
|
-
Logger10(err, LEVEL_VERBOSE, "watch");
|
|
4686
|
-
if (this.watching) {
|
|
4687
|
-
Logger10(`WATCH: CONNECTION HAS BEEN CLOSED, RECONNECTING...`, LEVEL_INFO, "watch");
|
|
4688
|
-
this.watching = false;
|
|
4689
|
-
this.changes = void 0;
|
|
4690
|
-
setTimeout(() => {
|
|
4691
|
-
this.beginWatch(callback, checkIsInterested);
|
|
4692
|
-
}, 1e4);
|
|
4693
|
-
} else {
|
|
4694
|
-
Logger10(`WATCH: CONNECTION HAS BEEN CLOSED.`, LEVEL_INFO, "watch");
|
|
4695
|
-
}
|
|
4696
|
-
});
|
|
4697
|
-
}
|
|
4698
|
-
endWatch() {
|
|
4699
|
-
if (this.changes) {
|
|
4700
|
-
Logger10(`WATCH: CANCELLING PROCESS.`, LEVEL_INFO, "watch");
|
|
4701
|
-
this.changes.cancel();
|
|
4702
|
-
Logger10(`WATCH: CANCELLING SIGNAL HAS BEEN SENT.`, LEVEL_INFO, "watch");
|
|
4703
|
-
}
|
|
4704
|
-
}
|
|
4705
|
-
async followUpdates(callback, checkIsInterested) {
|
|
4706
|
-
try {
|
|
4707
|
-
if (this.since == "") {
|
|
4708
|
-
this.since = "0";
|
|
4709
|
-
}
|
|
4710
|
-
Logger10(`FOLLOW: START: (since:${this.since})`, LEVEL_INFO, "followUpdates");
|
|
4711
|
-
const last = await this.liveSyncLocalDB.localDatabase.changes({
|
|
4712
|
-
include_docs: true,
|
|
4713
|
-
since: this.since,
|
|
4714
|
-
filter: "replicate/pull",
|
|
4715
|
-
live: false
|
|
4716
|
-
}).on("change", async (change) => {
|
|
4717
|
-
const doc = change.doc;
|
|
4718
|
-
if (!doc) {
|
|
4719
|
-
return;
|
|
4720
|
-
}
|
|
4721
|
-
if (!isNoteEntry(doc)) {
|
|
4722
|
-
return;
|
|
4723
|
-
}
|
|
4724
|
-
if (checkIsInterested) {
|
|
4725
|
-
if (!checkIsInterested(doc)) {
|
|
4726
|
-
Logger10(`FOLLOW: SKIP ${doc._id}: OUT OF TARGET FOLDER`, LOG_LEVEL_VERBOSE10, "watch");
|
|
4727
|
-
return;
|
|
4728
|
-
}
|
|
4729
|
-
}
|
|
4730
|
-
Logger10(`FOLLOW: PROCESSING: ${doc.path}`, LEVEL_VERBOSE, "watch");
|
|
4731
|
-
const docX = await this.getByMeta(doc);
|
|
4732
|
-
try {
|
|
4733
|
-
await callback(docX, change.seq);
|
|
4734
|
-
Logger10(`FOLLOW: PROCESS DONE: ${doc.path}`, LEVEL_INFO, "watch");
|
|
4735
|
-
} catch (ex) {
|
|
4736
|
-
Logger10(`FOLLOW: PROCESS FAILED`, LEVEL_INFO, "watch");
|
|
4737
|
-
Logger10(ex, LEVEL_VERBOSE, "watch");
|
|
4738
|
-
}
|
|
4739
|
-
}).on("complete", () => {
|
|
4740
|
-
Logger10(`FOLLOW: FINISHED AT ${this.since}`, LEVEL_INFO, "watch");
|
|
4741
|
-
this.watching = false;
|
|
4742
|
-
this.changes = void 0;
|
|
4743
|
-
}).on("error", (err) => {
|
|
4744
|
-
Logger10(`FOLLOW: ERROR at ${this.since}: ${err}`, LEVEL_INFO, "watch");
|
|
4745
|
-
});
|
|
4746
|
-
return last.last_seq;
|
|
4747
|
-
} catch (e) {
|
|
4748
|
-
Logger10(`FOLLOW: ERROR: ${e}`, LEVEL_INFO, "watch");
|
|
4749
|
-
}
|
|
4750
|
-
return this.since;
|
|
4751
|
-
}
|
|
4752
|
-
};
|
|
4753
|
-
|
|
4754
|
-
// src/vault.ts
|
|
4755
|
-
var Vault = class {
|
|
4756
|
-
manipulator;
|
|
4757
|
-
constructor(config) {
|
|
4758
|
-
const opts = {
|
|
4759
|
-
url: config.couchdbUrl,
|
|
4760
|
-
username: config.couchdbUser,
|
|
4761
|
-
password: config.couchdbPassword,
|
|
4762
|
-
database: config.database,
|
|
4763
|
-
passphrase: config.passphrase,
|
|
4764
|
-
obfuscatePassphrase: config.passphrase,
|
|
4765
|
-
useEden: false,
|
|
4766
|
-
enableCompression: false,
|
|
4767
|
-
handleFilenameCaseSensitive: false,
|
|
4768
|
-
doNotUseFixedRevisionForChunks: false
|
|
4769
|
-
};
|
|
4770
|
-
this.manipulator = new DirectFileManipulator(opts);
|
|
4771
|
-
}
|
|
4772
|
-
async init() {
|
|
4773
|
-
await this.manipulator.ready.promise;
|
|
4774
|
-
}
|
|
4775
|
-
async close() {
|
|
4776
|
-
this.manipulator.endWatch();
|
|
4777
|
-
await this.manipulator.close();
|
|
4778
|
-
}
|
|
4779
|
-
watchChanges(callback) {
|
|
4780
|
-
this.manipulator.beginWatch(
|
|
4781
|
-
(doc) => {
|
|
4782
|
-
const path = doc.path ?? "";
|
|
4783
|
-
if (!path.endsWith(".md")) return;
|
|
4784
|
-
if (doc.deleted) {
|
|
4785
|
-
callback(path, null);
|
|
4786
|
-
} else {
|
|
4787
|
-
const content = "data" in doc && Array.isArray(doc.data) ? doc.data.join("") : null;
|
|
4788
|
-
callback(path, content);
|
|
4789
|
-
}
|
|
4790
|
-
},
|
|
4791
|
-
(meta) => {
|
|
4792
|
-
const path = meta.path ?? "";
|
|
4793
|
-
return path.endsWith(".md");
|
|
4794
|
-
}
|
|
4795
|
-
);
|
|
4796
|
-
}
|
|
4797
|
-
validatePath(path) {
|
|
4798
|
-
if (!path || path.includes("\0") || path.length > 1e3) {
|
|
4799
|
-
throw new Error("Invalid path");
|
|
4800
|
-
}
|
|
4801
|
-
}
|
|
4802
|
-
async readNote(path) {
|
|
4803
|
-
this.validatePath(path);
|
|
4804
|
-
const entry = await this.manipulator.get(path);
|
|
4805
|
-
if (!entry) return null;
|
|
4806
|
-
if ("data" in entry && Array.isArray(entry.data)) {
|
|
4807
|
-
return entry.data.join("");
|
|
4808
|
-
}
|
|
4809
|
-
return null;
|
|
4810
|
-
}
|
|
4811
|
-
async writeNote(path, content) {
|
|
4812
|
-
this.validatePath(path);
|
|
4813
|
-
let ctime = Date.now();
|
|
4814
|
-
const existing = await this.manipulator.get(path, true);
|
|
4815
|
-
if (existing && "ctime" in existing) {
|
|
4816
|
-
ctime = existing.ctime;
|
|
4817
|
-
}
|
|
4818
|
-
const blob = createTextBlob(content);
|
|
4819
|
-
return await this.manipulator.put(path, blob, {
|
|
4820
|
-
ctime,
|
|
4821
|
-
mtime: Date.now(),
|
|
4822
|
-
size: new TextEncoder().encode(content).byteLength
|
|
4823
|
-
});
|
|
4824
|
-
}
|
|
4825
|
-
async deleteNote(path) {
|
|
4826
|
-
this.validatePath(path);
|
|
4827
|
-
return await this.manipulator.delete(path);
|
|
4828
|
-
}
|
|
4829
|
-
async moveNote(from, to) {
|
|
4830
|
-
this.validatePath(from);
|
|
4831
|
-
this.validatePath(to);
|
|
4832
|
-
const content = await this.readNote(from);
|
|
4833
|
-
if (content === null) return false;
|
|
4834
|
-
const wrote = await this.writeNote(to, content);
|
|
4835
|
-
if (!wrote) return false;
|
|
4836
|
-
return await this.deleteNote(from);
|
|
4837
|
-
}
|
|
4838
|
-
async getMetadata(path) {
|
|
4839
|
-
this.validatePath(path);
|
|
4840
|
-
const entry = await this.manipulator.get(path);
|
|
4841
|
-
if (!entry) return null;
|
|
4842
|
-
const content = "data" in entry && Array.isArray(entry.data) ? entry.data.join("") : "";
|
|
4843
|
-
return {
|
|
4844
|
-
path,
|
|
4845
|
-
size: entry.size,
|
|
4846
|
-
ctime: entry.ctime,
|
|
4847
|
-
mtime: entry.mtime,
|
|
4848
|
-
...parseFrontmatterAndLinks(content)
|
|
4849
|
-
};
|
|
4850
|
-
}
|
|
4851
|
-
async listNotes(folder) {
|
|
4852
|
-
const paths = [];
|
|
4853
|
-
for await (const doc of this.manipulator.enumerateAllNormalDocs({ metaOnly: true })) {
|
|
4854
|
-
const entry = doc;
|
|
4855
|
-
if (entry.deleted) continue;
|
|
4856
|
-
const notePath = entry.path ?? "";
|
|
4857
|
-
if (!notePath.endsWith(".md")) continue;
|
|
4858
|
-
if (folder) {
|
|
4859
|
-
if (!notePath.startsWith(folder)) continue;
|
|
4860
|
-
}
|
|
4861
|
-
paths.push(notePath);
|
|
4862
|
-
}
|
|
4863
|
-
return paths.sort();
|
|
4864
|
-
}
|
|
4865
|
-
};
|
|
4866
|
-
export {
|
|
4867
|
-
Vault
|
|
4868
|
-
};
|
|
4869
|
-
//# sourceMappingURL=vault-J2V2D3HA.js.map
|