obsidian-sync-mcp 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../lib/livesync-commonlib/src/common/types.ts","../lib/livesync-commonlib/src/common/models/db.const.ts","../lib/livesync-commonlib/src/common/models/shared.const.symbols.ts","../lib/livesync-commonlib/src/common/models/shared.const.behabiour.ts","../lib/livesync-commonlib/src/common/models/setting.const.ts","../lib/livesync-commonlib/src/common/models/setting.p2p.ts","../lib/livesync-commonlib/src/common/models/setting.const.preferred.ts","../lib/livesync-commonlib/src/common/models/setting.const.defaults.ts","../lib/livesync-commonlib/src/common/models/setting.lifecycle.ts","../lib/livesync-commonlib/src/common/models/db.definition.ts","../lib/livesync-commonlib/src/common/models/shared.const.ts","../lib/livesync-commonlib/src/common/models/sync.definition.ts","../lib/livesync-commonlib/src/common/models/tweak.definition.ts","../lib/livesync-commonlib/src/common/models/redflag.const.ts","../lib/livesync-commonlib/src/common/models/shared.definition.ts","../lib/livesync-commonlib/src/common/logger.ts","../lib/livesync-commonlib/src/common/coreEnvFunctions.ts","../lib/livesync-commonlib/src/string_and_binary/convert.ts","../lib/livesync-commonlib/src/pouchdb/utils_couchdb.ts","../lib/livesync-commonlib/src/mods.ts","../lib/livesync-commonlib/src/string_and_binary/hash.ts","../lib/livesync-commonlib/src/common/idDerivation.ts","../lib/livesync-commonlib/src/pouchdb/remoteFeatureCompatibility.ts","../lib/livesync-commonlib/src/pouchdb/negotiation.ts","../lib/livesync-commonlib/src/common/models/fileaccess.const.ts","../lib/livesync-commonlib/src/pouchdb/remoteIdCompatibility.ts","../lib/livesync-commonlib/src/pouchdb/pouchdb-http.ts","../lib/livesync-commonlib/src/managers/ChunkFetcher.ts","../lib/livesync-commonlib/src/managers/ChunkDeliveryCoordinator.ts","../lib/livesync-commonlib/src/mock_and_interop/stores.ts","../lib/livesync-commonlib/src/managers/chunkFetcher.helper.ts","../lib/livesync-commonlib/src/pouchdb/LiveSyncLocalDB.ts","../lib/livesync-commonlib/src/common/utils.ts","../lib/livesync-commonlib/src/string_and_binary/path.ts","../lib/livesync-commonlib/src/common/LSError.ts","../lib/livesync-commonlib/src/common/utils.object.ts","../lib/livesync-commonlib/src/common/utils.patch.ts","../lib/livesync-commonlib/src/ContentSplitter/ContentSplitter.ts","../lib/livesync-commonlib/src/ContentSplitter/ContentSplitterBase.ts","../lib/livesync-commonlib/src/string_and_binary/chunks.ts","../lib/livesync-commonlib/src/worker/bgWorker.direct.ts","../lib/livesync-commonlib/src/ContentSplitter/ContentSplitterRabinKarp.ts","../lib/livesync-commonlib/src/ContentSplitter/ContentSplitterV1.ts","../lib/livesync-commonlib/src/ContentSplitter/ContentSplitterV2.ts","../lib/livesync-commonlib/src/ContentSplitter/ContentSplitters.ts","../lib/livesync-commonlib/src/managers/ChangeManager.ts","../lib/livesync-commonlib/src/managers/LayeredChunkManager.ts","../lib/livesync-commonlib/src/managers/LayeredChunkManager/DatabaseReadLayer.ts","../lib/livesync-commonlib/src/managers/LayeredChunkManager/CacheLayer.ts","../lib/livesync-commonlib/src/managers/LayeredChunkManager/ArrivalWaitLayer.ts","../lib/livesync-commonlib/src/managers/LayeredChunkManager/DatabaseWriteLayer.ts","../lib/livesync-commonlib/src/managers/ConflictManager.ts","../lib/livesync-commonlib/src/managers/EntryManager/EntryManagerImpls.ts","../lib/livesync-commonlib/src/managers/EntryManager/EntryManager.ts","../lib/livesync-commonlib/src/managers/HashManager/HashManagerCore.ts","../lib/livesync-commonlib/src/managers/HashManager/XXHashHashManager.ts","../lib/livesync-commonlib/src/managers/HashManager/PureJSHashManager.ts","../lib/livesync-commonlib/src/managers/HashManager/HashManager.ts","../lib/livesync-commonlib/src/services/lib/logUtils.ts","../lib/livesync-commonlib/src/managers/LiveSyncManagers.ts","../lib/livesync-commonlib/src/pouchdb/compress.ts","../lib/livesync-commonlib/src/pouchdb/encryption.ts","../lib/livesync-commonlib/src/API/DirectFileManipulatorV2.ts","../lib/livesync-commonlib/src/replication/SyncParamsHandler.ts","../lib/livesync-commonlib/src/events/coreEvents.ts","../lib/livesync-commonlib/src/services/lib/HandlerUtils.ts","../lib/livesync-commonlib/src/hub/hub.ts","../lib/livesync-commonlib/src/services/base/CommonlibMessages.ts","../lib/livesync-commonlib/src/services/base/MessageTranslator.ts","../lib/livesync-commonlib/src/services/base/ServiceBase.ts","../lib/livesync-commonlib/src/services/base/AppLifecycleService.ts","../lib/livesync-commonlib/src/services/implements/injectable/InjectableAppLifecycleService.ts","../lib/livesync-commonlib/src/services/base/ConflictService.ts","../lib/livesync-commonlib/src/services/implements/injectable/InjectableConflictService.ts","../lib/livesync-commonlib/src/services/base/DatabaseEventService.ts","../lib/livesync-commonlib/src/services/implements/injectable/InjectableDatabaseEventService.ts","../lib/livesync-commonlib/src/services/base/FileProcessingService.ts","../lib/livesync-commonlib/src/services/implements/injectable/InjectableFileProcessingService.ts","../lib/livesync-commonlib/src/common/typeUtils.ts","../lib/livesync-commonlib/src/services/base/PathService.ts","../lib/livesync-commonlib/src/services/implements/injectable/InjectablePathService.ts","../lib/livesync-commonlib/src/replication/httplib.ts","../lib/livesync-commonlib/src/services/base/UnresolvedErrorManager.ts","../lib/livesync-commonlib/src/services/lib/remoteActivity.ts","../lib/livesync-commonlib/src/services/base/RemoteService.ts","../lib/livesync-commonlib/src/services/implements/injectable/InjectableRemoteService.ts","../lib/livesync-commonlib/src/services/base/ReplicationService.ts","../lib/livesync-commonlib/src/replication/ProviderCapability.ts","../lib/livesync-commonlib/src/replication/ReplicatorProvider.ts","../lib/livesync-commonlib/src/services/base/ReadinessEvaluator.ts","../lib/livesync-commonlib/src/services/base/ReplicationService.readiness.ts","../lib/livesync-commonlib/src/services/base/ReplicationService.typedReplication.ts","../lib/livesync-commonlib/src/services/implements/injectable/InjectableReplicationService.ts","../lib/livesync-commonlib/src/services/base/ReplicatorService.ts","../lib/livesync-commonlib/src/interfaces/AsyncActivityRunner.ts","../lib/livesync-commonlib/src/services/base/ReplicatorService.activeReplicatorState.ts","../lib/livesync-commonlib/src/services/base/ReplicatorService.remoteResourceResolver.ts","../lib/livesync-commonlib/src/replication/CentralRemoteAdministration.ts","../lib/livesync-commonlib/src/services/base/ReplicatorService.centralRemoteAdministration.ts","../lib/livesync-commonlib/src/services/implements/injectable/InjectableReplicatorService.ts","../lib/livesync-commonlib/src/services/base/TestService.ts","../lib/livesync-commonlib/src/services/implements/injectable/InjectableTestService.ts","../lib/livesync-commonlib/src/services/base/TweakValueService.ts","../lib/livesync-commonlib/src/services/implements/injectable/InjectableTweakValueService.ts","../lib/livesync-commonlib/src/services/base/VaultService.ts","../lib/livesync-commonlib/src/services/implements/injectable/InjectableVaultService.ts","../lib/livesync-commonlib/src/services/base/ConfigService.ts","../lib/livesync-commonlib/src/services/implements/browser/ConfigServiceBrowserCompat.ts","../lib/livesync-commonlib/src/services/base/ControlService.ts","../lib/livesync-commonlib/src/services/ServiceHub.ts","../lib/livesync-commonlib/src/services/implements/injectable/InjectableServiceHub.ts","../lib/livesync-commonlib/src/services/implements/base/UIService.ts","../lib/livesync-commonlib/src/services/base/APIService.ts","../lib/livesync-commonlib/src/services/implements/injectable/InjectableAPIService.ts","../lib/livesync-commonlib/src/services/implements/headless/HeadlessAPIService.ts","../lib/livesync-commonlib/src/services/base/KeyValueDBService.ts","../lib/livesync-commonlib/src/services/base/DatabaseService.ts","../lib/livesync-commonlib/src/services/implements/headless/HeadlessDatabaseService.ts","../lib/livesync-commonlib/src/encryption/stringEncryption.ts","../lib/livesync-commonlib/src/services/base/SettingService.ts","../lib/livesync-commonlib/src/common/ConnectionString.ts","../lib/livesync-commonlib/src/serviceFeatures/remoteConfig.ts","../lib/livesync-commonlib/src/services/implements/injectable/InjectableSettingService.ts","../node_modules/idb/build/index.js","../lib/livesync-commonlib/src/databases/IndexedDBKeyValueDatabase.ts","../lib/livesync-commonlib/src/services/HeadlessServices.ts","../src/vault.ts","../src/id-derivation-config.ts","../src/id-format.ts","../src/couchdb-preflight.ts"],"sourcesContent":["// Now migrating everything here to models, only re-exporting from this file\n\nexport type { TaggedType } from \"./models/shared.type.util.ts\";\n\nexport {\n LOG_LEVEL_DEBUG,\n LOG_LEVEL_INFO,\n LOG_LEVEL_NOTICE,\n LOG_LEVEL_URGENT,\n LOG_LEVEL_VERBOSE,\n} from \"octagonal-wheels/common/logger\";\nexport type { LOG_LEVEL } from \"octagonal-wheels/common/logger\";\nimport { RESULT_NOT_FOUND, RESULT_TIMED_OUT } from \"octagonal-wheels/common/const\";\nimport type { Credential } from \"./models/auth.type.ts\";\nimport type {\n AnyEntry,\n ChunkVersionRange,\n DatabaseEntry,\n EdenChunk,\n EntryBase,\n EntryChunkPack,\n EntryHasPath,\n EntryLeaf,\n EntryType,\n EntryTypeNotes,\n EntryTypeNotesWithLegacy,\n EntryVersionInfo,\n EntryWithEden,\n InternalFileEntry,\n LoadedEntry,\n MetaEntry,\n NewEntry,\n NoteEntry,\n PlainEntry,\n SavingEntry,\n SyncInfo,\n} from \"./models/db.type.ts\";\nimport {\n ChunkTypes,\n EntryTypes,\n MILESTONE_DOCID,\n NODEINFO_DOCID,\n NoteTypes,\n SYNCINFO_ID,\n VERSIONING_DOCID,\n} from \"./models/db.const.ts\";\nimport {\n AUTO_MERGED,\n CANCELLED,\n LEAVE_TO_SUBSEQUENT,\n MISSING_OR_ERROR,\n NOT_CONFLICTED,\n TIME_ARGUMENT_INFINITY,\n} from \"./models/shared.const.symbols.ts\";\nimport {\n IDPrefixes,\n LEAF_WAIT_ONLY_REMOTE,\n LEAF_WAIT_TIMEOUT,\n LEAF_WAIT_TIMEOUT_SEQUENTIAL_REPLICATOR,\n MAX_DOC_SIZE,\n MAX_DOC_SIZE_BIN,\n PREFIX_CHUNK,\n PREFIX_ENCRYPTED_CHUNK,\n PREFIX_OBFUSCATED,\n RECENT_MODIFIED_DOCS_QTY,\n REPLICATION_BUSY_TIMEOUT,\n SALT_OF_ID,\n SALT_OF_PASSPHRASE,\n SEED_MURMURHASH,\n VER,\n} from \"./models/shared.const.behabiour.ts\";\nimport {\n AutoAccepting,\n type BucketSyncSetting,\n type ChunkSplitterVersion,\n type ConfigPassphraseStore,\n type CouchDBConnection,\n type E2EEAlgorithm,\n type EncryptionSettings,\n type HashAlgorithm,\n type HasSettings,\n type LocalDBSettings,\n type ObsidianLiveSyncSettings,\n type P2PConnectionInfo,\n type P2PSyncSetting,\n type PluginSyncSettingEntry,\n type RemoteDBSettings,\n type RemoteType,\n type RemoteTypeSettings,\n type SYNC_MODE,\n} from \"./models/setting.type.ts\";\nimport {\n ChunkAlgorithmNames,\n ChunkAlgorithms,\n CURRENT_SETTING_VERSION,\n E2EEAlgorithmNames,\n E2EEAlgorithms,\n HashAlgorithms,\n REMOTE_COUCHDB,\n REMOTE_MINIO,\n REMOTE_P2P,\n RemoteTypes,\n SETTING_VERSION_INITIAL,\n SETTING_VERSION_SUPPORT_CASE_INSENSITIVE,\n MODE_AUTOMATIC,\n MODE_PAUSED,\n MODE_SELECTIVE,\n MODE_SHINY,\n P2PConnectionPaths,\n P2PMessageSizePresets,\n type P2PConnectionPath,\n} from \"./models/setting.const.ts\";\nimport {\n hasManagedP2PTurnConfiguration,\n hasP2PTurnConfiguration,\n hasValidP2PTurnServerUrl,\n omitP2PRuntimeSettings,\n isValidP2PTurnServerUrl,\n normaliseP2PConnectionPath,\n normaliseP2PMaxWirePayloadBytes,\n splitP2PTurnServerUrls,\n} from \"./models/setting.p2p.ts\";\nimport {\n PREFERRED_BASE,\n PREFERRED_JOURNAL_SYNC,\n PREFERRED_SETTING_CLOUDANT,\n PREFERRED_SETTING_SELF_HOSTED,\n} from \"./models/setting.const.preferred.ts\";\nimport {\n P2P_DEFAULT_SETTINGS,\n DEFAULT_SETTINGS,\n NEW_VAULT_SETTINGS,\n SETTINGS_SCHEMA_DEFAULTS,\n createNewVaultSettings,\n} from \"./models/setting.const.defaults.ts\";\nimport {\n prepareSettingsForLoad,\n SettingsMigrationReviewCodes,\n type PreparedSettings,\n type SettingsMigrationReviewCode,\n type SettingsMigrationReviewReason,\n type SettingsMigrationState,\n} from \"./models/setting.lifecycle.ts\";\nimport { KeyIndexOfSettings } from \"./models/setting.const.qr.ts\";\nimport type {\n DeviceInfo,\n EntryBody,\n EntryDoc,\n EntryDocResponse,\n EntryMilestoneInfo,\n EntryNodeInfo,\n NodeData,\n NodeKey,\n} from \"./models/db.definition.ts\";\nimport { isMetaEntry } from \"./models/db.definition.ts\";\nimport type {\n CouchDBCredentials,\n BasicCredentials,\n JWTCredentials,\n JWTHeader,\n JWTPayload,\n JWTParams,\n PreparedJWT,\n} from \"./models/auth.type.ts\";\nimport type {\n CacheData,\n FileEventArgs,\n FileEventItem,\n FileEventType,\n UXAbstractInfoStub,\n UXDataWriteOptions,\n UXFileInfo,\n UXFileInfoStub,\n UXFolderInfo,\n UXInternalFileInfoStub,\n UXStat,\n} from \"./models/fileaccess.type.ts\";\nimport {\n SETTING_KEY_P2P_DEVICE_NAME,\n configURIBase,\n configURIBaseQR,\n SuffixDatabaseName,\n ExtraSuffixIndexedDB,\n} from \"./models/shared.const.ts\";\nimport {\n configurationNames,\n LEVEL_ADVANCED,\n LEVEL_POWER_USER,\n LEVEL_EDGE_CASE,\n type ConfigLevel,\n type ConfigurationItem,\n statusDisplay,\n confName,\n confDesc,\n} from \"./models/shared.definition.configNames.ts\";\nimport type {\n CustomRegExpSource,\n CustomRegExpSourceList,\n ParsedCustomRegExp,\n Prettify,\n} from \"./models/shared.type.util.ts\";\nimport {\n ProtocolVersions,\n type ProtocolVersion,\n DOCID_SYNC_PARAMETERS,\n DOCID_JOURNAL_SYNC_PARAMETERS,\n type SyncParameters,\n DEFAULT_SYNC_PARAMETERS,\n} from \"./models/sync.definition.ts\";\nimport {\n TweakValuesShouldMatchedTemplate,\n IncompatibleChanges,\n CompatibleButLossyChanges,\n IncompatibleChangesInSpecificPattern,\n TweakValuesRecommendedTemplate,\n TweakValuesDefault,\n TweakValuesTemplate,\n type TweakValues,\n DEVICE_ID_PREFERRED,\n RemotePreferredTweakStatuses,\n type RemotePreferredTweakStatus,\n RemotePreferredTweakNotConfiguredReasons,\n type RemotePreferredTweakNotConfiguredReason,\n type RemotePreferredTweakResult,\n} from \"./models/tweak.definition.ts\";\nimport type {\n TweakAssessment,\n TweakAssessmentEntry,\n TweakAssessmentRelation,\n TweakAssessmentValue,\n TweakTransition,\n TweakTransitionReason,\n} from \"./models/tweak.compatibility.ts\";\nimport type { TweakReconstruction } from \"./models/tweak.definition.ts\";\nimport type {\n diff_result_leaf,\n dmp_result,\n diff_result,\n DIFF_CHECK_RESULT_AUTO,\n diff_check_result,\n} from \"./models/diff.definition.ts\";\nimport {\n PREFIXMD_LOGFILE,\n PREFIXMD_LOGFILE_UC,\n FlagFilesOriginal,\n FlagFilesHumanReadable,\n FLAGMD_REDFLAG,\n FLAGMD_REDFLAG2,\n FLAGMD_REDFLAG2_HR,\n FLAGMD_REDFLAG3,\n FLAGMD_REDFLAG3_HR,\n} from \"./models/redflag.const.ts\";\nimport { DatabaseConnectingStatuses, type DatabaseConnectingStatus } from \"./models/shared.definition.ts\";\n\nexport { RESULT_NOT_FOUND, RESULT_TIMED_OUT };\n\nexport type { FilePath, FilePathWithPrefixLC, FilePathWithPrefix, DocumentID } from \"./models/db.type.ts\";\n\nexport {\n MAX_DOC_SIZE,\n MAX_DOC_SIZE_BIN,\n VER,\n RECENT_MODIFIED_DOCS_QTY,\n LEAF_WAIT_TIMEOUT,\n LEAF_WAIT_ONLY_REMOTE,\n LEAF_WAIT_TIMEOUT_SEQUENTIAL_REPLICATOR,\n REPLICATION_BUSY_TIMEOUT,\n CANCELLED,\n AUTO_MERGED,\n NOT_CONFLICTED,\n MISSING_OR_ERROR,\n LEAVE_TO_SUBSEQUENT,\n TIME_ARGUMENT_INFINITY,\n VERSIONING_DOCID,\n MILESTONE_DOCID,\n NODEINFO_DOCID,\n};\n\nexport { type CouchDBConnection };\n\nexport type { ConfigPassphraseStore };\n\nexport { MODE_SELECTIVE, MODE_AUTOMATIC, MODE_PAUSED, MODE_SHINY, type SYNC_MODE };\n\nexport { type PluginSyncSettingEntry };\n\nexport { SETTING_VERSION_INITIAL, SETTING_VERSION_SUPPORT_CASE_INSENSITIVE, CURRENT_SETTING_VERSION };\nexport type { BucketSyncSetting, LocalDBSettings };\n\nexport {\n RemoteTypes,\n REMOTE_COUCHDB,\n REMOTE_MINIO,\n REMOTE_P2P,\n P2PConnectionPaths,\n P2PMessageSizePresets,\n type RemoteType,\n AutoAccepting,\n};\nexport type { P2PConnectionInfo, P2PConnectionPath, P2PSyncSetting };\nexport {\n hasManagedP2PTurnConfiguration,\n hasP2PTurnConfiguration,\n hasValidP2PTurnServerUrl,\n omitP2PRuntimeSettings,\n isValidP2PTurnServerUrl,\n normaliseP2PConnectionPath,\n normaliseP2PMaxWirePayloadBytes,\n splitP2PTurnServerUrls,\n};\n\nexport { P2P_DEFAULT_SETTINGS };\n\nexport type { RemoteTypeSettings };\nexport { E2EEAlgorithmNames, E2EEAlgorithms, type E2EEAlgorithm };\nexport type { EncryptionSettings };\n\nexport { HashAlgorithms, type HashAlgorithm, ChunkAlgorithmNames, ChunkAlgorithms, type ChunkSplitterVersion };\n\nexport type { RemoteDBSettings };\nexport type { ObsidianLiveSyncSettings };\n\nexport { DEFAULT_SETTINGS, NEW_VAULT_SETTINGS, SETTINGS_SCHEMA_DEFAULTS, createNewVaultSettings };\nexport {\n prepareSettingsForLoad,\n SettingsMigrationReviewCodes,\n type PreparedSettings,\n type SettingsMigrationReviewCode,\n type SettingsMigrationReviewReason,\n type SettingsMigrationState,\n};\nexport { KeyIndexOfSettings };\n\nexport { type HasSettings };\n\nexport { PREFERRED_BASE, PREFERRED_SETTING_CLOUDANT, PREFERRED_SETTING_SELF_HOSTED, PREFERRED_JOURNAL_SYNC };\n\nexport {\n EntryTypes,\n NoteTypes,\n ChunkTypes,\n type EntryType,\n type EntryTypeNotes,\n type EntryTypeNotesWithLegacy,\n type DatabaseEntry,\n type EntryBase,\n type EdenChunk,\n type EntryWithEden,\n type NoteEntry,\n type NewEntry,\n type PlainEntry,\n type InternalFileEntry,\n type AnyEntry,\n type LoadedEntry,\n type SavingEntry,\n type MetaEntry,\n isMetaEntry,\n type EntryLeaf,\n type EntryChunkPack,\n type EntryVersionInfo,\n type EntryHasPath,\n};\n\nexport type { ChunkVersionRange };\n\nexport { TweakValuesShouldMatchedTemplate };\n\nexport { IncompatibleChanges };\n\nexport { CompatibleButLossyChanges };\n\nexport { IncompatibleChangesInSpecificPattern };\n\nexport { TweakValuesRecommendedTemplate };\nexport { TweakValuesDefault };\n\nexport { configurationNames };\n\nexport { LEVEL_ADVANCED };\nexport { LEVEL_POWER_USER };\nexport { LEVEL_EDGE_CASE };\nexport type { ConfigLevel };\nexport type { ConfigurationItem };\n\nexport { statusDisplay };\n\nexport { confName };\nexport { confDesc };\n\nexport { TweakValuesTemplate };\nexport type { TweakValues };\nexport type {\n TweakAssessment,\n TweakAssessmentEntry,\n TweakAssessmentRelation,\n TweakAssessmentValue,\n TweakReconstruction,\n TweakTransition,\n TweakTransitionReason,\n};\nexport { DEVICE_ID_PREFERRED };\nexport { RemotePreferredTweakStatuses };\nexport type { RemotePreferredTweakStatus };\nexport { RemotePreferredTweakNotConfiguredReasons };\nexport type { RemotePreferredTweakNotConfiguredReason };\nexport type { RemotePreferredTweakResult };\n\nexport type { NodeKey };\nexport type { DeviceInfo };\n\nexport type { NodeData };\nexport type { EntryMilestoneInfo };\n\nexport type { EntryNodeInfo };\n\nexport type { EntryBody };\n\nexport type { EntryDoc };\n\nexport type { diff_result_leaf };\nexport type { dmp_result };\n\nexport type { diff_result };\n\nexport type { DIFF_CHECK_RESULT_AUTO };\nexport type { diff_check_result };\nexport type { Credential };\n\nexport type { EntryDocResponse };\n\nexport { DatabaseConnectingStatuses };\nexport type { DatabaseConnectingStatus };\n\nexport {\n PREFIXMD_LOGFILE,\n PREFIXMD_LOGFILE_UC,\n FlagFilesOriginal,\n FlagFilesHumanReadable,\n FLAGMD_REDFLAG,\n FLAGMD_REDFLAG2,\n FLAGMD_REDFLAG2_HR,\n FLAGMD_REDFLAG3,\n FLAGMD_REDFLAG3_HR,\n};\n\nexport { SYNCINFO_ID };\nexport type { SyncInfo };\n\nexport {\n SALT_OF_PASSPHRASE,\n SALT_OF_ID,\n SEED_MURMURHASH,\n IDPrefixes,\n PREFIX_OBFUSCATED,\n PREFIX_CHUNK,\n PREFIX_ENCRYPTED_CHUNK,\n};\n\nexport type {\n UXStat,\n UXFileInfo,\n UXAbstractInfoStub,\n UXFileInfoStub,\n UXInternalFileInfoStub,\n UXFolderInfo,\n UXDataWriteOptions,\n CacheData,\n FileEventType,\n FileEventArgs,\n FileEventItem,\n};\n\nexport type { Prettify };\nexport type { CouchDBCredentials };\nexport type { BasicCredentials };\n\nexport type { JWTCredentials };\n\nexport type { JWTHeader };\nexport type { JWTPayload };\nexport type { JWTParams };\nexport type { PreparedJWT };\nexport type { CustomRegExpSource };\n\nexport type { CustomRegExpSourceList };\nexport type { ParsedCustomRegExp };\n\nexport { ProtocolVersions };\n\nexport type { ProtocolVersion };\nexport { DOCID_SYNC_PARAMETERS };\nexport { DOCID_JOURNAL_SYNC_PARAMETERS };\nexport type { SyncParameters };\nexport { DEFAULT_SYNC_PARAMETERS };\n\nexport {\n SETTING_KEY_P2P_DEVICE_NAME,\n configURIBase,\n configURIBaseQR,\n SuffixDatabaseName,\n ExtraSuffixIndexedDB,\n};\n","import type { DocumentID } from \"./db.type\";\n\nexport const VERSIONING_DOCID = \"obsydian_livesync_version\" as DocumentID;\nexport const MILESTONE_DOCID = \"_local/obsydian_livesync_milestone\" as DocumentID;\nexport const NODEINFO_DOCID = \"_local/obsydian_livesync_nodeinfo\" as DocumentID;\n\nexport const SYNCINFO_ID = \"syncinfo\" as DocumentID;\n\nexport const EntryTypes = {\n NOTE_LEGACY: \"notes\",\n NOTE_BINARY: \"newnote\",\n NOTE_PLAIN: \"plain\",\n INTERNAL_FILE: \"internalfile\",\n CHUNK: \"leaf\",\n CHUNK_PACK: \"chunkpack\",\n VERSION_INFO: \"versioninfo\",\n SYNC_INFO: \"syncinfo\",\n SYNC_PARAMETERS: \"sync-parameters\",\n MILESTONE_INFO: \"milestoneinfo\",\n NODE_INFO: \"nodeinfo\",\n} as const;\n\nexport const NoteTypes = [EntryTypes.NOTE_LEGACY, EntryTypes.NOTE_BINARY, EntryTypes.NOTE_PLAIN];\nexport const ChunkTypes = [EntryTypes.CHUNK, EntryTypes.CHUNK_PACK];\n","// Magic Special value for arguments or results.\n\nexport const CANCELLED = Symbol(\"cancelled\");\nexport const AUTO_MERGED = Symbol(\"auto_merged\");\nexport const NOT_CONFLICTED = Symbol(\"not_conflicted\");\nexport const MISSING_OR_ERROR = Symbol(\"missing_or_error\");\nexport const LEAVE_TO_SUBSEQUENT = Symbol(\"leave_to_subsequent_proc\");\nexport const TIME_ARGUMENT_INFINITY = Symbol(\"infinity\");\n\n// File status comparison result\nexport const BASE_IS_NEW = Symbol(\"base\");\nexport const TARGET_IS_NEW = Symbol(\"target\");\nexport const EVEN = Symbol(\"even\");\n","// docs should be encoded as base64, so 1 char -> 1 bytes\n// and cloudant limitation is 1MB , we use 900kb;\n\nexport const MAX_DOC_SIZE = 1000; // for .md file, but if delimiters exists. use that before.\nexport const MAX_DOC_SIZE_BIN = 102400; // 100kb\nexport const VER = 12; // 12 Since 0.25.0, HKDF is used for encryption, so the version is changed to 12.\n\nexport const RECENT_MODIFIED_DOCS_QTY = 30;\n// Deprecated arrival-delay values retained for source compatibility. Chunk reads now follow explicit delivery lifecycles.\nexport const LEAF_WAIT_TIMEOUT = 30000;\nexport const LEAF_WAIT_ONLY_REMOTE = 5000;\nexport const LEAF_WAIT_TIMEOUT_SEQUENTIAL_REPLICATOR = 5000;\nexport const REPLICATION_BUSY_TIMEOUT = 3000000;\n\nexport const SALT_OF_PASSPHRASE = \"rHGMPtr6oWw7VSa3W3wpa8fT8U\";\nexport const SALT_OF_ID = \"a83hrf7f\\u0003y7sa8g31\";\nexport const SEED_MURMURHASH = 0x12345678;\n\nexport const IDPrefixes = {\n Obfuscated: \"f:\",\n Chunk: \"h:\",\n EncryptedChunk: \"h:+\",\n};\n/**\n * @deprecated Use `IDPrefixes.Obfuscated` instead.\n */\nexport const PREFIX_OBFUSCATED = \"f:\";\n/**\n * @deprecated Use `IDPrefixes.Chunk` instead.\n */\nexport const PREFIX_CHUNK = \"h:\";\n/**\n * @deprecated Use `IDPrefixes.EncryptedChunk` instead.\n */\nexport const PREFIX_ENCRYPTED_CHUNK = \"h:+\";\n","export const SETTING_VERSION_INITIAL = 0;\nexport const SETTING_VERSION_SUPPORT_CASE_INSENSITIVE = 10;\nexport const CURRENT_SETTING_VERSION = SETTING_VERSION_SUPPORT_CASE_INSENSITIVE;\n\n// Remote Type\nexport const RemoteTypes = {\n REMOTE_COUCHDB: \"\",\n REMOTE_MINIO: \"MINIO\",\n REMOTE_P2P: \"ONLY_P2P\",\n} as const;\nexport const REMOTE_COUCHDB = RemoteTypes.REMOTE_COUCHDB;\nexport const REMOTE_MINIO = RemoteTypes.REMOTE_MINIO;\n//\nexport const REMOTE_P2P = RemoteTypes.REMOTE_P2P;\n\n/** ICE route policies supported by a P2P connection profile. */\nexport const P2PConnectionPaths = {\n Automatic: \"automatic\",\n Relay: \"relay\",\n} as const;\nexport type P2PConnectionPath = (typeof P2PConnectionPaths)[keyof typeof P2PConnectionPaths];\n\n/**\n * User-facing message-size presets for the P2P RPC transport.\n *\n * These values limit Commonlib wire payloads before Trystero applies its own\n * framing. They are not file Chunk sizes or network MTUs.\n */\nexport const P2PMessageSizePresets = {\n Standard: 15_360,\n Reduced: 2_048,\n Conservative: 1_024,\n MaximumCompatibility: 800,\n} as const;\n\nexport const E2EEAlgorithmNames = {\n \"\": \"V1: Legacy\",\n v2: \"V2: AES-256-GCM With HKDF\",\n forceV1: \"Force-V1: Force Legacy (Not recommended)\",\n} as const;\nexport const E2EEAlgorithms = {\n V1: \"\",\n V2: \"v2\",\n ForceV1: \"forceV1\",\n} as const;\n\nexport const HashAlgorithms = {\n XXHASH32: \"xxhash32\",\n XXHASH64: \"xxhash64\",\n MIXED_PUREJS: \"mixed-purejs\",\n SHA1: \"sha1\",\n LEGACY: \"\",\n} as const;\n\n// Note: xxhash32 is obsolete and not preferred since v0.24.7.\n// export type HashAlgorithm = \"\" | \"xxhash32\" | \"xxhash64\" | \"mixed-purejs\" | \"sha1\";\nexport const ChunkAlgorithmNames = {\n v1: \"V1: Legacy\",\n v2: \"V2: Simple (Default)\",\n \"v2-segmenter\": \"V2.5: Lexical chunks\",\n \"v3-rabin-karp\": \"V3: Fine deduplication\",\n} as const;\nexport const ChunkAlgorithms = {\n V1: \"v1\",\n V2: \"v2\",\n V2Segmenter: \"v2-segmenter\",\n RabinKarp: \"v3-rabin-karp\",\n} as const;\n\n// Plugin Sync Settings\n\nexport const MODE_SELECTIVE = 0;\nexport const MODE_AUTOMATIC = 1;\nexport const MODE_PAUSED = 2;\nexport const MODE_SHINY = 3;\n\n// Network constants for banner setting\nexport const NetworkWarningStyles = {\n BANNER: \"\",\n ICON: \"icon\",\n HIDDEN: \"hidden\",\n} as const;\n","import { P2PConnectionPaths, P2PMessageSizePresets, type P2PConnectionPath } from \"./setting.const\";\nimport type { P2PConnectionInfo, P2PSyncSetting } from \"./setting.type\";\n\n/** Report whether the selected P2P settings request host-managed TURN credentials. */\nexport function hasManagedP2PTurnConfiguration(\n settings: Partial<Pick<P2PConnectionInfo, \"P2P_managedType\">>\n): boolean {\n return typeof settings.P2P_managedType === \"string\" && settings.P2P_managedType.trim().length > 0;\n}\n\n/** Remove connection-only ICE credentials before settings cross a serialisation boundary. */\nexport function omitP2PRuntimeSettings<T extends Partial<P2PSyncSetting>>(\n settings: T\n): Omit<T, \"P2P_iceServers\" | \"P2P_iceServersExpiresAt\"> {\n const { P2P_iceServers: _iceServers, P2P_iceServersExpiresAt: _expiresAt, ...persistable } = settings;\n return persistable;\n}\n\n/**\n * Report whether a P2P profile has a usable manual TURN endpoint or requests\n * host-managed TURN credentials. STUN-only profiles remain false.\n */\nexport function hasP2PTurnConfiguration(\n settings: Partial<Pick<P2PConnectionInfo, \"P2P_turnServers\" | \"P2P_managedType\">>\n): boolean {\n return (\n hasManagedP2PTurnConfiguration(settings) ||\n (typeof settings.P2P_turnServers === \"string\" && hasValidP2PTurnServerUrl(settings.P2P_turnServers))\n );\n}\n\n/**\n * Return a safe outgoing RPC wire-payload bound for Trystero.\n *\n * Existing profiles can omit this value. Invalid, excessively small, and\n * excessively large values retain the established 15,360-byte behaviour.\n */\nexport function normaliseP2PMaxWirePayloadBytes(value: unknown): number {\n if (\n typeof value !== \"number\" ||\n !Number.isSafeInteger(value) ||\n value < P2PMessageSizePresets.MaximumCompatibility ||\n value > P2PMessageSizePresets.Standard\n ) {\n return P2PMessageSizePresets.Standard;\n }\n return value;\n}\n\n/** Return a recognised P2P connection path, defaulting legacy values to automatic selection. */\nexport function normaliseP2PConnectionPath(value: unknown): P2PConnectionPath {\n return value === P2PConnectionPaths.Relay ? P2PConnectionPaths.Relay : P2PConnectionPaths.Automatic;\n}\n\n/** Split the stored comma-separated signalling relay list without changing its entries. */\nexport function splitP2PRelayUrls(value: string | undefined): string[] {\n if (!value) return [];\n return value\n .split(\",\")\n .map((entry) => entry.trim())\n .filter((entry) => entry.length > 0);\n}\n\n/** Split the stored comma-separated TURN server list without changing its entries. */\nexport function splitP2PTurnServerUrls(value: string): string[] {\n return value\n .split(\",\")\n .map((entry) => entry.trim())\n .filter((entry) => entry.length > 0);\n}\n\n/**\n * Report whether a value is a minimally valid TURN or TURN-over-TLS URL.\n *\n * Full allocation validation remains the responsibility of WebRTC. This\n * check only prevents relay-only mode when no TURN endpoint can be attempted.\n */\nexport function isValidP2PTurnServerUrl(value: string): boolean {\n const candidate = value.trim();\n if (!candidate || /\\s/.test(candidate)) return false;\n try {\n const parsed = new URL(candidate);\n const protocol = parsed.protocol.toLowerCase();\n if (protocol !== \"turn:\" && protocol !== \"turns:\") return false;\n return (parsed.hostname || parsed.pathname).length > 0;\n } catch {\n return false;\n }\n}\n\n/** Report whether a stored TURN server list contains at least one usable TURN URL. */\nexport function hasValidP2PTurnServerUrl(value: string): boolean {\n return splitP2PTurnServerUrls(value).some(isValidP2PTurnServerUrl);\n}\n","import { E2EEAlgorithms } from \"./setting.const\";\nimport type { ObsidianLiveSyncSettings } from \"./setting.type\";\n\nexport const PREFERRED_BASE: Partial<ObsidianLiveSyncSettings> = {\n syncMaxSizeInMB: 50,\n chunkSplitterVersion: \"v3-rabin-karp\",\n usePluginSyncV2: true,\n handleFilenameCaseSensitive: false,\n E2EEAlgorithm: E2EEAlgorithms.V2,\n};\n\nexport const PREFERRED_SETTING_CLOUDANT: Partial<ObsidianLiveSyncSettings> = {\n ...PREFERRED_BASE,\n customChunkSize: 0,\n sendChunksBulkMaxSize: 1,\n concurrencyOfReadChunksOnline: 100,\n minimumIntervalOfReadChunksOnline: 333,\n};\nexport const PREFERRED_SETTING_SELF_HOSTED: Partial<ObsidianLiveSyncSettings> = {\n ...PREFERRED_BASE,\n customChunkSize: 60,\n sendChunksBulkMaxSize: 1,\n concurrencyOfReadChunksOnline: 30,\n minimumIntervalOfReadChunksOnline: 25,\n};\nexport const PREFERRED_JOURNAL_SYNC: Partial<ObsidianLiveSyncSettings> = {\n ...PREFERRED_BASE,\n customChunkSize: 10,\n concurrencyOfReadChunksOnline: 30,\n minimumIntervalOfReadChunksOnline: 25,\n};\n","import {\n ChunkAlgorithms,\n CURRENT_SETTING_VERSION,\n E2EEAlgorithms,\n P2PConnectionPaths,\n P2PMessageSizePresets,\n REMOTE_COUCHDB,\n} from \"./setting.const\";\nimport { PREFERRED_BASE } from \"./setting.const.preferred\";\nimport { AutoAccepting, type ObsidianLiveSyncSettings, type P2PSyncSetting } from \"./setting.type\";\nimport type { CustomRegExpSourceList } from \"./shared.type.util\";\n\nexport const P2P_DEFAULT_SETTINGS: P2PSyncSetting = {\n P2P_Enabled: false,\n P2P_AutoAccepting: AutoAccepting.NONE,\n P2P_AppID: \"self-hosted-livesync\",\n P2P_roomID: \"\",\n P2P_passphrase: \"\",\n P2P_relays: \"wss://exp-relay.vrtmrz.net/\",\n P2P_AutoBroadcast: false,\n P2P_AutoStart: false,\n P2P_AutoSyncPeers: \"\",\n P2P_AutoWatchPeers: \"\",\n P2P_SyncOnReplication: \"\",\n P2P_RebuildFrom: \"\",\n P2P_AutoAcceptingPeers: \"\",\n P2P_AutoDenyingPeers: \"\",\n P2P_IsHeadless: false,\n P2P_DevicePeerName: \"\",\n P2P_turnServers: \"\",\n P2P_turnUsername: \"\",\n P2P_turnCredential: \"\",\n P2P_maxWirePayloadBytes: P2PMessageSizePresets.Standard,\n P2P_connectionPath: P2PConnectionPaths.Automatic,\n P2P_useDiagRTC: false,\n} as const;\n\n/**\n * Conservative fallback values used to complete stored settings.\n *\n * Keep these values compatible with existing installations. Defaults intended\n * only for a newly created Vault belong in {@link NEW_VAULT_SETTINGS}.\n */\nexport const SETTINGS_SCHEMA_DEFAULTS: ObsidianLiveSyncSettings = {\n remoteType: REMOTE_COUCHDB,\n useCustomRequestHandler: false,\n couchDB_URI: \"\",\n couchDB_USER: \"\",\n couchDB_PASSWORD: \"\",\n couchDB_DBNAME: \"\",\n liveSync: false,\n syncOnSave: false,\n syncOnStart: false,\n savingDelay: 200,\n lessInformationInLog: false,\n gcDelay: 300,\n versionUpFlash: \"\",\n minimumChunkSize: 20,\n longLineThreshold: 250,\n showVerboseLog: false,\n suspendFileWatching: false,\n trashInsteadDelete: true,\n periodicReplication: false,\n periodicReplicationInterval: 60,\n syncOnFileOpen: false,\n encrypt: false,\n passphrase: \"\",\n idDerivationVersion: 0,\n idDerivationKey: \"\",\n usePathObfuscation: false,\n encryptInternalMetadata: false,\n doNotDeleteFolder: false,\n resolveConflictsByNewerFile: false,\n batchSave: false,\n batchSaveMinimumDelay: 5,\n batchSaveMaximumDelay: 60,\n deviceAndVaultName: \"\",\n usePluginSettings: false,\n showOwnPlugins: false,\n showStatusOnEditor: true,\n showStatusOnStatusbar: true,\n showOnlyIconsOnEditor: false,\n hideFileWarningNotice: false,\n networkWarningStyle: \"\",\n usePluginSync: false,\n autoSweepPlugins: false,\n autoSweepPluginsPeriodic: false,\n notifyPluginOrSettingUpdated: false,\n checkIntegrityOnSave: false,\n batch_size: 25,\n batches_limit: 25,\n useHistory: false,\n disableRequestURI: false,\n skipOlderFilesOnSync: true,\n checkConflictOnlyOnOpen: false,\n showMergeDialogOnlyOnActive: false,\n syncInternalFiles: false,\n syncInternalFilesBeforeReplication: false,\n syncInternalFilesIgnorePatterns:\n \"\\\\/node_modules\\\\/, \\\\/\\\\.git\\\\/, \\\\/obsidian-livesync\\\\/\" as CustomRegExpSourceList<\",\">,\n syncInternalFilesTargetPatterns: \"\" as CustomRegExpSourceList<\",\">,\n syncInternalFilesInterval: 60,\n additionalSuffixOfDatabaseName: \"\",\n ignoreVersionCheck: false,\n lastReadUpdates: 0,\n deleteMetadataOfDeletedFiles: false,\n syncIgnoreRegEx: \"\" as CustomRegExpSourceList<\"|[]|\">,\n syncOnlyRegEx: \"\" as CustomRegExpSourceList<\"|[]|\">,\n customChunkSize: 0,\n readChunksOnline: true,\n watchInternalFileChanges: true,\n automaticallyDeleteMetadataOfDeletedFiles: 0,\n disableMarkdownAutoMerge: false,\n writeDocumentsIfConflicted: false,\n useDynamicIterationCount: false,\n syncAfterMerge: false,\n configPassphraseStore: \"\",\n encryptedPassphrase: \"\",\n encryptedIdDerivationKey: \"\",\n encryptedCouchDBConnection: \"\",\n permitEmptyPassphrase: false,\n remoteConfigurations: {},\n activeConfigurationId: \"\",\n P2P_ActiveRemoteConfigurationId: \"\",\n useIndexedDBAdapter: false,\n useTimeouts: false,\n writeLogToTheFile: false,\n doNotPaceReplication: false,\n hashCacheMaxCount: 300,\n hashCacheMaxAmount: 50,\n concurrencyOfReadChunksOnline: 40,\n minimumIntervalOfReadChunksOnline: 50,\n hashAlg: \"xxhash64\",\n suspendParseReplicationResult: false,\n doNotSuspendOnFetching: false,\n useIgnoreFiles: false,\n ignoreFiles: \".gitignore\",\n syncOnEditorSave: false,\n keepReplicationActiveInBackground: false,\n allowSleepDuringSynchronisation: false,\n allowSleepDuringSynchronisationOnDesktop: true,\n pluginSyncExtendedSetting: {},\n syncMaxSizeInMB: 50,\n settingSyncFile: \"\",\n writeCredentialsForSettingSync: false,\n notifyAllSettingSyncFile: false,\n isConfigured: undefined,\n settingVersion: CURRENT_SETTING_VERSION,\n enableCompression: false,\n accessKey: \"\",\n bucket: \"\",\n endpoint: \"\",\n region: \"auto\",\n secretKey: \"\",\n useEden: false,\n maxChunksInEden: 10,\n maxTotalLengthInEden: 1024,\n maxAgeInEden: 10,\n disableCheckingConfigMismatch: false,\n autoAcceptCompatibleTweak: undefined,\n displayLanguage: \"\",\n /**\n * @deprecated\n */\n enableChunkSplitterV2: false,\n disableWorkerForGeneratingChunks: false,\n processSmallFilesInUIThread: false,\n notifyThresholdOfRemoteStorageSize: -1,\n\n usePluginSyncV2: false,\n usePluginEtc: false,\n handleFilenameCaseSensitive: undefined!,\n doNotUseFixedRevisionForChunks: true,\n showLongerLogInsideEditor: false,\n /** @deprecated Retained for settings and Setup URI compatibility. */\n sendChunksBulk: false,\n sendChunksBulkMaxSize: 1,\n /**\n * @deprecated\n * This setting is no longer used and will be removed in the future.\n */\n useSegmenter: false,\n useAdvancedMode: false,\n usePowerUserMode: false,\n useEdgeCaseMode: false,\n enableDebugTools: false,\n suppressNotifyHiddenFilesChange: false,\n syncMinimumInterval: 2000,\n ...P2P_DEFAULT_SETTINGS,\n doctorProcessedVersion: \"\",\n\n bucketCustomHeaders: \"\",\n couchDB_CustomHeaders: \"\",\n useJWT: false,\n jwtAlgorithm: \"\",\n jwtKey: \"\",\n jwtKid: \"\",\n jwtSub: \"\",\n jwtExpDuration: 5,\n useRequestAPI: false,\n bucketPrefix: \"\",\n chunkSplitterVersion: ChunkAlgorithms.RabinKarp,\n E2EEAlgorithm: E2EEAlgorithms.V2,\n processSizeMismatchedFiles: false,\n forcePathStyle: true,\n syncInternalFileOverwritePatterns: \"\" as CustomRegExpSourceList<\",\">,\n useOnlyLocalChunk: false,\n maxMTimeForReflectEvents: 0,\n tweakModified: undefined,\n};\n\n/**\n * Initial values for a Vault which has never stored Self-hosted LiveSync settings.\n *\n * This object is deliberately separate from schema fallbacks so that future\n * releases can improve new-user defaults without changing existing choices.\n */\nexport const NEW_VAULT_SETTINGS: ObsidianLiveSyncSettings = {\n ...SETTINGS_SCHEMA_DEFAULTS,\n ...PREFERRED_BASE,\n encryptInternalMetadata: true,\n remoteConfigurations: {},\n pluginSyncExtendedSetting: {},\n};\n\n/** Create an independently mutable copy of the current new-Vault settings. */\nexport function createNewVaultSettings(): ObsidianLiveSyncSettings {\n return {\n ...NEW_VAULT_SETTINGS,\n remoteConfigurations: {},\n pluginSyncExtendedSetting: {},\n };\n}\n\n/**\n * Compatibility name for the conservative setting-schema fallbacks.\n */\nexport const DEFAULT_SETTINGS = SETTINGS_SCHEMA_DEFAULTS;\n","import { createNewVaultSettings, SETTINGS_SCHEMA_DEFAULTS } from \"./setting.const.defaults\";\nimport {\n CURRENT_SETTING_VERSION,\n SETTING_VERSION_INITIAL,\n SETTING_VERSION_SUPPORT_CASE_INSENSITIVE,\n} from \"./setting.const\";\nimport type { ObsidianLiveSyncSettings } from \"./setting.type\";\nimport { omitP2PRuntimeSettings } from \"./setting.p2p\";\n\nexport const SettingsMigrationReviewCodes = {\n LegacyUpdatePending: \"legacy-update-review-pending\",\n FutureSchema: \"settings-schema-newer-than-runtime\",\n /** @deprecated Missing legacy values are now normalised to false and do not emit this reason. */\n FilenameCaseSensitivityUnresolved: \"filename-case-sensitivity-unresolved\",\n} as const;\n\nexport type SettingsMigrationReviewCode =\n (typeof SettingsMigrationReviewCodes)[keyof typeof SettingsMigrationReviewCodes];\n\nexport interface SettingsMigrationReviewReason {\n code: SettingsMigrationReviewCode;\n fromVersion: number;\n toVersion: number;\n}\n\nexport interface SettingsMigrationState {\n sourceVersion: number;\n targetVersion: number;\n isNewVault: boolean;\n isFromFutureSchema: boolean;\n changed: boolean;\n requiresSyncReview: boolean;\n reviewReasons: readonly SettingsMigrationReviewReason[];\n}\n\nexport interface PreparedSettings extends SettingsMigrationState {\n settings: ObsidianLiveSyncSettings;\n}\n\ninterface SettingsMigration {\n toVersion: number;\n apply(settings: Partial<ObsidianLiveSyncSettings>): Partial<ObsidianLiveSyncSettings>;\n reviewReason?(\n settings: Partial<ObsidianLiveSyncSettings>,\n fromVersion: number\n ): SettingsMigrationReviewReason | undefined;\n}\n\nconst SETTINGS_MIGRATIONS: readonly SettingsMigration[] = [\n {\n toVersion: SETTING_VERSION_SUPPORT_CASE_INSENSITIVE,\n apply: (settings) => settings,\n reviewReason: (settings, fromVersion) =>\n settings.versionUpFlash\n ? {\n code: SettingsMigrationReviewCodes.LegacyUpdatePending,\n fromVersion,\n toVersion: SETTING_VERSION_SUPPORT_CASE_INSENSITIVE,\n }\n : undefined,\n },\n];\n\nfunction cloneSettings(\n source: Partial<ObsidianLiveSyncSettings>,\n fallbacks: ObsidianLiveSyncSettings\n): ObsidianLiveSyncSettings {\n const persistableSource = omitP2PRuntimeSettings(source);\n return {\n ...fallbacks,\n ...persistableSource,\n remoteConfigurations: Object.fromEntries(\n Object.entries(persistableSource.remoteConfigurations ?? fallbacks.remoteConfigurations).map(([id, config]) => [\n id,\n { ...config },\n ])\n ),\n pluginSyncExtendedSetting: {\n ...fallbacks.pluginSyncExtendedSetting,\n ...persistableSource.pluginSyncExtendedSetting,\n },\n };\n}\n\nfunction storedSettingVersion(settings: Partial<ObsidianLiveSyncSettings>): number {\n const version = settings.settingVersion;\n return typeof version === \"number\" && Number.isSafeInteger(version) && version >= SETTING_VERSION_INITIAL\n ? version\n : SETTING_VERSION_INITIAL;\n}\n\nfunction isBlankSettings(settings: Partial<ObsidianLiveSyncSettings> | undefined): boolean {\n return settings === undefined || Object.keys(settings).length === 0;\n}\n\nfunction inferLegacyConfiguredState(settings: Partial<ObsidianLiveSyncSettings>): boolean {\n // This is the exact pre-1.0 inference: a missing flag meant configured\n // only when completing the stored document changed a legacy default.\n const completed = { ...SETTINGS_SCHEMA_DEFAULTS, ...settings };\n return JSON.stringify(completed) !== JSON.stringify(SETTINGS_SCHEMA_DEFAULTS);\n}\n\n/**\n * Completes and migrates raw settings before services consume them.\n *\n * Stored settings use conservative schema fallbacks. A blank store uses the\n * independently maintained new-Vault defaults. Explicit stored values always\n * take precedence over both sets of defaults.\n */\nexport function prepareSettingsForLoad(\n storedSettings: Partial<ObsidianLiveSyncSettings> | undefined\n): PreparedSettings {\n if (isBlankSettings(storedSettings)) {\n return {\n settings: createNewVaultSettings(),\n sourceVersion: CURRENT_SETTING_VERSION,\n targetVersion: CURRENT_SETTING_VERSION,\n isNewVault: true,\n isFromFutureSchema: false,\n changed: false,\n requiresSyncReview: false,\n reviewReasons: [],\n };\n }\n\n const source = { ...storedSettings };\n const sourceVersion = storedSettingVersion(source);\n if (sourceVersion > CURRENT_SETTING_VERSION) {\n const reviewReasons: readonly SettingsMigrationReviewReason[] = [\n {\n code: SettingsMigrationReviewCodes.FutureSchema,\n fromVersion: sourceVersion,\n toVersion: CURRENT_SETTING_VERSION,\n },\n ];\n return {\n settings: cloneSettings(source, SETTINGS_SCHEMA_DEFAULTS),\n sourceVersion,\n targetVersion: sourceVersion,\n isNewVault: false,\n isFromFutureSchema: true,\n changed: false,\n requiresSyncReview: true,\n reviewReasons,\n };\n }\n\n let migrated: Partial<ObsidianLiveSyncSettings> = source;\n let targetVersion = sourceVersion;\n const reviewReasons: SettingsMigrationReviewReason[] = [];\n for (const migration of SETTINGS_MIGRATIONS) {\n if (targetVersion >= migration.toVersion) continue;\n const reason = migration.reviewReason?.(migrated, targetVersion);\n if (reason) reviewReasons.push(reason);\n migrated = migration.apply(migrated);\n targetVersion = migration.toVersion;\n migrated.settingVersion = targetVersion;\n }\n\n if (targetVersion !== CURRENT_SETTING_VERSION) {\n throw new Error(\n `No setting migration reaches schema ${CURRENT_SETTING_VERSION} from schema ${sourceVersion}.`\n );\n }\n\n // Keep the configured-state inference used before 1.0. A non-empty\n // default-equivalent document is still unconfigured; treating every\n // non-empty store as configured would make that state irreversible once\n // this migration is saved.\n const normalisedConfiguredState = migrated.isConfigured === undefined;\n if (normalisedConfiguredState) {\n migrated = { ...migrated, isConfigured: inferLegacyConfiguredState(source) };\n }\n\n // Every pre-1.0 path consumer treated an absent value as false. Persist\n // that effective legacy behaviour explicitly so the migration does not\n // invent a case-sensitive policy or require an unnecessary rebuild.\n const normalisedFilenameCase = typeof migrated.handleFilenameCaseSensitive !== \"boolean\";\n if (normalisedFilenameCase) migrated = { ...migrated, handleFilenameCaseSensitive: false };\n const normalisedInternalMetadata = typeof migrated.encryptInternalMetadata !== \"boolean\";\n if (normalisedInternalMetadata) migrated = { ...migrated, encryptInternalMetadata: false };\n\n return {\n settings: cloneSettings(migrated, SETTINGS_SCHEMA_DEFAULTS),\n sourceVersion,\n targetVersion,\n isNewVault: false,\n isFromFutureSchema: false,\n changed: sourceVersion !== targetVersion || normalisedConfiguredState || normalisedFilenameCase || normalisedInternalMetadata,\n requiresSyncReview: reviewReasons.length > 0,\n reviewReasons,\n };\n}\n","import type { MILESTONE_DOCID, NODEINFO_DOCID } from \"./db.const\";\nimport type {\n AnyEntry,\n ChunkVersionRange,\n DatabaseEntry,\n EntryChunkPack,\n EntryLeaf,\n EntryTypes,\n EntryVersionInfo,\n InternalFileEntry,\n LoadedEntry,\n MetaEntry,\n NewEntry,\n NoteEntry,\n PlainEntry,\n} from \"./db.type\";\nimport type { TweakValues } from \"./tweak.definition\";\n\nexport type NodeKey = string;\nexport interface DeviceInfo {\n /**\n * Name of the device (Initially from deviceAndVaultName setting, configurable).\n */\n device_name: string;\n /**\n * Vault name (From vaultName setting).\n */\n vault_name: string;\n /**\n * Obsidian App version of the device.\n */\n app_version: string;\n /**\n * Plugin version of the device.\n */\n plugin_version: string;\n progress: string;\n}\nexport interface NodeData extends DeviceInfo {\n /**\n * Epoch time in milliseconds when the device last connected.\n */\n last_connected: number;\n}\nexport interface EntryMilestoneInfo extends DatabaseEntry {\n _id: typeof MILESTONE_DOCID;\n type: EntryTypes[\"MILESTONE_INFO\"];\n created: number;\n accepted_nodes: string[];\n node_info: { [key: NodeKey]: NodeData };\n locked: boolean;\n cleaned?: boolean;\n node_chunk_info: { [key: NodeKey]: ChunkVersionRange };\n tweak_values: { [key: NodeKey]: TweakValues };\n encrypted_id_derivation_proof?: string;\n}\n\nexport interface EntryNodeInfo extends DatabaseEntry {\n _id: typeof NODEINFO_DOCID;\n type: EntryTypes[\"NODE_INFO\"];\n nodeid: string;\n v20220607?: boolean;\n}\n\nexport type EntryBody = NoteEntry | NewEntry | PlainEntry | InternalFileEntry;\n\nexport type EntryDoc =\n | EntryBody\n | LoadedEntry\n | EntryLeaf\n | EntryVersionInfo\n | EntryMilestoneInfo\n | EntryNodeInfo\n | EntryChunkPack;\n\nexport type EntryDocResponse = EntryDoc & PouchDB.Core.IdMeta & PouchDB.Core.GetMeta;\n\nexport function isMetaEntry(entry: AnyEntry): entry is MetaEntry {\n return \"children\" in entry;\n}\n","// Setting keys\nexport const SETTING_KEY_P2P_DEVICE_NAME = \"p2p_device_name\";\n\n// Configuration URI\nexport const configURIBase = \"obsidian://setuplivesync?settings=\";\nexport const configURIBaseQR = \"obsidian://setuplivesync?settingsQR=\";\n\n// Database\nexport const SuffixDatabaseName = \"-livesync-v2\";\nexport const ExtraSuffixIndexedDB = \"-indexeddb\";\n","import { EntryTypes } from \"./db.const\";\nimport type { DatabaseEntry, DocumentID } from \"./db.type\";\n\nexport const ProtocolVersions = {\n UNSET: undefined as undefined,\n LEGACY: 1,\n ADVANCED_E2EE: 2,\n} as const;\nexport type ProtocolVersion = (typeof ProtocolVersions)[keyof typeof ProtocolVersions];\nexport const DOCID_SYNC_PARAMETERS = \"_local/obsidian_livesync_sync_parameters\" as DocumentID;\nexport const DOCID_JOURNAL_SYNC_PARAMETERS = \"_obsidian_livesync_journal_sync_parameters.json\" as DocumentID;\n\nexport interface SyncParameters extends DatabaseEntry {\n _id: typeof DOCID_SYNC_PARAMETERS;\n _rev?: string;\n type: (typeof EntryTypes)[\"SYNC_PARAMETERS\"];\n protocolVersion: ProtocolVersion;\n pbkdf2salt: string;\n}\nexport const DEFAULT_SYNC_PARAMETERS: SyncParameters = {\n _id: DOCID_SYNC_PARAMETERS,\n type: EntryTypes[\"SYNC_PARAMETERS\"],\n protocolVersion: ProtocolVersions.ADVANCED_E2EE,\n pbkdf2salt: \"\",\n};\n","import { ChunkAlgorithms, E2EEAlgorithms } from \"./setting.const\";\nimport type { ObsidianLiveSyncSettings } from \"./setting.type\";\nimport { DEFAULT_SETTINGS } from \"./setting.const.defaults\";\n\nexport type TweakReconstruction = \"none\" | \"recommended\" | \"required\";\n\ntype TweakCompatibilityRule = {\n readonly key: keyof ObsidianLiveSyncSettings;\n readonly templateValue: ObsidianLiveSyncSettings[keyof ObsidianLiveSyncSettings];\n readonly reconstruction: TweakReconstruction;\n readonly knownDefault?: ObsidianLiveSyncSettings[keyof ObsidianLiveSyncSettings];\n readonly compatibleLossyOrder?: number;\n readonly specificPatterns?: readonly {\n readonly from?: ObsidianLiveSyncSettings[keyof ObsidianLiveSyncSettings];\n readonly to?: ObsidianLiveSyncSettings[keyof ObsidianLiveSyncSettings];\n readonly reconstruction: Exclude<TweakReconstruction, \"none\">;\n }[];\n};\n\n/**\n * Single source for tweak comparison semantics and the maintained legacy\n * compatibility projections below.\n */\nexport const TweakCompatibilityRules = Object.freeze([\n { key: \"minimumChunkSize\", templateValue: 20, reconstruction: \"none\" },\n { key: \"longLineThreshold\", templateValue: 250, reconstruction: \"none\" },\n { key: \"encrypt\", templateValue: false, reconstruction: \"required\" },\n { key: \"usePathObfuscation\", templateValue: false, reconstruction: \"required\" },\n { key: \"idDerivationVersion\", templateValue: 0, reconstruction: \"required\", knownDefault: 0 },\n { key: \"encryptInternalMetadata\", templateValue: false, reconstruction: \"none\", knownDefault: false },\n { key: \"enableCompression\", templateValue: false, reconstruction: \"none\" },\n { key: \"useEden\", templateValue: false, reconstruction: \"none\" },\n { key: \"customChunkSize\", templateValue: 0, reconstruction: \"recommended\", compatibleLossyOrder: 1 },\n { key: \"useDynamicIterationCount\", templateValue: false, reconstruction: \"required\" },\n { key: \"hashAlg\", templateValue: \"xxhash64\", reconstruction: \"recommended\", compatibleLossyOrder: 0 },\n { key: \"enableChunkSplitterV2\", templateValue: false, reconstruction: \"none\" },\n { key: \"maxChunksInEden\", templateValue: 10, reconstruction: \"none\" },\n { key: \"maxTotalLengthInEden\", templateValue: 1024, reconstruction: \"none\" },\n { key: \"maxAgeInEden\", templateValue: 10, reconstruction: \"none\" },\n {\n key: \"usePluginSyncV2\",\n templateValue: false,\n reconstruction: \"none\",\n knownDefault: false,\n },\n {\n key: \"handleFilenameCaseSensitive\",\n templateValue: false,\n reconstruction: \"required\",\n knownDefault: false,\n },\n { key: \"useSegmenter\", templateValue: false, reconstruction: \"none\" },\n {\n key: \"E2EEAlgorithm\",\n templateValue: E2EEAlgorithms.V2,\n reconstruction: \"none\",\n knownDefault: DEFAULT_SETTINGS.E2EEAlgorithm,\n },\n {\n key: \"chunkSplitterVersion\",\n templateValue: ChunkAlgorithms.RabinKarp,\n reconstruction: \"recommended\",\n knownDefault: DEFAULT_SETTINGS.chunkSplitterVersion,\n compatibleLossyOrder: 2,\n },\n] as const satisfies readonly TweakCompatibilityRule[]);\n\nexport type TweakComparedKey = (typeof TweakCompatibilityRules)[number][\"key\"];\n\nexport const TweakValuesShouldMatchedTemplate = Object.fromEntries(\n TweakCompatibilityRules.map(({ key, templateValue }) => [key, templateValue])\n) as Pick<ObsidianLiveSyncSettings, TweakComparedKey>;\n\ntype TweakKeys = keyof TweakValues;\n\nexport const IncompatibleChanges: TweakKeys[] = [\n ...TweakCompatibilityRules.filter(({ reconstruction }) => reconstruction === \"required\").map(({ key }) => key),\n] as TweakKeys[];\n\nexport const CompatibleButLossyChanges: TweakKeys[] = TweakCompatibilityRules.filter(\n (rule): rule is (typeof TweakCompatibilityRules)[number] & { readonly compatibleLossyOrder: number } =>\n \"compatibleLossyOrder\" in rule\n)\n .slice()\n .sort((left, right) => left.compatibleLossyOrder - right.compatibleLossyOrder)\n .map(({ key }) => key);\n\ntype IncompatibleRecommendationPatterns<T extends TweakKeys> = {\n key: T;\n isRecommendation?: boolean;\n} & (\n | {\n from: TweakValues[T];\n to: TweakValues[T];\n }\n | {\n from: TweakValues[T];\n }\n | {\n to: TweakValues[T];\n }\n);\n\nexport const IncompatibleChangesInSpecificPattern: IncompatibleRecommendationPatterns<TweakKeys>[] = (\n TweakCompatibilityRules as readonly TweakCompatibilityRule[]\n).flatMap((rule) =>\n (rule.specificPatterns ?? []).map((pattern) => ({\n key: rule.key,\n ...(Object.prototype.hasOwnProperty.call(pattern, \"from\") ? { from: pattern.from } : {}),\n ...(Object.prototype.hasOwnProperty.call(pattern, \"to\") ? { to: pattern.to } : {}),\n ...(pattern.reconstruction === \"recommended\" ? { isRecommendation: true } : {}),\n }))\n) as IncompatibleRecommendationPatterns<TweakKeys>[];\n\nexport const TweakValuesRecommendedTemplate: Partial<ObsidianLiveSyncSettings> = {\n useIgnoreFiles: false,\n useCustomRequestHandler: false,\n\n batch_size: 25,\n batches_limit: 25,\n // useIndexedDBAdapter: false,\n useTimeouts: false,\n readChunksOnline: true,\n hashCacheMaxCount: 300,\n hashCacheMaxAmount: 50,\n concurrencyOfReadChunksOnline: 40,\n minimumIntervalOfReadChunksOnline: 50,\n ignoreFiles: \".gitignore\",\n syncMaxSizeInMB: 50,\n enableChunkSplitterV2: false,\n usePluginSyncV2: true,\n handleFilenameCaseSensitive: false,\n E2EEAlgorithm: E2EEAlgorithms.V2,\n chunkSplitterVersion: ChunkAlgorithms.RabinKarp,\n} satisfies Partial<ObsidianLiveSyncSettings>;\nexport const TweakValuesDefault: Partial<ObsidianLiveSyncSettings> = {\n ...Object.fromEntries(\n TweakCompatibilityRules.filter(\n (rule) => \"knownDefault\" in rule && rule.key !== \"handleFilenameCaseSensitive\"\n ).map(({ key, knownDefault }) => [key, knownDefault])\n ),\n tweakModified: DEFAULT_SETTINGS.tweakModified,\n} satisfies Partial<ObsidianLiveSyncSettings>;\n\nexport const TweakValuesTemplate = {\n ...TweakValuesRecommendedTemplate,\n ...TweakValuesShouldMatchedTemplate,\n tweakModified: 0,\n} satisfies Partial<ObsidianLiveSyncSettings>;\nexport type TweakValues = Partial<typeof TweakValuesTemplate>;\n\nexport const DEVICE_ID_PREFERRED = \"PREFERRED\";\n\nexport const RemotePreferredTweakStatuses = {\n AVAILABLE: \"available\",\n NOT_CONFIGURED: \"not-configured\",\n UNAVAILABLE: \"unavailable\",\n UNSUPPORTED: \"unsupported\",\n} as const;\n\nexport type RemotePreferredTweakStatus =\n (typeof RemotePreferredTweakStatuses)[keyof typeof RemotePreferredTweakStatuses];\n\nexport const RemotePreferredTweakNotConfiguredReasons = {\n MILESTONE_MISSING: \"milestone-missing\",\n PREFERRED_VALUES_MISSING: \"preferred-values-missing\",\n} as const;\n\nexport type RemotePreferredTweakNotConfiguredReason =\n (typeof RemotePreferredTweakNotConfiguredReasons)[keyof typeof RemotePreferredTweakNotConfiguredReasons];\n\nexport type RemotePreferredTweakResult =\n | {\n status: typeof RemotePreferredTweakStatuses.AVAILABLE;\n values: TweakValues;\n }\n | {\n status: typeof RemotePreferredTweakStatuses.NOT_CONFIGURED;\n reason: RemotePreferredTweakNotConfiguredReason;\n }\n | {\n status: typeof RemotePreferredTweakStatuses.UNAVAILABLE;\n error: unknown;\n }\n | {\n status: typeof RemotePreferredTweakStatuses.UNSUPPORTED;\n };\n","import type { FilePath } from \"./db.type\";\n\nexport const PREFIXMD_LOGFILE = \"livesync_log_\";\nexport const PREFIXMD_LOGFILE_UC = \"LIVESYNC_LOG_\";\n\nexport const FlagFilesOriginal = {\n SUSPEND_ALL: \"redflag.md\" as FilePath,\n REBUILD_ALL: \"redflag2.md\" as FilePath,\n FETCH_ALL: \"redflag3.md\" as FilePath,\n} as const;\n\nexport const FlagFilesHumanReadable = {\n REBUILD_ALL: \"flag_rebuild.md\" as FilePath,\n FETCH_ALL: \"flag_fetch.md\" as FilePath,\n} as const;\n\n/**\n * @deprecated Use `FlagFilesOriginal.SUSPEND_ALL` instead.\n */\nexport const FLAGMD_REDFLAG = FlagFilesOriginal.SUSPEND_ALL;\n/**\n * @deprecated Use `FlagFilesHumanReadable.REBUILD_ALL` instead.\n */\nexport const FLAGMD_REDFLAG2 = FlagFilesOriginal.REBUILD_ALL;\n/**\n * @deprecated Use `FlagFilesHumanReadable.FETCH_ALL` instead.\n */\nexport const FLAGMD_REDFLAG2_HR = FlagFilesHumanReadable.REBUILD_ALL;\n/**\n * @deprecated Use `FlagFilesOriginal.FETCH_ALL` instead.\n */\nexport const FLAGMD_REDFLAG3 = FlagFilesOriginal.FETCH_ALL;\n/**\n * @deprecated Use `FlagFilesHumanReadable.FETCH_ALL` instead.\n */\nexport const FLAGMD_REDFLAG3_HR = FlagFilesHumanReadable.FETCH_ALL;\n","export const DatabaseConnectingStatuses = {\n STARTED: \"STARTED\",\n NOT_CONNECTED: \"NOT_CONNECTED\",\n PAUSED: \"PAUSED\",\n CONNECTED: \"CONNECTED\",\n COMPLETED: \"COMPLETED\",\n CLOSED: \"CLOSED\",\n ERRORED: \"ERRORED\",\n JOURNAL_SEND: \"JOURNAL_SEND\",\n JOURNAL_RECEIVE: \"JOURNAL_RECEIVE\",\n} as const;\nexport type DatabaseConnectingStatus = (typeof DatabaseConnectingStatuses)[keyof typeof DatabaseConnectingStatuses];\n\nexport type ReplicationStatics = {\n sent: number;\n arrived: number;\n maxPullSeq: number;\n maxPushSeq: number;\n lastSyncPullSeq: number;\n lastSyncPushSeq: number;\n syncStatus: DatabaseConnectingStatus;\n};\n\nexport const DEFAULT_REPLICATION_STATICS: ReplicationStatics = {\n sent: 0,\n arrived: 0,\n maxPullSeq: 0,\n maxPushSeq: 0,\n lastSyncPullSeq: 0,\n lastSyncPushSeq: 0,\n syncStatus: DatabaseConnectingStatuses.CLOSED,\n};\n","export * from \"octagonal-wheels/common/logger\";\nexport type * from \"octagonal-wheels/common/logger\";\n","// This module provides core environment functions that can be set by the\n// host application (like Obsidian) and used across the library without\n// direct dependencies on the host's APIs.\n// For `features`, please implement service, feature, or, serviceFeature for the sake of\n// robust architecture and dependency management. Only put truly core functions here that.\n\nexport type LanguageGetter = () => string;\n\nlet _getLanguage: LanguageGetter = () => \"en\";\n\nexport function setGetLanguage(func: LanguageGetter) {\n _getLanguage = func;\n}\n\nexport function getLanguage() {\n return _getLanguage();\n}\n\n// Compatibility for globalThis across different environments (browser, Node.js, etc.)\nexport const compatGlobal = (\n typeof window !== \"undefined\"\n ? window\n : // compatibility for CLIs, tests, and other non-browser environments.\n // eslint-disable-next-line obsidianmd/no-global-this\n globalThis\n) as typeof window;\n\nexport type CompatTimeoutHandle = ReturnType<typeof setTimeout> | number;\nexport type CompatIntervalHandle = ReturnType<typeof setInterval> | number;\n\n/**\n * A wrapper around the global fetch function to ensure compatibility across different environments.\n * In Obsidian, they recommend using their own requestUrl for better performance and reliability.\n * However, at least for now, requestUrl cannot handle multiple concurrent requests, which causes\n * problems for synchronise lively. So we will use the global fetch for now.\n * If the situation changes in the future, change this function to use requestUrl.\n * @param {RequestInfo} input The resource that you wish to fetch. Can be either a string or a Request object.\n * @param {RequestInit} [init] An options object containing any custom settings that you want to apply to the request.\n * @returns {Promise<Response>} A Promise that resolves to the Response to that request, whether it is successful or not.\n */\nexport const _fetch = compatGlobal.fetch.bind(compatGlobal);\n\ntype ActiveDocumentWindow = typeof window & { activeDocument?: Document };\nconst activeDocumentWindow = compatGlobal as ActiveDocumentWindow;\nexport const _activeDocument: Document = activeDocumentWindow.activeDocument ?? activeDocumentWindow.document;\n","// Misc\nimport {\n arrayBufferToBase64,\n base64ToArrayBuffer,\n base64ToArrayBufferInternalBrowser,\n arrayBufferToBase64Single as arrayBufferToBase64SingleInternal,\n readString,\n writeString,\n tryConvertBase64ToArrayBuffer,\n} from \"octagonal-wheels/binary\";\nimport { compatGlobal } from \"@lib/common/coreEnvFunctions\";\nexport {\n arrayBufferToBase64,\n base64ToArrayBuffer,\n base64ToArrayBufferInternalBrowser,\n readString,\n writeString,\n tryConvertBase64ToArrayBuffer,\n};\nexport async function arrayBufferToBase64Single(buffer: Uint8Array<ArrayBuffer> | ArrayBuffer): Promise<string> {\n try {\n return await arrayBufferToBase64SingleInternal(buffer);\n } catch (ex) {\n // In Node.js/CLI, FileReader is unavailable. Use Buffer as a runtime fallback.\n const maybeBuffer = compatGlobal?.Buffer;\n if (typeof maybeBuffer?.from === \"function\") {\n const view = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);\n return maybeBuffer.from(view.buffer, view.byteOffset, view.byteLength).toString(\"base64\");\n }\n throw ex;\n }\n}\nexport { uint8ArrayToHexString, hexStringToUint8Array } from \"octagonal-wheels/binary/hex\";\nexport { encodeBinaryEach, decodeToArrayBuffer } from \"octagonal-wheels/binary/encodedUTF16\";\nexport { decodeBinary, encodeBinary } from \"octagonal-wheels/binary\";\nexport { escapeStringToHTML } from \"octagonal-wheels/string\";\nexport function versionNumberString2Number(version: string): number {\n return version // \"1.23.45\"\n .split(\".\") // 1 23 45\n .reverse() // 45 23 1\n .map((e, i) => (Number(e) || 0) * 1000 ** i) // 45 23000 1000000\n .reduce((prev, current) => prev + current, 0); // 1023045\n}\n","import { _fetch, compatGlobal } from \"@lib/common/coreEnvFunctions.ts\";\nimport { writeString } from \"@lib/string_and_binary/convert.ts\";\n\nexport const isValidRemoteCouchDBURI = (uri: string): boolean => {\n if (uri.startsWith(\"https://\")) return true;\n if (uri.startsWith(\"http://\")) return true;\n return false;\n};\n\nexport function isCloudantURI(uri: string): boolean {\n if (uri.indexOf(\".cloudantnosqldb.\") !== -1 || uri.indexOf(\".cloudant.com\") !== -1) return true;\n return false;\n}\n\nexport function isErrorOfMissingDoc(ex: unknown): boolean {\n return (ex && (ex as { status?: number }).status) == 404;\n}\n\nexport const _requestToCouchDBFetch = async (\n baseUri: string,\n username: string,\n password: string,\n path?: string,\n body?: unknown,\n method?: string\n) => {\n const utf8str = String.fromCharCode.apply(null, [...writeString(`${username}:${password}`)]);\n const encoded = compatGlobal.btoa(utf8str);\n const authHeader = \"Basic \" + encoded;\n const transformedHeaders: Record<string, string> = {\n authorization: authHeader,\n \"content-type\": \"application/json\",\n };\n const uri = `${baseUri}/${path}`;\n const requestParam = {\n url: uri,\n method: method || (body ? \"PUT\" : \"GET\"),\n headers: new Headers(transformedHeaders),\n contentType: \"application/json\",\n body: JSON.stringify(body),\n };\n return await _fetch(uri, requestParam);\n};\n","import { compatGlobal } from \"./common/coreEnvFunctions\";\n\nlet webcrypto: Crypto;\nexport async function getWebCrypto() {\n if (webcrypto) {\n return webcrypto;\n }\n if (compatGlobal.crypto) {\n webcrypto = compatGlobal.crypto;\n return webcrypto;\n } else {\n // This is for Node.js.\n // eslint-disable-next-line import/no-nodejs-modules\n const module = await import(\"crypto\");\n webcrypto = module.webcrypto as Crypto;\n return webcrypto;\n }\n}\n","export * from \"octagonal-wheels/hash/xxhash.js\";\nexport type * from \"octagonal-wheels/hash/xxhash.js\";\n","import { getWebCrypto } from \"@lib/mods.ts\";\nimport { hexStringToUint8Array, uint8ArrayToHexString } from \"@lib/string_and_binary/convert.ts\";\nimport type { EncryptionSettings } from \"@lib/common/models/setting.type.ts\";\nimport { xxhashNew } from \"@lib/string_and_binary/hash.ts\";\n\nexport const ID_DERIVATION_VERSION = 1;\nexport const ID_RECOVERY_CODE_PREFIX = \"sls-id-v1:\";\nconst SOURCE_SALT = new TextEncoder().encode(\"self-hosted-livesync:id-source:v1\");\nconst SOURCE_ITERATIONS = 310_000;\nconst HEX_KEY = /^[0-9a-f]{64}$/u;\nconst CHUNK_KEY_CONTEXT = new TextEncoder().encode(\"self-hosted-livesync:id-v1:chunk-key:xxhash64\");\nconst CHUNK_ID_PREFIX = \"self-hosted-livesync:id-v1:chunk:xxhash64\\0\";\n\n/** Derive a portable key once, when the source string is saved. */\nexport async function deriveIdKey(source: string): Promise<string> {\n if (source.length === 0) {\n throw new Error(\"An ID source is required.\");\n }\n const crypto = await getWebCrypto();\n const sourceKey = await crypto.subtle.importKey(\n \"raw\",\n new TextEncoder().encode(source.normalize(\"NFC\")),\n \"PBKDF2\",\n false,\n [\"deriveBits\"]\n );\n const bits = await crypto.subtle.deriveBits(\n { name: \"PBKDF2\", hash: \"SHA-256\", salt: SOURCE_SALT, iterations: SOURCE_ITERATIONS },\n sourceKey,\n 256\n );\n return uint8ArrayToHexString(new Uint8Array(bits));\n}\n\n/** Export a saved key in a format which can be imported without deriving it again. */\nexport function formatIdRecoveryCode(key: string): string {\n if (!HEX_KEY.test(key)) throw new Error(\"The configured ID key is invalid.\");\n return `${ID_RECOVERY_CODE_PREFIX}${key}`;\n}\n\n/** Treat a tagged recovery code as a saved key; derive ordinary source strings. */\nexport async function deriveOrImportIdKey(input: string): Promise<string> {\n const candidate = input.trim();\n if (candidate.startsWith(ID_RECOVERY_CODE_PREFIX)) {\n const key = candidate.slice(ID_RECOVERY_CODE_PREFIX.length);\n if (!HEX_KEY.test(key)) throw new Error(\"The ID recovery code is invalid.\");\n return key;\n }\n if (candidate.startsWith(\"sls-id-v\")) throw new Error(\"The ID recovery code version is unsupported.\");\n return await deriveIdKey(input);\n}\n\n/** Return the independent ID key, rejecting an incomplete new-mode setting. */\nexport function configuredIdKey(\n settings: Pick<EncryptionSettings, \"idDerivationVersion\" | \"idDerivationKey\">\n): string | false {\n const version = settings.idDerivationVersion;\n const key = settings.idDerivationKey;\n if (version === 0 || version === undefined) {\n if (key) throw new Error(\"An ID key requires a supported derivation version.\");\n return false;\n }\n if (version !== ID_DERIVATION_VERSION || !HEX_KEY.test(key)) {\n throw new Error(\"The configured ID derivation is unavailable or invalid.\");\n }\n return key;\n}\n\n/** Prepare a purpose-separated Chunk key for repeated ID calculations. */\nexport async function createChunkIdGenerator(key: string): Promise<(value: string) => Promise<string>> {\n if (!HEX_KEY.test(key)) throw new Error(\"The configured ID key is invalid.\");\n const crypto = await getWebCrypto();\n const masterKey = await crypto.subtle.importKey(\n \"raw\",\n hexStringToUint8Array(key),\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"]\n );\n const derivedKey = await crypto.subtle.sign(\"HMAC\", masterKey, CHUNK_KEY_CONTEXT);\n const chunkKey = await crypto.subtle.importKey(\"raw\", derivedKey, { name: \"HMAC\", hash: \"SHA-256\" }, false, [\n \"sign\",\n ]);\n const xxhash = await xxhashNew();\n const encoder = new TextEncoder();\n return async (value) => {\n const digest = xxhash.h64(value).toString(16).padStart(16, \"0\");\n const id = await crypto.subtle.sign(\"HMAC\", chunkKey, encoder.encode(CHUNK_ID_PREFIX + digest));\n return uint8ArrayToHexString(new Uint8Array(id));\n };\n}\n\n/** Derive purpose-separated IDs; repeated Chunk calculations should reuse a prepared generator. */\nexport async function computeKeyedId(\n key: string,\n purpose: \"chunk\" | \"document\" | \"peer-agreement\" | \"remote-agreement\",\n value: string\n): Promise<string> {\n if (purpose === \"chunk\") return (await createChunkIdGenerator(key))(value);\n if (!HEX_KEY.test(key)) throw new Error(\"The configured ID key is invalid.\");\n const crypto = await getWebCrypto();\n const hmacKey = await crypto.subtle.importKey(\n \"raw\",\n hexStringToUint8Array(key),\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"]\n );\n const input = new TextEncoder().encode(`self-hosted-livesync:id-v1:${purpose}\\0${value}`);\n const digest = await crypto.subtle.sign(\"HMAC\", hmacKey, input);\n return uint8ArrayToHexString(new Uint8Array(digest));\n}\n","import { E2EEAlgorithms, VERSIONING_DOCID } from \"@lib/common/types\";\nimport { configuredIdKey } from \"@lib/common/idDerivation.ts\";\n\nexport const REMOTE_FEATURE_GENERATION = 13;\nexport const ENCRYPTED_INTERNAL_METADATA_FEATURE = \"encrypted-internal-metadata-v1\";\nexport const INDEPENDENT_ID_DERIVATION_FEATURE = \"independent-id-derivation-v1\";\n\nexport const supportedFeatures = new Set([ENCRYPTED_INTERNAL_METADATA_FEATURE, INDEPENDENT_ID_DERIVATION_FEATURE]);\n\nexport function requiredRemoteFeatures(setting: {\n encrypt?: boolean;\n usePathObfuscation?: boolean;\n E2EEAlgorithm?: string;\n encryptInternalMetadata?: boolean;\n idDerivationVersion: 0 | 1;\n idDerivationKey: string;\n}): string[] {\n const features: string[] = [];\n if (usesEncryptedInternalMetadata(setting)) features.push(ENCRYPTED_INTERNAL_METADATA_FEATURE);\n if (setting.encrypt && configuredIdKey(setting)) features.push(INDEPENDENT_ID_DERIVATION_FEATURE);\n return features;\n}\n\nexport function usesEncryptedInternalMetadata(setting: {\n encrypt?: boolean;\n usePathObfuscation?: boolean;\n E2EEAlgorithm?: string;\n encryptInternalMetadata?: boolean;\n}): boolean {\n return (\n setting.encryptInternalMetadata === true &&\n setting.encrypt === true &&\n setting.usePathObfuscation === true &&\n setting.E2EEAlgorithm === E2EEAlgorithms.V2\n );\n}\n\nexport type RemoteFeatureAssessment =\n | { status: \"supported\"; usedFeatures: readonly string[] }\n | { status: \"older-generation\"; version: number }\n | { status: \"unsupported-generation\"; version: number }\n | { status: \"unknown-features\"; identifiers: readonly string[] }\n | { status: \"invalid-control\" };\n\nexport function assessRemoteFeatureDocument(document: unknown): RemoteFeatureAssessment {\n if (typeof document !== \"object\" || document === null) return { status: \"invalid-control\" };\n const value = document as Record<string, unknown>;\n if (value._id !== VERSIONING_DOCID || value.type !== \"versioninfo\" || value._deleted === true) {\n return { status: \"invalid-control\" };\n }\n if (typeof value.version !== \"number\" || !Number.isSafeInteger(value.version) || value.version < 0) {\n return { status: \"invalid-control\" };\n }\n const version = value.version;\n if (version < 12) {\n return \"used_features\" in value ? { status: \"invalid-control\" } : { status: \"older-generation\", version };\n }\n if (version > REMOTE_FEATURE_GENERATION) return { status: \"unsupported-generation\", version };\n if (version === 12) {\n return \"used_features\" in value ? { status: \"invalid-control\" } : { status: \"supported\", usedFeatures: [] };\n }\n if (\n !Array.isArray(value.used_features) ||\n !value.used_features.every((name: unknown) => typeof name === \"string\" && name.length > 0)\n ) {\n return { status: \"invalid-control\" };\n }\n const usedFeatures = [...new Set(value.used_features as string[])];\n const identifiers = usedFeatures.filter((name) => !supportedFeatures.has(name));\n return identifiers.length > 0 ? { status: \"unknown-features\", identifiers } : { status: \"supported\", usedFeatures };\n}\n\nexport function describeRemoteFeatureRejection(assessment: RemoteFeatureAssessment): string {\n switch (assessment.status) {\n case \"unknown-features\":\n return `Unknown features are in use: ${assessment.identifiers.join(\", \")}`;\n case \"unsupported-generation\":\n return `Unsupported remote database generation: ${assessment.version}`;\n case \"invalid-control\":\n return \"The remote database version document is invalid.\";\n case \"older-generation\":\n return `The remote database requires migration from generation ${assessment.version}.`;\n case \"supported\":\n return \"\";\n }\n}\n","import { LOG_LEVEL_INFO, LOG_LEVEL_NOTICE, Logger } from \"@lib/common/logger\";\nimport {\n LOG_LEVEL_VERBOSE,\n SYNCINFO_ID,\n VER,\n VERSIONING_DOCID,\n type EntryVersionInfo,\n type SyncInfo,\n} from \"@lib/common/types\";\nimport { isErrorOfMissingDoc } from \"./utils_couchdb\";\nimport {\n assessRemoteFeatureDocument,\n describeRemoteFeatureRejection,\n supportedFeatures,\n REMOTE_FEATURE_GENERATION,\n} from \"./remoteFeatureCompatibility\";\n\nexport const checkRemoteVersion = async (\n db: PouchDB.Database,\n migrate: (from: number, to: number) => Promise<boolean>,\n barrier: number = VER,\n requiredFeatures: readonly string[] = []\n): Promise<boolean> => {\n try {\n const versionInfo = (await db.get(VERSIONING_DOCID)) as EntryVersionInfo;\n const assessment = assessRemoteFeatureDocument(versionInfo);\n if (assessment.status === \"older-generation\") {\n if (assessment.version >= barrier) return true;\n if (!(await migrate(assessment.version, barrier))) return false;\n if (!(await bumpRemoteVersion(db, barrier))) return false;\n return requiredFeatures.length === 0 || (await declareRemoteFeatures(db, requiredFeatures));\n }\n if (assessment.status !== \"supported\") {\n Logger(describeRemoteFeatureRejection(assessment), LOG_LEVEL_NOTICE);\n return false;\n }\n if (versionInfo.version < barrier) return false;\n return requiredFeatures.length === 0 || (await declareRemoteFeatures(db, requiredFeatures));\n } catch (ex) {\n if (isErrorOfMissingDoc(ex)) {\n const info = await db.info();\n if (info.doc_count > 0) return false;\n return await bumpRemoteVersion(\n db,\n requiredFeatures.length ? REMOTE_FEATURE_GENERATION : VER,\n requiredFeatures\n );\n }\n throw ex;\n }\n};\nexport const bumpRemoteVersion = async (\n db: PouchDB.Database,\n barrier: number = VER,\n usedFeatures: readonly string[] = []\n): Promise<boolean> => {\n for (let attempt = 0; attempt < 4; attempt++) {\n let current: EntryVersionInfo | undefined;\n try {\n current = (await db.get(VERSIONING_DOCID)) as EntryVersionInfo;\n } catch (error) {\n if (!isErrorOfMissingDoc(error)) throw error;\n }\n if (current) {\n const assessment = assessRemoteFeatureDocument(current);\n if (assessment.status !== \"supported\" && assessment.status !== \"older-generation\") {\n Logger(describeRemoteFeatureRejection(assessment), LOG_LEVEL_NOTICE);\n return false;\n }\n if (current.version >= barrier) {\n return usedFeatures.length === 0 || (await declareRemoteFeatures(db, usedFeatures));\n }\n }\n const next: EntryVersionInfo = {\n ...current,\n _id: VERSIONING_DOCID,\n version: barrier,\n type: \"versioninfo\",\n ...(barrier >= REMOTE_FEATURE_GENERATION ? { used_features: [...new Set(usedFeatures)] } : {}),\n };\n try {\n await db.put(next);\n return true;\n } catch (error) {\n if (typeof error !== \"object\" || error === null || !(\"status\" in error) || error.status !== 409) {\n throw error;\n }\n }\n }\n return false;\n};\n\nexport async function declareRemoteFeatures(\n db: PouchDB.Database,\n requiredFeatures: readonly string[]\n): Promise<boolean> {\n const requested = [...new Set(requiredFeatures)];\n if (requested.some((name) => !supportedFeatures.has(name))) {\n throw new Error(\"A writer requested an unsupported remote feature.\");\n }\n if (requested.length === 0) return true;\n for (let attempt = 0; attempt < 4; attempt++) {\n const current = (await db.get(VERSIONING_DOCID)) as EntryVersionInfo;\n const assessment = assessRemoteFeatureDocument(current);\n if (assessment.status !== \"supported\") {\n Logger(describeRemoteFeatureRejection(assessment), LOG_LEVEL_NOTICE);\n return false;\n }\n const usedFeatures = [...new Set([...assessment.usedFeatures, ...requested])];\n if (current.version === REMOTE_FEATURE_GENERATION && usedFeatures.length === assessment.usedFeatures.length) {\n return true;\n }\n try {\n await db.put({ ...current, version: REMOTE_FEATURE_GENERATION, used_features: usedFeatures });\n return true;\n } catch (ex) {\n if (typeof ex !== \"object\" || ex === null || !(\"status\" in ex) || ex.status !== 409) throw ex;\n }\n }\n return false;\n}\n\nexport const checkSyncInfo = async (db: PouchDB.Database): Promise<boolean> => {\n try {\n const syncinfo = (await db.get(SYNCINFO_ID)) as SyncInfo;\n console.log(syncinfo);\n // if we could decrypt the doc, it must be ok.\n return true;\n } catch (ex) {\n if (isErrorOfMissingDoc(ex)) {\n const randomStrSrc = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n const temp = [...Array(30)]\n .map((_e) => Math.floor(Math.random() * randomStrSrc.length))\n .map((e) => randomStrSrc[e])\n .join(\"\");\n const newSyncInfo: SyncInfo = {\n _id: SYNCINFO_ID,\n type: \"syncinfo\",\n data: temp,\n };\n if (await db.put(newSyncInfo)) {\n return true;\n }\n return false;\n } else {\n console.dir(ex);\n return false;\n }\n }\n};\n\n// Selectors to already transferred compromised chunks (before h:, i.e., \"0123456\")\nconst SELECTOR_COMPROMISED_CHUNK_1 = {\n selector: {\n _id: {\n $lt: \"h:\",\n },\n type: \"leaf\",\n },\n} as const;\n\n// Selectors to already transferred compromised chunks (after h:, i.e., \"ijklmnop\")\nconst SELECTOR_COMPROMISED_CHUNK_2 = {\n selector: {\n _id: {\n $gt: \"h;\",\n },\n type: \"leaf\",\n },\n} as const;\n\n/**\n * Counts the number of remote (potentially) compromised chunks in the database.\n * @param db The PouchDB database instance.\n * @returns The number of compromised chunks or false if an error occurs.\n */\nexport async function countCompromisedChunks(db: PouchDB.Database): Promise<number | false> {\n try {\n Logger(`Counting compromised chunks...`, LOG_LEVEL_VERBOSE);\n const task1 = db.find(SELECTOR_COMPROMISED_CHUNK_1);\n const task2 = db.find(SELECTOR_COMPROMISED_CHUNK_2);\n const [result1, result2] = await Promise.all([task1, task2]);\n return result1.docs.length + result2.docs.length;\n } catch (ex) {\n Logger(`Error counting compromised chunks!`, LOG_LEVEL_INFO);\n Logger(ex, LOG_LEVEL_VERBOSE);\n return false;\n }\n}\n","// Hidden items (Now means `chunk`)\nexport const CHeader = \"h:\";\n\n// Plug-in Stored Container (Obsolete)\nexport const PSCHeader = \"ps:\";\nexport const PSCHeaderEnd = \"ps;\";\n\n// Internal data Container\nexport const ICHeader = \"i:\";\nexport const ICHeaderEnd = \"i;\";\nexport const ICHeaderLength = ICHeader.length;\n\n// Internal data Container (eXtended)\nexport const ICXHeader = \"ix:\";\n","import type PouchDB from \"pouchdb-core\";\nimport type { DocumentID, EntryDoc, RemoteDBSettings } from \"@lib/common/types.ts\";\nimport { configuredIdKey } from \"@lib/common/idDerivation.ts\";\nimport { ICHeader, ICXHeader, PSCHeader } from \"@lib/common/models/fileaccess.const.ts\";\nimport { PREFIX_OBFUSCATED, type FilePathWithPrefix } from \"@lib/common/types.ts\";\n\nexport type RemoteIdCompatibility = \"matching\" | \"mismatched\" | \"unverified\";\n\n/** Check a bounded set of existing document IDs before admitting an ID configuration. */\nexport async function assessRemoteDocumentIds(\n db: PouchDB.Database<EntryDoc>,\n setting: Pick<\n RemoteDBSettings,\n | \"encrypt\"\n | \"idDerivationVersion\"\n | \"idDerivationKey\"\n | \"usePathObfuscation\"\n | \"passphrase\"\n | \"handleFilenameCaseSensitive\"\n >,\n path2id: (path: FilePathWithPrefix) => Promise<DocumentID>\n): Promise<RemoteIdCompatibility> {\n configuredIdKey(setting);\n if (!setting.encrypt || !setting.usePathObfuscation) return \"unverified\";\n let matched = false;\n\n for (const prefix of [\n PREFIX_OBFUSCATED,\n `${ICHeader}${PREFIX_OBFUSCATED}`,\n `${ICXHeader}${PREFIX_OBFUSCATED}`,\n `${PSCHeader}${PREFIX_OBFUSCATED}`,\n ]) {\n const rows = await db.allDocs({ startkey: prefix, endkey: `${prefix}\\ufff0`, limit: 2 });\n for (const row of rows.rows) {\n if (\"error\" in row || !row.id) continue;\n const doc = await db.get(row.id);\n if (!(\"path\" in doc) || typeof doc.path !== \"string\") continue;\n const expected = await path2id(doc.path as FilePathWithPrefix);\n if (expected !== doc._id) return \"mismatched\";\n matched = true;\n }\n }\n return matched ? \"matching\" : \"unverified\";\n}\n","// @ts-types=\"npm:@types/pouchdb\"\nimport PouchDB from \"pouchdb-core\";\nimport HttpPouch from \"pouchdb-adapter-http\";\nimport mapreduce from \"pouchdb-mapreduce\";\nimport replication from \"pouchdb-replication\";\n\nimport find from \"pouchdb-find\";\nimport transform from \"transform-pouch\";\n//@ts-ignore\nimport { findPathToLeaf } from \"pouchdb-merge\";\n//@ts-ignore\nimport { adapterFun } from \"pouchdb-utils\";\n//@ts-ignore\nimport { createError, MISSING_DOC, UNKNOWN_ERROR } from \"pouchdb-errors\";\nimport { mapAllTasksWithConcurrencyLimit, unwrapTaskResult } from \"octagonal-wheels/concurrency/task\";\n\nPouchDB.plugin(HttpPouch).plugin(mapreduce).plugin(replication).plugin(find).plugin(transform);\n\ntype PurgeMultiResult = {\n ok: true;\n deletedRevs: string[];\n documentWasRemovedCompletely: boolean;\n};\ntype PurgeMultiParam = [docId: string, rev$$1: string];\nfunction appendPurgeSeqs(db: PouchDB.Database, docs: PurgeMultiParam[]) {\n return (\n db\n .get(\"_local/purges\")\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Patches to PouchDB's internal document structure, which is not typed.\n .then(function (doc: any) {\n for (const [docId, rev$$1] of docs) {\n const purgeSeq = doc.purgeSeq + 1;\n doc.purges.push({\n docId,\n rev: rev$$1,\n purgeSeq,\n });\n //@ts-ignore : missing type def\n if (doc.purges.length > db.purged_infos_limit) {\n //@ts-ignore : missing type def\n doc.purges.splice(0, doc.purges.length - db.purged_infos_limit);\n }\n doc.purgeSeq = purgeSeq;\n }\n return doc;\n })\n .catch(function (err) {\n if (err.status !== 404) {\n throw err;\n }\n return {\n _id: \"_local/purges\",\n purges: docs.map(([docId, rev$$1], idx) => ({\n docId,\n rev: rev$$1,\n purgeSeq: idx,\n })),\n purgeSeq: docs.length,\n };\n })\n .then(function (doc) {\n return db.put(doc);\n })\n );\n}\n\n/**\n * purge multiple documents at once.\n */\nPouchDB.prototype.purgeMulti = adapterFun(\n \"_purgeMulti\",\n function (\n docs: PurgeMultiParam[],\n callback: (\n error?: Error,\n result?: {\n [x: string]: PurgeMultiResult | Error;\n }\n ) => void\n ) {\n //@ts-ignore\n if (typeof this._purge === \"undefined\") {\n return callback(\n //@ts-ignore: this ts-ignore might be hiding a `this` bug where we don't have \"this\" conext.\n createError(UNKNOWN_ERROR, \"Purge is not implemented in the \" + this.adapter + \" adapter.\")\n );\n }\n //@ts-ignore\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const self = this;\n const tasks = docs.map(\n (param) => () =>\n new Promise<[PurgeMultiParam, PurgeMultiResult | Error]>((res, rej) => {\n const [docId, rev$$1] = param;\n self._getRevisionTree(docId, (error: Error, revs: string[]) => {\n if (error) {\n return res([param, error]);\n }\n if (!revs) {\n //@ts-ignore\n return res([param, createError(MISSING_DOC)]);\n }\n let path;\n try {\n path = findPathToLeaf(revs, rev$$1);\n } catch (error) {\n //@ts-ignore\n return res([param, error.message || error]);\n }\n self._purge(docId, path, (error: Error, result: PurgeMultiResult) => {\n if (error) {\n return res([param, error]);\n } else {\n return res([param, result]);\n }\n });\n });\n })\n );\n (async () => {\n const ret = await mapAllTasksWithConcurrencyLimit(1, tasks);\n const retAll = ret.map((e) => unwrapTaskResult(e)) as [PurgeMultiParam, PurgeMultiResult | Error][];\n await appendPurgeSeqs(\n self,\n retAll.filter((e) => \"ok\" in e[1]).map((e) => e[0])\n );\n const result = Object.fromEntries(retAll.map((e) => [e[0][0], e[1]]));\n return result;\n })()\n //@ts-ignore\n .then((result) => callback(undefined, result))\n .catch((error) => callback(error));\n }\n);\n\nexport { PouchDB };\n","import { delay, promiseWithResolvers } from \"octagonal-wheels/promises\";\nimport { unique } from \"octagonal-wheels/collection\";\nimport { LOG_LEVEL_VERBOSE, Logger } from \"@lib/common/logger.ts\";\nimport { DEFAULT_SETTINGS, type DocumentID, type EntryLeaf } from \"@lib/common/types.ts\";\n\nimport { type ChunkManager } from \"./ChunkManager.ts\";\n\nimport type { IReplicatorService, ISettingService } from \"@lib/services/base/IService.ts\";\nimport type { ReplicatorInstance } from \"@lib/replication/ReplicatorInstance.ts\";\nimport { compatGlobal } from \"@lib/common/coreEnvFunctions.ts\";\nimport { DEFAULT_CHUNK_DELIVERY_STALL_TIMEOUT_MS, type ChunkDeliveryClaim } from \"./ChunkDeliveryCoordinator.ts\";\nimport { chunkFetchCounts, collectingChunks } from \"@lib/mock_and_interop/stores\";\nimport {\n classifyFetchedChunks,\n decideMissingChunkAction,\n type FetchedChunkClassification,\n} from \"./chunkFetcher.helper.ts\";\n\nexport const EVENT_MISSING_CHUNKS = \"missingChunks\";\nexport const EVENT_MISSING_CHUNK_REMOTE = \"missingChunkRemote\";\nexport const EVENT_CHUNK_FETCHED = \"chunkFetched\"; // Event for chunk arrival\nexport type ChunkFetcherOptions = {\n settingService: ISettingService;\n chunkManager: ChunkManager;\n replicatorService: IReplicatorService;\n deliveryStallTimeoutMs?: number;\n};\nconst BATCH_SIZE = 100; // Number of chunks to fetch in one request\n\ntype PendingChunkDelivery = {\n activityBoundaryEntered: Promise<boolean>;\n claim: ChunkDeliveryClaim;\n resolveActivityBoundary: (entered: boolean) => void;\n};\n\ntype PendingChunkFetch = {\n delivery: PendingChunkDelivery;\n missingResponses: number;\n nextRequestAt: number;\n inFlight: boolean;\n};\n\ninterface RemoteChunkReader extends ReplicatorInstance {\n fetchRemoteChunks(missingChunks: string[], showResult: boolean): Promise<false | EntryLeaf[]>;\n}\n\nfunction canFetchRemoteChunks(replicator: ReplicatorInstance): replicator is RemoteChunkReader {\n return \"fetchRemoteChunks\" in replicator && typeof replicator.fetchRemoteChunks === \"function\";\n}\n\nexport class ChunkFetcher {\n options: ChunkFetcherOptions;\n get chunkManager(): ChunkManager {\n return this.options.chunkManager;\n }\n\n queue = [] as DocumentID[];\n private readonly pendingClaims = new Map<DocumentID, PendingChunkFetch>();\n private reportedPendingCount = 0;\n private reportedFetchCounts = { initial: 0, retrying: 0 };\n private requestTimer: number | undefined;\n private requestTimerDueAt = 0;\n private finiteActivityWasActive: boolean;\n private finiteCompletionVersion = 0;\n private readonly stopObservingDelivery: () => void;\n private destroyed = false;\n\n get interval(): number {\n const settings = this.options.settingService.currentSettings();\n return settings.minimumIntervalOfReadChunksOnline || DEFAULT_SETTINGS.minimumIntervalOfReadChunksOnline;\n }\n\n get concurrency(): number {\n const settings = this.options.settingService.currentSettings();\n return settings.concurrencyOfReadChunksOnline || DEFAULT_SETTINGS.concurrencyOfReadChunksOnline;\n }\n\n abort: AbortController = new AbortController();\n constructor(options: ChunkFetcherOptions) {\n this.options = options;\n this.finiteActivityWasActive = this.chunkManager.deliveryCoordinator.isFiniteReplicationActive();\n this.stopObservingDelivery = this.chunkManager.deliveryCoordinator.onChanged(() => {\n const active = this.chunkManager.deliveryCoordinator.isFiniteReplicationActive();\n const completed = this.finiteActivityWasActive && !active;\n this.finiteActivityWasActive = active;\n if (!completed) return;\n this.finiteCompletionVersion++;\n for (const pending of this.pendingClaims.values()) {\n if (pending.missingResponses > 0 && !pending.inFlight) pending.nextRequestAt = Date.now();\n }\n this.scheduleRequest();\n });\n // TODO: Confirm whether this is correctly dereferenced upon instance re-creation. EventTarget may handle this safely.\n this.chunkManager.addListener(EVENT_MISSING_CHUNKS, this.onEventHandler, {\n signal: this.abort.signal,\n });\n }\n destroy(): void {\n if (this.destroyed) return;\n this.destroyed = true;\n this.abort.abort(); // Stop accepting missing-chunk events.\n this.stopObservingDelivery();\n this.clearRequestTimer();\n this.queue = []; // Clear the queue.\n const pendingDeliveries = new Set([...this.pendingClaims.values()].map((pending) => pending.delivery));\n this.pendingClaims.clear();\n this.updatePendingCount();\n for (const pending of pendingDeliveries) {\n pending.resolveActivityBoundary(false);\n pending.claim.release();\n }\n }\n onEventHandler = this.onEvent.bind(this);\n\n onEvent(ids: DocumentID[]): void {\n if (this.destroyed) return;\n const claimedIds = this.ensureClaims(ids);\n this.queue = unique([...this.queue, ...claimedIds]);\n this.scheduleRequest(1);\n }\n\n private clearRequestTimer(): void {\n if (this.requestTimer !== undefined) compatGlobal.clearTimeout(this.requestTimer);\n this.requestTimer = undefined;\n }\n\n private scheduleRequest(minimumDelayMs = 0): void {\n if (this.destroyed || this.currentProcessing >= this.concurrency || this.queue.length === 0) {\n this.clearRequestTimer();\n return;\n }\n let nextRequestAt = Infinity;\n for (const id of this.queue) {\n const pending = this.pendingClaims.get(id);\n if (!pending?.inFlight) nextRequestAt = Math.min(nextRequestAt, pending?.nextRequestAt ?? 0);\n }\n if (nextRequestAt === Infinity) {\n this.clearRequestTimer();\n return;\n }\n const now = Date.now();\n const dueAt = Math.max(nextRequestAt, now + minimumDelayMs);\n if (this.requestTimer !== undefined && this.requestTimerDueAt <= dueAt) return;\n this.clearRequestTimer();\n this.requestTimerDueAt = dueAt;\n this.requestTimer = compatGlobal.setTimeout(() => {\n this.requestTimer = undefined;\n void this.requestMissingChunks();\n }, dueAt - now);\n }\n\n private ensureClaims(ids: readonly DocumentID[]): DocumentID[] {\n const unclaimedIds = unique(ids.filter((id) => !this.pendingClaims.has(id)));\n if (unclaimedIds.length === 0) return [];\n\n let pending!: PendingChunkDelivery;\n const activityBoundary = promiseWithResolvers<boolean>();\n const claim = this.chunkManager.deliveryCoordinator.claim(unclaimedIds, {\n stallTimeoutMs: this.options.deliveryStallTimeoutMs ?? DEFAULT_CHUNK_DELIVERY_STALL_TIMEOUT_MS,\n onStalled: (stalledIds) => this.onClaimStalled(pending, stalledIds),\n });\n pending = {\n activityBoundaryEntered: activityBoundary.promise,\n claim,\n resolveActivityBoundary: activityBoundary.resolve,\n };\n for (const id of unclaimedIds) {\n this.pendingClaims.set(id, { delivery: pending, missingResponses: 0, nextRequestAt: 0, inFlight: false });\n }\n this.updatePendingCount();\n void this.options.replicatorService\n .runBoundedRemoteActivity(\n () => {\n pending.claim.touch();\n pending.resolveActivityBoundary(true);\n return claim.done;\n },\n { label: \"chunk-fetch\" }\n )\n .catch((error) => {\n const abandonedIds = claim.pendingIds;\n pending.resolveActivityBoundary(false);\n this.removePendingDelivery(pending, abandonedIds);\n claim.release();\n Logger(\"The chunk-delivery activity runner rejected before the claim settled.\", LOG_LEVEL_VERBOSE);\n Logger(error, LOG_LEVEL_VERBOSE);\n });\n return unclaimedIds;\n }\n\n private removePendingDelivery(pending: PendingChunkDelivery, ids: readonly DocumentID[]): void {\n for (const id of ids) {\n if (this.pendingClaims.get(id)?.delivery === pending) {\n this.pendingClaims.delete(id);\n }\n }\n const removed = new Set(ids);\n this.queue = this.queue.filter((id) => !(removed.has(id) && !this.pendingClaims.has(id)));\n this.updatePendingCount();\n this.scheduleRequest();\n }\n\n private updatePendingCount(): void {\n const nextCount = this.pendingClaims.size;\n const difference = nextCount - this.reportedPendingCount;\n // Record this fetcher's contribution before subscribers can re-enter it.\n this.reportedPendingCount = nextCount;\n if (difference !== 0) collectingChunks.value += difference;\n const nextFetchCounts = { initial: 0, retrying: 0 };\n for (const pending of this.pendingClaims.values()) {\n if (pending.missingResponses > 0) nextFetchCounts.retrying++;\n else nextFetchCounts.initial++;\n }\n const initialDifference = nextFetchCounts.initial - this.reportedFetchCounts.initial;\n const retryingDifference = nextFetchCounts.retrying - this.reportedFetchCounts.retrying;\n this.reportedFetchCounts = nextFetchCounts;\n if (initialDifference !== 0 || retryingDifference !== 0) {\n chunkFetchCounts.value = {\n initial: chunkFetchCounts.value.initial + initialDifference,\n retrying: chunkFetchCounts.value.retrying + retryingDifference,\n };\n }\n }\n\n private onClaimStalled(pending: PendingChunkDelivery, stalledIds: readonly DocumentID[]): void {\n pending.resolveActivityBoundary(false);\n this.removePendingDelivery(pending, stalledIds);\n Logger(`Chunk delivery stalled for the following IDs: ${stalledIds.join(\", \")}`, LOG_LEVEL_VERBOSE);\n }\n\n private settleClaim(id: DocumentID, pending: PendingChunkFetch | undefined): void {\n if (!pending || this.pendingClaims.get(id) !== pending) return;\n this.pendingClaims.delete(id);\n pending.delivery.claim.settle(id);\n this.updatePendingCount();\n }\n\n private getActiveClaimIds(\n ids: readonly DocumentID[],\n claims: ReadonlyMap<DocumentID, PendingChunkFetch>\n ): DocumentID[] {\n return ids.filter((id) => claims.has(id) && this.pendingClaims.get(id) === claims.get(id));\n }\n\n private touchClaims(ids: readonly DocumentID[], claims: ReadonlyMap<DocumentID, PendingChunkFetch>): void {\n const pendingDeliveries = new Set(this.getActiveClaimIds(ids, claims).map((id) => claims.get(id)!.delivery));\n for (const pending of pendingDeliveries) {\n pending.claim.touch();\n }\n }\n\n private async waitForActivityBoundary(claims: ReadonlyMap<DocumentID, PendingChunkFetch>): Promise<DocumentID[]> {\n const pendingDeliveries = new Set([...claims.values()].map((pending) => pending.delivery));\n const entered = new Map(\n await Promise.all(\n [...pendingDeliveries].map(async (pending) => [pending, await pending.activityBoundaryEntered] as const)\n )\n );\n return [...claims].flatMap(([id, pending]) =>\n this.pendingClaims.get(id) === pending && entered.get(pending.delivery) === true ? [id] : []\n );\n }\n\n private async waitBeforeRemoteRequest(\n ids: readonly DocumentID[],\n claims: ReadonlyMap<DocumentID, PendingChunkFetch>,\n localCheckCompletionVersion: number\n ): Promise<DocumentID[]> {\n this.touchClaims(ids, claims);\n while (!this.destroyed) {\n const activeIds = this.getActiveClaimIds(ids, claims);\n if (activeIds.length === 0) return [];\n if (localCheckCompletionVersion !== this.finiteCompletionVersion) {\n localCheckCompletionVersion = this.finiteCompletionVersion;\n await this.resolveLocallyAvailableRetries(claims);\n continue;\n }\n\n const now = Date.now();\n const timeToWait = this.previousRequestTime + this.interval - now;\n // An interval at or above the claim's inactivity fuse is exceptional;\n // the safety valve may release logical ownership before this pause ends.\n if (timeToWait > 0) {\n await delay(timeToWait);\n continue;\n }\n // Reserve the start before yielding, so other waiting requests recheck against it.\n this.previousRequestTime = now;\n this.touchClaims(activeIds, claims);\n return activeIds;\n }\n return [];\n }\n\n private async resolveLocallyAvailableRetries(claims: ReadonlyMap<DocumentID, PendingChunkFetch>): Promise<void> {\n const retryIds = this.getActiveClaimIds([...claims.keys()], claims).filter(\n (id) => claims.get(id)!.missingResponses > 0\n );\n if (retryIds.length === 0) return;\n const localChunks = await this.chunkManager.read(retryIds, {\n preventRemoteRequest: true,\n skipCache: true,\n waitForDelivery: false,\n });\n for (const chunk of localChunks) {\n if (!chunk) continue;\n this.chunkManager.emitEvent(EVENT_CHUNK_FETCHED, chunk);\n this.settleClaim(chunk._id, claims.get(chunk._id));\n }\n }\n\n private logFetchedChunks(\n requestedIds: readonly DocumentID[],\n { chunks, invalidChunks }: FetchedChunkClassification\n ): void {\n if (invalidChunks.length > 0) {\n Logger(\n `Some fetched chunks are invalid and will be ignored: (${invalidChunks.length} / ${chunks.length + invalidChunks.length}).`,\n LOG_LEVEL_VERBOSE\n );\n for (const chunk of invalidChunks) {\n Logger(`Invalid chunk: ${JSON.stringify(chunk)}`, LOG_LEVEL_VERBOSE);\n }\n }\n if (chunks.length === 0) {\n Logger(`No valid chunks were found for the following IDs: ${requestedIds.join(\", \")}`);\n }\n }\n\n private applyMissingChunkResults(\n missingIds: readonly DocumentID[],\n requestClaims: ReadonlyMap<DocumentID, PendingChunkFetch>,\n requestCompletionVersion: number\n ): void {\n for (const chunkID of this.getActiveClaimIds(missingIds, requestClaims)) {\n const pending = requestClaims.get(chunkID)!;\n const completedDuringRequest = requestCompletionVersion !== this.finiteCompletionVersion;\n const action = decideMissingChunkAction({\n missingResponses: pending.missingResponses,\n finiteReplicationActive: this.chunkManager.deliveryCoordinator.isFiniteReplicationActive(),\n completedDuringRequest,\n });\n if (action.kind === \"missing\") {\n this.chunkManager.emitEvent(EVENT_MISSING_CHUNK_REMOTE, chunkID);\n this.settleClaim(chunkID, pending);\n } else {\n pending.missingResponses = action.missingResponses;\n pending.inFlight = false;\n pending.nextRequestAt = Date.now() + action.delayMs;\n this.queue.push(chunkID);\n Logger(\n `Remote chunk is not available yet; retrying ${chunkID} in ${action.delayMs} ms.`,\n LOG_LEVEL_VERBOSE\n );\n }\n }\n this.updatePendingCount();\n }\n\n /**\n * Processing requests\n */\n currentProcessing = 0;\n /**\n * Time of the last request to the remote server.\n * This is used to manage the interval between requests.\n * Even if concurrency allows, every start of a request will ensure that the interval is respected.\n */\n previousRequestTime = 0;\n\n canRequestMore(): boolean {\n return this.currentProcessing < this.concurrency && this.queue.some((id) => this.isReady(id));\n }\n\n private isReady(id: DocumentID): boolean {\n const pending = this.pendingClaims.get(id);\n return !pending || (!pending.inFlight && pending.nextRequestAt <= Date.now());\n }\n\n async requestMissingChunks(): Promise<void> {\n if (this.destroyed || !this.canRequestMore()) {\n // The timer's earliest identifier may have expired while later retries remain queued.\n this.scheduleRequest();\n return;\n }\n let requestIDs: DocumentID[] = [];\n const requestClaims = new Map<DocumentID, PendingChunkFetch>();\n try {\n this.currentProcessing++;\n requestIDs = unique(this.queue.filter((id) => this.isReady(id))).slice(0, BATCH_SIZE);\n const selectedIds = new Set(requestIDs);\n this.queue = this.queue.filter((id) => !selectedIds.has(id));\n this.ensureClaims(requestIDs);\n for (const id of requestIDs) {\n const pending = this.pendingClaims.get(id);\n if (pending) {\n pending.inFlight = true;\n requestClaims.set(id, pending);\n }\n }\n this.scheduleRequest();\n requestIDs = await this.waitForActivityBoundary(requestClaims);\n if (requestIDs.length === 0) return;\n\n const localCheckCompletionVersion = this.finiteCompletionVersion;\n await this.resolveLocallyAvailableRetries(requestClaims);\n let pendingIDs = await this.waitBeforeRemoteRequest(requestIDs, requestClaims, localCheckCompletionVersion);\n if (pendingIDs.length === 0) return;\n\n const replicator = this.options.replicatorService.getActiveReplicator();\n if (!replicator) {\n Logger(\"No active replicator was found to request missing chunks.\");\n return;\n }\n if (!canFetchRemoteChunks(replicator)) {\n Logger(\"The active replicator does not support fetching individual remote chunks.\");\n for (const chunkID of pendingIDs) {\n this.chunkManager.emitEvent(EVENT_MISSING_CHUNK_REMOTE, chunkID);\n }\n return;\n }\n // A lookup begun before the latest finite completion cannot be the final probe.\n const requestCompletionVersion = this.finiteCompletionVersion;\n const fetched = await replicator.fetchRemoteChunks(pendingIDs, false);\n pendingIDs = this.getActiveClaimIds(pendingIDs, requestClaims);\n this.touchClaims(pendingIDs, requestClaims);\n if (!fetched) {\n Logger(`No chunks were found for the following IDs: ${pendingIDs.join(\", \")}`);\n for (const chunkID of pendingIDs) {\n this.chunkManager.emitEvent(EVENT_MISSING_CHUNK_REMOTE, chunkID);\n }\n return;\n }\n const classification = classifyFetchedChunks(pendingIDs, fetched);\n this.logFetchedChunks(pendingIDs, classification);\n const { chunks, missingIds, invalidIds } = classification;\n try {\n if (chunks.length > 0) {\n Logger(`Writing fetched chunks (${chunks.length}) to the database...`);\n const result = await this.chunkManager.write(\n chunks,\n {\n skipCache: true,\n force: true, // Force writing to ensure the chunks with existing _rev.\n },\n \"ChunkFetcher\" as DocumentID\n );\n this.touchClaims(pendingIDs, requestClaims);\n if (result.result === true) {\n Logger(`Fetched chunks were stored successfully: ${chunks.length}`, LOG_LEVEL_VERBOSE);\n } else {\n Logger(\n `Fetched chunks could not be stored: ${chunks.map((chunk) => chunk._id).join(\", \")}`,\n LOG_LEVEL_VERBOSE\n );\n }\n }\n } catch (error) {\n Logger(`An error occurred while storing fetched chunks!`, LOG_LEVEL_VERBOSE);\n Logger(error, LOG_LEVEL_VERBOSE);\n } finally {\n // Emitting fetched chunks regardless of write success preserves the existing refetch behaviour.\n for (const chunk of chunks) {\n this.chunkManager.emitEvent(EVENT_CHUNK_FETCHED, chunk);\n this.settleClaim(chunk._id, requestClaims.get(chunk._id));\n }\n for (const invalidID of this.getActiveClaimIds(invalidIds, requestClaims)) {\n this.chunkManager.emitEvent(EVENT_MISSING_CHUNK_REMOTE, invalidID);\n this.settleClaim(invalidID, requestClaims.get(invalidID));\n }\n }\n\n this.applyMissingChunkResults(missingIds, requestClaims, requestCompletionVersion);\n } catch (error) {\n Logger(\"An error occurred while fetching remote chunks.\", LOG_LEVEL_VERBOSE);\n Logger(error, LOG_LEVEL_VERBOSE);\n } finally {\n for (const [id, pending] of requestClaims) {\n if (pending.inFlight) this.settleClaim(id, pending);\n }\n this.currentProcessing--;\n this.previousRequestTime = Date.now();\n this.scheduleRequest();\n }\n }\n}\n","import type { ReactiveSource } from \"octagonal-wheels/dataobject/reactive\";\nimport { promiseWithResolvers } from \"octagonal-wheels/promises\";\nimport { compatGlobal } from \"@lib/common/coreEnvFunctions\";\nimport type { DocumentID } from \"@lib/common/types\";\n\n/**\n * A last-resort leak fuse for an accepted delivery claim which reports no\n * observable progress. It releases logical ownership so a waiter, and an\n * entered bounded activity with its Wake Lock and indicator, cannot be retained\n * forever by a stalled transport or never-settling Promise.\n *\n * Five minutes is a conservative operational ceiling, not a normal\n * chunk-arrival budget, evidence of remote absence, or a transport deadline.\n * The transport contract cannot yet abort the underlying request when it fires.\n */\nexport const DEFAULT_CHUNK_DELIVERY_STALL_TIMEOUT_MS = 5 * 60 * 1000;\n\nexport type ActivityCountSource = Pick<ReactiveSource<number>, \"value\" | \"onChanged\" | \"offChanged\">;\n\nexport type ChunkDeliveryClaimOptions = {\n stallTimeoutMs?: number;\n onStalled?: (ids: readonly DocumentID[]) => void;\n};\n\nexport type ChunkDeliveryChangeListener = (ids?: readonly DocumentID[]) => void;\n\n/** A finite claim that keeps chunk arrival waiters paused until every owned identifier settles. */\nexport interface ChunkDeliveryClaim {\n readonly done: Promise<void>;\n readonly pendingIds: readonly DocumentID[];\n release(): void;\n settle(id: DocumentID): void;\n touch(): void;\n}\n\n/**\n * Coordinates on-demand chunk ownership with broader finite remote activity.\n *\n * `ChunkFetcher` owns claims. `ArrivalWaitLayer` observes only whether an\n * identifier may still be delivered, so it does not depend on a replicator\n * service or on fetch scheduling details.\n */\nexport class ChunkDeliveryCoordinator {\n private readonly activeClaimCounts = new Map<DocumentID, number>();\n private readonly claimReleases = new Set<() => void>();\n private readonly listeners = new Set<ChunkDeliveryChangeListener>();\n private finiteActivityWasActive = false;\n private readonly finiteActivityChanged = () => {\n const active = (this.finiteReplicationActivity?.value ?? 0) > 0;\n if (active === this.finiteActivityWasActive) return;\n this.finiteActivityWasActive = active;\n this.notifyChanged();\n };\n private disposed = false;\n\n constructor(private readonly finiteReplicationActivity?: ActivityCountSource) {\n this.finiteActivityWasActive = (finiteReplicationActivity?.value ?? 0) > 0;\n this.finiteReplicationActivity?.onChanged(this.finiteActivityChanged);\n }\n\n claim(ids: readonly DocumentID[], options: ChunkDeliveryClaimOptions = {}): ChunkDeliveryClaim {\n if (this.disposed) {\n throw new Error(\"Cannot claim chunk delivery activity after the coordinator has been disposed.\");\n }\n\n const pending = new Set(ids);\n const resolver = promiseWithResolvers<void>();\n if (pending.size === 0) {\n resolver.resolve();\n return {\n done: resolver.promise,\n pendingIds: [],\n release: () => undefined,\n settle: () => undefined,\n touch: () => undefined,\n };\n }\n const stallTimeoutMs = options.stallTimeoutMs ?? DEFAULT_CHUNK_DELIVERY_STALL_TIMEOUT_MS;\n let timer: number | undefined;\n let released = false;\n\n const clearTimer = () => {\n if (timer === undefined) return;\n compatGlobal.clearTimeout(timer);\n timer = undefined;\n };\n const removeActiveIds = (activeIds: readonly DocumentID[]) => {\n for (const id of activeIds) {\n const count = this.activeClaimCounts.get(id) ?? 0;\n if (count <= 1) {\n this.activeClaimCounts.delete(id);\n } else {\n this.activeClaimCounts.set(id, count - 1);\n }\n }\n };\n const release = () => {\n if (released) return;\n released = true;\n clearTimer();\n const activeIds = [...pending];\n pending.clear();\n removeActiveIds(activeIds);\n this.claimReleases.delete(release);\n resolver.resolve();\n if (activeIds.length > 0) {\n this.notifyChanged(activeIds);\n }\n };\n const armStallTimer = () => {\n clearTimer();\n if (released || pending.size === 0 || stallTimeoutMs <= 0) return;\n timer = compatGlobal.setTimeout(() => {\n timer = undefined;\n const stalledIds = [...pending];\n release();\n options.onStalled?.(stalledIds);\n }, stallTimeoutMs);\n };\n const settle = (id: DocumentID) => {\n if (released || !pending.delete(id)) return;\n removeActiveIds([id]);\n this.notifyChanged([id]);\n if (pending.size === 0) {\n release();\n } else {\n armStallTimer();\n }\n };\n\n for (const id of pending) {\n this.activeClaimCounts.set(id, (this.activeClaimCounts.get(id) ?? 0) + 1);\n }\n this.claimReleases.add(release);\n this.notifyChanged([...pending]);\n armStallTimer();\n\n return {\n done: resolver.promise,\n get pendingIds() {\n return [...pending];\n },\n release,\n settle,\n touch: armStallTimer,\n };\n }\n\n isActivityActiveFor(id: DocumentID): boolean {\n return this.isClaimActiveFor(id) || this.isFiniteReplicationActive();\n }\n\n isClaimActiveFor(id: DocumentID): boolean {\n return this.activeClaimCounts.has(id);\n }\n\n isFiniteReplicationActive(): boolean {\n return (this.finiteReplicationActivity?.value ?? 0) > 0;\n }\n\n onChanged(listener: ChunkDeliveryChangeListener): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n this.finiteReplicationActivity?.offChanged(this.finiteActivityChanged);\n for (const release of [...this.claimReleases]) {\n release();\n }\n this.listeners.clear();\n }\n\n private notifyChanged(ids?: readonly DocumentID[]): void {\n for (const listener of this.listeners) {\n listener(ids);\n }\n }\n}\n","import { reactiveSource } from \"octagonal-wheels/dataobject/reactive\";\nimport type { LOG_LEVEL } from \"@lib/common/types.ts\";\n\nexport type LockStats = {\n pending: string[];\n running: string[];\n count: number;\n};\nexport const lockStats = reactiveSource({ pending: [], running: [], count: 0 });\nexport const collectingChunks = reactiveSource(0);\nexport const chunkFetchCounts = reactiveSource({ initial: 0, retrying: 0 });\nexport const pluginScanningCount = reactiveSource(0);\nexport const hiddenFilesProcessingCount = reactiveSource(0);\nexport const hiddenFilesEventCount = reactiveSource(0);\nexport type LogEntry = {\n message: string | Error;\n level?: LOG_LEVEL;\n key?: string;\n};\n\nexport const logMessages = reactiveSource<string[]>([]);\n","import type { DocumentID, EntryLeaf } from \"@lib/common/types.ts\";\n\nconst REMOTE_MISSING_RETRY_STEP_MS = 2_000;\nconst REMOTE_MISSING_RETRY_MAX_DELAY_MS = 10_000;\n\ntype MissingChunkAction = { kind: \"missing\" } | { kind: \"retry\"; missingResponses: number; delayMs: number };\n\nexport function decideMissingChunkAction({\n missingResponses,\n finiteReplicationActive,\n completedDuringRequest,\n}: {\n missingResponses: number;\n finiteReplicationActive: boolean;\n completedDuringRequest: boolean;\n}): MissingChunkAction {\n if (missingResponses > 0 && !finiteReplicationActive && !completedDuringRequest) {\n return { kind: \"missing\" };\n }\n const nextMissingResponses = missingResponses + 1;\n return {\n kind: \"retry\",\n missingResponses: nextMissingResponses,\n delayMs: completedDuringRequest\n ? 0\n : Math.min(nextMissingResponses * REMOTE_MISSING_RETRY_STEP_MS, REMOTE_MISSING_RETRY_MAX_DELAY_MS),\n };\n}\n\nexport type FetchedChunkClassification = {\n chunks: EntryLeaf[];\n invalidChunks: unknown[];\n missingIds: DocumentID[];\n invalidIds: DocumentID[];\n};\n\nfunction isValidChunk(chunk: unknown): chunk is EntryLeaf {\n const candidate = chunk as Partial<EntryLeaf> | null | undefined;\n return !!candidate && typeof candidate._id === \"string\" && typeof candidate.data === \"string\";\n}\n\nexport function classifyFetchedChunks(\n requestedIds: readonly DocumentID[],\n fetched: readonly unknown[]\n): FetchedChunkClassification {\n const chunks: EntryLeaf[] = [];\n const invalidChunks: unknown[] = [];\n const observedIds = new Set<DocumentID>();\n for (const chunk of fetched) {\n const candidate = chunk as Partial<EntryLeaf> | null | undefined;\n if (typeof candidate?._id === \"string\") observedIds.add(candidate._id);\n if (isValidChunk(chunk)) chunks.push(chunk);\n else invalidChunks.push(chunk);\n }\n const validIds = new Set(chunks.map((chunk) => chunk._id));\n return {\n chunks,\n invalidChunks,\n missingIds: requestedIds.filter((id) => !observedIds.has(id)),\n invalidIds: requestedIds.filter((id) => observedIds.has(id) && !validIds.has(id)),\n };\n}\n","import {\n type EntryDoc,\n type EntryLeaf,\n type Credential,\n VERSIONING_DOCID,\n type RemoteDBSettings,\n type DocumentID,\n type FilePathWithPrefix,\n type FilePath,\n type DatabaseEntry,\n LOG_LEVEL_NOTICE,\n LOG_LEVEL_VERBOSE,\n type LoadedEntry,\n type MetaEntry,\n type SavingEntry,\n type diff_result_leaf,\n SuffixDatabaseName,\n} from \"@lib/common/types.ts\";\nimport { Logger } from \"@lib/common/logger.ts\";\nimport { isErrorOfMissingDoc } from \"./utils_couchdb.ts\";\n\nimport { EVENT_CHUNK_FETCHED } from \"@lib/managers/ChunkFetcher.ts\";\nimport type { LiveSyncEventHub } from \"@lib/hub/hub.ts\";\nimport { FallbackWeakRef } from \"octagonal-wheels/common/polyfill\";\nimport { LiveSyncManagers } from \"@lib/managers/LiveSyncManagers.ts\";\nimport type { AutoMergeResult } from \"@lib/managers/ConflictManager.ts\";\nimport type { IServiceHub } from \"@lib/services/base/IService.ts\";\nimport type { ServiceContext } from \"@lib/services/base/ServiceBase.ts\";\nimport { createInstanceLogFunction, type LogFunction } from \"@lib/services/lib/logUtils.ts\";\n\nexport const REMOTE_CHUNK_FETCHED = \"remote-chunk-fetched\";\nexport type REMOTE_CHUNK_FETCHED = typeof REMOTE_CHUNK_FETCHED;\ndeclare global {\n interface LSEvents {\n [REMOTE_CHUNK_FETCHED]: EntryLeaf;\n }\n}\n\nexport type ChunkRetrievalResultSuccess = { _id: DocumentID; data: string; type: \"leaf\" };\nexport type ChunkRetrievalResultError = { _id: DocumentID; error: string };\nexport type ChunkRetrievalResult = ChunkRetrievalResultSuccess | ChunkRetrievalResultError;\nexport interface LiveSyncLocalDBEnv {\n // $$id2path(id: DocumentID, entry: EntryHasPath, stripPrefix?: boolean): FilePathWithPrefix;\n // $$path2id(filename: FilePathWithPrefix | FilePath, prefix?: string): Promise<DocumentID>;\n // $$createPouchDBInstance<T extends object>(\n // name?: string,\n // options?: PouchDB.Configuration.DatabaseConfiguration\n // ): PouchDB.Database<T>;\n\n // $allOnDBUnload(db: LiveSyncLocalDB): void;\n // $allOnDBClose(db: LiveSyncLocalDB): void;\n // $everyOnInitializeDatabase(db: LiveSyncLocalDB): Promise<boolean>;\n // $everyOnResetDatabase(db: LiveSyncLocalDB): Promise<boolean>;\n // $$getReplicator: () => LiveSyncAbstractReplicator;\n // getSettings(): RemoteDBSettings;\n // managers: LiveSyncManagers;\n services: Pick<IServiceHub, \"API\" | \"database\" | \"databaseEvents\" | \"replicator\" | \"setting\" | \"path\"> & {\n context: ServiceContext;\n };\n}\n\nexport function getNoFromRev(rev: string) {\n if (!rev) return 0;\n return parseInt(rev.split(\"-\")[0]);\n}\n\nexport type GeneratedChunk = {\n isNew: boolean;\n id: DocumentID;\n piece: string;\n};\n\nexport class LiveSyncLocalDB {\n auth: Credential;\n dbname: string;\n settings!: RemoteDBSettings;\n localDatabase!: PouchDB.Database<EntryDoc>;\n _log: LogFunction;\n\n private _managers?: LiveSyncManagers;\n get managers() {\n if (!this._managers) {\n throw new Error(\"Managers are not ready yet.\");\n }\n return this._managers;\n }\n\n isReady = false;\n\n needScanning = false;\n\n env: LiveSyncLocalDBEnv;\n\n clearCaches() {\n this._managers?.clearCaches();\n }\n\n async _prepareHashFunctions() {\n await this._managers?.prepareHashFunction();\n }\n\n refreshSettings() {\n const settings = this.env.services.setting.currentSettings();\n this.settings = settings;\n void this._prepareHashFunctions();\n }\n\n offRemoteChunkFetchedHandler?: ReturnType<LiveSyncEventHub[\"onEvent\"]>;\n private databaseCloseCleanup?: {\n database: PouchDB.Database<EntryDoc>;\n promise: Promise<void>;\n };\n /** Share owner retirement across every close path for one physical database lifetime. */\n private activeReplicationClose?: Promise<boolean>;\n private databaseUnloadNotification?: Promise<void>;\n constructor(dbname: string, env: LiveSyncLocalDBEnv) {\n this.auth = {\n username: \"\",\n password: \"\",\n };\n this.dbname = dbname;\n this.env = env;\n this._log = createInstanceLogFunction(\"LiveSyncLocalDB\", this.env.services.API);\n this.refreshSettings();\n }\n\n /** Notify dependent services at most once for each physical database lifecycle. */\n private notifyDatabaseUnload(): Promise<void> {\n if (!this.databaseUnloadNotification) {\n this.databaseUnloadNotification = Promise.resolve().then(async () => {\n await this.env.services.databaseEvents.onUnloadDatabase(this);\n });\n }\n return this.databaseUnloadNotification;\n }\n\n onunload() {\n void this.notifyDatabaseUnload();\n }\n\n async close() {\n this._log(\"Database closed (by close)\");\n this.isReady = false;\n this.offRemoteChunkFetchedHandler?.();\n this.offRemoteChunkFetchedHandler = undefined;\n await this.closeActiveReplication();\n if (this.localDatabase != null) {\n const database = this.localDatabase;\n await this.env.services.databaseEvents.onCloseDatabase(this);\n await database.close();\n if (this.databaseCloseCleanup?.database === database) {\n await this.databaseCloseCleanup.promise;\n }\n if (this.localDatabase === database) {\n this.localDatabase = null!;\n }\n }\n this._managers = undefined;\n await this.notifyDatabaseUnload();\n }\n\n private async closeActiveReplication(): Promise<boolean> {\n if (this.activeReplicationClose) {\n return await this.activeReplicationClose;\n }\n const closeOperation = this.env.services.replicator.onCloseActiveReplication();\n this.activeReplicationClose = closeOperation;\n try {\n return await closeOperation;\n } catch (error) {\n if (this.activeReplicationClose === closeOperation) {\n this.activeReplicationClose = undefined;\n }\n throw error;\n }\n }\n\n private async teardownDatabaseDependencies(managers: LiveSyncManagers): Promise<void> {\n try {\n await this.closeActiveReplication();\n } catch (error) {\n this._log(\"Failed to close replication while tearing down the local database.\", LOG_LEVEL_VERBOSE);\n this._log(error, LOG_LEVEL_VERBOSE);\n }\n try {\n await managers.teardownManagers();\n } catch (error) {\n this._log(\"Failed to tear down managers while closing the local database.\", LOG_LEVEL_VERBOSE);\n this._log(error, LOG_LEVEL_VERBOSE);\n }\n }\n\n private async rollbackFailedInitialisation(\n database: PouchDB.Database<EntryDoc>,\n managers: LiveSyncManagers\n ): Promise<void> {\n this.isReady = false;\n this.offRemoteChunkFetchedHandler?.();\n this.offRemoteChunkFetchedHandler = undefined;\n const closeCleanup = this.databaseCloseCleanup?.database === database ? this.databaseCloseCleanup : undefined;\n if (closeCleanup) {\n await closeCleanup.promise;\n } else {\n database.removeAllListeners();\n await this.teardownDatabaseDependencies(managers);\n try {\n await database.close();\n } catch (error) {\n this._log(\"Failed to close the database after its initialisation was rejected.\", LOG_LEVEL_VERBOSE);\n this._log(error, LOG_LEVEL_VERBOSE);\n }\n }\n if (this.localDatabase === database) {\n this.localDatabase = null!;\n }\n if (this._managers === managers) {\n this._managers = undefined;\n }\n try {\n await this.notifyDatabaseUnload();\n } catch (error) {\n this._log(\"A database unload handler failed after initialisation was rejected.\", LOG_LEVEL_VERBOSE);\n this._log(error, LOG_LEVEL_VERBOSE);\n }\n }\n\n onNewLeaf(chunk: EntryLeaf) {\n this.managers.chunkManager?.emitEvent(EVENT_CHUNK_FETCHED, chunk);\n }\n\n async initializeDatabase(): Promise<boolean> {\n await this._prepareHashFunctions();\n if (this.localDatabase != null) {\n this.localDatabase.removeAllListeners();\n await this.localDatabase.close();\n }\n this.localDatabase = null!;\n\n this.localDatabase = this.env.services.database.createPouchDBInstance<EntryDoc>(\n this.dbname + SuffixDatabaseName,\n {\n auto_compaction: false,\n revs_limit: 100,\n deterministic_revs: true,\n }\n );\n this.activeReplicationClose = undefined;\n this.databaseUnloadNotification = undefined;\n\n const manager = new LiveSyncManagers({\n database: this.localDatabase,\n APIService: this.env.services.API,\n pathService: this.env.services.path,\n replicatorService: this.env.services.replicator,\n settingService: this.env.services.setting,\n databaseService: this.env.services.database,\n });\n\n this._managers = manager;\n const openedDatabase = this.localDatabase;\n this.databaseCloseCleanup = undefined;\n try {\n if (!(await this.env.services.databaseEvents.onDatabaseInitialisation(this))) {\n await this.rollbackFailedInitialisation(openedDatabase, manager);\n this._log(\"Database initialisation was rejected by a required module.\", LOG_LEVEL_NOTICE);\n return false;\n }\n this._log(\"Opening Database...\");\n this._log(\"Database info\", LOG_LEVEL_VERBOSE);\n this._log(JSON.stringify(await openedDatabase.info(), null, 2), LOG_LEVEL_VERBOSE);\n await manager.initialise();\n openedDatabase.on(\"close\", () => {\n this._log(\"Database closed.\");\n this.isReady = false;\n openedDatabase.removeAllListeners();\n if (this.databaseCloseCleanup?.database !== openedDatabase) {\n this.databaseCloseCleanup = {\n database: openedDatabase,\n promise: this.teardownDatabaseDependencies(manager),\n };\n }\n });\n const _instance = new FallbackWeakRef(this);\n const unload = this.env.services.context.events.onEvent(REMOTE_CHUNK_FETCHED, (chunk: EntryLeaf) => {\n if (_instance.deref() == null) {\n unload();\n }\n _instance.deref()?.onNewLeaf(chunk);\n });\n this.offRemoteChunkFetchedHandler = unload;\n this.isReady = true;\n const readyAccepted = await this.env.services.databaseEvents.onDatabaseHasReady();\n if (!readyAccepted || this.localDatabase !== openedDatabase || !this.isReady) {\n await this.rollbackFailedInitialisation(openedDatabase, manager);\n this._log(\n \"Some module has prevented the database from being ready. The database is initialised but not ready for use.\",\n LOG_LEVEL_NOTICE\n );\n return false;\n }\n this._log(\"Database is now ready.\");\n return true;\n } catch (error) {\n await this.rollbackFailedInitialisation(openedDatabase, manager);\n throw error;\n }\n }\n\n /**\n * Retrieve all used and existing chunks in the database.\n * @param includeDeleted include deleted chunks in the result.\n * @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.\n */\n async allChunks(includeDeleted = false): Promise<{\n used: Set<string>;\n existing: Map<string, EntryLeaf>;\n }> {\n const used = new Set<string>();\n const existing = new Map<string, EntryLeaf>();\n let since = 0 as string | number;\n do {\n const changes = await this.localDatabase.changes({\n since: since,\n limit: 100,\n include_docs: true,\n conflicts: true,\n style: includeDeleted ? \"all_docs\" : \"main_only\",\n });\n if (changes.results.length == 0) {\n break;\n }\n for (const change of changes.results) {\n // console.log(`${change.seq}: ${change.id} ${change.deleted ? \"deleted\" : \"\"}`);\n const doc = change.doc as EntryDoc | EntryLeaf;\n if (doc.type == \"leaf\") {\n if (doc._deleted) {\n if (!includeDeleted) {\n continue;\n }\n }\n existing.set(doc._id, doc);\n }\n if (\"children\" in doc) {\n if (change.deleted) {\n if (!doc._conflicts || doc._conflicts.length == 0) {\n continue;\n }\n }\n doc.children.forEach((e: string) => used.add(e));\n if (doc._conflicts) {\n const revs = await this.localDatabase.get(doc._id, { revs: true, revs_info: true });\n const mineRevInfo = revs._revs_info || [];\n // Collect all revs that should be kept.\n // (All revs that are conflicted and its history before the maximum not conflicted rev).\n const keepRevs = new Set<string>();\n for (const conflict of doc._conflicts) {\n const conflictedRevs = await this.localDatabase.get(doc._id, {\n rev: conflict,\n revs: true,\n revs_info: true,\n });\n const conflictedRevInfo = conflictedRevs._revs_info || [];\n const diffRevs = mineRevInfo.filter(\n (e) => !conflictedRevInfo.some((f) => f.rev == e.rev && f.status == e.status)\n );\n const diffRevs2 = conflictedRevInfo.filter(\n (e) => !mineRevInfo.some((f) => f.rev == e.rev && f.status == e.status)\n );\n const diffRevs3 = diffRevs.concat(diffRevs2);\n const sameRevs = mineRevInfo\n .filter((e) => conflictedRevInfo.some((f) => f.rev == e.rev && f.status == e.status))\n .filter((e) => e.status == \"available\")\n .sort((a, b) => getNoFromRev(b.rev) - getNoFromRev(a.rev));\n const sameRevsTop = sameRevs.length > 0 ? [sameRevs[0].rev] : [];\n const keepRevList = [\n ...diffRevs3.filter((e) => e.status == \"available\").map((e) => e.rev),\n ...sameRevsTop,\n ];\n keepRevList.forEach((e) => keepRevs.add(e));\n }\n const detail = await this.localDatabase.bulkGet<EntryDoc>({\n docs: [...keepRevs.values()].map((e) => ({ id: doc._id, rev: e })),\n });\n for (const e of detail.results) {\n if (\"docs\" in e) {\n const docs = e.docs;\n for (const doc of docs) {\n if (\"ok\" in doc) {\n if (\"children\" in doc.ok) {\n doc.ok.children.forEach((e: string) => used.add(e));\n }\n }\n }\n }\n }\n }\n }\n }\n since = changes.results[changes.results.length - 1].seq;\n } while (true);\n return { used, existing };\n }\n\n async resetDatabase() {\n this.isReady = false;\n await this.closeActiveReplication();\n if (!(await this.env.services.databaseEvents.onResetDatabase(this))) {\n Logger(\"Database reset has been prevented or failed on some modules.\", LOG_LEVEL_NOTICE);\n return false;\n }\n await this.managers.teardownManagers();\n Logger(\"Database closed for reset Database.\");\n await this.localDatabase.destroy();\n //@ts-ignore\n this.localDatabase = null;\n if (!(await this.initializeDatabase())) {\n this._log(\"Local Database could not be reinitialised after reset.\", LOG_LEVEL_NOTICE);\n return false;\n }\n this._log(\"Local Database Reset\", LOG_LEVEL_NOTICE);\n return true;\n }\n\n async *findEntries(\n startKey: string,\n endKey: string,\n opt:\n | PouchDB.Core.AllDocsWithKeyOptions\n | PouchDB.Core.AllDocsOptions\n | PouchDB.Core.AllDocsWithKeysOptions\n | PouchDB.Core.AllDocsWithinRangeOptions\n ) {\n const pageLimit = 100;\n let nextKey = startKey;\n if (endKey == \"\") endKey = \"\\u{10ffff}\";\n let req = this.allDocsRaw({ limit: pageLimit, startkey: nextKey, endkey: endKey, include_docs: true, ...opt });\n do {\n const docs = await req;\n if (docs.rows.length === 0) {\n break;\n }\n nextKey = `${docs.rows[docs.rows.length - 1].id}`;\n req = this.allDocsRaw({\n limit: pageLimit,\n skip: 1,\n startkey: nextKey,\n endkey: endKey,\n include_docs: true,\n ...opt,\n });\n for (const row of docs.rows) {\n const doc = row.doc;\n //@ts-ignore: non null by include_docs\n if (!(\"type\" in doc)) {\n continue;\n }\n if (doc.type == \"newnote\" || doc.type == \"plain\") {\n yield doc;\n }\n }\n } while (nextKey != \"\");\n }\n async *findAllDocs(\n opt?:\n | PouchDB.Core.AllDocsWithKeyOptions\n | PouchDB.Core.AllDocsOptions\n | PouchDB.Core.AllDocsWithKeysOptions\n | PouchDB.Core.AllDocsWithinRangeOptions\n ) {\n const targets = [\n () => this.findEntries(\"\", \"_\", opt ?? {}),\n () => this.findEntries(\"_\\u{10ffff}\", \"h:\", opt ?? {}),\n () => this.findEntries(`h:\\u{10ffff}`, \"\", opt ?? {}),\n ];\n for (const targetFun of targets) {\n yield* targetFun();\n }\n }\n async *findEntryNames(\n startKey: string,\n endKey: string,\n opt:\n | PouchDB.Core.AllDocsWithKeyOptions\n | PouchDB.Core.AllDocsOptions\n | PouchDB.Core.AllDocsWithKeysOptions\n | PouchDB.Core.AllDocsWithinRangeOptions\n ) {\n const pageLimit = 100;\n let nextKey = startKey;\n if (endKey == \"\") endKey = \"\\u{10ffff}\";\n let req = this.allDocsRaw({ limit: pageLimit, startkey: nextKey, endkey: endKey, ...opt });\n do {\n const docs = await req;\n if (docs.rows.length == 0) {\n nextKey = \"\";\n break;\n }\n nextKey = `${docs.rows[docs.rows.length - 1].key}`;\n req = this.allDocsRaw({ limit: pageLimit, skip: 1, startkey: nextKey, endkey: endKey, ...opt });\n for (const row of docs.rows) {\n yield row.id;\n }\n } while (nextKey != \"\");\n }\n async *findAllDocNames(\n opt?:\n | PouchDB.Core.AllDocsWithKeyOptions\n | PouchDB.Core.AllDocsOptions\n | PouchDB.Core.AllDocsWithKeysOptions\n | PouchDB.Core.AllDocsWithinRangeOptions\n ) {\n const targets = [\n () => this.findEntryNames(\"\", \"_\", opt ?? {}),\n () => this.findEntryNames(\"_\\u{10ffff}\", \"h:\", opt ?? {}),\n () => this.findEntryNames(`h:\\u{10ffff}`, \"i:\", opt ?? {}),\n () => this.findEntryNames(`i:\\u{10ffff}`, \"ix:\", opt ?? {}),\n () => this.findEntryNames(`ix:\\u{10ffff}`, \"ps:\", opt ?? {}),\n () => this.findEntryNames(`ps:\\u{10ffff}`, \"\", opt ?? {}),\n ];\n for (const targetFun of targets) {\n const target = targetFun();\n for await (const f of target) {\n if (f.startsWith(\"_\")) continue;\n if (f == VERSIONING_DOCID) continue;\n yield f;\n }\n }\n }\n async *findAllNormalDocs(\n opt?:\n | PouchDB.Core.AllDocsWithKeyOptions\n | PouchDB.Core.AllDocsOptions\n | PouchDB.Core.AllDocsWithKeysOptions\n | PouchDB.Core.AllDocsWithinRangeOptions\n ) {\n const targets = [\n () => this.findEntries(\"\", \"_\", opt ?? {}),\n () => this.findEntries(\"_\\u{10ffff}\", \"h:\", opt ?? {}),\n () => this.findEntries(`h:\\u{10ffff}`, \"i:\", opt ?? {}),\n () => this.findEntries(`i:\\u{10ffff}`, \"ix:\", opt ?? {}),\n () => this.findEntries(`ix:\\u{10ffff}`, \"ps:\", opt ?? {}),\n () => this.findEntries(`ps:\\u{10ffff}`, \"\", opt ?? {}),\n ];\n for (const targetFun of targets) {\n const target = targetFun();\n for await (const f of target) {\n if (f._id.startsWith(\"_\")) continue;\n if (f.type != \"newnote\" && f.type != \"plain\") continue;\n yield f;\n }\n }\n }\n\n async removeRevision(docId: DocumentID, revision: string): Promise<boolean> {\n try {\n const doc = await this.localDatabase.get(docId, { rev: revision });\n doc._deleted = true;\n await this.localDatabase.put(doc);\n return true;\n } catch (ex) {\n if (isErrorOfMissingDoc(ex)) {\n Logger(`Remove revision: Missing target revision, ${docId}-${revision}`, LOG_LEVEL_VERBOSE);\n }\n }\n return false;\n }\n\n getRaw<T extends EntryDoc>(\n docId: DocumentID,\n options?: PouchDB.Core.GetOptions\n ): Promise<T & PouchDB.Core.IdMeta & PouchDB.Core.GetMeta> {\n return this.localDatabase.get<T>(docId, options || {});\n }\n\n removeRaw(docId: DocumentID, revision: string, options?: PouchDB.Core.Options): Promise<PouchDB.Core.Response> {\n return this.localDatabase.remove(docId, revision, options || {});\n }\n\n putRaw<T extends EntryDoc>(doc: T, options?: PouchDB.Core.PutOptions): Promise<PouchDB.Core.Response> {\n return this.localDatabase.put(doc, options || {});\n }\n\n allDocsRaw<T extends EntryDoc | DatabaseEntry>(\n options?:\n | PouchDB.Core.AllDocsWithKeyOptions\n | PouchDB.Core.AllDocsWithKeysOptions\n | PouchDB.Core.AllDocsWithinRangeOptions\n | PouchDB.Core.AllDocsOptions\n ): Promise<PouchDB.Core.AllDocsResponse<T>> {\n return this.localDatabase.allDocs<T>(options);\n }\n\n bulkDocsRaw<T extends EntryDoc>(\n docs: Array<PouchDB.Core.PutDocument<T>>,\n options?: PouchDB.Core.BulkDocsOptions\n ): Promise<Array<PouchDB.Core.Response | PouchDB.Core.Error>> {\n return this.localDatabase.bulkDocs(docs, options || {});\n }\n\n // For compatibility\n isTargetFile(filenameSrc: string) {\n return this.managers.entryManager.isTargetFile(filenameSrc);\n }\n async getDBEntryMeta(\n path: FilePathWithPrefix | FilePath,\n opt?: PouchDB.Core.GetOptions,\n includeDeleted = false\n ): Promise<false | LoadedEntry> {\n return await this.managers.entryManager.getDBEntryMeta(path, opt, includeDeleted);\n }\n\n async getDBEntry(\n path: FilePathWithPrefix | FilePath,\n opt?: PouchDB.Core.GetOptions,\n dump = false,\n waitForReady = true,\n includeDeleted = false,\n localOnly = false\n ): Promise<false | LoadedEntry> {\n return await this.managers.entryManager.getDBEntry(path, opt, dump, waitForReady, includeDeleted, localOnly);\n }\n async getDBEntryFromMeta(\n meta: LoadedEntry | MetaEntry,\n dump = false,\n waitForReady = true,\n localOnly = false\n ): Promise<false | LoadedEntry> {\n return await this.managers.entryManager.getDBEntryFromMeta(meta, dump, waitForReady, localOnly);\n }\n async deleteDBEntry(path: FilePathWithPrefix | FilePath, opt?: PouchDB.Core.GetOptions): Promise<boolean> {\n return await this.managers.entryManager.deleteDBEntry(path, opt);\n }\n async storeDeletionAtRevision(path: FilePathWithPrefix | FilePath, baseRevision: string) {\n return await this.managers.entryManager.storeDeletionAtRevision(path, baseRevision);\n }\n async putDBEntry(note: SavingEntry, onlyChunks?: boolean, conflictBaseRev?: string) {\n return await this.managers.entryManager.putDBEntry(note, onlyChunks, conflictBaseRev);\n }\n async putDBEntryWithLiveBaseRevision(note: SavingEntry, baseRevision: string, onlyChunks?: boolean) {\n return await this.managers.entryManager.putDBEntryWithLiveBaseRevision(note, baseRevision, onlyChunks);\n }\n /** Preserve existing branches and delegate a fresh root write to the entry manager. */\n async putDBEntryAsIndependentRoot(note: SavingEntry) {\n return await this.managers.entryManager.putDBEntryAsIndependentRoot(note);\n }\n\n async getConflictedDoc(path: FilePathWithPrefix, rev: string): Promise<false | diff_result_leaf> {\n return await this.managers.conflictManager.getConflictedDoc(path, rev);\n }\n async tryAutoMerge(path: FilePathWithPrefix, enableMarkdownAutoMerge: boolean): AutoMergeResult {\n return await this.managers.conflictManager.tryAutoMerge(path, enableMarkdownAutoMerge);\n }\n}\n","import { LRUCache } from \"octagonal-wheels/memory/LRUCache\";\nimport { isPlainText } from \"@lib/string_and_binary/path.ts\";\nimport { Semaphore } from \"octagonal-wheels/concurrency/semaphore\";\nimport { arrayBufferToBase64Single, decodeBinary, writeString } from \"@lib/string_and_binary/convert.ts\";\nimport {\n type AnyEntry,\n type DatabaseEntry,\n type EntryLeaf,\n PREFIX_ENCRYPTED_CHUNK,\n PREFIX_OBFUSCATED,\n SYNCINFO_ID,\n type SyncInfo,\n type LoadedEntry,\n type SavingEntry,\n type NewEntry,\n type PlainEntry,\n type CustomRegExpSource,\n type ParsedCustomRegExp,\n type CustomRegExpSourceList,\n type ObsidianLiveSyncSettings,\n type RemoteDBSettings,\n type P2PConnectionInfo,\n type BucketSyncSetting,\n type CouchDBConnection,\n type EncryptionSettings,\n} from \"./types.ts\";\nimport { normaliseP2PConnectionPath, normaliseP2PMaxWirePayloadBytes } from \"./models/setting.p2p.ts\";\nimport { isErrorOfMissingDoc } from \"@lib/pouchdb/utils_couchdb.ts\";\nimport { replaceAll, replaceAllPairs } from \"octagonal-wheels/string\";\nexport { replaceAll, replaceAllPairs };\nimport { concatUInt8Array } from \"octagonal-wheels/binary\";\nexport { concatUInt8Array };\n\nimport { delay, fireAndForget } from \"octagonal-wheels/promises\";\nexport { delay, fireAndForget };\n\nimport { arrayToChunkedArray, unique } from \"octagonal-wheels/collection\";\nexport { arrayToChunkedArray, unique };\n\nimport { extractObject, isObjectDifferent } from \"octagonal-wheels/object\";\nexport { extractObject, isObjectDifferent };\n\nimport { sendValue, sendSignal, waitForSignal, waitForValue } from \"octagonal-wheels/messagepassing/signal\";\nexport { sendValue, sendSignal, waitForSignal, waitForValue };\n\nimport { throttle } from \"octagonal-wheels/function\";\nexport { throttle };\n\nimport type { SimpleStore } from \"octagonal-wheels/databases/SimpleStoreBase\";\nimport { BASE_IS_NEW, EVEN, TARGET_IS_NEW } from \"./models/shared.const.symbols.ts\";\nexport type { SimpleStore };\n\nexport { sizeToHumanReadable } from \"octagonal-wheels/number\";\nimport { compatGlobal } from \"./coreEnvFunctions\";\nimport { ensureError } from \"./utils.object.ts\";\n\nexport function resolveWithIgnoreKnownError<T>(p: Promise<T>, def: T): Promise<T> {\n return new Promise((res, rej) => {\n p.then(res).catch((ex) => (isErrorOfMissingDoc(ex) ? res(def) : rej(ensureError(ex))));\n });\n}\n\n// Referenced below\n// https://zenn.dev/sora_kumo/articles/539d7f6e7f3c63\nexport const Parallels = (ps = new Set<Promise<unknown>>()) => ({\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n add: (p: Promise<unknown>) => ps.add(!!p.then(() => ps.delete(p)).catch(() => ps.delete(p)) && p),\n wait: (limit: number) => ps.size >= limit && Promise.race(ps),\n all: () => Promise.all(ps),\n});\nexport async function allSettledWithConcurrencyLimit<T>(processes: Promise<T>[], limit: number) {\n const ps = Parallels();\n for (const proc of processes) {\n ps.add(proc);\n await ps.wait(limit);\n }\n (await ps.all()).forEach(() => {});\n}\n\nexport function getDocData(doc: string | string[]) {\n return typeof doc == \"string\" ? doc : doc.join(\"\");\n}\nexport function getDocDataAsArray(doc: string | string[]) {\n return typeof doc == \"string\" ? [doc] : doc;\n}\n\nexport function getDocDataAsArrayBuffer(doc: string | string[] | ArrayBuffer) {\n if (doc instanceof ArrayBuffer) return new Uint8Array(doc);\n const docData = getDocDataAsArray(doc);\n const s = docData.map((e) => writeString(e));\n return concatUInt8Array(s);\n}\n\nexport function isTextBlob(blob: Blob) {\n return blob.type === \"text/plain\";\n}\nexport function createTextBlob(data: string | string[]) {\n const d = Array.isArray(data) ? data : [data];\n return new Blob(d, { endings: \"transparent\", type: \"text/plain\" });\n}\nexport function createBinaryBlob(data: Uint8Array<ArrayBuffer> | ArrayBuffer) {\n return new Blob([data], { endings: \"transparent\", type: \"application/octet-stream\" });\n}\nexport function createBlob(data: string | string[] | Uint8Array<ArrayBuffer> | ArrayBuffer | Blob) {\n if (data instanceof Blob) return data;\n if (data instanceof Uint8Array || data instanceof ArrayBuffer) return createBinaryBlob(data);\n return createTextBlob(data);\n}\n\nexport function isTextDocument(doc: LoadedEntry) {\n if (doc.type == \"plain\") return true;\n if (doc.datatype == \"plain\") return true;\n if (isPlainText(doc.path)) return true;\n return false;\n}\n\nexport function readAsBlob(doc: LoadedEntry) {\n if (isTextDocument(doc)) {\n return createTextBlob(doc.data);\n } else {\n return createBinaryBlob(decodeBinary(doc.data));\n }\n}\nexport function readContent(doc: LoadedEntry) {\n if (isTextDocument(doc)) {\n return getDocData(doc.data);\n } else {\n return decodeBinary(doc.data);\n }\n}\n\nconst isIndexDBCmpExist = typeof compatGlobal?.indexedDB?.cmp !== \"undefined\";\n\nexport async function isDocContentSame(\n docA: string | string[] | Blob | ArrayBuffer,\n docB: string | string[] | Blob | ArrayBuffer\n) {\n const blob1 = createBlob(docA);\n const blob2 = createBlob(docB);\n if (blob1.size != blob2.size) return false;\n if (isIndexDBCmpExist) {\n return compatGlobal.indexedDB.cmp(await blob1.arrayBuffer(), await blob2.arrayBuffer()) === 0;\n }\n const checkQuantum = 10000;\n const length = blob1.size;\n\n let i = 0;\n\n while (i < length) {\n const ab1 = await blob1.slice(i, i + checkQuantum).arrayBuffer();\n const ab2 = await blob2.slice(i, i + checkQuantum).arrayBuffer();\n i += checkQuantum;\n if ((await arrayBufferToBase64Single(ab1)) != (await arrayBufferToBase64Single(ab2))) return false;\n }\n return true;\n}\n\nexport function isObfuscatedEntry(doc: DatabaseEntry): doc is AnyEntry {\n if (doc._id.startsWith(PREFIX_OBFUSCATED)) {\n return true;\n }\n return false;\n}\n\nexport function isEncryptedChunkEntry(doc: DatabaseEntry): doc is EntryLeaf {\n if (doc._id.startsWith(PREFIX_ENCRYPTED_CHUNK)) {\n return true;\n }\n return false;\n}\n\nexport function isSyncInfoEntry(doc: DatabaseEntry): doc is SyncInfo {\n if (doc._id == SYNCINFO_ID) {\n return true;\n }\n return false;\n}\n\nexport function memorizeFuncWithLRUCache<T, U>(func: (key: T) => U) {\n const cache = new LRUCache<T, U>(100, 100000, true);\n return (key: T) => {\n const isExists = cache.has(key);\n if (isExists) return cache.get(key);\n const value = func(key);\n cache.set(key, value);\n return value;\n };\n}\n\nexport function memorizeFuncWithLRUCacheMulti<T extends unknown[], U>(func: (...keys: T) => U) {\n const cache = new LRUCache<string, U>(100, 100000, true);\n return (keys: T) => {\n const theKey = keys\n .map((e) =>\n typeof e == \"string\" || typeof e == \"number\" || typeof e == \"boolean\" ? e.toString() : JSON.stringify(e)\n )\n .join(\"-\");\n const isExists = cache.has(theKey);\n if (isExists) return cache.get(theKey);\n const value = func(...keys);\n cache.set(theKey, value);\n return value;\n };\n}\n\n/**\n *\n * @param exclusion return only not exclusion\n * @returns\n *\n * [\"something\",false,\"aaaaa\"].filter(onlyNot(false)) => yields [\"something\",\"aaaaaa\"]. but, as string[].\n */\nexport function onlyNot<A, B>(exclusion: B) {\n function _onlyNot(item: A | B): item is Exclude<A, B> {\n if (item === exclusion) return false;\n return true;\n }\n return _onlyNot;\n}\n\nconst lastProcessed = {} as Record<string, number>;\nfunction markInterval(key: string, now?: number) {\n const next = now ?? Date.now();\n if (lastProcessed?.[key] ?? 0 < next) {\n lastProcessed[key] = next;\n }\n}\n/**\n * Run task with keeping minimum interval\n * @param key waiting key\n * @param interval interval (ms)\n * @param task task to perform.\n * @returns result of task\n * @remarks This function is not designed to be concurrent.\n */\nexport async function runWithInterval<T>(key: string, interval: number, task: () => Promise<T>): Promise<T> {\n const now = Date.now();\n try {\n if (!(key in lastProcessed)) {\n markInterval(key, now);\n return await task();\n }\n\n const last = lastProcessed[key];\n const diff = now - last;\n if (diff < interval) {\n markInterval(key, now);\n await delay(diff);\n }\n markInterval(key);\n return await task();\n } finally {\n markInterval(key);\n }\n}\n\n/**\n * Run task with keeping minimum interval on start\n * @param key waiting key\n * @param interval interval (ms)\n * @param task task to perform.\n * @returns result of task\n * @remarks This function is not designed to be concurrent.\n */\nexport async function runWithStartInterval<T>(key: string, interval: number, task: () => Promise<T>): Promise<T> {\n const now = Date.now();\n if (!(key in lastProcessed)) {\n markInterval(key, now);\n return await task();\n }\n\n const last = lastProcessed[key];\n const diff = now - last;\n if (diff < interval) {\n markInterval(key, now);\n await delay(diff);\n }\n markInterval(key);\n return await task();\n}\n\nexport const globalConcurrencyController = Semaphore(50);\n\nexport function determineTypeFromBlob(data: Blob): \"newnote\" | \"plain\" {\n return isTextBlob(data) ? \"plain\" : \"newnote\";\n}\n\n/**\n * Whether remediation mode is active.\n *\n * While a modification-time limit is configured, Commonlib refuses every reconciliation scan\n * between the storage and the local database and keeps storage events unqueued, so that a state\n * being recovered is not overwritten by the current one. A host therefore stays unready while the\n * limit is configured, because readiness depends upon that refused scan. Applying the limit to the\n * documents which arrive is the responsibility of the host.\n * @param settings Settings to inspect\n * @returns `true` when a modification-time limit is configured.\n */\nexport function isRemediationModeActive(settings: Pick<ObsidianLiveSyncSettings, \"maxMTimeForReflectEvents\">): boolean {\n return (settings.maxMTimeForReflectEvents ?? 0) > 0;\n}\n\nexport function determineType(\n path: string,\n data: string | string[] | Uint8Array | ArrayBuffer | Blob\n): \"newnote\" | \"plain\" {\n if (data instanceof Blob) {\n return determineTypeFromBlob(data);\n }\n if (isPlainText(path)) return \"plain\";\n if (data instanceof Uint8Array) return \"newnote\";\n if (data instanceof ArrayBuffer) return \"newnote\";\n // string | string[]\n return \"plain\";\n}\n\nexport function isAnyNote(doc: DatabaseEntry): doc is NewEntry | PlainEntry {\n return \"type\" in doc && (doc.type == \"newnote\" || doc.type == \"plain\");\n}\nexport function isLoadedEntry(doc: DatabaseEntry): doc is LoadedEntry {\n return \"type\" in doc && (doc.type == \"newnote\" || doc.type == \"plain\") && \"data\" in doc;\n}\n\nexport function isDeletedEntry(doc: LoadedEntry): boolean {\n return doc._deleted || doc.deleted || false;\n}\nexport function createSavingEntryFromLoadedEntry(doc: LoadedEntry): SavingEntry {\n const data = readAsBlob(doc);\n const type = determineType(doc.path, data);\n return {\n ...doc,\n data: data,\n datatype: type,\n type,\n children: [],\n };\n}\n\nexport function setAllItems<T>(set: Set<T>, items: T[]) {\n items.forEach((e) => set.add(e));\n return set;\n}\n\nconst map = {\n \"\\n\": \"\\\\n\",\n \"\\r\": \"\\\\r\",\n \"\\\\\": \"\\\\\\\\\",\n} as Record<string, string>;\nconst revMap = {\n \"\\\\n\": \"\\n\",\n \"\\\\r\": \"\\r\",\n \"\\\\\\\\\": \"\\\\\",\n} as Record<string, string>;\nexport function escapeNewLineFromString(str: string) {\n if (str.indexOf(\"\\n\") === -1 && str.indexOf(\"\\r\") === -1) {\n return str;\n }\n const p = str.replace(/(\\n|\\r|\\\\)/g, (m) => `${map[m]}`);\n return \"\\\\f\" + p;\n}\n\nexport function unescapeNewLineFromString(str: string) {\n if (!str.startsWith(\"\\\\f\")) {\n return str;\n }\n const p = str.substring(2).replace(/(\\\\n|\\\\r|\\\\\\\\)/g, (m) => `${revMap[m]}`);\n return p;\n}\n\nexport function escapeMarkdownValue<T>(value: T): T {\n if (typeof value === \"string\") {\n return replaceAllPairs(value, [\"|\", \"\\\\|\"], [\"`\", \"\\\\`\"]) as unknown as T;\n } else {\n return value;\n }\n}\n\nexport function timeDeltaToHumanReadable(delta: number) {\n const sec = delta / 1000;\n if (sec < 60) {\n return `${sec.toFixed(2)}s`;\n }\n const min = sec / 60;\n if (min < 60) {\n return `${min.toFixed(2)}m`;\n }\n const hour = min / 60;\n if (hour < 24) {\n return `${hour.toFixed(2)}h`;\n }\n const day = hour / 24;\n if (day < 365) {\n return `${day.toFixed(2)}d`;\n }\n const year = day / 365;\n return `${year.toFixed(2)}y`;\n}\n\nexport async function wrapException<T>(func: () => Promise<Awaited<T>>): Promise<Awaited<T> | Error> {\n try {\n return await func();\n } catch (ex) {\n if (ex instanceof Error) {\n return ex;\n }\n return new Error(String(ex));\n }\n}\n\n// numeric array to range\n// IN : [1,2,3,5,6,10,11]\n// OUT : `1-3,5-6,10-11`\n\nexport function toRanges(sorted: number[]) {\n // const sorted = numbers.sort((a, b) => a - b);\n if (sorted?.length == 0) return \"\";\n const ranges = [];\n let start = sorted[0];\n let end = sorted[0];\n for (let i = 1; i < sorted.length; i++) {\n if (sorted[i] === end + 1) {\n end = sorted[i];\n } else {\n ranges.push(start === end ? `${start.toString(32)}` : `${start.toString(32)}-${end.toString(32)}`);\n start = sorted[i];\n end = sorted[i];\n }\n }\n ranges.push(start === end ? `${start.toString(32)}` : `${start.toString(32)}-${end.toString(32)}`);\n\n return ranges.join(\",\");\n}\n\nconst previousValues = new Map<string, unknown>();\nexport function isDirty(key: string, value: unknown) {\n const prev = previousValues.get(key);\n if (prev === value) return false;\n previousValues.set(key, value);\n return true;\n}\n\nexport function tryParseJSON<T extends object>(str: string, fallbackValue?: T): T | undefined {\n try {\n return JSON.parse(str) as T;\n } catch {\n return fallbackValue;\n }\n}\n\nexport {\n mergeObject,\n applyPatch,\n generatePatchObj,\n flattenObject,\n isObjectMargeApplicable,\n isSensibleMargeApplicable,\n} from \"./utils.patch.ts\";\n\nexport function parseHeaderValues(strHeader: string): Record<string, string> {\n const headers: Record<string, string> = {};\n const lines = strHeader.split(\"\\n\");\n for (const line of lines) {\n const [key, value] = line.split(\":\", 2).map((e) => e.trim());\n if (key && value) {\n headers[key] = value;\n }\n }\n return headers;\n}\n\n/***\n * Parse custom regular expression\n * @param regexp\n * @returns [negate: boolean, regexp: string]\n * @example `!!foo` => [true, \"foo\"]\n * @example `foo` => [false, \"foo\"]\n */\nexport function parseCustomRegExp(regexp: CustomRegExpSource): ParsedCustomRegExp {\n if (regexp.startsWith(\"!!\")) {\n return [true, regexp.slice(2)];\n }\n return [false, regexp];\n}\nexport function matchRegExp(regexp: CustomRegExpSource, target: string) {\n const [negate, regexpWithoutNegate] = parseCustomRegExp(regexp);\n if (regexpWithoutNegate.length == 0) return false;\n const re = new RegExp(regexpWithoutNegate);\n return negate ? !re.test(target) : re.test(target);\n}\nexport function isValidRegExp(regexp: CustomRegExpSource) {\n try {\n const [, exp] = parseCustomRegExp(regexp);\n new RegExp(exp);\n return true;\n } catch {\n return false;\n }\n}\nexport function isInvertedRegExp(regexp: CustomRegExpSource) {\n const [negate] = parseCustomRegExp(regexp);\n return negate;\n}\n\nfunction parseCustomRegExpList<D extends string>(list: CustomRegExpSourceList<D>, flags?: string, delimiter?: D) {\n const d = delimiter ?? \",\";\n const source = `${list ?? \"\"}`;\n const items = source\n .replace(/\\n| /g, \"\")\n .split(d)\n .filter((e) => e);\n return items.map((e) => new CustomRegExp(e as unknown as CustomRegExpSource, flags));\n}\n\nexport function constructCustomRegExpList<D extends string>(\n items: CustomRegExpSource[],\n delimiter: D\n): CustomRegExpSourceList<D> {\n return items.map((e) => `${e}`).join(`${delimiter}`) as CustomRegExpSourceList<D>;\n}\nexport function splitCustomRegExpList<D extends string>(list: CustomRegExpSourceList<D>, delimiter: D) {\n const d = delimiter;\n const source = `${list ?? \"\"}`;\n return source.split(d).filter((e) => e as CustomRegExpSource) as CustomRegExpSource[];\n}\n\nexport class CustomRegExp {\n regexp: RegExp;\n negate: boolean;\n pattern: string;\n constructor(regexp: CustomRegExpSource, flags?: string) {\n const [negate, exp] = parseCustomRegExp(regexp);\n this.pattern = exp;\n this.regexp = new RegExp(exp, flags);\n this.negate = negate;\n }\n test(str: string) {\n return this.negate ? !this.regexp.test(str) : this.regexp.test(str);\n }\n}\n\ntype RegExpSettingKey =\n | \"syncOnlyRegEx\"\n | \"syncIgnoreRegEx\"\n | \"syncInternalFilesIgnorePatterns\"\n | \"syncInternalFilesTargetPatterns\"\n | \"syncInternalFileOverwritePatterns\";\nexport function getFileRegExp(settings: ObsidianLiveSyncSettings | RemoteDBSettings, key: RegExpSettingKey) {\n const flagCase = settings.handleFilenameCaseSensitive ? \"\" : \"i\";\n if (\n key === \"syncInternalFilesIgnorePatterns\" ||\n key === \"syncInternalFilesTargetPatterns\" ||\n key === \"syncInternalFileOverwritePatterns\"\n ) {\n const regExp = (settings as ObsidianLiveSyncSettings)[key];\n return parseCustomRegExpList(regExp, flagCase, \",\");\n }\n const regExp = settings[key];\n return parseCustomRegExpList(regExp, flagCase, \"|[]|\");\n}\n\n/**\n * Copies properties from the source object to the target object only if they exist in the target.\n * @param source The object to copy properties from.\n * @param target The object to copy properties to.\n */\nexport function copyTo<T extends object, U extends T>(source: U, target: T): void {\n for (const key of Object.keys(target) as (keyof T)[]) {\n target[key] = source[key];\n }\n}\n\n// export function getConnectionSummaryP2P(settings: P2PConnectionInfo) { }\n// export function getConnectionSummaryBucket(settings: BucketSyncSetting) { }\n// export function getConnectionSummaryCouchDB(settings: CouchDBConnection) { }\n// export function getConnectionSummaryE2EE(settings: EncryptionSettings) { }\n\nexport function pickBucketSyncSettings(setting: ObsidianLiveSyncSettings): BucketSyncSetting {\n return {\n bucket: setting.bucket,\n region: setting.region,\n endpoint: setting.endpoint,\n accessKey: setting.accessKey,\n secretKey: setting.secretKey,\n bucketPrefix: setting.bucketPrefix,\n forcePathStyle: setting.forcePathStyle,\n useCustomRequestHandler: setting.useCustomRequestHandler,\n bucketCustomHeaders: setting.bucketCustomHeaders,\n };\n}\n\nexport function pickCouchDBSyncSettings(setting: ObsidianLiveSyncSettings): CouchDBConnection {\n return {\n couchDB_URI: setting.couchDB_URI,\n couchDB_USER: setting.couchDB_USER,\n couchDB_PASSWORD: setting.couchDB_PASSWORD,\n couchDB_DBNAME: setting.couchDB_DBNAME,\n useRequestAPI: setting.useRequestAPI,\n // Advanced settings\n couchDB_CustomHeaders: setting.couchDB_CustomHeaders,\n jwtAlgorithm: setting.jwtAlgorithm,\n jwtExpDuration: setting.jwtExpDuration,\n jwtKey: setting.jwtKey,\n jwtKid: setting.jwtKid,\n jwtSub: setting.jwtSub,\n useJWT: setting.useJWT,\n };\n}\n\nexport function pickEncryptionSettings(setting: ObsidianLiveSyncSettings | EncryptionSettings): EncryptionSettings {\n return {\n E2EEAlgorithm: setting.E2EEAlgorithm,\n encrypt: setting.encrypt,\n passphrase: setting.passphrase,\n usePathObfuscation: setting.usePathObfuscation,\n encryptInternalMetadata: setting.encryptInternalMetadata,\n idDerivationVersion: setting.idDerivationVersion,\n idDerivationKey: setting.idDerivationKey,\n };\n}\nexport function pickP2PSyncSettings(setting: Partial<ObsidianLiveSyncSettings> & P2PConnectionInfo): P2PConnectionInfo {\n return {\n P2P_Enabled: setting.P2P_Enabled,\n P2P_AppID: setting.P2P_AppID,\n P2P_roomID: setting.P2P_roomID,\n P2P_passphrase: setting.P2P_passphrase,\n P2P_relays: setting.P2P_relays,\n P2P_AutoStart: setting.P2P_AutoStart,\n P2P_AutoBroadcast: setting.P2P_AutoBroadcast,\n P2P_DevicePeerName: setting.P2P_DevicePeerName || \"\",\n P2P_turnServers: setting.P2P_turnServers,\n P2P_turnUsername: setting.P2P_turnUsername,\n P2P_turnCredential: setting.P2P_turnCredential,\n P2P_maxWirePayloadBytes: normaliseP2PMaxWirePayloadBytes(setting.P2P_maxWirePayloadBytes),\n P2P_connectionPath: normaliseP2PConnectionPath(setting.P2P_connectionPath),\n P2P_managedType: setting.P2P_managedType,\n P2P_managedId: setting.P2P_managedId,\n P2P_managedToken: setting.P2P_managedToken,\n };\n}\n\nexport function wrapByDefault<T, U>(func: () => T, onError: (err: Error) => U): T | U {\n try {\n return func();\n } catch (ex) {\n const error = ex instanceof Error ? ex : new Error(String(ex));\n return onError(error);\n }\n}\n\nconst resolution = 2000;\nexport function compareMTime(\n baseMTime: number,\n targetMTime: number\n): typeof BASE_IS_NEW | typeof TARGET_IS_NEW | typeof EVEN {\n const truncatedBaseMTime = ~~(baseMTime / resolution) * resolution;\n const truncatedTargetMTime = ~~(targetMTime / resolution) * resolution;\n // Logger(`Resolution MTime ${truncatedBaseMTime} and ${truncatedTargetMTime} `, LOG_LEVEL_VERBOSE);\n if (truncatedBaseMTime == truncatedTargetMTime) return EVEN;\n if (truncatedBaseMTime > truncatedTargetMTime) return BASE_IS_NEW;\n if (truncatedBaseMTime < truncatedTargetMTime) return TARGET_IS_NEW;\n throw new Error(\"Unexpected error\");\n}\n\nexport function displayRev(rev: string) {\n const [number, hash] = rev.split(\"-\");\n return `${number}-${hash.substring(0, 6)}`;\n}\n\n/**\n * Generate a random P2P Room ID in the format `123-456-789-abc`.\n */\nexport function generateP2PRoomId(): string {\n const randomValues = new Uint16Array(4);\n crypto.getRandomValues(randomValues);\n const MAX_UINT16 = 65536;\n const a = Math.floor((randomValues[0] / MAX_UINT16) * 1000);\n const b = Math.floor((randomValues[1] / MAX_UINT16) * 1000);\n const c = Math.floor((randomValues[2] / MAX_UINT16) * 1000);\n const dRange = 36 * 36 * 36;\n const d = Math.floor((randomValues[3] / MAX_UINT16) * dRange);\n return `${a.toString().padStart(3, \"0\")}-${b.toString().padStart(3, \"0\")}-${c\n .toString()\n .padStart(3, \"0\")}-${d.toString(36).padStart(3, \"0\")}`;\n}\n\n/**\n * Extract the stable suffix (last segment) from a Room ID.\n */\nexport function extractP2PRoomSuffix(roomId: string): string {\n const trimmed = roomId.trim();\n if (trimmed === \"\") return \"\";\n const parts = trimmed\n .split(\"-\")\n .map((e) => e.trim())\n .filter((e) => e);\n if (parts.length === 0) return \"\";\n return parts[parts.length - 1] ?? \"\";\n}\n","import { Minimatch, type MinimatchOptions } from \"minimatch\";\nimport { getWebCrypto } from \"@lib/mods.ts\";\nimport {\n type AnyEntry,\n type DocumentID,\n type EntryHasPath,\n type FilePath,\n type FilePathWithPrefix,\n FLAGMD_REDFLAG,\n FLAGMD_REDFLAG2,\n FLAGMD_REDFLAG3,\n PREFIX_OBFUSCATED,\n PREFIXMD_LOGFILE,\n FLAGMD_REDFLAG2_HR,\n FLAGMD_REDFLAG3_HR,\n PREFIXMD_LOGFILE_UC,\n} from \"@lib/common/types.ts\";\nimport { memorizeFuncWithLRUCache } from \"@lib/common/utils.ts\";\nimport { uint8ArrayToHexString, writeString } from \"./convert.ts\";\nimport { unique } from \"octagonal-wheels/collection.js\";\nimport { CHeader, ICHeader, ICXHeader, PSCHeader } from \"@lib/common/models/fileaccess.const\";\nimport { computeKeyedId } from \"@lib/common/idDerivation.ts\";\n// --- path utilities\nexport function isValidFilenameInWidows(filename: string): boolean {\n // eslint-disable-next-line no-control-regex\n const regex = /[\\u0000-\\u001f]|[\\\\\":?<>|*#]/g;\n if (regex.test(filename)) return false;\n const win = /(\\\\|\\/)(COM\\d|LPT\\d|CON|PRN|AUX|NUL|CLOCK$)($|\\.)/gi;\n if (win.test(filename)) return false;\n return true;\n}\nexport function isValidFilenameInDarwin(filename: string): boolean {\n // eslint-disable-next-line no-control-regex\n const regex = /[\\u0000-\\u001f]/g;\n return !regex.test(filename);\n}\nexport function isValidFilenameInLinux(filename: string): boolean {\n // eslint-disable-next-line no-control-regex\n const regex = /[\\u0000-\\u001f]/g;\n return !regex.test(filename);\n}\nexport function isValidFilenameInAndroid(filename: string): boolean {\n // In principle, Android can handle the path as like Linux, but most devices mount the storage in VFAT.\n // eslint-disable-next-line no-control-regex\n const regex = /[\\u0000-\\u001f]|[\\\\\":?<>|*#]/g;\n return !regex.test(filename);\n}\n\nexport function isFilePath(path: FilePath | FilePathWithPrefix): path is FilePath {\n return expandFilePathPrefix(path)[0] === \"\";\n}\nexport function stripAllPrefixes(prefixedPath: FilePathWithPrefix): FilePath {\n // A file path has one namespace; further colons belong to its name.\n return stripPrefix(prefixedPath);\n}\nexport function addPrefix(path: FilePath | FilePathWithPrefix, prefix: string): FilePathWithPrefix {\n if (prefix && path.startsWith(prefix)) return path;\n return `${prefix ?? \"\"}${path}` as FilePathWithPrefix;\n}\nexport function expandFilePathPrefix(path: FilePathWithPrefix | FilePath): [string, FilePathWithPrefix] {\n for (const prefix of [ICHeader, ICXHeader, PSCHeader]) {\n if (path.startsWith(prefix)) {\n return [prefix, path.substring(prefix.length) as FilePathWithPrefix];\n }\n }\n return [\"\", path];\n}\nexport function expandDocumentIDPrefix(id: DocumentID): [string, FilePathWithPrefix] {\n for (const prefix of [CHeader, PREFIX_OBFUSCATED]) {\n if (id.startsWith(prefix)) {\n return [prefix, id.substring(prefix.length) as FilePathWithPrefix];\n }\n }\n return expandFilePathPrefix(id as string as FilePathWithPrefix);\n}\n\nconst _hashString = memorizeFuncWithLRUCache(async (key: string) => {\n const buff = writeString(key);\n const webcrypto = await getWebCrypto();\n // Derive the obfuscated document ID from this input.\n const digest = await webcrypto.subtle.digest(\"SHA-256\", buff);\n return uint8ArrayToHexString(new Uint8Array(digest));\n});\n\nfunction hashString(key: string) {\n return _hashString(key);\n}\n\nexport async function path2id_base(\n filenameSrc: FilePathWithPrefix | FilePath,\n obfuscatePassphrase: string | false,\n caseInsensitive: boolean,\n idDerivationKey?: string\n): Promise<DocumentID> {\n if (filenameSrc.startsWith(PREFIX_OBFUSCATED)) return `${filenameSrc}` as DocumentID;\n let filename = `${filenameSrc}`;\n const newPrefix = obfuscatePassphrase ? PREFIX_OBFUSCATED : \"\";\n if (caseInsensitive) {\n filename = filename.toLowerCase();\n }\n\n let x = filename;\n if (x.startsWith(\"_\")) x = \"/\" + x;\n\n if (!obfuscatePassphrase) {\n return (newPrefix + x) as DocumentID;\n }\n\n // obfuscating...\n const [prefix, body] = expandFilePathPrefix(x as FilePathWithPrefix);\n // Already Hashed\n if (body.startsWith(PREFIX_OBFUSCATED)) return (newPrefix + x) as DocumentID;\n const out = idDerivationKey\n ? await computeKeyedId(idDerivationKey, \"document\", filename)\n : await hashString(`${await hashString(obfuscatePassphrase)}:${filename}`);\n return (prefix + newPrefix + out) as DocumentID;\n}\n\nexport function id2path_base(id: DocumentID, entry?: EntryHasPath): FilePathWithPrefix {\n if (entry && entry?.path) {\n return id2path_base(entry.path as string as DocumentID);\n }\n if (id.startsWith(PREFIX_OBFUSCATED)) throw new Error(\"Entry has been obfuscated!\");\n const [prefix, body] = expandDocumentIDPrefix(id);\n if (body.startsWith(PREFIX_OBFUSCATED)) throw new Error(\"Entry has been obfuscated!\");\n if (body.startsWith(\"/\")) {\n return body.substring(1) as FilePathWithPrefix;\n }\n return (prefix + body) as FilePathWithPrefix;\n}\n\nexport function getPath(entry: AnyEntry) {\n return id2path_base(entry._id, entry);\n}\nexport function getPathWithoutPrefix(entry: AnyEntry) {\n const f = getPath(entry);\n return stripAllPrefixes(f);\n}\nexport function stripPrefix(prefixedPath: FilePathWithPrefix): FilePath {\n return expandFilePathPrefix(prefixedPath)[1] as FilePath;\n}\n\nexport function shouldBeIgnored(filename: string): boolean {\n if (filename == FLAGMD_REDFLAG) {\n return true;\n }\n if (filename == FLAGMD_REDFLAG2) {\n return true;\n }\n if (filename == FLAGMD_REDFLAG2_HR) {\n return true;\n }\n if (filename == FLAGMD_REDFLAG3) {\n return true;\n }\n if (filename == FLAGMD_REDFLAG3_HR) {\n return true;\n }\n if (filename.startsWith(PREFIXMD_LOGFILE)) {\n return true;\n }\n if (filename.startsWith(PREFIXMD_LOGFILE_UC)) {\n return true;\n }\n return false;\n}\nexport function isPlainText(filename: string): boolean {\n if (filename.endsWith(\".md\")) return true;\n if (filename.endsWith(\".txt\")) return true;\n if (filename.endsWith(\".svg\")) return true;\n if (filename.endsWith(\".html\")) return true;\n if (filename.endsWith(\".csv\")) return true;\n if (filename.endsWith(\".css\")) return true;\n if (filename.endsWith(\".js\")) return true;\n if (filename.endsWith(\".xml\")) return true;\n if (filename.endsWith(\".canvas\")) return true;\n return false;\n}\nexport function shouldSplitAsPlainText(filename: string): boolean {\n if (filename.endsWith(\".md\")) return true;\n if (filename.endsWith(\".txt\")) return true;\n if (filename.endsWith(\".canvas\")) return true;\n return false;\n}\n\nconst matchOpts: MinimatchOptions = { platform: \"linux\", dot: true, flipNegate: true, nocase: true };\nconst matcherCache = new WeakMap<string[], Map<string, Minimatch>>();\n\nfunction matchIgnoredPath(path: string, pattern: string, ignore: string[]): boolean {\n let matchers = matcherCache.get(ignore);\n if (matchers === undefined) {\n matchers = new Map();\n matcherCache.set(ignore, matchers);\n }\n let matcher = matchers.get(pattern);\n if (matcher === undefined) {\n matcher = new Minimatch(pattern, matchOpts);\n matchers.set(pattern, matcher);\n }\n return matcher.match(path);\n}\n\n/**\n * returns whether the given path is accepted (not ignored) by the `.gitignore`.\n * @param path path of the file which is relative from `.gitignore` file\n * @param ignore lines of `.gitignore`\n * @returns true when accepted.\n * false when not accepted.\n * undefined when the path is not mentioned in the `.gitignore` file.\n */\nexport function isAccepted(path: string, ignore: string[]): boolean | undefined {\n if (path.indexOf(\"./\") !== -1 || path.indexOf(\"../\") !== -1) {\n // We do not accept this for handle the cases which ends with `/` by wildcard\n return false;\n }\n const patterns = ignore.map((e) => e.trim()).filter((e) => e.length > 0 && !e.startsWith(\"#\"));\n let result = undefined;\n for (const pattern of patterns) {\n if (pattern.endsWith(\"/\")) {\n // If the path ends with `/` and matched to the path. we do not handle more patterns to negate the result.\n if (matchIgnoredPath(path, `${pattern}**`, ignore)) {\n return false;\n }\n }\n const newResult = pattern.startsWith(\"!\");\n const matched =\n matchIgnoredPath(path, pattern, ignore) ||\n (!pattern.endsWith(\"/\") && matchIgnoredPath(path, pattern + \"/**\", ignore));\n\n if (matched) {\n result = newResult;\n }\n }\n return result;\n}\n\n/**\n * Checks whether the path is accepted by all ignored files.\n * @param path path of target file\n * @param ignoreFiles list of ignore files. i.e. [\".gitignore\", \".dockerignore\"]\n * @param getList function to retrieve the file.\n * @returns true when accepted. false when should be ignored.\n */\nexport async function isAcceptedAll(\n path: string,\n ignoreFiles: string[],\n getList: (path: string) => Promise<string[] | false>\n) {\n const pathBase = path.substring(0, path.lastIndexOf(\"/\"));\n const intermediatePaths = unique(\n pathBase\n .split(\"/\")\n .reduce((p, c) => [...p, p[p.length - 1] + \"/\" + c], [\"\"])\n .map((e) => e.substring(1))\n ).reverse();\n\n for (const intermediatePath of intermediatePaths) {\n for (const ignoreFile of ignoreFiles) {\n const ignoreFilePath = intermediatePath + \"/\" + ignoreFile;\n const list = await getList(ignoreFilePath);\n if (list === false) continue;\n const result = isAccepted(path.substring(intermediatePath.length ? intermediatePath.length + 1 : 0), list);\n if (result !== undefined) {\n return result;\n }\n }\n }\n return true;\n}\n","import type { Constructor } from \"@lib/common/utils.type\";\ninterface ErrorWithCause extends Error {\n cause?: unknown;\n}\n\nfunction getStatusFromError(error: unknown): number | undefined {\n if (error && typeof error === \"object\") {\n if (\"status\" in error && typeof error.status === \"number\") {\n return error.status;\n }\n if (\"cause\" in error) {\n return getStatusFromError(error.cause);\n }\n }\n return 500; // Default status code for internal server error if no status found in the cause chain\n}\n\nfunction getMessageFromError(error: unknown): string {\n if (error instanceof Error) {\n return error.message;\n }\n if (typeof error === \"object\" && error !== null) {\n return JSON.stringify(error);\n }\n return String(error);\n}\nfunction getErrorCause(error: unknown): unknown {\n if (error && typeof error === \"object\" && \"cause\" in error) {\n return (error as { cause?: unknown }).cause;\n }\n return undefined;\n}\n\n/**\n * Error class for Self-hosted LiveSync errors.\n * This class extends the base LiveSyncError class and provides additional context for errors related to LiveSync operations.\n * It includes a name property and a cause property to capture the original error.\n * The status property returns the HTTP status code if available, defaulting to 500 for internal server errors.\n * The class also includes static methods to check whether an error is caused by a specific error class.\n */\nexport class LiveSyncError extends Error implements ErrorWithCause {\n override name = this.constructor.name;\n override cause?: Error | object | string;\n overrideStatus?: number;\n /**\n * Returns the HTTP status code associated with the error, if available.\n * If the error has a status property, it returns that; otherwise, it defaults to 500 (Internal Server Error).\n * @returns {number} The HTTP status code.\n */\n get status(): number {\n if (this.overrideStatus !== undefined) {\n return this.overrideStatus;\n }\n if (this.cause) {\n const status = getStatusFromError(this.cause);\n if (status !== undefined) {\n return status;\n }\n }\n return 500; // Default status code for internal server error\n }\n /**\n * Constructs a new LiveSyncError instance.\n * @param message The error message to be displayed.\n */\n constructor(message: string, options?: { cause?: unknown; status?: number }) {\n super(message);\n if (options?.cause) {\n const actualCause = getErrorCause(options);\n this.cause =\n actualCause instanceof Error\n ? actualCause\n : new Error(`Unknown cause: ${getMessageFromError(actualCause)}`);\n }\n if (options?.status !== undefined) {\n this.overrideStatus = options.status;\n }\n }\n\n /**\n * Determines whether an error is caused by a specific error class.\n * @param error The error to examine.\n * @param errorClass The error class to compare against.\n * @returns True if the error is caused by the specified error class; otherwise, false.\n * @example\n * LiveSyncError.isCausedBy(someSyncParamsFetchError, SyncParamsNotFoundError); // Returns true if the error is caused by SyncParamsNotFoundError; this is usually represented as SyncParamsFetchError at the uppermost layer.\n */\n static isCausedBy<T extends LiveSyncError>(error: unknown, errorClass: Constructor<T>): boolean {\n if (!error) {\n return false;\n }\n if (error instanceof errorClass) {\n return true;\n }\n if (typeof error === \"object\" && !!error && \"cause\" in error) {\n const cause = getErrorCause(error);\n if (cause === error) {\n // Avoid infinite loop in case of circular cause reference.\n return false;\n }\n return LiveSyncError.isCausedBy(cause, errorClass);\n }\n return false;\n }\n /**\n * Creates a new instance of the error class from an existing error.\n * @param error The error to wrap.\n * @returns A new instance of the error class with the original error's message and stack trace.\n */\n static fromError<T extends typeof LiveSyncError>(this: T, error: unknown): InstanceType<T> {\n if (error instanceof this) {\n return error as InstanceType<T>;\n }\n const instance = new this(`${this.name}: ${getMessageFromError(error)}`, {\n cause: error,\n status: getStatusFromError(error),\n }) as InstanceType<T>;\n if (error instanceof Error) {\n instance.stack = error.stack;\n } else {\n instance.stack = new Error().stack;\n }\n return instance;\n }\n}\n\nexport class LiveSyncFatalError extends LiveSyncError {}\n","import { LiveSyncError } from \"./LSError\";\n\nexport function asCopy<T>(obj: T): T {\n return JSON.parse(JSON.stringify(obj)) as T;\n}\n\nexport function ensureError(error: unknown): Error {\n if (error instanceof Error) {\n return error;\n }\n return LiveSyncError.fromError(error);\n}\n","const MARK_OPERATOR = `\\u{0001}`;\nconst MARK_DELETED = `${MARK_OPERATOR}__DELETED`;\nconst MARK_ISARRAY = `${MARK_OPERATOR}__ARRAY`;\nconst MARK_SWAPPED = `${MARK_OPERATOR}__SWAP`;\n\ninterface ObjectWithID {\n id: string;\n}\nfunction unorderedArrayToObject<T extends ObjectWithID>(obj: Array<T>) {\n return obj.map((e) => ({ [e.id]: e })).reduce((p, c) => ({ ...p, ...c }), {});\n}\nfunction objectToUnorderedArray<T extends ObjectWithID>(obj: Record<string, T>) {\n const entries = Object.entries(obj);\n if (entries.some((e) => e[0] != e[1]?.id)) throw new Error(\"Item looks like not unordered array\");\n return entries.map((e) => e[1]);\n}\nfunction generatePatchUnorderedArray<T extends ObjectWithID>(from: Array<T>, to: Array<T>) {\n if (from.every((e) => typeof e == \"object\" && \"id\" in e) && to.every((e) => typeof e == \"object\" && \"id\" in e)) {\n const fObj = unorderedArrayToObject(from);\n const tObj = unorderedArrayToObject(to);\n const diff = generatePatchObj(fObj, tObj);\n if (Object.keys(diff).length > 0) {\n return { [MARK_ISARRAY]: diff };\n } else {\n return {};\n }\n }\n return { [MARK_SWAPPED]: to };\n}\n\nexport function generatePatchObj(\n from: Record<string | number | symbol, unknown>,\n to: Record<string | number | symbol, unknown>\n) {\n const entries = Object.entries(from);\n const tempMap = new Map<string | number | symbol, unknown>(entries);\n const ret = {} as Record<string | number | symbol, unknown>;\n const newEntries = Object.entries(to);\n for (const [key, value] of newEntries) {\n if (!tempMap.has(key)) {\n //New\n ret[key] = value;\n tempMap.delete(key);\n } else {\n //Exists\n const v = tempMap.get(key);\n if (typeof v !== typeof value || Array.isArray(v) !== Array.isArray(value)) {\n //if type is not match, replace completely.\n ret[key] = { [MARK_SWAPPED]: value };\n } else {\n if (v === null && value === null) {\n // NO OP.\n } else if (v === null && value !== null) {\n ret[key] = { [MARK_SWAPPED]: value };\n } else if (v !== null && value === null) {\n ret[key] = { [MARK_SWAPPED]: value };\n } else if (\n typeof v == \"object\" &&\n typeof value == \"object\" &&\n !Array.isArray(v) &&\n !Array.isArray(value)\n ) {\n const wk = generatePatchObj(\n v as Record<string | number | symbol, unknown>,\n value as Record<string | number | symbol, unknown>\n );\n if (Object.keys(wk).length > 0) ret[key] = wk;\n } else if (\n typeof v == \"object\" &&\n typeof value == \"object\" &&\n Array.isArray(v) &&\n Array.isArray(value)\n ) {\n const wk = generatePatchUnorderedArray(v, value);\n if (Object.keys(wk).length > 0) ret[key] = wk;\n } else if (typeof v != \"object\" && typeof value != \"object\") {\n if (JSON.stringify(tempMap.get(key)) !== JSON.stringify(value)) {\n ret[key] = value;\n }\n } else {\n if (JSON.stringify(tempMap.get(key)) !== JSON.stringify(value)) {\n ret[key] = { [MARK_SWAPPED]: value };\n }\n }\n }\n tempMap.delete(key);\n }\n }\n //Not used item, means deleted one\n for (const [key] of tempMap) {\n ret[key] = MARK_DELETED;\n }\n return ret;\n}\n\nexport function applyPatch(\n from: Record<string | number | symbol, unknown>,\n patch: Record<string | number | symbol, unknown>\n) {\n const ret = from;\n const patches = Object.entries(patch);\n for (const [key, value] of patches) {\n if (value == MARK_DELETED) {\n delete ret[key];\n continue;\n }\n if (value === null) {\n ret[key] = null;\n continue;\n }\n if (typeof value == \"object\") {\n if (MARK_SWAPPED in value) {\n ret[key] = (value as Record<string, unknown>)[MARK_SWAPPED];\n continue;\n }\n if (MARK_ISARRAY in value) {\n if (!(key in ret)) ret[key] = [];\n if (!Array.isArray(ret[key])) {\n throw new Error(\"Patch target type is mismatched (array to something)\");\n }\n const orgArrayObject = unorderedArrayToObject(ret[key] as Array<ObjectWithID>);\n const appliedObject = applyPatch(\n orgArrayObject,\n (value as Record<string, unknown>)[MARK_ISARRAY] as Record<string | number | symbol, unknown>\n );\n const appliedArray = objectToUnorderedArray(appliedObject as Record<string, ObjectWithID>);\n ret[key] = [...appliedArray];\n } else {\n if (!(key in ret)) {\n ret[key] = value;\n continue;\n }\n ret[key] = applyPatch(\n ret[key] as Record<string | number | symbol, unknown>,\n value as Record<string | number | symbol, unknown>\n );\n }\n } else {\n ret[key] = value;\n }\n }\n return ret;\n}\n\nexport function mergeObject(\n objA: Record<string | number | symbol, unknown> | [unknown],\n objB: Record<string | number | symbol, unknown> | [unknown]\n) {\n const newEntries = Object.entries(objB);\n const ret: Record<string | number | symbol, unknown> = { ...(objA as object) };\n if (typeof objA !== typeof objB || Array.isArray(objA) !== Array.isArray(objB)) {\n return objB;\n }\n\n for (const [key, v] of newEntries) {\n if (key in ret) {\n const value = ret[key];\n if (typeof v !== typeof value || Array.isArray(v) !== Array.isArray(value)) {\n //if type is not match, replace completely.\n ret[key] = v;\n } else {\n if (typeof v == \"object\" && typeof value == \"object\" && !Array.isArray(v) && !Array.isArray(value)) {\n // TODO: Null handling\n ret[key] = mergeObject(\n v as Record<string | number | symbol, unknown>,\n value as Record<string | number | symbol, unknown>\n );\n } else if (\n typeof v == \"object\" &&\n typeof value == \"object\" &&\n Array.isArray(v) &&\n Array.isArray(value)\n ) {\n ret[key] = [...new Set([...(v as Array<unknown>), ...(value as Array<unknown>)])];\n } else {\n ret[key] = v;\n }\n }\n } else {\n ret[key] = v;\n }\n }\n const retSorted = Object.fromEntries(Object.entries(ret).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)));\n if (Array.isArray(objA) && Array.isArray(objB)) {\n return Object.values(retSorted);\n }\n return retSorted;\n}\n\nexport function flattenObject(\n obj: Record<string | number | symbol, unknown>,\n path: string[] = []\n): [string, unknown][] {\n if (typeof obj != \"object\") return [[path.join(\".\"), obj]];\n if (obj === null) return [[path.join(\".\"), null]];\n if (Array.isArray(obj)) return [[path.join(\".\"), JSON.stringify(obj)]];\n const e = Object.entries(obj);\n const ret = [];\n for (const [key, value] of e) {\n const p = flattenObject(value as Record<string | number | symbol, unknown>, [...path, key]);\n ret.push(...p);\n }\n return ret;\n}\n\nexport function isSensibleMargeApplicable(path: string) {\n if (path.endsWith(\".md\")) return true;\n return false;\n}\nexport function isObjectMargeApplicable(path: string) {\n if (path.endsWith(\".canvas\")) return true;\n if (path.endsWith(\".json\")) return true;\n return false;\n}\n","/**\n * Content-Splitter for Self-hosted LiveSync.\n * Splits content into manageable chunks for efficient storage and synchronisation.\n */\nimport { type FilePathWithPrefix } from \"@lib/common/types.ts\";\nimport type { ISettingService } from \"@lib/services/base/IService.ts\";\n\n/**\n * ContentSplitter interface for splitting content into chunks.\n */\nexport type SplitOptions = {\n blob: Blob;\n path: FilePathWithPrefix;\n pieceSize: number;\n plainSplit: boolean;\n minimumChunkSize: number;\n useWorker: boolean;\n useSegmenter: boolean;\n};\n\n/**\n * The maximum size, in bytes, of a document to be processed by the content splitter in the foreground.\n */\nexport const MAX_CHUNKS_SIZE_ON_UI = 1024;\n\n/**\n * Options for the content splitter.\n */\nexport type ContentSplitterOptions = {\n settingService: ISettingService;\n};\n","import { MAX_DOC_SIZE_BIN, ChunkAlgorithms, type SavingEntry } from \"@lib/common/types.ts\";\nimport { createTextBlob } from \"@lib/common/utils.ts\";\nimport { shouldSplitAsPlainText } from \"@lib/string_and_binary/path.ts\";\nimport { type ContentSplitterOptions, type SplitOptions, MAX_CHUNKS_SIZE_ON_UI } from \"./ContentSplitter.ts\";\n\nexport abstract class ContentSplitterCore {\n /**\n * Options for the content splitter.\n * These settings include the chunk splitter version and other configurations.\n */\n options: ContentSplitterOptions;\n /**\n * Task for initialising the content splitter.\n * This ensures that the splitter is initialised before any operations are performed.\n */\n initialised: Promise<boolean> | undefined;\n\n /**\n * Constructor for the content splitter core.\n * @param params Content splitter options\n */\n constructor(params: ContentSplitterOptions) {\n this.options = params;\n this.initialised = this.initialise(params);\n }\n\n /**\n * Initialise the content splitter with the provided options.\n * @param options Content splitter options\n */\n abstract initialise(options: ContentSplitterOptions): Promise<boolean>;\n\n /**\n * Split the content of the loaded entry into chunks.\n * @param entry The loaded entry to be split into chunks\n */\n abstract splitContent(\n entry: SavingEntry\n ): Promise<AsyncGenerator<string, void, unknown> | Generator<string, void, unknown>>;\n}\n\nexport abstract class ContentSplitterBase extends ContentSplitterCore {\n initialise(_options: ContentSplitterOptions): Promise<boolean> {\n this.options = _options;\n return Promise.resolve(true); // Default implementation, should be overridden\n }\n\n /**\n * Check whether the content splitter is available for the given settings.\n * @param setting Content splitter options\n * @returns True if the content splitter is available; false otherwise\n */\n static isAvailableFor(setting: ContentSplitterOptions): boolean {\n return false; // Default implementation, should be overridden\n }\n\n /**\n * Process the content and split it into chunks.\n * @param options Blob content to be split into chunks\n */\n abstract processSplit(\n options: SplitOptions\n ): Promise<AsyncGenerator<string, void, unknown> | Generator<string, void, unknown>>;\n\n getParamsFor(entry: SavingEntry): SplitOptions {\n const settings = this.options.settingService.currentSettings();\n const maxChunkSize = Math.floor(MAX_DOC_SIZE_BIN * ((settings.customChunkSize || 0) * 1 + 1));\n const pieceSize = maxChunkSize;\n\n const minimumChunkSize = settings.minimumChunkSize;\n const path = entry.path;\n\n const plainSplit = shouldSplitAsPlainText(path);\n const maxSize = MAX_CHUNKS_SIZE_ON_UI;\n const blob = entry.data instanceof Blob ? entry.data : createTextBlob(entry.data);\n let useWorker = true;\n if (settings.disableWorkerForGeneratingChunks) {\n useWorker = false;\n }\n if (useWorker && settings.processSmallFilesInUIThread) {\n if (blob.size <= maxSize) {\n useWorker = false;\n }\n }\n const useSegmenter = settings.chunkSplitterVersion === ChunkAlgorithms.V2Segmenter;\n return {\n blob,\n path,\n pieceSize,\n plainSplit,\n minimumChunkSize,\n useWorker,\n useSegmenter,\n };\n }\n\n /**\n * Split the content of the loaded entry into chunks.\n * This method waits for the initialisation task to complete before proceeding.\n * @param entry The loaded entry to be split into chunks\n * @returns A generator that yields the split chunks\n */\n async splitContent(\n entry: SavingEntry\n ): Promise<AsyncGenerator<string, void, unknown> | Generator<string, void, unknown>> {\n await this.initialised;\n const options = this.getParamsFor(entry);\n const generator = await this.processSplit(options);\n return generator;\n }\n}\n","function isTextBlob(blob: Blob) {\n return blob.type === \"text/plain\";\n}\n\nimport { LOG_LEVEL_VERBOSE, Logger } from \"@lib/common/logger.ts\";\nimport { arrayBufferToBase64Single, readString } from \"./convert.ts\";\nimport { wrapByDefault } from \"@lib/common/utils.ts\";\nimport { compatGlobal } from \"@lib/common/coreEnvFunctions.ts\";\n\n/// Chunk utilities\nfunction* pickPiece(leftData: string[], minimumChunkSize: number): Generator<string> {\n let buffer = \"\";\n L1: do {\n const curLine = leftData.shift();\n if (typeof curLine === \"undefined\") {\n yield buffer;\n break L1;\n }\n\n // Do not use regexp for performance.\n if (\n curLine.startsWith(\"```\") ||\n curLine.startsWith(\" ```\") ||\n curLine.startsWith(\" ```\") ||\n curLine.startsWith(\" ```\")\n ) {\n yield buffer;\n buffer = curLine + (leftData.length != 0 ? \"\\n\" : \"\");\n L2: do {\n const curPx = leftData.shift();\n if (typeof curPx === \"undefined\") {\n break L2;\n }\n buffer += curPx + (leftData.length != 0 ? \"\\n\" : \"\");\n } while (\n leftData.length > 0 &&\n !(\n leftData[0].startsWith(\"```\") ||\n leftData[0].startsWith(\" ```\") ||\n leftData[0].startsWith(\" ```\") ||\n leftData[0].startsWith(\" ```\")\n )\n );\n const isLooksLikeBASE64 = buffer.endsWith(\"=\");\n const maybeUneditable = buffer.length > 2048;\n // concat code block end mark\n const endOfCodeBlock = leftData.shift();\n if (typeof endOfCodeBlock !== \"undefined\") {\n buffer += endOfCodeBlock;\n buffer += leftData.length != 0 ? \"\\n\" : \"\";\n }\n if (!isLooksLikeBASE64 && !maybeUneditable) {\n const splitExpr = /(.*?[;,:<])/g;\n const sx = buffer.split(splitExpr).filter((e) => e != \"\");\n for (const v of sx) {\n yield v;\n }\n } else {\n yield buffer;\n }\n buffer = \"\";\n } else {\n buffer += curLine + (leftData.length != 0 ? \"\\n\" : \"\");\n if (buffer.length >= minimumChunkSize || leftData.length == 0 || leftData[0] == \"#\" || buffer[0] == \"#\") {\n yield buffer;\n buffer = \"\";\n }\n }\n } while (leftData.length > 0);\n}\n\nconst charNewLine = \"\\n\".charCodeAt(0);\n\n// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\nconst segmenter =\n \"Segmenter\" in Intl\n ? wrapByDefault(\n // @ts-ignore We have checked Intl existence above.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-return\n () => new Intl.Segmenter(compatGlobal.navigator.language, { granularity: \"sentence\" }),\n (err: Error): undefined => {\n Logger(`Failed to create Intl.Segmenter: ${err.message}`, LOG_LEVEL_VERBOSE);\n return undefined;\n }\n )\n : undefined;\n\nfunction* splitStringWithinLength(text: string, pieceSize: number) {\n let leftData = text;\n do {\n const splitSize = pieceSize;\n const piece = leftData.substring(0, splitSize);\n leftData = leftData.substring(splitSize);\n yield piece;\n } while (leftData != \"\");\n}\n\nfunction* splitTextInSegment(text: string, pieceSize: number, minimumChunkSize: number) {\n const segments = segmenter!.segment(text);\n\n let prev = \"\";\n let buf = \"\";\n\n for (const seg of segments) {\n // Same segment, concat.\n const buffer = seg.segment;\n if (prev == buffer || buf.length < minimumChunkSize) {\n buf += buffer;\n prev = buffer;\n } else {\n prev = buffer;\n if (buf.length > 0) {\n yield* splitStringWithinLength(buf, pieceSize);\n }\n buf = buffer;\n }\n }\n if (buf.length > 0) {\n yield* splitStringWithinLength(buf, pieceSize);\n }\n}\n\nfunction* splitInNewLine(texts: string[]) {\n for (const text of texts) {\n let start = -1;\n let end = -1;\n do {\n end = text.indexOf(\"\\n\", start);\n if (end == -1) {\n yield text.substring(start);\n break;\n }\n // Concat empty lines.\n while (text[end] == \"\\n\") {\n end++;\n }\n yield text.substring(start, end);\n start = end;\n } while (end != -1);\n }\n return;\n}\nexport function splitPiecesTextV2(dataSrc: string | string[], pieceSize: number, minimumChunkSize: number) {\n const dataListAllArray = typeof dataSrc == \"string\" ? [dataSrc] : dataSrc;\n const dataListAll = splitInNewLine(dataListAllArray);\n let inCodeBlock = 0;\n let flush = false;\n let flushBefore = false;\n return function* (): Generator<string> {\n const buf = [] as string[];\n for (const line of dataListAll) {\n if (line.startsWith(\"````\")) {\n if (inCodeBlock == 0) {\n inCodeBlock = 4;\n flushBefore = true;\n } else if (inCodeBlock == 4) {\n inCodeBlock = 0;\n flush = true;\n }\n } else if (line.startsWith(\"```\")) {\n if (inCodeBlock == 0) {\n inCodeBlock = 3;\n flushBefore = true;\n } else if (inCodeBlock == 3) {\n inCodeBlock = 0;\n flush = true;\n }\n }\n if (flushBefore) {\n if (buf.length > 0) {\n yield* splitTextInSegment(buf.join(\"\"), pieceSize, minimumChunkSize);\n buf.length = 0;\n }\n flushBefore = false;\n }\n buf.push(line);\n if (flush) {\n if (buf.length > 0) {\n yield* splitStringWithinLength(buf.join(\"\"), pieceSize);\n buf.length = 0;\n }\n flush = false;\n }\n }\n if (buf.length > 0) {\n if (inCodeBlock == 0) {\n yield* splitTextInSegment(buf.join(\"\"), pieceSize, minimumChunkSize);\n } else {\n yield* splitStringWithinLength(buf.join(\"\"), pieceSize);\n }\n }\n };\n}\nexport function binaryTextSplit(data: string, pieceSize: number, minimumChunkSize: number) {\n return function* pieces(): Generator<string> {\n yield* splitStringWithinLength(data, pieceSize);\n };\n}\n// Split string into pieces within specific lengths (characters).\nexport function splitPiecesText(\n dataSrc: string | string[],\n pieceSize: number,\n plainSplit: boolean,\n minimumChunkSize: number,\n useSegmenter: boolean\n) {\n if (!useSegmenter || !segmenter) {\n return splitPiecesTextV1(dataSrc, pieceSize, plainSplit, minimumChunkSize);\n }\n if (!plainSplit) {\n return binaryTextSplit(dataSrc as string, pieceSize, minimumChunkSize);\n }\n return splitPiecesTextV2(dataSrc, pieceSize, minimumChunkSize);\n}\n\nexport function splitPiecesTextV1(\n dataSrc: string | string[],\n pieceSize: number,\n plainSplit: boolean,\n minimumChunkSize: number\n) {\n const dataList = typeof dataSrc == \"string\" ? [dataSrc] : dataSrc;\n return function* pieces(): Generator<string> {\n for (const data of dataList) {\n if (plainSplit) {\n const leftData = data.split(\"\\n\"); //use memory\n const f = pickPiece(leftData, minimumChunkSize);\n for (const piece of f) {\n let buffer = piece;\n do {\n // split to within maximum pieceSize\n let ps = pieceSize;\n if (buffer.charCodeAt(ps - 1) != buffer.codePointAt(ps - 1)) {\n // If the char at the end of the chunk has been part of the surrogate pair, grow the piece size a bit.\n ps++;\n }\n yield buffer.substring(0, ps);\n buffer = buffer.substring(ps);\n } while (buffer != \"\");\n }\n } else {\n let leftData = data;\n do {\n const splitSize = pieceSize;\n const piece = leftData.substring(0, splitSize);\n leftData = leftData.substring(splitSize);\n yield piece;\n } while (leftData != \"\");\n }\n }\n };\n}\n\nfunction* splitByDelimiterWithMinLength(\n sources: Generator<string, void, unknown>,\n delimiter: string,\n minimumChunkLength = 25,\n splitThreshold?: number\n) {\n let buf = \"\";\n let last = false;\n const dl = delimiter.length;\n for (const source of sources) {\n const max = source.length;\n if (splitThreshold && max > splitThreshold) {\n yield buf + source;\n last = false;\n buf = \"\";\n continue;\n }\n let i = -1;\n let prev = 0;\n L1: do {\n i = source.indexOf(delimiter, prev);\n if (i == -1) break L1;\n buf += source.slice(prev, i) + delimiter;\n if (buf.length > minimumChunkLength) {\n yield buf;\n buf = \"\";\n last = false;\n } else {\n last = true;\n }\n prev = i + dl;\n } while (i < max);\n if (prev != i || (prev == -1 && i == -1)) {\n buf += source.slice(prev);\n last = true;\n }\n }\n if (last) {\n yield buf;\n }\n}\nfunction* chunkStringGenerator(source: string, maxLength: number) {\n const strLen = source.length;\n if (strLen > maxLength) {\n let from = 0;\n do {\n let end = from + maxLength;\n if (end > strLen) {\n yield source.substring(from);\n break;\n }\n while (source.charCodeAt(end - 1) != source.codePointAt(end - 1)) {\n // If the char at the end of the chunk has been part of the surrogate pair, grow the piece size a bit.\n end++;\n }\n yield source.substring(from, end);\n from = end;\n } while (from < strLen);\n } else {\n yield source;\n }\n}\n\nfunction* chunkStringGeneratorFromGenerator(sources: Generator<string, void, unknown>, maxLength: number) {\n for (const source of sources) {\n yield* chunkStringGenerator(source, maxLength);\n }\n}\n\nfunction* stringGenerator(sources: string[]) {\n for (const str of sources) {\n yield str;\n }\n}\nexport async function collectGenAll(strGen: AsyncGenerator<string, unknown, unknown> | Generator<string>) {\n const ret = [] as string[];\n for await (const str of strGen) {\n ret.push(str);\n }\n return ret;\n}\nexport async function concatGeneratedAll(strGen: AsyncGenerator<string, unknown, unknown> | Generator<string>) {\n return (await collectGenAll(strGen)).join(\"\");\n}\n\nconst MAX_ITEMS = 100;\nexport async function splitPieces2V2(\n dataSrc: Blob,\n pieceSize: number,\n plainSplit: boolean,\n minimumChunkSize: number,\n filename?: string,\n useSegmenter?: boolean\n) {\n if (dataSrc.size == 0) {\n // eslint-disable-next-line require-yield\n return function* noItems(): Generator<string> {\n return;\n };\n }\n if (isTextBlob(dataSrc)) {\n const text = await dataSrc.text();\n // let pPieceSize = pieceSize;\n\n if (!plainSplit) {\n // const srcGen = stringGenerator([text]);\n const gen = chunkStringGenerator(text, pieceSize);\n return function* pieces(): Generator<string> {\n yield* gen;\n };\n }\n const textLen = text.length;\n let xMinimumChunkSize = minimumChunkSize;\n while (textLen / xMinimumChunkSize > MAX_ITEMS) {\n xMinimumChunkSize += minimumChunkSize;\n }\n const org = stringGenerator([text]);\n const gen1 = splitByDelimiterWithMinLength(org, \"\\n\", xMinimumChunkSize);\n\n // const genHeading = splitByDelimiterWithMinLength(gen1, \"\\n#\", minimumChunkSize);\n // const genCodeblock = splitByDelimiterWithMinLength(genHeading, \"```\", minimumChunkSize);\n // const srcGen = splitByDelimiterWithMinLength(genCodeblock, \"\\n\", minimumChunkSize, minimumChunkSize * 25);\n const gen = chunkStringGeneratorFromGenerator(gen1, pieceSize);\n return function* pieces(): Generator<string> {\n yield* gen;\n };\n }\n let canBeSmall = false;\n let delimiter = 0; // Split null by default.\n if (filename && filename.endsWith(\".pdf\")) {\n delimiter = \"/\".charCodeAt(0);\n } else if (filename && filename.endsWith(\".json\")) {\n canBeSmall = true;\n delimiter = \",\".charCodeAt(0);\n }\n\n // Optimise chunk size to efficient dedupe.\n const clampMin = canBeSmall ? 100 : 100000; //100kb\n const clampMax = 100000000; //100mb\n const clampedSize = Math.max(clampMin, Math.min(clampMax, dataSrc.size));\n let step = 1;\n let w = clampedSize;\n while (w > 10) {\n w /= 12.5;\n step++;\n }\n minimumChunkSize = Math.floor(10 ** (step - 1));\n\n return async function* piecesBlob(): AsyncGenerator<string> {\n const size = dataSrc.size;\n let i = 0;\n const buf = new Uint8Array(await dataSrc.arrayBuffer());\n do {\n // Find null (or / at PDF) or newLine, and make chunks.\n // To avoid making too much chunks, all chunks should be longer than minimumChunkSize.\n // However, we might have been capped the chunk size due to HTTP request size or document size on CouchDB.\n // The illustration is as follows. Each `[]` will yielded.\n // data | ........ \\0 ....\\0 .... \\0 ...\\0 ...\\0..\n // minimum -- |{--------------} |\n // pieceSize == |[============][..]|\n // minimum -- | |{--------------} |\n // pieceSize == | |[============][...]|\n const findStart = i + minimumChunkSize;\n const defaultSplitEnd = i + pieceSize;\n let splitEnd: number | undefined;\n let i1 = buf.indexOf(delimiter, findStart);\n if (i1 == -1) {\n i1 = buf.indexOf(charNewLine, findStart);\n }\n if (i1 == -1) {\n splitEnd = defaultSplitEnd;\n } else {\n splitEnd = i1 < defaultSplitEnd ? i1 : defaultSplitEnd;\n }\n yield await arrayBufferToBase64Single(buf.slice(i, splitEnd));\n i = splitEnd;\n } while (i < size);\n };\n}\n\nexport async function splitPieces2(\n dataSrc: Blob,\n pieceSize: number,\n plainSplit: boolean,\n minimumChunkSize: number,\n filename?: string,\n useSegmenter?: boolean\n) {\n if (isTextBlob(dataSrc)) {\n return splitPiecesText(await dataSrc.text(), pieceSize, plainSplit, minimumChunkSize, useSegmenter ?? false);\n }\n\n let delimiter = 0; // Split null by default.\n let canBeSmall = false;\n if (filename && filename.endsWith(\".pdf\")) {\n delimiter = \"/\".charCodeAt(0);\n } else if (filename && filename.endsWith(\".json\")) {\n canBeSmall = true;\n delimiter = \",\".charCodeAt(0);\n }\n\n // Optimise chunk size to efficient dedupe.\n const clampMin = canBeSmall ? 100 : 100000; //100kb\n const clampMax = 100000000; //100mb\n const clampedSize = Math.max(clampMin, Math.min(clampMax, dataSrc.size));\n let step = 1;\n let w = clampedSize;\n while (w > 10) {\n w /= 12.5;\n step++;\n }\n minimumChunkSize = Math.floor(10 ** (step - 1));\n\n return async function* piecesBlob(): AsyncGenerator<string> {\n const size = dataSrc.size;\n let i = 0;\n do {\n let splitSize = pieceSize;\n const currentData = new Uint8Array(await dataSrc.slice(i, i + pieceSize).arrayBuffer());\n // Find null (or / at PDF) or newLine, and make chunks.\n // To avoid making too much chunks, all chunks should be longer than minimumChunkSize.\n // However, we might have been capped the chunk size due to HTTP request size or document size on CouchDB.\n // The illustration is as follows. Each `[]` will yielded.\n // data | ........ \\0 ....\\0 .... \\0 ...\\0 ...\\0..\n // minimum -- |{--------------} |\n // pieceSize == |[============][..]|\n // minimum -- | |{--------------} |\n // pieceSize == | |[============][...]|\n let nextIdx = currentData.indexOf(delimiter, minimumChunkSize);\n splitSize = nextIdx == -1 ? pieceSize : Math.min(pieceSize, nextIdx);\n if (nextIdx == -1) nextIdx = currentData.indexOf(charNewLine, minimumChunkSize);\n const piece = currentData.slice(0, splitSize);\n i += piece.length;\n const b64 = await arrayBufferToBase64Single(piece);\n yield b64;\n } while (i < size);\n };\n}\n\nexport async function splitPiecesRabinKarp(\n dataSrc: Blob,\n absoluteMaxPieceSize: number,\n doPlainSplit: boolean,\n minimumChunkSize: number,\n _filename?: string,\n _useSegmenter?: boolean\n): Promise<() => AsyncGenerator<string, void, unknown>> {\n let plainSplit = doPlainSplit || isTextBlob(dataSrc);\n const dataSize = dataSrc.size;\n let chunkUnitPlain = 64; // 64 bytes for text\n const MAX_CHUNK_COUNT = 500;\n if (plainSplit) {\n const isDataSizeTooLargeForPlainSplit = dataSize >= 4 * 1024 * 1024; // 4 MB\n if (isDataSizeTooLargeForPlainSplit) {\n // For very large text files, we should increase the chunk size to avoid producing too many chunks, which can cause performance issues in replication and syncing.\n plainSplit = false;\n } else {\n let estimatedChunkCount: number;\n do {\n estimatedChunkCount = dataSize / (chunkUnitPlain * 4);\n if (estimatedChunkCount > MAX_CHUNK_COUNT) {\n // If the estimated chunk count is too large, we should increase the chunk size to reduce the number of chunks.\n chunkUnitPlain += 32;\n }\n } while (estimatedChunkCount > MAX_CHUNK_COUNT);\n }\n }\n\n const chunkUnitBinary = 256 * 1024; // 256KB for binary\n\n // Use fixed target sizes to keep chunking predictable and avoid overly small binary chunks.\n\n const fixedAvgChunkSize = plainSplit ? chunkUnitPlain * 4 : chunkUnitBinary * 4; // 256B (in unit) for text, 1MB for binary\n const fixedMaxChunkSize = plainSplit ? chunkUnitPlain * 16 : chunkUnitBinary * 16; // 1KB for text, 4MB for binary\n // 4BM is enough. The file might be smaller than 4GB, hence splitting into 4MB chunks will produce at most 4000 chunks, or around.\n const fixedMinChunkSize = plainSplit ? chunkUnitPlain * 2 : chunkUnitBinary; // 128B for text, 256KB for binary\n // 30KB is the absolute minimum for Rabin-Karp to work efficiently, as the hash window is 48 bytes and we need enough data to find boundaries.\n const rkAbsoluteMaxPieceSizeFloor = 30 * 1024;\n\n const effectiveAbsoluteMaxPieceSize = Math.max(absoluteMaxPieceSize, rkAbsoluteMaxPieceSizeFloor);\n const maxChunkSize = Math.min(fixedMaxChunkSize, effectiveAbsoluteMaxPieceSize);\n const minChunkSize = Math.min(Math.max(fixedMinChunkSize, minimumChunkSize), maxChunkSize);\n const avgChunkSize = Math.min(Math.max(fixedAvgChunkSize, minChunkSize), maxChunkSize);\n\n const windowSize = 48;\n\n // Rabin-Karp chunking illustration:\n\n // 1. The data is processed in a rolling hash manner, where each byte contributes to the hash.\n // Yielding candidate is keep glowing until the hash matches the boundary pattern.\n // Data: |---------------------------------------------------------------|\n // Buffer: |---------------...===>|\n // Hash window: | |<---48--->|\n\n // 2. The hash computed over the sliding window of 48 bytes got a modulus === 1, indicating a potential chunk boundary.\n // Data: |---------------------------------------------------------------|\n // Buffer: |{---- CANDIDATE ----}|\n // Hash window: | |<---48--->| ==> hashModulus % 1 == 0\n\n // 3. But, if the current chunk size is shorter than the minimum chunk size, we continue to grow the candidate.\n // |<=========MINIMUM=========>|========MAXIMUM=======>| |\n // Data: |---------------------------------------------------------------|\n // Buffer: |{---- CANDIDATE ----}|\n // Hash window: | |<---48--->| ==> hashModulus % 1 == 0\n\n // 4. If the current chunk size is longer than the minimum chunk size, we want to yield the buffer. However, we must check.\n // |<=========MINIMUM=========>|========MAXIMUM=======>| |\n // Data: |---------------------------------------------------------------|\n // Buffer: |{---- CANDIDATE -------------}|\n // Hash window: | |<---48--->| ==> hashModulus % 1 == 0\n\n // Check the last byte of the hash window to ensure it does not split in the middle of a surrogate pair (for text).\n // (if `*` is the surrogate pair, progress the position to the next byte and extends the candidate), and find the next candidate.\n // |<=========MINIMUM=========>|========MAXIMUM=======>| |\n // Data: |---------------------------------------------------------------|\n // Buffer: |{---- CANDIDATE ------------*-}|\n\n // 5. Yield the candidate as a chunk, and reset the buffer, and continue processing the data.\n\n // Probability of the hash modulus matching the boundary pattern is inversely proportional to the average chunk size. This is a notable very property so I very impressed.\n // (This means that, when aiming for 100 bytes, there is a 1 in 100 chance of matching the boundary pattern).\n const hashModulus = avgChunkSize;\n const boundaryPattern = 1;\n\n const PRIME = 31;\n let P_pow_w = 1;\n for (let i = 0; i < windowSize - 1; i++) {\n P_pow_w = Math.imul(P_pow_w, PRIME);\n }\n\n const buffer = new Uint8Array(await dataSrc.arrayBuffer());\n let pos = 0;\n\n let hash = 0;\n let start = 0;\n const isText = isTextBlob(dataSrc);\n\n const length = buffer.length;\n return async function* piecesBlob() {\n while (pos < length) {\n // Process the internal buffer byte by byte.\n const byte = buffer[pos];\n\n // Update the rolling hash.\n if (pos >= start + windowSize) {\n const oldByte = buffer[pos - windowSize];\n const oldByteTerm = Math.imul(oldByte, P_pow_w);\n hash = (hash - oldByteTerm) | 0;\n hash = Math.imul(hash, PRIME);\n hash = (hash + byte) | 0;\n } else {\n hash = Math.imul(hash, PRIME);\n hash = (hash + byte) | 0;\n }\n\n const currentChunkSize = pos - start + 1;\n let isBoundaryCandidate = false;\n\n // Boundary judgement.\n if (currentChunkSize >= minChunkSize) {\n if ((hash >>> 0) % hashModulus === boundaryPattern) {\n isBoundaryCandidate = true;\n }\n }\n if (currentChunkSize >= maxChunkSize) {\n isBoundaryCandidate = true;\n }\n // Extract the chunk.\n if (isBoundaryCandidate) {\n let isSafeBoundary = true;\n // For text, ensure we do not split in the middle of a multi-byte character.\n if (isText) {\n if (pos + 1 < length && (buffer[pos + 1] & 0xc0) === 0x80) {\n isSafeBoundary = false;\n }\n }\n if (isSafeBoundary) {\n if (isText) {\n yield Promise.resolve(readString(buffer.subarray(start, pos + 1)));\n } else {\n yield await arrayBufferToBase64Single(buffer.subarray(start, pos + 1));\n }\n start = pos + 1;\n }\n }\n pos++;\n }\n // After the stream ends, yield the remaining data in the buffer as the last chunk.\n if (start < length) {\n if (isText) {\n yield Promise.resolve(readString(buffer.subarray(start, length)));\n } else {\n yield await arrayBufferToBase64Single(buffer.subarray(start, length));\n }\n }\n };\n}\n\n// This may used as compatibilities for old version, but now disabled.\nexport async function splitPiecesRabinKarpOld(\n dataSrc: Blob,\n absoluteMaxPieceSize: number,\n doPlainSplit: boolean,\n minimumChunkSize: number,\n _filename?: string,\n _useSegmenter?: boolean\n) {\n const plainSplit = doPlainSplit || isTextBlob(dataSrc);\n // Minimum piece size is 128 bytes for text, 4KB for binary.\n const minPieceSize = plainSplit ? 128 : 1024 * 4;\n // For text, split into 20 pieces (5%) on average; for binary, split into 12 pieces on average.\n // 128 bytes or 5% of the file size, whichever is larger.\n // Therefore, for a 10KB text file, the average chunk size is 500B; for 1MB, 50KB; for 10MB, 500KB.\n // If the file is smaller than 128 bytes, the chunk size is 128 bytes. This means that for files smaller than 1KB, the chunk size is 128 bytes.\n const splitPieceCount = plainSplit ? 20 : 12;\n const avgChunkSize = Math.max(minPieceSize, Math.floor(dataSrc.size / splitPieceCount));\n const maxChunkSize = Math.min(absoluteMaxPieceSize, avgChunkSize * 5);\n const minChunkSize = Math.min(Math.max(Math.floor(avgChunkSize / 4), minimumChunkSize), maxChunkSize);\n const windowSize = 48;\n\n // Rabin-Karp chunking illustration:\n\n // 1. The data is processed in a rolling hash manner, where each byte contributes to the hash.\n // Yielding candidate is keep glowing until the hash matches the boundary pattern.\n // Data: |---------------------------------------------------------------|\n // Buffer: |---------------...===>|\n // Hash window: | |<---48--->|\n\n // 2. The hash computed over the sliding window of 48 bytes got a modulus === 1, indicating a potential chunk boundary.\n // Data: |---------------------------------------------------------------|\n // Buffer: |{---- CANDIDATE ----}|\n // Hash window: | |<---48--->| ==> hashModulus % 1 == 0\n\n // 3. But, if the current chunk size is shorter than the minimum chunk size, we continue to grow the candidate.\n // |<=========MINIMUM=========>|========MAXIMUM=======>| |\n // Data: |---------------------------------------------------------------|\n // Buffer: |{---- CANDIDATE ----}|\n // Hash window: | |<---48--->| ==> hashModulus % 1 == 0\n\n // 4. If the current chunk size is longer than the minimum chunk size, we want to yield the buffer. However, we must check.\n // |<=========MINIMUM=========>|========MAXIMUM=======>| |\n // Data: |---------------------------------------------------------------|\n // Buffer: |{---- CANDIDATE -------------}|\n // Hash window: | |<---48--->| ==> hashModulus % 1 == 0\n\n // Check the last byte of the hash window to ensure it does not split in the middle of a surrogate pair (for text).\n // (if `*` is the surrogate pair, progress the position to the next byte and extends the candidate), and find the next candidate.\n // |<=========MINIMUM=========>|========MAXIMUM=======>| |\n // Data: |---------------------------------------------------------------|\n // Buffer: |{---- CANDIDATE ------------*-}|\n\n // 5. Yield the candidate as a chunk, and reset the buffer, and continue processing the data.\n\n // Probability of the hash modulus matching the boundary pattern is inversely proportional to the average chunk size. This is a notable very property so I very impressed.\n // (This means that, when aiming for 100 bytes, there is a 1 in 100 chance of matching the boundary pattern).\n const hashModulus = avgChunkSize;\n const boundaryPattern = 1;\n\n const PRIME = 31;\n let P_pow_w = 1;\n for (let i = 0; i < windowSize - 1; i++) {\n P_pow_w = Math.imul(P_pow_w, PRIME);\n }\n\n const buffer = new Uint8Array(await dataSrc.arrayBuffer());\n let pos = 0;\n\n let hash = 0;\n let start = 0;\n const isText = isTextBlob(dataSrc);\n\n const length = buffer.length;\n return async function* piecesBlob() {\n while (pos < length) {\n // Process the internal buffer byte by byte.\n const byte = buffer[pos];\n\n // Update the rolling hash.\n if (pos >= start + windowSize) {\n const oldByte = buffer[pos - windowSize];\n const oldByteTerm = Math.imul(oldByte, P_pow_w);\n hash = (hash - oldByteTerm) | 0;\n hash = Math.imul(hash, PRIME);\n hash = (hash + byte) | 0;\n } else {\n hash = Math.imul(hash, PRIME);\n hash = (hash + byte) | 0;\n }\n\n const currentChunkSize = pos - start + 1;\n let isBoundaryCandidate = false;\n\n // Boundary judgement.\n if (currentChunkSize >= minChunkSize) {\n if ((hash >>> 0) % hashModulus === boundaryPattern) {\n isBoundaryCandidate = true;\n }\n }\n if (currentChunkSize >= maxChunkSize) {\n isBoundaryCandidate = true;\n }\n\n // Extract the chunk.\n if (isBoundaryCandidate) {\n let isSafeBoundary = true;\n // For text, ensure we do not split in the middle of a multi-byte character.\n if (isText) {\n if (pos + 1 < length && (buffer[pos + 1] & 0xc0) === 0x80) {\n isSafeBoundary = false;\n }\n }\n if (isSafeBoundary) {\n if (isText) {\n yield Promise.resolve(readString(buffer.subarray(start, pos + 1)));\n } else {\n yield await arrayBufferToBase64Single(buffer.subarray(start, pos + 1));\n }\n start = pos + 1;\n }\n }\n pos++;\n }\n // After the stream ends, yield the remaining data in the buffer as the last chunk.\n if (start < length) {\n if (isText) {\n yield Promise.resolve(readString(buffer.subarray(start, length)));\n } else {\n yield await arrayBufferToBase64Single(buffer.subarray(start, length));\n }\n }\n };\n}\n","// A mock for bgWorker (For environments where Worker cannot be used).\nimport { decrypt, encrypt } from \"octagonal-wheels/encryption/index.js\";\nimport { encrypt as encryptHKDF, decrypt as decryptHKDF } from \"octagonal-wheels/encryption/hkdf\";\n\nimport { splitPieces2, splitPieces2V2, splitPiecesRabinKarp } from \"@lib/string_and_binary/chunks.ts\";\nimport type { EncryptHKDFProcessItem, EncryptProcessItem, SplitProcessItem, ProcessItem } from \"./universalTypes.ts\";\nimport { promiseWithResolvers } from \"octagonal-wheels/promises\";\nimport type { LiveSyncEventHub } from \"@lib/hub/hub.ts\";\n\nexport type SplitArguments = {\n key: number;\n type: \"split\";\n dataSrc: Blob;\n pieceSize: number;\n plainSplit: boolean;\n minimumChunkSize: number;\n filename?: string;\n useV2: boolean;\n useSegmenter: boolean;\n};\n\nexport type EncryptArguments = {\n key: number;\n type: \"encrypt\" | \"decrypt\";\n input: string;\n passphrase: string;\n autoCalculateIterations: boolean;\n};\n\nexport type EncryptHKDFArguments = {\n key: number;\n type: \"encryptHKDF\" | \"decryptHKDF\";\n input: string;\n passphrase: string;\n pbkdf2Salt: Uint8Array;\n};\n\nexport function terminateWorker() {\n return;\n}\n\nexport function splitPieces2Worker(\n dataSrc: Blob,\n pieceSize: number,\n plainSplit: boolean,\n minimumChunkSize: number,\n filename?: string,\n useSegmenter?: boolean\n) {\n return splitPieces2(dataSrc, pieceSize, plainSplit, minimumChunkSize, filename, useSegmenter ?? false);\n}\nexport function splitPieces2WorkerV2(\n dataSrc: Blob,\n pieceSize: number,\n plainSplit: boolean,\n minimumChunkSize: number,\n filename?: string,\n useSegmenter?: boolean\n) {\n return splitPieces2V2(dataSrc, pieceSize, plainSplit, minimumChunkSize, filename, useSegmenter ?? false);\n}\nexport function splitPieces2WorkerRabinKarp(\n dataSrc: Blob,\n pieceSize: number,\n plainSplit: boolean,\n minimumChunkSize: number,\n filename?: string,\n useSegmenter?: boolean\n) {\n return async function* () {\n const splitter = await splitPiecesRabinKarp(\n dataSrc,\n pieceSize,\n plainSplit,\n minimumChunkSize,\n filename,\n useSegmenter ?? false\n );\n yield* splitter();\n };\n}\n\nexport function encryptWorker(input: string, passphrase: string, autoCalculateIterations: boolean): Promise<string> {\n return encrypt(input, passphrase, autoCalculateIterations);\n}\n\nexport function decryptWorker(input: string, passphrase: string, autoCalculateIterations: boolean) {\n return decrypt(input, passphrase, autoCalculateIterations);\n}\n\nexport function encryptHKDFWorker(\n input: string,\n passphrase: string,\n pbkdf2Salt: Uint8Array<ArrayBuffer>\n): Promise<string> {\n return encryptHKDF(input, passphrase, pbkdf2Salt);\n}\n\nexport function decryptHKDFWorker(\n input: string,\n passphrase: string,\n pbkdf2Salt: Uint8Array<ArrayBuffer>\n): Promise<string> {\n return decryptHKDF(input, passphrase, pbkdf2Salt);\n}\n\nexport function startWorker(data: Omit<EncryptHKDFArguments, \"key\">): EncryptHKDFProcessItem;\nexport function startWorker(data: Omit<EncryptArguments, \"key\">): EncryptProcessItem;\nexport function startWorker(data: Omit<SplitArguments, \"key\">): SplitProcessItem;\nexport function startWorker(data: Omit<EncryptArguments | SplitArguments | EncryptHKDFArguments, \"key\">): ProcessItem {\n const task = promiseWithResolvers<string>();\n task.resolve(\"\");\n return {\n task: task,\n key: 0,\n type: data.type,\n finalize: () => {\n // No op\n },\n };\n}\n\nexport const tasks = new Map<number, ProcessItem>();\n\nexport function initialiseWorkerModule(_events: LiveSyncEventHub) {}\n","import { ChunkAlgorithms } from \"@lib/common/types.ts\";\nimport { splitPiecesRabinKarp } from \"@lib/string_and_binary/chunks.ts\";\nimport { splitPieces2WorkerRabinKarp } from \"#worker\";\nimport type { ContentSplitterOptions, SplitOptions } from \"./ContentSplitter.ts\";\nimport { ContentSplitterBase } from \"./ContentSplitterBase.ts\";\n/**\n * Rabin-Karp content splitter for efficient chunking\n */\nexport class ContentSplitterRabinKarp extends ContentSplitterBase {\n static override isAvailableFor(setting: ContentSplitterOptions): boolean {\n const settings = setting.settingService.currentSettings();\n return settings.chunkSplitterVersion === ChunkAlgorithms.RabinKarp;\n }\n async processSplit(\n options: SplitOptions\n ): Promise<AsyncGenerator<string, void, unknown> | Generator<string, void, unknown>> {\n if (options.useWorker) {\n return (\n await splitPieces2WorkerRabinKarp(\n options.blob,\n options.pieceSize,\n options.plainSplit,\n options.minimumChunkSize,\n options.path\n )\n )();\n } else {\n return (\n await splitPiecesRabinKarp(\n options.blob,\n options.pieceSize,\n options.plainSplit,\n options.minimumChunkSize,\n options.path\n )\n )();\n }\n }\n}\n","import { ChunkAlgorithms } from \"@lib/common/types\";\nimport { splitPieces2 } from \"@lib/string_and_binary/chunks\";\nimport { splitPieces2Worker } from \"#worker\";\nimport type { ContentSplitterOptions, SplitOptions } from \"./ContentSplitter\";\nimport { ContentSplitterBase } from \"./ContentSplitterBase\";\n\n/**\n * Legacy content splitter for version 1.\n */\nexport class ContentSplitterV1 extends ContentSplitterBase {\n static override isAvailableFor(setting: ContentSplitterOptions): boolean {\n const settings = setting.settingService.currentSettings();\n return (\n settings.chunkSplitterVersion === ChunkAlgorithms.V1 ||\n settings.chunkSplitterVersion === \"\" ||\n settings.chunkSplitterVersion === undefined\n );\n }\n async processSplit(\n options: SplitOptions\n ): Promise<AsyncGenerator<string, void, unknown> | Generator<string, void, unknown>> {\n if (options.useWorker) {\n return (\n await splitPieces2Worker(\n options.blob,\n options.pieceSize,\n options.plainSplit,\n options.minimumChunkSize,\n options.path,\n options.useSegmenter\n )\n )();\n } else {\n return (\n await splitPieces2(\n options.blob,\n options.pieceSize,\n options.plainSplit,\n options.minimumChunkSize,\n options.path,\n options.useSegmenter\n )\n )();\n }\n }\n}\n","import { ChunkAlgorithms } from \"@lib/common/types.ts\";\nimport { splitPieces2V2 } from \"@lib/string_and_binary/chunks.ts\";\nimport { splitPieces2WorkerV2 } from \"#worker\";\nimport type { ContentSplitterOptions, SplitOptions } from \"./ContentSplitter.ts\";\nimport { ContentSplitterBase } from \"./ContentSplitterBase.ts\";\n\n/**\n * Content splitter for version 2, which supports segmenter-based splitting.\n */\nexport class ContentSplitterV2 extends ContentSplitterBase {\n static override isAvailableFor(setting: ContentSplitterOptions): boolean {\n const settings = setting.settingService.currentSettings();\n return (\n settings.chunkSplitterVersion === ChunkAlgorithms.V2 ||\n settings.chunkSplitterVersion === ChunkAlgorithms.V2Segmenter\n );\n }\n async processSplit(\n options: SplitOptions\n ): Promise<AsyncGenerator<string, void, unknown> | Generator<string, void, unknown>> {\n if (options.useWorker) {\n return (\n await splitPieces2WorkerV2(\n options.blob,\n options.pieceSize,\n options.plainSplit,\n options.minimumChunkSize,\n options.path,\n options.useSegmenter\n )\n )();\n } else {\n return (\n await splitPieces2V2(\n options.blob,\n options.pieceSize,\n options.plainSplit,\n options.minimumChunkSize,\n options.path,\n options.useSegmenter\n )\n )();\n }\n }\n}\n","import type { SavingEntry } from \"@lib/common/types\";\nimport type { ContentSplitterOptions } from \"./ContentSplitter\";\nimport { ContentSplitterCore, type ContentSplitterBase } from \"./ContentSplitterBase\";\nimport { ContentSplitterRabinKarp } from \"./ContentSplitterRabinKarp\";\nimport { ContentSplitterV1 } from \"./ContentSplitterV1\";\nimport { ContentSplitterV2 } from \"./ContentSplitterV2\";\n\nconst ContentSplitters = [ContentSplitterV1, ContentSplitterV2, ContentSplitterRabinKarp];\n/**\n * ContentSplitter class that manages the active content splitter based on the provided settings.\n */\nexport class ContentSplitter extends ContentSplitterCore {\n // The base constructor calls initialise(). `declare` prevents a class-field\n // initialiser from overwriting the selected splitter after super() returns.\n declare _activeSplitter: ContentSplitterBase;\n constructor(options: ContentSplitterOptions) {\n super(options);\n }\n initialise(options: ContentSplitterOptions): Promise<boolean> {\n for (const Splitter of ContentSplitters) {\n if (Splitter.isAvailableFor(options)) {\n this._activeSplitter = new Splitter(options);\n break;\n }\n }\n if (!this._activeSplitter) {\n // Mostly this should not happen, but if no splitter is available, throw an error\n throw new Error(`ContentSplitter: No available splitter for settings!!`);\n }\n return this._activeSplitter.initialise(options);\n }\n async splitContent(\n entry: SavingEntry\n ): Promise<AsyncGenerator<string, void, unknown> | Generator<string, void, unknown>> {\n await this.initialised;\n return this._activeSplitter.splitContent(entry);\n }\n}\n","import { LOG_LEVEL_VERBOSE, Logger } from \"@lib/common/logger.ts\";\nimport { FallbackWeakRef } from \"octagonal-wheels/common/polyfill\";\n\n/**\n * Options for configuring the ChangeManager.\n */\nexport interface ChangeManagerOptions {\n /**\n * The PouchDB database instance to monitor for changes.\n */\n database: PouchDB.Database<object>;\n}\n\nexport type ChangeManagerCallback<T extends object = object> = (\n change: PouchDB.Core.ChangesResponseChange<T>\n) => void | Promise<void>;\n\n/**\n * Manages and dispatches changes from a PouchDB database to registered callbacks.\n *\n * @template T The type of documents stored in the PouchDB database.\n */\nexport class ChangeManager<T extends object = object> {\n /**\n * The PouchDB database instance being monitored.\n */\n _database: PouchDB.Database<T>;\n\n /**\n * Creates a new instance of the ChangeManager.\n *\n * @param options - Configuration options for the ChangeManager.\n */\n constructor(options: ChangeManagerOptions) {\n this._database = options.database as PouchDB.Database<T>;\n this.setupListener();\n }\n\n /**\n * A list of registered callbacks wrapped in WeakRefs to avoid memory leaks.\n */\n _callbacks: FallbackWeakRef<ChangeManagerCallback<T>>[] = [];\n\n /**\n * Registers a new callback to be invoked when a change occurs.\n *\n * @param callback - The callback function to register.\n */\n addCallback(callback: ChangeManagerCallback<T>): () => void {\n const callbackHandler = new FallbackWeakRef(callback);\n this._callbacks.push(callbackHandler);\n return () => {\n this._callbacks = this._callbacks.filter((cb) => cb !== callbackHandler);\n };\n }\n removeCallback(callback: ChangeManagerCallback<T>): void {\n this._callbacks = this._callbacks.filter((cb) => cb.deref() !== callback);\n }\n\n /**\n * The PouchDB changes feed instance, if active.\n */\n _changes?: PouchDB.Core.Changes<T>;\n\n /**\n * Handles a change event from the PouchDB changes feed.\n *\n * @param changeResponse - The change response object from the PouchDB changes feed.\n */\n async _onChange(changeResponse: PouchDB.Core.ChangesResponseChange<T>): Promise<void> {\n if (!this._callbacks.length) {\n return;\n }\n // Cleanup dead WeakRefs\n this._callbacks = this._callbacks.filter((callback) => callback.deref() !== undefined);\n for (const callback of this._callbacks) {\n try {\n const cb = callback.deref();\n if (!cb) {\n continue;\n }\n await Promise.resolve(cb(changeResponse));\n } catch (err) {\n this._changes?.emit(\"error\", err);\n }\n }\n }\n\n /**\n * Sets up the PouchDB changes feed listener to monitor for database changes.\n */\n setupListener(): void {\n if (this._changes) {\n const changes = this._changes;\n this._changes = undefined;\n void changes.removeAllListeners();\n changes.cancel();\n }\n\n const changes = this._database.changes({\n since: \"now\",\n live: true,\n include_docs: true,\n });\n void changes.on(\"change\", (change) => {\n void this._onChange(change);\n });\n void changes.on(\"error\", (err) => {\n Logger(\"ChangeManager Error watching changes\");\n Logger(err, LOG_LEVEL_VERBOSE);\n // void this.restartWatch();\n });\n this._changes = changes;\n }\n\n /**\n * Tears down the PouchDB changes feed listener and cleans up resources.\n */\n teardown(): void {\n void this._changes?.removeAllListeners();\n this._changes?.cancel();\n this._changes = undefined;\n }\n\n /**\n * Restarts the PouchDB changes feed listener.\n */\n restartWatch(): void {\n void this.teardown();\n void this.setupListener();\n }\n}\n","import { LOG_LEVEL_VERBOSE, Logger } from \"@lib/common/logger.ts\";\nimport { promiseWithResolvers } from \"octagonal-wheels/promises\";\nimport type { DocumentID, EntryDoc, EntryLeaf } from \"@lib/common/types.ts\";\nimport type { ChangeManager } from \"@lib/managers/ChangeManager.ts\";\nimport { EVENT_MISSING_CHUNK_REMOTE, EVENT_MISSING_CHUNKS, EVENT_CHUNK_FETCHED } from \"@lib/managers/ChunkFetcher.ts\";\nimport { DatabaseReadLayer } from \"./LayeredChunkManager/DatabaseReadLayer.ts\";\nimport { CacheLayer } from \"./LayeredChunkManager/CacheLayer.ts\";\nimport { ArrivalWaitLayer } from \"./LayeredChunkManager/ArrivalWaitLayer.ts\";\nimport { DatabaseWriteLayer } from \"./LayeredChunkManager/DatabaseWriteLayer.ts\";\nimport type { IReadLayer, IWriteLayer } from \"./LayeredChunkManager/ChunkLayerInterfaces.ts\";\nimport type {\n ChunkManagerEventMap,\n ChunkManagerOptions,\n ChunkReadOptions,\n ChunkWriteOptions,\n WriteResult,\n} from \"./LayeredChunkManager/types.ts\";\nimport { unique } from \"octagonal-wheels/collection\";\nimport { ChunkDeliveryCoordinator } from \"./ChunkDeliveryCoordinator.ts\";\n\n/**\n * ChunkManager class that manages chunk operations such as reading, writing, and caching.\n * Now uses a middleware layer architecture for read and write operations.\n */\nexport class LayeredChunkManager {\n protected options: ChunkManagerOptions;\n protected eventTarget: EventTarget = new EventTarget();\n\n // Middleware layers\n private cacheLayer: CacheLayer;\n private databaseReadLayer: DatabaseReadLayer;\n private readLayers: IReadLayer[];\n private writeLayers: IWriteLayer[];\n private arrivalWaitLayer: ArrivalWaitLayer;\n readonly deliveryCoordinator: ChunkDeliveryCoordinator;\n\n get changeManager(): ChangeManager<EntryDoc> {\n return this.options.changeManager;\n }\n get database(): PouchDB.Database<EntryDoc> {\n return this.options.database;\n }\n\n // Expose cache statistics\n get cacheStatistics() {\n return this.cacheLayer.getStatistics();\n }\n\n addListener<K extends keyof ChunkManagerEventMap>(\n type: K,\n listener: (this: LayeredChunkManager, ev: ChunkManagerEventMap[K]) => void,\n options?: boolean | AddEventListenerOptions\n ): () => void {\n const callback = (ev: CustomEvent<ChunkManagerEventMap[K]>) => {\n listener.call(this, ev.detail);\n };\n this.eventTarget.addEventListener(type, callback as EventListener, options);\n return () => {\n this.eventTarget.removeEventListener(type, callback as EventListener, options);\n };\n }\n emitEvent<K extends keyof ChunkManagerEventMap>(type: K, detail: ChunkManagerEventMap[K]): void {\n const event = new CustomEvent(type, { detail });\n this.eventTarget.dispatchEvent(event);\n }\n\n protected abort: AbortController = new AbortController();\n\n // Change listener cleanup\n protected offChangeHandler: ReturnType<typeof this.changeManager.addCallback>;\n\n // initialisation promise to ensure the manager is ready before processing transactions\n protected initialised = Promise.resolve();\n\n async _initialise() {\n Logger(\"ChunkManager initialised\", LOG_LEVEL_VERBOSE);\n // TODO: Add chunkpack\n return await Promise.resolve();\n }\n\n constructor(options: ChunkManagerOptions) {\n this.options = options;\n const settings = options.settingService.currentSettings();\n const maxCacheSize = settings.hashCacheMaxCount * 10;\n\n // Initialize cache layer\n this.cacheLayer = new CacheLayer(maxCacheSize);\n this.databaseReadLayer = new DatabaseReadLayer(this.database);\n\n // Initialise the shared arrival/fetch activity coordinator and wait layer.\n this.deliveryCoordinator = new ChunkDeliveryCoordinator(options.finiteReplicationActivity);\n this.arrivalWaitLayer = new ArrivalWaitLayer(\n (eventName: string, data: DocumentID[]) => {\n if (eventName === \"missingChunks\") {\n this.emitEvent(EVENT_MISSING_CHUNKS, data);\n }\n },\n this.deliveryCoordinator,\n (ids) =>\n this.databaseReadLayer.read(\n [...ids],\n { preventRemoteRequest: true, skipCache: true, waitForDelivery: false },\n (remaining) => Promise.resolve(remaining.map(() => false))\n )\n );\n\n // Build read layers pipeline: Cache → Database → ArrivalWait\n // Cache layer implements IReadLayer interface\n this.readLayers = [this.cacheLayer, this.databaseReadLayer, this.arrivalWaitLayer];\n\n // Build write layers pipeline: HotPack → Database → Cache\n // Cache layer implements IWriteLayer interface at the end\n this.writeLayers = [\n // new HotPackLayer(),\n new DatabaseWriteLayer(this.database),\n this.cacheLayer,\n ];\n\n // Set up change listener\n this.offChangeHandler = this.changeManager.addCallback(this.onChangeHandler);\n this.addListener(EVENT_CHUNK_FETCHED, this.onChunkArrivedHandler, { signal: this.abort.signal });\n this.addListener(EVENT_MISSING_CHUNK_REMOTE, this.onMissingChunkRemoteHandler, { signal: this.abort.signal });\n\n this.initialised = this._initialise();\n }\n\n destroy(): void {\n const layers = unique([...this.readLayers, ...this.writeLayers]);\n this.abort.abort();\n this.offChangeHandler();\n for (const layer of layers) {\n if (layer.tearDown) {\n layer.tearDown();\n }\n }\n this.deliveryCoordinator.dispose();\n }\n\n // Cache management methods (delegated to cacheLayer)\n getCachedChunk(id: DocumentID): EntryLeaf | false {\n return this.cacheLayer.getCachedChunk(id);\n }\n\n getChunkIDFromCache(data: string): DocumentID | false {\n return this.cacheLayer.getChunkIDFromCache(data);\n }\n\n cacheChunk(chunk: EntryLeaf): void {\n this.cacheLayer.cacheChunk(chunk);\n }\n\n // reorderChunk(id: DocumentID): void {\n // this.cacheLayer.reorderChunk(id);\n // }\n\n // deleteCachedChunk(id: DocumentID): void {\n // this.cacheLayer.deleteCachedChunk(id);\n // }\n\n clearCaches(): void {\n this.cacheLayer.clearCaches();\n }\n\n // Read pipeline execution\n async read(\n ids: DocumentID[],\n options: ChunkReadOptions,\n preloadedChunks?: Record<DocumentID, EntryLeaf>\n ): Promise<(EntryLeaf | false)[]> {\n const order = [...ids];\n const resultMap = new Map<DocumentID, EntryLeaf | false>(ids.map((id) => [id, false]));\n const readIds = new Set([...resultMap.keys()]);\n\n // Handle preloaded chunks\n if (preloadedChunks) {\n for (const [id, chunk] of Object.entries(preloadedChunks) as [DocumentID, EntryLeaf][]) {\n if (this.isChunkDoc(chunk)) {\n this.cacheLayer.cacheChunk(chunk);\n resultMap.set(id, chunk);\n readIds.delete(id);\n }\n }\n }\n\n // Execute read pipeline\n const results = await this.executeReadPipeline([...readIds], options);\n\n // Merge results\n for (let i = 0; i < results.length; i++) {\n if (results[i]) {\n const chunk = results[i] as EntryLeaf;\n resultMap.set(chunk._id, chunk);\n }\n }\n\n // Return in original order\n return order.map((id) => resultMap.get(id) || false);\n }\n\n private executeReadPipeline(ids: DocumentID[], options: ChunkReadOptions): Promise<(EntryLeaf | false)[]> {\n let layerIndex = 0;\n const layers = this.readLayers;\n\n const executeNextLayer = (remaining: DocumentID[]): Promise<(EntryLeaf | false)[]> => {\n if (layerIndex >= layers.length) {\n return Promise.resolve(remaining.map(() => false));\n }\n\n const layer = layers[layerIndex];\n layerIndex++;\n return layer.read(remaining, options, executeNextLayer);\n };\n\n return executeNextLayer(ids);\n }\n\n // Write pipeline execution\n async write(chunks: EntryLeaf[], options: ChunkWriteOptions, origin: DocumentID): Promise<WriteResult> {\n const result = await this.executeWritePipeline(chunks, options, origin);\n return result;\n }\n\n private executeWritePipeline(\n chunks: EntryLeaf[],\n options: ChunkWriteOptions,\n origin: DocumentID\n ): Promise<WriteResult> {\n let layerIndex = 0;\n const layers = this.writeLayers;\n\n const executeNextLayer = (remaining: EntryLeaf[]): Promise<WriteResult> => {\n if (layerIndex >= layers.length) {\n return Promise.resolve({\n result: true,\n processed: {\n cached: 0,\n hotPack: 0,\n written: 0,\n duplicated: 0,\n },\n });\n }\n\n const layer = layers[layerIndex];\n layerIndex++;\n return layer.write(remaining, options, origin, executeNextLayer);\n };\n\n return executeNextLayer(chunks);\n }\n\n // Helper methods\n private isChunkDoc(doc: unknown): doc is EntryLeaf {\n if (typeof doc !== \"object\" || doc === null) {\n return false;\n }\n if (\"_id\" in doc && \"type\" in doc) {\n return doc && typeof doc._id === \"string\" && doc.type === \"leaf\";\n }\n return false;\n }\n\n // Event handlers\n private onChunkArrived(doc: EntryLeaf, deleted: boolean = false): void {\n this.arrivalWaitLayer.onChunkArrived(doc, deleted);\n }\n protected onChunkArrivedHandler = this.onChunkArrived.bind(this);\n\n private onChange(change: PouchDB.Core.ChangesResponseChange<EntryDoc>): void {\n const doc = change.doc;\n if (!doc || !doc._id) {\n return;\n }\n\n if (doc.type !== \"leaf\") {\n return;\n }\n this.onChunkArrived(doc, change.deleted);\n }\n protected onChangeHandler = this.onChange.bind(this);\n\n onMissingChunkRemote(id: DocumentID): void {\n this.arrivalWaitLayer.onMissingChunk(id);\n }\n protected onMissingChunkRemoteHandler = this.onMissingChunkRemote.bind(this);\n\n // Transaction management\n protected concurrentTransactions = 0;\n protected stabilised = Promise.resolve();\n\n async transaction<T>(callback: () => Promise<T>): Promise<T> {\n await this.initialised;\n await this.stabilised;\n this.concurrentTransactions++;\n try {\n const result = await callback();\n return result;\n } finally {\n this.concurrentTransactions--;\n if (this.concurrentTransactions === 0) {\n Logger(`All transactions completed. Performing stabilisation.`, LOG_LEVEL_VERBOSE);\n await this._stabilise();\n } else {\n Logger(`Transaction completed. Remaining: ${this.concurrentTransactions}`, LOG_LEVEL_VERBOSE);\n }\n }\n }\n\n async _stabilise() {\n const pr = promiseWithResolvers<void>();\n this.stabilised = pr.promise;\n try {\n await this.__stabilise();\n } finally {\n pr.resolve();\n }\n }\n\n __stabilise() {\n // Called when idle; can be used to process hot pack or other tasks\n // TODO: Implement hot pack processing\n return Promise.resolve();\n }\n}\n","import { Logger, LOG_LEVEL_VERBOSE } from \"octagonal-wheels/common/logger\";\nimport { LiveSyncError } from \"@lib/common/LSError\";\nimport type { EntryLeaf, DocumentID, EntryDoc } from \"@lib/common/types\";\nimport type { IReadLayer } from \"./ChunkLayerInterfaces\";\nimport type { ChunkReadOptions } from \"./types.ts\";\n\n/**\n * Database read layer - reads chunks from the database\n */\n\nexport class DatabaseReadLayer implements IReadLayer {\n constructor(private database: PouchDB.Database<EntryDoc>) {}\n\n private isChunkDoc(doc: EntryDoc): doc is EntryLeaf {\n return doc && typeof doc._id === \"string\" && doc.type === \"leaf\";\n }\n\n private getError(error: unknown): Error | undefined {\n if (error instanceof Error) {\n return error;\n }\n if (typeof error === \"object\" && error !== null && \"error\" in error && error.error instanceof Error) {\n return error.error;\n }\n return undefined;\n }\n\n private isMissingError(error: unknown): boolean {\n if (typeof error !== \"object\" || error === null) {\n return false;\n }\n if (\"status\" in error && error.status === 404) {\n return true;\n }\n if (\"error\" in error && error.error === \"not_found\") {\n return true;\n }\n if (\"error\" in error) {\n return this.isMissingError(error.error);\n }\n return false;\n }\n\n async read(\n ids: DocumentID[],\n options: ChunkReadOptions,\n next: (remaining: DocumentID[]) => Promise<(EntryLeaf | false)[]>\n ): Promise<(EntryLeaf | false)[]> {\n if (ids.length === 0) {\n return [];\n }\n\n const resultMap = new Map<DocumentID, EntryLeaf | false>();\n const remainingIds: DocumentID[] = [];\n\n try {\n const results = await this.database.allDocs({ keys: ids, include_docs: true });\n\n for (const row of results.rows) {\n if (\"doc\" in row && row.doc && this.isChunkDoc(row.doc)) {\n const chunk = row.doc;\n resultMap.set(chunk._id, chunk);\n } else if (!this.isMissingError(row)) {\n throw new LiveSyncError(`Failed to read chunk ${row.key}`, {\n status: 404,\n cause: this.getError(row),\n });\n } else {\n const idFromRow = typeof row.key === \"string\" ? (row.key as DocumentID) : undefined;\n if (idFromRow) {\n remainingIds.push(idFromRow);\n }\n }\n }\n } catch (error) {\n if (error instanceof LiveSyncError) {\n throw error;\n }\n // For other errors, treat as database read failure\n Logger(`Database read error!`, LOG_LEVEL_VERBOSE);\n Logger(error, LOG_LEVEL_VERBOSE);\n return ids.map(() => false);\n }\n\n // If all chunks were found, return immediately\n if (remainingIds.length === 0) {\n return ids.map((id) => resultMap.get(id) ?? false);\n }\n\n // Get remaining chunks from next layer\n const nextResults = await next(remainingIds);\n const nextResultMap = new Map(remainingIds.map((id, index) => [id, nextResults[index]]));\n\n // Merge results\n const mergedResults = [...ids.map((id) => resultMap.get(id) ?? nextResultMap.get(id) ?? false)];\n // console.log(\"DatabaseReadLayer: Merged results for read\", { ids, mergedResults });\n return mergedResults;\n }\n}\n","import { FallbackWeakRef } from \"octagonal-wheels/common/polyfill\";\nimport type { DocumentID, EntryLeaf } from \"@lib/common/types\";\nimport type { IReadLayer, IWriteLayer } from \"./ChunkLayerInterfaces\";\nimport type { ChunkReadOptions, ChunkWriteOptions, WriteResult } from \"./types.ts\";\n\n/**\n * Cache layer - manages in-memory cache of chunks.\n * Implements both IReadLayer and IWriteLayer for unified cache management.\n * This layer is self-contained and handles cache operations for both read and write operations.\n */\n\nexport class CacheLayer implements IReadLayer, IWriteLayer {\n private caches: Map<DocumentID, FallbackWeakRef<EntryLeaf>> = new Map();\n private maxCacheSize: number;\n allocCount = 0;\n derefCount = 0;\n\n constructor(maxCacheSize: number) {\n this.maxCacheSize = maxCacheSize;\n }\n\n /**\n * Get a cached chunk\n */\n getCachedChunk(id: DocumentID): EntryLeaf | false {\n if (!this.caches.has(id)) {\n return false;\n }\n const weakRef = this.caches.get(id);\n if (weakRef) {\n const cachedChunk = weakRef.deref();\n if (cachedChunk) {\n return cachedChunk;\n } else {\n this.derefCount++;\n this.deleteCachedChunk(id);\n return false;\n }\n }\n return false;\n }\n\n /**\n * Find chunk ID by data content\n */\n getChunkIDFromCache(data: string): DocumentID | false {\n for (const [id, weakRef] of this.caches) {\n const chunk = weakRef.deref();\n if (chunk) {\n if (chunk.data === data) {\n return id;\n }\n } else {\n this.derefCount++;\n this.deleteCachedChunk(id);\n }\n }\n return false;\n }\n\n /**\n * Cache a chunk\n */\n cacheChunk(chunk: EntryLeaf): void {\n if (this.getCachedChunk(chunk._id)) {\n this.reorderChunk(chunk._id);\n return;\n }\n this.caches.set(chunk._id, new FallbackWeakRef(chunk));\n this.allocCount++;\n // Limit cache size\n if (this.caches.size > this.maxCacheSize) {\n do {\n const firstKey = this.caches.keys().next().value;\n if (firstKey) {\n this.caches.delete(firstKey);\n }\n } while (this.caches.size > this.maxCacheSize);\n }\n }\n\n /**\n * Reorder chunk for LRU (move to end)\n */\n reorderChunk(id: DocumentID): void {\n const chunk = this.getCachedChunk(id);\n if (chunk) {\n this.caches.delete(id);\n this.caches.set(id, new FallbackWeakRef(chunk));\n }\n }\n\n /**\n * Delete a cached chunk\n */\n deleteCachedChunk(id: DocumentID): void {\n if (this.caches.has(id)) {\n this.caches.delete(id);\n }\n }\n\n /**\n * Clear all caches\n */\n clearCaches(): void {\n this.caches.clear();\n this.allocCount = 0;\n this.derefCount = 0;\n }\n\n /**\n * Tear down the layer (clear caches on shutdown)\n */\n tearDown(): void {\n this.clearCaches();\n }\n\n /**\n * Get current cache statistics\n */\n getStatistics() {\n return {\n size: this.caches.size,\n allocCount: this.allocCount,\n derefCount: this.derefCount,\n };\n }\n\n /**\n * IReadLayer implementation - read from cache\n */\n async read(\n ids: DocumentID[],\n options: ChunkReadOptions,\n next: (remaining: DocumentID[]) => Promise<(EntryLeaf | false)[]>\n ): Promise<(EntryLeaf | false)[]> {\n if (options.skipCache) {\n return next(ids);\n }\n\n const resultMap = new Map<DocumentID, EntryLeaf | false>();\n const remainingIds: DocumentID[] = [];\n\n for (const id of ids) {\n const cached = this.getCachedChunk(id);\n if (cached) {\n this.reorderChunk(id);\n resultMap.set(id, cached);\n } else {\n remainingIds.push(id);\n }\n }\n\n // If all chunks were found in cache, return immediately\n if (remainingIds.length === 0) {\n return ids.map((id) => resultMap.get(id) || false);\n }\n\n // Get remaining chunks from next layer\n const nextResults = await next(remainingIds);\n const nextResultMap = new Map(remainingIds.map((id, index) => [id, nextResults[index]]));\n\n // Merge results\n return ids.map((id) => resultMap.get(id) ?? nextResultMap.get(id) ?? false);\n }\n\n /**\n * IWriteLayer implementation - cache chunks after database write\n */\n async write(\n chunks: EntryLeaf[],\n options: ChunkWriteOptions,\n origin: DocumentID,\n next: (remaining: EntryLeaf[]) => Promise<WriteResult>\n ): Promise<WriteResult> {\n // Filter out chunks already in cache\n const filtered: EntryLeaf[] = [];\n const cachedCount = chunks.length;\n\n for (const chunk of chunks) {\n const cached = this.getCachedChunk(chunk._id);\n if (!cached) {\n filtered.push(chunk);\n } else {\n this.reorderChunk(chunk._id);\n }\n }\n\n // Pass non-cached chunks to the next layer (database write)\n const result = await next(filtered);\n\n // Cache all chunks (both database-written and pre-cached)\n if (result.result && !options.skipCache) {\n for (const chunk of chunks) {\n this.cacheChunk(chunk);\n }\n }\n\n // Update cache count in the result\n if (result.processed) {\n result.processed.cached = cachedCount - filtered.length;\n }\n\n return result;\n }\n}\n","import { type PromiseWithResolvers, promiseWithResolvers } from \"octagonal-wheels/promises\";\nimport type { DocumentID, EntryLeaf } from \"@lib/common/types\";\nimport type { IReadLayer } from \"./ChunkLayerInterfaces\";\nimport type { ChunkReadOptions } from \"./types.ts\";\nimport { ChunkDeliveryCoordinator } from \"@lib/managers/ChunkDeliveryCoordinator.ts\";\nimport { LOG_LEVEL_VERBOSE, Logger } from \"@lib/common/logger.ts\";\n\nexport type ChunkAvailabilityRecheck = (ids: readonly DocumentID[]) => Promise<readonly (EntryLeaf | false)[]>;\n\n/**\n * Waits only for a delivery lifecycle which is already observable when the\n * local miss is handled. It does not guess at an arrival delay.\n */\nexport class ArrivalWaitLayer implements IReadLayer {\n private readonly waitingMap = new Map<\n DocumentID,\n {\n resolver: PromiseWithResolvers<EntryLeaf | false>;\n observedActivity: boolean;\n activityVersion: number;\n }\n >();\n private readonly eventEmitter: (eventName: string, data: DocumentID[]) => void;\n private readonly deliveryCoordinator: ChunkDeliveryCoordinator;\n private readonly ownsDeliveryCoordinator: boolean;\n private readonly stopObservingActivity: () => void;\n\n constructor(\n eventEmitter: (eventName: string, data: DocumentID[]) => void,\n deliveryCoordinator?: ChunkDeliveryCoordinator,\n private readonly recheckAvailability?: ChunkAvailabilityRecheck\n ) {\n this.eventEmitter = eventEmitter;\n this.deliveryCoordinator = deliveryCoordinator ?? new ChunkDeliveryCoordinator();\n this.ownsDeliveryCoordinator = deliveryCoordinator === undefined;\n this.stopObservingActivity = this.deliveryCoordinator.onChanged((ids) => this.refreshActivity(ids));\n }\n\n private enqueueWaiting(id: DocumentID): Promise<EntryLeaf | false> {\n const previous = this.waitingMap.get(id);\n if (previous) return previous.resolver.promise;\n\n const resolver = promiseWithResolvers<EntryLeaf | false>();\n this.waitingMap.set(id, { activityVersion: 0, observedActivity: false, resolver });\n return resolver.promise;\n }\n\n private settle(id: DocumentID, value: EntryLeaf | false): void {\n const queue = this.waitingMap.get(id);\n if (!queue) return;\n this.waitingMap.delete(id);\n queue.resolver.resolve(value);\n }\n\n private async settleAfterObservedActivity(ids: readonly DocumentID[]): Promise<void> {\n const candidates = ids.flatMap((id) => {\n const queue = this.waitingMap.get(id);\n if (!queue?.observedActivity || this.deliveryCoordinator.isActivityActiveFor(id)) return [];\n const version = ++queue.activityVersion;\n return [{ id, version }];\n });\n if (candidates.length === 0) return;\n\n let results: readonly (EntryLeaf | false)[];\n try {\n results = this.recheckAvailability\n ? await this.recheckAvailability(candidates.map(({ id }) => id))\n : candidates.map(() => false);\n } catch (error) {\n Logger(\"Could not recheck chunk availability after finite delivery activity completed.\", LOG_LEVEL_VERBOSE);\n Logger(error, LOG_LEVEL_VERBOSE);\n results = candidates.map(() => false);\n }\n\n for (let index = 0; index < candidates.length; index++) {\n const { id, version } = candidates[index];\n const queue = this.waitingMap.get(id);\n if (!queue || queue.activityVersion !== version) continue;\n const result = results[index] ?? false;\n if (result) {\n this.settle(id, result);\n } else if (this.deliveryCoordinator.isActivityActiveFor(id)) {\n this.refreshActivity([id]);\n } else {\n this.settle(id, false);\n }\n }\n }\n\n private refreshActivity(ids: readonly DocumentID[] = [...this.waitingMap.keys()]): void {\n const completedActivityIds: DocumentID[] = [];\n for (const id of ids) {\n const queue = this.waitingMap.get(id);\n if (!queue) continue;\n if (this.deliveryCoordinator.isActivityActiveFor(id)) {\n queue.observedActivity = true;\n queue.activityVersion++;\n } else if (queue.observedActivity) {\n completedActivityIds.push(id);\n } else {\n this.settle(id, false);\n }\n }\n if (completedActivityIds.length > 0) {\n void this.settleAfterObservedActivity(completedActivityIds);\n }\n }\n\n /** Handle a chunk document becoming available. */\n onChunkArrived(doc: EntryLeaf, deleted: boolean = false): void {\n this.settle(doc._id, doc._deleted || deleted ? false : doc);\n }\n\n /** Handle an explicit remote-missing result. */\n onMissingChunk(id: DocumentID): void {\n this.settle(id, false);\n }\n\n async read(\n ids: DocumentID[],\n options: ChunkReadOptions,\n next: (remaining: DocumentID[]) => Promise<(EntryLeaf | false)[]>\n ): Promise<(EntryLeaf | false)[]> {\n const waitForDelivery = options.waitForDelivery ?? (options.timeout === undefined || options.timeout > 0);\n if (!waitForDelivery || ids.length === 0) return ids.map(() => false);\n\n const tasks = ids.map((id) => this.enqueueWaiting(id));\n if (!options.preventRemoteRequest) {\n // EventTarget dispatch is synchronous. ChunkFetcher claims the identifiers\n // before this call returns, closing the scheduling gap without a timer.\n this.eventEmitter(\"missingChunks\", ids);\n }\n this.refreshActivity(ids);\n return await Promise.all(tasks);\n }\n\n clearWaiting(): void {\n for (const id of [...this.waitingMap.keys()]) {\n this.settle(id, false);\n }\n }\n\n tearDown(): void {\n this.stopObservingActivity();\n this.clearWaiting();\n if (this.ownsDeliveryCoordinator) {\n this.deliveryCoordinator.dispose();\n }\n }\n\n getWaitingCount(): number {\n return this.waitingMap.size;\n }\n}\n","import { LiveSyncError } from \"@lib/common/LSError\";\nimport type { EntryLeaf, DocumentID, EntryDoc } from \"@lib/common/types\";\nimport type { IWriteLayer } from \"./ChunkLayerInterfaces\";\nimport type { ChunkWriteOptions, WriteResult } from \"./types.ts\";\n\n/**\n * Database write layer - writes chunks to the database\n */\n\nexport class DatabaseWriteLayer implements IWriteLayer {\n constructor(private database: PouchDB.Database<EntryDoc>) {}\n\n async write(\n chunks: EntryLeaf[],\n options: ChunkWriteOptions | undefined = undefined,\n origin: DocumentID,\n next: (remaining: EntryLeaf[]) => Promise<WriteResult>\n ): Promise<WriteResult> {\n if (chunks.length === 0) {\n return next([]);\n }\n\n try {\n const result = await this.database.bulkDocs(chunks, { new_edits: !options?.force });\n const failed = result.filter((res) => \"error\" in res) as PouchDB.Core.Error[];\n\n // Check for non-409 errors\n if (failed.some((res) => res.status !== 409)) {\n throw new LiveSyncError(`Failed to write chunks: ${failed.map((res) => res.error).join(\", \")}`, {\n status: 500,\n });\n }\n\n // Handle 409 conflicts\n const conflictedChunkIDs = failed\n .filter((res) => typeof res.id === \"string\")\n .map((res) => res.id as DocumentID);\n\n // Pass chunks to next layer (e.g., CacheLayer)\n const nextResult = await next(chunks);\n\n // Merge results\n const writeResult: WriteResult = {\n result: true,\n processed: {\n cached: nextResult.processed.cached,\n hotPack: nextResult.processed.hotPack,\n written: result.length - failed.length,\n duplicated: conflictedChunkIDs.length,\n },\n };\n\n if (conflictedChunkIDs.length > 0) {\n // TODO: Handle conflict resolution if needed\n }\n\n return writeResult;\n } catch (error) {\n if (error instanceof LiveSyncError) {\n throw error;\n }\n throw new LiveSyncError(`Database write layer error!`, { status: 500, cause: error as Error });\n }\n }\n}\n","import { type Diff, diff_match_patch, DIFF_DELETE, DIFF_INSERT, DIFF_EQUAL } from \"diff-match-patch\";\nimport { readString, decodeBinary } from \"octagonal-wheels/binary\";\nimport { Logger, LOG_LEVEL_VERBOSE, LOG_LEVEL_INFO } from \"octagonal-wheels/common/logger\";\nimport {\n type EntryDoc,\n type FilePathWithPrefix,\n type diff_result_leaf,\n type LoadedEntry,\n MISSING_OR_ERROR,\n NOT_CONFLICTED,\n type DIFF_CHECK_RESULT_AUTO,\n} from \"@lib/common/types.ts\";\nimport {\n getDocData,\n tryParseJSON,\n generatePatchObj,\n flattenObject,\n applyPatch,\n isSensibleMargeApplicable,\n isObjectMargeApplicable,\n} from \"@lib/common/utils.ts\";\nimport type { EntryManager } from \"@lib/managers/EntryManager/EntryManager.ts\";\nimport { isErrorOfMissingDoc } from \"@lib/pouchdb/utils_couchdb.ts\";\nimport type { IPathService } from \"@lib/services/base/IService.ts\";\n\ntype AutoMergeOutcomeOK = {\n ok: DIFF_CHECK_RESULT_AUTO;\n};\n\ntype AutoMergeCanBeDoneByDeletingRev = {\n result: string;\n conflictedRev: string;\n};\n\ntype UserActionRequired = {\n leftRev: string;\n rightRev: string;\n leftLeaf: diff_result_leaf | false;\n rightLeaf: diff_result_leaf | false;\n};\n\ntype ConflictCandidate = {\n revision: string;\n leaf: diff_result_leaf | false;\n};\n\nfunction revisionGeneration(revision: string): number {\n const generation = Number(revision.split(\"-\", 1)[0]);\n return Number.isFinite(generation) ? generation : Number.MAX_SAFE_INTEGER;\n}\n\nfunction compareConflictCandidates(left: ConflictCandidate, right: ConflictCandidate): number {\n const generationDifference = revisionGeneration(left.revision) - revisionGeneration(right.revision);\n if (generationDifference !== 0) return generationDifference;\n\n // A missing modification time is reviewed first. It must not acquire\n // accidental priority from PouchDB's internal leaf enumeration order.\n const leftMtime =\n left.leaf === false || !Number.isFinite(left.leaf.mtime) ? Number.NEGATIVE_INFINITY : left.leaf.mtime;\n const rightMtime =\n right.leaf === false || !Number.isFinite(right.leaf.mtime) ? Number.NEGATIVE_INFINITY : right.leaf.mtime;\n const mtimeDifference = leftMtime - rightMtime;\n if (mtimeDifference !== 0) return mtimeDifference;\n\n // Compare the complete revision IDs by code unit so the final tie-breaker\n // is independent of the host locale.\n if (left.revision < right.revision) return -1;\n if (left.revision > right.revision) return 1;\n return 0;\n}\n\nexport type AutoMergeResult = Promise<AutoMergeOutcomeOK | AutoMergeCanBeDoneByDeletingRev | UserActionRequired>;\n\nexport interface ConflictManagerOptions {\n entryManager: EntryManager;\n pathService: IPathService;\n database: PouchDB.Database<EntryDoc>;\n}\nexport class ConflictManager {\n options: ConflictManagerOptions;\n constructor(options: ConflictManagerOptions) {\n this.options = options;\n }\n get database(): PouchDB.Database<EntryDoc> {\n return this.options.database;\n }\n\n async getConflictedDoc(path: FilePathWithPrefix, rev: string): Promise<false | diff_result_leaf> {\n try {\n const doc = await this.options.entryManager.getDBEntry(path, { rev: rev }, false, true, true);\n if (doc === false) return false;\n let data = getDocData(doc.data);\n if (doc.datatype == \"newnote\") {\n data = readString(new Uint8Array(decodeBinary(doc.data)));\n } else if (doc.datatype == \"plain\") {\n // NO OP.\n }\n return {\n deleted: doc.deleted || doc._deleted,\n ctime: doc.ctime,\n mtime: doc.mtime,\n rev: rev,\n data: data,\n };\n } catch (ex) {\n if (isErrorOfMissingDoc(ex)) {\n return false;\n }\n }\n return false;\n }\n async mergeSensibly(\n path: FilePathWithPrefix,\n baseRev: string,\n currentRev: string,\n conflictedRev: string\n ): Promise<Diff[] | false> {\n const baseLeaf = await this.getConflictedDoc(path, baseRev);\n const leftLeaf = await this.getConflictedDoc(path, currentRev);\n const rightLeaf = await this.getConflictedDoc(path, conflictedRev);\n let autoMerge = false;\n if (baseLeaf == false || leftLeaf == false || rightLeaf == false) {\n return false;\n }\n if (leftLeaf.deleted || rightLeaf.deleted) {\n // Either one is deleted\n return false;\n }\n // diff between base and each revision\n const dmp = new diff_match_patch();\n const mapLeft = dmp.diff_linesToChars_(baseLeaf.data, leftLeaf.data);\n const diffLeftSrc = dmp.diff_main(mapLeft.chars1, mapLeft.chars2, false);\n dmp.diff_charsToLines_(diffLeftSrc, mapLeft.lineArray);\n const mapRight = dmp.diff_linesToChars_(baseLeaf.data, rightLeaf.data);\n const diffRightSrc = dmp.diff_main(mapRight.chars1, mapRight.chars2, false);\n dmp.diff_charsToLines_(diffRightSrc, mapRight.lineArray);\n function splitDiffPiece(src: Diff[]): Diff[] {\n const ret = [] as Diff[];\n do {\n const d = src.shift();\n if (d === undefined) {\n return ret;\n }\n const pieces = d[1].split(/([^\\n]*\\n)/).filter((f) => f != \"\");\n if (typeof d == \"undefined\") {\n break;\n }\n if (d[0] != DIFF_DELETE) {\n ret.push(...pieces.map((e) => [d[0], e] as Diff));\n }\n if (d[0] == DIFF_DELETE) {\n const nd = src.shift();\n\n if (typeof nd != \"undefined\") {\n const piecesPair = nd[1].split(/([^\\n]*\\n)/).filter((f) => f != \"\");\n if (nd[0] == DIFF_INSERT) {\n // it might be pair\n for (const pt of pieces) {\n ret.push([d[0], pt]);\n const pairP = piecesPair.shift();\n if (typeof pairP != \"undefined\") ret.push([DIFF_INSERT, pairP]);\n }\n ret.push(...piecesPair.map((e) => [nd[0], e] as Diff));\n } else {\n ret.push(...pieces.map((e) => [d[0], e] as Diff));\n ret.push(...piecesPair.map((e) => [nd[0], e] as Diff));\n }\n } else {\n ret.push(...pieces.map((e) => [0, e] as Diff));\n }\n }\n } while (src.length > 0);\n return ret;\n }\n\n const diffLeft = splitDiffPiece(diffLeftSrc);\n const diffRight = splitDiffPiece(diffRightSrc);\n\n let rightIdx = 0;\n let leftIdx = 0;\n const merged = [] as Diff[];\n autoMerge = true;\n LOOP_MERGE: do {\n if (leftIdx >= diffLeft.length && rightIdx >= diffRight.length) {\n break LOOP_MERGE;\n }\n const leftItem = diffLeft[leftIdx] ?? [0, \"\"];\n const rightItem = diffRight[rightIdx] ?? [0, \"\"];\n leftIdx++;\n rightIdx++;\n // Same unchanged line on both sides: keep it once.\n if (leftItem[0] == DIFF_EQUAL && rightItem[0] == DIFF_EQUAL && leftItem[1] == rightItem[1]) {\n merged.push(leftItem);\n continue;\n }\n if (leftItem[0] == DIFF_DELETE && rightItem[0] == DIFF_DELETE && leftItem[1] == rightItem[1]) {\n // Same deletion on both sides is safe. If only one side immediately inserts a replacement,\n // this is a delete-vs-edit overlap and must remain a manual conflict.\n const nextLeftIdx = leftIdx;\n const nextRightIdx = rightIdx;\n const [nextLeftItem, nextRightItem] = [\n diffLeft[nextLeftIdx] ?? [0, \"\"],\n diffRight[nextRightIdx] ?? [0, \"\"],\n ];\n const nextLeftIsInsert = nextLeftItem[0] == DIFF_INSERT;\n const nextRightIsInsert = nextRightItem[0] == DIFF_INSERT;\n if (nextLeftIsInsert != nextRightIsInsert) {\n autoMerge = false;\n break;\n }\n if (nextLeftIsInsert && nextRightIsInsert && nextLeftItem[1] != nextRightItem[1]) {\n // Both sides replaced the same deleted line differently.\n autoMerge = false;\n break;\n }\n merged.push(leftItem);\n continue;\n }\n // Insertions are additive. If both sides inserted different content at the same\n // position, keep both in a deterministic mtime order.\n if (leftItem[0] == DIFF_INSERT && rightItem[0] == DIFF_INSERT) {\n if (leftItem[1] == rightItem[1]) {\n merged.push(leftItem);\n continue;\n } else {\n // sort by file date.\n if (leftLeaf.mtime <= rightLeaf.mtime) {\n merged.push(leftItem);\n merged.push(rightItem);\n continue;\n } else {\n merged.push(rightItem);\n merged.push(leftItem);\n continue;\n }\n }\n }\n // A one-sided insertion does not consume the other side's current line.\n if (leftItem[0] == DIFF_INSERT) {\n rightIdx--;\n merged.push(leftItem);\n continue;\n }\n if (rightItem[0] == DIFF_INSERT) {\n leftIdx--;\n merged.push(rightItem);\n continue;\n }\n // Apart from insertions, mismatched line contents mean the regions are no\n // longer aligned enough for a safe automatic merge.\n if (rightItem[1] != leftItem[1]) {\n //TODO: SHOULD BE PANIC.\n Logger(\n `MERGING PANIC:${leftItem[0]},${leftItem[1]} == ${rightItem[0]},${rightItem[1]}`,\n LOG_LEVEL_VERBOSE\n );\n autoMerge = false;\n break LOOP_MERGE;\n }\n if (leftItem[0] == DIFF_DELETE) {\n if (rightItem[0] == DIFF_EQUAL) {\n // One side deleted a line the other side left unchanged. Prefer the\n // deletion; final content generation drops DIFF_DELETE entries.\n merged.push(leftItem);\n continue;\n } else {\n //we cannot perform auto merge.\n autoMerge = false;\n break LOOP_MERGE;\n }\n }\n if (rightItem[0] == DIFF_DELETE) {\n if (leftItem[0] == DIFF_EQUAL) {\n // Symmetric safe deletion.\n merged.push(rightItem);\n continue;\n } else {\n //we cannot perform auto merge.\n autoMerge = false;\n break LOOP_MERGE;\n }\n }\n Logger(\n `Weird condition:${leftItem[0]},${leftItem[1]} == ${rightItem[0]},${rightItem[1]}`,\n LOG_LEVEL_VERBOSE\n );\n // here is the exception\n break LOOP_MERGE;\n } while (leftIdx < diffLeft.length || rightIdx < diffRight.length);\n if (autoMerge) {\n Logger(`Sensibly merge available`, LOG_LEVEL_VERBOSE);\n return merged;\n } else {\n return false;\n }\n }\n\n async mergeObject(\n path: FilePathWithPrefix,\n baseRev: string,\n currentRev: string,\n conflictedRev: string\n ): Promise<string | false> {\n try {\n const baseLeaf = await this.getConflictedDoc(path, baseRev);\n const leftLeaf = await this.getConflictedDoc(path, currentRev);\n const rightLeaf = await this.getConflictedDoc(path, conflictedRev);\n if (baseLeaf == false || leftLeaf == false || rightLeaf == false) {\n Logger(`Could not load leafs for merge`, LOG_LEVEL_VERBOSE);\n Logger(\n `${baseLeaf ? \"base\" : \"missing base\"}, ${leftLeaf ? \"left\" : \"missing left\"}, ${rightLeaf ? \"right\" : \"missing right\"} }`,\n LOG_LEVEL_VERBOSE\n );\n return false;\n }\n if (leftLeaf.deleted || rightLeaf.deleted) {\n Logger(`Either is deleted`, LOG_LEVEL_VERBOSE);\n return false;\n }\n const baseObj = { data: tryParseJSON(baseLeaf.data, {}) } as Record<string | number | symbol, unknown>;\n const leftObj = { data: tryParseJSON(leftLeaf.data, {}) } as Record<string | number | symbol, unknown>;\n const rightObj = { data: tryParseJSON(rightLeaf.data, {}) } as Record<string | number | symbol, unknown>;\n\n const diffLeft = generatePatchObj(baseObj, leftObj);\n const diffRight = generatePatchObj(baseObj, rightObj);\n\n // If each value of the same key has been modified, the automatic merge should be prevented.\n //TODO Does it have to be a configurable item?\n const diffSetLeft = new Map(flattenObject(diffLeft));\n const diffSetRight = new Map(flattenObject(diffRight));\n for (const [key, value] of diffSetLeft) {\n if (diffSetRight.has(key)) {\n if (diffSetRight.get(key) == value) {\n // No matter, if changed to the same value.\n diffSetRight.delete(key);\n }\n }\n }\n for (const [key, value] of diffSetRight) {\n if (diffSetLeft.has(key) && diffSetLeft.get(key) != value) {\n // Some changes are conflicted\n Logger(`Conflicted key:${key}`, LOG_LEVEL_VERBOSE);\n return false;\n }\n }\n\n const patches = [\n { mtime: leftLeaf.mtime, patch: diffLeft },\n { mtime: rightLeaf.mtime, patch: diffRight },\n ].sort((a, b) => a.mtime - b.mtime);\n let newObj = { ...baseObj };\n for (const patch of patches) {\n newObj = applyPatch(newObj, patch.patch);\n }\n Logger(`Object merge is applicable!`, LOG_LEVEL_VERBOSE);\n return JSON.stringify(newObj.data);\n } catch (ex) {\n Logger(\"Could not merge object\");\n Logger(ex, LOG_LEVEL_VERBOSE);\n return false;\n }\n }\n async tryAutoMergeSensibly(path: FilePathWithPrefix, test: LoadedEntry, conflicts: string[]) {\n const conflictedRev = conflicts[0];\n let commonBase = \"\";\n try {\n const documentId = await this.options.pathService.path2id(path);\n const [currentBranch, conflictedBranch] = await Promise.all([\n this.database.get<EntryDoc>(documentId, { rev: test._rev, revs_info: true }),\n this.database.get<EntryDoc>(documentId, { rev: conflictedRev, revs_info: true }),\n ]);\n const currentAvailable = new Set(\n (currentBranch._revs_info || [])\n .filter((revision) => revision.status === \"available\")\n .map((revision) => revision.rev)\n );\n commonBase =\n (conflictedBranch._revs_info || [])\n .filter((revision) => revision.status === \"available\" && currentAvailable.has(revision.rev))\n .sort((left, right) => Number(right.rev.split(\"-\")[0]) - Number(left.rev.split(\"-\")[0]))[0]?.rev ??\n \"\";\n } catch (ex) {\n Logger(`Could not determine the common revision for ${path}`, LOG_LEVEL_VERBOSE);\n Logger(ex, LOG_LEVEL_VERBOSE);\n return false;\n }\n let p = undefined;\n if (commonBase) {\n if (isSensibleMargeApplicable(path)) {\n const result = await this.mergeSensibly(path, commonBase, test._rev!, conflictedRev);\n if (result) {\n p = result\n .filter((e) => e[0] != DIFF_DELETE)\n .map((e) => e[1])\n .join(\"\");\n // can be merged.\n Logger(`Sensible merge:${path}`, LOG_LEVEL_INFO);\n } else {\n Logger(`Sensible merge is not applicable.`, LOG_LEVEL_VERBOSE);\n }\n } else if (isObjectMargeApplicable(path)) {\n // can be merged.\n const result = await this.mergeObject(path, commonBase, test._rev!, conflictedRev);\n if (result) {\n Logger(`Object merge:${path}`, LOG_LEVEL_INFO);\n p = result;\n } else {\n Logger(`Object merge is not applicable..`, LOG_LEVEL_VERBOSE);\n }\n }\n if (p !== undefined) {\n return { result: p, conflictedRev };\n }\n }\n return false;\n }\n async tryAutoMerge(path: FilePathWithPrefix, enableMarkdownAutoMerge: boolean): AutoMergeResult {\n const test = await this.options.entryManager.getDBEntry(\n path,\n { conflicts: true, revs_info: true },\n false,\n false,\n true\n );\n if (test === false) return { ok: MISSING_OR_ERROR };\n if (test == null) return { ok: MISSING_OR_ERROR };\n if (!test._conflicts) return { ok: NOT_CONFLICTED };\n if (test._conflicts.length == 0) return { ok: NOT_CONFLICTED };\n const conflictCandidates = await Promise.all(\n test._conflicts.map(\n async (revision): Promise<ConflictCandidate> => ({\n revision,\n leaf: await this.getConflictedDoc(path, revision),\n })\n )\n );\n conflictCandidates.sort(compareConflictCandidates);\n const conflicts = conflictCandidates.map(({ revision }) => revision);\n // Resolve identical conflict leaves without creating a new revision.\n const leftLeaf = await this.getConflictedDoc(path, test._rev!);\n const rightLeaf = conflictCandidates[0].leaf;\n if (\n leftLeaf !== false &&\n rightLeaf !== false &&\n leftLeaf.data == rightLeaf.data &&\n leftLeaf.deleted == rightLeaf.deleted\n ) {\n return { leftRev: test._rev!, rightRev: conflicts[0], leftLeaf, rightLeaf };\n }\n if ((isSensibleMargeApplicable(path) || isObjectMargeApplicable(path)) && enableMarkdownAutoMerge) {\n const autoMergeResult = await this.tryAutoMergeSensibly(path, test, conflicts);\n if (autoMergeResult !== false) {\n return autoMergeResult;\n }\n }\n // should be one or more conflicts;\n return { leftRev: test._rev!, rightRev: conflicts[0], leftLeaf, rightLeaf };\n }\n}\n","import type PouchDB from \"pouchdb-core\";\nimport { Logger, LOG_LEVEL_VERBOSE, LOG_LEVEL_NOTICE } from \"octagonal-wheels/common/logger\";\nimport {\n type SavingEntry,\n type EntryLeaf,\n type DocumentID,\n type EntryDoc,\n type NewEntry,\n type PlainEntry,\n IDPrefixes,\n type EntryBase,\n type EntryDocResponse,\n type FilePath,\n type FilePathWithPrefix,\n type LoadedEntry,\n REMOTE_COUCHDB,\n type ObsidianLiveSyncSettings,\n type MetaEntry,\n RemoteTypes,\n type NoteEntry,\n} from \"@lib/common/types\";\nimport type { ContentSplitter } from \"@lib/ContentSplitter/ContentSplitters\";\nimport type { HashManager } from \"@lib/managers/HashManager/HashManager\";\nimport type { LayeredChunkManager as ChunkManager } from \"@lib/managers/LayeredChunkManager\";\nimport type { ChunkWriteOptions } from \"@lib/managers/LayeredChunkManager/types\";\nimport { serialized } from \"octagonal-wheels/concurrency/lock\";\nimport { createTextBlob, getFileRegExp, isTextBlob } from \"@lib/common/utils\";\nimport { compatGlobal } from \"@lib/common/coreEnvFunctions\";\nimport type { NecessaryServicesInterfaces } from \"@lib/interfaces/ServiceModule\";\nimport { isErrorOfMissingDoc } from \"@lib/pouchdb/utils_couchdb\";\nimport { stripAllPrefixes } from \"@lib/string_and_binary/path\";\nimport { ICHeader, ICXHeader, PSCHeader } from \"@lib/common/models/fileaccess.const\";\nimport type { GeneratedChunk } from \"@lib/pouchdb/LiveSyncLocalDB\";\n\ntype Managers = {\n hashManager: HashManager;\n chunkManager: ChunkManager;\n splitter: ContentSplitter;\n localDatabase: PouchDB.Database<EntryDoc>;\n};\ntype NecessaryManagers<T extends keyof Managers> = Pick<Managers, T>;\n/** Select ancestry and stale-base handling when writing document metadata. */\ntype PutDBEntryRevisionTarget =\n /** Use the current winning revision, retaining the legacy forced-write behaviour. */\n | { mode: \"latest\" }\n /** Branch from this exact revision, even when it has already acquired children. */\n | { mode: \"force-base\"; baseRevision: string }\n /** Advance this exact live leaf through MVCC; a stale base must fail with 409. */\n | { mode: \"live-base\"; baseRevision: string }\n /** Preserve unknown ancestry as a fresh, parentless branch of the same document. */\n | { mode: \"independent-root\" };\n\nexport async function createChunks(\n managers: NecessaryManagers<\"chunkManager\" | \"hashManager\" | \"splitter\">,\n dispFilename: string,\n note: SavingEntry\n) {\n const { chunkManager, splitter } = managers;\n let bufferedChunk = [] as EntryLeaf[];\n let bufferedSize = 0;\n\n let writeCount = 0;\n let newCount = 0;\n let cachedCount = 0;\n let resultCachedCount = 0;\n let duplicatedCount = 0;\n let totalWritingCount = 0;\n let createChunkCount = 0;\n // If total size of current buffered chunks exceeds this, they will be flushed to the database to avoid memory extravagance.\n const MAX_WRITE_SIZE = 1000 * 1024 * 2; // 2MB\n const chunks: DocumentID[] = [];\n\n let writeChars = 0;\n const flushBufferedChunks = async () => {\n if (bufferedChunk.length === 0) {\n Logger(`No chunks to flush for ${dispFilename}`, LOG_LEVEL_VERBOSE);\n return true;\n }\n const writeBuf = [...bufferedChunk];\n bufferedSize = 0;\n bufferedChunk = [];\n const result = await chunkManager.write(\n writeBuf,\n {\n skipCache: false,\n timeout: 0,\n } as ChunkWriteOptions,\n note._id\n );\n if (result.result === false) {\n Logger(`Failed to write buffered chunks for ${dispFilename}`, LOG_LEVEL_NOTICE);\n return false;\n }\n totalWritingCount++;\n writeCount += result.processed.written;\n resultCachedCount += result.processed.cached;\n duplicatedCount += result.processed.duplicated;\n writeChars += writeBuf.map((e) => e.data.length).reduce((a, b) => a + b, 0);\n // chunks.push(...writeBuf.map((e) => e._id));\n Logger(`Flushed ${writeBuf.length} (${writeChars}) chunks for ${dispFilename}`, LOG_LEVEL_VERBOSE);\n return true;\n };\n const flushIfNeeded = async () => {\n if (bufferedSize > MAX_WRITE_SIZE) {\n if (!(await flushBufferedChunks())) {\n Logger(`Failed to flush buffered chunks for ${dispFilename}`, LOG_LEVEL_NOTICE);\n return false;\n }\n }\n return true;\n };\n const addBuffer = async (id: DocumentID, data: string) => {\n const chunk = {\n _id: id,\n data: data,\n type: \"leaf\",\n } as const;\n bufferedChunk.push(chunk);\n chunks.push(chunk._id);\n bufferedSize += chunk.data.length;\n return await flushIfNeeded();\n };\n const pieces = await splitter.splitContent(note);\n let totalChunkCount = 0;\n try {\n for await (const piece of pieces) {\n totalChunkCount++;\n if (piece.length === 0) {\n continue;\n }\n createChunkCount++;\n const chunk = await prepareChunk(managers, piece);\n cachedCount += chunk.isNew ? 0 : 1;\n newCount += chunk.isNew ? 1 : 0;\n if (!(await addBuffer(chunk.id, chunk.piece))) {\n return false;\n }\n }\n } catch (ex) {\n Logger(`Error processing pieces for ${dispFilename}`);\n Logger(ex, LOG_LEVEL_VERBOSE);\n return false;\n }\n if (!(await flushBufferedChunks())) {\n return false;\n }\n\n const dataSize = note.data.size;\n const stats = `(✨: ${newCount}, 🗃️: ${cachedCount} (${resultCachedCount}) / 🗄️: ${writeCount}, ♻:${duplicatedCount})`;\n Logger(\n `Chunks processed for ${dispFilename} (${dataSize}): 📚:${totalChunkCount} (${createChunkCount}) , 📥:${totalWritingCount} ${stats}`,\n LOG_LEVEL_VERBOSE\n );\n\n if (dataSize > 0 && totalWritingCount === 0) {\n Logger(\n `No data to save in ${dispFilename}!! This document may be corrupted in the local database! Please back it up immediately, and report an issue!`,\n LOG_LEVEL_NOTICE\n );\n }\n return chunks;\n}\n\nexport async function putDBEntry(\n host: NecessaryServicesInterfaces<\"path\" | \"setting\", never>,\n managers: NecessaryManagers<\"localDatabase\" | \"chunkManager\" | \"hashManager\" | \"splitter\">,\n note: SavingEntry,\n onlyChunks?: boolean,\n conflictBaseRev?: string\n) {\n const revisionTarget: PutDBEntryRevisionTarget = conflictBaseRev\n ? { mode: \"force-base\", baseRevision: conflictBaseRev }\n : { mode: \"latest\" };\n return await putDBEntryInternal(host, managers, note, onlyChunks, revisionTarget);\n}\n\n/**\n * Store an entry below an exact revision only while that revision remains a live leaf.\n *\n * PouchDB's ordinary MVCC write is the authority for this check. A 409 response means that the\n * base has already been advanced, so the caller receives `false` and can retry from fresh state.\n */\nexport async function putDBEntryWithLiveBaseRevision(\n host: NecessaryServicesInterfaces<\"path\" | \"setting\", never>,\n managers: NecessaryManagers<\"localDatabase\" | \"chunkManager\" | \"hashManager\" | \"splitter\">,\n note: SavingEntry,\n baseRevision: string,\n onlyChunks?: boolean\n) {\n try {\n return await putDBEntryInternal(host, managers, note, onlyChunks, {\n mode: \"live-base\",\n baseRevision,\n });\n } catch (ex) {\n if (ex && typeof ex === \"object\" && \"status\" in ex && ex.status === 409) {\n return false;\n }\n throw ex;\n }\n}\n\n/**\n * Preserve content with unknown ancestry as a fresh parentless revision of the same document.\n * Store the body as Chunks as usual, then insert a Metadata root with a random revision ID using\n * `new_edits: false`. This retains existing branches without reusing an identical historical root.\n * Return the Metadata write result, or `false` when the entry cannot be stored.\n */\nexport async function putDBEntryAsIndependentRoot(\n host: NecessaryServicesInterfaces<\"path\" | \"setting\", never>,\n managers: NecessaryManagers<\"localDatabase\" | \"chunkManager\" | \"hashManager\" | \"splitter\">,\n note: SavingEntry\n) {\n return await putDBEntryInternal(host, managers, note, false, { mode: \"independent-root\" });\n}\n\nasync function putDBEntryInternal(\n host: NecessaryServicesInterfaces<\"path\" | \"setting\", never>,\n managers: NecessaryManagers<\"localDatabase\" | \"chunkManager\" | \"hashManager\" | \"splitter\">,\n note: SavingEntry,\n onlyChunks: boolean | undefined,\n revisionTarget: PutDBEntryRevisionTarget\n) {\n const { localDatabase, chunkManager, splitter } = managers;\n\n //safety valve\n const filename = host.services.path.id2path(note._id, note);\n const dispFilename = stripAllPrefixes(filename);\n\n //prepare eden\n if (!note.eden) note.eden = {};\n\n if (!isTargetFile(host, filename)) {\n Logger(`File skipped:${dispFilename}`, LOG_LEVEL_VERBOSE);\n return false;\n }\n\n // Set datatype again for modified datatype.\n const data = note.data instanceof Blob ? note.data : createTextBlob(note.data);\n note.data = data;\n note.type = isTextBlob(data) ? \"plain\" : \"newnote\";\n note.datatype = note.type;\n\n await splitter.initialised;\n\n // TODO: Pack chunks in a single file for performance.\n const result = await chunkManager.transaction(async () => {\n const chunks = await createChunks(managers, dispFilename, note);\n if (chunks === false) {\n return false;\n }\n if (onlyChunks) {\n return {\n id: note._id,\n ok: true,\n rev: \"dummy\",\n };\n }\n\n const newDoc: PlainEntry | NewEntry = {\n children: chunks,\n _id: note._id,\n path: note.path,\n ctime: note.ctime,\n mtime: note.mtime,\n size: note.size,\n type: note.datatype,\n eden: {},\n };\n\n return (\n (await serialized(\"file:\" + filename, async () => {\n if (revisionTarget.mode === \"force-base\" || revisionTarget.mode === \"live-base\") {\n // An explicit base identifies the branch the caller edited. Do not\n // replace it with the winner; the write below controls stale-base policy.\n newDoc._rev = revisionTarget.baseRevision;\n } else if (revisionTarget.mode === \"latest\") {\n // Legacy callers use whichever revision currently wins. A missing\n // document starts a new tree through PouchDB's normal write path.\n try {\n const old = await localDatabase.get(newDoc._id);\n newDoc._rev = old._rev;\n } catch (ex) {\n if (isErrorOfMissingDoc(ex)) {\n // NO OP/\n } else {\n throw ex;\n }\n }\n }\n if (revisionTarget.mode === \"independent-root\") {\n // new_edits:false imports an exact revision tree. A fresh random ID\n // keeps this root distinct even when its metadata and chunk references\n // match a historical root. PouchDB's usual deterministic MD5 would\n // reuse that revision, which cannot preserve a new independent branch.\n // This API accepts the supplied ID; it does not require an MD5 digest.\n const randomBytes = compatGlobal.crypto.getRandomValues(new Uint8Array(16));\n const rootId = Array.from(randomBytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n newDoc._rev = `1-${rootId}`;\n const imported = { ...newDoc, _revisions: { start: 1, ids: [rootId] } };\n await localDatabase.bulkDocs([imported], { new_edits: false });\n const stored = await localDatabase.get(newDoc._id, { rev: newDoc._rev });\n return stored._rev === newDoc._rev ? { id: newDoc._id, ok: true, rev: newDoc._rev } : false;\n }\n // Only live-base relies on ordinary MVCC to reject an advanced base.\n // force:true deliberately preserves an edit as a child of its supplied\n // base, even after replication has added another child to that revision.\n const r =\n revisionTarget.mode === \"live-base\"\n ? await localDatabase.put<PlainEntry | NewEntry>(newDoc)\n : await localDatabase.put<PlainEntry | NewEntry>(newDoc, { force: true });\n if (r.ok) {\n return r;\n } else {\n return false;\n }\n })) ?? false\n );\n });\n if (result === false) {\n Logger(`Failed to write document ${dispFilename}`, LOG_LEVEL_NOTICE);\n return false;\n }\n Logger(`Document saved: ${dispFilename} (${result.id.substring(0, 8)}-${result.rev})`, LOG_LEVEL_VERBOSE);\n return result;\n}\nexport function isTargetFile(host: NecessaryServicesInterfaces<\"setting\", never>, filenameSrc: string) {\n const settings = host.services.setting.currentSettings();\n const file = filenameSrc.startsWith(ICHeader) ? filenameSrc.substring(ICHeader.length) : filenameSrc;\n if (file.startsWith(ICXHeader)) return true;\n if (file.startsWith(PSCHeader)) return true;\n if (file.startsWith(IDPrefixes.Chunk) || file.startsWith(IDPrefixes.Obfuscated)) {\n return false;\n }\n if (!settings.syncInternalFiles) {\n if (file.startsWith(\".\")) {\n return false;\n }\n }\n if (settings.syncOnlyRegEx) {\n const syncOnly = getFileRegExp(settings, \"syncOnlyRegEx\");\n if (syncOnly.length > 0 && !syncOnly.some((e) => e.test(file))) return false;\n }\n if (settings.syncIgnoreRegEx) {\n const syncIgnore = getFileRegExp(settings, \"syncIgnoreRegEx\");\n if (syncIgnore.some((e) => e.test(file))) return false;\n }\n return true;\n}\nexport async function prepareChunk(\n { chunkManager, hashManager }: NecessaryManagers<\"chunkManager\" | \"hashManager\">,\n piece: string\n): Promise<GeneratedChunk> {\n if (hashManager.usesIndependentIdKey()) {\n const id = `${IDPrefixes.Chunk}${await hashManager.computeHash(piece)}` as DocumentID;\n const cached = chunkManager.getCachedChunk(id);\n return { isNew: !cached || cached.data !== piece, id, piece };\n }\n\n const cachedChunkId = chunkManager.getChunkIDFromCache(piece);\n if (cachedChunkId !== false) {\n return { isNew: false, id: cachedChunkId, piece: piece };\n }\n\n // Generate a new chunk ID based on the piece and the hashed passphrase.\n const chunkId = (await hashManager.computeHash(piece)) as DocumentID;\n return { isNew: true, id: `${IDPrefixes.Chunk}${chunkId}` as DocumentID, piece: piece };\n}\n\nexport async function getDBEntryMetaByPath(\n host: NecessaryServicesInterfaces<\"path\" | \"setting\", never>,\n { localDatabase }: NecessaryManagers<\"localDatabase\">,\n path: FilePathWithPrefix | FilePath,\n opt?: PouchDB.Core.GetOptions,\n includeDeleted = false\n): Promise<false | LoadedEntry> {\n if (!isTargetFile(host, path)) {\n return false;\n }\n const id = await host.services.path.path2id(path);\n try {\n let obj: EntryDocResponse | null = null;\n if (opt) {\n obj = await localDatabase.get(id, opt);\n } else {\n obj = await localDatabase.get(id);\n }\n const deleted: boolean | undefined =\n (obj as unknown as { deleted?: boolean })?.deleted ?? obj._deleted ?? undefined;\n if (!includeDeleted && deleted) return false;\n if (obj.type && obj.type == \"leaf\") {\n //do nothing for leaf;\n return false;\n }\n\n // retrieve metadata only\n if (!obj.type || (obj.type && obj.type == \"notes\") || obj.type == \"newnote\" || obj.type == \"plain\") {\n const note = obj as EntryBase;\n let children: string[] = [];\n let type: \"plain\" | \"newnote\" = \"plain\";\n if (obj.type == \"newnote\" || obj.type == \"plain\") {\n children = obj.children;\n type = obj.type;\n }\n const doc: LoadedEntry & PouchDB.Core.IdMeta & PouchDB.Core.GetMeta = {\n data: \"\",\n _id: (note as EntryDoc)._id,\n path: path,\n ctime: note.ctime,\n mtime: note.mtime,\n size: note.size,\n // _deleted: obj._deleted,\n _rev: obj._rev,\n _conflicts: obj._conflicts,\n children: children,\n datatype: type,\n deleted: deleted,\n _revisions: obj?._revisions ?? undefined,\n _revs_info: obj?._revs_info ?? undefined,\n type: type,\n eden: \"eden\" in obj ? obj.eden : {},\n };\n return doc;\n }\n } catch (ex) {\n if (isErrorOfMissingDoc(ex)) {\n return false;\n }\n throw ex;\n }\n return false;\n}\n\nexport function isLegacyNote(meta: LoadedEntry | MetaEntry) {\n return !meta.type || (meta.type && meta.type == \"notes\");\n}\nfunction complementEntryMeta(note: NoteEntry) {\n const deleted = note.deleted ?? note._deleted ?? undefined;\n const doc: LoadedEntry & PouchDB.Core.IdMeta = {\n data: note.data,\n path: note.path,\n _id: note._id,\n ctime: note.ctime,\n mtime: note.mtime,\n size: note.size,\n // _deleted: obj._deleted,\n _rev: note._rev,\n _conflicts: note._conflicts,\n children: [],\n datatype: \"newnote\",\n deleted: deleted,\n type: \"newnote\",\n eden: \"eden\" in note ? note.eden : {},\n };\n return doc;\n}\n\n// only for legacy support. Will be removed in the future. No longer this type will be stored in the database, but we need to support it for a while until all documents are migrated.\nfunction respondOldFashionedEntry(note: NoteEntry, dump = false) {\n const doc = complementEntryMeta(note);\n if (dump) {\n Logger(`--Old fashioned document--`);\n Logger(doc);\n }\n return doc;\n}\n\nexport function canUseOnDemandChunking(settings: ObsidianLiveSyncSettings) {\n if (settings.remoteType !== REMOTE_COUCHDB) {\n return false;\n }\n if (settings.useOnlyLocalChunk) {\n return false;\n }\n return true;\n}\n\nfunction canFetchRemotely(settings: ObsidianLiveSyncSettings) {\n if (!canUseOnDemandChunking(settings)) {\n return false;\n }\n if (settings.remoteType === RemoteTypes.REMOTE_MINIO) {\n return false;\n }\n return true;\n}\n/**\n * Decide how to retrieve chunks based on settings and the caller's read policy.\n * `waitForReady` allows an already-observable finite delivery lifecycle to finish.\n * `localOnly` overrides both settings and waiting for provenance comparisons.\n */\nexport function computeChunkRetrievalMethod(\n waitForReady: boolean,\n settings: ObsidianLiveSyncSettings,\n localOnly = false\n) {\n if (localOnly) {\n return { waitForDelivery: false, preventRemoteRequest: true };\n }\n const isOnDemandFetchEnabled = canFetchRemotely(settings);\n if (!waitForReady) {\n // Normally this requests an immediate local result. CouchDB on-demand\n // delivery is the exception because synchronous dispatch creates a\n // producer claim which has a meaningful completion boundary.\n if (isOnDemandFetchEnabled) {\n return {\n waitForDelivery: true,\n preventRemoteRequest: false,\n };\n }\n return {\n waitForDelivery: false,\n preventRemoteRequest: true,\n };\n }\n // Wait only for an already-observable finite replication, or for the\n // per-identifier claim created by CouchDB on-demand fetching.\n return {\n waitForDelivery: true,\n preventRemoteRequest: !isOnDemandFetchEnabled,\n };\n}\n\nasync function respondEntryFromMeta(\n { localDatabase, chunkManager }: NecessaryManagers<\"localDatabase\" | \"chunkManager\">,\n settings: ObsidianLiveSyncSettings,\n filename: FilePathWithPrefix | FilePath,\n meta: NewEntry | PlainEntry,\n dump: boolean,\n waitForReady: boolean,\n localOnly = false\n) {\n const dispFilename = stripAllPrefixes(filename);\n const deleted = meta.deleted ?? meta._deleted ?? undefined;\n if (dump) {\n const conflicts = await localDatabase.get(meta._id, {\n rev: meta._rev,\n conflicts: true,\n revs_info: true,\n });\n Logger(\"-- Conflicts --\");\n Logger(conflicts._conflicts ?? \"No conflicts\");\n Logger(\"-- Revs info -- \");\n Logger(conflicts._revs_info);\n }\n // search children\n try {\n if (dump) {\n Logger(`--Bare document--`);\n Logger(meta);\n }\n\n // Reading `Eden` for legacy support.\n // It will be removed in the future.\n let edenChunks: Record<string, EntryLeaf> = {};\n if (meta.eden && Object.keys(meta.eden).length > 0) {\n const chunks = Object.entries(meta.eden).map(([id, data]) => ({\n _id: id as DocumentID,\n data: data.data,\n type: \"leaf\",\n })) as EntryLeaf[];\n edenChunks = Object.fromEntries(chunks.map((e) => [e._id, e]));\n }\n\n const { waitForDelivery, preventRemoteRequest } = computeChunkRetrievalMethod(\n waitForReady,\n settings,\n localOnly\n );\n\n const childrenKeys = [...meta.children] as DocumentID[];\n const chunks = await chunkManager.read(\n childrenKeys,\n {\n skipCache: false,\n waitForDelivery,\n preventRemoteRequest: preventRemoteRequest,\n },\n edenChunks\n );\n\n if (chunks.some((e) => e === false)) {\n // TODO EXACT MESSAGE\n throw new Error(\"Load failed\");\n }\n\n const doc: LoadedEntry & PouchDB.Core.IdMeta = {\n data: (chunks as EntryLeaf[]).map((e) => e.data),\n path: meta.path,\n _id: meta._id,\n ctime: meta.ctime,\n mtime: meta.mtime,\n size: meta.size,\n _rev: meta._rev,\n children: meta.children,\n datatype: meta.type,\n _conflicts: meta._conflicts,\n eden: meta.eden,\n deleted: deleted,\n type: meta.type,\n };\n if (dump) {\n Logger(`--Loaded Document--`);\n Logger(doc);\n }\n return doc;\n } catch (ex) {\n if (isErrorOfMissingDoc(ex)) {\n Logger(\n `Missing document content!, could not read ${dispFilename}(${meta._id.substring(0, 8)}) from database.`,\n LOG_LEVEL_NOTICE\n );\n return false;\n }\n Logger(\n `Something went wrong on reading ${dispFilename}(${meta._id.substring(0, 8)}) from database:`,\n LOG_LEVEL_NOTICE\n );\n Logger(ex);\n }\n return false;\n}\n\nexport async function getDBEntryFromMeta(\n host: NecessaryServicesInterfaces<\"path\" | \"setting\", never>,\n { localDatabase, chunkManager }: NecessaryManagers<\"localDatabase\" | \"chunkManager\">,\n meta: LoadedEntry | MetaEntry,\n dump = false,\n waitForReady = true,\n localOnly = false\n) {\n const filename = host.services.path.id2path(meta._id, meta);\n if (!isTargetFile(host, filename)) {\n return false;\n }\n const settings = host.services.setting.currentSettings();\n\n if (isLegacyNote(meta)) {\n // simple note\n const note = meta as NoteEntry;\n return respondOldFashionedEntry(note, dump);\n }\n if (meta.type == \"newnote\" || meta.type == \"plain\") {\n // newnote or plain\n return await respondEntryFromMeta(\n { localDatabase, chunkManager },\n settings,\n filename,\n meta,\n dump,\n waitForReady,\n localOnly\n );\n }\n return false;\n}\nexport async function getDBEntryByPath(\n host: NecessaryServicesInterfaces<\"path\" | \"setting\", never>,\n managers: NecessaryManagers<\"localDatabase\" | \"chunkManager\">,\n path: FilePathWithPrefix | FilePath,\n opt?: PouchDB.Core.GetOptions,\n dump = false,\n waitForReady = true,\n includeDeleted = false,\n localOnly = false\n) {\n const meta = await getDBEntryMetaByPath(host, managers, path, opt, includeDeleted);\n if (meta) {\n return await getDBEntryFromMeta(host, managers, meta, dump, waitForReady, localOnly);\n } else {\n return false;\n }\n}\nexport async function deleteDBEntryByPath(\n host: NecessaryServicesInterfaces<\"path\" | \"setting\", never>,\n { localDatabase }: NecessaryManagers<\"localDatabase\">,\n path: FilePathWithPrefix | FilePath,\n opt?: PouchDB.Core.GetOptions\n): Promise<boolean> {\n if (!isTargetFile(host, path)) {\n return false;\n }\n const id = await host.services.path.path2id(path);\n try {\n return (\n (await serialized(\"file:\" + path, async () => {\n const settings = host.services.setting.currentSettings();\n let obj: EntryDocResponse | null = null;\n if (opt) {\n obj = await localDatabase.get(id, opt);\n } else {\n obj = await localDatabase.get(id);\n }\n const revDeletion = opt && (\"rev\" in opt ? opt.rev : \"\") != \"\";\n\n if (obj.type && obj.type == \"leaf\") {\n //do nothing for leaf;\n return false;\n }\n //Check it out and fix docs to regular case\n if (!obj.type || (obj.type && obj.type == \"notes\")) {\n obj._deleted = true;\n const r = await localDatabase.put(obj, { force: !revDeletion });\n Logger(`Entry removed: ${path} (${obj._id.substring(0, 8)}-${r.rev}) `);\n return true;\n\n // simple note\n }\n if (obj.type == \"newnote\" || obj.type == \"plain\") {\n if (revDeletion) {\n obj._deleted = true;\n } else {\n obj.deleted = true;\n obj.mtime = Date.now();\n if (settings.deleteMetadataOfDeletedFiles) {\n obj._deleted = true;\n }\n }\n const r = await localDatabase.put(obj, { force: !revDeletion });\n\n Logger(\n `Entry removed: [${revDeletion ? \"REV\" : \"DEL\"}] ${path} (${obj._id.substring(0, 8)}-${r.rev})`\n );\n return true;\n } else {\n return false;\n }\n })) ?? false\n );\n } catch (ex) {\n if (isErrorOfMissingDoc(ex)) {\n return false;\n }\n throw ex;\n }\n}\n\nexport async function storeDeletionByPathAtRevision(\n host: NecessaryServicesInterfaces<\"path\" | \"setting\", never>,\n { localDatabase }: NecessaryManagers<\"localDatabase\">,\n path: FilePathWithPrefix | FilePath,\n baseRevision: string\n): Promise<PouchDB.Core.Response | false> {\n if (!isTargetFile(host, path)) {\n return false;\n }\n const id = await host.services.path.path2id(path);\n try {\n return (\n (await serialized(\"file:\" + path, async () => {\n const obj = (await localDatabase.get<EntryDocResponse>(id, {\n rev: baseRevision,\n })) as EntryDocResponse & EntryBase;\n if (obj.type === \"leaf\") {\n return false;\n }\n delete obj._deleted;\n obj.deleted = true;\n obj.mtime = Date.now();\n const result = await localDatabase.put(obj, { force: true });\n Logger(`Entry soft-deleted from revision: ${path} (${obj._id.substring(0, 8)}-${result.rev})`);\n return result;\n })) ?? false\n );\n } catch (ex) {\n if (isErrorOfMissingDoc(ex)) {\n return false;\n }\n throw ex;\n }\n}\n","import {\n type FilePathWithPrefix,\n type FilePath,\n type LoadedEntry,\n type EntryDoc,\n REMOTE_COUCHDB,\n type SavingEntry,\n type MetaEntry,\n} from \"@lib/common/types\";\nimport type { ChunkManager } from \"@lib/managers/ChunkManager\";\nimport type { ContentSplitter } from \"@lib/ContentSplitter/ContentSplitters\";\nimport type { HashManager } from \"@lib/managers/HashManager/HashManager\";\nimport type { GeneratedChunk } from \"@lib/pouchdb/LiveSyncLocalDB\";\nimport type { IPathService, ISettingService } from \"@lib/services/base/IService\";\nimport {\n deleteDBEntryByPath,\n getDBEntryByPath,\n getDBEntryFromMeta,\n getDBEntryMetaByPath,\n isTargetFile,\n prepareChunk,\n putDBEntry,\n putDBEntryWithLiveBaseRevision,\n putDBEntryAsIndependentRoot,\n storeDeletionByPathAtRevision,\n} from \"./EntryManagerImpls\";\n\nexport interface EntryManagerOptions {\n hashManager: HashManager;\n chunkManager: ChunkManager;\n splitter: ContentSplitter;\n database: PouchDB.Database<EntryDoc>;\n settingService: ISettingService;\n pathService: IPathService;\n}\n\nexport class EntryManager {\n options: EntryManagerOptions;\n\n constructor(options: EntryManagerOptions) {\n this.options = options;\n }\n get localDatabase(): PouchDB.Database<EntryDoc> {\n return this.options.database;\n }\n get hashManager(): HashManager {\n return this.options.hashManager;\n }\n get chunkManager(): ChunkManager {\n return this.options.chunkManager;\n }\n\n get splitter(): ContentSplitter {\n return this.options.splitter;\n }\n get serviceHost() {\n return {\n services: {\n setting: this.options.settingService,\n path: this.options.pathService,\n },\n serviceModules: {},\n };\n }\n\n get isOnDemandChunkEnabled() {\n const settings = this.options.settingService.currentSettings();\n if (settings.remoteType !== REMOTE_COUCHDB) {\n return false;\n }\n if (settings.useOnlyLocalChunk) {\n return false;\n }\n return true;\n }\n\n isTargetFile(filenameSrc: string) {\n return isTargetFile(this.serviceHost, filenameSrc);\n }\n\n async prepareChunk(piece: string): Promise<GeneratedChunk> {\n return await prepareChunk(this, piece);\n }\n\n async getDBEntryMeta(\n path: FilePathWithPrefix | FilePath,\n opt?: PouchDB.Core.GetOptions,\n includeDeleted = false\n ): Promise<false | LoadedEntry> {\n return await getDBEntryMetaByPath(this.serviceHost, this, path, opt, includeDeleted);\n }\n async getDBEntry(\n path: FilePathWithPrefix | FilePath,\n opt?: PouchDB.Core.GetOptions,\n dump = false,\n waitForReady = true,\n includeDeleted = false,\n localOnly = false\n ): Promise<false | LoadedEntry> {\n return await getDBEntryByPath(this.serviceHost, this, path, opt, dump, waitForReady, includeDeleted, localOnly);\n }\n async getDBEntryFromMeta(\n meta: LoadedEntry | MetaEntry,\n dump = false,\n waitForReady = true,\n localOnly = false\n ): Promise<false | LoadedEntry> {\n return await getDBEntryFromMeta(this.serviceHost, this, meta, dump, waitForReady, localOnly);\n }\n\n async deleteDBEntry(path: FilePathWithPrefix | FilePath, opt?: PouchDB.Core.GetOptions): Promise<boolean> {\n return await deleteDBEntryByPath(this.serviceHost, this, path, opt);\n }\n\n async storeDeletionAtRevision(path: FilePathWithPrefix | FilePath, baseRevision: string) {\n return await storeDeletionByPathAtRevision(this.serviceHost, this, path, baseRevision);\n }\n\n async putDBEntry(note: SavingEntry, onlyChunks?: boolean, conflictBaseRev?: string) {\n return await putDBEntry(this.serviceHost, this, note, onlyChunks, conflictBaseRev);\n }\n\n async putDBEntryWithLiveBaseRevision(note: SavingEntry, baseRevision: string, onlyChunks?: boolean) {\n return await putDBEntryWithLiveBaseRevision(this.serviceHost, this, note, baseRevision, onlyChunks);\n }\n /** Store unknown ancestry as a fresh root; return the Metadata write result or `false`. */\n async putDBEntryAsIndependentRoot(note: SavingEntry) {\n return await putDBEntryAsIndependentRoot(this.serviceHost, this, note);\n }\n}\n","import { fallbackMixedHashEach, mixedHash } from \"octagonal-wheels/hash/purejs\";\nimport type { ISettingService } from \"@lib/services/base/IService.ts\";\nimport { SALT_OF_ID, SEED_MURMURHASH } from \"@lib/common/models/shared.const.behabiour.ts\";\nimport type { HashAlgorithm } from \"@lib/common/models/setting.type.ts\";\n\n/**\n * Prefix for encrypted hashes.\n *\n * This constant is prepended to hash strings when encryption is enabled.\n */\nexport const HashEncryptedPrefix = \"+\";\n\n/**\n * Options for initialising {@link HashManagerCore}.\n */\nexport type HashManagerCoreOptions = {\n /**\n * Remote database settings used for hash management.\n */\n settingService: ISettingService;\n};\n\n/**\n * Abstract base class for hash management.\n *\n * Provides core logic for handling passphrase hashing, encryption toggling,\n * and initialisation routines. Subclasses should implement encryption-specific\n * hash computation methods.\n */\nexport abstract class HashManagerCore {\n protected settingService: ISettingService;\n\n /**\n * Indicates whether encryption is enabled for hash computation.\n */\n useEncryption: boolean = false;\n\n /**\n * Hashed passphrase as a string, used for hash operations.\n */\n hashedPassphrase: string = \"\";\n\n /**\n * Hashed passphrase as a 32-bit number, used for hash operations.\n */\n hashedPassphrase32: number = 0;\n\n /**\n * Options used for initialisation and configuration.\n */\n options: HashManagerCoreOptions;\n\n /**\n * Constructs a new {@link HashManagerCore} instance.\n *\n * @param options - Configuration options for hash management.\n */\n constructor(options: HashManagerCoreOptions) {\n this.options = options;\n this.settingService = options.settingService;\n this.applyOptions(options);\n }\n\n /**\n * Applies the given options to the hash manager.\n *\n * Updates encryption settings and computes passphrase hashes.\n *\n * @param options - Optional configuration to apply.\n */\n applyOptions(options?: HashManagerCoreOptions): void {\n if (options) {\n this.options = options;\n }\n const settings = this.options.settingService.currentSettings();\n this.useEncryption = settings.encrypt ?? false;\n const passphrase = settings.passphrase || \"\";\n const usingLetters = ~~((passphrase.length / 4) * 3);\n const passphraseForHash = SALT_OF_ID + passphrase.substring(0, usingLetters);\n this.hashedPassphrase = fallbackMixedHashEach(passphraseForHash);\n this.hashedPassphrase32 = mixedHash(passphraseForHash, SEED_MURMURHASH)[0];\n }\n\n /**\n * Performs initialisation logic specific to the hash manager implementation.\n *\n * Subclasses must implement this method.\n *\n * @returns Promise resolving to true if initialisation succeeds.\n */\n abstract processInitialise(): Promise<boolean>;\n\n /**\n * Task representing the initialisation process.\n */\n initialiseTask?: Promise<boolean>;\n\n /**\n * Ensures the hash manager is initialised.\n *\n * Returns a promise that resolves when initialisation is complete.\n *\n * @returns Promise resolving to true if initialisation succeeds.\n */\n initialise(): Promise<boolean> {\n if (this.initialiseTask) {\n return this.initialiseTask;\n }\n this.initialiseTask = this.processInitialise();\n return this.initialiseTask;\n }\n\n /**\n * Computes a hash for the given string.\n *\n * If encryption is enabled, the hash is computed with encryption and prefixed.\n * Otherwise, a plain hash is computed.\n *\n * @param piece - The input string to hash.\n * @returns Promise resolving to the computed hash string.\n */\n async computeHash(piece: string): Promise<string> {\n // if (!this.initialiseTask) {\n // await this.initialise();\n // } else {\n // await this.initialiseTask;\n // }\n if (this.useEncryption) {\n return HashEncryptedPrefix + (await this.computeHashWithEncryption(piece));\n }\n return await this.computeHashWithoutEncryption(piece);\n }\n\n /**\n * Computes a hash for the given string without encryption.\n *\n * Subclasses must implement this method.\n *\n * @param piece - The input string to hash.\n * @returns Promise resolving to the computed hash string.\n */\n abstract computeHashWithoutEncryption(piece: string): Promise<string>;\n\n /**\n * Computes a hash for the given string with encryption.\n *\n * Subclasses must implement this method.\n *\n * @param piece - The input string to hash.\n * @returns Promise resolving to the computed encrypted hash string.\n */\n abstract computeHashWithEncryption(piece: string): Promise<string>;\n\n /**\n * Determines whether the hash manager is available for the specified algorithm.\n *\n * Subclasses should override this method to indicate supported algorithms.\n *\n * @param hashAlg - The hash algorithm to check.\n * @returns True if available, false otherwise.\n */\n static isAvailableFor(hashAlg: HashAlgorithm): boolean {\n return false; // Default implementation; subclasses should override\n }\n}\n","import { HashManagerCore, type HashManagerCoreOptions } from \"./HashManagerCore.ts\";\nimport { xxhashNew } from \"@lib/string_and_binary/hash.ts\";\nimport type { XXHashAPI } from \"xxhash-wasm-102\";\nimport { HashAlgorithms } from \"@lib/common/models/setting.const.ts\";\nimport type { HashAlgorithm } from \"@lib/common/models/setting.type.ts\";\n\n/**\n * Abstract base class for hash managers using XXHash algorithms.\n * Provides initialisation and common properties for XXHash-based managers.\n */\nexport abstract class XXHashHashManager extends HashManagerCore {\n /**\n * Instance of XXHash API used for hashing operations.\n */\n xxhash!: XXHashAPI;\n\n /**\n * Constructs a new XXHashHashManager.\n * @param options - Options for the hash manager core.\n */\n constructor(options: HashManagerCoreOptions) {\n super(options);\n }\n\n /**\n * Initialises the XXHash API instance.\n * @returns A promise resolving to true when initialisation is complete.\n */\n async processInitialise(): Promise<boolean> {\n this.xxhash = await xxhashNew();\n return true;\n }\n}\n\n/**\n * Hash manager for the legacy hash algorithm (empty string).\n * Utilises XXHash32 raw hashing.\n */\nexport class XXHash32RawHashManager extends XXHashHashManager {\n /**\n * Determines whether this manager is available for the specified algorithm.\n * @param hashAlg - The hash algorithm to check.\n * @returns True if available, false otherwise.\n */\n static override isAvailableFor(hashAlg: HashAlgorithm): boolean {\n return hashAlg === HashAlgorithms.LEGACY;\n }\n\n /**\n * Computes a hash for the given piece using encryption.\n * @param piece - The input string to hash.\n * @returns A promise resolving to the hash string.\n */\n computeHashWithEncryption(piece: string): Promise<string> {\n return Promise.resolve(\n (this.xxhash.h32Raw(new TextEncoder().encode(piece)) ^ this.hashedPassphrase32 ^ piece.length).toString(36)\n );\n }\n\n /**\n * Computes a hash for the given piece without encryption.\n * @param piece - The input string to hash.\n * @returns A promise resolving to the hash string.\n */\n computeHashWithoutEncryption(piece: string): Promise<string> {\n return Promise.resolve((this.xxhash.h32Raw(new TextEncoder().encode(piece)) ^ piece.length).toString(36));\n }\n}\n\n/**\n * Hash manager for the XXHash64 algorithm (\"xxhash64\").\n */\nexport class XXHash64HashManager extends XXHashHashManager {\n /**\n * Determines whether this manager is available for the specified algorithm.\n * @param hashAlg - The hash algorithm to check.\n * @returns True if available, false otherwise.\n */\n static override isAvailableFor(hashAlg: HashAlgorithm): boolean {\n return hashAlg === HashAlgorithms.XXHASH64;\n }\n\n /**\n * Computes a hash for the given piece using encryption.\n * @param piece - The input string to hash.\n * @returns A promise resolving to the hash string.\n */\n computeHashWithEncryption(piece: string): Promise<string> {\n return Promise.resolve(this.xxhash.h64(`${piece}-${this.hashedPassphrase}-${piece.length}`).toString(36));\n }\n\n /**\n * Computes a hash for the given piece without encryption.\n * @param piece - The input string to hash.\n * @returns A promise resolving to the hash string.\n */\n computeHashWithoutEncryption(piece: string): Promise<string> {\n return Promise.resolve(this.xxhash.h64(`${piece}-${piece.length}`).toString(36));\n }\n}\n\n/**\n * Fallback hash manager utilising XXHash32.\n * Used when no specific algorithm is matched.\n * Please be careful with this manager, as it is different from XXHash32RawHashManager.\n */\nexport class FallbackWasmHashManager extends XXHashHashManager {\n /**\n * Determines whether this manager is available for the specified algorithm.\n * Always returns true as a fallback.\n * @param hashAlg - The hash algorithm to check.\n * @returns True.\n */\n static override isAvailableFor(hashAlg: HashAlgorithm): boolean {\n return true; // As a fallback hash manager, it is always available.\n }\n\n /**\n * Computes a hash for the given piece using encryption.\n * @param piece - The input string to hash.\n * @returns A promise resolving to the hash string.\n */\n computeHashWithEncryption(piece: string): Promise<string> {\n return Promise.resolve(this.xxhash.h32(`${piece}-${this.hashedPassphrase}-${piece.length}`).toString(36));\n }\n\n /**\n * Computes a hash for the given piece without encryption.\n * @param piece - The input string to hash.\n * @returns A promise resolving to the hash string.\n */\n computeHashWithoutEncryption(piece: string): Promise<string> {\n return Promise.resolve(this.xxhash.h32(`${piece}-${piece.length}`).toString(36));\n }\n}\n","import { HashManagerCore } from \"./HashManagerCore.ts\";\nimport { fallbackMixedHashEach, sha1 } from \"octagonal-wheels/hash/purejs\";\nimport { HashAlgorithms } from \"@lib/common/models/setting.const.ts\";\nimport type { HashAlgorithm } from \"@lib/common/models/setting.type.ts\";\n/**\n * Provides hash management using the \"mixed-purejs\" algorithm.\n *\n * This manager utilises a pure JavaScript implementation for hashing.\n * It is available only when the hash algorithm is set to \"mixed-purejs\".\n */\nexport class PureJSHashManager extends HashManagerCore {\n /**\n * Determines whether this manager is available for the specified algorithm.\n * @param hashAlg The hash algorithm to check.\n * @returns True if the algorithm is \"mixed-purejs\".\n */\n static override isAvailableFor(hashAlg: HashAlgorithm): boolean {\n return hashAlg === HashAlgorithms.MIXED_PUREJS;\n }\n\n /**\n * Initialises the hash manager.\n * @returns Always resolves to true.\n */\n processInitialise(): Promise<boolean> {\n return Promise.resolve(true);\n }\n\n /**\n * Computes a hash for the given input, including encryption.\n * @param input The input string to hash.\n * @returns The computed hash as a promise.\n */\n computeHashWithEncryption(input: string): Promise<string> {\n return Promise.resolve(fallbackMixedHashEach(`${input}${this.hashedPassphrase}${input.length}`));\n }\n\n /**\n * Computes a hash for the given input, without encryption.\n * @param input The input string to hash.\n * @returns The computed hash as a promise.\n */\n computeHashWithoutEncryption(input: string): Promise<string> {\n return Promise.resolve(fallbackMixedHashEach(`${input}-${input.length}`));\n }\n}\n\n/**\n * Provides hash management using the \"sha1\" algorithm.\n *\n * This manager utilises a pure JavaScript SHA-1 implementation.\n * It is available only when the hash algorithm is set to \"sha1\".\n */\nexport class SHA1HashManager extends HashManagerCore {\n /**\n * Determines whether this manager is available for the specified algorithm.\n * @param hashAlg The hash algorithm to check.\n * @returns True if the algorithm is \"sha1\".\n */\n static override isAvailableFor(hashAlg: HashAlgorithm): boolean {\n return hashAlg === HashAlgorithms.SHA1;\n }\n\n /**\n * Initialises the hash manager.\n * @returns Always resolves to true.\n */\n processInitialise(): Promise<boolean> {\n return Promise.resolve(true);\n }\n\n /**\n * Computes a SHA-1 hash for the given input, including encryption.\n * @param input The input string to hash.\n * @returns The computed SHA-1 hash as a promise.\n */\n computeHashWithEncryption(input: string): Promise<string> {\n return sha1(`${input}-${this.hashedPassphrase}-${input.length}`);\n }\n\n /**\n * Computes a SHA-1 hash for the given input, without encryption.\n * @param input The input string to hash.\n * @returns The computed SHA-1 hash as a promise.\n */\n computeHashWithoutEncryption(input: string): Promise<string> {\n return sha1(`${input}-${input.length}`);\n }\n}\n\n/**\n * Fallback hash manager using the pure JavaScript implementation.\n *\n * This manager is always available and acts as a fallback when no specific algorithm matches.\n */\nexport class FallbackPureJSHashManager extends PureJSHashManager {\n /**\n * Always returns true, indicating this manager is available for any algorithm.\n * @param _hashAlg The hash algorithm (ignored).\n * @returns True.\n */\n static override isAvailableFor(_hashAlg: HashAlgorithm): boolean {\n return true; // As a fallback hash manager, it is always available.\n }\n}\n","import type { HashAlgorithm } from \"@lib/common/models/setting.type.ts\";\nimport { FallbackWasmHashManager, XXHash32RawHashManager, XXHash64HashManager } from \"./XXHashHashManager.ts\";\nimport { FallbackPureJSHashManager, PureJSHashManager, SHA1HashManager } from \"./PureJSHashManager.ts\";\nimport { HashEncryptedPrefix, HashManagerCore, type HashManagerCoreOptions } from \"./HashManagerCore.ts\";\nimport { LOG_LEVEL_VERBOSE, Logger } from \"@lib/common/logger.ts\";\nimport { createChunkIdGenerator, configuredIdKey } from \"@lib/common/idDerivation.ts\";\n/**\n * List of available hash managers.\n * For compatibility, please retain fallback managers.\n */\nconst HashManagers = [\n XXHash64HashManager,\n XXHash32RawHashManager,\n SHA1HashManager,\n PureJSHashManager,\n // Please retain these fallback managers, as they are essential for compatibility.\n FallbackWasmHashManager,\n FallbackPureJSHashManager,\n];\n\n/**\n * Class for managing hash managers and performing hash calculations.\n * Selects an appropriate manager according to the available hash algorithm.\n */\nexport class HashManager extends HashManagerCore {\n /**\n * Instance of the hash manager currently in use.\n */\n manager: HashManagerCore = undefined!;\n private chunkIdGenerator?: { key: string; task: ReturnType<typeof createChunkIdGenerator> };\n\n clearCaches(): void {\n this.chunkIdGenerator = undefined;\n }\n\n private async computeIndependentChunkId(key: string, piece: string): Promise<string> {\n let cached = this.chunkIdGenerator;\n if (cached?.key !== key) {\n const entry = { key, task: createChunkIdGenerator(key) };\n this.chunkIdGenerator = cached = entry;\n void entry.task.catch(() => {\n if (this.chunkIdGenerator === entry) this.clearCaches();\n });\n }\n const generate = await cached.task;\n return await generate(piece);\n }\n\n /**\n * Checks whether the specified hash algorithm is available.\n *\n * @param hashAlg The hash algorithm to check\n * @returns True if available\n */\n static override isAvailableFor(hashAlg: HashAlgorithm): boolean {\n return HashManagers.some((manager) => manager.isAvailableFor(hashAlg));\n }\n\n /**\n * Selects and initialises an available hash manager.\n *\n * @returns True if initialisation is successful\n * @throws Throws an error if no available manager exists\n */\n async setManager(): Promise<boolean> {\n const settings = this.options.settingService.currentSettings();\n for (const Manager of HashManagers) {\n if (Manager.isAvailableFor(settings.hashAlg)) {\n this.manager = new Manager(this.options);\n return await this.manager.initialise();\n }\n }\n // deno-coverage-ignore Fallback managers are always present, so this should never be reached.\n throw new Error(`HashManager for ${settings.hashAlg} is not available`);\n }\n\n /**\n * Constructs a new HashManager.\n *\n * @param options Initialisation options\n */\n constructor(options: HashManagerCoreOptions) {\n super(options);\n }\n\n /**\n * Initialises the hash manager.\n *\n * @returns True if initialisation is successful\n * @throws Throws an error if initialisation fails\n */\n async processInitialise(): Promise<boolean> {\n const settings = this.options.settingService.currentSettings();\n if (await this.setManager()) {\n Logger(`HashManager for ${settings.hashAlg} has been initialised`, LOG_LEVEL_VERBOSE);\n return true;\n }\n // deno-coverage-ignore-start This branch should never be reached.\n Logger(`HashManager for ${settings.hashAlg} failed to initialise`);\n throw new Error(`HashManager for ${settings.hashAlg} failed to initialise`);\n // deno-coverage-ignore-stop\n }\n\n /**\n * Computes the hash value for the specified string.\n *\n * @param piece The string to be hashed\n * @returns The hash value (returned as a Promise)\n */\n override async computeHash(piece: string): Promise<string> {\n const settings = this.options.settingService.currentSettings();\n const key = configuredIdKey(settings);\n if (settings.encrypt && key) {\n return HashEncryptedPrefix + (await this.computeIndependentChunkId(key, piece));\n }\n this.clearCaches();\n return settings.encrypt\n ? HashEncryptedPrefix + (await this.manager.computeHashWithEncryption(piece))\n : await this.manager.computeHashWithoutEncryption(piece);\n }\n\n usesIndependentIdKey(): boolean {\n const settings = this.options.settingService.currentSettings();\n const active = settings.encrypt && configuredIdKey(settings) !== false;\n if (!active) this.clearCaches();\n return active;\n }\n\n /**\n * Computes the hash value without encryption.\n *\n * @param piece The string to be hashed\n * @returns The hash value (returned as a Promise)\n */\n computeHashWithoutEncryption(piece: string): Promise<string> {\n return this.manager.computeHashWithoutEncryption(piece);\n }\n\n /**\n * Computes the hash value with encryption.\n *\n * @param piece The string to be hashed\n * @returns The hash value (returned as a Promise)\n */\n computeHashWithEncryption(piece: string): Promise<string> {\n const key = configuredIdKey(this.options.settingService.currentSettings());\n if (key) return this.computeIndependentChunkId(key, piece);\n this.clearCaches();\n return this.manager.computeHashWithEncryption(piece);\n }\n}\n","import {\n type LOG_LEVEL,\n LOG_LEVEL_INFO,\n LOG_LEVEL_NOTICE,\n LOG_LEVEL_VERBOSE,\n Logger,\n} from \"octagonal-wheels/common/logger\";\nimport type { IAPIService } from \"@lib/services/base/IService\";\nexport const MARK_LOG_SEPARATOR = \"\\u{200A}\";\nexport const MARK_LOG_NETWORK_ERROR = \"\\u{200b}\"; // u+200B is a zero-width space, which is used to tag logs as network errors for filtering purposes.\n\n/**\n * Creates a log function that prefixes messages with the service name and uses the provided APIService's addLog method if available.\n * If APIService is not provided, it falls back to using the global Logger function.\n * @param serviceName The name of the service to prefix log messages with.\n * @param APIService An optional APIService instance to use for logging.\n * @returns A log function that can be used to log messages with the specified service name and APIService.\n */\nexport function createInstanceLogFunction(serviceName: string, APIService?: IAPIService) {\n const logFunc = APIService?.addLog.bind(APIService) ?? Logger;\n return (msg: unknown, level: LOG_LEVEL = LOG_LEVEL_INFO, key: string = \"\") => {\n const isError = msg instanceof Error;\n if (isError && level <= LOG_LEVEL_VERBOSE) {\n logFunc(msg, level, key);\n return;\n }\n let formattedMsg: string = typeof msg === \"string\" ? msg : isError ? msg.message : JSON.stringify(msg);\n // u+200A is a hair space, which is used to create a small gap between the service name and the message.\n if (level < LOG_LEVEL_NOTICE) {\n // If we simply logging the message, add a service name prefix to make it easier to identify which service the log is coming from.\n // On the other hand, if the log level is notice or above, pop-up-notification may not have enough space to show the service name.\n formattedMsg = `[${serviceName}]${MARK_LOG_SEPARATOR} ${formattedMsg}`;\n }\n\n logFunc(formattedMsg, level, key);\n };\n}\n\nexport type LogFunction = ReturnType<typeof createInstanceLogFunction>;\n","import { LOG_LEVEL_VERBOSE, type EntryDoc } from \"@lib/common/types\";\nimport { ContentSplitter } from \"@lib/ContentSplitter/ContentSplitters.ts\";\nimport { ChangeManager } from \"@lib/managers/ChangeManager.ts\";\nimport { ChunkFetcher } from \"@lib/managers/ChunkFetcher.ts\";\nimport { ChunkManager } from \"@lib/managers/ChunkManager.ts\";\nimport { ConflictManager } from \"@lib/managers/ConflictManager.ts\";\nimport { EntryManager } from \"@lib/managers/EntryManager/EntryManager.ts\";\nimport { HashManager } from \"@lib/managers/HashManager/HashManager.ts\";\nimport type {\n IAPIService,\n IDatabaseService,\n IPathService,\n IReplicatorService,\n ISettingService,\n} from \"@lib/services/base/IService.ts\";\nimport { createInstanceLogFunction, type LogFunction } from \"@lib/services/lib/logUtils.ts\";\n\nexport interface LiveSyncManagersOptions<TSettingService extends ISettingService = ISettingService> {\n database: PouchDB.Database<EntryDoc>;\n databaseService: IDatabaseService;\n settingService: TSettingService;\n pathService: IPathService;\n replicatorService: IReplicatorService;\n APIService: IAPIService;\n}\nexport class LiveSyncManagers {\n protected _pathService: IPathService;\n protected _replicatorService: IReplicatorService;\n protected _settingService: ISettingService;\n protected _APIService: IAPIService;\n\n hashManager: HashManager;\n chunkFetcher: ChunkFetcher;\n changeManager: ChangeManager<EntryDoc>;\n chunkManager: ChunkManager;\n splitter: ContentSplitter;\n entryManager: EntryManager;\n conflictManager: ConflictManager;\n\n protected options: LiveSyncManagersOptions;\n protected log: LogFunction;\n constructor(options: LiveSyncManagersOptions) {\n this.options = options;\n this._APIService = options.APIService;\n this._pathService = options.pathService;\n this._replicatorService = options.replicatorService;\n this._settingService = options.settingService;\n this.log = createInstanceLogFunction(\"LiveSyncManagers\", this._APIService);\n const { changeManager, hashManager, splitter, chunkManager, chunkFetcher, entryManager, conflictManager } =\n this.getManagerMembers();\n this.changeManager = changeManager;\n this.hashManager = hashManager;\n this.splitter = splitter;\n this.chunkManager = chunkManager;\n this.chunkFetcher = chunkFetcher;\n this.entryManager = entryManager;\n this.conflictManager = conflictManager;\n }\n\n async teardownManagers() {\n this.log(\"Teardown LiveSync Managers...\", LOG_LEVEL_VERBOSE);\n this.hashManager?.clearCaches();\n this.entryManager?.hashManager?.clearCaches();\n if (this.changeManager) {\n this.changeManager.teardown();\n this.changeManager = undefined!;\n }\n if (this.chunkFetcher) {\n this.chunkFetcher.destroy();\n this.chunkFetcher = undefined!;\n }\n if (this.chunkManager) {\n this.chunkManager.destroy();\n this.chunkManager = undefined!;\n }\n this.log(\"Teardown LiveSync Managers... Done\");\n return await Promise.resolve();\n }\n\n protected getManagerMembers() {\n this.log(\"Creating LiveSync Managers...\");\n const database = this.options.database;\n\n const changeManager = new ChangeManager<EntryDoc>({\n database,\n });\n\n const hashManager = new HashManager({\n settingService: this.options.settingService,\n });\n\n const splitter = new ContentSplitter({\n settingService: this.options.settingService,\n });\n\n const chunkManager = new ChunkManager({\n changeManager: changeManager,\n database,\n settingService: this.options.settingService,\n finiteReplicationActivity: this.options.replicatorService.finiteReplicationActivityCount,\n });\n const chunkFetcher = new ChunkFetcher({\n chunkManager: chunkManager,\n replicatorService: this.options.replicatorService,\n settingService: this.options.settingService,\n });\n const entryManager = new EntryManager({\n database,\n hashManager: hashManager,\n chunkManager: chunkManager,\n splitter: splitter,\n pathService: this._pathService,\n settingService: this.options.settingService,\n });\n const conflictManager = new ConflictManager({\n entryManager: entryManager,\n database,\n pathService: this._pathService,\n });\n this.log(\"LiveSync Managers have been created\");\n return {\n changeManager,\n hashManager,\n splitter,\n chunkManager,\n chunkFetcher,\n entryManager,\n conflictManager,\n };\n }\n async initialise() {\n this.log(\"Initialising LiveSync Managers...\", LOG_LEVEL_VERBOSE);\n await this.splitter.initialise({\n settingService: this.options.settingService,\n });\n await this.hashManager.initialise();\n this.log(\"LiveSync Manager has been initialised\");\n }\n async reinitialise() {\n await this.teardownManagers();\n\n const { changeManager, hashManager, splitter, chunkManager, chunkFetcher, entryManager, conflictManager } =\n this.getManagerMembers();\n this.changeManager = changeManager;\n this.hashManager = hashManager;\n this.splitter = splitter;\n this.chunkManager = chunkManager;\n this.chunkFetcher = chunkFetcher;\n this.entryManager = entryManager;\n this.conflictManager = conflictManager;\n await this.initialise();\n }\n\n clearCaches() {\n this.chunkManager?.clearCaches();\n this.hashManager?.clearCaches();\n this.entryManager?.hashManager?.clearCaches();\n }\n\n async prepareHashFunction() {\n this.hashManager?.clearCaches();\n this.entryManager?.hashManager?.clearCaches();\n this.hashManager = new HashManager({\n settingService: this.options.settingService,\n });\n await this.hashManager.initialise();\n }\n}\n","import * as fflate from \"fflate\";\nimport {\n tryConvertBase64ToArrayBuffer,\n arrayBufferToBase64Single,\n base64ToArrayBuffer,\n} from \"@lib/string_and_binary/convert\";\nimport type { EntryDoc } from \"@lib/common/types\";\n\nexport async function _compressText(text: string) {\n const converted = tryConvertBase64ToArrayBuffer(text);\n const data = new Uint8Array(\n converted || (await new Blob([text], { type: \"application/octet-stream\" }).arrayBuffer())\n );\n if (data.buffer.byteLength == 0) {\n return \"\";\n }\n const df = await wrappedDeflate(new Uint8Array(data), { consume: true, level: 8 });\n // Reverted: Even if chars in UTF-16 encoded were short, bytes in UTF-8 are longer than in base64 encoding.\n // const deflateResult = (converted ? \"~\" : \"\") + \"%\" + fflate.strFromU8(df, true);\n // @ts-ignore Wrong type at octagonal-wheels v0.1.25\n const deflateResult = (converted ? \"~\" : \"\") + (await arrayBufferToBase64Single(df));\n return deflateResult;\n}\nexport const wrappedInflate = wrapFflateFunc<Uint8Array<ArrayBuffer>, fflate.AsyncInflateOptions>(fflate.inflate);\nexport const wrappedDeflate = wrapFflateFunc<Uint8Array<ArrayBuffer>, fflate.AsyncDeflateOptions>(fflate.deflate);\nexport async function _decompressText(compressed: string, _useUTF16 = false) {\n if (compressed.length == 0) {\n return \"\";\n }\n const converted = compressed[0] == \"~\";\n const src = compressed.substring(converted ? 1 : 0);\n if (src.length == 0) {\n return \"\";\n }\n // const ab = src.startsWith(\"%\") ? fflate.strToU8(src.substring(1), true) : new Uint8Array(base64ToArrayBuffer(src));\n const ab = new Uint8Array(base64ToArrayBuffer(src));\n if (ab.length == 0) {\n return \"\";\n }\n const ret = await wrappedInflate(new Uint8Array(ab), { consume: true });\n if (converted) {\n //@ts-ignore Wrong type at octagonal-wheels v0.1.25\n return await arrayBufferToBase64Single(ret);\n }\n const response = new Blob([ret]);\n const text = await response.text();\n return text;\n}\nexport async function compressDoc(doc: EntryDoc) {\n if (!(\"data\" in doc)) {\n return doc;\n }\n if (typeof doc.data !== \"string\") return doc;\n if (doc.data.startsWith(MARK_SHIFT_COMPRESSED)) return doc;\n const oldData = doc.data;\n const compressed = await _compressText(oldData);\n const newData = MARK_SHIFT_COMPRESSED + compressed;\n if (doc.data.length > newData.length) doc.data = newData;\n return doc;\n}\nexport async function decompressDoc(doc: EntryDoc) {\n if (!(\"data\" in doc)) {\n return doc;\n }\n if (typeof doc.data !== \"string\") return doc;\n\n // Already decrypted\n if (doc.data.startsWith(MARK_SHIFT_COMPRESSED)) {\n doc.data = await _decompressText(doc.data.substring(MARK_SHIFT_COMPRESSED.length));\n }\n return doc;\n}\nexport function wrapFflateFunc<T, U>(\n func: (data: T, opts: U, cb: fflate.FlateCallback) => unknown\n): (data: T, opts: U) => Promise<Uint8Array<ArrayBuffer>> {\n return (data: T, opts: U) => {\n return new Promise<Uint8Array<ArrayBuffer>>((res, rej) => {\n func(data, opts, (err, result) => {\n if (err) rej(err);\n else res(new Uint8Array(result));\n });\n });\n };\n}\nexport const replicationFilter = (db: PouchDB.Database<EntryDoc>, compress: boolean) => {\n //@ts-ignore\n db.transform({\n //@ts-ignore\n async incoming(doc) {\n if (!compress) return doc;\n return await compressDoc(doc);\n },\n //@ts-ignore\n async outgoing(doc) {\n // We should decompress if compression is not configured.\n return await decompressDoc(doc);\n },\n });\n};\nconst MARK_SHIFT = `\\u{000E}L`;\nexport const MARK_SHIFT_COMPRESSED = `${MARK_SHIFT}Z\\u{001D}`;\n","import { Logger, LOG_LEVEL_NOTICE, LOG_LEVEL_VERBOSE } from \"@lib/common/logger\";\nimport {\n type EntryDoc,\n type AnyEntry,\n type EntryLeaf,\n type FilePathWithPrefix,\n type DocumentID,\n type EntryWithEden,\n type E2EEAlgorithm,\n E2EEAlgorithms,\n isMetaEntry,\n} from \"@lib/common/types\";\nimport { isEncryptedChunkEntry, isSyncInfoEntry, isObfuscatedEntry } from \"@lib/common/utils\";\nimport { isPathProbablyObfuscated, obfuscatePath } from \"octagonal-wheels/encryption/encryption\";\n// import { encryptHKDF, decryptHKDF } from \"../encryption/encryptHKDF.ts\";\nimport { getPath } from \"@lib/string_and_binary/path.ts\";\nimport { ICHeader, ICXHeader, PSCHeader } from \"@lib/common/models/fileaccess.const\";\nimport { PREFIX_OBFUSCATED } from \"@lib/common/types\";\nimport { encryptWorker, decryptWorker, encryptHKDFWorker, decryptHKDFWorker } from \"#worker\";\n\nexport const encrypt = encryptWorker;\nexport const decrypt = decryptWorker;\nexport const encryptHKDF = encryptHKDFWorker;\nexport const decryptHKDF = decryptHKDFWorker;\n\nconst Encrypt_HKDF_Header = \"%=\";\nconst Encrypt_OLD_Header = \"%\";\n\nconst EncryptionVersions = {\n UNENCRYPTED: 0,\n ENCRYPTED: 1,\n HKDF: 2,\n UNKNOWN: 99,\n} as const;\ntype EncryptionVersion = (typeof EncryptionVersions)[keyof typeof EncryptionVersions];\n\nfunction getEncryptionVersion(data: EntryLeaf): EncryptionVersion {\n if (\"e_\" in data && data.e_ === true) {\n if (data.data.startsWith(Encrypt_HKDF_Header)) {\n return EncryptionVersions.HKDF;\n } else if (data.data.startsWith(Encrypt_OLD_Header)) {\n return EncryptionVersions.ENCRYPTED;\n }\n return EncryptionVersions.UNKNOWN;\n }\n return EncryptionVersions.UNENCRYPTED;\n}\n\nasync function tryDecryptV1AsFallback(\n encryptedData: string,\n passphrase: string,\n useDynamicIterationCount: boolean\n): Promise<string | false> {\n try {\n return await decrypt(encryptedData, passphrase, useDynamicIterationCount);\n } catch (ex) {\n try {\n Logger(\n \"Failed to decrypt with V1 method. Fallback to disable useDynamicIterationCount.\",\n LOG_LEVEL_VERBOSE\n );\n Logger(ex, LOG_LEVEL_VERBOSE);\n return await decrypt(encryptedData, passphrase, false);\n } catch (ex) {\n Logger(\"Completely failed to decrypt with V1 method.\", LOG_LEVEL_VERBOSE);\n Logger(ex, LOG_LEVEL_VERBOSE);\n return false; // failed to decrypt\n }\n }\n}\n\ntype EncryptedDocument<T> = T & {\n e_?: boolean; // indicates that the document is encrypted\n};\n\nconst ENCRYPTED_META_PREFIX = \"/\\\\:\";\nfunction isEncryptedMeta<T extends AnyEntry>(doc: T) {\n return \"path\" in doc && doc.path.startsWith(ENCRYPTED_META_PREFIX);\n}\nfunction isInternalObfuscatedEntry(doc: AnyEntry | EntryLeaf): doc is AnyEntry {\n return [ICHeader, ICXHeader, PSCHeader].some((prefix) =>\n doc._id.startsWith(`${prefix}${PREFIX_OBFUSCATED}`)\n );\n}\ntype EncryptProps = {\n path: string;\n mtime: number;\n ctime: number;\n size: number;\n children?: string[];\n};\nasync function encryptMetaWithHKDF<T extends AnyEntry>(\n doc: T,\n passphrase: string,\n pbkdf2Salt: Uint8Array<ArrayBuffer>\n): Promise<string> {\n if (isEncryptedMeta(doc)) {\n // already encrypted with HKDF, no need to re-encrypt\n return doc.path;\n }\n const props: EncryptProps = {\n path: getPath(doc),\n mtime: doc.mtime,\n ctime: doc.ctime,\n size: doc.size,\n children: isMetaEntry(doc) ? doc.children : undefined,\n };\n const propStr = JSON.stringify(props);\n const encryptedMeta = await encryptHKDFWorker(propStr, passphrase, pbkdf2Salt);\n return ENCRYPTED_META_PREFIX + encryptedMeta;\n}\nasync function decryptMetaWithHKDF(\n meta: string,\n passphrase: string,\n pbkdf2Salt: Uint8Array<ArrayBuffer>\n): Promise<EncryptProps> {\n if (!meta.startsWith(ENCRYPTED_META_PREFIX)) {\n throw new Error(\"Meta is not encrypted with HKDF.\");\n }\n const encryptedMeta = meta.slice(ENCRYPTED_META_PREFIX.length);\n const props = await decryptHKDF(encryptedMeta, passphrase, pbkdf2Salt);\n const parsedProps = JSON.parse(props) as EncryptProps;\n return parsedProps;\n}\n\nconst MESSAGE_FALLBACK_DECRYPT_FAILED = \"Failed to decrypt the data with V1 method. Cannot encrypt with HKDF.\";\nconst ENCRYPTION_HKDF_FAILED = \"Encryption with HKDF failed.\";\nconst DECRYPTION_HKDF_FAILED = \"Decryption with HKDF failed.\";\nconst DECRYPTION_FALLBACK_FAILED = \"Decryption with fallback failed.\";\n\n// requires transform-pouch\nasync function incomingEncryptHKDF(\n doc: AnyEntry | EntryLeaf,\n passphrase: string,\n useDynamicIterationCount: boolean,\n getPBKDF2Salt: () => Promise<Uint8Array<ArrayBuffer>>,\n encryptInternalMetadata: boolean\n): Promise<EntryLeaf | AnyEntry> {\n const saveDoc = {\n ...doc,\n } as EncryptedDocument<EntryLeaf | AnyEntry>;\n\n if (isEncryptedChunkEntry(saveDoc) || isSyncInfoEntry(saveDoc)) {\n try {\n const encryptionVersion = getEncryptionVersion(saveDoc);\n if (encryptionVersion === EncryptionVersions.ENCRYPTED) {\n const decrypted = await tryDecryptV1AsFallback(saveDoc.data, passphrase, useDynamicIterationCount);\n if (decrypted === false) {\n Logger(MESSAGE_FALLBACK_DECRYPT_FAILED, LOG_LEVEL_NOTICE);\n throw new Error(MESSAGE_FALLBACK_DECRYPT_FAILED);\n }\n const pbkdf2salt = await getPBKDF2Salt();\n // re-encrypt with HKDF\n saveDoc.data = await encryptHKDF(saveDoc.data, passphrase, pbkdf2salt);\n saveDoc.e_ = true; // mark as encrypted\n }\n if (encryptionVersion === EncryptionVersions.HKDF) {\n // already encrypted with HKDF, no need to re-encrypt\n } else if (encryptionVersion === EncryptionVersions.UNENCRYPTED) {\n // not encrypted, encrypt with HKDF\n const pbkdf2salt = await getPBKDF2Salt();\n saveDoc.data = await encryptHKDF(saveDoc.data, passphrase, pbkdf2salt);\n saveDoc.e_ = true; // mark as encrypted\n }\n } catch (ex) {\n Logger(ENCRYPTION_HKDF_FAILED, LOG_LEVEL_NOTICE);\n Logger(ex);\n throw ex;\n }\n }\n\n if (shouldEncryptEdenHKDF(saveDoc)) {\n // If failed, throw an error.\n const pbkdf2salt = await getPBKDF2Salt();\n\n try {\n saveDoc.eden = {\n [EDEN_ENCRYPTED_KEY_HKDF]: {\n data: await encryptHKDF(JSON.stringify(saveDoc.eden), passphrase, pbkdf2salt),\n epoch: 999999,\n },\n };\n } catch (ex) {\n Logger(`${ENCRYPTION_HKDF_FAILED} on Eden`, LOG_LEVEL_NOTICE);\n Logger(ex);\n throw ex;\n }\n }\n if (isObfuscatedEntry(saveDoc) || (encryptInternalMetadata && isInternalObfuscatedEntry(saveDoc))) {\n const pbkdf2salt = await getPBKDF2Salt();\n\n if (!isEncryptedMeta(saveDoc)) {\n try {\n saveDoc.path = (await encryptMetaWithHKDF(\n saveDoc,\n passphrase,\n pbkdf2salt\n )) as unknown as FilePathWithPrefix;\n saveDoc.mtime = 0;\n saveDoc.ctime = 0;\n saveDoc.size = 0;\n if (\"children\" in saveDoc) saveDoc.children = [];\n } catch (ex) {\n Logger(`${ENCRYPTION_HKDF_FAILED} on Metadata`, LOG_LEVEL_NOTICE);\n Logger(ex);\n throw ex;\n }\n }\n }\n return saveDoc;\n}\n\nasync function outgoingDecryptHKDF(\n doc: EntryDoc,\n migrationDecrypt: boolean,\n decrypted: Map<DocumentID, boolean>,\n passphrase: string,\n useDynamicIterationCount: boolean,\n getPBKDF2Salt: () => Promise<Uint8Array<ArrayBuffer>>\n): Promise<AnyEntry | EntryLeaf> {\n const loadDoc = {\n ...doc,\n } as EncryptedDocument<AnyEntry | EntryLeaf>;\n //TODO\n\n if (isEncryptedChunkEntry(loadDoc) || isSyncInfoEntry(loadDoc)) {\n try {\n const encryptionVersion = getEncryptionVersion(loadDoc);\n if (encryptionVersion === EncryptionVersions.HKDF) {\n const pbkdf2salt = await getPBKDF2Salt();\n loadDoc.data = await decryptHKDF(loadDoc.data, passphrase, pbkdf2salt);\n delete loadDoc.e_;\n } else if (encryptionVersion === EncryptionVersions.ENCRYPTED) {\n const decryptedData = await tryDecryptV1AsFallback(loadDoc.data, passphrase, useDynamicIterationCount);\n if (decryptedData === false) {\n Logger(MESSAGE_FALLBACK_DECRYPT_FAILED, LOG_LEVEL_NOTICE);\n throw new Error(MESSAGE_FALLBACK_DECRYPT_FAILED);\n }\n loadDoc.data = decryptedData;\n delete loadDoc.e_;\n } else if (encryptionVersion === EncryptionVersions.UNENCRYPTED) {\n // not encrypted, no need to decrypt\n } else {\n Logger(\"Unknown encryption version. Cannot decrypt.\", LOG_LEVEL_NOTICE);\n throw new Error(\"Unknown encryption version. Cannot decrypt.\");\n }\n } catch (ex) {\n Logger(DECRYPTION_HKDF_FAILED, LOG_LEVEL_NOTICE);\n Logger(ex);\n throw ex;\n }\n }\n if (isObfuscatedEntry(loadDoc) || (isInternalObfuscatedEntry(loadDoc) && isEncryptedMeta(loadDoc))) {\n if (isEncryptedMeta(loadDoc)) {\n const pbkdf2salt = await getPBKDF2Salt();\n try {\n const metadata = await decryptMetaWithHKDF(loadDoc.path, passphrase, pbkdf2salt);\n for (const key of Object.keys(metadata)) {\n (loadDoc as unknown as Record<string, unknown>)[key] = metadata[key as keyof EncryptProps];\n }\n } catch (ex) {\n Logger(`${DECRYPTION_HKDF_FAILED} on Path`, LOG_LEVEL_NOTICE);\n Logger(ex);\n throw ex;\n }\n } else {\n const path = getPath(loadDoc);\n if (isPathProbablyObfuscated(path)) {\n // As a fallback, try to decrypt with V1 method. This part will eventually be removed.\n const decryptedPath = await tryDecryptV1AsFallback(path, passphrase, useDynamicIterationCount);\n if (decryptedPath === false) {\n Logger(`${MESSAGE_FALLBACK_DECRYPT_FAILED} on Path`, LOG_LEVEL_NOTICE);\n throw new Error(MESSAGE_FALLBACK_DECRYPT_FAILED);\n }\n loadDoc.path = decryptedPath as FilePathWithPrefix;\n }\n }\n }\n let readEden: EntryWithEden[\"eden\"] = {};\n let edenDecrypted = false;\n // Fallback to V1 decryption if Eden is not encrypted with HKDF.\n if (shouldDecryptEden(loadDoc)) {\n try {\n const decryptedEden = await tryDecryptV1AsFallback(\n loadDoc.eden[EDEN_ENCRYPTED_KEY].data,\n passphrase,\n useDynamicIterationCount\n );\n if (decryptedEden === false) throw new Error(MESSAGE_FALLBACK_DECRYPT_FAILED);\n readEden = {\n ...readEden,\n ...JSON.parse(decryptedEden),\n };\n edenDecrypted = true;\n } catch (ex) {\n Logger(`${DECRYPTION_FALLBACK_FAILED} on Eden`, LOG_LEVEL_NOTICE);\n Logger(ex);\n throw ex;\n }\n }\n /// If Eden is encrypted with HKDF, decrypt it.\n if (shouldDecryptEdenHKDF(loadDoc)) {\n const pbkdf2salt = await getPBKDF2Salt();\n\n try {\n const decryptedEdenData = await decryptHKDF(\n loadDoc.eden[EDEN_ENCRYPTED_KEY_HKDF].data,\n passphrase,\n pbkdf2salt\n );\n readEden = {\n ...readEden,\n ...JSON.parse(decryptedEdenData),\n };\n edenDecrypted = true;\n } catch (ex) {\n Logger(`${DECRYPTION_HKDF_FAILED} on Eden`, LOG_LEVEL_NOTICE);\n Logger(ex);\n throw ex;\n }\n }\n if (edenDecrypted) {\n (loadDoc as unknown as Record<string, unknown>).eden = readEden;\n } else {\n // If Eden is not decrypted, NO OP.\n }\n return loadDoc;\n}\n// requires transform-pouch\nasync function incomingEncryptV1(\n doc: AnyEntry | EntryLeaf,\n passphrase: string,\n useDynamicIterationCount: boolean\n): Promise<EntryLeaf | AnyEntry> {\n const saveDoc = {\n ...doc,\n } satisfies EntryLeaf | AnyEntry;\n\n if (isEncryptedChunkEntry(saveDoc) || isSyncInfoEntry(saveDoc)) {\n try {\n if (!(\"e_\" in saveDoc)) {\n saveDoc.data = await encrypt(saveDoc.data, passphrase, useDynamicIterationCount);\n (saveDoc as unknown as Record<string, unknown>).e_ = true;\n }\n } catch (ex) {\n Logger(\"Encryption failed.\", LOG_LEVEL_NOTICE);\n Logger(ex);\n throw ex;\n }\n }\n\n if (shouldEncryptEden(saveDoc)) {\n saveDoc.eden = {\n [EDEN_ENCRYPTED_KEY]: {\n data: await encrypt(JSON.stringify(saveDoc.eden), passphrase, useDynamicIterationCount),\n epoch: 999999,\n },\n };\n }\n if (isObfuscatedEntry(saveDoc)) {\n try {\n const path = getPath(saveDoc);\n if (!isPathProbablyObfuscated(path)) {\n saveDoc.path = (await obfuscatePath(\n path,\n passphrase,\n useDynamicIterationCount\n )) as unknown as FilePathWithPrefix;\n }\n } catch (ex) {\n Logger(\"Encryption failed.\", LOG_LEVEL_NOTICE);\n Logger(ex);\n throw ex;\n }\n }\n return saveDoc;\n}\nasync function outgoingDecryptV1(\n doc: EntryDoc,\n migrationDecrypt: boolean,\n decrypted: Map<DocumentID, boolean>,\n passphrase: string,\n useDynamicIterationCount: boolean\n): Promise<AnyEntry | EntryLeaf> {\n const loadDoc = {\n ...doc,\n } as AnyEntry | EntryLeaf;\n const _isChunkOrSyncInfo = isEncryptedChunkEntry(loadDoc) || isSyncInfoEntry(loadDoc);\n\n const _isObfuscatedEntry = isObfuscatedEntry(loadDoc);\n const _shouldDecryptEden = shouldDecryptEden(loadDoc);\n if (_isChunkOrSyncInfo || _isObfuscatedEntry || _shouldDecryptEden) {\n if (migrationDecrypt && decrypted.has(loadDoc._id)) {\n return loadDoc; // once decrypted.\n }\n try {\n if (_isChunkOrSyncInfo) {\n loadDoc.data = await decrypt(loadDoc.data, passphrase, useDynamicIterationCount);\n delete (loadDoc as unknown as Record<string, unknown>).e_;\n } else if (\"e_\" in loadDoc) {\n (loadDoc as unknown as Record<string, unknown>).data = await decrypt(\n (loadDoc as unknown as { data: string }).data,\n passphrase,\n useDynamicIterationCount\n );\n delete (loadDoc as unknown as Record<string, unknown>).e_;\n }\n if (_isObfuscatedEntry) {\n const path = getPath(loadDoc);\n if (isPathProbablyObfuscated(path)) {\n loadDoc.path = (await decrypt(\n path,\n passphrase,\n useDynamicIterationCount\n )) as unknown as FilePathWithPrefix;\n }\n }\n if (_shouldDecryptEden) {\n loadDoc.eden = JSON.parse(\n await decrypt(loadDoc.eden[EDEN_ENCRYPTED_KEY].data, passphrase, useDynamicIterationCount)\n );\n }\n if (migrationDecrypt) {\n decrypted.set(loadDoc._id, true);\n }\n } catch (ex) {\n if (useDynamicIterationCount) {\n try {\n if (_isChunkOrSyncInfo) {\n loadDoc.data = await decrypt(loadDoc.data, passphrase, false);\n }\n if (_isObfuscatedEntry) {\n const path = getPath(loadDoc);\n if (isPathProbablyObfuscated(path)) {\n loadDoc.path = (await decrypt(path, passphrase, false)) as unknown as FilePathWithPrefix;\n }\n }\n if (_shouldDecryptEden) {\n loadDoc.eden = JSON.parse(\n await decrypt(loadDoc.eden[EDEN_ENCRYPTED_KEY].data, passphrase, false)\n );\n }\n if (migrationDecrypt) {\n decrypted.set(loadDoc._id, true);\n }\n } catch (ex) {\n if (migrationDecrypt && ex instanceof SyntaxError) {\n return loadDoc; // This logic will be removed in a while.\n }\n Logger(\"Decryption failed.\", LOG_LEVEL_NOTICE);\n Logger(ex, LOG_LEVEL_VERBOSE);\n Logger(`id:${loadDoc._id}-${loadDoc._rev?.substring(0, 10)}`, LOG_LEVEL_VERBOSE);\n throw ex;\n }\n } else {\n Logger(\"Decryption failed.\", LOG_LEVEL_NOTICE);\n Logger(ex, LOG_LEVEL_VERBOSE);\n Logger(`id:${loadDoc._id}-${loadDoc._rev?.substring(0, 10)}`, LOG_LEVEL_VERBOSE);\n throw ex;\n }\n }\n }\n return loadDoc;\n}\nexport let preprocessOutgoing: (doc: AnyEntry | EntryLeaf) => Promise<AnyEntry | EntryLeaf> = async (doc) => {\n return await Promise.resolve(doc);\n};\nexport let preprocessIncoming: (doc: EntryDoc) => Promise<EntryDoc> = async (doc) => {\n return await Promise.resolve(doc);\n};\n\nexport function getConfiguredFunctionsForEncryption(\n passphrase: string,\n useDynamicIterationCount: boolean,\n migrationDecrypt: boolean,\n getPBKDF2Salt: () => Promise<Uint8Array<ArrayBuffer>>,\n algorithm: E2EEAlgorithm,\n encryptInternalMetadata = false\n): {\n incoming: (doc: AnyEntry | EntryLeaf) => Promise<AnyEntry | EntryLeaf>;\n outgoing: (doc: EntryDoc) => Promise<AnyEntry | EntryLeaf>;\n} {\n const decryptedCache = new Map();\n const incoming = (doc: AnyEntry | EntryLeaf) =>\n algorithm === E2EEAlgorithms.V2\n ? incomingEncryptHKDF(doc, passphrase, useDynamicIterationCount, getPBKDF2Salt, encryptInternalMetadata)\n : incomingEncryptV1(doc, passphrase, useDynamicIterationCount);\n // If unless specified algorithm is ForceV1, then use HKDF decryption for forward compatibility.\n const outgoing = (doc: EntryDoc) =>\n algorithm !== E2EEAlgorithms.ForceV1\n ? outgoingDecryptHKDF(\n doc,\n migrationDecrypt,\n decryptedCache,\n passphrase,\n useDynamicIterationCount,\n getPBKDF2Salt\n )\n : outgoingDecryptV1(doc, migrationDecrypt, decryptedCache, passphrase, useDynamicIterationCount);\n return {\n incoming,\n outgoing,\n };\n}\n\nexport const enableEncryption = (\n db: PouchDB.Database<EntryDoc>,\n passphrase: string,\n useDynamicIterationCount: boolean,\n migrationDecrypt: boolean,\n getPBKDF2Salt: () => Promise<Uint8Array<ArrayBuffer>>,\n algorithm: E2EEAlgorithm,\n encryptInternalMetadata = false\n) => {\n const { incoming, outgoing } = getConfiguredFunctionsForEncryption(\n passphrase,\n useDynamicIterationCount,\n migrationDecrypt,\n getPBKDF2Salt,\n algorithm,\n encryptInternalMetadata\n );\n //@ts-ignore\n db.transform({\n incoming,\n outgoing,\n });\n};\n\nexport function disableEncryption() {\n preprocessOutgoing = async (doc) => {\n return await Promise.resolve(doc);\n };\n preprocessIncoming = async (doc) => {\n return await Promise.resolve(doc);\n };\n}\n\nexport const EDEN_ENCRYPTED_KEY = \"h:++encrypted\" as DocumentID;\nexport const EDEN_ENCRYPTED_KEY_HKDF = \"h:++encrypted-hkdf\" as DocumentID;\nexport function shouldEncryptEden(doc: AnyEntry | EntryLeaf): doc is AnyEntry {\n if (\"eden\" in doc && !(EDEN_ENCRYPTED_KEY in doc.eden)) {\n return true;\n }\n return false;\n}\nexport function shouldEncryptEdenHKDF(doc: AnyEntry | EntryLeaf): doc is AnyEntry {\n if (\"eden\" in doc && !(EDEN_ENCRYPTED_KEY_HKDF in doc.eden)) {\n if (Object.keys(doc.eden).length === 0) {\n return false; // If eden is empty, do not encrypt.\n }\n return true;\n }\n return false;\n}\n\nexport function shouldDecryptEden(doc: AnyEntry | EntryLeaf): doc is AnyEntry {\n if (\"eden\" in doc && EDEN_ENCRYPTED_KEY in doc.eden) {\n return true;\n }\n return false;\n}\n\nexport function shouldDecryptEdenHKDF(doc: AnyEntry | EntryLeaf): doc is AnyEntry {\n if (\"eden\" in doc && EDEN_ENCRYPTED_KEY_HKDF in doc.eden) {\n return true;\n }\n return false;\n}\n","/**\n * The API for manipulating files stored in the CouchDB by Self-hosted LiveSync or its families.\n */\nimport {\n type DocumentID,\n type FilePathWithPrefix,\n type EntryHasPath,\n type FilePath,\n type EntryDoc,\n type NewEntry,\n type PlainEntry,\n type LoadedEntry,\n DEFAULT_SETTINGS,\n type HashAlgorithm,\n type ObsidianLiveSyncSettings,\n type RemoteDBSettings,\n type ChunkSplitterVersion,\n type SyncParameters,\n DEFAULT_SYNC_PARAMETERS,\n ProtocolVersions,\n DOCID_SYNC_PARAMETERS,\n type E2EEAlgorithm,\n E2EEAlgorithms,\n VER,\n} from \"@lib/common/types.ts\";\nimport { checkRemoteVersion } from \"@lib/pouchdb/negotiation.ts\";\nimport { requiredRemoteFeatures, usesEncryptedInternalMetadata } from \"@lib/pouchdb/remoteFeatureCompatibility.ts\";\nimport { assessRemoteDocumentIds } from \"@lib/pouchdb/remoteIdCompatibility.ts\";\n\nimport { PouchDB } from \"@lib/pouchdb/pouchdb-http.ts\";\nimport { LiveSyncLocalDB, type LiveSyncLocalDBEnv } from \"@lib/pouchdb/LiveSyncLocalDB.ts\";\nimport { isErrorOfMissingDoc } from \"@lib/pouchdb/utils_couchdb.ts\";\nimport { replicationFilter } from \"@lib/pouchdb/compress.ts\";\nimport { disableEncryption } from \"@lib/pouchdb/encryption.ts\";\nimport { enableEncryption } from \"@lib/pouchdb/encryption.ts\";\nimport {\n LEVEL_INFO,\n LEVEL_VERBOSE,\n LOG_LEVEL_INFO,\n LOG_LEVEL_NOTICE,\n LOG_LEVEL_VERBOSE,\n Logger,\n} from \"octagonal-wheels/common/logger\";\nimport { createBlob, determineTypeFromBlob } from \"@lib/common/utils.ts\";\nimport { promiseWithResolvers } from \"octagonal-wheels/promises\";\nimport {\n createSyncParamsHanderForServer,\n SyncParamsFetchError,\n SyncParamsNotFoundError,\n SyncParamsUpdateError,\n} from \"@lib/replication/SyncParamsHandler.ts\";\n\nimport { HeadlessServiceHub } from \"@lib/services/HeadlessServices.ts\";\nimport { HeadlessDatabaseService } from \"@lib/services/implements/headless/HeadlessDatabaseService.ts\";\nimport { ServiceContext } from \"@lib/services/base/ServiceBase.ts\";\nimport type { InjectableSettingService } from \"@lib/services/implements/injectable/InjectableSettingService.ts\";\nimport { compatGlobal } from \"@lib/common/coreEnvFunctions.ts\";\n\nexport type DirectFileManipulatorOptions = {\n url: string;\n username: string;\n password: string;\n passphrase: string | undefined;\n database: string;\n obfuscatePassphrase: string | undefined;\n idDerivationVersion?: 0 | 1;\n idDerivationKey?: string;\n encryptInternalMetadata?: boolean;\n useDynamicIterationCount?: boolean;\n customChunkSize?: number;\n minimumChunkSize?: number;\n hashAlg?: HashAlgorithm;\n useEden?: boolean;\n maxChunksInEden?: number;\n maxTotalLengthInEden?: number;\n maxAgeInEden?: number;\n /**\n * @deprecated use chunkSplitterVersion instead.\n */\n enableChunkSplitterV2?: boolean;\n enableCompression?: boolean;\n handleFilenameCaseSensitive?: boolean;\n /**\n * @deprecated Chunk revisions are always derived from their content.\n */\n doNotUseFixedRevisionForChunks?: boolean;\n chunkSplitterVersion?: ChunkSplitterVersion;\n E2EEAlgorithm?: E2EEAlgorithm;\n};\n\n/** Host runtime capabilities used by a direct CouchDB connection. */\nexport type DirectFileManipulatorRuntimeOptions = Readonly<{\n /** Fetch implementation passed to PouchDB. Omit it to use PouchDB's default transport. */\n fetch?: typeof globalThis.fetch;\n}>;\n\nexport type ReadyEntry = (NewEntry | PlainEntry) & { data: string[] };\nexport type MetaEntry = (NewEntry | PlainEntry) & { children: string[] };\n\nfunction isNoteEntry(doc: EntryDoc | false): doc is NewEntry | PlainEntry {\n if (!doc) return false;\n return doc.type == \"newnote\" || doc.type == \"plain\";\n}\nfunction isReadyEntry(doc: EntryDoc | false): doc is ReadyEntry {\n if (!doc) return false;\n return \"data\" in doc;\n}\n// function isMetaEntry(doc: EntryDoc | false): doc is MetaEntry {\n// if (!doc) return false;\n// return \"children\" in doc;\n// }\n\nexport type FileInfo = {\n ctime: number;\n mtime: number;\n size: number;\n};\n\nexport type EnumerateConditions = {\n startKey?: string;\n endKey?: string;\n ids?: string[];\n metaOnly: boolean;\n};\n\nexport class DirectFileManipulator implements LiveSyncLocalDBEnv {\n liveSyncLocalDB: LiveSyncLocalDB;\n options: DirectFileManipulatorOptions;\n readonly runtimeOptions: DirectFileManipulatorRuntimeOptions;\n ready = promiseWithResolvers<void>();\n services: HeadlessServiceHub<ServiceContext>;\n public async init() {\n try {\n await this.services.appLifecycle.onReady();\n if (!(await this.liveSyncLocalDB.initializeDatabase())) {\n throw new Error(\"Direct database initialisation was rejected.\");\n }\n const idSettings = {\n ...this.settings,\n passphrase: this.options.obfuscatePassphrase || this.settings.passphrase,\n };\n const idCompatibility = await assessRemoteDocumentIds(\n this.liveSyncLocalDB.localDatabase,\n idSettings,\n (path) => this.services.path.path2idWithSettings(path, idSettings)\n );\n if (idCompatibility === \"mismatched\") {\n throw new Error(\"Direct database document IDs do not match the configured ID key.\");\n }\n const requiredFeatures = requiredRemoteFeatures(this.settings);\n if (\n !(await checkRemoteVersion(\n this.liveSyncLocalDB.localDatabase,\n async () => false,\n VER,\n requiredFeatures\n ))\n ) {\n throw new Error(\"Direct database version or features are not compatible.\");\n }\n this.liveSyncLocalDB.refreshSettings();\n this.ready.resolve();\n } catch (error) {\n this.ready.reject(error);\n }\n }\n getBoundDatabaseService(\n options: () => DirectFileManipulatorOptions,\n runtimeOptions: DirectFileManipulatorRuntimeOptions\n ): typeof HeadlessDatabaseService {\n const _option = options;\n const _runtimeOptions = runtimeOptions;\n return class HeadlessDatabaseServiceExt<T extends ServiceContext> extends HeadlessDatabaseService<T> {\n override createPouchDBInstance<T extends object>(\n _name?: string,\n _options?: PouchDB.Configuration.DatabaseConfiguration\n ): PouchDB.Database<T> {\n const option = _option();\n const pouchDBOptions: PouchDB.Configuration.DatabaseConfiguration = {\n auth: { username: option.username, password: option.password },\n };\n if (_runtimeOptions.fetch) {\n pouchDBOptions.fetch = _runtimeOptions.fetch;\n }\n return new PouchDB(option.url + \"/\" + option.database, pouchDBOptions);\n }\n };\n }\n\n constructor(options: DirectFileManipulatorOptions, runtimeOptions: DirectFileManipulatorRuntimeOptions = {}) {\n this.options = options;\n this.runtimeOptions = runtimeOptions;\n const getSettings = () => this.settings;\n const context = new ServiceContext();\n this.services = new HeadlessServiceHub(context, {\n pouchDB: PouchDB,\n database: this.getBoundDatabaseService(() => this.options, this.runtimeOptions),\n getPathObfuscationPassphrase: () => this.options.obfuscatePassphrase ?? false,\n databaseLifecycleMode: \"direct-access\",\n });\n\n // (this.services.setting as InjectableSettingService<ServiceContext>).currentSettings.setHandler(\n // getSettings.bind(this)\n // );\n (this.services.setting as InjectableSettingService<ServiceContext>).saveData.setHandler((data) => {\n console.warn(\"Saving settings is not supported in DirectFileManipulator.\");\n return Promise.resolve();\n });\n (this.services.setting as InjectableSettingService<ServiceContext>).loadData.setHandler(() => {\n console.warn(\"Loading settings is not supported in DirectFileManipulator.\");\n return Promise.resolve(getSettings());\n });\n this.services.setting.settings = getSettings();\n // this.services.database.createPouchDBInstance.setHandler(this.$$createPouchDBInstance.bind(this));\n this.services.databaseEvents.onDatabaseInitialisation.addHandler(this.$everyOnInitializeDatabase.bind(this));\n this.liveSyncLocalDB = new LiveSyncLocalDB(this.options.url, this);\n // Callers observe constructor-started initialisation through `ready`. Register a\n // handler immediately so a failure cannot become an unhandled rejection before\n // the host starts awaiting that promise.\n void this.ready.promise.catch((): void => {});\n void this.init();\n }\n\n $$id2path(id: DocumentID, entry?: EntryHasPath, stripPrefix?: boolean): FilePathWithPrefix {\n return this.services.path.id2path(id, entry, stripPrefix);\n }\n async $$path2id(filename: FilePathWithPrefix | FilePath, prefix?: string): Promise<DocumentID> {\n return await this.services.path.path2id(filename, prefix);\n }\n // $$createPouchDBInstance<T extends object>(\n // _name?: string,\n // _options?: PouchDB.Configuration.DatabaseConfiguration\n // ): PouchDB.Database<T> {\n // return new PouchDB(this.options.url + \"/\" + this.options.database, {\n // auth: { username: this.options.username, password: this.options.password },\n // });\n // }\n\n getInitialSyncParameters(setting: RemoteDBSettings): Promise<SyncParameters> {\n // TODO: Switch to select protocolVersion based on the setting.\n return Promise.resolve({\n ...DEFAULT_SYNC_PARAMETERS,\n protocolVersion: ProtocolVersions.ADVANCED_E2EE,\n } satisfies SyncParameters);\n }\n async getSyncParameters(setting: RemoteDBSettings): Promise<SyncParameters> {\n try {\n const downloadedSyncParams = await this.rawGet<SyncParameters>(DOCID_SYNC_PARAMETERS);\n if (!downloadedSyncParams) {\n throw new SyncParamsNotFoundError(`Sync parameters have not been found in the database.`);\n }\n return downloadedSyncParams;\n } catch (ex) {\n Logger(`Could not retrieve remote sync parameters`, LOG_LEVEL_INFO);\n throw SyncParamsFetchError.fromError(ex);\n }\n }\n async putSyncParameters(setting: RemoteDBSettings, params: SyncParameters): Promise<boolean> {\n try {\n const ret = await this.liveSyncLocalDB.putRaw(params as unknown as EntryDoc);\n if (ret.ok) {\n return true;\n }\n throw new SyncParamsUpdateError(`Could not store remote sync parameters`);\n } catch (ex) {\n Logger(`Could not store remote sync parameters`, LOG_LEVEL_INFO);\n throw SyncParamsUpdateError.fromError(ex);\n }\n }\n async getReplicationPBKDF2Salt(setting: RemoteDBSettings, refresh?: boolean): Promise<Uint8Array<ArrayBuffer>> {\n const server = `${setting.couchDB_URI.replace(/\\/+$/, \"\")}/${setting.couchDB_DBNAME}`;\n const manager = createSyncParamsHanderForServer(server, {\n put: (params: SyncParameters) => this.putSyncParameters(setting, params),\n get: () => this.getSyncParameters(setting),\n create: () => this.getInitialSyncParameters(setting),\n });\n return await manager.getPBKDF2Salt(refresh);\n }\n $everyOnInitializeDatabase(db: LiveSyncLocalDB): Promise<boolean> {\n replicationFilter(db.localDatabase, this.options.enableCompression ?? false);\n disableEncryption();\n if (this.options.passphrase && typeof this.options.passphrase === \"string\") {\n enableEncryption(\n db.localDatabase,\n this.options.passphrase,\n this.options.useDynamicIterationCount ?? false,\n false,\n async () => await this.getReplicationPBKDF2Salt(this.getSettings()),\n this.options.E2EEAlgorithm ?? E2EEAlgorithms.V2,\n usesEncryptedInternalMetadata(this.settings)\n );\n }\n return Promise.resolve(true);\n }\n\n getSettings(): RemoteDBSettings {\n return this.settings;\n }\n async close() {\n await this.liveSyncLocalDB.close();\n return this.liveSyncLocalDB.onunload();\n }\n async path2id(filename: FilePathWithPrefix | FilePath, prefix?: string): Promise<DocumentID> {\n return await this.services.path.path2id(filename, prefix);\n }\n\n get settings() {\n const retObj: ObsidianLiveSyncSettings = {\n ...DEFAULT_SETTINGS,\n ...{\n minimumChunkSize: this.options.minimumChunkSize ?? DEFAULT_SETTINGS.minimumChunkSize,\n encrypt: this.options.passphrase ? true : false,\n passphrase: this.options.passphrase ?? \"\",\n idDerivationVersion: this.options.idDerivationVersion ?? 0,\n idDerivationKey: this.options.idDerivationKey ?? \"\",\n deleteMetadataOfDeletedFiles: DEFAULT_SETTINGS.deleteMetadataOfDeletedFiles,\n customChunkSize: this.options.customChunkSize ?? DEFAULT_SETTINGS.customChunkSize,\n doNotPaceReplication: DEFAULT_SETTINGS.doNotPaceReplication,\n hashAlg: this.options.hashAlg ?? DEFAULT_SETTINGS.hashAlg,\n useEden: this.options.useEden ?? DEFAULT_SETTINGS.useEden,\n maxChunksInEden: this.options.maxChunksInEden ?? DEFAULT_SETTINGS.maxChunksInEden,\n maxTotalLengthInEden: this.options.maxTotalLengthInEden ?? DEFAULT_SETTINGS.maxTotalLengthInEden,\n maxAgeInEden: this.options.maxAgeInEden ?? DEFAULT_SETTINGS.maxAgeInEden,\n enableChunkSplitterV2: this.options.enableChunkSplitterV2 ?? DEFAULT_SETTINGS.enableChunkSplitterV2,\n chunkSplitterVersion: this.options.chunkSplitterVersion ?? DEFAULT_SETTINGS.chunkSplitterVersion,\n disableWorkerForGeneratingChunks: true,\n processSmallFilesInUIThread: true,\n doNotUseFixedRevisionForChunks:\n this.options.doNotUseFixedRevisionForChunks ?? DEFAULT_SETTINGS.doNotUseFixedRevisionForChunks,\n couchDB_URI: this.options.url,\n couchDB_DBNAME: this.options.database,\n couchDB_USER: this.options.username,\n couchDB_PASSWORD: this.options.password,\n accessKey: \"\",\n secretKey: \"\",\n bucket: \"\",\n region: \"\",\n endpoint: \"\",\n enableCompression: this.options.enableCompression ?? DEFAULT_SETTINGS.enableCompression,\n handleFilenameCaseSensitive:\n this.options.handleFilenameCaseSensitive ?? DEFAULT_SETTINGS.handleFilenameCaseSensitive,\n usePathObfuscation: !!this.options.obfuscatePassphrase,\n encryptInternalMetadata: this.options.encryptInternalMetadata ?? false,\n E2EEAlgorithm: this.options.E2EEAlgorithm ?? E2EEAlgorithms.V2,\n },\n };\n return retObj;\n }\n\n /**\n * Get specific document from the Remote Database by path.\n * @param path\n * @param metaOnly if it has been enabled, the note does not contains the content.\n * @returns\n */\n async get(path: FilePathWithPrefix, metaOnly = false) {\n if (metaOnly) {\n return await this.liveSyncLocalDB.getDBEntryMeta(path);\n } else {\n return await this.liveSyncLocalDB.getDBEntry(path);\n }\n }\n\n /**\n * Get specific document from the Remote Database by ID.\n * @param path\n * @param metaOnly if it has been enabled, the note does not contains the content.\n * @returns\n */\n async getById(id: string, metaOnly = false): Promise<false | MetaEntry | ReadyEntry> {\n // TODO: TREAT FOR CONFLICTED FILES or OLD REVISIONS.\n // Logger(`GET: START: ${id}`, LOG_LEVEL_VERBOSE)\n const meta = await this.liveSyncLocalDB.getRaw(id as DocumentID);\n if (!isNoteEntry(meta)) return false;\n if (metaOnly) {\n // Logger(`GET: DONE (METAONLY): ${id}`, LOG_LEVEL_INFO)\n return meta;\n }\n return this.getByMeta(meta);\n }\n async getByMeta(doc: MetaEntry): Promise<ReadyEntry> {\n const docX = await this.liveSyncLocalDB.getDBEntryFromMeta(doc as LoadedEntry);\n if (!isReadyEntry(docX)) {\n throw new Error(`Corrupted document: ${doc.path}`);\n }\n return docX;\n }\n\n async rawGet<T>(id: DocumentID): Promise<false | T> {\n try {\n const doc = await this.liveSyncLocalDB.getRaw(id);\n return doc as T;\n } catch (ex) {\n if (isErrorOfMissingDoc(ex)) {\n return false;\n }\n throw ex;\n }\n }\n\n /**\n * Put a note to the remote database\n * @param path\n * @param data\n * @param info\n * @param type\n * @returns\n */\n async put(path: string, data: string[] | Blob, info: FileInfo, _type: \"newnote\" | \"plain\" = \"plain\") {\n const id = await this.path2id(path as FilePathWithPrefix);\n const saveData = data instanceof Blob ? data : createBlob(data);\n const datatype = determineTypeFromBlob(saveData);\n const putDoc = {\n _id: id,\n path: path as FilePathWithPrefix,\n data: saveData,\n ctime: info.ctime,\n mtime: info.mtime,\n size: info.size,\n type: datatype,\n eden: {},\n children: [] as string[],\n datatype: datatype,\n };\n Logger(`PUT: UPLOADING: ${path}`, LOG_LEVEL_VERBOSE);\n const ret = await this.liveSyncLocalDB.putDBEntry(putDoc);\n if (ret) {\n Logger(`PUT: DONE: ${path}`, LOG_LEVEL_INFO);\n return true;\n } else {\n Logger(`PUT: FAILED: ${path}`, LOG_LEVEL_NOTICE);\n return false;\n }\n }\n\n async delete(path: string) {\n Logger(`DELETE: START: ${path}`, LOG_LEVEL_VERBOSE);\n const ret = await this.liveSyncLocalDB.deleteDBEntry(path as FilePathWithPrefix);\n if (ret) {\n Logger(`DELETE: DONE: ${path}`, LOG_LEVEL_INFO);\n return true;\n } else {\n Logger(`DELETE: FAILED: ${path}`, LOG_LEVEL_INFO);\n return false;\n }\n }\n // Untested\n async *enumerate(_cond: EnumerateConditions) {\n //TODO\n // const param = {} as Record<string, string>;\n // if (cond.startKey) param.startkey = cond.startKey;\n // if (cond.endKey) param.endkey = cond.endKey;\n // if (cond.ids) param.keys = JSON.stringify(cond.ids);\n // let key = cond.startKey;\n // do {\n // const result = await this._fetchJson([\"_all_docs\"], {}, \"get\", { ...param, include_docs: true, startkey: key, limit: 100 });\n // if (!result.rows || result.rows.length == 0) {\n // break;\n // }\n // //there are some result\n // for (const v of result.rows) {\n // const doc = v.doc;\n // if (cond.metaOnly) {\n // yield await doc;\n // } else {\n // yield await this.getByMeta(doc);\n // }\n // key = doc._id + \"\\u{10ffff}\"\n // }\n // } while (true);\n // return;\n }\n async *_enumerate(startKey: string, endKey: string, opt: { metaOnly: boolean }) {\n if (opt.metaOnly) return yield* this.liveSyncLocalDB.findEntries(startKey, endKey, {});\n for await (const f of this.liveSyncLocalDB.findEntries(startKey, endKey, {})) {\n yield await this.getByMeta(f);\n }\n }\n async *enumerateAllNormalDocs(opt: { metaOnly: boolean }) {\n // const opt = {};\n const targets = [\n this._enumerate(\"\", \"h:\", opt),\n this._enumerate(`h:\\u{10ffff}`, \"i:\", opt),\n this._enumerate(`i:\\u{10ffff}`, \"ix:\", opt),\n this._enumerate(`ix:\\u{10ffff}`, \"ps:\", opt),\n this._enumerate(`ps:\\u{10ffff}`, \"\\u{10ffff}\", opt),\n ];\n for (const target of targets) {\n for await (const f of target) {\n yield f;\n }\n }\n }\n\n watching = false;\n // _abortController?: AbortController;\n changes: PouchDB.Core.Changes<EntryDoc> | undefined;\n since = \"\";\n\n beginWatch(\n callback: (doc: ReadyEntry, seq?: string | number) => Promise<any> | void,\n checkIsInterested?: (doc: MetaEntry) => boolean\n ) {\n if (this.watching) return false;\n this.watching = true;\n this.changes = this.liveSyncLocalDB.localDatabase\n .changes({\n include_docs: true,\n since: this.since,\n selector: {\n type: { $ne: \"leaf\" },\n },\n live: true,\n })\n .on(\"change\", async (change: any) => {\n const doc = change.doc;\n if (!doc) {\n return;\n }\n if (!isNoteEntry(doc)) {\n return;\n }\n if (checkIsInterested) {\n if (!checkIsInterested(doc)) {\n Logger(`WATCH: SKIP ${doc.path}: OUT OF TARGET FOLDER`, LOG_LEVEL_VERBOSE, \"watch\");\n return;\n }\n }\n Logger(`WATCH: PROCESSING: ${doc.path}`, LEVEL_VERBOSE, \"watch\");\n let docX;\n try {\n docX = await this.getByMeta(doc);\n } catch (ex) {\n Logger(`WATCH: DOCUMENT LOAD FAILED: ${doc.path}`, LEVEL_INFO, \"watch\");\n Logger(ex, LEVEL_VERBOSE, \"watch\");\n return;\n }\n try {\n await callback(docX, change.seq);\n Logger(`WATCH: PROCESS DONE: ${doc.path}`, LEVEL_INFO, \"watch\");\n } catch (ex) {\n Logger(`WATCH: PROCESS FAILED`, LEVEL_INFO, \"watch\");\n Logger(ex, LEVEL_VERBOSE, \"watch\");\n }\n })\n .on(\"complete\", () => {\n Logger(`WATCH: FINISHED`, LEVEL_INFO, \"watch\");\n this.watching = false;\n this.changes = undefined;\n })\n .on(\"error\", (err: Error) => {\n Logger(`WATCH: ERROR: `, LEVEL_INFO, \"watch\");\n Logger(err, LEVEL_VERBOSE, \"watch\");\n if (this.watching) {\n Logger(`WATCH: CONNECTION HAS BEEN CLOSED, RECONNECTING...`, LEVEL_INFO, \"watch\");\n this.watching = false;\n this.changes = undefined;\n compatGlobal.setTimeout(() => {\n this.beginWatch(callback, checkIsInterested);\n }, 10000);\n } else {\n Logger(`WATCH: CONNECTION HAS BEEN CLOSED.`, LEVEL_INFO, \"watch\");\n }\n });\n }\n endWatch() {\n if (this.changes) {\n Logger(`WATCH: CANCELLING PROCESS.`, LEVEL_INFO, \"watch\");\n this.changes.cancel();\n Logger(`WATCH: CANCELLING SIGNAL HAS BEEN SENT.`, LEVEL_INFO, \"watch\");\n }\n }\n async followUpdates(\n callback: (doc: ReadyEntry, seq?: string | number) => Promise<any> | void,\n checkIsInterested?: (doc: MetaEntry) => boolean\n ) {\n try {\n if (this.since == \"\") {\n this.since = \"0\";\n }\n Logger(`FOLLOW: START: (since:${this.since})`, LEVEL_INFO, \"followUpdates\");\n const last = await this.liveSyncLocalDB.localDatabase\n .changes({\n include_docs: true,\n since: this.since,\n filter: \"replicate/pull\",\n live: false,\n })\n .on(\"change\", async (change) => {\n const doc = change.doc;\n if (!doc) {\n return;\n }\n if (!isNoteEntry(doc)) {\n return;\n }\n if (checkIsInterested) {\n if (!checkIsInterested(doc)) {\n Logger(`FOLLOW: SKIP ${doc._id}: OUT OF TARGET FOLDER`, LOG_LEVEL_VERBOSE, \"watch\");\n return;\n }\n }\n Logger(`FOLLOW: PROCESSING: ${doc.path}`, LEVEL_VERBOSE, \"watch\");\n const docX = await this.getByMeta(doc);\n try {\n await callback(docX, change.seq);\n Logger(`FOLLOW: PROCESS DONE: ${doc.path}`, LEVEL_INFO, \"watch\");\n } catch (ex) {\n Logger(`FOLLOW: PROCESS FAILED`, LEVEL_INFO, \"watch\");\n Logger(ex, LEVEL_VERBOSE, \"watch\");\n }\n })\n .on(\"complete\", () => {\n Logger(`FOLLOW: FINISHED AT ${this.since}`, LEVEL_INFO, \"watch\");\n this.watching = false;\n this.changes = undefined;\n })\n .on(\"error\", (err) => {\n Logger(`FOLLOW: ERROR at ${this.since}: ${err}`, LEVEL_INFO, \"watch\");\n });\n return last.last_seq;\n } catch (e) {\n Logger(`FOLLOW: ERROR: ${e}`, LEVEL_INFO, \"watch\");\n }\n return this.since;\n }\n}\n","// Sync Parameters management functions\n// This file is responsible for managing synchronisation parameters, including fetching, creating, and updating them.\n//\n// The Security Seed (represented as PBKDF2 Salt in logs) derives the encryption key for replication, so it should be stored on the server prior to synchronisation.\nimport { createPBKDF2Salt } from \"octagonal-wheels/encryption/hkdf\";\nimport { LOG_LEVEL_INFO, LOG_LEVEL_VERBOSE, Logger } from \"@lib/common/logger.ts\";\nimport type { SyncParameters } from \"@lib/common/types.ts\";\nimport { arrayBufferToBase64Single, base64ToArrayBufferInternalBrowser } from \"@lib/string_and_binary/convert.ts\";\nimport { LiveSyncError } from \"@lib/common/LSError.ts\";\n\n/**\n * Creates a SyncParamsHandler for managing synchronisation parameters.\n */\ntype putFunc = (params: SyncParameters) => Promise<boolean>;\n/**\n * Fetches synchronisation parameters from the server.\n */\ntype getFunc = () => Promise<SyncParameters>;\n/**\n * The function to create new synchronisation parameters.\n * Note that this function should not return `pbkdf2salt` in the result; it should be generated and stored in the handler.\n */\ntype createFunc = () => Promise<SyncParameters>;\n\ntype CreateSyncParamsHanderOptions = {\n put: putFunc;\n get: getFunc;\n create: createFunc;\n};\n\nexport type SyncParamsHandler = {\n fetch: (refresh?: boolean) => Promise<SyncParameters | false>;\n getPBKDF2Salt: (refresh?: boolean) => Promise<Uint8Array<ArrayBuffer>>;\n};\nconst _handlers = new Map<string, SyncParamsHandler>();\n\nexport function createSyncParamsHanderForServer(\n key: string,\n options: CreateSyncParamsHanderOptions\n): SyncParamsHandler {\n if (_handlers.has(key)) {\n return _handlers.get(key)!;\n }\n const handler = createSyncParamsHandler(options);\n _handlers.set(key, handler);\n return handler;\n}\nexport function clearHandlers() {\n _handlers.clear();\n}\nexport class SyncParamsHandlerError extends LiveSyncError {}\nexport class SyncParamsFetchError extends SyncParamsHandlerError {}\nexport class SyncParamsNotFoundError extends SyncParamsHandlerError {}\nexport class SyncParamsUpdateError extends SyncParamsHandlerError {}\n\n/**\n * SyncParameters with decoded PBKDF2 salt (as Uint8Array).\n * This is for performance reasons, to avoid decoding it every time.\n */\ntype SyncParametersWithDecoded = SyncParameters & {\n pbkdf2saltDecoded?: Uint8Array<ArrayBuffer>;\n};\n\n/** Create a handler owned by one operation rather than the process-wide server cache. */\nexport function createSyncParamsHandler({ put, get, create }: CreateSyncParamsHanderOptions): SyncParamsHandler {\n // To cache the fetched synchronisation parameters, we re-use the promise to save memory consumption.\n let taskFetchParameters: Promise<SyncParametersWithDecoded | false> | undefined = undefined;\n\n // This function fetches synchronisation parameters from the server, ensuring that they have PBKDF2 salt.\n const _fetchSyncParameters = async (): Promise<SyncParametersWithDecoded | false> => {\n let syncParams: SyncParametersWithDecoded | undefined = undefined;\n try {\n let shouldRetry = false;\n do {\n shouldRetry = false;\n // 1. Try to fetch the synchronisation parameters from the server.\n try {\n syncParams = await get();\n Logger(`Fetched synchronisation parameters`, LOG_LEVEL_INFO);\n } catch (ex) {\n if (LiveSyncError.isCausedBy(ex, SyncParamsNotFoundError)) {\n // Expected error; we will create new synchronisation parameters.\n Logger(`Synchronisation parameters not found, creating new ones`, LOG_LEVEL_INFO);\n const newSyncParams = await create();\n // If we have created new synchronisation parameters, immediately store them to the server, without salt.\n // If a race condition occurs, it will cause a 409 (conflict) error. This should be detected and handled as an error; purging the cache and retrying.\n const putResult = await put(newSyncParams);\n if (!putResult) {\n Logger(`Failed to store initial synchronisation parameters`, LOG_LEVEL_INFO);\n throw new SyncParamsUpdateError(`Failed to store initial synchronisation parameters`);\n }\n Logger(\n `Initial synchronisation parameters stored successfully, retrying fetch`,\n LOG_LEVEL_INFO\n );\n shouldRetry = true;\n } else {\n // Unexpected error; rethrow it, as we cannot proceed without synchronisation parameters.\n throw ex;\n }\n }\n } while (shouldRetry);\n\n // 2. If the synchronisation parameters are fetched, ensure that they have PBKDF2 salt.\n // 2.1. If something went wrong, we cannot proceed without synchronisation parameters.\n if (!syncParams) {\n throw new SyncParamsFetchError(`Unexpected empty synchronisation parameters`);\n }\n // 2.2. If the synchronisation parameters do not have PBKDF2 salt, create a new one.\n if (!syncParams.pbkdf2salt) {\n Logger(`Synchronisation parameters do not have PBKDF2 salt, generating a new salt`, LOG_LEVEL_INFO);\n const salt = await arrayBufferToBase64Single(createPBKDF2Salt());\n if (!salt) {\n Logger(`Failed to generate PBKDF2 salt`, LOG_LEVEL_INFO);\n throw new SyncParamsFetchError(`Failed to generate PBKDF2 salt`);\n }\n syncParams.pbkdf2salt = salt;\n // We need to store the synchronisation parameters with the new salt immediately. If this fails, we cannot proceed (this means synchronisation parameters are created with another device).\n const putResult = await put(syncParams);\n if (!putResult) {\n Logger(`Failed to store synchronisation parameters with new PBKDF2 salt`, LOG_LEVEL_INFO);\n throw new SyncParamsUpdateError(`Failed to store synchronisation parameters with new PBKDF2 salt`);\n }\n syncParams = await get();\n }\n\n if (!syncParams) {\n // Again, something went wrong; we cannot proceed without synchronisation parameters. Indeed, this should not happen.\n throw new Error(`Failed to prepare synchronisation key in synchronisation parameters`);\n }\n\n Logger(`Synchronisation parameters fetched successfully`, LOG_LEVEL_INFO);\n // 3. Decode PBKDF2 salt from base64 to Uint8Array.\n if (!syncParams.pbkdf2saltDecoded) {\n const decodedSalt = new Uint8Array(base64ToArrayBufferInternalBrowser(syncParams.pbkdf2salt));\n if (!decodedSalt) {\n throw new SyncParamsFetchError(`Failed to decode PBKDF2 salt`);\n }\n syncParams.pbkdf2saltDecoded = decodedSalt;\n }\n return syncParams;\n } catch (ex) {\n Logger(`Failed to fetch synchronisation parameters`, LOG_LEVEL_INFO);\n Logger(ex, LOG_LEVEL_VERBOSE);\n // To retry fetching synchronisation parameters in the next call.\n taskFetchParameters = undefined;\n return false;\n }\n };\n const fetchSyncParameters = (refresh: boolean = false): Promise<SyncParametersWithDecoded | false> => {\n if (taskFetchParameters && !refresh) {\n return taskFetchParameters;\n }\n taskFetchParameters = _fetchSyncParameters();\n return taskFetchParameters;\n };\n\n return {\n fetch: fetchSyncParameters,\n getPBKDF2Salt: async (refresh: boolean = false) => {\n const syncParams = await fetchSyncParameters(refresh);\n if (!syncParams) {\n Logger(`Failed to fetch synchronisation parameters`, LOG_LEVEL_INFO);\n throw new SyncParamsFetchError(`Failed to fetch synchronisation parameters`);\n }\n return syncParams.pbkdf2saltDecoded!;\n },\n };\n}\n","import type { FilePathWithPrefix, ObsidianLiveSyncSettings } from \"@lib/common/types\";\n\nexport const EVENT_LAYOUT_READY = \"layout-ready\";\nexport const EVENT_PLUGIN_LOADED = \"plugin-loaded\";\nexport const EVENT_PLUGIN_UNLOADED = \"plugin-unloaded\";\nexport const EVENT_SETTING_SAVED = \"setting-saved\";\nexport const EVENT_FILE_RENAMED = \"file-renamed\";\nexport const EVENT_FILE_SAVED = \"file-saved\";\nexport const EVENT_LEAF_ACTIVE_CHANGED = \"leaf-active-changed\";\n\nexport const EVENT_DATABASE_REBUILT = \"database-rebuilt\";\n/** Emitted by `AppLifecycleService.markIsReady()` each time it establishes application readiness. */\nexport const EVENT_APPLICATION_READY = \"application-ready\";\n\nexport const EVENT_LOG_ADDED = \"log-added\";\n\nexport const EVENT_REQUEST_OPEN_SETUP_URI = \"request-open-setup-uri\";\nexport const EVENT_REQUEST_COPY_SETUP_URI = \"request-copy-setup-uri\";\nexport const EVENT_REQUEST_SHOW_SETUP_QR = \"request-show-setup-qr\";\n\nexport const EVENT_REQUEST_RELOAD_SETTING_TAB = \"reload-setting-tab\";\n\nexport const EVENT_REQUEST_OPEN_PLUGIN_SYNC_DIALOG = \"request-open-plugin-sync-dialog\";\n\nexport const EVENT_FILE_CHANGED = \"event-file-changed\";\n\nexport const EVENT_REQUEST_OPEN_P2P_SETTINGS = \"request-open-p2p-settings\";\nexport const EVENT_REQUEST_OPEN_P2P = \"request-open-p2p\";\nexport const EVENT_REQUEST_CLOSE_P2P = \"request-close-p2p\";\nexport const EVENT_PLATFORM_UNLOADED = \"platform-unloaded\";\n\nexport const EVENT_ON_UNRESOLVED_ERROR = \"on-unresolved-error\";\n\nexport const EVENT_REQUEST_CHECK_REMOTE_SIZE = \"request-check-remote-size\";\nexport const EVENT_CONFLICT_CANCELLED = \"conflict-cancelled\";\n\n// export const EVENT_FILE_CHANGED = \"file-changed\";\n\ndeclare global {\n interface LSEvents {\n [EVENT_PLUGIN_LOADED]: undefined;\n [EVENT_PLUGIN_UNLOADED]: undefined;\n [EVENT_FILE_SAVED]: undefined;\n [EVENT_SETTING_SAVED]: ObsidianLiveSyncSettings;\n [EVENT_LAYOUT_READY]: undefined;\n [EVENT_FILE_CHANGED]: { file: FilePathWithPrefix; automated: boolean };\n [EVENT_FILE_RENAMED]: { newPath: FilePathWithPrefix; old: FilePathWithPrefix };\n\n [EVENT_DATABASE_REBUILT]: undefined;\n [EVENT_APPLICATION_READY]: undefined;\n [EVENT_REQUEST_OPEN_P2P_SETTINGS]: undefined;\n [EVENT_LEAF_ACTIVE_CHANGED]: undefined;\n [EVENT_REQUEST_OPEN_SETUP_URI]: undefined;\n [EVENT_REQUEST_COPY_SETUP_URI]: undefined;\n [EVENT_REQUEST_RELOAD_SETTING_TAB]: undefined;\n [EVENT_REQUEST_OPEN_PLUGIN_SYNC_DIALOG]: undefined;\n [EVENT_REQUEST_SHOW_SETUP_QR]: undefined;\n [EVENT_REQUEST_OPEN_P2P]: undefined;\n [EVENT_REQUEST_CLOSE_P2P]: undefined;\n [EVENT_PLATFORM_UNLOADED]: undefined;\n [EVENT_ON_UNRESOLVED_ERROR]: undefined;\n [EVENT_REQUEST_CHECK_REMOTE_SIZE]: undefined;\n [EVENT_CONFLICT_CANCELLED]: FilePathWithPrefix;\n }\n}\n","import { promiseWithResolvers } from \"octagonal-wheels/promises\";\nimport { LOG_LEVEL_VERBOSE, Logger } from \"@lib/common/logger\";\n/**\n * A function type that can be used as a handler.\n */\ntype HandlerFunc<TArg extends unknown[], TResult> = (...args: TArg) => TResult | Promise<TResult>;\n\n/**\n * A function type that returns a boolean or a Promise of boolean.\n */\ntype BooleanHandlerFunc<TArg extends unknown[], U = boolean> = (...args: TArg) => U | Promise<U>;\n\n/**\n * An interface for invokable handlers that can add and remove handler functions.\n */\nexport interface InvokableHandler<T extends unknown[], U> {\n /**\n * Invokes the handler with the provided arguments.\n * @param args The arguments to pass to the handler.\n * @returns A Promise that resolves to the result of the handler.\n */\n invoke(...args: T): Promise<U>;\n}\n/**\n * An interface for invokable boolean handlers that can add and remove handler functions.\n */\ntype InvokableBooleanHandler<T extends unknown[]> = InvokableHandler<T, boolean>;\n/**\n * A function type that can be used to unregister a handler.\n */\nexport type UnregisterFunction = () => void;\n\n/**\n * An interface for binder handlers that can assign a single handler function.\n */\nexport interface BinderHandler<T extends unknown[], U> {\n assign(callback: HandlerFunc<T, U>, override?: boolean): UnregisterFunction;\n}\n/**\n * An interface for multi-binder handlers that can add and remove handler functions.\n */\nexport interface MultiRegisterHandler<T extends unknown[], U> {\n /**\n * Adds a handler function.\n * Note: The same function only added once.\n * If you want to prevent duplication, please remove the existing handler before adding it again.\n * @param callback The handler function to add.\n * @returns A function to remove the added handler.\n */\n addHandler(callback: BooleanHandlerFunc<T, U>): UnregisterFunction;\n /**\n * Removes a handler function.\n * @param callback The handler function to remove.\n */\n removeHandler(callback: BooleanHandlerFunc<T, U>): void;\n use(callback: BooleanHandlerFunc<T, U>): UnregisterFunction;\n}\n\n/**\n * An interface for dispatch handlers that can dispatch events to multiple handlers.\n */\nexport interface DispatcherHandler<T extends unknown[], U> {\n dispatch(...args: T): Promise<(Awaited<U> | Error)[]>;\n}\n/**\n * An interface for dispatch handlers that can add and remove handler functions.\n */\nexport interface DispatchHandler<T extends unknown[], U> extends DispatcherHandler<T, U>, MultiRegisterHandler<T, U> {}\n\n/**\n * A binder that allows assigning and invoking a single handler function.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- covariant in return type, so cannot be generic.\nexport class Binder<T extends (...args: any[]) => any>\n implements BinderHandler<Parameters<T>, ReturnType<T>>, InvokableHandler<Parameters<T>, ReturnType<T>>\n{\n private _name: string;\n /**\n * Creates a new Binder instance.\n * @param name The name of the handler.\n * @param initialCallback An optional initial callback function to assign.\n */\n constructor(name: string, initialCallback?: T) {\n this._name = name;\n if (initialCallback) {\n this._callback = initialCallback;\n }\n }\n private _callback: T | null = null;\n\n /**\n * Assigns a new handler function.\n * @param callback The new handler function to assign.\n */\n assign(callback: T, override: boolean = false) {\n if (this._callback && !override) {\n throw new Error(`Handler ${this._name} is already assigned.`);\n }\n this._callback = callback;\n return () => {\n this._callback = null;\n };\n }\n\n /**\n * Invokes the assigned handler function with the provided arguments.\n * @param args The arguments to pass to the handler function.\n * @returns The result of the handler function.\n */\n invoke(...args: Parameters<T>): ReturnType<T> {\n if (this._callback) {\n return this._callback(...args);\n }\n throw new Error(`Handler ${this._name} is not assigned.`);\n }\n}\n\n/**\n * A binder that allows assigning and invoking a single handler function asynchronously.\n * The invocation will wait until a handler is assigned.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- covariant in return type, so cannot be generic.\nexport class LazyBinder<T extends (...args: any[]) => any>\n implements\n BinderHandler<Parameters<T>, ReturnType<T>>,\n InvokableHandler<Parameters<T>, Promise<Awaited<ReturnType<T>>>>\n{\n private _name: string;\n private _callbackPromise = promiseWithResolvers<void>();\n private _callback: T | null = null;\n\n /**\n * Creates a new LazyBinder instance.\n * @param name The name of the handler.\n * @param initialCallback An optional initial callback function to assign.\n */\n constructor(name: string, initialCallback?: T) {\n this._name = name;\n if (initialCallback) {\n this._callback = initialCallback;\n this._callbackPromise.resolve();\n }\n }\n assign(callback: T, override: boolean = false) {\n if (this._callback && !override) {\n throw new Error(`Handler ${this._name} is already assigned.`);\n }\n this._callback = callback;\n this._callbackPromise.resolve();\n return () => {\n this._callback = null;\n this._callbackPromise = promiseWithResolvers<void>();\n };\n }\n\n /**\n * Invokes the assigned handler function with the provided arguments.\n * @param args The arguments to pass to the handler function.\n * @returns The result of the handler function.\n */\n async invoke(...args: Parameters<T>): Promise<Awaited<ReturnType<T>>> {\n await this._callbackPromise.promise;\n if (this._callback) {\n return await this._callback(...args);\n }\n // Most likely unreachable (assign by null?)\n throw new Error(`Handler ${this._name} is not assigned.`);\n }\n}\n\n/**\n * A multi-binder that allows adding and removing multiple handler functions.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- covariant in return type, so cannot be generic.\nexport class MultiBinder<T extends (...args: any[]) => any> implements MultiRegisterHandler<\n Parameters<T>,\n ReturnType<T>\n> {\n protected _name: string;\n /**\n * Creates a new MultiBinder instance.\n * @param name The name of the handler.\n */\n constructor(name: string) {\n this._name = name;\n }\n protected _callbackMap = new Map<T, [number, number]>();\n protected _isCallbackDirty = false;\n protected _maxUsedPriority = 0;\n\n /**\n * Adds a handler function.\n * Note: The same function is only added once.\n * @param callback The handler function to add.\n * @param priority The priority of the handler, Do not use floating numbers to prevent confusion.\n * @returns A function to unregister the added handler.\n *\n */\n addHandler(callback: T, priority: number = 0, allowSwap: boolean = false): UnregisterFunction {\n // if (this._callbackMap.has(callback)) {\n // if (allowSwap) {\n // this.removeHandler(callback);\n // } else {\n // throw new Error(`Handler ${this._name} already has the same callback`);\n // }\n // }\n this._callbackMap.set(callback, [priority, this._maxUsedPriority++]);\n this._isCallbackDirty = true;\n const unregister = () => {\n this.removeHandler(callback);\n this._isCallbackDirty = true;\n };\n return unregister;\n }\n\n /**\n * Removes a handler function.\n * @param callback The handler function to remove.\n */\n removeHandler(callback: T) {\n this._callbackMap.delete(callback);\n this._isCallbackDirty = true;\n }\n\n /**\n * Adds a handler function (alias of addHandler, but more semantic).\n * @param callback\n * @returns\n */\n use(callback: T, priority: number = 0) {\n return this.addHandler(callback, priority);\n }\n\n _sortedCallbacks: T[] = [];\n protected get _callbacks(): T[] {\n if (this._isCallbackDirty) {\n this._sortedCallbacks = Array.from(this._callbackMap.entries())\n .sort((a, b) => {\n const [priorityA, registerOrderA] = a[1];\n const [priorityB, registerOrderB] = b[1];\n if (priorityA !== priorityB) {\n return priorityA - priorityB; // Sort by priority first\n }\n return registerOrderA - registerOrderB; // If priorities are equal, sort by registration order\n })\n .map((entry) => entry[0]);\n this._isCallbackDirty = false;\n }\n return this._sortedCallbacks;\n }\n}\n\n/**\n * A dispatcher that invokes all added handler functions sequentially and collects their results.\n * */\nexport class Dispatch<T extends unknown[], U>\n extends MultiBinder<HandlerFunc<T, U>>\n implements DispatcherHandler<T, U>\n{\n /**\n * Dispatches the event to all registered handlers sequentially.\n * @param args The arguments to pass to the handlers.\n * @returns An array of results or errors from each handler.\n */\n async dispatch(...args: T): Promise<(Awaited<U> | Error)[]> {\n const results: (Awaited<U> | Error)[] = [];\n const _callbacks = [...this._callbacks];\n for (const callback of _callbacks) {\n try {\n const result = await Promise.resolve(callback(...args));\n results.push(result);\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n results.push(err);\n }\n }\n return results;\n }\n}\n\n/**\n * A dispatcher that invokes all added handler functions in parallel and collects their results.\n */\nexport class DispatchParallel<T extends unknown[], U>\n extends MultiBinder<HandlerFunc<T, U>>\n implements DispatcherHandler<T, U>\n{\n /**\n * Dispatches the event to all registered handlers in parallel.\n * @param args The arguments to pass to the handlers.\n * @returns An array of results or errors from each handler.\n */\n dispatch(...args: T): Promise<(Awaited<U> | Error)[]> {\n const callbacks = [...this._callbacks];\n const promises: Promise<U | Error>[] = callbacks.map(async (callback) => {\n try {\n const result = await Promise.resolve(callback(...args));\n return result;\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n return err;\n }\n });\n const results = Promise.all(promises);\n return results;\n }\n}\n\n/**\n * A base class for boolean handlers that can add and remove handler functions.\n */\nexport abstract class BooleanHandlerBase<T extends unknown[], U = boolean>\n extends MultiBinder<BooleanHandlerFunc<T, U>>\n implements InvokableBooleanHandler<T>\n{\n abstract invoke(...args: T): Promise<boolean>;\n}\n\n/**\n * A handler that invokes all added handler functions sequentially until one returns false.\n */\nexport class AllHandler<T extends unknown[]> extends BooleanHandlerBase<T> {\n /**\n * Invoke all handlers sequentially until one returns false.\n * @param args The arguments to pass to the handlers.\n * @returns A Promise that resolves to true if all handlers return true, otherwise false.\n */\n async invoke(...args: T): Promise<boolean> {\n const _callbacks = [...this._callbacks];\n for (const callback of _callbacks) {\n try {\n const result = await Promise.resolve(callback(...args));\n if (result === false) {\n return false;\n }\n } catch (error) {\n // On error, consider it as failure\n Logger(`AllHandler ${this._name} treated error as failure!`, LOG_LEVEL_VERBOSE);\n Logger(error, LOG_LEVEL_VERBOSE);\n return false;\n }\n }\n return true;\n }\n}\n\n/**\n * A handler that preserves a non-boolean continuation result while continuing\n * to give false results and exceptions veto power.\n */\nexport class AllWithResultHandler<T extends unknown[], U extends boolean | string>\n extends MultiBinder<BooleanHandlerFunc<T, U>>\n implements InvokableHandler<T, U>\n{\n /**\n * Invokes every handler in order. The first non-boolean continuation result\n * is retained, but every remaining handler can still reject the operation.\n * @param args The arguments to pass to the handlers.\n * @returns False after any failure, otherwise the retained result or true.\n */\n async invoke(...args: T): Promise<U> {\n let aggregateResult = true as U;\n const callbacks = [...this._callbacks];\n for (const callback of callbacks) {\n try {\n const result = await Promise.resolve(callback(...args));\n if (result === false) {\n return false as U;\n }\n if (aggregateResult === true && result !== true) {\n aggregateResult = result;\n }\n } catch (error) {\n Logger(`AllWithResultHandler ${this._name} treated error as failure!`, LOG_LEVEL_VERBOSE);\n Logger(error, LOG_LEVEL_VERBOSE);\n return false as U;\n }\n }\n return aggregateResult;\n }\n}\n\n/**\n * A handler that invokes every added handler sequentially and reports whether\n * all of them succeeded.\n *\n * Unlike {@link AllHandler}, a failure does not prevent later cleanup handlers\n * from settling.\n */\nexport class SettledAllHandler<T extends unknown[]> extends BooleanHandlerBase<T> {\n /**\n * Invokes every handler in order, treating a false result or an exception\n * as an aggregate failure.\n * @param args The arguments to pass to the handlers.\n * @returns True only when every handler succeeds.\n */\n async invoke(...args: T): Promise<boolean> {\n let succeeded = true;\n const callbacks = [...this._callbacks];\n for (const callback of callbacks) {\n try {\n const result = await Promise.resolve(callback(...args));\n if (result === false) {\n succeeded = false;\n }\n } catch (error) {\n Logger(`SettledAllHandler ${this._name} treated error as failure!`, LOG_LEVEL_VERBOSE);\n Logger(error, LOG_LEVEL_VERBOSE);\n succeeded = false;\n }\n }\n return succeeded;\n }\n}\n/**\n * A handler that invokes all added handler functions in parallel and returns true only if all return true.\n */\nexport class ParallelAllHandler<T extends unknown[]> extends BooleanHandlerBase<T> {\n /**\n * Invoke all handlers in parallel\n * @param args The arguments to pass to the handlers.\n * @returns True if all handlers return true, otherwise false.\n */\n async invoke(...args: T): Promise<boolean> {\n const callbacks = [...this._callbacks];\n const promises: Promise<boolean>[] = callbacks.map(async (callback) => {\n try {\n const result = await Promise.resolve(callback(...args));\n return result;\n } catch (error) {\n // On error, consider it as failure\n Logger(`ParallelAllHandler ${this._name} treated error as failure!`, LOG_LEVEL_VERBOSE);\n Logger(error, LOG_LEVEL_VERBOSE);\n return false;\n }\n });\n const results = await Promise.all(promises);\n return results.every((res) => res === true);\n }\n}\n\n/**\n * A handler that invokes all added handler functions sequentially until one returns true.\n */\nexport class AnySuccessHandler<T extends unknown[]> extends BooleanHandlerBase<T> {\n /**\n * Invokes handlers sequentially until one returns true.\n * @param args The arguments to pass to the handlers.\n * @returns True if any handler returns true, otherwise false.\n */\n async invoke(...args: T): Promise<boolean> {\n const _callbacks = [...this._callbacks];\n for (const callback of _callbacks) {\n try {\n const result = await Promise.resolve(callback(...args));\n if (result === true) {\n return true;\n }\n } catch (error) {\n // Ignore errors for 'first success' handler\n Logger(`FirstSuccessHandler ${this._name} ignored error!`, LOG_LEVEL_VERBOSE);\n Logger(error, LOG_LEVEL_VERBOSE);\n }\n }\n return false;\n }\n}\n\n/**\n * A handler that invokes all added handler functions sequentially until one returns a non-falsy value.\n */\nexport class FirstResultHandler<T extends unknown[], U> extends MultiBinder<BooleanHandlerFunc<T, U>> {\n /**\n * Invokes handlers sequentially until one returns a non-falsy value.\n * @param args The arguments to pass to the handlers.\n * @returns The first non-falsy result from the handlers, or false if none found.\n */\n async invoke(...args: T): Promise<U | false> {\n const _callbacks = [...this._callbacks];\n for (const callback of _callbacks) {\n try {\n const result = await Promise.resolve(callback(...args));\n if (result !== undefined && result !== false) {\n return result;\n }\n } catch (error) {\n Logger(`FirstResultHandler ${this._name} ignored error!`, LOG_LEVEL_VERBOSE);\n Logger(error, LOG_LEVEL_VERBOSE);\n }\n }\n return false;\n }\n}\n\n/**\n * A function type that can be used as a handler with assignable functionality.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- covariant in return type, so cannot be generic.\nexport interface HandlerFunction<TFunc extends (...args: any[]) => U | Promise<U>, U = unknown> {\n /**\n * Invokes the handler function with the provided arguments.\n */\n (...args: Parameters<TFunc>): ReturnType<TFunc>;\n\n /**\n * Assigns a new handler function.\n * @param callback The new handler function to assign.\n * @param override Whether to override the existing handler if one is already assigned.\n * @returns A function to unregister the assigned handler.\n */\n setHandler: (callback: TFunc, override?: boolean) => void;\n}\n/**\n * A function type that can be used as a handler with assignable functionality.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- covariant in return type, so cannot be generic.\nexport interface LazyHandlerFunction<TFunc extends (...args: any[]) => U | Promise<U>, U = unknown> {\n /**\n * Invokes the handler function with the provided arguments.\n */\n (...args: Parameters<TFunc>): Promise<Awaited<ReturnType<TFunc>>>;\n\n /**\n * Assigns a new handler function.\n * @param callback The new handler function to assign.\n * @param override Whether to override the existing handler if one is already assigned.\n * @returns A function to unregister the assigned handler.\n */\n setHandler: (callback: TFunc, override?: boolean) => void;\n}\n/**\n * A function type that can be used as a multiple handler with add/remove functionality.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- covariant in return type, so cannot be generic.\nexport interface MultipleHandlerFunction<TFunc extends (...args: any[]) => U | Promise<U>, U = unknown> {\n /**\n * Invokes the handler function with the provided arguments.\n */\n (...args: Parameters<TFunc>): ReturnType<TFunc>;\n /**\n * Adds a handler function.\n * @param callback The handler function to add.\n * @returns A function to remove the added handler.\n */\n addHandler: (callback: TFunc, priority?: number) => () => void;\n /**\n * Removes a handler function.\n * @param callback The handler function to remove.\n * @returns\n */\n removeHandler: (callback: TFunc) => void;\n}\n\n/**\n * A function type that can be used as a value-collecting handler with add/remove functionality.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- covariant in return type, so cannot be generic.\nexport type CollectorFunction<TFunc extends (...args: any[]) => U | Promise<U>, U = unknown> = (\n ...args: Parameters<TFunc>\n) => Promise<Awaited<U>>;\n\n/**\n * A Handler function type that can have multiple handlers added or removed, and collects their results into an array.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- covariant in return type, so cannot be generic.\nexport interface CollectiveHandlerFunction<TFunc extends (...args: any[]) => U[] | Promise<U[]>, U = unknown> {\n /**\n * Invokes the handler function with the provided arguments.\n */\n (...args: Parameters<TFunc>): ReturnType<TFunc>;\n /**\n * Adds a handler function.\n * @param callback The handler function to add.\n * @returns A function to remove the added handler.\n */\n addHandler: (callback: CollectorFunction<TFunc>) => () => void;\n /**\n * Removes a handler function.\n * @param callback The handler function to remove.\n * @returns\n */\n removeHandler: (callback: CollectorFunction<TFunc>) => void;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- covariant in return type, so cannot be generic.\nexport interface BooleanMultipleHandlerFunction<TFunc extends (...args: any[]) => boolean | Promise<boolean>> {\n /**\n * Invokes the handler function with the provided arguments.\n */\n (...args: Parameters<TFunc>): ReturnType<TFunc>;\n /**\n * Adds a handler function.\n * @param callback The handler function to add.\n * @returns A function to remove the added handler.\n */\n addHandler: (callback: TFunc, priority?: number) => () => void;\n /**\n * Removes a handler function.\n * @param callback The handler function to remove.\n * @returns\n */\n removeHandler: (callback: TFunc) => void;\n}\n\nexport interface MultiBinderInstance<T extends unknown[], U>\n extends InvokableHandler<T, U>, MultiRegisterHandler<T, U> {}\nexport interface BooleanMultiBinderInstance<T extends unknown[]>\n extends InvokableBooleanHandler<T>, MultiRegisterHandler<T, boolean> {}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- covariant ...\nfunction getMultipleBound<T extends BooleanMultiBinderInstance<any[]>>(\n handler: T\n): BooleanMultipleHandlerFunction<T[\"invoke\"]>;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- covariant ...\nfunction getMultipleBound<T extends MultiBinderInstance<any[], any>>(handler: T): MultipleHandlerFunction<T[\"invoke\"]>;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- covariant ...\nfunction getMultipleBound<T extends DispatchHandler<any[], any>>(handler: T): CollectiveHandlerFunction<T[\"dispatch\"]>;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- covariant ...\nfunction getMultipleBound<T extends MultiBinderInstance<any[], any> | DispatchHandler<any[], any>>(handler: T) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const _handler = \"invoke\" in handler ? handler.invoke : handler.dispatch;\n const __handler = _handler.bind(handler);\n const func = (...args: Parameters<typeof __handler>): ReturnType<typeof __handler> => {\n return __handler(...args);\n };\n func.addHandler = handler.addHandler.bind(handler);\n func.removeHandler = handler.removeHandler.bind(handler);\n func.use = handler;\n return func as MultipleHandlerFunction<typeof __handler>;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- covariant in return type, so cannot be generic.\nexport function allFunction<TFunc extends (...args: any[]) => Promise<boolean>>(\n name?: string\n): BooleanMultipleHandlerFunction<TFunc> {\n const handler = new AllHandler<Parameters<TFunc>>(name ?? \"handleAllFunc\");\n return getMultipleBound(handler);\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- covariant in return type, so cannot be generic.\nexport function allSettledFunction<TFunc extends (...args: any[]) => Promise<boolean>>(\n name?: string\n): BooleanMultipleHandlerFunction<TFunc> {\n const handler = new SettledAllHandler<Parameters<TFunc>>(name ?? \"allSettledFunction\");\n return getMultipleBound(handler);\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- covariant in return type, so cannot be generic.\nexport function bailFirstFailureFunction<TFunc extends (...args: any[]) => Promise<boolean>>(\n name?: string\n): BooleanMultipleHandlerFunction<TFunc> {\n const handler = new AllHandler<Parameters<TFunc>>(name ?? \"bailFirstFailureFunction\");\n return getMultipleBound(handler);\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- covariant in return type, so cannot be generic.\nexport function bailFirstFailureWithResultFunction<TFunc extends (...args: any[]) => Promise<boolean | string>>(\n name?: string\n): MultipleHandlerFunction<TFunc> {\n const handler = new AllWithResultHandler<Parameters<TFunc>, Awaited<ReturnType<TFunc>>>(\n name ?? \"bailFirstFailureWithResultFunction\"\n );\n return getMultipleBound(handler) as unknown as MultipleHandlerFunction<TFunc>;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- covariant in return type, so cannot be generic.\nexport function allParallelFunction<TFunc extends (...args: any[]) => Promise<boolean>>(\n name?: string\n): BooleanMultipleHandlerFunction<TFunc> {\n const handler = new ParallelAllHandler<Parameters<TFunc>>(name ?? \"allParallelFunction\");\n return getMultipleBound(handler);\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- covariant in return type, so cannot be generic.\nexport function anySuccessFunction<TFunc extends (...args: any[]) => Promise<boolean>>(\n name?: string\n): BooleanMultipleHandlerFunction<TFunc> {\n const handler = new AnySuccessHandler<Parameters<TFunc>>(name ?? \"anySuccessFunction\");\n return getMultipleBound(handler);\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- covariant in return type, so cannot be generic.\nexport function firstResultFunction<TFunc extends (...args: any[]) => Promise<unknown>>(\n name?: string\n): MultipleHandlerFunction<TFunc> {\n const handler = new FirstResultHandler<Parameters<TFunc>, ReturnType<TFunc>>(name ?? \"firstResultFunction\");\n return getMultipleBound(handler) as MultipleHandlerFunction<TFunc>;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- covariant in return type, so cannot be generic.\nexport function dispatchParallelFunction<TFunc extends (...args: any[]) => Promise<unknown[]>>(\n name?: string\n): CollectiveHandlerFunction<TFunc> {\n const handler = new DispatchParallel<Parameters<TFunc>, Awaited<ReturnType<TFunc>>[number]>(\n name ?? \"dispatchParallelFunction\"\n );\n return getMultipleBound(handler) as CollectiveHandlerFunction<TFunc>;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- covariant in return type, so cannot be generic.\nexport function bindableFunction<TFunc extends (...args: any[]) => any>(name?: string): HandlerFunction<TFunc> {\n const handler = new Binder<TFunc>(name ?? \"bindableFunction\");\n const func = (...args: Parameters<TFunc>): ReturnType<TFunc> => {\n return handler.invoke(...args);\n };\n func.setHandler = handler.assign.bind(handler);\n return func;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- covariant in return type, so cannot be generic.\nexport function lazyBindableFunction<TFunc extends (...args: any[]) => any>(name?: string): LazyHandlerFunction<TFunc> {\n const handler = new LazyBinder<TFunc>(name ?? \"lazyBindableFunction\");\n const func = async (...args: Parameters<TFunc>): Promise<Awaited<ReturnType<TFunc>>> => {\n return await handler.invoke(...args);\n };\n func.setHandler = handler.assign.bind(handler);\n return func;\n}\n\n// === Helpers === (handlers<T> function) ===\n\ntype FunctionKeys<T> = Extract<\n {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- covariant in return type, so cannot be generic.\n [K in keyof T]: T[K] extends (...args: any[]) => any ? K : never;\n }[keyof T],\n string\n>;\n\nexport function handlers<T extends object>() {\n return {\n /**\n * Create a handler that invokes all added handler functions sequentially until one returns false.\n * @param name\n * @returns\n */\n all<K extends FunctionKeys<T>>(\n name: K\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- parameter type is covariant in return type, so cannot be generic.\n ): BooleanMultipleHandlerFunction<Extract<T[K], (...args: any[]) => Promise<boolean>>> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- covariant in return type, so cannot be generic.\n return allFunction<Extract<T[K], (...args: any[]) => Promise<boolean>>>(String(name));\n },\n /**\n * Create a handler that invokes every added handler sequentially and\n * returns true only if all of them succeed.\n * @param name\n * @returns\n */\n allSettled<K extends FunctionKeys<T>>(\n name: K\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- parameter type is covariant in return type, so cannot be generic.\n ): BooleanMultipleHandlerFunction<Extract<T[K], (...args: any[]) => Promise<boolean>>> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- covariant in return type, so cannot be generic.\n return allSettledFunction<Extract<T[K], (...args: any[]) => Promise<boolean>>>(String(name));\n },\n /**\n * Create a handler that invokes all added handler functions in parallel and returns true only if all return true.\n * @param name\n * @returns\n */\n allParallel<K extends FunctionKeys<T>>(\n name: K\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- covariant in return type, so cannot be generic.\n ): BooleanMultipleHandlerFunction<Extract<T[K], (...args: any[]) => Promise<boolean>>> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- covariant in return type, so cannot be generic.\n return allParallelFunction<Extract<T[K], (...args: any[]) => Promise<boolean>>>(String(name));\n },\n /**\n * Create a handler that invokes all added handler functions sequentially until one returns false.\n * @param name\n * @returns\n */\n bailFirstFailure<K extends FunctionKeys<T>>(\n name: K\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- parameter type is covariant in return type, so cannot be generic.\n ): BooleanMultipleHandlerFunction<Extract<T[K], (...args: any[]) => Promise<boolean>>> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- covariant in return type, so cannot be generic.\n return bailFirstFailureFunction<Extract<T[K], (...args: any[]) => Promise<boolean>>>(String(name));\n },\n /**\n * Create a handler that preserves a non-boolean continuation result, but\n * still invokes later handlers so that false results and exceptions\n * can reject the operation.\n * @param name\n * @returns\n */\n bailFirstFailureWithResult<K extends FunctionKeys<T>>(\n name: K\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- parameter type is covariant in return type, so cannot be generic.\n ): MultipleHandlerFunction<Extract<T[K], (...args: any[]) => Promise<boolean | string>>> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- covariant in return type, so cannot be generic.\n return bailFirstFailureWithResultFunction<Extract<T[K], (...args: any[]) => Promise<boolean | string>>>(\n String(name)\n );\n },\n /**\n * Create a handler that invokes all added handler functions sequentially until one returns true.\n * @param name\n * @returns\n */\n anySuccess<K extends FunctionKeys<T>>(\n name: K\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- covariant in return type, so cannot be generic.\n ): BooleanMultipleHandlerFunction<Extract<T[K], (...args: any[]) => Promise<boolean>>> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- covariant in return type, so cannot be generic.\n return anySuccessFunction<Extract<T[K], (...args: any[]) => Promise<boolean>>>(String(name));\n },\n /**\n * Create a handler that invokes all added handler functions sequentially until one returns a non-falsy value.\n * @param name\n * @returns\n */\n firstResult<K extends FunctionKeys<T>>(\n name: K\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- covariant in return type, so cannot be generic.\n ): MultipleHandlerFunction<Extract<T[K], (...args: any[]) => Promise<unknown>>> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- covariant in return type, so cannot be generic.\n return firstResultFunction<Extract<T[K], (...args: any[]) => Promise<unknown>>>(String(name));\n },\n /**\n * Create a handler that invokes all added handler functions in parallel.\n * @param name\n * @returns\n */\n dispatchParallel<K extends FunctionKeys<T>>(\n name: K\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- covariant in return type, so cannot be generic.\n ): CollectiveHandlerFunction<Extract<T[K], (...args: any[]) => Promise<unknown[]>>> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- covariant in return type, so cannot be generic.\n return dispatchParallelFunction<Extract<T[K], (...args: any[]) => Promise<unknown[]>>>(String(name));\n },\n /**\n * Create a binder handler that can assign a single handler function.\n * @param name\n * @returns\n */\n binder<K extends FunctionKeys<T>>(\n name: K\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- covariant in return type, so cannot be generic.\n ): HandlerFunction<Extract<T[K], (...args: any[]) => any>> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- covariant in return type, so cannot be generic.\n return bindableFunction<Extract<T[K], (...args: any[]) => any>>(String(name));\n },\n lazyBinder<K extends FunctionKeys<T>>(\n name: K\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- covariant in return type, so cannot be generic.\n ): LazyHandlerFunction<Extract<T[K], (...args: any[]) => any>> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- covariant in return type, so cannot be generic.\n return lazyBindableFunction<Extract<T[K], (...args: any[]) => any>>(String(name));\n },\n };\n}\n","import { EventHub } from \"octagonal-wheels/events\";\n\ndeclare global {\n interface LSEvents {\n hello: string;\n world: undefined;\n }\n}\n\n/** An event hub owned by one Commonlib service context. */\nexport type LiveSyncEventHub = EventHub<LSEvents>;\n\n/** Creates an isolated event hub for one Commonlib client or host composition. */\nexport function createLiveSyncEventHub(): LiveSyncEventHub {\n return new EventHub<LSEvents>();\n}\n","/**\n * Canonical English messages owned by Commonlib.\n *\n * Hosts may optionally translate these keys. When they do not, Commonlib uses\n * these messages so that symbolic keys are never exposed to users.\n */\nexport const commonlibEnglishMessages = {\n \"(BETA) Always overwrite with a newer file\": \"(BETA) Always overwrite with a newer file\",\n \"(Beta) Use ignore files\": \"(Beta) Use ignore files\",\n \"(Days passed, 0 to disable automatic-deletion)\": \"(Days passed, 0 to disable automatic-deletion)\",\n \"(MB) If this is set, changes to local and remote files that are larger than this will be skipped. If the file becomes smaller again, a newer one will be used.\":\n \"(MB) If this is set, changes to local and remote files that are larger than this will be skipped. If the file becomes smaller again, a newer one will be used.\",\n \"(Mega chars)\": \"(Mega chars)\",\n \"(Not recommended) If set, credentials will be stored in the file.\":\n \"(Not recommended) If set, credentials will be stored in the file.\",\n \"(Obsolete) Use an old adapter for compatibility\": \"(Obsolete) Use an old adapter for compatibility\",\n \"(ex. Read chunks online) If this option is enabled, LiveSync reads chunks online directly instead of replicating them locally. Increasing Custom chunk size is recommended.\":\n \"(ex. Read chunks online) If this option is enabled, LiveSync reads chunks online directly instead of replicating them locally. Increasing Custom chunk size is recommended.\",\n \"Access Key\": \"Access Key\",\n \"Active Remote Type\": \"Active Remote Type\",\n \"Always prompt merge conflicts\": \"Always prompt merge conflicts\",\n \"Application ID\": \"Application ID\",\n \"Apply Latest Change if Conflicting\": \"Apply Latest Change if Conflicting\",\n \"Apply preset configuration\": \"Apply preset configuration\",\n \"Auto-accept compatible tweak mismatches\": \"Auto-accept compatible tweak mismatches\",\n \"Automatically Sync all files when opening Obsidian.\": \"Automatically Sync all files when opening Obsidian.\",\n \"Automatically accepts mismatches that are compatible but potentially lossy by comparing tweak modification times.\":\n \"Automatically accepts mismatches that are compatible but potentially lossy by comparing tweak modification times.\",\n \"Automatically broadcast changes to connected peers\": \"Automatically broadcast changes to connected peers\",\n \"Automatically start P2P connection on launch\": \"Automatically start P2P connection on launch\",\n \"Batch database update\": \"Batch database update\",\n \"Batch limit\": \"Batch limit\",\n \"Batch size\": \"Batch size\",\n \"Batch size of on-demand fetching\": \"Batch size of on-demand fetching\",\n \"Before v0.17.16, we used an old adapter for the local database. Now the new adapter is preferred. However, it needs local database rebuilding. Please disable this toggle when you have enough time. If leave it enabled, also while fetching from the remote database, you will be asked to disable this.\":\n \"Before v0.17.16, we used an old adapter for the local database. Now the new adapter is preferred. However, it needs local database rebuilding. Please disable this toggle when you have enough time. If leave it enabled, also while fetching from the remote database, you will be asked to disable this.\",\n \"Bucket Name\": \"Bucket Name\",\n \"Chunk Splitter\": \"Chunk Splitter\",\n \"Chunk revisions are always derived from their content. This stored key is retained only for compatibility.\":\n \"Chunk revisions are always derived from their content. This stored key is retained only for compatibility.\",\n \"Comma separated `.gitignore, .dockerignore`\": \"Comma separated `.gitignore, .dockerignore`\",\n \"Content-derived chunk revisions (obsolete setting)\": \"Content-derived chunk revisions (obsolete setting)\",\n \"Custom Headers\": \"Custom Headers\",\n \"Custom headers for requesting the CouchDB. e.g. `x-custom-header1: value1\\n x-custom-header2: value2`\":\n \"Custom headers for requesting the CouchDB. e.g. `x-custom-header1: value1\\n x-custom-header2: value2`\",\n \"Custom headers for requesting the bucket. e.g. `x-custom-header1: value1\\n x-custom-header2: value2`\":\n \"Custom headers for requesting the bucket. e.g. `x-custom-header1: value1\\n x-custom-header2: value2`\",\n \"Data Compression\": \"Data Compression\",\n \"Database Name\": \"Database Name\",\n \"Database suffix\": \"Database suffix\",\n \"Delay conflict resolution of inactive files\": \"Delay conflict resolution of inactive files\",\n \"Delay merge conflict prompt for inactive files.\": \"Delay merge conflict prompt for inactive files.\",\n \"Delete old metadata of deleted files on start-up\": \"Delete old metadata of deleted files on start-up\",\n \"Desktop only; uses more battery and network.\": \"Desktop only; uses more battery and network.\",\n \"Device name\": \"Device name\",\n \"Disables logging, only shows notifications. Please disable if you report an issue.\":\n \"Disables logging, only shows notifications. Please disable if you report an issue.\",\n \"Display Language\": \"Display Language\",\n \"Do not check configuration mismatch before replication\": \"Do not check configuration mismatch before replication\",\n \"Do not keep metadata of deleted files.\": \"Do not keep metadata of deleted files.\",\n \"Do not split chunks in the background\": \"Do not split chunks in the background\",\n \"Do not use internal API\": \"Do not use internal API\",\n \"Doctor.Button.DismissThisVersion\": \"No, and do not ask again until the next release\",\n \"Doctor.Button.Fix\": \"Fix it\",\n \"Doctor.Button.FixButNoRebuild\": \"Fix it but no rebuild\",\n \"Doctor.Button.No\": \"No\",\n \"Doctor.Button.Skip\": \"Leave it as is\",\n \"Doctor.Button.Yes\": \"Yes\",\n \"Doctor.Dialogue.Main\":\n \"Hi! Config Doctor has been activated because of ${activateReason}!\\nAnd, unfortunately some configurations were detected as potential problems.\\nPlease be assured. Let's solve them one by one.\\n\\nTo let you know ahead of time, we will ask you about the following items.\\n\\n${issues}\\n\\nShall we get started?\",\n \"Doctor.Dialogue.MainFix\":\n \"\\n## ${name}\\n\\n| Current | Ideal |\\n|:---:|:---:|\\n| ${current} | ${ideal} |\\n\\n**Recommendation Level:** ${level}\\n\\n### Why this has been detected?\\n\\n${reason}\\n\\n${note}\\n\\nFix this to the ideal value?\",\n \"Doctor.Dialogue.Title\": \"Self-hosted LiveSync Config Doctor\",\n \"Doctor.Dialogue.TitleAlmostDone\": \"Almost done!\",\n \"Doctor.Dialogue.TitleFix\": \"Fix issue ${current}/${total}\",\n \"Doctor.Level.Must\": \"Must\",\n \"Doctor.Level.Necessary\": \"Necessary\",\n \"Doctor.Level.Optional\": \"Optional\",\n \"Doctor.Level.Recommended\": \"Recommended\",\n \"Doctor.Message.NoIssues\": \"No issues detected!\",\n \"Doctor.Message.RebuildLocalRequired\": \"Attention! A local database rebuild is required to apply this!\",\n \"Doctor.Message.RebuildRequired\": \"Attention! A rebuild is required to apply this!\",\n \"Doctor.Message.SomeSkipped\": \"We left some issues as is. Shall I ask you again on next startup?\",\n \"Doctor.RULES.E2EE_V02500.REASON\":\n \"The End-to-End Encryption has got now more robust and faster. Also because, the previous E2EE was found to be compromised in a re-conducted code review. It should be applied as soon as possible. Really apologises for your inconvenience. And, this setting is not forward compatible. All synchronised devices must be updated to v0.25.0 or higher. Rebuilds are not required and will be converted from the new transfer to the new format, However, it is recommended to rebuild whenever possible.\",\n \"Effectively a directory. Should end with `/`. e.g., `vault-name/`.\":\n \"Effectively a directory. Should end with `/`. e.g., `vault-name/`.\",\n \"Enable Developers' Debug Tools (If available).\": \"Enable Developers' Debug Tools (If available).\",\n \"Enable P2P Synchronization\": \"Enable P2P Synchronization\",\n \"Enable advanced features\": \"Enable advanced features\",\n \"Enable customization sync\": \"Enable customization sync\",\n \"Enable edge case treatment features\": \"Enable edge case treatment features\",\n \"Enable forcePathStyle\": \"Enable forcePathStyle\",\n \"Enable per-file customization sync\": \"Enable per-file customization sync\",\n \"Enable poweruser features\": \"Enable poweruser features\",\n \"Enable this if your Object Storage doesn't support CORS\":\n \"Enable this if your Object Storage doesn't support CORS\",\n \"Enable this option to automatically apply the most recent change to documents even when it conflicts\":\n \"Enable this option to automatically apply the most recent change to documents even when it conflicts\",\n \"Encrypt contents on the remote database. If you use the plugin's synchronization feature, enabling this is recommended.\":\n \"Encrypt contents on the remote database. If you use the plugin's synchronization feature, enabling this is recommended.\",\n \"Encrypt internal file Properties\": \"Encrypt internal file Properties\",\n \"Encrypt file properties (paths, times, sizes, and Chunk references) used by Hidden File Sync and Customisation Sync. This affects future writes; manually rebuild the remote database to protect existing properties. Requires E2EE V2, Property Encryption, and compatible clients on every device.\":\n \"Encrypt file properties (paths, times, sizes, and Chunk references) used by Hidden File Sync and Customisation Sync. This affects future writes; manually rebuild the remote database to protect existing properties. Requires E2EE V2, Property Encryption, and compatible clients on every device.\",\n \"Encrypting sensitive configuration items\": \"Encrypting sensitive configuration items\",\n \"Encryption passphrase. If changed, you should overwrite the server's database with the new (encrypted) files.\":\n \"Encryption passphrase. If changed, you should overwrite the server's database with the new (encrypted) files.\",\n \"End-to-End Encryption\": \"End-to-End Encryption\",\n \"End-to-End Encryption Algorithm\": \"End-to-End Encryption Algorithm\",\n \"Endpoint URL\": \"Endpoint URL\",\n \"Enhance chunk size\": \"Enhance chunk size\",\n \"Fetch chunks on demand\": \"Fetch chunks on demand\",\n \"Fetch database with previous behaviour\": \"Fetch database with previous behaviour\",\n \"File prefix on the bucket\": \"File prefix on the bucket\",\n Filename: \"Filename\",\n \"Files with modification times greater than this value (in seconds since the Unix epoch) will not have their events reflected. Set to 0 to disable this limit.\":\n \"Files with modification times greater than this value (in seconds since the Unix epoch) will not have their events reflected. Set to 0 to disable this limit.\",\n \"Forces the file to be synced when opened.\": \"Forces the file to be synced when opened.\",\n \"Handle files as Case-Sensitive\": \"Handle files as Case-Sensitive\",\n \"How to display network errors when the sync server is unreachable.\":\n \"How to display network errors when the sync server is unreachable.\",\n \"If disabled(toggled), chunks will be split on the UI thread (Previous behaviour).\":\n \"If disabled(toggled), chunks will be split on the UI thread (Previous behaviour).\",\n \"If enabled per-filed efficient customization sync will be used. We need a small migration when enabling this. And all devices should be updated to v0.23.18. Once we enabled this, we lost a compatibility with old versions.\":\n \"If enabled per-filed efficient customization sync will be used. We need a small migration when enabling this. And all devices should be updated to v0.23.18. Once we enabled this, we lost a compatibility with old versions.\",\n \"If enabled, changes will be automatically broadcasted to all connected peers. Notified peers will start fetching the changes.\":\n \"If enabled, changes will be automatically broadcasted to all connected peers. Notified peers will start fetching the changes.\",\n \"If enabled, chunks will be split into no more than 100 items. However, dedupe is slightly weaker.\":\n \"If enabled, chunks will be split into no more than 100 items. However, dedupe is slightly weaker.\",\n \"If enabled, efficient per-file customization sync will be used. A minor migration is required when enabling this feature, and all devices must be updated to v0.23.18. Enabling this feature will result in losing compatibility with older versions.\":\n \"If enabled, efficient per-file customization sync will be used. A minor migration is required when enabling this feature, and all devices must be updated to v0.23.18. Enabling this feature will result in losing compatibility with older versions.\",\n \"If enabled, newly created chunks are temporarily kept within the document, and graduated to become independent chunks once stabilised.\":\n \"If enabled, newly created chunks are temporarily kept within the document, and graduated to become independent chunks once stabilised.\",\n \"If enabled, the P2P connection will be automatically started when the application launches.\":\n \"If enabled, the P2P connection will be automatically started when the application launches.\",\n \"If enabled, the file properties will be encrypted in the remote database. This is useful for protecting sensitive information in file paths, sizes, and IDs of its chunks. If you are using V1 E2EE, this only obfuscates the file path.\":\n \"If enabled, the file properties will be encrypted in the remote database. This is useful for protecting sensitive information in file paths, sizes, and IDs of its chunks. If you are using V1 E2EE, this only obfuscates the file path.\",\n \"If enabled, the file under 1kb will be processed in the UI thread.\":\n \"If enabled, the file under 1kb will be processed in the UI thread.\",\n \"If enabled, the forcePathStyle option will be used for bucket operations.\":\n \"If enabled, the forcePathStyle option will be used for bucket operations.\",\n \"If enabled, the notification of hidden files change will be suppressed.\":\n \"If enabled, the notification of hidden files change will be suppressed.\",\n \"If enabled, the plugin will not attempt to connect to the remote database even if the chunk was not found locally.\":\n \"If enabled, the plugin will not attempt to connect to the remote database even if the chunk was not found locally.\",\n \"If enabled, the request API will be used to avoid `inevitable` CORS problems. This is a workaround and may not work in all cases. PLEASE READ THE DOCUMENTATION BEFORE USING THIS OPTION. This is a less-secure option.\":\n \"If enabled, the request API will be used to avoid `inevitable` CORS problems. This is a workaround and may not work in all cases. PLEASE READ THE DOCUMENTATION BEFORE USING THIS OPTION. This is a less-secure option.\",\n \"If enabled, the ⛔ icon will be shown inside the status instead of the file warnings banner. No details will be shown.\":\n \"If enabled, the ⛔ icon will be shown inside the status instead of the file warnings banner. No details will be shown.\",\n \"If this enabled, All files are handled as case-Sensitive (Previous behaviour).\":\n \"If this enabled, All files are handled as case-Sensitive (Previous behaviour).\",\n \"If this enabled, JWT will be used for authentication.\": \"If this enabled, JWT will be used for authentication.\",\n \"If this enabled, chunks will be split into semantically meaningful segments. Not all platforms support this feature.\":\n \"If this enabled, chunks will be split into semantically meaningful segments. Not all platforms support this feature.\",\n \"If this is set, changes to local files which are matched by the ignore files will be skipped. Remote changes are determined using local ignore files.\":\n \"If this is set, changes to local files which are matched by the ignore files will be skipped. Remote changes are determined using local ignore files.\",\n \"If this option is enabled, PouchDB will hold the connection open for 60 seconds, and if no change arrives in that time, close and reopen the socket, instead of holding it open indefinitely. Useful when a proxy limits request duration but can increase resource usage.\":\n \"If this option is enabled, PouchDB will hold the connection open for 60 seconds, and if no change arrives in that time, close and reopen the socket, instead of holding it open indefinitely. Useful when a proxy limits request duration but can increase resource usage.\",\n \"Ignore files\": \"Ignore files\",\n \"Incubate Chunks in Document\": \"Incubate Chunks in Document\",\n \"Internal timestamp for resolving compatible tweak mismatches.\":\n \"Internal timestamp for resolving compatible tweak mismatches.\",\n \"Interval (sec)\": \"Interval (sec)\",\n \"JWT Algorithm\": \"JWT Algorithm\",\n \"K.long_p2p_sync\": \"%{title_p2p_sync}\",\n \"K.title_p2p_sync\": \"Peer-to-Peer Sync\",\n \"Keep empty folder\": \"Keep empty folder\",\n \"Keep replication active in the background\": \"Keep replication active in the background\",\n \"Key ID\": \"Key ID\",\n \"Keypair or pre-shared key\": \"Keypair or pre-shared key\",\n \"Last tweak modified timestamp\": \"Last tweak modified timestamp\",\n \"LiveSync could not handle multiple vaults which have same name without different prefix, This should be automatically configured.\":\n \"LiveSync could not handle multiple vaults which have same name without different prefix, This should be automatically configured.\",\n \"Longest chunk line threshold value (Not Configurable from the UI Now).\":\n \"Longest chunk line threshold value (Not Configurable from the UI Now).\",\n \"MB (0 to disable).\": \"MB (0 to disable).\",\n \"MB per request\": \"MB per request\",\n \"Maximum Incubating Chunk Size\": \"Maximum Incubating Chunk Size\",\n \"Maximum Incubating Chunks\": \"Maximum Incubating Chunks\",\n \"Maximum Incubation Period\": \"Maximum Incubation Period\",\n \"Maximum delay for batch database updating\": \"Maximum delay for batch database updating\",\n \"Maximum file modification time for reflected file events\":\n \"Maximum file modification time for reflected file events\",\n \"Maximum file size\": \"Maximum file size\",\n \"Maximum request size for manually resending chunks\": \"Maximum request size for manually resending chunks\",\n \"Memory cache size (by total characters)\": \"Memory cache size (by total characters)\",\n \"Memory cache size (by total items)\": \"Memory cache size (by total items)\",\n \"Minimum Chunk Size (Not Configurable from the UI Now).\": \"Minimum Chunk Size (Not Configurable from the UI Now).\",\n \"Minimum delay for batch database updating\": \"Minimum delay for batch database updating\",\n \"Minimum interval for syncing\": \"Minimum interval for syncing\",\n \"Move remotely deleted files to the trash, instead of deleting. (This setting is ineffective from Obsidian v1.7.2 onwards, as deletion always respects your Obsidian preferences.)\":\n \"Move remotely deleted files to the trash, instead of deleting. (This setting is ineffective from Obsidian v1.7.2 onwards, as deletion always respects your Obsidian preferences.)\",\n \"Network warning style\": \"Network warning style\",\n 'Not all messages have been translated. And, please revert to \"Default\" when reporting errors.':\n 'Not all messages have been translated. And, please revert to \"Default\" when reporting errors.',\n \"Notify all setting files\": \"Notify all setting files\",\n \"Notify customized\": \"Notify customized\",\n \"Notify when other device has newly customized.\": \"Notify when other device has newly customized.\",\n \"Notify when the estimated remote storage size exceeds on start up\":\n \"Notify when the estimated remote storage size exceeds on start up\",\n \"Now we can choose how to split the chunks; V3 is the most efficient. If you have troubled, please make this Default or Legacy.\":\n \"Now we can choose how to split the chunks; V3 is the most efficient. If you have troubled, please make this Default or Legacy.\",\n \"Number of batches to process at a time. Defaults to 40. Minimum is 2. This along with batch size controls how many docs are kept in memory at a time.\":\n \"Number of batches to process at a time. Defaults to 40. Minimum is 2. This along with batch size controls how many docs are kept in memory at a time.\",\n \"Number of changes to sync at a time. Defaults to 50. Minimum is 2.\":\n \"Number of changes to sync at a time. Defaults to 50. Minimum is 2.\",\n \"P2P.AskPassphraseForDecrypt\":\n \"The remote peer shared the configuration. Please input the passphrase to decrypt the configuration.\",\n \"P2P.AskPassphraseForShare\":\n \"The remote peer requested this device configuration. Please input the passphrase to share the configuration. You can ignore the request by cancelling this dialogue.\",\n \"P2P.DisabledButNeed\": \"%{title_p2p_sync} is disabled. Do you really want to enable it?\",\n \"P2P.NoAutoSyncPeers\": \"No auto-sync peers found. Please set peers on the %{long_p2p_sync} pane.\",\n \"P2P.NoKnownPeers\": \"No peers has been detected, waiting incoming other peers...\",\n \"P2P.NotEnabled\": \"%{title_p2p_sync} is not enabled. We cannot open a new connection.\",\n \"P2P.ReplicatorInstanceMissing\": \"P2P Sync replicator is not found, possibly not have been configured or enabled.\",\n \"P2P.SeemsOffline\": \"Peer ${name} seems offline, skipped.\",\n \"P2P.SyncAlreadyRunning\": \"P2P Sync is already running.\",\n \"P2P.SyncCompleted\": \"P2P Sync completed.\",\n \"P2P.SyncStartedWith\": \"P2P Sync with ${name} have been started.\",\n Passphrase: \"Passphrase\",\n \"Passphrase of sensitive configuration items\": \"Passphrase of sensitive configuration items\",\n Password: \"Password\",\n \"Per-file-saved customization sync\": \"Per-file-saved customization sync\",\n \"Periodic Sync interval\": \"Periodic Sync interval\",\n \"Please select 'Cancel' explicitly to cancel this operation.\":\n \"Please select 'Cancel' explicitly to cancel this operation.\",\n \"Please use V2, V1 is deprecated and will be removed in the future, It was not a very appropriate algorithm. Only for compatibility V1 is kept.\":\n \"Please use V2, V1 is deprecated and will be removed in the future, It was not a very appropriate algorithm. Only for compatibility V1 is kept.\",\n Presets: \"Presets\",\n \"Process files even if seems to be corrupted\": \"Process files even if seems to be corrupted\",\n \"Process small files in the foreground\": \"Process small files in the foreground\",\n \"Property Encryption\": \"Property Encryption\",\n \"Reducing the frequency with which on-disk changes are reflected into the DB\":\n \"Reducing the frequency with which on-disk changes are reflected into the DB\",\n Region: \"Region\",\n \"Remote server type\": \"Remote server type\",\n \"Replicator.Message.Cleaned\": \"Database cleaning up is in process. replication has been cancelled\",\n \"Replicator.Message.InitialiseFatalError\": \"No replicator is available, this is the fatal error.\",\n \"Replicator.Message.Pending\": \"Some file events are pending. Replication has been cancelled.\",\n \"Replicator.Message.SomeModuleFailed\": \"Replication has been cancelled by some module failure\",\n \"Replicator.Message.VersionUpFlash\":\n \"An update has been detected. Please open the Settings dialogue and check the Change Log. Replication has been cancelled.\",\n \"Requires restart of Obsidian.\": \"Requires restart of Obsidian.\",\n \"Room ID\": \"Room ID\",\n \"Rotation Duration\": \"Rotation Duration\",\n \"Save settings to a markdown file. You will be notified when new settings arrive. You can set different files by the platform.\":\n \"Save settings to a markdown file. You will be notified when new settings arrive. You can set different files by the platform.\",\n \"Saving will be performed forcefully after this number of seconds.\":\n \"Saving will be performed forcefully after this number of seconds.\",\n \"Scan changes on customization sync\": \"Scan changes on customization sync\",\n \"Scan customization automatically\": \"Scan customization automatically\",\n \"Scan customization before replicating.\": \"Scan customization before replicating.\",\n \"Scan customization every 1 minute.\": \"Scan customization every 1 minute.\",\n \"Scan customization periodically\": \"Scan customization periodically\",\n \"Scan for hidden files before replication\": \"Scan for hidden files before replication\",\n \"Scan hidden files periodically\": \"Scan hidden files periodically\",\n \"Seconds, 0 to disable\": \"Seconds, 0 to disable\",\n \"Seconds. Saving to the local database will be delayed until this value after we stop typing or saving.\":\n \"Seconds. Saving to the local database will be delayed until this value after we stop typing or saving.\",\n \"Secret Key\": \"Secret Key\",\n \"Server URI\": \"Server URI\",\n \"Setup.QRCode\":\n 'We have generated a QR code to transfer the settings. Please scan the QR code with your phone or other device.\\nNote: The QR code is not encrypted, so be careful to open this.\\n\\n>[!FOR YOUR EYES ONLY]-\\n> <div class=\"sls-qr\">${qr_image}</div>',\n \"Should we keep folders that don't have any files inside?\":\n \"Should we keep folders that don't have any files inside?\",\n \"Should we only check for conflicts when a file is opened?\":\n \"Should we only check for conflicts when a file is opened?\",\n \"Should we prompt you about conflicting files when a file is opened?\":\n \"Should we prompt you about conflicting files when a file is opened?\",\n \"Should we prompt you for every single merge, even if we can safely merge automatcially?\":\n \"Should we prompt you for every single merge, even if we can safely merge automatcially?\",\n \"Show only notifications\": \"Show only notifications\",\n \"Show status as icons only\": \"Show status as icons only\",\n \"Show status icon instead of file warnings banner\": \"Show status icon instead of file warnings banner\",\n \"Show status inside the editor\": \"Show status inside the editor\",\n \"Show status on the status bar\": \"Show status on the status bar\",\n \"Show verbose log. Please enable if you report an issue.\":\n \"Show verbose log. Please enable if you report an issue.\",\n \"Signalling Relays\": \"Signalling Relays\",\n \"Starts synchronisation when a file is saved.\": \"Starts synchronisation when a file is saved.\",\n \"Stop reflecting database changes to storage files.\": \"Stop reflecting database changes to storage files.\",\n \"Stop watching for file changes.\": \"Stop watching for file changes.\",\n \"Subject (whoami)\": \"Subject (whoami)\",\n \"Suppress notification of hidden files change\": \"Suppress notification of hidden files change\",\n \"Suspend database reflecting\": \"Suspend database reflecting\",\n \"Suspend file watching\": \"Suspend file watching\",\n \"Sync Mode\": \"Sync Mode\",\n \"Sync after merging file\": \"Sync after merging file\",\n \"Sync automatically after merging files\": \"Sync automatically after merging files\",\n \"Sync on Editor Save\": \"Sync on Editor Save\",\n \"Sync on File Open\": \"Sync on File Open\",\n \"Sync on Save\": \"Sync on Save\",\n \"Sync on Startup\": \"Sync on Startup\",\n \"TURN Credential\": \"TURN Credential\",\n \"TURN Servers\": \"TURN Servers\",\n \"TURN Username\": \"TURN Username\",\n \"Testing only - Resolve file conflicts by syncing newer copies of the file, this can overwrite modified files. Be Warned.\":\n \"Testing only - Resolve file conflicts by syncing newer copies of the file, this can overwrite modified files. Be Warned.\",\n \"The Application ID for P2P connection. This should be same among your devices. Default is 'self-hosted-livesync' and could not be modified from the UI.\":\n \"The Application ID for P2P connection. This should be same among your devices. Default is 'self-hosted-livesync' and could not be modified from the UI.\",\n \"The Hash algorithm for chunk IDs\": \"The Hash algorithm for chunk IDs\",\n \"The Nostr relay servers to establish connections for P2P connections. Multiple servers can be separated by commas.\":\n \"The Nostr relay servers to establish connections for P2P connections. Multiple servers can be separated by commas.\",\n \"The Passphrase for P2P connection. This should be same among your devices.\":\n \"The Passphrase for P2P connection. This should be same among your devices.\",\n \"The Room ID for P2P connection. This should be same among your devices.\":\n \"The Room ID for P2P connection. This should be same among your devices.\",\n \"The Rotation duration of token in minutes. Each generated tokens will be valid only within this duration.\":\n \"The Rotation duration of token in minutes. Each generated tokens will be valid only within this duration.\",\n \"The TURN servers to use for P2P connections. Multiple servers can be separated by commas.\":\n \"The TURN servers to use for P2P connections. Multiple servers can be separated by commas.\",\n \"The algorithm used for JWT authentication.\": \"The algorithm used for JWT authentication.\",\n \"The credential/password for the TURN servers.\": \"The credential/password for the TURN servers.\",\n \"The delay for consecutive on-demand fetches\": \"The delay for consecutive on-demand fetches\",\n \"The key (PSK in HSxxx in base64, or private key in ESxxx in PEM) used for JWT authentication.\":\n \"The key (PSK in HSxxx in base64, or private key in ESxxx in PEM) used for JWT authentication.\",\n \"The key ID. this should be matched with CouchDB->jwt_keys->ALG:_`kid`.\":\n \"The key ID. this should be matched with CouchDB->jwt_keys->ALG:_`kid`.\",\n \"The maximum duration for which chunks can be incubated within the document. Chunks exceeding this period will graduate to independent chunks.\":\n \"The maximum duration for which chunks can be incubated within the document. Chunks exceeding this period will graduate to independent chunks.\",\n \"The maximum number of chunks that can be incubated within the document. Chunks exceeding this number will immediately graduate to independent chunks.\":\n \"The maximum number of chunks that can be incubated within the document. Chunks exceeding this number will immediately graduate to independent chunks.\",\n \"The maximum total size of chunks that can be incubated within the document. Chunks exceeding this size will immediately graduate to independent chunks.\":\n \"The maximum total size of chunks that can be incubated within the document. Chunks exceeding this size will immediately graduate to independent chunks.\",\n \"The minimum interval for automatic synchronisation on event.\":\n \"The minimum interval for automatic synchronisation on event.\",\n \"The subject for JWT authentication. Mostly username.\": \"The subject for JWT authentication. Mostly username.\",\n \"The username for the TURN servers.\": \"The username for the TURN servers.\",\n \"This passphrase will not be copied to another device. It will be set to `Default` until you configure it again.\":\n \"This passphrase will not be copied to another device. It will be set to `Default` until you configure it again.\",\n \"Unique name between all synchronized devices. To edit this setting, please disable customization sync once.\":\n \"Unique name between all synchronized devices. To edit this setting, please disable customization sync once.\",\n \"Use Custom HTTP Handler\": \"Use Custom HTTP Handler\",\n \"Use JWT instead of Basic Authentication\": \"Use JWT instead of Basic Authentication\",\n \"Use Only Local Chunks\": \"Use Only Local Chunks\",\n \"Use Request API to avoid `inevitable` CORS problem\": \"Use Request API to avoid `inevitable` CORS problem\",\n \"Use Segmented-splitter\": \"Use Segmented-splitter\",\n \"Use dynamic iteration count\": \"Use dynamic iteration count\",\n \"Use splitting-limit-capped chunk splitter\": \"Use splitting-limit-capped chunk splitter\",\n \"Use the trash bin\": \"Use the trash bin\",\n \"Use timeouts instead of heartbeats\": \"Use timeouts instead of heartbeats\",\n Username: \"Username\",\n \"Verbose Log\": \"Verbose Log\",\n \"Warning! This will have a serious impact on performance. And the logs will not be synchronised under the default name. Please be careful with logs; they often contain your confidential information.\":\n \"Warning! This will have a serious impact on performance. And the logs will not be synchronised under the default name. Please be careful with logs; they often contain your confidential information.\",\n \"When you save a file in the editor, start a sync automatically\":\n \"When you save a file in the editor, start a sync automatically\",\n \"While enabled, it causes very performance impact but debugging replication testing and other features will be enabled. Please disable this if you have not read the source code. Requires restart of Obsidian. Sometimes there is no implementation.\":\n \"While enabled, it causes very performance impact but debugging replication testing and other features will be enabled. Please disable this if you have not read the source code. Requires restart of Obsidian. Sometimes there is no implementation.\",\n \"Write credentials in the file\": \"Write credentials in the file\",\n \"Write logs into the file\": \"Write logs into the file\",\n \"You can enable this setting to process the files with size mismatches, these files can be created by some APIs or integrations.\":\n \"You can enable this setting to process the files with size mismatches, these files can be created by some APIs or integrations.\",\n \"liveSyncReplicator.beforeLiveSync\": \"Before LiveSync, start OneShot once...\",\n \"liveSyncReplicator.cantReplicateLowerValue\": \"We can't replicate more lower value.\",\n \"liveSyncReplicator.checkingLastSyncPoint\": \"Looking for the point last synchronized point.\",\n \"liveSyncReplicator.couldNotConnectTo\": \"Could not connect to ${uri} : ${name}\\n(${db})\",\n \"liveSyncReplicator.couldNotConnectToRemoteDb\": \"Could not connect to remote database: ${d}\",\n \"liveSyncReplicator.couldNotConnectToServer\": \"The connection to the remote has been prevented, or failed.\",\n \"liveSyncReplicator.couldNotConnectToURI\": \"Could not connect to ${uri}:${dbRet}\",\n \"liveSyncReplicator.couldNotMarkResolveRemoteDb\": \"Could not mark resolve remote database.\",\n \"liveSyncReplicator.liveSyncBegin\": \"LiveSync begin...\",\n \"liveSyncReplicator.lockRemoteDb\": \"Lock remote database to prevent data corruption\",\n \"liveSyncReplicator.markDeviceResolved\": \"Mark this device as 'resolved'.\",\n \"liveSyncReplicator.mismatchedTweakDetected\":\n \"Some mismatches have been detected in the configuration between devices. Running a manual replication will attempt to resolve this issue.\",\n \"liveSyncReplicator.oneShotSyncBegin\": \"OneShot Sync begin... (${syncMode})\",\n \"liveSyncReplicator.remoteDbCorrupted\":\n \"Remote database is newer or corrupted, make sure to latest version of self-hosted-livesync installed\",\n \"liveSyncReplicator.remoteDbCreatedOrConnected\": \"Remote Database Created or Connected\",\n \"liveSyncReplicator.remoteDbDestroyError\": \"Something happened on Remote Database Destroy:\",\n \"liveSyncReplicator.remoteDbDestroyed\": \"Remote Database Destroyed\",\n \"liveSyncReplicator.remoteDbMarkedResolved\": \"Remote database has been marked resolved.\",\n \"liveSyncReplicator.replicationClosed\": \"Replication closed\",\n \"liveSyncReplicator.replicationInProgress\": \"Replication is already in progress\",\n \"liveSyncReplicator.retryLowerBatchSize\": \"Retry with lower batch size:${batch_size}/${batches_limit}\",\n \"liveSyncReplicator.unlockRemoteDb\": \"Unlock remote database to prevent data corruption\",\n \"moduleCheckRemoteSize.logCheckingStorageSizes\": \"Checking storage sizes\",\n \"moduleCheckRemoteSize.logCurrentStorageSize\": \"Remote storage size: ${measuredSize}\",\n \"moduleCheckRemoteSize.logExceededWarning\": \"Remote storage size: ${measuredSize} exceeded ${notifySize}\",\n \"moduleCheckRemoteSize.logThresholdEnlarged\": \"Threshold has been enlarged to ${size}MB\",\n \"moduleCheckRemoteSize.msgConfirmRebuild\":\n \"This may take a bit of a long time. Do you really want to rebuild everything now?\",\n \"moduleCheckRemoteSize.msgDatabaseGrowing\":\n \"**Your database is getting larger!** But do not worry, we can address it now. The time before running out of space on the remote storage.\\n\\n| Measured size | Configured size |\\n| --- | --- |\\n| ${estimatedSize} | ${maxSize} |\\n\\n> [!MORE]-\\n> If you have been using it for many years, there may be unreferenced chunks - that is, garbage - accumulating in the database. Therefore, we recommend rebuilding everything. It will probably become much smaller.\\n>\\n> If the volume of your vault is simply increasing, it is better to rebuild everything after organizing the files. Self-hosted LiveSync does not delete the actual data even if you delete it to speed up the process. It is roughly [documented](https://github.com/vrtmrz/obsidian-livesync/blob/main/docs/tech_info.md).\\n>\\n> If you don't mind the increase, you can increase the notification limit by 100MB. This is the case if you are running it on your own server. However, it is better to rebuild everything from time to time.\\n>\\n\\n> [!WARNING]\\n> If you perform rebuild everything, make sure all devices are synchronised. The plug-in will merge as much as possible, though.\\n\",\n \"moduleCheckRemoteSize.msgSetDBCapacity\":\n \"We can set a maximum database capacity warning, **to take action before running out of space on the remote storage**.\\nDo you want to enable this?\\n\\n> [!MORE]-\\n> - 0: Do not warn about storage size.\\n> This is recommended if you have enough space on the remote storage especially you have self-hosted. And you can check the storage size and rebuild manually.\\n> - 800: Warn if the remote storage size exceeds 800MB.\\n> This is recommended if you are using fly.io with 1GB limit or IBM Cloudant.\\n> - 2000: Warn if the remote storage size exceeds 2GB.\\n\\nIf we have reached the limit, we will be asked to enlarge the limit step by step.\\n\",\n \"moduleCheckRemoteSize.noticeExceeded\":\n \"Remote storage size is ${measuredSize}, above the configured ${notifySize} notification threshold. {HERE}\",\n \"moduleCheckRemoteSize.noticeNotConfigured\": \"Remote storage size notifications are not configured. {HERE}\",\n \"moduleCheckRemoteSize.option2GB\": \"2GB (Standard)\",\n \"moduleCheckRemoteSize.option800MB\": \"800MB (Cloudant, fly.io)\",\n \"moduleCheckRemoteSize.optionAskMeLater\": \"Ask me later\",\n \"moduleCheckRemoteSize.optionDismiss\": \"Dismiss\",\n \"moduleCheckRemoteSize.optionIncreaseLimit\": \"increase to ${newMax}MB\",\n \"moduleCheckRemoteSize.optionNoWarn\": \"No, never warn please\",\n \"moduleCheckRemoteSize.optionRebuildAll\": \"Rebuild Everything Now\",\n \"moduleCheckRemoteSize.optionReview\": \"Review options\",\n \"moduleCheckRemoteSize.titleDatabaseSizeLimitExceeded\": \"Remote storage size exceeded the limit\",\n \"moduleCheckRemoteSize.titleDatabaseSizeNotify\": \"Setting up database size notification\",\n \"moduleLiveSyncMain.logUnloadingPlugin\": \"Unloading plugin...\",\n \"moduleLocalDatabase.logWaitingForReady\": \"Waiting for ready...\",\n password: \"password\",\n username: \"username\",\n \"xxhash64 is the current default.\": \"xxhash64 is the current default.\",\n} as const;\n\n/** Message keys which Commonlib may request from a host translator. */\nexport type CommonlibMessageKey = keyof typeof commonlibEnglishMessages;\n","import { commonlibEnglishMessages, type CommonlibMessageKey } from \"@lib/services/base/CommonlibMessages\";\n\n/** Placeholder values substituted by a host translator. */\nexport type TranslationParameters = Readonly<Record<string, string>>;\n\n/** A message translator supplied by the host for one service context. */\nexport type MessageTranslator<TKey extends string = CommonlibMessageKey> = (\n key: TKey,\n params?: TranslationParameters\n) => string;\n\nfunction resolveEnglishMessage(key: string, seen = new Set<string>()): string {\n if (seen.has(key)) return key;\n seen.add(key);\n const message = commonlibEnglishMessages[key as CommonlibMessageKey] ?? key;\n return message.replace(/%\\{([^}]+)\\}/g, (_token, referencedKey: string) => {\n const directKey = referencedKey as CommonlibMessageKey;\n const keywordKey = `K.${referencedKey}` as CommonlibMessageKey;\n if (directKey in commonlibEnglishMessages) return resolveEnglishMessage(directKey, new Set(seen));\n if (keywordKey in commonlibEnglishMessages) return resolveEnglishMessage(keywordKey, new Set(seen));\n return `%{${referencedKey}}`;\n });\n}\n\n/** Default translator which renders Commonlib's canonical English messages. */\nexport const englishMessageTranslator: MessageTranslator = (key, params = {}) => {\n let message = resolveEnglishMessage(key);\n for (const [placeholder, value] of Object.entries(params)) {\n message = message.replaceAll(`\\${${placeholder}}`, value);\n }\n return message;\n};\n\n/** Compatibility translator for hosts which intentionally render raw message keys. */\nexport const passthroughMessageTranslator: MessageTranslator = (key) => key;\n","import { createLiveSyncEventHub, type LiveSyncEventHub } from \"@lib/hub/hub\";\nimport { englishMessageTranslator, type MessageTranslator } from \"@lib/services/base/MessageTranslator\";\n\n/** Capabilities shared by services which belong to one Commonlib client. */\nexport interface ServiceContextOptions {\n /** An isolated event channel. A new channel is created when omitted. */\n events?: LiveSyncEventHub;\n /** Optional host-provided translation. Canonical English is used when omitted. */\n translate?: MessageTranslator;\n}\n\n/**\n * Minimum host-owned capabilities required by Commonlib service composition.\n *\n * Hosts may extend this contract with platform-specific capabilities, but the\n * event channel and translator remain instance-selected and must be passed\n * unchanged to every service in one composition.\n */\nexport interface ServiceContextContract {\n readonly events: LiveSyncEventHub;\n readonly translate: MessageTranslator;\n}\n\n/** Instance-owned capabilities shared by a composed set of Commonlib services. */\nexport class ServiceContext implements ServiceContextContract {\n readonly events: LiveSyncEventHub;\n readonly translate: MessageTranslator;\n\n constructor(options: ServiceContextOptions = {}) {\n this.events = options.events ?? createLiveSyncEventHub();\n this.translate = options.translate ?? englishMessageTranslator;\n }\n}\n\n/** Creates a service context without requiring a subclass. */\nexport function createServiceContext(options: ServiceContextOptions = {}): ServiceContext {\n return new ServiceContext(options);\n}\n\nexport abstract class ServiceBase<T extends ServiceContext> {\n /** Context shared by the services which belong to this composition. */\n readonly context: T;\n constructor(context: T) {\n this.context = context;\n }\n}\n","import { EVENT_APPLICATION_READY } from \"@lib/events/coreEvents\";\nimport { handlers } from \"@lib/services/lib/HandlerUtils\";\nimport type { IAppLifecycleService, ISettingService } from \"./IService\";\nimport { ServiceBase, type ServiceContext } from \"./ServiceBase\";\n\nexport interface AppLifecycleServiceDependencies {\n settingService: ISettingService;\n}\n/**\n * The AppLifecycleService provides methods for managing the plug-in's lifecycle events.\n */\nexport abstract class AppLifecycleService<T extends ServiceContext = ServiceContext>\n extends ServiceBase<T>\n implements IAppLifecycleService\n{\n protected readonly settingService: ISettingService;\n\n constructor(context: T, dependencies: AppLifecycleServiceDependencies) {\n super(context);\n this.settingService = dependencies.settingService;\n }\n\n /**\n * Event triggered when the plug-in's layout is ready.\n * In Obsidian, it is after the workspace is ready.\n */\n readonly onLayoutReady = handlers<IAppLifecycleService>().bailFirstFailure(\"onLayoutReady\");\n\n /**\n * Event triggered when the plug-in is being initialized for the first time.\n * This is only called once per plug-in lifecycle.\n */\n readonly onFirstInitialise = handlers<IAppLifecycleService>().bailFirstFailure(\"onFirstInitialise\");\n\n /**\n * Event triggered when the plug-in is fully ready.\n * This is called after all initialisation processes are complete.\n */\n readonly onReady = handlers<IAppLifecycleService>().bailFirstFailure(\"onReady\");\n\n /**\n * Event triggered to wire up necessary event listeners.\n * This is typically called during the initialisation phase.\n */\n readonly onWireUpEvents = handlers<IAppLifecycleService>().bailFirstFailure(\"onWireUpEvents\");\n\n /**\n * Event triggered when the plug-in is being initialised.\n */\n readonly onInitialise = handlers<IAppLifecycleService>().bailFirstFailure(\"onInitialise\");\n\n /**\n * Event triggered when the plug-in is loading.\n * This is typically called during the quite early initialisation phase, before everything.\n * In Obsidian, it is in the onload() method of the plugin.\n */\n readonly onLoad = handlers<IAppLifecycleService>().bailFirstFailure(\"onLoad\");\n\n /**\n * Event triggered when the plug-in's settings have been loaded and applied.\n */\n readonly onSettingLoaded = handlers<IAppLifecycleService>().bailFirstFailure(\"onSettingLoaded\");\n\n /**\n * Event triggered when the plug-in has fully loaded.\n * This is typically called after all initialisation and loading processes are complete.\n */\n readonly onLoaded = handlers<IAppLifecycleService>().bailFirstFailure(\"onLoaded\");\n\n /**\n * Scan for any startup issues that may affect the plug-in's operation.\n */\n readonly onScanningStartupIssues = handlers<IAppLifecycleService>().all(\"onScanningStartupIssues\");\n\n /**\n * Event triggered when the plug-in is unloading (e.g., during app shutdown or plug-in disable).\n * This is typically called during the unload() method of the plugin.\n * Entry point to unload everything.\n */\n readonly onAppUnload = handlers<IAppLifecycleService>().dispatchParallel(\"onAppUnload\");\n /**\n * Event triggered before the plug-in is unloaded.\n * This is typically used to perform any necessary cleanup or save state before the plug-in is unloaded.\n */\n readonly onBeforeUnload = handlers<IAppLifecycleService>().all(\"onBeforeUnload\");\n\n /**\n * Event triggered when the plug-in is being unloaded.\n *\n * Resource owners complete terminal retirement here. `ControlService`\n * awaits every handler before it closes the local database.\n */\n readonly onUnload = handlers<IAppLifecycleService>().all(\"onUnload\");\n /**\n * Perform an immediate restart of the application.\n * Note that this is not graceful, and not only the plug-in. APPLICATION (means Obsidian) will be restarted.\n */\n abstract performRestart(): void;\n\n /**\n * Ask the user for a restart.\n * @param message Optional message to display to the user when asking for a restart.\n */\n abstract askRestart(message?: string): void;\n\n /**\n * Schedule a restart of the application.\n * After the current operation is done, the application will be restarted.\n * Note that this is not graceful, and not only the plug-in. APPLICATION (means Obsidian) will be restarted.\n */\n abstract scheduleRestart(): void;\n\n /**\n * Event triggered when the application is being suspended (e.g., system sleep).\n * Suspension is reversible and is not equivalent to terminal unload.\n */\n readonly onSuspending = handlers<IAppLifecycleService>().bailFirstFailure(\"onSuspending\");\n\n /**\n * Event triggered when the application is resuming from a suspended state.\n */\n readonly onResuming = handlers<IAppLifecycleService>().bailFirstFailure(\"onResuming\");\n\n /**\n * Event triggered after the application has resumed from a suspended state.\n */\n readonly onResumed = handlers<IAppLifecycleService>().bailFirstFailure(\"onResumed\");\n\n private _isSuspended = false;\n\n /**\n * Check if the plug-in is currently suspended.\n * Also consider the plug-in as suspended if it is not configured, to prevent any issues before configuration.\n */\n isSuspended(): boolean {\n const settings = this.settingService.currentSettings();\n return this._isSuspended || !settings?.isConfigured;\n }\n\n /**\n * Set the suspension state of the plug-in.\n * @param suspend Set to true to suspend the plug-in, false to resume.\n */\n setSuspended(suspend: boolean): void {\n this._isSuspended = suspend;\n }\n\n private _isReady = false;\n /**\n * Check if the plug-in is ready.\n * A ready plug-in means it has been fully initialised and is operational.\n * If not ready, most operations will be blocked.\n */\n isReady(): boolean {\n return this._isReady;\n }\n\n /**\n * Mark the plug-in as ready.\n * Establishing readiness emits `EVENT_APPLICATION_READY` on the context's event channel, so a host can\n * continue work it held while the plug-in was not ready. Marking a plug-in which is already ready emits nothing.\n */\n markIsReady(): void {\n if (this._isReady) return;\n this._isReady = true;\n this.context.events.emitEvent(EVENT_APPLICATION_READY);\n }\n\n /**\n * Reset the ready state of the plug-in.\n */\n resetIsReady(): void {\n this._isReady = false;\n }\n\n /**\n * Check if a restart has been scheduled.\n */\n abstract isReloadingScheduled(): boolean;\n\n /**\n * Get unresolved error messages.\n */\n readonly getUnresolvedMessages = handlers<IAppLifecycleService>().dispatchParallel(\"getUnresolvedMessages\");\n}\n","import { AppLifecycleService } from \"@lib/services/base/AppLifecycleService\";\nimport type { IAppLifecycleService } from \"@lib/services/base/IService\";\nimport type { ServiceContext } from \"@lib/services/base/ServiceBase\";\nimport { handlers } from \"@lib/services/lib/HandlerUtils\";\n\nexport abstract class AppLifecycleServiceBase<T extends ServiceContext> extends AppLifecycleService<T> {\n askRestart = handlers<IAppLifecycleService>().binder(\"askRestart\");\n scheduleRestart = handlers<IAppLifecycleService>().binder(\"scheduleRestart\");\n isReloadingScheduled = handlers<IAppLifecycleService>().binder(\"isReloadingScheduled\");\n}\n\nexport abstract class InjectableAppLifecycleService<T extends ServiceContext = ServiceContext>\n extends AppLifecycleServiceBase<T>\n implements IAppLifecycleService\n{\n performRestart = handlers<IAppLifecycleService>().binder(\"performRestart\");\n}\n","import type { FilePathWithPrefix, MISSING_OR_ERROR, AUTO_MERGED } from \"@lib/common/types\";\nimport { handlers } from \"@lib/services/lib/HandlerUtils\";\nimport type { IConflictService } from \"@lib/services/base/IService\";\nimport { ServiceBase } from \"@lib/services/base/ServiceBase\";\nimport type { ServiceContext } from \"@lib/services/base/ServiceBase\";\nimport { reactiveSource } from \"octagonal-wheels/dataobject/reactive\";\n\n/**\n * The ConflictService provides methods for handling file conflicts.\n */\nexport abstract class ConflictService<T extends ServiceContext = ServiceContext>\n extends ServiceBase<T>\n implements IConflictService\n{\n /**\n * Get an optional conflict check method for a given file (virtual) path.\n */\n readonly getOptionalConflictCheckMethod = handlers<IConflictService>().firstResult(\n \"getOptionalConflictCheckMethod\"\n );\n /**\n * Queue a check for conflicts if the file is currently open in the editor.\n * @param path The file (virtual) path to check for conflicts.\n */\n abstract queueCheckForIfOpen(path: FilePathWithPrefix): Promise<void>;\n\n /**\n * Queue a check for conflicts for a given file (virtual) path.\n * @param path The file (virtual) path to check for conflicts.\n */\n abstract queueCheckFor(path: FilePathWithPrefix): Promise<void>;\n\n /**\n * Ensure all queued file conflict checks are processed.\n */\n abstract ensureAllProcessed(): Promise<boolean>;\n\n /**\n * Resolve a conflict by user interaction (e.g., showing a modal dialog).\n * @param filename The file (virtual) path with conflict.\n * @param conflictCheckResult The result of the conflict check.\n * @returns A promise that resolves to true if the conflict was resolved, false if not, or undefined if no action was taken.\n */\n readonly resolveByUserInteraction = handlers<IConflictService>().firstResult(\"resolveByUserInteraction\");\n\n /**\n * Resolve a conflict by deleting a specific revision.\n * @param path The file (virtual) path with conflict.\n * @param deleteRevision The revision to delete.\n * @param title The title of the conflict (for user display).\n */\n abstract resolveByDeletingRevision(\n path: FilePathWithPrefix,\n deleteRevision: string,\n title: string\n ): Promise<typeof MISSING_OR_ERROR | typeof AUTO_MERGED>;\n\n /**\n * Resolve a conflict as several possible strategies.\n * It may involve user interaction (means raising resolveByUserInteraction).\n * @param filename The file (virtual) path to resolve.\n */\n abstract resolve(filename: FilePathWithPrefix): Promise<void>;\n\n /**\n * Resolve a conflict by choosing the newest version.\n * @param filename The file (virtual) path to resolve.\n */\n abstract resolveByNewest(filename: FilePathWithPrefix): Promise<boolean>;\n\n abstract resolveAllConflictedFilesByNewerOnes(): Promise<void>;\n conflictProcessQueueCount = reactiveSource(0);\n}\n","import { ConflictService } from \"@lib/services/base/ConflictService\";\nimport type { IConflictService } from \"@lib/services/base/IService\";\nimport type { ServiceContext } from \"@lib/services/base/ServiceBase\";\nimport { handlers } from \"@lib/services/lib/HandlerUtils\";\n\nexport class InjectableConflictService<T extends ServiceContext> extends ConflictService<T> {\n queueCheckForIfOpen = handlers<IConflictService>().binder(\"queueCheckForIfOpen\");\n queueCheckFor = handlers<IConflictService>().binder(\"queueCheckFor\");\n ensureAllProcessed = handlers<IConflictService>().binder(\"ensureAllProcessed\");\n resolveByDeletingRevision = handlers<IConflictService>().binder(\"resolveByDeletingRevision\");\n resolve = handlers<IConflictService>().binder(\"resolve\");\n resolveByNewest = handlers<IConflictService>().binder(\"resolveByNewest\");\n resolveAllConflictedFilesByNewerOnes = handlers<IConflictService>().binder(\"resolveAllConflictedFilesByNewerOnes\");\n}\n","import { handlers } from \"@lib/services/lib/HandlerUtils\";\nimport type { IDatabaseEventService } from \"./IService\";\nimport { ServiceBase, type ServiceContext } from \"./ServiceBase\";\n\n/**\n * The DatabaseEventService provides methods for handling database lifecycle events.\n */\nexport abstract class DatabaseEventService<T extends ServiceContext = ServiceContext>\n extends ServiceBase<T>\n implements IDatabaseEventService\n{\n /**\n * Event triggered when the database is about to be unloaded.\n */\n readonly onUnloadDatabase = handlers<IDatabaseEventService>().all(\"onUnloadDatabase\");\n\n /**\n * Event triggered when the database is about to be closed.\n */\n readonly onCloseDatabase = handlers<IDatabaseEventService>().allSettled(\"onCloseDatabase\");\n\n /**\n * Event triggered when the database is being initialized.\n */\n readonly onDatabaseInitialisation = handlers<IDatabaseEventService>().bailFirstFailure(\"onDatabaseInitialisation\");\n\n /**\n * Event triggered when the database has been initialized.\n */\n readonly onDatabaseInitialised = handlers<IDatabaseEventService>().bailFirstFailure(\"onDatabaseInitialised\");\n\n /**\n * Event triggered when the database is being reset.\n */\n readonly onResetDatabase = handlers<IDatabaseEventService>().bailFirstFailure(\"onResetDatabase\");\n\n /**\n * Event triggered when the database is ready for use.\n */\n readonly onDatabaseHasReady = handlers<IDatabaseEventService>().bailFirstFailure(\"onDatabaseHasReady\");\n /**\n * Initialize the database.\n * @param showingNotice Whether to show a notice to the user.\n * @param reopenDatabase Whether to reopen the database if it is already open.\n * @param ignoreSuspending Whether to ignore any suspending state.\n */\n readonly initialiseDatabase = handlers<IDatabaseEventService>().bailFirstFailureWithResult(\"initialiseDatabase\");\n}\n","import { DatabaseEventService } from \"@lib/services/base/DatabaseEventService\";\nimport type { ServiceContext } from \"@lib/services/base/ServiceBase\";\n\nexport class InjectableDatabaseEventService<T extends ServiceContext> extends DatabaseEventService<T> {\n // initialiseDatabase = handlers<IDatabaseEventService>().binder(\"initialiseDatabase\");\n}\n","import { handlers } from \"@lib/services/lib/HandlerUtils\";\nimport type { IFileProcessingService } from \"./IService\";\nimport { ServiceBase, type ServiceContext } from \"./ServiceBase\";\nimport { reactiveSource } from \"octagonal-wheels/dataobject/reactive\";\n\n/**\n * File processing service handles file events and processes them accordingly.\n */\nexport class FileProcessingService<T extends ServiceContext = ServiceContext>\n extends ServiceBase<T>\n implements IFileProcessingService\n{\n /**\n * Process a file event item by the registered handlers.\n */\n readonly processFileEvent = handlers<IFileProcessingService>().anySuccess(\"processFileEvent\");\n\n /**\n * Process a file event item optionally, if any handler is registered.\n * i.e., hidden files synchronisation or customisation sync.\n */\n readonly processOptionalFileEvent = handlers<IFileProcessingService>().anySuccess(\"processOptionalFileEvent\");\n\n /**\n * Commit any pending file events that have been queued for processing.\n */\n readonly commitPendingFileEvents = handlers<IFileProcessingService>().bailFirstFailure(\"commitPendingFileEvents\");\n batched = reactiveSource(0);\n totalQueued = reactiveSource(0);\n processing = reactiveSource(0);\n totalStorageFileEventCount: number = 0;\n onStorageFileEvent() {\n this.totalStorageFileEventCount++;\n }\n}\n","import { FileProcessingService } from \"@lib/services/base/FileProcessingService\";\nimport type { ServiceContext } from \"@lib/services/base/ServiceBase\";\n\nexport class InjectableFileProcessingService<T extends ServiceContext> extends FileProcessingService<T> {}\n","import { stripAllPrefixes } from \"@lib/string_and_binary/path\";\nimport type { DocumentID, FilePath, FilePathWithPrefix } from \"./models/db.type\";\nimport { CHeader, ICHeader, ICHeaderLength, ICXHeader, PSCHeader } from \"./models/fileaccess.const\";\nimport type { UXFileInfoStub } from \"./types\";\n\n/**\n * returns is internal chunk of file\n * @param id ID\n * @returns\n */\nexport function isInternalMetadata(id: FilePath | FilePathWithPrefix | DocumentID): boolean {\n return id.startsWith(ICHeader);\n}\n\nexport function isInternalFile(file: UXFileInfoStub | string | FilePathWithPrefix) {\n if (typeof file == \"string\") return isInternalMetadata(file as FilePathWithPrefix);\n if (file.isInternal) return true;\n return false;\n}\nexport function stripInternalMetadataPrefix<T extends FilePath | FilePathWithPrefix | DocumentID>(id: T): T {\n return id.substring(ICHeaderLength) as T;\n}\nexport function id2InternalMetadataId(id: DocumentID): DocumentID {\n return (ICHeader + id) as DocumentID;\n}\n\n// const CHeaderLength = CHeader.length;\nexport function isChunk(str: string): boolean {\n return str.startsWith(CHeader);\n}\n\nexport function isPluginMetadata(str: string): boolean {\n return str.startsWith(PSCHeader);\n}\nexport function isCustomisationSyncMetadata(str: string): boolean {\n return str.startsWith(ICXHeader);\n}\n\nexport function getPathFromUXFileInfo(file: UXFileInfoStub | string | FilePathWithPrefix) {\n if (typeof file == \"string\") return file as FilePathWithPrefix;\n return file.path;\n}\nexport function getStoragePathFromUXFileInfo(file: UXFileInfoStub | string | FilePathWithPrefix) {\n if (typeof file == \"string\") return stripAllPrefixes(file as FilePathWithPrefix);\n return stripAllPrefixes(file.path);\n}\nexport function getDatabasePathFromUXFileInfo(file: UXFileInfoStub | string | FilePathWithPrefix) {\n if (typeof file == \"string\" && file.startsWith(ICXHeader)) return file as FilePathWithPrefix;\n const prefix = isInternalFile(file) ? ICHeader : \"\";\n if (typeof file == \"string\") return (prefix + stripAllPrefixes(file as FilePathWithPrefix)) as FilePathWithPrefix;\n return (prefix + stripAllPrefixes(file.path)) as FilePathWithPrefix;\n}\n","import type {\n DocumentID,\n EntryHasPath,\n FilePathWithPrefix,\n FilePath,\n AnyEntry,\n RemoteDBSettings,\n UXFileInfo,\n UXFileInfoStub,\n} from \"@lib/common/types\";\nimport type { IPathService, ISettingService } from \"./IService\";\nimport { ServiceBase, type ServiceContext } from \"./ServiceBase\";\nimport { addPrefix, expandFilePathPrefix, id2path_base, path2id_base } from \"@lib/string_and_binary/path\";\nimport { configuredIdKey } from \"@lib/common/idDerivation.ts\";\nimport { isInternalMetadata, stripInternalMetadataPrefix } from \"@lib/common/typeUtils\";\nimport type { BASE_IS_NEW, EVEN, TARGET_IS_NEW } from \"@lib/common/models/shared.const.symbols\";\n\nexport interface PathServiceDependencies {\n settingService: ISettingService;\n /**\n * Optional host capability for consumers which keep content encryption and\n * path-obfuscation passphrases separate.\n */\n getPathObfuscationPassphrase?: () => string | false;\n}\n/**\n * The PathService provides methods for converting between file paths and document IDs.\n * This class would be migrated to the new logic later.\n */\nexport abstract class PathService<T extends ServiceContext = ServiceContext>\n extends ServiceBase<T>\n implements IPathService\n{\n protected settingService: ISettingService;\n private readonly getPathObfuscationPassphrase?: () => string | false;\n protected abstract normalizePath(path: string): string;\n get settings() {\n return this.settingService.currentSettings();\n }\n constructor(context: T, dependencies: PathServiceDependencies) {\n super(context);\n this.settingService = dependencies.settingService;\n this.getPathObfuscationPassphrase = dependencies.getPathObfuscationPassphrase;\n }\n private _id2path(id: DocumentID, entry?: EntryHasPath): FilePathWithPrefix {\n const filename = id2path_base(id, entry);\n const [prefix, path] = expandFilePathPrefix(filename);\n return (prefix + this.normalizePath(path)) as FilePathWithPrefix;\n }\n private async _path2id(\n filename: FilePathWithPrefix | FilePath,\n obfuscatePassphrase: string | false,\n caseInsensitive: boolean,\n idDerivationKey?: string\n ): Promise<DocumentID> {\n const [prefix, path] = expandFilePathPrefix(filename);\n const fixedPath = (prefix + this.normalizePath(path)) as FilePathWithPrefix;\n\n const out = await path2id_base(fixedPath, obfuscatePassphrase, caseInsensitive, idDerivationKey);\n return out;\n }\n /**\n * Convert a document ID or entry to a virtual file path.\n * @param id A document ID. Nowadays, it is mostly not the same as the file path.\n * If the document has `_` prefixed, saved as `/_`.\n * @param entry An entry object. If provided, it can be used to get the path directly.\n * @param stripPrefix Whether to strip the prefix from the path.\n */\n id2path(id: DocumentID, entry?: EntryHasPath, stripPrefix?: boolean): FilePathWithPrefix {\n const tempId = this._id2path(id, entry);\n if (stripPrefix && isInternalMetadata(tempId)) {\n const out = stripInternalMetadataPrefix(tempId);\n return out;\n }\n return tempId;\n }\n\n /**\n * Convert a virtual file path to a document ID (with prefix if any).\n * @param filename A file path with or without prefix.\n * @param prefix The prefix to use for the document ID.\n */\n async path2id(filename: FilePathWithPrefix | FilePath, prefix?: string): Promise<DocumentID> {\n return this.path2idWithSettings(filename, this.settings, prefix);\n }\n\n /** Convert a path using the caller's settings snapshot and this host's path normalisation. */\n async path2idWithSettings(\n filename: FilePathWithPrefix | FilePath,\n setting: Pick<\n RemoteDBSettings,\n | \"encrypt\"\n | \"usePathObfuscation\"\n | \"passphrase\"\n | \"handleFilenameCaseSensitive\"\n | \"idDerivationVersion\"\n | \"idDerivationKey\"\n >,\n prefix?: string\n ): Promise<DocumentID> {\n const destPath = addPrefix(filename, prefix ?? \"\");\n const pathObfuscationPassphrase =\n this.getPathObfuscationPassphrase?.() ?? (setting.usePathObfuscation ? setting.passphrase : false);\n return await this._path2id(\n destPath,\n pathObfuscationPassphrase,\n !setting.handleFilenameCaseSensitive,\n (setting.encrypt && configuredIdKey(setting)) || undefined\n );\n }\n\n getPath(entry: AnyEntry): FilePathWithPrefix {\n return this.id2path(entry._id, entry);\n }\n\n abstract markChangesAreSame(\n old: UXFileInfo | AnyEntry | FilePathWithPrefix,\n newMtime: number,\n oldMtime: number\n ): boolean | undefined;\n abstract unmarkChanges(file: AnyEntry | FilePathWithPrefix | UXFileInfoStub): void;\n abstract compareFileFreshness(\n baseFile: UXFileInfoStub | AnyEntry | undefined,\n checkTarget: UXFileInfo | AnyEntry | undefined\n ): typeof BASE_IS_NEW | typeof TARGET_IS_NEW | typeof EVEN;\n abstract isMarkedAsSameChanges(\n file: UXFileInfoStub | AnyEntry | FilePathWithPrefix,\n mtimes: number[]\n ): undefined | typeof EVEN;\n}\n","import type { UXFileInfo, AnyEntry, UXFileInfoStub, FilePathWithPrefix } from \"@lib/common/types\";\nimport { PathService } from \"@lib/services/base/PathService\";\nimport type { ServiceContext } from \"@lib/services/base/ServiceBase\";\nimport { BASE_IS_NEW, EVEN, TARGET_IS_NEW } from \"@lib/common/models/shared.const.symbols\";\nimport { compareMTime } from \"@lib/common/utils\";\nexport function compareFileFreshnessGeneric(\n baseFile: UXFileInfoStub | AnyEntry | undefined,\n checkTarget: UXFileInfo | AnyEntry | undefined\n): typeof BASE_IS_NEW | typeof TARGET_IS_NEW | typeof EVEN {\n if (baseFile === undefined && checkTarget == undefined) return EVEN;\n if (baseFile == undefined) return TARGET_IS_NEW;\n if (checkTarget == undefined) return BASE_IS_NEW;\n\n const modifiedBase = \"stat\" in baseFile ? (baseFile?.stat?.mtime ?? 0) : (baseFile?.mtime ?? 0);\n const modifiedTarget = \"stat\" in checkTarget ? (checkTarget?.stat?.mtime ?? 0) : (checkTarget?.mtime ?? 0);\n\n if (!modifiedBase && !modifiedTarget) {\n return EVEN;\n }\n return compareMTime(modifiedBase, modifiedTarget);\n}\nexport class PathServiceCompat<T extends ServiceContext> extends PathService<T> {\n override markChangesAreSame(\n old: UXFileInfo | AnyEntry | FilePathWithPrefix,\n newMtime: number,\n oldMtime: number\n ): boolean | undefined {\n return undefined;\n }\n override unmarkChanges(file: AnyEntry | FilePathWithPrefix | UXFileInfoStub): void {\n return;\n }\n override compareFileFreshness(\n baseFile: UXFileInfoStub | AnyEntry | undefined,\n checkTarget: UXFileInfo | AnyEntry | undefined\n ): typeof BASE_IS_NEW | typeof TARGET_IS_NEW | typeof EVEN {\n return compareFileFreshnessGeneric(baseFile, checkTarget);\n }\n override isMarkedAsSameChanges(\n file: UXFileInfoStub | AnyEntry | FilePathWithPrefix,\n mtimes: number[]\n ): undefined | typeof EVEN {\n return undefined;\n }\n override normalizePath(path: string): string {\n // Turns the path with forward slashes, strip double slashes\n const fPath = path.replace(/\\\\/g, \"/\").replace(/\\/+/g, \"/\");\n return fPath;\n }\n}\n","import type {\n CouchDBCredentials,\n JWTCredentials,\n JWTHeader,\n JWTParams,\n JWTPayload,\n PreparedJWT,\n RemoteDBSettings,\n} from \"@lib/common/types\";\nimport { arrayBufferToBase64Single, writeString } from \"@lib/string_and_binary/convert\";\nimport { Computed } from \"octagonal-wheels/dataobject/Computed\";\nimport { compatGlobal } from \"@lib/common/coreEnvFunctions.ts\";\n\n/**\n * Generates a credential object based on the provided settings.\n * @param settings - RemoteDBSettings\n * @returns {CouchDBCredentials} credentials object\n */\nexport function generateCredentialObject(settings: RemoteDBSettings) {\n if (settings.useJWT) {\n return {\n jwtAlgorithm: settings.jwtAlgorithm,\n jwtKey: settings.jwtKey,\n jwtKid: settings.jwtKid,\n jwtSub: settings.jwtSub,\n jwtExpDuration: settings.jwtExpDuration,\n type: \"jwt\",\n } satisfies JWTCredentials;\n } else {\n return {\n username: settings.couchDB_USER,\n password: settings.couchDB_PASSWORD,\n type: \"basic\",\n } satisfies CouchDBCredentials;\n }\n throw new Error(\"Invalid credentials\");\n}\n/**\n * Generates a basic authentication header for CouchDB credentials using the provided username and password.\n * And it caches the result for performance if the credentials are not changed.\n */\nexport class BasicHeaderGenerator {\n _header = new Computed({\n evaluation: (source: CouchDBCredentials) => {\n if (\"username\" in source) {\n const userNameAndPassword =\n source.username && source.password ? `${source.username}:${source.password}` : \"\";\n return `Basic ${btoa(userNameAndPassword)}`;\n }\n return \"\";\n },\n });\n\n /**\n * Generates a basic authentication header for CouchDB credentials using the provided username and password.\n * @param auth - CouchDBCredentials\n * @returns {Promise<string>} The basic authentication header (without \"Basic\" prefix).\n */\n async getBasicHeader(auth: CouchDBCredentials): Promise<string> {\n return (await this._header.update(auth)).value;\n }\n}\n/**\n * Generates a JWT token based on the provided credentials and parameters.\n * And it caches the result for performance if the credentials are not changed.\n */\nexport class JWTTokenGenerator {\n _importKey(auth: JWTCredentials) {\n if (auth.jwtAlgorithm == \"HS256\" || auth.jwtAlgorithm == \"HS512\") {\n const key = (auth.jwtKey || \"\").trim();\n if (key == \"\") {\n throw new Error(\"JWT key is empty\");\n }\n const binaryDerString = compatGlobal.atob(key);\n const binaryDer = new Uint8Array(binaryDerString.length);\n for (let i = 0; i < binaryDerString.length; i++) {\n binaryDer[i] = binaryDerString.charCodeAt(i);\n }\n const hashName = auth.jwtAlgorithm == \"HS256\" ? \"SHA-256\" : \"SHA-512\";\n return crypto.subtle.importKey(\"raw\", binaryDer, { name: \"HMAC\", hash: { name: hashName } }, true, [\n \"sign\",\n ]);\n } else if (auth.jwtAlgorithm == \"ES256\" || auth.jwtAlgorithm == \"ES512\") {\n const pem = auth.jwtKey\n .replace(/-----BEGIN [^-]+-----/, \"\")\n .replace(/-----END [^-]+-----/, \"\")\n .replace(/\\s+/g, \"\");\n // const pem = key.replace(/\\s/g, \"\");\n const binaryDerString = compatGlobal.atob(pem);\n const binaryDer = new Uint8Array(binaryDerString.length);\n for (let i = 0; i < binaryDerString.length; i++) {\n binaryDer[i] = binaryDerString.charCodeAt(i);\n }\n // const binaryDer = base64ToArrayBuffer(pem);\n const namedCurve = auth.jwtAlgorithm == \"ES256\" ? \"P-256\" : \"P-521\";\n const param = { name: \"ECDSA\", namedCurve };\n return crypto.subtle.importKey(\"pkcs8\", binaryDer, param, true, [\"sign\"]);\n } else {\n throw new Error(\"Supplied JWT algorithm is not supported.\");\n }\n }\n _currentCryptoKey = new Computed({\n evaluation: async (auth: JWTCredentials) => {\n return await this._importKey(auth);\n },\n });\n\n _jwt = new Computed({\n evaluation: async (params: JWTParams) => {\n const encodedHeader = btoa(JSON.stringify(params.header));\n const encodedPayload = btoa(JSON.stringify(params.payload));\n const buff = `${encodedHeader}.${encodedPayload}`.replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n\n const key = (await this._currentCryptoKey.update(params.credentials)).value;\n let token = \"\";\n if (params.header.alg == \"ES256\" || params.header.alg == \"ES512\") {\n const digestAlg = params.header.alg == \"ES256\" ? \"SHA-256\" : \"SHA-512\";\n const jwt = await crypto.subtle.sign(\n { name: \"ECDSA\", hash: { name: digestAlg } },\n key,\n writeString(buff)\n );\n token = (await arrayBufferToBase64Single(jwt))\n .replace(/\\+/g, \"-\")\n .replace(/\\//g, \"_\")\n .replace(/=/g, \"\");\n } else if (params.header.alg == \"HS256\" || params.header.alg == \"HS512\") {\n const jwt = await crypto.subtle.sign(\n { name: \"HMAC\", hash: { name: params.header.alg } },\n key,\n writeString(buff)\n );\n token = (await arrayBufferToBase64Single(jwt))\n .replace(/\\+/g, \"-\")\n .replace(/\\//g, \"_\")\n .replace(/=/g, \"\");\n } else {\n throw new Error(\"JWT algorithm is not supported.\");\n }\n return {\n ...params,\n token: `${buff}.${token}`,\n } satisfies PreparedJWT;\n },\n });\n\n _jwtParams = new Computed({\n evaluation(source: JWTCredentials) {\n const kid = source.jwtKid || undefined;\n const sub = (source.jwtSub || \"\").trim();\n if (sub == \"\") {\n throw new Error(\"JWT sub is empty\");\n }\n const algorithm = source.jwtAlgorithm || \"\";\n if (!algorithm) {\n throw new Error(\"JWT algorithm is not configured.\");\n }\n if (algorithm != \"HS256\" && algorithm != \"HS512\" && algorithm != \"ES256\" && algorithm != \"ES512\") {\n throw new Error(\"JWT algorithm is not supported.\");\n }\n const header: JWTHeader = {\n alg: source.jwtAlgorithm || \"HS256\",\n typ: \"JWT\",\n kid,\n };\n const iat = ~~(new Date().getTime() / 1000);\n const exp = iat + (source.jwtExpDuration || 5) * 60; // 5 minutes\n const payload = {\n exp,\n iat,\n sub: source.jwtSub || \"\",\n \"_couchdb.roles\": [\"_admin\"],\n } satisfies JWTPayload;\n return {\n header,\n payload,\n credentials: source,\n };\n },\n requiresUpdate(args, previousArgs, previous) {\n // if previous is not present.\n if (!previous || previous instanceof Error) {\n return true;\n }\n // Check if the expiration time is near.\n // This means that if the token is valid for 100 seconds, we consider it expired 10 seconds before actual expiration.\n const ttl = previous.payload.exp - previous.payload.iat;\n const margin20p = ttl * 0.1; // 10% margin of ttl\n const margin = Math.min(10, Math.max(margin20p, 60)); // max 10 seconds, min 60 seconds\n const d = ~~(new Date().getTime() / 1000) + margin; // current time + margin\n if (previous.payload.exp < d) {\n // console.warn(`jwt expired ${previous.payload.exp} < ${d}`);\n return true;\n }\n return false;\n },\n });\n\n async getJWT(auth: JWTCredentials): Promise<PreparedJWT> {\n const params = (await this._jwtParams.update(auth)).value;\n const jwt = (await this._jwt.update(params)).value;\n return jwt;\n }\n\n /**\n * Generates a JWT token based on the provided credentials and parameters.\n * @param auth - JWTCredentials\n * @returns {Promise<string>} The JWT token (with \"Bearer\" prefix).\n */\n async getBearerToken(auth: JWTCredentials): Promise<string> {\n const jwt = await this.getJWT(auth);\n return `Bearer ${jwt.token}`;\n }\n}\nexport class AuthorizationHeaderGenerator {\n _basicHeader = new BasicHeaderGenerator();\n _jwtHeader = new JWTTokenGenerator();\n async getAuthorizationHeader(auth: CouchDBCredentials): Promise<string> {\n if (\"username\" in auth) {\n return await this._basicHeader.getBasicHeader(auth);\n } else if (\"jwtAlgorithm\" in auth) {\n return await this._jwtHeader.getBearerToken(auth);\n }\n return \"\";\n }\n}\n","import { EVENT_ON_UNRESOLVED_ERROR } from \"@lib/events/coreEvents\";\nimport { type LOG_LEVEL, LEVEL_NOTICE, LEVEL_INFO } from \"octagonal-wheels/common/logger\";\nimport { createInstanceLogFunction } from \"@lib/services/lib/logUtils\";\nimport type { AppLifecycleService } from \"./AppLifecycleService\";\nimport type { LiveSyncEventHub } from \"@lib/hub/hub\";\n\nexport class UnresolvedErrorManager {\n private _log = createInstanceLogFunction(\"UnresolvedErrorManager\");\n private appLifecycleService: AppLifecycleService;\n private _occurredErrors = new Set<string>();\n showError(msg: string, max_log_level: LOG_LEVEL = LEVEL_NOTICE) {\n // If the error has already occurred, we will only log it as info, to avoid spamming the user with the same error.\n const level = this._occurredErrors.has(msg) ? LEVEL_INFO : max_log_level;\n this._log(msg, level);\n if (!this._occurredErrors.has(msg)) {\n this._occurredErrors.add(msg);\n this.events.emitEvent(EVENT_ON_UNRESOLVED_ERROR);\n }\n }\n\n clearError(msg: string) {\n if (!this._occurredErrors.has(msg)) {\n return;\n }\n this._occurredErrors.delete(msg);\n this.events.emitEvent(EVENT_ON_UNRESOLVED_ERROR);\n }\n clearErrors() {\n this._occurredErrors.clear();\n this.events.emitEvent(EVENT_ON_UNRESOLVED_ERROR);\n }\n\n countErrors(needle: string) {\n return Array.from(this._occurredErrors).filter(\n (error) => typeof error === \"string\" && error.indexOf(needle) !== -1\n ).length;\n }\n\n private _reportUnresolvedMessages() {\n return Promise.resolve(Array.from(this._occurredErrors));\n }\n\n constructor(\n appLifecycleService: AppLifecycleService,\n private readonly events: LiveSyncEventHub\n ) {\n this.appLifecycleService = appLifecycleService;\n this.appLifecycleService.getUnresolvedMessages.addHandler(this._reportUnresolvedMessages.bind(this));\n }\n}\n","import type { ReactiveSource } from \"octagonal-wheels/dataobject/reactive\";\n\nexport type TrackedPhysicalRequestCounters = {\n requestCount: ReactiveSource<number>;\n responseCount: ReactiveSource<number>;\n};\n\n/**\n * Tracks one physical-request unit for status reporting.\n *\n * A unit may be an exact transport attempt or a higher-level SDK command. The\n * resulting in-flight count is deliberately approximate and must not be used\n * for protocol correctness, throttling, or completion decisions.\n */\nexport async function runWithTrackedPhysicalRequest<T>(\n counters: TrackedPhysicalRequestCounters,\n task: () => T | PromiseLike<T>\n): Promise<T> {\n counters.requestCount.value++;\n try {\n return await task();\n } finally {\n counters.responseCount.value++;\n }\n}\n","import type { CouchDBCredentials, EntryDoc } from \"@lib/common/types\";\nimport type { IRemoteService } from \"./IService\";\nimport { ServiceBase, type ServiceContext } from \"./ServiceBase\";\nimport {\n LOG_LEVEL_DEBUG,\n LOG_LEVEL_INFO,\n LOG_LEVEL_NOTICE,\n LOG_LEVEL_VERBOSE,\n type LOG_LEVEL,\n} from \"@lib/common/types\";\nimport { replicationFilter } from \"@lib/pouchdb/compress\";\nimport { disableEncryption, enableEncryption } from \"@lib/pouchdb/encryption\";\nimport { isCloudantURI, isValidRemoteCouchDBURI } from \"@lib/pouchdb/utils_couchdb\";\nimport { AuthorizationHeaderGenerator } from \"@lib/replication/httplib\";\nimport type { APIService } from \"@lib/services/base/APIService\";\nimport type { AppLifecycleService } from \"@lib/services/base/AppLifecycleService\";\nimport type { SettingService } from \"@lib/services/base/SettingService\";\nimport { UnresolvedErrorManager } from \"@lib/services/base/UnresolvedErrorManager\";\nimport { createInstanceLogFunction, MARK_LOG_NETWORK_ERROR, type LogFunction } from \"@lib/services/lib/logUtils\";\nimport { runWithTrackedPhysicalRequest } from \"@lib/services/lib/remoteActivity.ts\";\nimport type PouchDB from \"pouchdb-core\";\nimport type { PouchDBConstructor } from \"@lib/pouchdb/PouchDBConstructor.ts\";\nimport { LiveSyncError } from \"@lib/common/LSError\";\nimport type { OwnedCouchDBConnection, RemoteConnectionOpenOptions } from \"./RemoteConnection.ts\";\n\ntype RemoteConnectionScope = {\n readonly signal: AbortSignal;\n combine(signal?: AbortSignal | null): AbortSignal;\n abort(reason?: unknown): void;\n};\n\nfunction createRemoteConnectionScope(ownerSignal?: AbortSignal): RemoteConnectionScope {\n const controller = new AbortController();\n const combinedSignals = new WeakMap<AbortSignal, AbortSignal>();\n let detachOwner = () => {};\n const abort = (reason?: unknown) => {\n detachOwner();\n if (!controller.signal.aborted) {\n controller.abort(reason);\n }\n };\n if (ownerSignal?.aborted) {\n abort(ownerSignal.reason);\n } else if (ownerSignal) {\n const onOwnerAbort = () => abort(ownerSignal.reason);\n ownerSignal.addEventListener(\"abort\", onOwnerAbort, { once: true });\n detachOwner = () => ownerSignal.removeEventListener(\"abort\", onOwnerAbort);\n }\n const combine = (signal?: AbortSignal | null) => {\n if (!signal || signal === controller.signal) return controller.signal;\n const cached = combinedSignals.get(signal);\n if (cached) return cached;\n const combined = combineAbortSignals(signal, controller.signal);\n combinedSignals.set(signal, combined);\n return combined;\n };\n return { signal: controller.signal, combine, abort };\n}\n\nfunction combineAbortSignals(first: AbortSignal, second: AbortSignal): AbortSignal {\n if (first === second) return first;\n\n const abortSignalWithAny = AbortSignal as typeof AbortSignal & {\n any?: (signals: AbortSignal[]) => AbortSignal;\n };\n if (typeof abortSignalWithAny.any === \"function\") {\n return abortSignalWithAny.any([first, second]);\n }\n\n // Older hosts do not provide AbortSignal.any(). Keep both cancellation\n // sources without replacing PouchDB's per-request signal.\n const controller = new AbortController();\n const listeners = new Map<AbortSignal, () => void>();\n const detach = () => {\n for (const [signal, listener] of listeners) {\n signal.removeEventListener(\"abort\", listener);\n }\n listeners.clear();\n };\n const abortFrom = (signal: AbortSignal) => {\n detach();\n if (!controller.signal.aborted) {\n controller.abort(signal.reason);\n }\n };\n for (const signal of [first, second]) {\n if (signal.aborted) {\n abortFrom(signal);\n break;\n }\n const listener = () => abortFrom(signal);\n listeners.set(signal, listener);\n signal.addEventListener(\"abort\", listener, { once: true });\n }\n return controller.signal;\n}\n\nfunction createCouchDBConnection<T extends object>(\n db: PouchDB.Database<T>,\n info: PouchDB.Core.DatabaseInfo,\n scope: RemoteConnectionScope\n): OwnedCouchDBConnection<T> {\n let closePromise: Promise<void> | undefined;\n return {\n db,\n info,\n close: () => {\n closePromise ??= (async () => {\n scope.abort(new Error(\"Remote connection closed.\"));\n await db.close();\n })();\n return closePromise;\n },\n };\n}\n\nexport interface RemoteServiceDependencies {\n /** PouchDB with the HTTP adapter required by the host runtime already registered. */\n pouchDB: PouchDBConstructor;\n APIService: APIService;\n appLifecycle: AppLifecycleService;\n setting: SettingService;\n}\n\nconst FetchMethod = {\n webCompat: 0,\n native: 1,\n} as const;\n\ntype FetchMethod = (typeof FetchMethod)[keyof typeof FetchMethod];\n\n/**\n * The RemoteService provides methods for interacting with the remote database.\n */\nexport abstract class RemoteService<T extends ServiceContext = ServiceContext>\n extends ServiceBase<T>\n implements IRemoteService\n{\n protected _log: LogFunction;\n protected _authHeader = new AuthorizationHeaderGenerator();\n protected _APIService: APIService;\n protected _appLifecycleService: AppLifecycleService;\n protected _settingService: SettingService;\n protected _unresolvedErrors: UnresolvedErrorManager;\n protected _pouchDB: PouchDBConstructor;\n protected last_successful_post = false;\n\n get hadLastPostFailedBySize(): boolean {\n return !this.last_successful_post;\n }\n\n constructor(context: T, dependencies: RemoteServiceDependencies) {\n super(context);\n this._pouchDB = dependencies.pouchDB;\n this._APIService = dependencies.APIService;\n this._appLifecycleService = dependencies.appLifecycle;\n this._settingService = dependencies.setting;\n this._log = createInstanceLogFunction(\"RemoteService\", dependencies.APIService);\n this._unresolvedErrors = new UnresolvedErrorManager(this._appLifecycleService, this.context.events);\n }\n\n showError(msg: string, max_log_level: LOG_LEVEL = LOG_LEVEL_NOTICE) {\n this._unresolvedErrors.showError(msg, max_log_level);\n }\n\n clearErrors() {\n this._unresolvedErrors.clearErrors();\n }\n\n async performFetch(\n req: string | Request,\n opts?: RequestInit,\n fetchMethod: FetchMethod = FetchMethod.webCompat\n ): Promise<Response> {\n const useNativeFetch = fetchMethod === FetchMethod.native;\n const fetchFunction = useNativeFetch\n ? this._APIService.nativeFetch.bind(this._APIService)\n : this._APIService.webCompatFetch.bind(this._APIService);\n return await runWithTrackedPhysicalRequest(this._APIService, async () => {\n const response = await fetchFunction(req, opts);\n const method = opts?.method ?? \"GET\";\n if (method == \"POST\" || method == \"PUT\") {\n this.last_successful_post = response.ok;\n } else {\n this.last_successful_post = true;\n }\n const url = new URL(typeof req === \"string\" ? req : req.url);\n const localURL = `${url.protocol}//${url.host}${url.pathname}`;\n this._log(`[REQ] (${method}) ${localURL} -> ${response.status}`, LOG_LEVEL_DEBUG);\n if (Math.floor(response.status / 100) !== 2) {\n if (response.status == 404) {\n if (method === \"GET\" && url.pathname.indexOf(\"/_local/\") === -1) {\n this._log(\n `Just checkpoint or some server information has been missing. The 404 error shown above is not an error.`,\n LOG_LEVEL_VERBOSE\n );\n }\n } else {\n const r = response.clone();\n this._log(\n `The request may have failed. The reason sent by the server: ${r.status}: ${r.statusText}`,\n LOG_LEVEL_NOTICE\n );\n try {\n const result = await r.text();\n this._log(result, LOG_LEVEL_VERBOSE);\n } catch (_) {\n this._log(\"Could not fetch response body\", LOG_LEVEL_VERBOSE);\n this._log(_, LOG_LEVEL_VERBOSE);\n }\n }\n } else {\n this.clearErrors();\n }\n return response;\n });\n }\n\n /**\n * Opens a remote CouchDB connection with request cancellation bound to its\n * owner.\n *\n * @param uri - The URI of the remote database.\n * @param auth - Authentication credentials for the remote database.\n * @param disableRequestURI - Whether request URI handling is disabled.\n * @param passphrase - The database encryption passphrase, or `false` when\n * encryption is disabled.\n * @param useDynamicIterationCount - Whether legacy dynamic iteration counts\n * are enabled.\n * @param performSetup - Whether PouchDB may set up a missing database.\n * @param skipInfo - Whether to omit the opening database information request.\n * @param compression - Whether chunk compression is enabled.\n * @param customHeaders - Additional HTTP headers for every request.\n * @param useRequestAPI - Whether to use the host-native request adapter.\n * @param getPBKDF2Salt - Resolves the PBKDF2 salt when encryption needs it.\n * @param connectionOptions - Ownership and request fallback options.\n * @returns An error description, or the owned connection. The caller must\n * transfer ownership or call `close()`.\n */\n async connect(\n uri: string,\n auth: CouchDBCredentials,\n disableRequestURI: boolean,\n passphrase: string | false,\n useDynamicIterationCount: boolean,\n performSetup: boolean,\n skipInfo: boolean,\n compression: boolean,\n customHeaders: Record<string, string>,\n useRequestAPI: boolean,\n getPBKDF2Salt: () => Promise<Uint8Array<ArrayBuffer>>,\n connectionOptions: RemoteConnectionOpenOptions = {}\n ): Promise<string | OwnedCouchDBConnection<EntryDoc>> {\n if (!isValidRemoteCouchDBURI(uri)) return \"Remote URI is not valid\";\n if (uri.toLowerCase() != uri) return \"Remote URI and database name could not contain capital letters.\";\n if (uri.indexOf(\" \") !== -1) return \"Remote URI and database name could not contain spaces.\";\n if (!this._APIService.isOnline) {\n return \"Network is offline\";\n }\n const connectionScope = createRemoteConnectionScope(connectionOptions.signal);\n // let authHeader = await this._authHeader.getAuthorizationHeader(auth);\n const conf: PouchDB.HttpAdapter.HttpAdapterConfiguration = {\n adapter: \"http\",\n auth: \"username\" in auth ? auth : undefined,\n skip_setup: !performSetup,\n fetch: async (requestSrc: string | Request, opts?: RequestInit) => {\n const url = new URL(typeof requestSrc === \"string\" ? requestSrc : requestSrc.url);\n const authHeader = await this._authHeader.getAuthorizationHeader(auth);\n let size = \"\";\n const localURL = url.toString().substring(uri.length);\n const method = opts?.method ?? \"GET\";\n if (opts?.body) {\n const bodyLength =\n typeof opts.body === \"string\" ? opts.body.length : JSON.stringify(opts.body).length;\n const opts_length = isNaN(bodyLength) ? 0 : bodyLength;\n if (opts_length > 1000 * 1000 * 10) {\n // over 10MB\n if (isCloudantURI(uri)) {\n this.last_successful_post = false;\n this._log(\"This request should fail on IBM Cloudant.\", LOG_LEVEL_VERBOSE);\n throw new Error(\"This request should fail on IBM Cloudant.\");\n }\n }\n size = ` (${opts_length})`;\n }\n try {\n const headers = new Headers(opts?.headers);\n if (customHeaders) {\n for (const [key, value] of Object.entries(customHeaders)) {\n if (key && value) {\n headers.append(key, value);\n }\n }\n }\n if (!(\"username\" in auth)) {\n headers.append(\"authorization\", authHeader);\n }\n try {\n // const response: Response = await (useRequestAPI\n // ? this.nativeFetch(url.toString(), { ...opts, headers })\n // : this.webCompatFetch(url, { ...opts, headers }));\n // if (method == \"POST\" || method == \"PUT\") {\n // this.last_successful_post = response.ok;\n // } else {\n // this.last_successful_post = true;\n // }\n // this._log(`HTTP:${method}${size} to:${localURL} -> ${response.status}`, LOG_LEVEL_DEBUG);\n // if (Math.floor(response.status / 100) !== 2) {\n // if (response.status == 404) {\n // if (method === \"GET\" && localURL.indexOf(\"/_local/\") === -1) {\n // this._log(\n // `Just checkpoint or some server information has been missing. The 404 error shown above is not an error.`,\n // LOG_LEVEL_VERBOSE\n // );\n // }\n // } else {\n // const r = response.clone();\n // this._log(\n // `The request may have failed. The reason sent by the server: ${r.status}: ${r.statusText}`,\n // LOG_LEVEL_NOTICE\n // );\n // try {\n // const result = await r.text();\n // this._log(result, LOG_LEVEL_VERBOSE);\n // } catch (_) {\n // this._log(\"Cloud not fetch response body\", LOG_LEVEL_VERBOSE);\n // this._log(_, LOG_LEVEL_VERBOSE);\n // }\n // }\n // }\n // this.clearErrors();\n const signal = connectionScope.combine(opts?.signal);\n const response = await this.performFetch(\n requestSrc,\n { ...opts, headers, signal },\n useRequestAPI ? FetchMethod.native : FetchMethod.webCompat\n );\n return response;\n } catch (ex) {\n if (ex instanceof TypeError) {\n if (connectionScope.signal.aborted || connectionOptions.allowNativeFallback === false) {\n throw ex;\n }\n if (useRequestAPI) {\n this._log(\"Failed to request by API.\");\n throw ex;\n }\n this._log(\n \"Failed to fetch by native fetch API. Trying to fetch by API to get more information.\"\n );\n // const resp2 = await this.fetchByAPI(url.toString(), localURL, method, authHeader, {\n // ...opts,\n // headers,\n // });\n const resp2 = await this.performFetch(requestSrc, { ...opts, headers }, FetchMethod.native);\n if (resp2.status / 100 == 2) {\n this.showError(\n \"The request was successful by API. But the native fetch API failed! Please check CORS settings on the remote database!. While this condition, you cannot enable LiveSync\",\n LOG_LEVEL_NOTICE\n );\n return resp2;\n }\n const r2 = resp2.clone();\n const msg = await r2.text();\n this.showError(`Failed to fetch by API. ${resp2.status}: ${msg}`, LOG_LEVEL_NOTICE);\n return resp2;\n }\n throw ex;\n }\n } catch (ex) {\n this._log(`HTTP:${method}${size} to:${localURL} -> failed`, LOG_LEVEL_VERBOSE);\n const msg = ex instanceof Error ? `${ex?.name}:${ex?.message}` : ex?.toString();\n if (!connectionScope.signal.aborted) {\n this.showError(\n `${MARK_LOG_NETWORK_ERROR}Network Error: Failed to fetch: ${msg}`,\n LOG_LEVEL_INFO\n ); // Do not show notice, due to throwing below\n }\n this._log(ex, LOG_LEVEL_VERBOSE);\n // limit only in bulk_docs.\n if (url.toString().indexOf(\"_bulk_docs\") !== -1) {\n this.last_successful_post = false;\n }\n this._log(ex);\n throw ex;\n }\n // return await fetch(url, opts);\n },\n };\n const encryptionAlgorithm =\n connectionOptions.encryptionAlgorithm ?? this._settingService.currentSettings().E2EEAlgorithm;\n let db: PouchDB.Database<EntryDoc>;\n try {\n db = new this._pouchDB<EntryDoc>(uri, conf);\n } catch (ex) {\n connectionScope.abort(ex);\n throw ex;\n }\n const compatibilityInfo = { db_name: \"\", doc_count: 0, update_seq: \"\" };\n const connection = createCouchDBConnection(db, compatibilityInfo, connectionScope);\n const closeAfterConnectionFailure = async () => {\n try {\n await connection.close();\n } catch (closeError) {\n this._log(\"Failed to close remote database after connection failure.\", LOG_LEVEL_INFO);\n this._log(closeError, LOG_LEVEL_VERBOSE);\n }\n };\n try {\n replicationFilter(db, compression);\n disableEncryption();\n if (passphrase !== \"false\" && typeof passphrase === \"string\") {\n enableEncryption(\n db,\n passphrase,\n useDynamicIterationCount,\n false,\n getPBKDF2Salt,\n encryptionAlgorithm,\n connectionOptions.encryptInternalMetadata ?? false\n );\n }\n } catch (ex) {\n await closeAfterConnectionFailure();\n throw ex;\n }\n if (skipInfo) {\n return connection;\n }\n try {\n const info = await db.info();\n return { ...connection, info };\n } catch (ex) {\n const exMsg = ex instanceof Error ? ex : LiveSyncError.fromError(ex);\n const msg = `${exMsg.name}:${exMsg.message}`;\n this._log(ex, LOG_LEVEL_VERBOSE);\n await closeAfterConnectionFailure();\n return msg;\n }\n }\n}\n","import { RemoteService } from \"@lib/services/base/RemoteService\";\nimport type { ServiceContext } from \"@lib/services/base/ServiceBase\";\n\nexport class InjectableRemoteService<T extends ServiceContext> extends RemoteService<T> {\n // connect = handlers<IRemoteService>().binder(\"connect\");\n}\n","import {\n LOG_LEVEL_INFO,\n LOG_LEVEL_NOTICE,\n LOG_LEVEL_VERBOSE,\n type LOG_LEVEL,\n type ObsidianLiveSyncSettings,\n type RemoteDBSettings,\n} from \"@lib/common/types\";\nimport { handlers } from \"@lib/services/lib/HandlerUtils\";\nimport type {\n IAPIService,\n IDatabaseService,\n IFileProcessingService,\n IReplicationService,\n IReplicatorService,\n ISettingService,\n} from \"./IService\";\nimport { ServiceBase, type ServiceContext } from \"./ServiceBase\";\nimport { reactiveSource } from \"octagonal-wheels/dataobject/reactive\";\nimport { createInstanceLogFunction, type LogFunction } from \"@lib/services/lib/logUtils\";\nimport {\n CAPABILITY_SUPPORT_KINDS,\n NO_INTERACTION,\n CENTRAL_REMOTE_REPLICATION_READINESS,\n REPLICATION_PROGRESS_PRESENTATIONS,\n USER_INITIATED_REPLICATION_AUTHORITY,\n isActiveReplicatorContextBoundToSetting,\n isReplicationCompleted,\n replicationBlocked,\n replicationFailed,\n outcomeFromFiniteOpenReplication,\n type ActiveReplicatorContext,\n type ContinuousReplicationRequest,\n type ReplicationAttemptFailure,\n type ReplicationOutcome,\n type ReplicationReadinessRequirements,\n type UnattendedOneShotRequest,\n type UserInitiatedOneShotRequest,\n} from \"@lib/replication/ReplicatorProvider.ts\";\nimport type { ReplicatorInstance } from \"@lib/replication/ReplicatorInstance.ts\";\nimport { UnresolvedErrorManager } from \"./UnresolvedErrorManager\";\nimport type { AppLifecycleService } from \"./AppLifecycleService\";\nimport { isLockAcquired, shareRunningResult } from \"octagonal-wheels/concurrency/lock\";\nimport {\n createReplicationReadinessEvaluator,\n type ReplicationReadinessEvaluator,\n} from \"./ReplicationService.readiness.ts\";\nimport { TypedReplicationCoordinator } from \"./ReplicationService.typedReplication.ts\";\nimport { asCopy } from \"@lib/common/utils.object.ts\";\n\n/**\n * Event-triggered replication interval forecasted time.\n */\nconst REPLICATION_ON_EVENT_FORECASTED_TIME = 5000;\n\nconst DIRECTIONAL_REPLICATION = Object.freeze({\n UPLOAD: \"upload\",\n DOWNLOAD: \"download\",\n} as const);\n\ntype DirectionalReplication = (typeof DIRECTIONAL_REPLICATION)[keyof typeof DIRECTIONAL_REPLICATION];\n\nconst DIRECTIONAL_REPLICATION_ADMISSION = Object.freeze({\n ORDINARY: \"ordinary\",\n EXPLICIT_REBUILD: \"explicit-rebuild\",\n} as const);\n\ntype DirectionalReplicationAdmission =\n (typeof DIRECTIONAL_REPLICATION_ADMISSION)[keyof typeof DIRECTIONAL_REPLICATION_ADMISSION];\n\ninterface DirectionalReplicationAdapter extends ReplicatorInstance {\n replicateAllToServer?(setting: RemoteDBSettings, showingNotice?: boolean): Promise<boolean>;\n replicateAllFromServer?(setting: RemoteDBSettings, showingNotice?: boolean): Promise<boolean>;\n replicateAllToServerWithOutcome?(setting: RemoteDBSettings, showingNotice?: boolean): Promise<ReplicationOutcome>;\n replicateAllFromServerWithOutcome?(setting: RemoteDBSettings, showingNotice?: boolean): Promise<ReplicationOutcome>;\n}\n\ninterface LegacyCentralRemoteAdministrationAdapter extends ReplicatorInstance {\n markRemoteLocked(setting: RemoteDBSettings, locked: boolean, lockByClean: boolean): Promise<void>;\n markRemoteResolved(setting: RemoteDBSettings): Promise<void>;\n}\n\nfunction canUploadAll(replicator: ReplicatorInstance): replicator is DirectionalReplicationAdapter & {\n replicateAllToServer(setting: RemoteDBSettings, showingNotice?: boolean): Promise<boolean>;\n} {\n return \"replicateAllToServer\" in replicator && typeof replicator.replicateAllToServer === \"function\";\n}\n\nfunction canUploadAllWithOutcome(replicator: ReplicatorInstance): replicator is DirectionalReplicationAdapter & {\n replicateAllToServerWithOutcome(setting: RemoteDBSettings, showingNotice?: boolean): Promise<ReplicationOutcome>;\n} {\n return (\n \"replicateAllToServerWithOutcome\" in replicator &&\n typeof replicator.replicateAllToServerWithOutcome === \"function\"\n );\n}\n\nfunction canDownloadAll(replicator: ReplicatorInstance): replicator is DirectionalReplicationAdapter & {\n replicateAllFromServer(setting: RemoteDBSettings, showingNotice?: boolean): Promise<boolean>;\n} {\n return \"replicateAllFromServer\" in replicator && typeof replicator.replicateAllFromServer === \"function\";\n}\n\nfunction canDownloadAllWithOutcome(replicator: ReplicatorInstance): replicator is DirectionalReplicationAdapter & {\n replicateAllFromServerWithOutcome(setting: RemoteDBSettings, showingNotice?: boolean): Promise<ReplicationOutcome>;\n} {\n return (\n \"replicateAllFromServerWithOutcome\" in replicator &&\n typeof replicator.replicateAllFromServerWithOutcome === \"function\"\n );\n}\n\nfunction canAdministerLegacyCentralRemote(\n replicator: ReplicatorInstance\n): replicator is LegacyCentralRemoteAdministrationAdapter {\n return (\n \"markRemoteLocked\" in replicator &&\n typeof replicator.markRemoteLocked === \"function\" &&\n \"markRemoteResolved\" in replicator &&\n typeof replicator.markRemoteResolved === \"function\"\n );\n}\n\n/** Request and await cooperative stop of the admitted publication's active transfer before a directional operation. */\nasync function stopActiveTransferForDirectionalReplication(\n context: ActiveReplicatorContext\n): Promise<ReplicationOutcome> {\n const capability = context.provider.stopActiveTransfer;\n if (capability.kind !== CAPABILITY_SUPPORT_KINDS.SUPPORTED) {\n return replicationBlocked(capability.reason);\n }\n try {\n const outcome = await capability.run(context.replicator);\n // A failed stop is not a failed remote transfer and must not enter the\n // compatibility-retry path. Report it as unavailable for this attempt.\n return outcome.status === \"failed\" ? replicationBlocked(\"not-ready\") : outcome;\n } catch {\n return replicationBlocked(\"not-ready\");\n }\n}\n\nasync function runDirectionalReplication(\n context: ActiveReplicatorContext,\n setting: RemoteDBSettings,\n direction: DirectionalReplication,\n showingNotice: boolean\n): Promise<ReplicationOutcome> {\n if (!isActiveReplicatorContextBoundToSetting(context, setting)) {\n return replicationBlocked(\"not-ready\");\n }\n const stopOutcome = await stopActiveTransferForDirectionalReplication(context);\n if (!isReplicationCompleted(stopOutcome)) return stopOutcome;\n\n try {\n let result: boolean | void;\n if (direction === DIRECTIONAL_REPLICATION.UPLOAD) {\n if (canUploadAllWithOutcome(context.replicator)) {\n return await context.replicator.replicateAllToServerWithOutcome(setting, showingNotice);\n }\n if (!canUploadAll(context.replicator)) return replicationBlocked(\"capability-not-applicable\");\n result = await context.replicator.replicateAllToServer(setting, showingNotice);\n } else {\n if (canDownloadAllWithOutcome(context.replicator)) {\n return await context.replicator.replicateAllFromServerWithOutcome(setting, showingNotice);\n }\n if (!canDownloadAll(context.replicator)) return replicationBlocked(\"capability-not-applicable\");\n result = await context.replicator.replicateAllFromServer(setting, showingNotice);\n }\n return outcomeFromFiniteOpenReplication(result);\n } catch (error) {\n return replicationFailed(error);\n }\n}\n\nexport interface ReplicationServiceDependencies {\n APIService: IAPIService;\n settingService: ISettingService;\n appLifecycleService: AppLifecycleService;\n databaseService: IDatabaseService;\n replicatorService: IReplicatorService;\n fileProcessingService: IFileProcessingService;\n}\n/**\n * Host-facing replication façade for handlers, legacy entry points, and counters.\n *\n * Ordered readiness evaluation and typed capability dispatch are delegated to\n * focused collaborators. Handler objects remain on this service so existing\n * hosts retain their registration identity, priority ordering, and failure\n * semantics. Active Replicator ownership remains with `ReplicatorService`.\n */\nexport abstract class ReplicationService<T extends ServiceContext = ServiceContext>\n extends ServiceBase<T>\n implements IReplicationService\n{\n private _unresolvedErrorManager: UnresolvedErrorManager;\n private readonly _evaluateReadiness: ReplicationReadinessEvaluator;\n private readonly _typedReplication: TypedReplicationCoordinator;\n\n showError(msg: string, max_log_level: LOG_LEVEL = LOG_LEVEL_NOTICE) {\n this._unresolvedErrorManager.showError(msg, max_log_level);\n }\n clearErrors() {\n this._unresolvedErrorManager.clearErrors();\n }\n\n _log: LogFunction;\n settingService: ISettingService;\n appLifecycleService: AppLifecycleService;\n replicatorService: IReplicatorService;\n APIService: IAPIService;\n fileProcessing: IFileProcessingService;\n databaseService: IDatabaseService;\n constructor(context: T, dependencies: ReplicationServiceDependencies) {\n super(context);\n this.appLifecycleService = dependencies.appLifecycleService;\n this.settingService = dependencies.settingService;\n this.replicatorService = dependencies.replicatorService;\n this.APIService = dependencies.APIService;\n this.fileProcessing = dependencies.fileProcessingService;\n this.databaseService = dependencies.databaseService;\n this._log = createInstanceLogFunction(\"ReplicationService\", dependencies.APIService);\n this._unresolvedErrorManager = new UnresolvedErrorManager(\n dependencies.appLifecycleService,\n this.context.events\n );\n this._evaluateReadiness = createReplicationReadinessEvaluator({\n gates: {\n isApplicationReady: () => this.appLifecycleService.isReady(),\n runPolicyChecks: (showMessage) => this.onCheckReplicationReady(showMessage),\n currentSettings: () => this.settingService.currentSettings(),\n isCleanupRunning: () => isLockAcquired(\"cleanup\"),\n isOnline: () => this.APIService.isOnline,\n },\n preparation: {\n commitPendingFileEvents: () => this.fileProcessing.commitPendingFileEvents(),\n prepareCentralRemote: (showMessage) => this.onPrepareCentralRemoteReplication(showMessage),\n runBeforeReplicate: (showMessage) => this.onBeforeReplicate(showMessage),\n },\n diagnostics: {\n getUnresolvedMessages: () => this.appLifecycleService.getUnresolvedMessages(),\n translate: (key) => this.context.translate(key),\n log: this._log,\n showError: (message, maxLogLevel) => this.showError(message, maxLogLevel),\n clearErrors: () => this.clearErrors(),\n },\n });\n this._typedReplication = new TypedReplicationCoordinator({\n replicatorService: this.replicatorService,\n currentSettings: () => this.settingService.currentSettings(),\n checkReadiness: (showMessage, readiness) => this.isReplicationReady(showMessage, readiness),\n handleFailure: (request) => this.onReplicationFailed(request),\n recordFiniteAttempt: () => {\n this.previousReplicated = Date.now();\n },\n });\n }\n /**\n * Process a synchronisation result document.\n */\n readonly processSynchroniseResult = handlers<IReplicationService>().anySuccess(\"processSynchroniseResult\");\n\n /**\n * Process a synchronisation result document for optional entries i.e., hidden files.\n */\n readonly processOptionalSynchroniseResult = handlers<IReplicationService>().anySuccess(\n \"processOptionalSynchroniseResult\"\n );\n /**\n * Process an array of synchronisation result documents.\n * @param docs An array of documents to parse and handle.\n */\n readonly parseSynchroniseResult = handlers<IReplicationService>().all(\"parseSynchroniseResult\");\n /**\n * Process a virtual document (e.g., for customisation sync).\n */\n readonly processVirtualDocument = handlers<IReplicationService>().anySuccess(\"processVirtualDocument\");\n\n /**\n * An event triggered before starting replication.\n */\n readonly onBeforeReplicate = handlers<IReplicationService>().bailFirstFailure(\"onBeforeReplicate\");\n\n /** Provider preparation which applies only to the central remote. */\n readonly onPrepareCentralRemoteReplication = handlers<IReplicationService>().bailFirstFailure(\n \"onPrepareCentralRemoteReplication\"\n );\n\n /**\n * Lightweight, repeatable policy checks shared by every replication entry point.\n * Handlers must remain idempotent because a high-level replication may cross\n * more than one entry point before work begins.\n */\n readonly onCheckReplicationReady = handlers<IReplicationService>().bailFirstFailure(\"onCheckReplicationReady\");\n\n /**\n * Evaluate the ordered readiness conditions for an operation.\n *\n * This method does not acquire a Replicator or begin activity accounting.\n * Provider requirements select whether central-remote preparation applies.\n *\n * @param showMessage Whether condition-specific diagnostics may be prominent.\n * @param readiness Provider-owned preparation requirements.\n */\n async isReplicationReady(\n showMessage: boolean = false,\n readiness: ReplicationReadinessRequirements = CENTRAL_REMOTE_REPLICATION_READINESS\n ): Promise<boolean> {\n return (await this._evaluateReadiness({ showMessage, requirements: readiness })).ready;\n }\n\n onReplicationFailed = handlers<IReplicationService>().bailFirstFailure(\"onReplicationFailed\");\n\n async replicateUserInitiated(\n request: UserInitiatedOneShotRequest = {\n trigger: \"manual\",\n progressPresentation: REPLICATION_PROGRESS_PRESENTATIONS.NOTICE,\n interaction: USER_INITIATED_REPLICATION_AUTHORITY,\n }\n ): Promise<ReplicationOutcome> {\n return await this._typedReplication.runUserInitiated(request);\n }\n\n async replicateUnattended(request: UnattendedOneShotRequest): Promise<ReplicationOutcome> {\n return await this._typedReplication.runUnattended(request);\n }\n\n replicateUnattendedByEvent(request: UnattendedOneShotRequest): Promise<ReplicationOutcome> {\n return shareRunningResult(`replication`, async () => {\n const currentSettings = this.settingService.currentSettings();\n const least = currentSettings.syncMinimumInterval;\n if (least > 0) {\n const now = Date.now();\n const elapsed = now - this.previousReplicated;\n if (elapsed < least) {\n this._log(\n `Replication triggered by event is rate limited. Elapsed: ${elapsed}ms, Least interval: ${least}ms`,\n LOG_LEVEL_VERBOSE\n );\n return replicationBlocked(\"rate-limited\");\n }\n this.previousReplicated = now + REPLICATION_ON_EVENT_FORECASTED_TIME;\n }\n return await this.replicateUnattended(request);\n });\n }\n\n async startContinuous(request: ContinuousReplicationRequest): Promise<ReplicationOutcome> {\n return await this._typedReplication.startContinuous(request);\n }\n\n /**\n * Stop finite transfer work on the active provider without entering the\n * replication readiness or activity accounting paths.\n *\n * The provider and replicator are obtained together so that a concurrent\n * replacement cannot pair a capability from one provider with a\n * replicator from another. Stopping is an operator action, not a failed\n * replication, so it does not invoke failure-recovery handlers.\n */\n async stopActiveTransfer(): Promise<ReplicationOutcome> {\n return await this._typedReplication.stopActiveTransfer();\n }\n\n private async performReplicationRequest(showMessage?: boolean): Promise<boolean | void> {\n const activeReplicator = this.replicatorService.getActiveReplicator();\n if (!activeReplicator) {\n this._log(`No active replicator found`, showMessage ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO);\n return false;\n }\n const settings = this.settingService.currentSettings();\n return await activeReplicator.openReplication(settings, false, !!showMessage, false);\n }\n\n /**\n * Perform replication and handle a failed result.\n * @param showMessage Whether to show replication progress messages.\n */\n async performReplication(showMessage?: boolean): Promise<boolean | void> {\n const result = await this.performReplicationRequest(showMessage);\n if (!result) {\n return false;\n }\n return result;\n }\n\n /**\n * Start the replication process.\n * @param showMessage Whether to show messages to the user.\n */\n async replicate(showMessage?: boolean): Promise<boolean | void> {\n if (await this.replicatorService.acquireActiveReplicatorContext()) {\n const outcome = showMessage\n ? await this.replicateUserInitiated()\n : await this.replicateUnattended({\n trigger: \"database-event\",\n interaction: NO_INTERACTION,\n });\n return outcome.status === \"completed\";\n }\n try {\n const checkBeforeReplicate = await this.isReplicationReady(showMessage);\n if (!checkBeforeReplicate) return false;\n const result = await this.replicatorService.runFiniteReplicationActivity(\n () => this.performReplicationRequest(showMessage),\n { label: \"replication\" }\n );\n if (!result) {\n return false;\n }\n return result;\n } finally {\n this.previousReplicated = Date.now();\n }\n }\n\n previousReplicated: number = 0;\n /**\n * Start the replication process triggered by an event (e.g., file change).\n * @param showMessage Whether to show messages to the user.\n */\n async replicateByEvent(showMessage?: boolean): Promise<boolean | void> {\n if (await this.replicatorService.acquireActiveReplicatorContext()) {\n return await this.replicateUnattendedByEvent({\n trigger: \"database-event\",\n interaction: NO_INTERACTION,\n }).then((outcome) => outcome.status === \"completed\");\n }\n // If triggered multiple times in a short time, we will only perform replication once.\n return shareRunningResult(`replication`, async () => {\n const currentSettings = this.settingService.currentSettings();\n const least = currentSettings.syncMinimumInterval;\n if (least > 0) {\n const now = Date.now();\n const elapsed = now - this.previousReplicated;\n if (elapsed < least) {\n this._log(\n `Replication triggered by event is rate limited. Elapsed: ${elapsed}ms, Least interval: ${least}ms`,\n LOG_LEVEL_VERBOSE\n );\n return Promise.resolve(true);\n }\n // Update once.\n this.previousReplicated = now + REPLICATION_ON_EVENT_FORECASTED_TIME;\n return await this.replicate();\n }\n // No rate limit, replicate immediately, but serialised.\n return this.replicate();\n });\n }\n\n /**\n * Check if there is a connection failure with the remote database.\n */\n readonly checkConnectionFailure = handlers<IReplicationService>().firstResult(\"checkConnectionFailure\");\n databaseQueueCount = reactiveSource(0);\n storageApplyingCount = reactiveSource(0);\n replicationResultCount = reactiveSource(0);\n\n /**\n * Dispatch one directional full transfer through one admitted publication.\n *\n * Each attempt owns a separate reservation. Compatibility recovery runs\n * between those reservations, and a retry is admitted only when the exact\n * first-attempt context remains active. Each attempt uses a detached settings\n * snapshot, and a compatibility retry captures its snapshot after recovery.\n */\n private async performDirectionalReplication(\n direction: DirectionalReplication,\n showingNotice: boolean,\n admission: DirectionalReplicationAdmission = DIRECTIONAL_REPLICATION_ADMISSION.ORDINARY\n ): Promise<boolean> {\n if (direction === DIRECTIONAL_REPLICATION.UPLOAD && !(await this.onBeforeReplicate(showingNotice))) {\n this._log(this.context.translate(\"Replicator.Message.SomeModuleFailed\"), LOG_LEVEL_NOTICE);\n return false;\n }\n const captureSetting = (): Readonly<ObsidianLiveSyncSettings> => {\n const detachedSetting = asCopy(this.settingService.currentSettings());\n if (admission === DIRECTIONAL_REPLICATION_ADMISSION.EXPLICIT_REBUILD) {\n // The confirmed recovery may run while ordinary replication stays\n // paused. Authorise only this detached attempt; persistence and\n // explicit compatibility acknowledgement remain unchanged.\n detachedSetting.versionUpFlash = \"\";\n }\n return Object.freeze(detachedSetting);\n };\n const setting = captureSetting();\n let expectedContext: ActiveReplicatorContext | undefined;\n const run = async (attemptSetting: Readonly<ObsidianLiveSyncSettings>): Promise<ReplicationOutcome> => {\n const admitted = await this.replicatorService.runWithActiveReplicatorContext((context) => {\n if (expectedContext && context !== expectedContext) {\n return replicationBlocked(\"not-ready\");\n }\n expectedContext ??= context;\n return runDirectionalReplication(context, attemptSetting, direction, showingNotice);\n });\n if (admitted) return admitted;\n this._log(`Active replicator not found during directional ${direction}`, LOG_LEVEL_NOTICE);\n return replicationBlocked(\"no-active-replicator\");\n };\n const outcome = await run(setting);\n if (isReplicationCompleted(outcome)) return true;\n if (outcome.status !== \"failed\") return false;\n\n const failedContext = expectedContext;\n if (!failedContext) return false;\n const failure = Object.freeze({ context: failedContext, setting, outcome }) satisfies ReplicationAttemptFailure;\n const checkResult = await this.checkConnectionFailure(failure);\n return checkResult === \"CHECKAGAIN\" && isReplicationCompleted(await run(captureSetting()));\n }\n\n async replicateAllToRemote(showingNotice: boolean = false): Promise<boolean> {\n if (!this.appLifecycleService.isReady()) return false;\n return await this.performDirectionalReplication(DIRECTIONAL_REPLICATION.UPLOAD, showingNotice);\n }\n\n async replicateAllFromRemote(showingNotice: boolean = false): Promise<boolean> {\n if (!this.appLifecycleService.isReady()) return false;\n return await this.performDirectionalReplication(DIRECTIONAL_REPLICATION.DOWNLOAD, showingNotice);\n }\n\n /**\n * Perform a full upload owned by an active rebuild while the physical database is ready.\n *\n * This concrete maintenance entry point is intentionally absent from `IReplicationService`;\n * it is not a general application-readiness bypass.\n */\n async replicateAllToRemoteForRebuild(showingNotice: boolean = false): Promise<boolean> {\n if (!this.databaseService.isDatabaseReady()) {\n this._log(\"The selected local database is not ready for the rebuild upload.\", LOG_LEVEL_NOTICE);\n return false;\n }\n return await this.performDirectionalReplication(\n DIRECTIONAL_REPLICATION.UPLOAD,\n showingNotice,\n DIRECTIONAL_REPLICATION_ADMISSION.EXPLICIT_REBUILD\n );\n }\n\n /**\n * Perform a full download owned by an active rebuild while the physical database is ready.\n *\n * This concrete maintenance entry point is intentionally absent from `IReplicationService`;\n * it is not a general application-readiness bypass.\n */\n async replicateAllFromRemoteForRebuild(showingNotice: boolean = false): Promise<boolean> {\n if (!this.databaseService.isDatabaseReady()) {\n this._log(\"The selected local database is not ready for the rebuild download.\", LOG_LEVEL_NOTICE);\n return false;\n }\n return await this.performDirectionalReplication(\n DIRECTIONAL_REPLICATION.DOWNLOAD,\n showingNotice,\n DIRECTIONAL_REPLICATION_ADMISSION.EXPLICIT_REBUILD\n );\n }\n\n private getActiveReplicatorFor(usage: string) {\n const activeReplicator = this.replicatorService.getActiveReplicator();\n if (!activeReplicator) {\n this._log(`Active replicator not found during ${usage}`, LOG_LEVEL_NOTICE);\n return false;\n }\n return activeReplicator;\n }\n\n private _getReplicatorAndPerform(\n action: string,\n perform: (\n setting: ObsidianLiveSyncSettings,\n replicator: LegacyCentralRemoteAdministrationAdapter\n ) => Promise<void>\n ) {\n const activeReplicator = this.getActiveReplicatorFor(action);\n if (!activeReplicator) return Promise.resolve();\n if (!canAdministerLegacyCentralRemote(activeReplicator)) {\n this._log(`Active replicator does not support ${action}`, LOG_LEVEL_NOTICE);\n return Promise.resolve();\n }\n return perform(this.settingService.currentSettings(), activeReplicator);\n }\n\n async markLocked(lockByClean: boolean = false): Promise<void> {\n return await this._getReplicatorAndPerform(\n \"marking remote locked\",\n async (currentSettings, activeReplicator) =>\n await activeReplicator.markRemoteLocked(currentSettings, true, lockByClean)\n );\n }\n\n async markUnlocked(): Promise<void> {\n return await this._getReplicatorAndPerform(\n \"marking remote unlocked\",\n async (currentSettings, activeReplicator) =>\n await activeReplicator.markRemoteLocked(currentSettings, false, false)\n );\n }\n\n async markResolved(): Promise<void> {\n return await this._getReplicatorAndPerform(\n \"marking remote resolved\",\n async (currentSettings, activeReplicator) => await activeReplicator.markRemoteResolved(currentSettings)\n );\n }\n}\n","/** Stable machine values for provider capability availability. */\nexport const CAPABILITY_SUPPORT_KINDS = Object.freeze({\n SUPPORTED: \"supported\",\n NOT_IMPLEMENTED: \"not-implemented\",\n NOT_APPLICABLE: \"not-applicable\",\n} as const);\n\n/** Stable machine reasons for an unavailable provider capability. */\nexport const CAPABILITY_UNAVAILABLE_REASONS = Object.freeze({\n NOT_IMPLEMENTED: \"capability-not-implemented\",\n NOT_APPLICABLE: \"capability-not-applicable\",\n} as const);\n\n/** A declared role is available, but its implementation is not included. */\nexport type NotImplementedCapability = {\n readonly kind: typeof CAPABILITY_SUPPORT_KINDS.NOT_IMPLEMENTED;\n readonly reason: typeof CAPABILITY_UNAVAILABLE_REASONS.NOT_IMPLEMENTED;\n};\n\n/** A declared role does not apply to this provider. */\nexport type NotApplicableCapability = {\n readonly kind: typeof CAPABILITY_SUPPORT_KINDS.NOT_APPLICABLE;\n readonly reason: typeof CAPABILITY_UNAVAILABLE_REASONS.NOT_APPLICABLE;\n};\n\n/** One available capability paired with the only runner allowed to perform its role. */\nexport type SupportedCapability<TRole> = {\n readonly kind: typeof CAPABILITY_SUPPORT_KINDS.SUPPORTED;\n readonly run: TRole;\n};\n\n/** Provider capability declaration correlated with the role runner. */\nexport type CapabilitySupport<TRole> = SupportedCapability<TRole> | NotImplementedCapability | NotApplicableCapability;\n\nexport const CAPABILITY_NOT_IMPLEMENTED: NotImplementedCapability = Object.freeze({\n kind: CAPABILITY_SUPPORT_KINDS.NOT_IMPLEMENTED,\n reason: CAPABILITY_UNAVAILABLE_REASONS.NOT_IMPLEMENTED,\n});\n\nexport const CAPABILITY_NOT_APPLICABLE: NotApplicableCapability = Object.freeze({\n kind: CAPABILITY_SUPPORT_KINDS.NOT_APPLICABLE,\n reason: CAPABILITY_UNAVAILABLE_REASONS.NOT_APPLICABLE,\n});\n\n/** Declare one implemented provider capability without repeating its machine value. */\nexport function supportedCapability<TRole>(run: TRole): SupportedCapability<TRole> {\n return { kind: CAPABILITY_SUPPORT_KINDS.SUPPORTED, run };\n}\n","import type { RemoteDBSettings, ObsidianLiveSyncSettings, RemoteType } from \"@lib/common/types.ts\";\nimport type { ReplicatorInstance } from \"./ReplicatorInstance.ts\";\nimport { supportedCapability, type CapabilitySupport, type SupportedCapability } from \"./ProviderCapability.ts\";\nimport type { RemoteResourceCapabilities } from \"./RemoteResource.ts\";\nimport type { CentralRemoteAdministrationRunner } from \"./CentralRemoteAdministration.ts\";\nimport type { CentralCompatibilityRecoveryHint } from \"./CentralCompatibility.ts\";\n\nexport {\n CAPABILITY_NOT_APPLICABLE,\n CAPABILITY_NOT_IMPLEMENTED,\n CAPABILITY_SUPPORT_KINDS,\n CAPABILITY_UNAVAILABLE_REASONS,\n supportedCapability,\n} from \"./ProviderCapability.ts\";\nexport type {\n CapabilitySupport,\n NotApplicableCapability,\n NotImplementedCapability,\n SupportedCapability,\n} from \"./ProviderCapability.ts\";\n\n/**\n * A finite replication trigger which can run without opening a user dialogue.\n *\n * This is deliberately a closed list. Adding another automatic trigger must\n * make its lifecycle ownership visible at the call site and in the provider\n * contract rather than silently inheriting manual interaction permissions.\n */\nexport type UnattendedReplicationTrigger =\n | \"resume\"\n | \"periodic\"\n | \"database-event\"\n | \"editor-save\"\n | \"file-open\"\n | \"merge\"\n | \"daemon\";\n\n/** Automatic trigger which may start or resume a long-lived connection. */\nexport type ContinuousReplicationTrigger = \"resume\" | \"daemon\";\n\n/** No user interaction may be requested by an unattended replication path. */\nexport const NO_INTERACTION = Object.freeze({ kind: \"forbidden\" } as const);\n\n/**\n * The authority carried by a user-initiated replication command.\n *\n * The permissions are explicit so that a future caller can narrow an\n * operation without passing a broad boolean such as `showMessage` through\n * provider code. The common authority grants all currently supported user\n * actions.\n */\nexport const USER_INITIATED_REPLICATION_AUTHORITY = Object.freeze({\n kind: \"permitted\",\n permissions: Object.freeze({\n peerSelection: true,\n localPeerAdmission: true,\n configurationExchange: true,\n failureRecovery: true,\n }),\n} as const);\n\nexport type NoInteraction = typeof NO_INTERACTION;\n\n/** All interaction permissions understood by the current provider boundary. */\nexport interface InteractionPermissions {\n readonly peerSelection: boolean;\n readonly localPeerAdmission: boolean;\n readonly configurationExchange: boolean;\n readonly failureRecovery: boolean;\n}\n\n/**\n * A permitted authority must retain at least one explicit permission.\n *\n * This prevents an apparently user-authorised request from carrying an empty\n * permission set, while allowing a caller to veto or narrow individual\n * actions without introducing a second authority type.\n */\nexport type PermittedInteractionPermissions =\n | (InteractionPermissions & { readonly peerSelection: true })\n | (InteractionPermissions & { readonly localPeerAdmission: true })\n | (InteractionPermissions & { readonly configurationExchange: true })\n | (InteractionPermissions & { readonly failureRecovery: true });\n\nexport interface UserInitiatedReplicationAuthority {\n readonly kind: \"permitted\";\n readonly permissions: PermittedInteractionPermissions;\n}\n\nexport type ReplicationInteraction = NoInteraction | UserInitiatedReplicationAuthority;\n\n/** Authority carried through a replication request and its failure path. */\nexport type InteractionAuthority = ReplicationInteraction;\n\n/** Stable host presentation choices for routine OneShot progress. */\nexport const REPLICATION_PROGRESS_PRESENTATIONS = Object.freeze({\n QUIET: \"quiet\",\n NOTICE: \"notice\",\n} as const);\n\nexport type ReplicationProgressPresentation =\n (typeof REPLICATION_PROGRESS_PRESENTATIONS)[keyof typeof REPLICATION_PROGRESS_PRESENTATIONS];\n\n/**\n * A request made by an explicitly user-initiated one-shot command.\n *\n * Progress presentation is independent of interaction authority: a quiet\n * command may still open an authorised peer-selection or failure-recovery\n * dialogue when the operation requires a decision.\n */\nexport interface UserInitiatedOneShotRequest {\n readonly trigger: \"manual\";\n readonly progressPresentation: ReplicationProgressPresentation;\n readonly interaction: InteractionAuthority;\n}\n\n/** A request made by an automatic finite replication trigger. */\nexport interface UnattendedOneShotRequest {\n readonly trigger: UnattendedReplicationTrigger;\n readonly interaction: NoInteraction;\n}\n\n/** A request which starts a provider's long-lived/continuous operation. */\nexport interface ContinuousReplicationRequest {\n readonly trigger: ContinuousReplicationTrigger;\n readonly interaction: NoInteraction;\n}\n\n/** Stable reasons for which a provider role cannot be run. */\nexport type ReplicationBlockReason =\n | \"no-active-replicator\"\n | \"no-targets\"\n | \"not-ready\"\n | \"provider-not-composed\"\n | \"provider-not-configured\"\n | \"capability-not-implemented\"\n | \"capability-not-applicable\"\n | \"interaction-required\"\n | \"replication-in-progress\"\n | \"rate-limited\";\n\n/** A finite operation completed without a partial or failed result. */\nexport const REPLICATION_COMPLETED = Object.freeze({ status: \"completed\" } as const);\n\n/** A user-initiated operation was cancelled before it completed. */\nexport const REPLICATION_CANCELLED = Object.freeze({ status: \"cancelled\" } as const);\n\nexport type ReplicationCompleted = typeof REPLICATION_COMPLETED;\nexport type ReplicationCancelled = typeof REPLICATION_CANCELLED;\n\nexport type ReplicationBlocked = {\n readonly status: \"blocked\";\n readonly reason: ReplicationBlockReason;\n};\n\nexport type ReplicationPartial = {\n readonly status: \"partial\";\n readonly detail: unknown;\n};\n\nexport type ReplicationFailed = {\n readonly status: \"failed\";\n readonly error: unknown;\n readonly recoveryHint?: CentralCompatibilityRecoveryHint;\n};\n\n/**\n * Result of a typed replication role.\n *\n * `completed` is intentionally not represented by a truthy value from the\n * legacy `openReplication` method. Providers must opt into this singleton,\n * which keeps `false` and `void` observable as non-completion for finite work.\n */\nexport type ReplicationOutcome =\n | ReplicationCompleted\n | ReplicationCancelled\n | ReplicationBlocked\n | ReplicationPartial\n | ReplicationFailed;\n\n/** Preparation required before an ordinary operation may use a provider. */\nexport interface ReplicationReadinessRequirements {\n readonly centralRemotePreparation: \"required\" | \"provider-owned\" | \"not-applicable\";\n}\n\n/** Shared readiness contract for providers backed by the central remote. */\nexport const CENTRAL_REMOTE_REPLICATION_READINESS = Object.freeze({\n centralRemotePreparation: \"required\",\n} as const satisfies ReplicationReadinessRequirements);\n\n/** Central provider which prepares its Security Seed within each transfer. */\nexport const PROVIDER_OWNED_CENTRAL_REMOTE_REPLICATION_READINESS = Object.freeze({\n centralRemotePreparation: \"provider-owned\",\n} as const satisfies ReplicationReadinessRequirements);\n\n/** Shared readiness contract for peer-to-peer providers without a central remote. */\nexport const PEER_REPLICATION_READINESS = Object.freeze({\n centralRemotePreparation: \"not-applicable\",\n} as const satisfies ReplicationReadinessRequirements);\n\n/** Return whether a typed replication result represents completed work. */\nexport function isReplicationCompleted(outcome: ReplicationOutcome): outcome is ReplicationCompleted {\n return outcome.status === \"completed\";\n}\n\nexport function replicationBlocked(reason: ReplicationBlockReason): ReplicationBlocked {\n return { status: \"blocked\", reason };\n}\n\nexport function replicationFailed(error: unknown, recoveryHint?: CentralCompatibilityRecoveryHint): ReplicationFailed {\n return {\n status: \"failed\",\n error,\n ...(recoveryHint === undefined ? {} : { recoveryHint }),\n };\n}\n\nexport type UserInitiatedOneShotRunner = (\n replicator: ReplicatorInstance,\n setting: RemoteDBSettings,\n request: UserInitiatedOneShotRequest\n) => Promise<ReplicationOutcome>;\n\nexport type UnattendedOneShotRunner = (\n replicator: ReplicatorInstance,\n setting: RemoteDBSettings,\n request: UnattendedOneShotRequest\n) => Promise<ReplicationOutcome>;\n\n/**\n * Register a provider-owned Continuous task and settle its startup request.\n *\n * The runner must return after task ownership and pre-controller cancellation\n * have been registered. It must not retain the caller's active-publication\n * admission for the lifetime of the long-lived transfer.\n */\nexport type ContinuousRunner = (\n replicator: ReplicatorInstance,\n setting: RemoteDBSettings,\n request: ContinuousReplicationRequest\n) => Promise<ReplicationOutcome>;\n\n/**\n * Request cancellation of finite transfer work on the currently active\n * replicator. A `completed` outcome confirms that the stop request was\n * accepted; it does not claim rollback of work which had already settled.\n */\nexport type StopActiveTransferRunner = (replicator: ReplicatorInstance) => Promise<ReplicationOutcome>;\n\n/**\n * Opaque provider-owned projection of every setting which binds an active Replicator.\n * It is private comparison state and must not be logged, persisted, or displayed.\n */\nexport type ReplicatorConfigurationIdentity = string;\n\n/** One host-composed provider and every role which may use its active instance. */\nexport interface ReplicatorProviderDefinition<TKind extends RemoteType = RemoteType> {\n /** Canonical persisted remote kind used for provider selection. */\n readonly kind: TKind;\n /** Human-readable diagnostic label; never use it as a machine decision. */\n readonly diagnosticName: string;\n /** Preparation gates required before an ordinary replication role runs. */\n readonly readiness: ReplicationReadinessRequirements;\n /** Return whether the effective settings are sufficient to construct this provider. */\n readonly isConfigured: (setting: RemoteDBSettings) => boolean;\n /** Project the fully merged effective settings to this provider's stable binding identity. */\n readonly configurationIdentity: (setting: RemoteDBSettings) => ReplicatorConfigurationIdentity;\n /** Construct a replicator from the fully merged effective settings. */\n readonly create: (setting: ObsidianLiveSyncSettings) => Promise<ReplicatorInstance | undefined | false>;\n /** Exhaustive provider-owned catalogue for finite remote resources. */\n readonly remoteResources: RemoteResourceCapabilities;\n /** Optional provider-owned central-remote administration runner. */\n readonly centralRemoteAdministration?: CapabilitySupport<CentralRemoteAdministrationRunner>;\n /** Finite role carrying explicit user-interaction authority. */\n readonly userInitiatedOneShot: CapabilitySupport<UserInitiatedOneShotRunner>;\n /** Finite role which must not request user interaction. */\n readonly unattendedOneShot: CapabilitySupport<UnattendedOneShotRunner>;\n /** Explicit support decision for ordinary long-lived Continuous replication. */\n readonly continuous: CapabilitySupport<ContinuousRunner>;\n /** Bounded cancellation request for transfer work on the active instance. */\n readonly stopActiveTransfer: CapabilitySupport<StopActiveTransferRunner>;\n}\n\n/** The atomic provider, Replicator, and binding identity published by the owner service. */\nexport interface ActiveReplicatorContext<TKind extends RemoteType = RemoteType> {\n readonly provider: ReplicatorProviderDefinition<TKind>;\n readonly replicator: ReplicatorInstance;\n /** Private comparison state; callers must not log, persist, or display it. */\n readonly configurationIdentity: ReplicatorConfigurationIdentity;\n}\n\n/** Immutable source of one failed attempt, safe to carry after its reservation is released. */\nexport interface ReplicationAttemptFailure {\n readonly context: ActiveReplicatorContext;\n readonly setting: ObsidianLiveSyncSettings;\n readonly outcome: ReplicationFailed;\n}\n\n/** Immutable failure source plus presentation and interaction policy from its original request. */\nexport interface ReplicationFailureRequest extends ReplicationAttemptFailure {\n readonly progressPresentation: ReplicationProgressPresentation;\n readonly interaction: InteractionAuthority;\n}\n\n/** Return whether one detached setting still belongs to the admitted publication. */\nexport function isActiveReplicatorContextBoundToSetting(\n context: ActiveReplicatorContext,\n setting: RemoteDBSettings\n): boolean {\n try {\n return (\n setting.remoteType === context.provider.kind &&\n context.provider.isConfigured(setting) &&\n context.provider.configurationIdentity(setting) === context.configurationIdentity\n );\n } catch {\n // Invalid or partially edited settings must fail closed instead of\n // dispatching them through the previously bound Replicator.\n return false;\n }\n}\n\nexport type ReplicatorProviderDefinitionMap = ReadonlyMap<RemoteType, ReplicatorProviderDefinition>;\n\n/**\n * Define exactly the provider subset composed by a host.\n *\n * The tuple is the host's closed catalogue for this composition. The mapped\n * argument makes every selected kind required at compile time, while the\n * runtime checks reject duplicate, omitted, or extra definitions. A host can\n * therefore omit a provider intentionally, but cannot silently select a\n * partially defined provider.\n */\nexport function defineReplicatorProviderDefinitions<const TKind extends readonly RemoteType[]>(\n kinds: TKind,\n definitions: { readonly [K in TKind[number]]: ReplicatorProviderDefinition<K> }\n): ReplicatorProviderDefinitionMap {\n const selectedKinds = new Set<RemoteType>(kinds);\n if (selectedKinds.size !== kinds.length) {\n throw new Error(\"Replicator provider kinds must be unique.\");\n }\n\n if (Object.keys(definitions).length !== selectedKinds.size) {\n throw new Error(\"Replicator provider definitions must match the selected provider kinds.\");\n }\n\n const result = new Map<RemoteType, ReplicatorProviderDefinition>();\n for (const kind of kinds) {\n // TypeScript widens a value iterated from the generic tuple to its\n // `RemoteType` constraint. The mapped argument above still guarantees\n // this key, and the following runtime check protects JavaScript callers.\n const definition = definitions[kind as TKind[number]];\n if (!definition || definition.kind !== kind) {\n throw new Error(`Replicator provider definition does not match '${kind}'.`);\n }\n result.set(kind, definition);\n }\n return result;\n}\n\n/**\n * Convert a legacy `openReplication` result to the typed finite outcome.\n * `void` is not a success signal for a finite operation.\n */\nexport function outcomeFromFiniteOpenReplication(\n result: void | boolean,\n recoveryHint?: CentralCompatibilityRecoveryHint\n): ReplicationOutcome {\n return result === true\n ? REPLICATION_COMPLETED\n : replicationFailed(new Error(\"The provider did not complete finite replication.\"), recoveryHint);\n}\n\n/**\n * Convert a legacy `openReplication` result to a continuous-start outcome.\n * A provider which returns `void` has accepted the start request, whereas an\n * explicit `false` still reports a failed start.\n */\nexport function outcomeFromContinuousOpenReplication(result: void | boolean): ReplicationOutcome {\n return result === false\n ? replicationFailed(new Error(\"The provider rejected continuous replication.\"))\n : REPLICATION_COMPLETED;\n}\n\n/**\n * Adapt legacy `openReplication` for package and test compatibility.\n *\n * Current central providers use exact-outcome wrappers; this\n * adapter remains for consumers and tests which still expose the legacy role.\n */\nexport function supportedOpenReplicationOneShot(): SupportedCapability<UserInitiatedOneShotRunner> {\n return supportedCapability(async (replicator, setting, request) => {\n try {\n const result = await replicator.openReplication(\n setting,\n false,\n request.progressPresentation === REPLICATION_PROGRESS_PRESENTATIONS.NOTICE,\n false\n );\n return outcomeFromFiniteOpenReplication(result);\n } catch (error) {\n return replicationFailed(error);\n }\n });\n}\n\n/**\n * Adapt legacy `openReplication` for unattended package and test compatibility.\n *\n * Current central providers use exact-outcome wrappers; this\n * adapter remains for consumers and tests which still expose the legacy role.\n */\nexport function supportedOpenReplicationUnattended(): SupportedCapability<UnattendedOneShotRunner> {\n return supportedCapability(async (replicator, setting, request) => {\n if (request.interaction.kind !== NO_INTERACTION.kind) {\n return replicationBlocked(\"interaction-required\");\n }\n try {\n const result = await replicator.openReplication(setting, false, false, false);\n return outcomeFromFiniteOpenReplication(result);\n } catch (error) {\n return replicationFailed(error);\n }\n });\n}\n\nexport function supportedOpenReplicationContinuous(): SupportedCapability<ContinuousRunner> {\n return supportedCapability(async (replicator, setting, request) => {\n if (request.interaction.kind !== NO_INTERACTION.kind) {\n return replicationBlocked(\"interaction-required\");\n }\n try {\n const result = await replicator.openReplication(setting, true, false, false);\n return outcomeFromContinuousOpenReplication(result);\n } catch (error) {\n return replicationFailed(error);\n }\n });\n}\n\n/**\n * Adapt the legacy termination hook to the typed active-transfer capability.\n *\n * `terminateSync` is intentionally awaited even though existing replicators\n * implement it synchronously. This keeps the capability boundary valid for a\n * provider whose cancellation work needs to settle asynchronously.\n */\nexport function supportedStopActiveTransfer(): SupportedCapability<StopActiveTransferRunner> {\n return supportedCapability(async (replicator) => {\n try {\n await replicator.terminateSync();\n return REPLICATION_COMPLETED;\n } catch (error) {\n return replicationFailed(error);\n }\n });\n}\n","/** One ordered condition in a readiness evaluation. */\nexport interface ReadinessCondition<TContext> {\n /** Stable diagnostic name for the condition; it is not user-facing text. */\n readonly name: string;\n /**\n * Return whether this condition applies to the current evaluation.\n *\n * Applicability checks must be side-effect-free. Conditions without this\n * callback always apply.\n */\n readonly appliesTo?: (context: TContext) => boolean;\n /** Return whether the condition admits the requested operation. */\n readonly evaluate: (context: TContext) => boolean | Promise<boolean>;\n /** Perform condition-specific reporting after a false result. */\n readonly onRejected?: (context: TContext) => void | Promise<void>;\n}\n\n/** A purpose and its ordered readiness conditions. */\nexport interface ReadinessEvaluationRequest<TContext> {\n /** Stable diagnostic purpose; it is not user-facing text. */\n readonly purpose: string;\n readonly context: TContext;\n readonly conditions: readonly ReadinessCondition<TContext>[];\n}\n\n/** Structured result from an ordered readiness evaluation. */\nexport type ReadinessEvaluationResult =\n | { readonly ready: true; readonly purpose: string }\n | { readonly ready: false; readonly purpose: string; readonly rejectedCondition: string };\n\n/**\n * Evaluate applicable conditions in declaration order until one rejects.\n *\n * Rejection reporting completes before the result is returned. Exceptions\n * from applicability, evaluation, or reporting callbacks propagate unchanged;\n * the evaluator does not reinterpret operational failures as policy results.\n */\nexport async function evaluateReadiness<TContext>(\n request: ReadinessEvaluationRequest<TContext>\n): Promise<ReadinessEvaluationResult> {\n for (const condition of request.conditions) {\n if (condition.appliesTo && !condition.appliesTo(request.context)) continue;\n if (await condition.evaluate(request.context)) continue;\n await condition.onRejected?.(request.context);\n return {\n ready: false,\n purpose: request.purpose,\n rejectedCondition: condition.name,\n };\n }\n return { ready: true, purpose: request.purpose };\n}\n","import { LOG_LEVEL_INFO, LOG_LEVEL_NOTICE, type LOG_LEVEL, type ObsidianLiveSyncSettings } from \"@lib/common/types\";\nimport {\n CENTRAL_REMOTE_REPLICATION_READINESS,\n type ReplicationReadinessRequirements,\n} from \"@lib/replication/ReplicatorProvider.ts\";\nimport { MARK_LOG_NETWORK_ERROR, type LogFunction } from \"@lib/services/lib/logUtils\";\nimport type { MessageTranslator } from \"./MessageTranslator.ts\";\nimport { evaluateReadiness, type ReadinessCondition, type ReadinessEvaluationResult } from \"./ReadinessEvaluator.ts\";\n\n/** State and policy gates consulted without beginning remote preparation. */\nexport interface ReplicationReadinessGates {\n readonly isApplicationReady: () => boolean;\n readonly runPolicyChecks: (showMessage: boolean) => Promise<boolean>;\n readonly currentSettings: () => Pick<ObsidianLiveSyncSettings, \"versionUpFlash\">;\n readonly isCleanupRunning: () => boolean;\n readonly isOnline: () => boolean;\n}\n\n/** Ordered operational gates which may release or prepare replication work. */\nexport interface ReplicationReadinessPreparation {\n readonly commitPendingFileEvents: () => Promise<boolean>;\n readonly prepareCentralRemote: (showMessage: boolean) => Promise<boolean>;\n readonly runBeforeReplicate: (showMessage: boolean) => Promise<boolean>;\n}\n\n/** Diagnostic state, presentation, and unresolved-error output for readiness. */\nexport interface ReplicationReadinessDiagnostics {\n readonly getUnresolvedMessages: () => Promise<(string | Error)[][]>;\n readonly translate: MessageTranslator;\n readonly log: LogFunction;\n readonly showError: (message: string, maxLogLevel?: LOG_LEVEL) => void;\n readonly clearErrors: () => void;\n}\n\n/** Role-grouped collaborators for the common replication readiness sequence. */\nexport interface ReplicationReadinessDependencies {\n readonly gates: ReplicationReadinessGates;\n readonly preparation: ReplicationReadinessPreparation;\n readonly diagnostics: ReplicationReadinessDiagnostics;\n}\n\nexport interface ReplicationReadinessContext {\n readonly showMessage: boolean;\n readonly requirements: ReplicationReadinessRequirements;\n}\n\n/** Optional inputs accepted by the host-facing replication readiness evaluator. */\nexport interface ReplicationReadinessRequest {\n readonly showMessage?: boolean;\n readonly requirements?: ReplicationReadinessRequirements;\n}\n\nexport type ReplicationReadinessEvaluator = (\n context?: ReplicationReadinessRequest\n) => Promise<ReadinessEvaluationResult>;\n\n/**\n * Compose the ordered readiness conditions shared by replication entry points.\n *\n * The returned evaluator owns readiness decisions and their diagnostics only.\n * It does not acquire a Replicator, run provider capabilities, or account for\n * remote activity. Provider-specific preparation is selected by the supplied\n * requirements while the common conditions retain their declaration order.\n */\nexport function createReplicationReadinessEvaluator(\n dependencies: ReplicationReadinessDependencies\n): ReplicationReadinessEvaluator {\n const { diagnostics, gates, preparation } = dependencies;\n const reportPreparationFailure = async (): Promise<void> => {\n // A tagged network error already carries its specific diagnostic. Keep\n // the generic module-failure message informational in that case.\n const hasNetworkError = (await diagnostics.getUnresolvedMessages())\n .flat()\n .some((entry) => typeof entry == \"string\" && entry.includes(MARK_LOG_NETWORK_ERROR));\n const message = diagnostics.translate(\"Replicator.Message.SomeModuleFailed\");\n if (hasNetworkError) {\n diagnostics.log(message, LOG_LEVEL_INFO);\n } else {\n diagnostics.showError(message, LOG_LEVEL_NOTICE);\n }\n };\n\n const conditions: readonly ReadinessCondition<ReplicationReadinessContext>[] = [\n {\n name: \"application-ready\",\n evaluate: () => {\n if (gates.isApplicationReady()) return true;\n diagnostics.log(\"Replication is not ready because application initialisation has not completed.\");\n return false;\n },\n },\n {\n name: \"replication-policy-approved\",\n evaluate: ({ showMessage }) => gates.runPolicyChecks(showMessage),\n },\n {\n name: \"local-replication-state-ready\",\n evaluate: () => {\n // Preserve the established settings-read position: after host\n // policy approval and before cleanup-state evaluation.\n const currentSettings = gates.currentSettings();\n if (gates.isCleanupRunning()) {\n diagnostics.log(diagnostics.translate(\"Replicator.Message.Cleaned\"), LOG_LEVEL_NOTICE);\n return false;\n }\n if (currentSettings.versionUpFlash != \"\") {\n diagnostics.log(diagnostics.translate(\"Replicator.Message.VersionUpFlash\"), LOG_LEVEL_NOTICE);\n return false;\n }\n return true;\n },\n },\n {\n name: \"pending-file-events-committed\",\n evaluate: () => preparation.commitPendingFileEvents(),\n onRejected: () => {\n diagnostics.showError(diagnostics.translate(\"Replicator.Message.Pending\"), LOG_LEVEL_NOTICE);\n },\n },\n {\n name: \"network-online\",\n evaluate: () => gates.isOnline(),\n onRejected: ({ showMessage }) => {\n diagnostics.showError(\"Network is offline\", showMessage ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO);\n },\n },\n {\n name: \"central-remote-prepared\",\n appliesTo: ({ requirements }) => requirements.centralRemotePreparation === \"required\",\n evaluate: ({ showMessage }) => preparation.prepareCentralRemote(showMessage),\n onRejected: reportPreparationFailure,\n },\n {\n name: \"general-replication-prepared\",\n evaluate: ({ showMessage }) => preparation.runBeforeReplicate(showMessage),\n onRejected: reportPreparationFailure,\n },\n ];\n\n return async (context = {}) => {\n const result = await evaluateReadiness({\n purpose: \"replication\",\n context: {\n showMessage: context.showMessage ?? false,\n requirements: context.requirements ?? CENTRAL_REMOTE_REPLICATION_READINESS,\n },\n conditions,\n });\n if (result.ready) diagnostics.clearErrors();\n return result;\n };\n}\n","import type { ObsidianLiveSyncSettings } from \"@lib/common/types.ts\";\nimport {\n CAPABILITY_SUPPORT_KINDS,\n NO_INTERACTION,\n REPLICATION_PROGRESS_PRESENTATIONS,\n isActiveReplicatorContextBoundToSetting,\n replicationBlocked,\n replicationFailed,\n type ActiveReplicatorContext,\n type ContinuousReplicationRequest,\n type InteractionAuthority,\n type ReplicationFailureRequest,\n type ReplicationOutcome,\n type ReplicationProgressPresentation,\n type ReplicationReadinessRequirements,\n type UnattendedOneShotRequest,\n type UserInitiatedOneShotRequest,\n} from \"@lib/replication/ReplicatorProvider.ts\";\nimport type { IReplicatorService } from \"./IService.ts\";\nimport { asCopy } from \"@lib/common/utils.object.ts\";\n\n/** ReplicationService collaborators required to execute typed provider roles. */\nexport interface TypedReplicationCoordinatorDependencies {\n readonly replicatorService: Pick<\n IReplicatorService,\n | \"acquireActiveReplicatorContext\"\n | \"hasActiveReplicator\"\n | \"runWithActiveReplicatorContext\"\n | \"runFiniteReplicationActivity\"\n >;\n readonly currentSettings: () => ObsidianLiveSyncSettings;\n readonly checkReadiness: (showMessage: boolean, readiness: ReplicationReadinessRequirements) => Promise<boolean>;\n readonly handleFailure: (request: ReplicationFailureRequest) => Promise<boolean>;\n /**\n * Advance the host's finite-attempt clock after readiness admits dispatch.\n *\n * This includes a provider-declared blocked capability, because the legacy\n * service advanced its event rate-limit clock at the same boundary.\n */\n readonly recordFiniteAttempt: () => void;\n}\n\n/**\n * Execute typed provider capabilities against one captured active context.\n *\n * The coordinator owns capability selection, readiness dispatch, finite\n * activity accounting, and failure notification. It does not own event rate\n * limiting, legacy Replicator calls, or the active Replicator lifecycle.\n *\n * Each role is deliberately expressed as a separate control flow. Readiness,\n * interaction authority, activity accounting, and failure handling differ by\n * role, so a flag-driven capability table would conceal lifecycle decisions\n * which callers and reviewers need to see explicitly.\n */\nexport class TypedReplicationCoordinator {\n private oneShotInProgress = false;\n\n constructor(private readonly dependencies: TypedReplicationCoordinatorDependencies) {}\n\n /**\n * Execute a user-initiated finite role with the request's interaction authority.\n *\n * The active context is acquired atomically, readiness runs before\n * capability dispatch, and the settings snapshot is captured before the\n * finite activity begins. A failed result invokes recovery only after that\n * activity has settled.\n */\n async runUserInitiated(request: UserInitiatedOneShotRequest): Promise<ReplicationOutcome> {\n return await this.runOneShot(async () => {\n const showProgress = request.progressPresentation === REPLICATION_PROGRESS_PRESENTATIONS.NOTICE;\n const ready = await this.acquireReadyContext(showProgress);\n if (\"status\" in ready) return ready;\n\n const capability = ready.provider.userInitiatedOneShot;\n if (capability.kind !== CAPABILITY_SUPPORT_KINDS.SUPPORTED) {\n return this.finishFiniteAttempt(replicationBlocked(capability.reason));\n }\n const settings = Object.freeze(asCopy(this.dependencies.currentSettings()));\n return this.finishFiniteAttempt(\n await this.runAdmittedFiniteActivity(\n ready,\n (context) => capability.run(context.replicator, settings, request),\n settings,\n request.interaction,\n request.progressPresentation\n )\n );\n });\n }\n\n /**\n * Execute an unattended finite role without granting interaction authority.\n *\n * Requests carrying interaction authority are rejected before context\n * acquisition. Accepted requests otherwise retain the same readiness,\n * settings-snapshot, activity, and recovery ordering as user work.\n */\n async runUnattended(request: UnattendedOneShotRequest): Promise<ReplicationOutcome> {\n if (request.interaction.kind !== NO_INTERACTION.kind) {\n return replicationBlocked(\"interaction-required\");\n }\n return await this.runOneShot(async () => {\n const ready = await this.acquireReadyContext(false);\n if (\"status\" in ready) return ready;\n\n const capability = ready.provider.unattendedOneShot;\n if (capability.kind !== CAPABILITY_SUPPORT_KINDS.SUPPORTED) {\n return this.finishFiniteAttempt(replicationBlocked(capability.reason));\n }\n const settings = Object.freeze(asCopy(this.dependencies.currentSettings()));\n return this.finishFiniteAttempt(\n await this.runAdmittedFiniteActivity(\n ready,\n (context) => capability.run(context.replicator, settings, request),\n settings,\n NO_INTERACTION,\n REPLICATION_PROGRESS_PRESENTATIONS.QUIET\n )\n );\n });\n }\n\n /**\n * Start the provider's continuous role outside finite activity accounting.\n *\n * Capability applicability is established before readiness, because an\n * inapplicable long-lived role must not trigger unrelated preparation or\n * diagnostics. After readiness, the short startup call is admitted against\n * that exact publication. The provider owns the registered long-lived task\n * after startup settles; it does not retain this admission for its lifetime.\n * Startup failures become typed outcomes without invoking the finite-operation\n * recovery handler.\n */\n async startContinuous(request: ContinuousReplicationRequest): Promise<ReplicationOutcome> {\n if (request.interaction.kind !== NO_INTERACTION.kind) {\n return replicationBlocked(\"interaction-required\");\n }\n const context = await this.acquireContext();\n if (\"status\" in context) return context;\n\n // Capability support is checked before readiness so an inapplicable\n // role does not trigger unrelated probes or user-facing diagnostics.\n const capability = context.provider.continuous;\n if (capability.kind !== CAPABILITY_SUPPORT_KINDS.SUPPORTED) {\n return replicationBlocked(capability.reason);\n }\n const ready = await this.acquireReadyContext(false, context);\n if (\"status\" in ready) return ready;\n const setting = Object.freeze(asCopy(this.dependencies.currentSettings()));\n const admitted = await this.dependencies.replicatorService.runWithActiveReplicatorContext(\n async (activeContext) => {\n if (activeContext !== ready || !isActiveReplicatorContextBoundToSetting(activeContext, setting)) {\n return replicationBlocked(\"not-ready\");\n }\n try {\n return await capability.run(activeContext.replicator, setting, request);\n } catch (error) {\n return replicationFailed(error);\n }\n }\n );\n return admitted ?? replicationBlocked(\"no-active-replicator\");\n }\n\n /**\n * Request transfer cancellation on one atomically acquired active context.\n *\n * Cancellation deliberately bypasses readiness, activity accounting, and\n * failure-recovery handlers: it is an operator control over existing work,\n * not a request to begin new remote work.\n */\n async stopActiveTransfer(): Promise<ReplicationOutcome> {\n const context = await this.acquireContext();\n if (\"status\" in context) return context;\n\n const capability = context.provider.stopActiveTransfer;\n if (capability.kind !== CAPABILITY_SUPPORT_KINDS.SUPPORTED) {\n return replicationBlocked(capability.reason);\n }\n const admitted = await this.dependencies.replicatorService.runWithActiveReplicatorContext(\n async (activeContext) => {\n if (activeContext !== context) return replicationBlocked(\"not-ready\");\n try {\n return await capability.run(activeContext.replicator);\n } catch (error) {\n return replicationFailed(error);\n }\n }\n );\n return admitted ?? replicationBlocked(\"no-active-replicator\");\n }\n\n /**\n * Admit one complete typed OneShot attempt for this service instance.\n *\n * Ownership is recorded before the operation reaches its first await and is\n * retained through readiness, provider work, activity settlement, and\n * failure handling. Later requests are neither queued nor joined: they\n * settle immediately so repeated UI actions cannot replay after the owner.\n */\n private async runOneShot(run: () => Promise<ReplicationOutcome>): Promise<ReplicationOutcome> {\n if (this.oneShotInProgress) return replicationBlocked(\"replication-in-progress\");\n this.oneShotInProgress = true;\n try {\n return await run();\n } finally {\n this.oneShotInProgress = false;\n }\n }\n\n private finishFiniteAttempt(outcome: ReplicationOutcome): ReplicationOutcome {\n // The attempt clock advances after readiness even when the provider\n // declares the role unavailable; this preserves event-rate semantics.\n this.dependencies.recordFiniteAttempt();\n return outcome;\n }\n\n private async acquireContext(): Promise<ActiveReplicatorContext | ReplicationOutcome> {\n // Acquire the provider and Replicator atomically after queued ownership\n // transitions. Never combine a capability with a later Replicator.\n const context = await this.dependencies.replicatorService.acquireActiveReplicatorContext();\n if (context) return context;\n return this.dependencies.replicatorService.hasActiveReplicator()\n ? replicationBlocked(\"provider-not-composed\")\n : replicationBlocked(\"no-active-replicator\");\n }\n\n private async acquireReadyContext(\n showMessage: boolean,\n contextOverride?: ActiveReplicatorContext\n ): Promise<ActiveReplicatorContext | ReplicationOutcome> {\n const context = contextOverride ?? (await this.acquireContext());\n if (\"status\" in context) return context;\n if (!(await this.dependencies.checkReadiness(showMessage, context.provider.readiness))) {\n return replicationBlocked(\"not-ready\");\n }\n return context;\n }\n\n private async runFiniteActivity(run: () => Promise<ReplicationOutcome>): Promise<ReplicationOutcome> {\n try {\n return await this.dependencies.replicatorService.runFiniteReplicationActivity(run, {\n label: \"replication\",\n });\n } catch (error) {\n return replicationFailed(error);\n }\n }\n\n /**\n * Reserve the readiness-tested publication for provider dispatch.\n *\n * Readiness and settings capture intentionally happen before admission. If\n * an ownership transition completes in between, the newly admitted context\n * is rejected instead of running work prepared for an older publication.\n * Failure recovery runs only after the reservation has been released.\n */\n private async runAdmittedFiniteActivity(\n expectedContext: ActiveReplicatorContext,\n run: (context: ActiveReplicatorContext) => Promise<ReplicationOutcome>,\n setting: ObsidianLiveSyncSettings,\n interaction: InteractionAuthority,\n progressPresentation: ReplicationProgressPresentation\n ): Promise<ReplicationOutcome> {\n const admitted = await this.dependencies.replicatorService.runWithActiveReplicatorContext((context) => {\n if (context !== expectedContext || !isActiveReplicatorContextBoundToSetting(context, setting)) {\n return replicationBlocked(\"not-ready\");\n }\n return this.runFiniteActivity(() => run(context));\n });\n const result = admitted ?? replicationBlocked(\"no-active-replicator\");\n // Failure recovery starts only after both finite activity accounting\n // and publication admission have settled. It may queue lifecycle work\n // which must never wait on its own reservation.\n if (result.status === \"failed\") {\n await this.dependencies.handleFailure(\n Object.freeze({\n context: expectedContext,\n setting,\n outcome: result,\n progressPresentation,\n interaction,\n })\n );\n }\n return result;\n }\n}\n","import { ReplicationService } from \"@lib/services/base/ReplicationService\";\nimport type { ServiceContext } from \"@lib/services/base/ServiceBase\";\n\nexport class InjectableReplicationService<T extends ServiceContext> extends ReplicationService<T> {}\n","import type { ReplicatorInstance } from \"@lib/replication/ReplicatorInstance\";\nimport { firstResultFunction, handlers, type MultipleHandlerFunction } from \"@lib/services/lib/HandlerUtils\";\nimport type { IReplicatorService, ReplicatorFactoryCallback } from \"./IService\";\nimport { ServiceBase, type ServiceContext } from \"./ServiceBase\";\nimport type { SettingService } from \"./SettingService\";\nimport { createInstanceLogFunction } from \"@lib/services/lib/logUtils\";\nimport type { AppLifecycleService } from \"./AppLifecycleService\";\nimport { UnresolvedErrorManager } from \"./UnresolvedErrorManager\";\nimport { yieldMicrotask } from \"octagonal-wheels/promises\";\nimport type { DatabaseEventService } from \"./DatabaseEventService\";\nimport { LOG_LEVEL_NOTICE, LOG_LEVEL_VERBOSE } from \"@lib/common/logger\";\nimport { DEFAULT_REPLICATION_STATICS } from \"@lib/common/models/shared.definition\";\nimport { reactiveSource } from \"octagonal-wheels/dataobject/reactive\";\nimport {\n runWithOptionalActivity,\n type AsyncActivityOptions,\n type AsyncActivityRunner,\n} from \"@lib/interfaces/AsyncActivityRunner.ts\";\nimport type {\n ActiveReplicatorContext,\n ReplicatorProviderDefinition,\n ReplicatorProviderDefinitionMap,\n} from \"@lib/replication/ReplicatorProvider.ts\";\nimport { CAPABILITY_SUPPORT_KINDS } from \"@lib/replication/ProviderCapability.ts\";\nimport type { ObsidianLiveSyncSettings, RemoteDBSettings } from \"@lib/common/types.ts\";\nimport {\n ActiveReplicatorState,\n type ActiveReplicatorPublication,\n type ActiveReplicatorRetirement,\n} from \"./ReplicatorService.activeReplicatorState.ts\";\nimport type { RemoteResourceKind, RemoteResourceMap } from \"@lib/replication/RemoteResource.ts\";\nimport { resolveRemoteResource } from \"./ReplicatorService.remoteResourceResolver.ts\";\nimport type {\n CentralRemoteAdministrationRequest,\n CentralRemoteAdministrationResult,\n} from \"@lib/replication/CentralRemoteAdministration.ts\";\nimport { runCentralRemoteAdministrationWithContext } from \"./ReplicatorService.centralRemoteAdministration.ts\";\nimport { asCopy } from \"@lib/common/utils.object.ts\";\n\nexport interface ReplicatorServiceDependencies {\n settingService: SettingService;\n appLifecycleService: AppLifecycleService;\n databaseEventService: DatabaseEventService;\n activityRunner?: AsyncActivityRunner;\n registerLifecycleHandlers?: boolean;\n}\n/**\n * Own the active Replicator publication and its serialised lifecycle transitions.\n *\n * This service composes provider definitions, retires active instances when\n * their configuration identity changes, and publishes the provider and\n * Replicator atomically. Remote administration is dispatched through the\n * admitted active context; `ReplicationService` owns synchronisation\n * readiness and replication dispatch.\n */\nexport abstract class ReplicatorService<T extends ServiceContext = ServiceContext>\n extends ServiceBase<T>\n implements IReplicatorService\n{\n readonly boundedRemoteActivityCount = reactiveSource(0);\n readonly finiteReplicationActivityCount = reactiveSource(0);\n _log = createInstanceLogFunction(\"ReplicatorService\");\n\n private settingService: SettingService;\n private databaseEventService: DatabaseEventService;\n private readonly _activeReplicatorState = new ActiveReplicatorState();\n private _providerDefinitions = new Map<ReplicatorProviderDefinition[\"kind\"], ReplicatorProviderDefinition>();\n private _transition: Promise<unknown> = Promise.resolve();\n private appLifecycleService: AppLifecycleService;\n _unresolvedErrorManager: UnresolvedErrorManager;\n constructor(\n context: T,\n protected dependencies: ReplicatorServiceDependencies\n ) {\n super(context);\n this.appLifecycleService = dependencies.appLifecycleService;\n this._unresolvedErrorManager = new UnresolvedErrorManager(\n dependencies.appLifecycleService,\n this.context.events\n );\n this.settingService = dependencies.settingService;\n this.databaseEventService = dependencies.databaseEventService;\n if (dependencies.registerLifecycleHandlers ?? true) {\n this.settingService.onRealiseSetting.addHandler(this._initialiseReplicator.bind(this));\n this.databaseEventService.onDatabaseInitialisation.addHandler(this.onCloseActiveReplication.bind(this));\n this.databaseEventService.onDatabaseInitialised.addHandler(this.reinitialiseReplicator.bind(this));\n this.databaseEventService.onDatabaseHasReady.addHandler(this.reinitialiseReplicator.bind(this));\n this.appLifecycleService.onSuspending.addHandler(this.suspendReplication.bind(this));\n this.appLifecycleService.onUnload.addHandler(this.onCloseActiveReplication.bind(this));\n }\n }\n\n /**\n * Runs one finite remote operation while exposing its lifetime to host policy and status UI.\n * Continuous replication must not use this boundary.\n */\n async runBoundedRemoteActivity<TValue>(\n task: () => TValue | PromiseLike<TValue>,\n options?: AsyncActivityOptions\n ): Promise<TValue> {\n return await this.runRemoteActivity(task, options, false);\n }\n\n /** Runs one finite replication and exposes its document-delivery lifetime. */\n async runFiniteReplicationActivity<TValue>(\n task: () => TValue | PromiseLike<TValue>,\n options?: AsyncActivityOptions\n ): Promise<TValue> {\n return await this.runRemoteActivity(task, options, true);\n }\n\n private async runRemoteActivity<TValue>(\n task: () => TValue | PromiseLike<TValue>,\n options: AsyncActivityOptions | undefined,\n isFiniteReplication: boolean\n ): Promise<TValue> {\n this.boundedRemoteActivityCount.value++;\n if (isFiniteReplication) {\n this.finiteReplicationActivityCount.value++;\n }\n try {\n return await runWithOptionalActivity(this.dependencies.activityRunner, task, options);\n } finally {\n if (isFiniteReplication) {\n this.finiteReplicationActivityCount.value--;\n }\n this.boundedRemoteActivityCount.value--;\n }\n }\n\n /** Request a reversible transfer stop without retiring the active publication. */\n private async suspendReplication(): Promise<boolean> {\n return await this.enqueueTransition(async () => {\n // Suspension can precede Replicator initialisation during settings\n // migration. An absent publication is therefore an ordinary no-op.\n const publication = this._activeReplicatorState.current;\n if (publication) {\n await this.requestPublicationTransferStop(publication, \"suspension\");\n }\n return true;\n });\n }\n\n private async reinitialiseReplicator() {\n return await this.enqueueTransition(async () => {\n await this.disposeReplicatorNow();\n await yieldMicrotask();\n return await this.initialiseReplicatorNow();\n });\n }\n /** Request transfer cancellation for either a reversible pause or terminal retirement. */\n private async requestPublicationTransferStop(\n publication: ActiveReplicatorPublication,\n reason: \"retirement\" | \"suspension\"\n ): Promise<void> {\n try {\n const capability = publication.context?.provider.stopActiveTransfer;\n if (capability?.kind === CAPABILITY_SUPPORT_KINDS.SUPPORTED) {\n const outcome = await capability.run(publication.replicator);\n if (outcome.status !== \"completed\") {\n this._log(\n `Active Replicator transfer stop settled as '${outcome.status}' during ${reason}.`,\n LOG_LEVEL_VERBOSE\n );\n }\n return;\n }\n if (!publication.context) {\n await Promise.resolve(publication.replicator.terminateSync());\n }\n } catch (error) {\n // Retirement still proceeds to physical close when a cooperative\n // stop fails. Suspension keeps the publication for later resumption.\n this._log(`Failed to request active Replicator transfer cancellation during ${reason}.`, LOG_LEVEL_VERBOSE);\n this._log(error, LOG_LEVEL_VERBOSE);\n }\n }\n\n /** Fence new work, request cancellation, and drain only this publication's admitted tasks. */\n private async quiesceActiveReplicator(): Promise<ActiveReplicatorRetirement | undefined> {\n const retirement = this._activeReplicatorState.beginRetirement();\n if (!retirement) return undefined;\n\n await this.requestPublicationTransferStop(retirement.publication, \"retirement\");\n await retirement.waitForDemandSettlement();\n return retirement;\n }\n\n /** Close one drained publication and release its private retirement state. */\n private async closeRetiringReplicator(retirement: ActiveReplicatorRetirement): Promise<void> {\n await Promise.resolve(retirement.publication.replicator.closeReplication());\n retirement.complete();\n }\n\n private async disposeReplicatorNow(reason?: \"configuration transition\") {\n const retirement = await this.quiesceActiveReplicator();\n if (!retirement) return true;\n this._log(\n reason === \"configuration transition\"\n ? \"Configuration changed, closing active replicator.\"\n : \"Closing active replicator.\"\n );\n await this.closeRetiringReplicator(retirement);\n return true;\n }\n\n private async discardFailedReplicator(replicator: ReplicatorInstance): Promise<void> {\n try {\n await Promise.resolve(replicator.closeReplication());\n } catch (error) {\n this._log(\"Failed to close a replicator after its initialisation failed.\", LOG_LEVEL_VERBOSE);\n this._log(error, LOG_LEVEL_VERBOSE);\n }\n }\n\n private enqueueTransition<TResult>(operation: () => Promise<TResult>): Promise<TResult> {\n // A failed transition must not poison the queue. Later lifecycle events\n // still need an ordered opportunity to retire or construct an owner.\n const transition = this._transition.then(operation, operation);\n this._transition = transition.then(\n (): undefined => undefined,\n (): undefined => undefined\n );\n return transition;\n }\n\n private async _initialiseReplicator() {\n return await this.enqueueTransition(() => this.initialiseReplicatorNow());\n }\n\n private getProviderDefinition(\n setting: Pick<RemoteDBSettings, \"remoteType\">\n ): ReplicatorProviderDefinition | undefined {\n return this._providerDefinitions.get(setting.remoteType);\n }\n\n private async createReplicator(\n settingOverride: Partial<ObsidianLiveSyncSettings> = {}\n ): Promise<ReplicatorInstance | undefined | false> {\n const currentSettings = this.settingService.currentSettings();\n const setting = { ...currentSettings, ...settingOverride };\n return await this.createReplicatorForSetting(setting, settingOverride);\n }\n\n private async createReplicatorForSetting(\n setting: ObsidianLiveSyncSettings,\n legacySettingOverride: Partial<ObsidianLiveSyncSettings> = {}\n ): Promise<ReplicatorInstance | undefined | false> {\n const provider = this.getProviderDefinition(setting);\n if (provider) {\n return await provider.create(setting);\n }\n return await this.legacyGetNewReplicator(legacySettingOverride);\n }\n\n private isCurrentProviderConfiguration(\n provider: ReplicatorProviderDefinition,\n configurationIdentity: string\n ): boolean {\n // Re-read effective settings at the publication boundary. Candidate\n // construction and host preparation may both have yielded meanwhile.\n const currentSetting = this.settingService.currentSettings();\n return (\n !!currentSetting &&\n this.getProviderDefinition(currentSetting) === provider &&\n provider.isConfigured(currentSetting) &&\n provider.configurationIdentity(currentSetting) === configurationIdentity\n );\n }\n\n private publishActiveReplicator(\n provider: ReplicatorProviderDefinition | undefined,\n replicator: ReplicatorInstance,\n replicatorType: string,\n configurationIdentity: string | undefined\n ): void {\n this._activeReplicatorState.publish(provider, replicator, replicatorType, configurationIdentity);\n }\n\n private async initialiseReplicatorNow() {\n const message = this.context.translate(\"Replicator.Message.InitialiseFatalError\");\n const setting = this.settingService.currentSettings();\n if (!setting) {\n await this.disposeReplicatorNow(\"configuration transition\");\n // Settings may not be available yet during early lifecycle.\n // Do not treat this as a fatal initialisation failure.\n this._unresolvedErrorManager.clearError(message);\n return true;\n }\n const replicatorType = setting.remoteType;\n const provider = this.getProviderDefinition(setting);\n let hasReplicatorConfig: boolean;\n let configurationIdentity: string | undefined;\n try {\n hasReplicatorConfig = provider ? provider.isConfigured(setting) : this._providerDefinitions.size === 0;\n configurationIdentity =\n provider && hasReplicatorConfig ? provider.configurationIdentity(setting) : undefined;\n } catch (error) {\n await this.disposeReplicatorNow(\"configuration transition\");\n this._unresolvedErrorManager.showError(message, LOG_LEVEL_NOTICE);\n throw error;\n }\n\n if (!hasReplicatorConfig) {\n // Configuration changes are transitions too: fence and close an old\n // transport before forgetting it, rather than orphaning its listeners.\n await this.disposeReplicatorNow(\"configuration transition\");\n this._unresolvedErrorManager.clearError(message);\n this._log(\"No remote replicator configuration found. Skipping replicator initialisation.\");\n return true;\n }\n\n const activePublication = this._activeReplicatorState.current;\n const isSameProvider =\n replicatorType === activePublication?.replicatorType &&\n (!provider || activePublication.context?.provider === provider);\n if (\n isSameProvider &&\n (!provider || configurationIdentity === activePublication?.context?.configurationIdentity)\n ) {\n // No need to change the replicator.\n this._unresolvedErrorManager.clearError(message);\n this._log(\"Active replicator has been kept\", LOG_LEVEL_VERBOSE);\n return true;\n } else {\n this._log(\"Acquiring new replicator\");\n await this.disposeReplicatorNow(\"configuration transition\");\n if (activePublication) {\n this._log(\"Active replicator closed\", LOG_LEVEL_VERBOSE);\n }\n const newReplicator = await this.createReplicatorForSetting(setting);\n if (!newReplicator) {\n this._unresolvedErrorManager.showError(message, LOG_LEVEL_NOTICE);\n return false;\n }\n\n // Reset replication statics when replicator changes.\n this.replicationStatics.value = { ...DEFAULT_REPLICATION_STATICS };\n await yieldMicrotask();\n // Host preparation clears state such as cached key-derivation\n // parameters before this candidate can become active.\n try {\n if (!(await newReplicator.initializeDatabaseForReplication())) {\n this._log(\"Failed to initialise the replicator's local node information.\");\n await this.discardFailedReplicator(newReplicator);\n this._unresolvedErrorManager.showError(message, LOG_LEVEL_NOTICE);\n return false;\n }\n if (!(await this.onBeforeReplicatorPublication())) {\n this._log(\n \"Failed to initialise the replicator, onBeforeReplicatorPublication reported some problems.\"\n );\n await this.discardFailedReplicator(newReplicator);\n this._unresolvedErrorManager.showError(message, LOG_LEVEL_NOTICE);\n return false;\n }\n if (\n provider &&\n (configurationIdentity === undefined ||\n !this.isCurrentProviderConfiguration(provider, configurationIdentity))\n ) {\n await this.discardFailedReplicator(newReplicator);\n this._unresolvedErrorManager.clearError(message);\n this._log(\n \"Discarded a replicator whose configuration changed before publication.\",\n LOG_LEVEL_VERBOSE\n );\n return true;\n }\n } catch (error) {\n await this.discardFailedReplicator(newReplicator);\n this._unresolvedErrorManager.showError(message, LOG_LEVEL_NOTICE);\n throw error;\n }\n this.publishActiveReplicator(provider, newReplicator, replicatorType, configurationIdentity);\n const remoteTypeDisplay = provider?.diagnosticName ?? (replicatorType || \"CouchDB\");\n this._log(`Replicator (${remoteTypeDisplay}) initialised and activated`, LOG_LEVEL_VERBOSE);\n\n this._unresolvedErrorManager.clearError(message);\n return true;\n }\n }\n\n /**\n * Fence new work, drain admitted work, and close the active Replicator.\n *\n * The command is serialised with every other ownership transition. Callers\n * must not await it from inside `runWithActiveReplicatorContext()`, because\n * retirement waits for that admitted callback to settle.\n */\n async onCloseActiveReplication(): Promise<boolean> {\n return await this.enqueueTransition(() => this.disposeReplicatorNow());\n }\n\n /**\n * Get a new replicator instance based on the provided settings.\n */\n private readonly legacyGetNewReplicator = firstResultFunction<ReplicatorFactoryCallback>(\"getNewReplicator\");\n\n readonly getNewReplicator: MultipleHandlerFunction<ReplicatorFactoryCallback> = Object.assign(\n async (settingOverride: Partial<ObsidianLiveSyncSettings> = {}) => await this.createReplicator(settingOverride),\n {\n addHandler: (callback: ReplicatorFactoryCallback) => this.legacyGetNewReplicator.addHandler(callback),\n removeHandler: (callback: ReplicatorFactoryCallback) => this.legacyGetNewReplicator.removeHandler(callback),\n }\n );\n\n registerReplicatorProviderDefinitions(definitions: ReplicatorProviderDefinitionMap): void {\n for (const [kind, definition] of definitions) {\n const existing = this._providerDefinitions.get(kind);\n if (existing && existing !== definition) {\n throw new Error(`Replicator provider '${kind}' is already composed.`);\n }\n this._providerDefinitions.set(kind, definition);\n }\n }\n\n /**\n * Return a non-owning synchronous view for lifecycle diagnostics and focused tests.\n *\n * Production work must use an admitted acquisition or callback boundary so that\n * the context cannot be retired while it is in use.\n */\n protected inspectActiveReplicatorContext(): ActiveReplicatorContext | undefined {\n return this._activeReplicatorState.current?.context;\n }\n\n async createRemoteResource<TKind extends RemoteResourceKind>(\n kind: TKind,\n setting: RemoteDBSettings\n ): Promise<RemoteResourceMap[TKind] | undefined> {\n const provider = this.getProviderDefinition(setting);\n if (!provider || !provider.isConfigured(setting)) {\n return undefined;\n }\n return await resolveRemoteResource(provider.remoteResources, kind, setting);\n }\n\n /** Apply and verify one provider-declared action before permitting a later switch. */\n async runCentralRemoteAdministration(\n request: CentralRemoteAdministrationRequest\n ): Promise<CentralRemoteAdministrationResult> {\n const setting = asCopy(this.settingService.currentSettings());\n const result = await this.runWithActiveReplicatorContext((context) =>\n runCentralRemoteAdministrationWithContext(context, setting, request)\n );\n return result ?? (await runCentralRemoteAdministrationWithContext(undefined, setting, request));\n }\n\n async acquireActiveReplicatorContext(): Promise<ActiveReplicatorContext | undefined> {\n // A transition may enqueue another transition while settling. Return\n // only after the observed promise is still the tail of the queue.\n while (true) {\n const transition = this._transition;\n await transition;\n if (transition === this._transition) {\n return this._activeReplicatorState.current?.context;\n }\n }\n }\n\n /**\n * Admit one callback against the publication ordered before later transitions.\n *\n * Release never enters the transition queue. The callback must not initiate\n * or await a settings, database, or Replicator lifecycle transition which\n * would wait for this same reservation.\n */\n async runWithActiveReplicatorContext<TResult>(\n task: (context: ActiveReplicatorContext) => TResult | PromiseLike<TResult>\n ): Promise<TResult | undefined> {\n const reservation = await this.enqueueTransition(async () => this._activeReplicatorState.reserve());\n if (!reservation) return undefined;\n\n try {\n return await task(reservation.context);\n } finally {\n reservation.release();\n }\n }\n\n readonly onBeforeReplicatorPublication = handlers<IReplicatorService>().bailFirstFailure(\n \"onBeforeReplicatorPublication\"\n );\n\n /**\n * Return the legacy unreserved view of the active Replicator.\n *\n * Missing active state retains its established Notice-level diagnostic.\n * New work must acquire or admit an `ActiveReplicatorContext` instead.\n */\n getActiveReplicator(): ReplicatorInstance | undefined {\n const message = \"No replicator has been activated or has not been initialised yet.\";\n const activeReplicator = this._activeReplicatorState.current?.replicator;\n if (!activeReplicator) {\n this._unresolvedErrorManager.showError(message, LOG_LEVEL_NOTICE);\n return undefined;\n }\n this._unresolvedErrorManager.clearError(message);\n return activeReplicator;\n }\n\n /**\n * Classify whether a compatibility active Replicator exists without\n * acquiring or returning it.\n *\n * This side-effect-free, non-owning predicate exists only for\n * compatibility-state classification. Work must acquire or admit an\n * `ActiveReplicatorContext` before using a Replicator.\n */\n hasActiveReplicator(): boolean {\n return this._activeReplicatorState.current !== undefined;\n }\n\n replicationStatics = reactiveSource({ ...DEFAULT_REPLICATION_STATICS });\n}\n","/** Options attached to one bounded asynchronous activity. */\nexport interface AsyncActivityOptions {\n /** An optional diagnostic label supplied to the activity owner. */\n label?: string;\n}\n\n/**\n * Runs bounded asynchronous work inside a consumer-owned activity scope.\n *\n * The common library deliberately does not prescribe what the scope does. A\n * browser host may keep the screen awake, while a headless host may omit the\n * runner and execute the task directly.\n */\nexport interface AsyncActivityRunner {\n /** Runs the task and returns its result without changing its error semantics. */\n run<T>(task: () => T | PromiseLike<T>, options?: AsyncActivityOptions): Promise<T>;\n}\n\n/** Runs a task through the injected activity owner, or directly when none is supplied. */\nexport async function runWithOptionalActivity<T>(\n runner: AsyncActivityRunner | undefined,\n task: () => T | PromiseLike<T>,\n options?: AsyncActivityOptions\n): Promise<T> {\n if (runner) return await runner.run(task, options);\n return await task();\n}\n","import type { ReplicatorInstance } from \"@lib/replication/ReplicatorInstance\";\nimport type { ActiveReplicatorContext, ReplicatorProviderDefinition } from \"@lib/replication/ReplicatorProvider\";\n\n/** Atomic service publication used as both the active view and generation identity. */\nexport interface ActiveReplicatorPublication {\n readonly replicator: ReplicatorInstance;\n readonly replicatorType: string;\n readonly context: ActiveReplicatorContext | undefined;\n}\n\n/** One admitted use of an exact active publication. */\nexport interface ActiveReplicatorReservation {\n readonly context: ActiveReplicatorContext;\n /** Release this reservation. Repeated calls have no effect. */\n release(): void;\n}\n\n/** Private service-side control over one fenced publication. */\nexport interface ActiveReplicatorRetirement {\n readonly publication: ActiveReplicatorPublication;\n /** Wait until every use admitted before the fence has settled. */\n waitForDemandSettlement(): Promise<void>;\n /** Mark physical close complete. Repeated calls have no effect. */\n complete(): void;\n}\n\nclass ActiveReplicatorPublicationOwner {\n private accepting = true;\n private demandCount = 0;\n private demandSettlement: Promise<void> | undefined;\n private settleDemand: (() => void) | undefined;\n\n constructor(readonly publication: ActiveReplicatorPublication) {}\n\n reserve(): ActiveReplicatorReservation | undefined {\n const context = this.publication.context;\n if (!this.accepting || !context) {\n return undefined;\n }\n\n this.demandCount++;\n let released = false;\n return {\n context,\n release: () => {\n if (released) return;\n released = true;\n this.demandCount--;\n if (this.demandCount === 0) {\n this.settleDemand?.();\n this.settleDemand = undefined;\n }\n },\n };\n }\n\n stopAccepting(): void {\n this.accepting = false;\n }\n\n waitForDemandSettlement(): Promise<void> {\n if (this.demandCount === 0) {\n return Promise.resolve();\n }\n this.demandSettlement ??= new Promise<void>((resolve) => {\n this.settleDemand = resolve;\n });\n return this.demandSettlement;\n }\n\n get hasDemand(): boolean {\n return this.demandCount !== 0;\n }\n}\n\n/**\n * Keep active publication, admission, and quiescing retirement as one state.\n *\n * The publication object itself is the generation identity. Retirement first\n * removes it from `current`, then waits only for reservations captured from\n * that object. A replacement cannot be published until physical retirement is\n * explicitly completed.\n */\nexport class ActiveReplicatorState {\n private activeOwner: ActiveReplicatorPublicationOwner | undefined;\n private retiringOwner: ActiveReplicatorPublicationOwner | undefined;\n private retirement: ActiveReplicatorRetirement | undefined;\n\n get current(): ActiveReplicatorPublication | undefined {\n return this.activeOwner?.publication;\n }\n\n publish(\n provider: ReplicatorProviderDefinition | undefined,\n replicator: ReplicatorInstance,\n replicatorType: string,\n configurationIdentity: string | undefined\n ): void {\n if (this.activeOwner) {\n throw new Error(\"Cannot replace an active Replicator without beginning retirement.\");\n }\n if (this.retiringOwner) {\n throw new Error(\"Cannot publish an active Replicator before retirement has completed.\");\n }\n this.activeOwner = new ActiveReplicatorPublicationOwner({\n replicator,\n replicatorType,\n context:\n provider && configurationIdentity !== undefined\n ? { provider, replicator, configurationIdentity }\n : undefined,\n });\n }\n\n /** Reserve the current typed publication, or reject admission while quiescing. */\n reserve(): ActiveReplicatorReservation | undefined {\n return this.activeOwner?.reserve();\n }\n\n /**\n * Fence the current publication and begin its explicit quiescing transition.\n *\n * Completion is separate from demand settlement so callers cannot publish a\n * replacement between draining admitted work and physically closing the old\n * Replicator.\n */\n beginRetirement(): ActiveReplicatorRetirement | undefined {\n if (this.retirement) return this.retirement;\n\n const owner = this.activeOwner;\n if (!owner) return undefined;\n\n owner.stopAccepting();\n this.activeOwner = undefined;\n this.retiringOwner = owner;\n let completed = false;\n const retirement: ActiveReplicatorRetirement = {\n publication: owner.publication,\n waitForDemandSettlement: () => owner.waitForDemandSettlement(),\n complete: () => {\n if (completed) return;\n if (owner.hasDemand) {\n throw new Error(\"Cannot complete active Replicator retirement while admitted work remains.\");\n }\n if (this.retiringOwner !== owner) {\n throw new Error(\"Active Replicator retirement no longer owns the quiescing state.\");\n }\n completed = true;\n this.retiringOwner = undefined;\n this.retirement = undefined;\n },\n };\n this.retirement = retirement;\n return retirement;\n }\n}\n","import type { RemoteDBSettings } from \"@lib/common/types.ts\";\nimport { CAPABILITY_SUPPORT_KINDS } from \"@lib/replication/ProviderCapability.ts\";\nimport type {\n RemoteResourceCapabilities,\n RemoteResourceKind,\n RemoteResourceMap,\n} from \"@lib/replication/RemoteResource.ts\";\n\n/** Resolve one ReplicatorService-owned finite resource without adding a method per role. */\nexport async function resolveRemoteResource<TKind extends RemoteResourceKind>(\n capabilities: RemoteResourceCapabilities,\n kind: TKind,\n setting: RemoteDBSettings\n): Promise<RemoteResourceMap[TKind] | undefined> {\n const capability = capabilities[kind];\n if (capability.kind !== CAPABILITY_SUPPORT_KINDS.SUPPORTED) {\n return undefined;\n }\n return await capability.run(setting);\n}\n","import type { RemoteDBSettings } from \"@lib/common/types.ts\";\nimport { CAPABILITY_UNAVAILABLE_REASONS } from \"./ProviderCapability.ts\";\nimport type { ReplicatorInstance } from \"./ReplicatorInstance.ts\";\n\n/** Stable machine identifiers for central-remote administration mutations. */\nexport const CENTRAL_REMOTE_ADMINISTRATION_ACTIONS = Object.freeze({\n MARK_RESOLVED: \"mark-resolved\",\n LOCK: \"lock\",\n UNLOCK: \"unlock\",\n} as const);\n\n/** Stable machine identifiers for central-remote administration settlement. */\nexport const CENTRAL_REMOTE_ADMINISTRATION_RESULT_STATUSES = Object.freeze({\n VERIFIED: \"verified\",\n VERIFICATION_FAILED: \"verification-failed\",\n} as const);\n\n/** Stable machine identifiers for provider-specific observations. */\nexport const CENTRAL_REMOTE_ADMINISTRATION_OBSERVATION_KINDS = Object.freeze({\n MILESTONE: \"milestone\",\n} as const);\n\n/** Stable machine reasons which must not be used as display or translation keys. */\nexport const CENTRAL_REMOTE_ADMINISTRATION_FAILURE_REASONS = Object.freeze({\n NO_ACTIVE_REPLICATOR: \"no-active-replicator\",\n ACTIVE_CONFIGURATION_MISMATCH: \"active-configuration-mismatch\",\n CAPABILITY_NOT_IMPLEMENTED: CAPABILITY_UNAVAILABLE_REASONS.NOT_IMPLEMENTED,\n CAPABILITY_NOT_APPLICABLE: CAPABILITY_UNAVAILABLE_REASONS.NOT_APPLICABLE,\n LOCAL_IDENTITY_UNAVAILABLE: \"local-identity-unavailable\",\n CONNECTION_FAILED: \"connection-failed\",\n MILESTONE_NOT_FOUND: \"milestone-not-found\",\n MILESTONE_READ_FAILED: \"milestone-read-failed\",\n POSTCONDITION_MISMATCH: \"postcondition-mismatch\",\n} as const);\n\nexport type CentralRemoteAdministrationAction =\n (typeof CENTRAL_REMOTE_ADMINISTRATION_ACTIONS)[keyof typeof CENTRAL_REMOTE_ADMINISTRATION_ACTIONS];\nexport type CentralRemoteAdministrationFailureReason =\n (typeof CENTRAL_REMOTE_ADMINISTRATION_FAILURE_REASONS)[keyof typeof CENTRAL_REMOTE_ADMINISTRATION_FAILURE_REASONS];\n\n/** One requested mutation of the central milestone protocol. */\nexport interface CentralRemoteAdministrationRequest {\n readonly action: CentralRemoteAdministrationAction;\n}\n\n/** Provider-independent projection of a central milestone after mutation. */\nexport interface MilestoneCentralRemoteAdministrationObservation {\n readonly kind: typeof CENTRAL_REMOTE_ADMINISTRATION_OBSERVATION_KINDS.MILESTONE;\n readonly locked: boolean;\n readonly accepted: boolean;\n readonly nodeId: string;\n}\n\nexport type CentralRemoteAdministrationObservation = MilestoneCentralRemoteAdministrationObservation;\n\n/** The requested mutation was observed in the provider's central milestone. */\nexport interface CentralRemoteAdministrationVerified {\n readonly status: typeof CENTRAL_REMOTE_ADMINISTRATION_RESULT_STATUSES.VERIFIED;\n readonly observation: CentralRemoteAdministrationObservation;\n}\n\n/** The request settled without a verified postcondition. */\nexport interface CentralRemoteAdministrationVerificationFailed {\n readonly status: typeof CENTRAL_REMOTE_ADMINISTRATION_RESULT_STATUSES.VERIFICATION_FAILED;\n readonly reason: CentralRemoteAdministrationFailureReason;\n readonly observation?: CentralRemoteAdministrationObservation;\n readonly detail?: unknown;\n}\n\n/**\n * Settled central-remote administration result.\n *\n * Provider runners return verification failures. They must allow mutation\n * exceptions to reject so a compatibility exit policy cannot hide a failed\n * write behind an earlier command's historical success code.\n */\nexport type CentralRemoteAdministrationResult =\n | CentralRemoteAdministrationVerified\n | CentralRemoteAdministrationVerificationFailed;\n\n/** Operations required by a provider which owns central remote administration. */\nexport interface CentralRemoteAdministrationReplicator extends ReplicatorInstance {\n readonly nodeid: string;\n markRemoteResolved(setting: RemoteDBSettings): Promise<void>;\n markRemoteLocked(setting: RemoteDBSettings, locked: boolean, lockByClean: boolean): Promise<void>;\n}\n\n/** Provider boundary which must narrow the active instance before mutation. */\nexport type CentralRemoteAdministrationRunner = (\n replicator: ReplicatorInstance,\n setting: RemoteDBSettings,\n request: CentralRemoteAdministrationRequest\n) => Promise<CentralRemoteAdministrationResult>;\n\n/** Construct a verified result from the provider's postcondition observation. */\nexport function centralRemoteAdministrationVerified(\n observation: CentralRemoteAdministrationObservation\n): CentralRemoteAdministrationVerified {\n return { status: CENTRAL_REMOTE_ADMINISTRATION_RESULT_STATUSES.VERIFIED, observation };\n}\n\n/** Construct a stable verification failure without converting mutation exceptions. */\nexport function centralRemoteAdministrationVerificationFailed(\n reason: CentralRemoteAdministrationFailureReason,\n options: {\n readonly observation?: CentralRemoteAdministrationObservation;\n readonly detail?: unknown;\n } = {}\n): CentralRemoteAdministrationVerificationFailed {\n return {\n status: CENTRAL_REMOTE_ADMINISTRATION_RESULT_STATUSES.VERIFICATION_FAILED,\n reason,\n ...options,\n };\n}\n\n/** Narrow one settled administration result to its verified arm. */\nexport function isCentralRemoteAdministrationVerified(\n result: CentralRemoteAdministrationResult\n): result is CentralRemoteAdministrationVerified {\n return result.status === CENTRAL_REMOTE_ADMINISTRATION_RESULT_STATUSES.VERIFIED;\n}\n\n/** Apply the legacy mutation selected by a typed administration request. */\nexport async function applyCentralRemoteAdministrationMutation(\n replicator: CentralRemoteAdministrationReplicator,\n setting: RemoteDBSettings,\n action: CentralRemoteAdministrationAction\n): Promise<void> {\n switch (action) {\n case CENTRAL_REMOTE_ADMINISTRATION_ACTIONS.MARK_RESOLVED:\n await replicator.markRemoteResolved(setting);\n return;\n case CENTRAL_REMOTE_ADMINISTRATION_ACTIONS.LOCK:\n await replicator.markRemoteLocked(setting, true, false);\n return;\n case CENTRAL_REMOTE_ADMINISTRATION_ACTIONS.UNLOCK:\n await replicator.markRemoteLocked(setting, false, false);\n return;\n }\n}\n\n/** Return whether an observed milestone proves the requested postcondition. */\nexport function milestoneSatisfiesCentralRemoteAdministration(\n action: CentralRemoteAdministrationAction,\n observation: MilestoneCentralRemoteAdministrationObservation\n): boolean {\n switch (action) {\n case CENTRAL_REMOTE_ADMINISTRATION_ACTIONS.MARK_RESOLVED:\n return observation.accepted;\n case CENTRAL_REMOTE_ADMINISTRATION_ACTIONS.LOCK:\n return observation.locked;\n case CENTRAL_REMOTE_ADMINISTRATION_ACTIONS.UNLOCK:\n return !observation.locked;\n }\n}\n","import type { RemoteDBSettings } from \"@lib/common/types.ts\";\nimport {\n CENTRAL_REMOTE_ADMINISTRATION_FAILURE_REASONS,\n centralRemoteAdministrationVerificationFailed,\n type CentralRemoteAdministrationRequest,\n type CentralRemoteAdministrationResult,\n} from \"@lib/replication/CentralRemoteAdministration.ts\";\nimport { CAPABILITY_SUPPORT_KINDS } from \"@lib/replication/ProviderCapability.ts\";\nimport {\n isActiveReplicatorContextBoundToSetting,\n type ActiveReplicatorContext,\n} from \"@lib/replication/ReplicatorProvider.ts\";\n\n/** Stop the captured publication before an exclusive central-remote mutation. */\nasync function stopActiveTransfer(context: ActiveReplicatorContext): Promise<void> {\n const capability = context.provider.stopActiveTransfer;\n if (capability.kind !== CAPABILITY_SUPPORT_KINDS.SUPPORTED) {\n throw new Error(\"The active Replicator does not support the stop required for central remote administration.\");\n }\n const outcome = await capability.run(context.replicator);\n if (outcome.status === \"completed\") return;\n if (outcome.status === \"failed\") throw outcome.error;\n throw new Error(\"The active Replicator transfer did not stop before central remote administration.\");\n}\n\n/** Stop, then dispatch central-remote administration through the atomically captured provider. */\nexport async function runCentralRemoteAdministrationWithContext(\n context: ActiveReplicatorContext | undefined,\n setting: RemoteDBSettings,\n request: CentralRemoteAdministrationRequest\n): Promise<CentralRemoteAdministrationResult> {\n if (!context) {\n return centralRemoteAdministrationVerificationFailed(\n CENTRAL_REMOTE_ADMINISTRATION_FAILURE_REASONS.NO_ACTIVE_REPLICATOR\n );\n }\n if (!isActiveReplicatorContextBoundToSetting(context, setting)) {\n return centralRemoteAdministrationVerificationFailed(\n CENTRAL_REMOTE_ADMINISTRATION_FAILURE_REASONS.ACTIVE_CONFIGURATION_MISMATCH\n );\n }\n\n const capability = context.provider.centralRemoteAdministration;\n if (!capability) {\n return centralRemoteAdministrationVerificationFailed(\n CENTRAL_REMOTE_ADMINISTRATION_FAILURE_REASONS.CAPABILITY_NOT_APPLICABLE\n );\n }\n if (capability.kind !== CAPABILITY_SUPPORT_KINDS.SUPPORTED) {\n return centralRemoteAdministrationVerificationFailed(capability.reason);\n }\n // The enclosing service reservation keeps this exact publication active\n // while its transfer settles and the provider-specific mutation runs.\n await stopActiveTransfer(context);\n // The selected provider owns validation of its concrete Replicator shape.\n return await capability.run(context.replicator, setting, request);\n}\n","import { ReplicatorService } from \"@lib/services/base/ReplicatorService\";\nimport type { ServiceContext } from \"@lib/services/base/ServiceBase\";\n\n// TODO: Remove this layer.\nexport class InjectableReplicatorService<T extends ServiceContext> extends ReplicatorService<T> {\n // getActiveReplicator = handlers<IReplicatorService>().binder(\"getActiveReplicator\");\n}\n","import { handlers } from \"@lib/services/lib/HandlerUtils\";\nimport type { ITestService } from \"./IService\";\nimport { ServiceBase, type ServiceContext } from \"./ServiceBase\";\n\n/**\n * The TestService provides methods for adding and handling test results.\n */\nexport abstract class TestService<T extends ServiceContext = ServiceContext>\n extends ServiceBase<T>\n implements ITestService\n{\n /**\n * Run the test suite to verify the plug-in's functionality.\n * This is typically used for development and debugging purposes.\n * It may involve user interaction (means raising resolveByUserInteraction).\n */\n readonly test = handlers<ITestService>().bailFirstFailure(\"test\");\n\n /**\n * Run the multi-device test suite to verify the plug-in's functionality across multiple devices.\n * This is typically used for development and debugging purposes.\n * It may involve user interaction (means raising resolveByUserInteraction).\n */\n readonly testMultiDevice = handlers<ITestService>().bailFirstFailure(\"testMultiDevice\");\n\n /**\n * Add a test result to the test suite.\n * @param name The name of the test case.\n * @param key The key of the test result.\n * @param result The result of the test (true for success, false for failure).\n * @param summary A brief summary of the test result.\n * @param message A detailed message about the test result.\n */\n abstract addTestResult(name: string, key: string, result: boolean, summary?: string, message?: string): void;\n}\n","import type { ITestService } from \"@lib/services/base/IService\";\nimport type { ServiceContext } from \"@lib/services/base/ServiceBase\";\nimport { TestService } from \"@lib/services/base/TestService\";\nimport { handlers } from \"@lib/services/lib/HandlerUtils\";\n\nexport class InjectableTestService<T extends ServiceContext> extends TestService<T> {\n addTestResult = handlers<ITestService>().binder(\"addTestResult\");\n}\n","import type {\n ObsidianLiveSyncSettings,\n RemoteDBSettings,\n RemotePreferredTweakResult,\n TweakAssessment,\n TweakValues,\n} from \"@lib/common/types\";\nimport type { ITweakValueService } from \"./IService\";\nimport { ServiceBase, type ServiceContext } from \"./ServiceBase\";\n\n/**\n * The TweakValueService provides methods for managing tweak values and resolving mismatches.\n */\nexport abstract class TweakValueService<T extends ServiceContext = ServiceContext>\n extends ServiceBase<T>\n implements ITweakValueService\n{\n /**\n * Fetch and trial the remote database settings to determine if they are preferred.\n * @param trialSetting The remote database settings to connect.\n */\n abstract fetchRemotePreferred(trialSetting: RemoteDBSettings): Promise<RemotePreferredTweakResult>;\n\n /**\n * Check and ask the user to resolve any mismatched tweak values.\n * @param preferred The preferred tweak values to check against.\n * @param assessment The exact compatibility assessment from the calling operation, when available.\n */\n abstract checkAndAskResolvingMismatched(\n preferred: Partial<TweakValues>,\n assessment?: TweakAssessment\n ): Promise<[TweakValues | boolean, boolean]>;\n\n /**\n * Ask the user to resolve any mismatched tweak values.\n * @param preferredSource The preferred tweak values to resolve against.\n * @param updatePreferredRemote Optional exact-context writer supplied by the failed operation.\n * @param assessment The exact compatibility assessment from the failed operation, when available.\n */\n abstract askResolvingMismatched(\n preferredSource: TweakValues,\n updatePreferredRemote?: (setting: ObsidianLiveSyncSettings) => Promise<boolean>,\n assessment?: TweakAssessment\n ): Promise<\"OK\" | \"CHECKAGAIN\" | \"IGNORE\">;\n\n /**\n * Check and ask the user to use the remote configuration.\n * @param settings The remote database settings to connect.\n */\n abstract checkAndAskUseRemoteConfiguration(\n settings: RemoteDBSettings\n ): Promise<{ result: false | TweakValues; requireFetch: boolean }>;\n\n /**\n * Ask the user to use the remote configuration.\n * @param trialSetting The remote database settings to connect.\n * @param preferred The preferred tweak values to use.\n */\n abstract askUseRemoteConfiguration(\n trialSetting: RemoteDBSettings,\n preferred: TweakValues\n ): Promise<{ result: false | TweakValues; requireFetch: boolean }>;\n}\n","import type { ITweakValueService } from \"@lib/services/base/IService\";\nimport type { ServiceContext } from \"@lib/services/base/ServiceBase\";\nimport { TweakValueService } from \"@lib/services/base/TweakValueService\";\nimport { handlers } from \"@lib/services/lib/HandlerUtils\";\n\nexport class InjectableTweakValueService<T extends ServiceContext> extends TweakValueService<T> {\n fetchRemotePreferred = handlers<ITweakValueService>().binder(\"fetchRemotePreferred\");\n checkAndAskResolvingMismatched = handlers<ITweakValueService>().binder(\"checkAndAskResolvingMismatched\");\n\n askResolvingMismatched = handlers<ITweakValueService>().binder(\"askResolvingMismatched\");\n checkAndAskUseRemoteConfiguration = handlers<ITweakValueService>().binder(\"checkAndAskUseRemoteConfiguration\");\n askUseRemoteConfiguration = handlers<ITweakValueService>().binder(\"askUseRemoteConfiguration\");\n}\n","import type { FilePath } from \"@lib/common/types\";\nimport type { IAPIService, ISettingService, IVaultService } from \"./IService\";\nimport { ServiceBase, type ServiceContext } from \"./ServiceBase\";\nimport { handlers } from \"@lib/services/lib/HandlerUtils\";\n\nexport interface VaultServiceDependencies {\n settingService: ISettingService;\n APIService: IAPIService;\n}\n/**\n * The VaultService provides methods for interacting with the vault (local file system).\n */\nexport abstract class VaultService<T extends ServiceContext = ServiceContext>\n extends ServiceBase<T>\n implements IVaultService\n{\n protected settingService: ISettingService;\n protected APIService: IAPIService;\n\n get settings() {\n return this.settingService.currentSettings();\n }\n constructor(context: T, dependencies: VaultServiceDependencies) {\n super(context);\n this.settingService = dependencies.settingService;\n this.APIService = dependencies.APIService;\n }\n /**\n * Get the vault name only.\n */\n vaultName(): string {\n return this.APIService.getSystemVaultName();\n }\n\n /**\n * Get the vault name with additional suffixes.\n */\n getVaultName() {\n return (\n this.vaultName() +\n (this.settings.additionalSuffixOfDatabaseName ? \"-\" + this.settings.additionalSuffixOfDatabaseName : \"\")\n );\n }\n\n /**\n * Scan the vault for changes (especially for changes during the plug-in were not running).\n * @param showingNotice Whether to show a notice to the user.\n * @param ignoreSuspending Whether to ignore any suspending state.\n */\n readonly scanVault = handlers<IVaultService>().bailFirstFailureWithResult(\"scanVault\");\n\n /**\n * Check if a file is ignored by the ignore file (e.g., .gitignore, .obsidianignore).\n * @param file The file path or file info stub to check.\n */\n readonly isIgnoredByIgnoreFile = handlers<IVaultService>().anySuccess(\"isIgnoredByIgnoreFile\");\n\n /**\n * Check if a file is a target file for synchronisation.\n * @param file The file path or file info stub to check.\n * @param options Optional selection inspection without filename collision rejection.\n */\n readonly isTargetFile = handlers<IVaultService>().bailFirstFailure(\"isTargetFile\");\n\n /**\n * Check if a file is a target file for some extra feature\n */\n readonly isTargetFileInExtra = handlers<IVaultService>().anySuccess(\"isTargetFileInExtra\");\n /**\n * Check if a filesize is too large against the current settings.\n * @param size The file size to check.\n */\n isFileSizeTooLarge(size: number) {\n const maxSize = this.settings.syncMaxSizeInMB;\n if (maxSize > 0 && size > 0) {\n if (maxSize * 1024 * 1024 < size) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Get the currently active file path in the editor, if any.\n */\n abstract getActiveFilePath(): FilePath | undefined;\n\n /**\n * Check if the vault is on a case-insensitive file system.\n * This is important for certain operating systems like Windows and macOS.\n */\n abstract isStorageInsensitive(): boolean;\n\n /**\n * Check if the file system should be treated case-insensitively.\n * This is important for certain operating systems like Windows and macOS.\n */\n shouldCheckCaseInsensitively(): boolean {\n // By default, only check if the setting says so.\n // Override this method in subclasses for the platform-specific logic, i.e., checking the underlying file system.\n return !this.settings.handleFilenameCaseSensitive;\n }\n\n /**\n * Check if a given path is valid in the vault.\n * @param path The file path to check.\n */\n abstract isValidPath(path: string): boolean;\n}\n","import { isValidFilenameInWidows } from \"@lib/string_and_binary/path\";\nimport type { IVaultService } from \"@lib/services/base/IService\";\nimport type { ServiceContext } from \"@lib/services/base/ServiceBase\";\nimport { VaultService } from \"@lib/services/base/VaultService\";\nimport { handlers } from \"@lib/services/lib/HandlerUtils\";\n\nexport abstract class InjectableVaultService<T extends ServiceContext> extends VaultService<T> {\n // scanVault = handlers<IVaultService>().binder(\"scanVault\");\n // isIgnoredByIgnoreFile = handlers<IVaultService>().binder(\"isIgnoredByIgnoreFile\");\n // isTargetFile = handlers<IVaultService>().bailFirstFailure(\"isTargetFile\");\n // markFileListPossiblyChanged = handlers<IVaultService>().binder(\"markFileListPossiblyChanged\");\n}\n\nexport class InjectableVaultServiceCompat<T extends ServiceContext> extends InjectableVaultService<T> {\n isStorageInsensitive = handlers<IVaultService>().binder(\"isStorageInsensitive\");\n getActiveFilePath = handlers<IVaultService>().binder(\"getActiveFilePath\");\n override isValidPath(path: string): boolean {\n // Most strict rule.\n return isValidFilenameInWidows(path);\n }\n}\n","import type { IConfigService } from \"@lib/services/base/IService\";\nimport { ServiceBase, type ServiceContext } from \"./ServiceBase\";\n\nexport abstract class ConfigService<T extends ServiceContext = ServiceContext>\n extends ServiceBase<T>\n implements IConfigService\n{\n abstract getSmallConfig(key: string): string | null;\n\n abstract setSmallConfig(key: string, value: string): void;\n\n abstract deleteSmallConfig(key: string): void;\n}\n","import { ConfigService } from \"@lib/services/base/ConfigService\";\nimport type { IAPIService, ISettingService } from \"@lib/services/base/IService\";\nimport type { ServiceContext } from \"@lib/services/base/ServiceBase\";\nimport { createInstanceLogFunction } from \"@lib/services/lib/logUtils\";\nexport interface ConfigServiceBrowserCompatDependencies {\n settingService: ISettingService;\n APIService: IAPIService;\n}\nexport class ConfigServiceBrowserCompat<T extends ServiceContext = ServiceContext> extends ConfigService<T> {\n private _settingService: ISettingService;\n\n _log: ReturnType<typeof createInstanceLogFunction>;\n constructor(context: T, dependencies: ConfigServiceBrowserCompatDependencies) {\n super(context);\n this._settingService = dependencies.settingService;\n this._log = createInstanceLogFunction(\"ConfigService\", dependencies.APIService);\n }\n\n getSmallConfig(key: string) {\n return this._settingService.getSmallConfig(key);\n }\n\n setSmallConfig(key: string, value: string): void {\n return this._settingService.setSmallConfig(key, value);\n }\n\n deleteSmallConfig(key: string): void {\n return this._settingService.deleteSmallConfig(key);\n }\n}\n","// ControlService is meta-service.\n//\n// As the name suggests, it is responsible for multiple services related things.\n// In the other word, it is orchestrating services.\n\nimport { LOG_LEVEL_URGENT } from \"octagonal-wheels/common/logger\";\nimport { createInstanceLogFunction } from \"@lib/services/lib/logUtils\";\nimport type { APIService } from \"./APIService\";\nimport type { DatabaseService } from \"./DatabaseService\";\nimport type { IControlService, IFileProcessingService, IReplicatorService, ISettingService } from \"./IService\";\nimport { ServiceBase, type ServiceContext } from \"./ServiceBase\";\nimport { EVENT_PLATFORM_UNLOADED, EVENT_PLUGIN_UNLOADED } from \"@lib/events/coreEvents\";\nimport { cancelAllPeriodicTask, cancelAllTasks } from \"octagonal-wheels/concurrency/task\";\nimport { stopAllRunningProcessors } from \"octagonal-wheels/concurrency/processor\";\nimport { promiseWithResolvers, type PromiseWithResolvers } from \"octagonal-wheels/promises\";\nimport type { AppLifecycleService } from \"./AppLifecycleService\";\n\n// ControlService can depend on any service.\nexport interface ControlServiceDependencies {\n appLifecycleService: AppLifecycleService;\n replicatorService: IReplicatorService;\n settingService: ISettingService;\n databaseService: DatabaseService;\n fileProcessingService: IFileProcessingService;\n APIService: APIService;\n}\n\n/**\n * The ControlService provides methods for controlling the overall behaviour of the plugin, such as applying settings or handling lifecycle events.\n */\nexport class ControlService<T extends ServiceContext = ServiceContext>\n extends ServiceBase<T>\n implements IControlService\n{\n protected services: ControlServiceDependencies;\n protected _log: ReturnType<typeof createInstanceLogFunction>;\n protected _unloaded = false;\n protected _activated: PromiseWithResolvers<boolean>;\n\n /**\n * Check if the plug-in has been unloaded.\n */\n hasUnloaded(): boolean {\n return this._unloaded;\n }\n\n constructor(context: T, dependencies: ControlServiceDependencies) {\n super(context);\n this.services = dependencies;\n this._log = createInstanceLogFunction(\"ControlService\", this.services.APIService);\n this._activated = promiseWithResolvers();\n this.services.appLifecycleService.onLoaded.addHandler(() => {\n this.onActivated();\n return Promise.resolve(true);\n });\n }\n\n get activated() {\n return this._activated.promise;\n }\n\n private onActivated() {\n this._activated.resolve(true);\n }\n\n /**\n * Apply current settings to reflect the changes immediately.\n * @returns\n */\n async applySettings() {\n await this.services.appLifecycleService.onSuspending();\n await this.services.settingService.onBeforeRealiseSetting();\n this.services.databaseService.localDatabase.refreshSettings();\n await this.services.fileProcessingService.commitPendingFileEvents();\n await this.services.settingService.onRealiseSetting();\n // disable all sync temporary.\n if (this.services.appLifecycleService.isSuspended()) return;\n await this.services.appLifecycleService.onResuming();\n await this.services.appLifecycleService.onResumed();\n await this.services.settingService.onSettingRealised();\n }\n\n private async _onLiveSyncUnload(): Promise<void> {\n this.context.events.emitEvent(EVENT_PLUGIN_UNLOADED);\n await this.services.appLifecycleService.onBeforeUnload();\n await Promise.resolve(this.services.appLifecycleService.onAppUnload());\n cancelAllPeriodicTask();\n cancelAllTasks();\n stopAllRunningProcessors();\n await this.services.appLifecycleService.onUnload();\n this._unloaded = true;\n const localDatabase = this.services.databaseService.localDatabaseDirect;\n if (localDatabase != null) {\n localDatabase.onunload();\n await localDatabase.close();\n }\n this.context.events.emitEvent(EVENT_PLATFORM_UNLOADED);\n this.context.events.offAll();\n this._log(this.context.translate(\"moduleLiveSyncMain.logUnloadingPlugin\"));\n return;\n }\n\n /**\n * Called when the plugin is loaded. It will trigger the app lifecycle event onLoad.\n * Main process should be called in onReady.\n * @returns\n */\n async onLoad() {\n if (!(await this.services.appLifecycleService.onLoad())) {\n this._log(\"Self-hosted LiveSync cannot be initialised, exiting loading.\", LOG_LEVEL_URGENT);\n return false;\n }\n return true;\n }\n /**\n * Main entry point of the plugin. It will trigger the app lifecycle event onReady.\n * Usually it should be called on `app.workspace.onLayoutReady`\n * @returns\n */\n async onReady() {\n return await this.services.appLifecycleService.onReady();\n }\n\n /**\n * On unload event of the plugin. It will trigger the app lifecycle event onUnload.\n * @returns\n */\n async onUnload() {\n return await this._onLiveSyncUnload();\n }\n}\n","import type { UIService } from \"./implements/base/UIService.ts\";\nimport type { ConfigService } from \"@lib/services/base/ConfigService.ts\";\nimport type { TestService } from \"@lib/services/base/TestService.ts\";\nimport type { VaultService } from \"@lib/services/base/VaultService.ts\";\nimport type { TweakValueService } from \"@lib/services/base/TweakValueService.ts\";\nimport type { SettingService } from \"@lib/services/base/SettingService.ts\";\nimport type { AppLifecycleService } from \"@lib/services/base/AppLifecycleService.ts\";\nimport type { ConflictService } from \"@lib/services/base/ConflictService.ts\";\nimport type { RemoteService } from \"@lib/services/base/RemoteService.ts\";\nimport type { ReplicationService } from \"@lib/services/base/ReplicationService.ts\";\nimport type { ReplicatorService } from \"@lib/services/base/ReplicatorService.ts\";\nimport type { FileProcessingService } from \"@lib/services/base/FileProcessingService.ts\";\nimport type { DatabaseEventService } from \"@lib/services/base/DatabaseEventService.ts\";\nimport type { DatabaseService } from \"@lib/services/base/DatabaseService.ts\";\nimport type { PathService } from \"@lib/services/base/PathService.ts\";\nimport type { APIService } from \"@lib/services/base/APIService.ts\";\nimport type { ServiceContext } from \"./base/ServiceBase.ts\";\nimport type { IServiceHub } from \"./base/IService.ts\";\nimport type { KeyValueDBService } from \"./base/KeyValueDBService.ts\";\nimport type { ControlService } from \"./base/ControlService.ts\";\n\nexport type ServiceInstances<T extends ServiceContext = ServiceContext> = {\n API?: APIService<T>;\n path?: PathService<T>;\n database?: DatabaseService<T>;\n databaseEvents?: DatabaseEventService<T>;\n replicator?: ReplicatorService<T>;\n fileProcessing?: FileProcessingService<T>;\n replication?: ReplicationService<T>;\n remote?: RemoteService<T>;\n conflict?: ConflictService<T>;\n appLifecycle?: AppLifecycleService<T>;\n setting?: SettingService<T>;\n tweakValue?: TweakValueService<T>;\n vault?: VaultService<T>;\n test?: TestService<T>;\n ui?: UIService<T>;\n config?: ConfigService<T>;\n keyValueDB?: KeyValueDBService<T>;\n control?: ControlService<T>;\n};\n\nexport abstract class ServiceHub<T extends ServiceContext = ServiceContext> implements IServiceHub {\n /** Context shared by every service exposed by this hub. */\n readonly context: T;\n protected abstract _api: APIService<T>;\n protected abstract _path: PathService<T>;\n protected abstract _database: DatabaseService<T>;\n protected abstract _databaseEvents: DatabaseEventService<T>;\n protected abstract _replicator: ReplicatorService<T>;\n protected abstract _fileProcessing: FileProcessingService<T>;\n protected abstract _replication: ReplicationService<T>;\n protected abstract _remote: RemoteService<T>;\n protected abstract _conflict: ConflictService<T>;\n protected abstract _appLifecycle: AppLifecycleService<T>;\n protected abstract _setting: SettingService<T>;\n protected abstract _tweakValue: TweakValueService<T>;\n protected abstract _vault: VaultService<T>;\n protected abstract _test: TestService<T>;\n protected abstract _ui: UIService<T>;\n protected abstract _config: ConfigService<T>;\n protected abstract _keyValueDB: KeyValueDBService<T>;\n protected abstract _control: ControlService<T>;\n protected _injected: ServiceInstances<T> = {};\n constructor(context: T, services: ServiceInstances<T> = {}) {\n this.context = context;\n this._injected = services;\n }\n\n get API(): APIService<T> {\n return this._injected.API || this._api;\n }\n get path(): PathService<T> {\n return this._injected.path || this._path;\n }\n get database(): DatabaseService<T> {\n return this._injected.database || this._database;\n }\n get databaseEvents(): DatabaseEventService<T> {\n return this._injected.databaseEvents || this._databaseEvents;\n }\n get replicator(): ReplicatorService<T> {\n return this._injected.replicator || this._replicator;\n }\n get fileProcessing(): FileProcessingService<T> {\n return this._injected.fileProcessing || this._fileProcessing;\n }\n get replication(): ReplicationService<T> {\n return this._injected.replication || this._replication;\n }\n get remote(): RemoteService<T> {\n return this._injected.remote || this._remote;\n }\n get conflict(): ConflictService<T> {\n return this._injected.conflict || this._conflict;\n }\n get appLifecycle(): AppLifecycleService<T> {\n return this._injected.appLifecycle || this._appLifecycle;\n }\n get setting(): SettingService<T> {\n return this._injected.setting || this._setting;\n }\n get tweakValue(): TweakValueService<T> {\n return this._injected.tweakValue || this._tweakValue;\n }\n get vault(): VaultService<T> {\n return this._injected.vault || this._vault;\n }\n get test(): TestService<T> {\n return this._injected.test || this._test;\n }\n\n get UI(): UIService<T> {\n return this._injected.ui || this._ui;\n }\n get config(): ConfigService<T> {\n return this._injected.config || this._config;\n }\n get keyValueDB(): KeyValueDBService<T> {\n return this._injected.keyValueDB || this._keyValueDB;\n }\n get control(): ControlService<T> {\n return this._injected.control || this._control;\n }\n}\n","import type { ConfigService } from \"@lib/services/base/ConfigService\";\nimport { ControlService } from \"@lib/services/base/ControlService\";\nimport type { KeyValueDBService } from \"@lib/services/base/KeyValueDBService\";\nimport { PathService } from \"@lib/services/base/PathService\";\nimport type { ServiceContext } from \"@lib/services/base/ServiceBase\";\nimport type { SettingService } from \"@lib/services/base/SettingService\";\nimport { ServiceHub } from \"@lib/services/ServiceHub\";\nimport type { UIService } from \"@lib/services/implements/base/UIService\";\nimport { InjectableAPIService } from \"./InjectableAPIService\";\nimport { type AppLifecycleServiceBase } from \"./InjectableAppLifecycleService\";\nimport { InjectableConflictService } from \"./InjectableConflictService\";\nimport { InjectableDatabaseEventService } from \"./InjectableDatabaseEventService\";\nimport { InjectableFileProcessingService } from \"./InjectableFileProcessingService\";\nimport type { InjectableRemoteService } from \"./InjectableRemoteService\";\nimport { InjectableReplicationService } from \"./InjectableReplicationService\";\nimport { InjectableReplicatorService } from \"./InjectableReplicatorService\";\nimport type { InjectableServiceInstances } from \"./InjectableServices\";\nimport { InjectableTestService } from \"./InjectableTestService\";\nimport { InjectableTweakValueService } from \"./InjectableTweakValueService\";\nimport { InjectableVaultService } from \"./InjectableVaultService\";\nimport type { DatabaseService } from \"@lib/services/base/DatabaseService.ts\";\n\nexport class InjectableServiceHub<T extends ServiceContext = ServiceContext> extends ServiceHub<T> {\n protected readonly _api: InjectableAPIService<T>;\n\n protected readonly _path: PathService<T>;\n protected readonly _database: DatabaseService<T>;\n protected readonly _databaseEvents: InjectableDatabaseEventService<T>;\n protected readonly _replicator: InjectableReplicatorService<T>;\n protected readonly _fileProcessing: InjectableFileProcessingService<T>;\n protected readonly _replication: InjectableReplicationService<T>;\n protected readonly _remote: InjectableRemoteService<T>;\n protected readonly _conflict: InjectableConflictService<T>;\n protected readonly _appLifecycle: AppLifecycleServiceBase<T>;\n protected readonly _setting: SettingService<T>;\n protected readonly _tweakValue: InjectableTweakValueService<T>;\n protected readonly _vault: InjectableVaultService<T>;\n protected readonly _test: InjectableTestService<T>;\n protected readonly _ui: UIService<T>;\n protected readonly _config: ConfigService<T>;\n protected readonly _keyValueDB: KeyValueDBService<T>;\n protected readonly _control: ControlService<T>;\n\n override get API(): InjectableAPIService<T> {\n return this._api;\n }\n override get path(): PathService<T> {\n return this._path;\n }\n override get database(): DatabaseService<T> {\n return this._database;\n }\n override get databaseEvents(): InjectableDatabaseEventService<T> {\n return this._databaseEvents;\n }\n override get replicator(): InjectableReplicatorService<T> {\n return this._replicator;\n }\n override get fileProcessing(): InjectableFileProcessingService<T> {\n return this._fileProcessing;\n }\n override get replication(): InjectableReplicationService<T> {\n return this._replication;\n }\n override get remote(): InjectableRemoteService<T> {\n return this._remote;\n }\n override get conflict(): InjectableConflictService<T> {\n return this._conflict;\n }\n override get appLifecycle(): AppLifecycleServiceBase<T> {\n return this._appLifecycle;\n }\n override get setting(): SettingService<T> {\n return this._setting;\n }\n override get tweakValue(): InjectableTweakValueService<T> {\n return this._tweakValue;\n }\n override get vault(): InjectableVaultService<T> {\n return this._vault;\n }\n override get test(): InjectableTestService<T> {\n return this._test;\n }\n\n override get control(): ControlService<T> {\n return this._control;\n }\n\n override get keyValueDB(): KeyValueDBService<T> {\n return this._keyValueDB;\n }\n\n override get UI(): UIService<T> {\n return this._ui;\n }\n override get config(): ConfigService<T> {\n return this._config;\n }\n\n constructor(\n context: T,\n services: InjectableServiceInstances<T> & {\n setting: SettingService<T>;\n appLifecycle: AppLifecycleServiceBase<T>;\n path: PathService<T>;\n API: InjectableAPIService<T>;\n ui: UIService<T>;\n config: ConfigService<T>;\n database: DatabaseService<T>;\n remote: InjectableRemoteService<T>;\n vault: InjectableVaultService<T>;\n keyValueDB: KeyValueDBService<T>;\n replicator: InjectableReplicatorService<T>;\n }\n ) {\n super(context, services);\n // TODO reorder to resolve dependencies (or make sure dependencies)\n this._api = services.API;\n this._path = services.path;\n this._database = services.database;\n this._databaseEvents = services.databaseEvents ?? new InjectableDatabaseEventService<T>(context);\n this._replicator = services.replicator;\n this._fileProcessing = services.fileProcessing ?? new InjectableFileProcessingService<T>(context);\n this._conflict = services.conflict ?? new InjectableConflictService<T>(context);\n this._appLifecycle = services.appLifecycle;\n this._setting = services.setting;\n this._remote = services.remote;\n this._tweakValue = services.tweakValue ?? new InjectableTweakValueService<T>(context);\n this._replication =\n services.replication ??\n new InjectableReplicationService<T>(context, {\n APIService: this._api,\n appLifecycleService: this._appLifecycle,\n replicatorService: this._replicator,\n settingService: this._setting,\n databaseService: this._database,\n fileProcessingService: this._fileProcessing,\n });\n this._vault = services.vault;\n this._test = services.test ?? new InjectableTestService<T>(context);\n this._ui = services.ui;\n this._config = services.config;\n this._keyValueDB = services.keyValueDB;\n this._control =\n services.control ??\n new ControlService<T>(context, {\n appLifecycleService: this._appLifecycle,\n databaseService: this._database,\n fileProcessingService: this._fileProcessing,\n settingService: this._setting,\n APIService: this._api,\n replicatorService: this._replicator,\n });\n }\n}\n","import type { Confirm } from \"@lib/interfaces/Confirm\";\nimport type { ComponentHasResult, SvelteDialogManager } from \"@lib/services/implements/base/SvelteDialog\";\nimport type { IAPIService, IUIService } from \"@lib/services/base/IService\";\n\nimport { ServiceBase, type ServiceContext } from \"@lib/services/base/ServiceBase\";\n\nexport type UIServiceDependencies<T extends ServiceContext = ServiceContext> = {\n dialogManager: SvelteDialogManager<T>;\n APIService: IAPIService;\n};\n\ntype DialogResult = \"ok\" | \"cancel\";\ntype DialogParams = {\n title: string;\n dataToCopy: string;\n};\n\nexport abstract class UIService<T extends ServiceContext = ServiceContext>\n extends ServiceBase<T>\n implements IUIService\n{\n private _dialogManager: SvelteDialogManager<T>;\n protected _APIService: IAPIService;\n abstract get dialogToCopy(): ComponentHasResult<DialogResult, DialogParams>;\n constructor(context: T, dependents: UIServiceDependencies<T>) {\n super(context);\n this._dialogManager = dependents.dialogManager;\n this._APIService = dependents.APIService;\n }\n get dialogManager(): SvelteDialogManager<T> {\n return this._dialogManager;\n }\n\n async promptCopyToClipboard(title: string, value: string): Promise<boolean> {\n const param = {\n title: title,\n dataToCopy: value,\n };\n const result = await this._dialogManager.open<DialogResult, DialogParams>(this.dialogToCopy, param);\n if (result !== \"ok\") {\n return false;\n }\n return true;\n }\n\n showMarkdownDialog<T extends string[]>(\n title: string,\n contentMD: string,\n buttons: T,\n defaultAction?: (typeof buttons)[number]\n ): Promise<(typeof buttons)[number] | false> {\n return this._APIService.confirm.askSelectStringDialogue(contentMD, buttons, {\n title,\n defaultAction: defaultAction ?? buttons[0],\n timeout: 0,\n });\n }\n get confirm(): Confirm {\n return this._APIService.confirm;\n }\n}\n","import type { FetchHttpHandler } from \"@smithy/fetch-http-handler\";\nimport type { LOG_LEVEL } from \"@lib/common/logger\";\nimport type { IAPIService, ICommandCompat } from \"./IService\";\nimport { ServiceBase, type ServiceContext } from \"./ServiceBase\";\nimport type { Confirm } from \"@lib/interfaces/Confirm\";\nimport { reactiveSource } from \"octagonal-wheels/dataobject/reactive\";\nimport { _fetch, compatGlobal } from \"@lib/common/coreEnvFunctions\";\n/**\n * The APIService provides methods for interacting with the plug-in's API,\n */\nexport abstract class APIService<T extends ServiceContext = ServiceContext>\n extends ServiceBase<T>\n implements IAPIService\n{\n /**\n * Get a custom fetch handler for making HTTP requests (e.g., S3 without CORS issues).\n */\n abstract getCustomFetchHandler(): FetchHttpHandler;\n\n /**\n * Add a log entry to the log (Now not used).\n * @param message The log message.\n * @param level The log level.\n * @param key The log key.\n */\n abstract addLog(message: unknown, level: LOG_LEVEL, key: string): void;\n\n /**\n * Check if the app is running on a mobile device.\n * @returns true if running on mobile, false otherwise.\n */\n abstract isMobile(): boolean;\n\n /**\n * Show a window (or in Obsidian, a leaf).\n * @param type The type of window to show.\n */\n abstract showWindow(type: string): Promise<void>;\n\n /**\n * Show a window on the right sidebar when supported.\n * Platforms that do not support sidebars can fall back to showWindow.\n */\n showWindowOnRight(type: string): Promise<void> {\n return this.showWindow(type);\n }\n\n /**\n * returns App ID. In Obsidian, it is vault ID.\n */\n abstract getAppID(): string;\n\n /**\n * Returns the vaultName which system has identified, without any additional suffix.\n */\n abstract getSystemVaultName(): string;\n /**\n * Check if the last POST request failed due to payload size.\n */\n // abstract isLastPostFailedDueToPayloadSize(): boolean;\n\n abstract getPlatform(): string;\n\n abstract getAppVersion(): string;\n\n abstract getPluginVersion(): string;\n\n abstract getCrypto(): Crypto;\n\n /**\n * Register a command to the runtime.\n * @param command\n */\n abstract addCommand<TCommand extends ICommandCompat>(command: TCommand): TCommand;\n\n /**\n * Register a window (or leaf) type to the runtime.\n * @param type\n * @param factory\n */\n abstract registerWindow<T>(type: string, factory: (leaf: T) => unknown): void;\n\n /**\n * Add a ribbon icon to the UI.\n * @param icon\n * @param title\n * @param callback\n */\n abstract addRibbonIcon(icon: string, title: string, callback: (evt: MouseEvent) => unknown): HTMLElement;\n\n /**\n * Register a protocol handler.\n * @param action The action string for the protocol.\n * @param handler The handler function for the protocol.\n */\n abstract registerProtocolHandler(action: string, handler: (params: Record<string, string>) => unknown): void;\n\n /**\n * Get the basic UI component for showing a confirmation dialog to the user.\n */\n abstract get confirm(): Confirm;\n requestCount = reactiveSource(0);\n responseCount = reactiveSource(0);\n\n get isOnline() {\n if (\"navigator\" in compatGlobal) {\n return compatGlobal.navigator.onLine;\n }\n return true;\n }\n\n webCompatFetch(req: string | Request, opts?: RequestInit): Promise<Response> {\n return _fetch(req, opts);\n }\n\n // By default, nativeFetch is not implemented. It can be overridden by platforms that support it (e.g., ObsidianAPIService).\n nativeFetch(req: string | Request, opts?: RequestInit): Promise<Response> {\n throw new Error(\"nativeFetch is not implemented for this platform\");\n }\n\n abstract addStatusBarItem(): HTMLElement | undefined;\n\n setInterval(handler: () => void, timeout: number): number {\n return compatGlobal.setInterval(handler, timeout);\n }\n\n clearInterval(timerId: number): void {\n compatGlobal.clearInterval(timerId);\n }\n\n /**\n * Get the system configuration directory.\n * This is used for storing configuration files in a consistent location across platforms.\n * @returns\n */\n getSystemConfigDir() {\n // SHIM.\n return \".livesync\";\n }\n}\n","import { APIService } from \"@lib/services/base/APIService\";\nimport type { IAPIService } from \"@lib/services/base/IService\";\nimport type { ServiceContext } from \"@lib/services/base/ServiceBase\";\nimport { handlers } from \"@lib/services/lib/HandlerUtils\";\n\nexport abstract class InjectableAPIService<T extends ServiceContext> extends APIService<T> {\n addLog = handlers<IAPIService>().binder(\"addLog\");\n // isLastPostFailedDueToPayloadSize = handlers<IAPIService>().binder(\"isLastPostFailedDueToPayloadSize\");\n\n override getPlatform(): string {\n return \"unknown\";\n }\n override getCrypto(): Crypto {\n if (typeof crypto !== \"undefined\") {\n return crypto;\n }\n throw new Error(\"Crypto API is not available in this environment.\");\n }\n}\n","import type { ServiceContext } from \"@lib/services/base/ServiceBase\";\nimport { InjectableAPIService } from \"@lib/services/implements/injectable/InjectableAPIService\";\nimport type { FetchHttpHandler } from \"@smithy/fetch-http-handler\";\nimport type { ICommandCompat } from \"@lib/services/base/IService\";\nimport type { Confirm, ConfirmActionLayout } from \"@lib/interfaces/Confirm\";\n// const module = await import(\"node:crypto\");\nimport module from \"node:crypto\";\nimport { _activeDocument } from \"@lib/common/coreEnvFunctions.ts\";\nimport { Logger } from \"@lib/common/logger\";\n\ndeclare const MANIFEST_VERSION: string | undefined;\n// declare const PACKAGE_VERSION: string | undefined;\n/**\n * Headless implementation of Confirm that returns sensible defaults instead\n * of throwing. Dialogs are logged to stderr so the prompts are visible in\n * service logs, and the default/conservative action is taken automatically.\n */\nexport class HeadlessConfirm implements Confirm {\n askYesNo(message: string): Promise<\"yes\" | \"no\"> {\n console.error(`[Headless] ${message} → no`);\n return Promise.resolve(\"no\");\n }\n askString(title: string, key: string, placeholder: string, isPassword?: boolean): Promise<string | false> {\n console.error(`[Headless] String input required: ${title} → declined`);\n return Promise.resolve(false);\n }\n askYesNoDialog(\n message: string,\n opt: { title?: string; defaultOption?: \"Yes\" | \"No\"; timeout?: number }\n ): Promise<\"yes\" | \"no\"> {\n const result = opt.defaultOption === \"Yes\" ? (\"yes\" as const) : (\"no\" as const);\n console.error(`[Headless] ${opt.title ?? \"Confirm\"}: ${message} → ${result}`);\n return Promise.resolve(result);\n }\n askSelectString(message: string, items: string[]): Promise<string> {\n console.error(`[Headless] ${message} → ${items[0]}`);\n return Promise.resolve(items[0]);\n }\n askSelectStringDialogue<T extends readonly string[]>(\n message: string,\n buttons: T,\n opt: { title?: string; defaultAction: T[number]; timeout?: number }\n ): Promise<T[number] | false> {\n console.error(`[Headless] ${opt.title ?? \"Confirm\"}: ${message} → ${String(opt.defaultAction)}`);\n return Promise.resolve(opt.defaultAction);\n }\n askInPopup(\n key: string,\n dialogText: string,\n anchorCallback: (anchor: HTMLAnchorElement) => void,\n durationMs?: number\n ): void {\n console.error(`[Headless] Popup (${key}): ${dialogText}`);\n }\n confirmWithMessage(\n title: string,\n contentMd: string,\n buttons: string[],\n defaultAction: (typeof buttons)[number],\n timeout?: number,\n _actionLayout?: ConfirmActionLayout\n ): Promise<(typeof buttons)[number] | false> {\n console.error(`[Headless] ${title}: ${contentMd} → ${defaultAction}`);\n return Promise.resolve(defaultAction);\n }\n}\nexport class HeadlessAPIService<T extends ServiceContext> extends InjectableAPIService<T> {\n private _confirmInstance: Confirm;\n private _systemVaultName: string | undefined;\n constructor(context: T) {\n super(context);\n this._confirmInstance = new HeadlessConfirm();\n this.addLog.setHandler(Logger);\n }\n get confirm(): Confirm {\n return this._confirmInstance;\n }\n showWindow(type: string): Promise<void> {\n // In a browser environment, showing a window might not be applicable.\n // TODO: Think implementation\n return Promise.resolve();\n }\n getCustomFetchHandler(): FetchHttpHandler {\n return undefined!;\n }\n isMobile(): boolean {\n return false;\n }\n getAppID(): string {\n return \"headless-app\";\n }\n getAppVersion(): string {\n return `${MANIFEST_VERSION ?? \"0.0.0.\"}`;\n }\n getPluginVersion(): string {\n return `${MANIFEST_VERSION ?? \"0.0.0.\"}`;\n }\n override getPlatform(): string {\n return \"server\";\n }\n\n override getCrypto(): Crypto {\n const webcrypto = module.webcrypto as Crypto;\n return webcrypto;\n }\n addCommand<TCommand extends ICommandCompat>(command: TCommand): TCommand {\n // In a browser environment, command registration might not be applicable.\n return command;\n }\n addRibbonIcon(icon: string, title: string, callback: (evt: MouseEvent) => any): HTMLElement {\n return _activeDocument?.createElement(\"div\") || ({} as HTMLElement);\n }\n registerWindow(type: string, factory: (leaf: any) => any): void {\n // In a browser environment, window registration might not be applicable.\n }\n registerProtocolHandler(action: string, handler: (params: Record<string, string>) => any): void {\n // In a browser environment, protocol handler registration might not be applicable.\n }\n addStatusBarItem(): HTMLElement | undefined {\n // In a browser environment, status bar item might not be applicable.\n return undefined;\n }\n\n private toSafeKeyPart(value: string): string {\n const trimmed = value.trim();\n if (trimmed === \"\") {\n return \"vault\";\n }\n return trimmed.replace(/[^a-zA-Z0-9._-]/g, \"_\");\n }\n\n private hash32(value: string): string {\n // Simple FNV-1a hash to create a short stable suffix for key separation.\n let hash = 0x811c9dc5;\n for (let i = 0; i < value.length; i++) {\n hash ^= value.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193);\n }\n return (hash >>> 0).toString(16).padStart(8, \"0\");\n }\n\n private deriveSystemVaultName(): string {\n const contextLike = this.context as ServiceContext & { vaultPath?: string; vaultName?: string };\n const explicitName = contextLike.vaultName;\n if (typeof explicitName === \"string\" && explicitName.trim() !== \"\") {\n return this.toSafeKeyPart(explicitName);\n }\n\n const vaultPath = contextLike.vaultPath;\n if (typeof vaultPath === \"string\" && vaultPath.trim() !== \"\") {\n const normalised = vaultPath.replace(/\\\\/g, \"/\").replace(/\\/+$/, \"\");\n const leaf =\n normalised\n .split(\"/\")\n .filter((e) => e !== \"\")\n .pop() ?? \"vault\";\n return `${this.toSafeKeyPart(leaf)}-${this.hash32(normalised)}`;\n }\n\n return \"headless-vault\";\n }\n\n getSystemVaultName(): string {\n if (!this._systemVaultName) {\n this._systemVaultName = this.deriveSystemVaultName();\n }\n return this._systemVaultName;\n }\n\n override get isOnline(): boolean {\n return true;\n }\n override nativeFetch(req: string | Request, opts?: RequestInit): Promise<Response> {\n return fetch(req, opts);\n }\n}\n","import type { SimpleStore } from \"@lib/common/utils\";\nimport type { IKeyValueDBService, IVaultService } from \"./IService\";\nimport { ServiceBase, type ServiceContext } from \"./ServiceBase\";\nimport type { KeyValueDatabase, KeyValueDatabaseFactory } from \"@lib/interfaces/KeyValueDatabase\";\nimport { delay, yieldMicrotask } from \"octagonal-wheels/promises\";\nimport { LOG_LEVEL_NOTICE, LOG_LEVEL_VERBOSE } from \"@lib/common/logger\";\nimport { createInstanceLogFunction } from \"@lib/services/lib/logUtils\";\nimport type { InjectableDatabaseEventService } from \"@lib/services/implements/injectable/InjectableDatabaseEventService\";\nimport type { AppLifecycleServiceBase } from \"@lib/services/implements/injectable/InjectableAppLifecycleService\";\n\nexport interface KeyValueDBDependencies<T extends ServiceContext = ServiceContext> {\n openKeyValueDatabase: KeyValueDatabaseFactory;\n databaseEvents: InjectableDatabaseEventService<T>;\n vault: IVaultService;\n appLifecycle: AppLifecycleServiceBase<T>;\n registerLifecycleHandlers?: boolean;\n}\n/**\n * The KeyValueDBService provides methods for managing the local key-value database.\n * Please note that each event of database lifecycle is handled in DatabaseEventService.\n */\nexport abstract class KeyValueDBService<T extends ServiceContext = ServiceContext>\n extends ServiceBase<T>\n implements IKeyValueDBService\n{\n private _kvDB: KeyValueDatabase | undefined;\n private _simpleStore: SimpleStore<unknown> | undefined;\n get simpleStore() {\n if (!this._simpleStore) {\n throw new Error(\"SimpleStore is not initialized yet\");\n }\n return this._simpleStore;\n }\n get kvDB() {\n if (!this._kvDB) {\n throw new Error(\"KeyValueDB is not initialized yet\");\n }\n return this._kvDB;\n }\n\n private databaseEvents: InjectableDatabaseEventService<T>;\n private vault: IVaultService;\n private appLifecycle: AppLifecycleServiceBase<T>;\n private openKeyValueDatabase: KeyValueDatabaseFactory;\n private _log = createInstanceLogFunction(\"KeyValueDBService\");\n\n private async _everyOnResetDatabase(any: unknown): Promise<boolean> {\n try {\n const kvDBKey = \"queued-files\";\n await this._kvDB?.del(kvDBKey);\n // localStorage.removeItem(lsKey);\n await this._kvDB?.destroy();\n await yieldMicrotask();\n this._kvDB = await this.openKeyValueDatabase(this.vault.getVaultName() + \"-livesync-kv\");\n await delay(100);\n } catch (e) {\n this._kvDB = undefined!;\n this._log(\"Failed to reset KeyValueDB\", LOG_LEVEL_NOTICE);\n this._log(e, LOG_LEVEL_VERBOSE);\n return false;\n }\n return true;\n }\n\n private async tryCloseKvDB() {\n try {\n await this._kvDB?.close();\n return true;\n } catch (e) {\n this._log(\"Failed to close KeyValueDB\", LOG_LEVEL_VERBOSE);\n this._log(e);\n return false;\n }\n }\n private async openKeyValueDB(): Promise<boolean> {\n await delay(10);\n try {\n await this.tryCloseKvDB();\n await delay(10);\n await yieldMicrotask();\n this._kvDB = await this.openKeyValueDatabase(this.vault.getVaultName() + \"-livesync-kv\");\n await yieldMicrotask();\n await delay(100);\n } catch (e) {\n this._kvDB = undefined!;\n this._log(\"Failed to open KeyValueDB\", LOG_LEVEL_NOTICE);\n this._log(e, LOG_LEVEL_VERBOSE);\n return false;\n }\n return true;\n }\n // Called when another database; LiveSyncLocalDB, is being unloaded.\n // We need to close our KeyValueDB to avoid IndexedDB locking issues.\n private async _onOtherDatabaseUnload() {\n if (this._kvDB) await this.tryCloseKvDB();\n return Promise.resolve(true);\n }\n // Also, Called when another database; LiveSyncLocalDB, is being closed.\n // We need to close our KeyValueDB to avoid IndexedDB locking issues.\n private async _onOtherDatabaseClose() {\n if (this._kvDB) await this.tryCloseKvDB();\n return Promise.resolve(true);\n }\n\n private _everyOnInitializeDatabase(any: unknown): Promise<boolean> {\n return this.openKeyValueDB();\n }\n\n private async _everyOnloadAfterLoadSettings(): Promise<boolean> {\n if (!(await this.openKeyValueDB())) {\n return false;\n }\n this._simpleStore = this.openSimpleStore<unknown>(\"os\");\n return Promise.resolve(true);\n }\n\n constructor(context: T, dependencies: KeyValueDBDependencies<T>) {\n super(context);\n this.databaseEvents = dependencies.databaseEvents;\n this.vault = dependencies.vault;\n this.appLifecycle = dependencies.appLifecycle;\n this.openKeyValueDatabase = dependencies.openKeyValueDatabase;\n if (dependencies.registerLifecycleHandlers ?? true) {\n this.databaseEvents.onResetDatabase.addHandler(this._everyOnResetDatabase.bind(this));\n this.appLifecycle.onSettingLoaded.addHandler(this._everyOnloadAfterLoadSettings.bind(this));\n this.databaseEvents.onDatabaseInitialisation.addHandler(this._everyOnInitializeDatabase.bind(this));\n this.databaseEvents.onUnloadDatabase.addHandler(this._onOtherDatabaseUnload.bind(this));\n this.databaseEvents.onCloseDatabase.addHandler(this._onOtherDatabaseClose.bind(this));\n }\n }\n\n openSimpleStore<T>(kind: string) {\n // Creating a namespaced handle is intentionally safe during service\n // composition, before onSettingLoaded has opened the backing database.\n // Operations remain fail-fast: maintained hosts complete the sequential\n // onSettingLoaded lifecycle before scans, watchers, or replication can\n // use the handle. We must not wait here because a failed or omitted\n // lifecycle transition would otherwise wait forever, and a store access\n // from an initialisation handler could wait on its own completion.\n // Database reset is also a transient unavailable boundary; callers must\n // not perform store work during reset and can reconstruct derived state\n // after the database has reopened.\n const getDB = () => {\n if (!this._kvDB) {\n throw new Error(\"KeyValueDB is not initialized yet\");\n }\n return this._kvDB;\n };\n const prefix = `${kind}-`;\n return {\n get: async (key: string): Promise<T> => {\n return await getDB().get(`${prefix}${key}`);\n },\n set: async (key: string, value: unknown): Promise<void> => {\n await getDB().set(`${prefix}${key}`, value);\n },\n delete: async (key: string): Promise<void> => {\n await getDB().del(`${prefix}${key}`);\n },\n keys: async (from: string | undefined, to: string | undefined, count?: number): Promise<string[]> => {\n const ret = await getDB().keys(\n IDBKeyRange.bound(`${prefix}${from || \"\"}`, `${prefix}${to || \"\"}`),\n count\n );\n return ret\n .map((e) => (typeof e === \"string\" ? e : JSON.stringify(e)).toString())\n .filter((e) => e.startsWith(prefix))\n .map((e) => e.substring(prefix.length));\n },\n get db() {\n return Promise.resolve(getDB());\n },\n } satisfies SimpleStore<T>;\n }\n}\n","import type { IDatabaseService, IPathService, IVaultService, openDatabaseParameters } from \"./IService\";\nimport { ServiceBase, type ServiceContext } from \"./ServiceBase\";\nimport { LiveSyncLocalDB } from \"@lib/pouchdb/LiveSyncLocalDB\";\nimport { handlers } from \"@lib/services/lib/HandlerUtils\";\nimport { createInstanceLogFunction } from \"@lib/services/lib/logUtils.ts\";\nimport type PouchDB from \"pouchdb-core\";\nimport type { PouchDBConstructor } from \"@lib/pouchdb/PouchDBConstructor.ts\";\nimport { ExtraSuffixIndexedDB } from \"@lib/common/models/shared.const.ts\";\nimport type { SettingService } from \"./SettingService\";\nimport type { APIService } from \"./APIService\";\nimport type { ObsidianLiveSyncSettings } from \"@lib/common/models/setting.type\";\nimport { LOG_LEVEL_VERBOSE } from \"@lib/common/logger\";\n\nexport type DatabaseServiceDependencies = {\n /** PouchDB with the adapters required by the host runtime already registered. */\n pouchDB: PouchDBConstructor;\n path: IPathService;\n vault: IVaultService;\n setting: SettingService;\n API: APIService;\n};\n/**\n * The DatabaseService provides methods for managing the local database.\n * Please note that each event of database lifecycle is handled in DatabaseEventService.\n */\nexport abstract class DatabaseService<T extends ServiceContext = ServiceContext>\n extends ServiceBase<T>\n implements IDatabaseService\n{\n _log = createInstanceLogFunction(\"InjectableDatabaseService\");\n\n constructor(context: T, dependencies: DatabaseServiceDependencies) {\n super(context);\n this.services = dependencies;\n }\n\n protected _localDatabase: LiveSyncLocalDB | null = null;\n\n protected services: DatabaseServiceDependencies;\n\n // Additional process when opening database, such as initialising managers or local database instance.\n onOpenDatabase = handlers<IDatabaseService>().bailFirstFailure(\"onOpenDatabase\");\n\n /** Called after the active database has been reset and successfully reinitialised. */\n onDatabaseReset = handlers<IDatabaseService>().bailFirstFailure(\"onDatabaseReset\");\n\n get localDatabase() {\n if (!this._localDatabase) {\n throw new Error(\"Local database is not ready yet.\");\n }\n return this._localDatabase;\n }\n get localDatabaseDirect() {\n return this._localDatabase;\n }\n\n protected modifyDatabaseOptions(\n settings: ObsidianLiveSyncSettings,\n name: string,\n options: PouchDB.Configuration.DatabaseConfiguration\n ): {\n name: string;\n options: PouchDB.Configuration.DatabaseConfiguration;\n } {\n const optionPass = { ...options };\n if (settings.useIndexedDBAdapter) {\n optionPass.adapter = \"indexeddb\";\n //@ts-ignore :missing def\n optionPass.purged_infos_limit = 1;\n return {\n name: name + ExtraSuffixIndexedDB,\n options: optionPass,\n };\n }\n return {\n name: name,\n options: optionPass,\n };\n }\n\n createPouchDBInstance<T extends object>(\n name?: string,\n options?: PouchDB.Configuration.DatabaseConfiguration\n ): PouchDB.Database<T> {\n const settings = this.services.setting.currentSettings();\n const optionPass = this.modifyDatabaseOptions(settings, name ?? \"\", options ?? {});\n return new this.services.pouchDB(optionPass.name, optionPass.options);\n }\n\n async openDatabase(params: openDatabaseParameters): Promise<boolean> {\n if (this._localDatabase != null) {\n await this._localDatabase.close();\n }\n const vaultName = this.services.vault.getVaultName();\n this._log(this.context.translate(\"moduleLocalDatabase.logWaitingForReady\"));\n const env = {\n services: {\n context: this.context,\n ...this.services,\n ...params,\n database: this,\n },\n };\n const selectedDatabase = new LiveSyncLocalDB(vaultName, env);\n this._localDatabase = selectedDatabase;\n try {\n await this.onOpenDatabase(vaultName);\n const initialised = await selectedDatabase.initializeDatabase();\n if (!initialised && this._localDatabase === selectedDatabase) {\n this._localDatabase = null;\n }\n return initialised;\n } catch (error) {\n if (this._localDatabase === selectedDatabase) {\n this._localDatabase = null;\n }\n throw error;\n }\n }\n\n isDatabaseReady(): boolean {\n return this._localDatabase != null && this._localDatabase.isReady;\n }\n\n private async discardFailedActiveDatabase(database: LiveSyncLocalDB): Promise<void> {\n if (this._localDatabase === database) {\n this._localDatabase = null;\n }\n try {\n await database.close();\n } catch (error) {\n this._log(\"Failed to close the active database after a rejected lifecycle transition.\", LOG_LEVEL_VERBOSE);\n this._log(error, LOG_LEVEL_VERBOSE);\n }\n }\n\n async resetDatabase(): Promise<boolean> {\n if (!this._localDatabase) {\n return Promise.resolve(true);\n }\n const activeDatabase = this._localDatabase;\n try {\n if (!(await activeDatabase.resetDatabase())) {\n await this.discardFailedActiveDatabase(activeDatabase);\n return false;\n }\n if (!(await this.onDatabaseReset())) {\n await this.discardFailedActiveDatabase(activeDatabase);\n return false;\n }\n return true;\n } catch (error) {\n await this.discardFailedActiveDatabase(activeDatabase);\n throw error;\n }\n }\n\n /**\n * Reset the database selected by the current settings.\n *\n * A `LiveSyncLocalDB` captures its name when constructed, so changing a\n * suffix does not retarget the active instance. This operation selects and\n * opens the settings-derived database before resetting it when necessary.\n * The formerly active physical database is closed but not destroyed.\n */\n async resetDatabaseForCurrentSettings(params: openDatabaseParameters): Promise<boolean> {\n const selectedDatabaseName = this.services.vault.getVaultName();\n if (this._localDatabase?.dbname !== selectedDatabaseName) {\n if (!(await this.openDatabase(params))) {\n return false;\n }\n if (this._localDatabase?.dbname !== selectedDatabaseName) {\n return false;\n }\n }\n return await this.resetDatabase();\n }\n}\n","import { KeyValueDBService } from \"@lib/services/base/KeyValueDBService\";\nimport type { ServiceContext } from \"@lib/services/base/ServiceBase\";\nimport { DatabaseService } from \"@lib/services/base/DatabaseService.ts\";\n\nexport class HeadlessDatabaseService<T extends ServiceContext> extends DatabaseService<T> {}\n\nexport class HeadlessKeyValueDBService<T extends ServiceContext> extends KeyValueDBService<T> {}\n","import {\n decrypt,\n ENCRYPT_V2_PREFIX,\n ENCRYPT_V3_PREFIX,\n ENCRYPT_V1_PREFIX_PROBABLY,\n} from \"octagonal-wheels/encryption/encryption\";\nimport {\n encryptWithEphemeralSalt,\n decryptWithEphemeralSalt,\n HKDF_SALTED_ENCRYPTED_PREFIX,\n} from \"octagonal-wheels/encryption/hkdf\";\nimport { LOG_LEVEL_VERBOSE, Logger } from \"@lib/common/logger\";\n/**\n * Encrypts a string using a passphrase, unless the string is already encrypted.\n *\n * If the input string begins with `ENCRYPT_V2_PREFIX` or `HKDF_SALTED_ENCRYPTED_PREFIX`,\n * we assume it is already encrypted and return it unchanged.\n * Otherwise, we encrypt the string using an ephemeral salt and the provided passphrase.\n *\n * @param source - The plaintext string to encrypt, or an already encrypted string.\n * @param passphrase - The passphrase used for encryption.\n * @returns A promise resolving to the encrypted string, or the original string if it is already encrypted.\n */\nexport async function encryptString(source: string, passphrase: string): Promise<string> {\n if (source.startsWith(ENCRYPT_V2_PREFIX)) {\n return source;\n } else if (source.startsWith(HKDF_SALTED_ENCRYPTED_PREFIX)) {\n return source; // Already encrypted with ephemeral salt\n } else {\n return await encryptWithEphemeralSalt(source, passphrase);\n }\n}\n\nasync function tryDecryption(trials: (() => Promise<string>)[]): Promise<string> {\n for (const trial of trials) {\n try {\n return await trial();\n } catch (error) {\n Logger(`Decryption trial failed!`, LOG_LEVEL_VERBOSE);\n Logger(error, LOG_LEVEL_VERBOSE);\n }\n }\n throw new Error(\"All decryption trials failed\");\n}\n/**\n * Decrypts an encrypted string using the provided passphrase.\n *\n * This function determines the encryption format by inspecting the string prefix, then applies\n * the appropriate decryption method. It supports several encryption formats, including\n * HKDF salted encryption and legacy formats (V1, V2, V3). If the format is not supported,\n * an error is thrown.\n *\n * @param encrypted - The encrypted string to decrypt.\n * @param passphrase - The passphrase used for decryption.\n * @returns A promise resolving to the decrypted string.\n * @throws {Error} If the encryption format is unsupported.\n */\nexport async function decryptString(encrypted: string, passphrase: string): Promise<string> {\n if (encrypted.startsWith(HKDF_SALTED_ENCRYPTED_PREFIX)) {\n return decryptWithEphemeralSalt(encrypted, passphrase);\n } else if (\n encrypted.startsWith(ENCRYPT_V2_PREFIX) ||\n encrypted.startsWith(ENCRYPT_V3_PREFIX) ||\n encrypted.startsWith(ENCRYPT_V1_PREFIX_PROBABLY)\n ) {\n return await tryDecryption([\n async () => await decrypt(encrypted, passphrase, false),\n async () => await decrypt(encrypted, passphrase, true), // Try with legacy support\n ]);\n } else {\n throw new Error(\"Unsupported encryption format\");\n }\n}\nexport async function tryDecryptString(encrypted: string, passphrase: string | false): Promise<string | false> {\n try {\n return await decryptString(encrypted, passphrase as string);\n } catch (error) {\n Logger(`Decryption failed!`, LOG_LEVEL_VERBOSE);\n Logger(error, LOG_LEVEL_VERBOSE);\n return false;\n }\n}\n","import {\n ChunkAlgorithmNames,\n LOG_LEVEL_NOTICE,\n LOG_LEVEL_URGENT,\n LOG_LEVEL_VERBOSE,\n SALT_OF_PASSPHRASE,\n SETTING_KEY_P2P_DEVICE_NAME,\n omitP2PRuntimeSettings,\n prepareSettingsForLoad,\n type BucketSyncSetting,\n type ConfigPassphraseStore,\n type CouchDBConnection,\n type ObsidianLiveSyncSettings,\n type SettingsMigrationState,\n} from \"@lib/common/types\";\nimport { handlers } from \"@lib/services/lib/HandlerUtils\";\nimport type { IAPIService, ISettingService } from \"./IService\";\nimport { ServiceBase, type ServiceContext } from \"./ServiceBase\";\nimport { createInstanceLogFunction } from \"@lib/services/lib/logUtils\";\nimport { isCloudantURI } from \"@lib/pouchdb/utils_couchdb\";\nimport { decryptString, encryptString } from \"@lib/encryption/stringEncryption\";\nimport { encryptWithEphemeralSalt } from \"octagonal-wheels/encryption/hkdf\";\nimport {\n activateP2PRemoteConfiguration,\n activateRemoteConfiguration,\n migrateLegacyRemoteConfigurationsInPlace,\n migrateP2PActiveRemoteConfigurationIdInPlace,\n} from \"@lib/serviceFeatures/remoteConfig\";\nimport { ConnectionStringParser } from \"@lib/common/ConnectionString\";\nimport { configuredIdKey } from \"@lib/common/idDerivation\";\n\nexport interface SettingServiceDependencies {\n APIService: IAPIService;\n /** Optional host hook for applying the loaded display language to its catalogue. */\n onDisplayLanguageChanged?: (language: ObsidianLiveSyncSettings[\"displayLanguage\"]) => void;\n}\nexport abstract class SettingService<T extends ServiceContext = ServiceContext>\n extends ServiceBase<T>\n implements ISettingService\n{\n deviceAndVaultName: string = \"\";\n protected APIService: IAPIService;\n private readonly onDisplayLanguageChanged?: SettingServiceDependencies[\"onDisplayLanguageChanged\"];\n\n protected abstract setItem(key: string, value: string): void;\n protected abstract getItem(key: string): string;\n protected abstract deleteItem(key: string): void;\n\n _settings!: ObsidianLiveSyncSettings;\n\n get settings() {\n return this._settings;\n }\n set settings(value: ObsidianLiveSyncSettings) {\n this._settings = value;\n }\n\n // Save setting to the runtime storage.\n protected abstract saveData(setting: ObsidianLiveSyncSettings): Promise<void>;\n\n // Load setting from the runtime storage.\n protected abstract loadData(): Promise<ObsidianLiveSyncSettings | undefined>;\n\n private _lastPersistedSettings?: ObsidianLiveSyncSettings;\n private _settingsMigrationState?: SettingsMigrationState;\n\n getSettingsMigrationState(): SettingsMigrationState | undefined {\n return this._settingsMigrationState;\n }\n\n _log: ReturnType<typeof createInstanceLogFunction>;\n constructor(context: T, dependencies: SettingServiceDependencies) {\n super(context);\n this.APIService = dependencies.APIService;\n this.onDisplayLanguageChanged = dependencies.onDisplayLanguageChanged;\n this._log = createInstanceLogFunction(\"SettingService\", this.APIService);\n }\n\n /**\n * Adjust the given settings, e.g., migrate old settings to new format.\n * @param settings The settings to adjust.\n */\n adjustSettings(settings: ObsidianLiveSyncSettings): Promise<ObsidianLiveSyncSettings> {\n if (\n migrateLegacyRemoteConfigurationsInPlace(settings, (message) => {\n this._log(message, LOG_LEVEL_NOTICE);\n })\n ) {\n this._log(\n \"Legacy remote configuration has been migrated to the remote configuration list.\",\n LOG_LEVEL_NOTICE\n );\n }\n\n // Delete this feature to avoid problems on mobile.\n settings.disableRequestURI = true;\n\n // GC is disabled.\n settings.gcDelay = 0;\n // So, use history is always enabled.\n settings.useHistory = true;\n\n if (\"workingEncrypt\" in settings) delete settings.workingEncrypt;\n if (\"workingPassphrase\" in settings) delete settings.workingPassphrase;\n // Splitter configurations have been replaced with chunkSplitterVersion.\n if (settings.chunkSplitterVersion == \"\") {\n // Migration\n // eslint-disable-next-line @typescript-eslint/no-deprecated\n if (settings.enableChunkSplitterV2) {\n // Migration\n // eslint-disable-next-line @typescript-eslint/no-deprecated\n if (settings.useSegmenter) {\n settings.chunkSplitterVersion = \"v2-segmenter\";\n } else {\n settings.chunkSplitterVersion = \"v2\";\n }\n } else {\n settings.chunkSplitterVersion = \"\";\n }\n } else if (!(settings.chunkSplitterVersion in ChunkAlgorithmNames)) {\n settings.chunkSplitterVersion = \"\";\n }\n return Promise.resolve(settings);\n }\n /**\n * Get the unique name for identify the device.\n */\n getDeviceAndVaultName(): string {\n return this.deviceAndVaultName;\n }\n\n /**\n * Set the unique name for identify the device.\n * @param name The unique name to set.\n */\n setDeviceAndVaultName(name: string): void {\n this.deviceAndVaultName = name;\n }\n\n /**\n * Save the current device and vault name to settings, aside from the main settings.\n */\n saveDeviceAndVaultName(): void {\n const lsKey =\n \"obsidian-live-sync-vaultanddevicename-\" +\n this.APIService.getSystemVaultName() +\n this.additionalSuffixOfDatabaseName();\n this.setDeviceLocalConfig(lsKey, this.deviceAndVaultName);\n }\n\n /**\n * Read an exact key from the host's device-local configuration store.\n *\n * Unlike the main settings document, this state is not synchronised. Callers\n * which need Vault namespacing should normally use {@link getSmallConfig}.\n */\n getDeviceLocalConfig(key: string): string | null {\n return this.getItem(key);\n }\n\n /** Store an exact key in the host's non-synchronised configuration store. */\n setDeviceLocalConfig(key: string, value: string): void {\n this.setItem(key, value);\n }\n\n /** Delete an exact key from the host's non-synchronised configuration store. */\n deleteDeviceLocalConfig(key: string): void {\n this.deleteItem(key);\n }\n\n private additionalSuffixOfDatabaseName() {\n const suffix = this.settings?.additionalSuffixOfDatabaseName;\n if (typeof suffix === \"undefined\") {\n this._log(\"too early to get additionalSuffixOfDatabaseName, returning empty string\");\n return \"\";\n }\n return `-${suffix}`;\n }\n private getKey(key: string) {\n const keyMain = this.APIService.getSystemVaultName();\n const addSuffix = this.additionalSuffixOfDatabaseName();\n return `${keyMain}${addSuffix}-${key}`;\n }\n\n setSmallConfig(key: string, value: string): void {\n const dbKey = this.getKey(key);\n this.setDeviceLocalConfig(dbKey, value);\n }\n getSmallConfig(key: string): string {\n const dbKey = this.getKey(key);\n return this.getDeviceLocalConfig(dbKey) ?? \"\";\n }\n deleteSmallConfig(key: string): void {\n const dbKey = this.getKey(key);\n this.deleteDeviceLocalConfig(dbKey);\n }\n\n /**\n * Save the current settings to storage.\n */\n async saveSettingData() {\n this.saveDeviceAndVaultName();\n const previousSettings = this._lastPersistedSettings ?? this.cloneSettings(this.settings);\n const settings = this.cloneSettings(this.settings);\n const hookResults = await this.onBeforeSaveSettingData(settings, previousSettings);\n for (const patch of hookResults) {\n if (patch instanceof Error || !patch) continue;\n Object.assign(settings, patch);\n Object.assign(this.settings, patch);\n }\n const idKey = configuredIdKey(settings);\n if (settings.idDerivationVersion === 1) {\n if (idKey === false) {\n throw new Error(\"The configured ID derivation key is unavailable.\");\n }\n let passphrase: string | false = this.usedPassphrase;\n if (passphrase === \"\") {\n passphrase = await this.getPassphrase(settings);\n }\n if (passphrase === false || passphrase === \"\") {\n const message = \"Failed to retrieve a passphrase for the ID derivation key. Settings were not saved.\";\n this._log(message, LOG_LEVEL_URGENT);\n throw new Error(message);\n }\n const encryptedIdKey = await encryptString(idKey, passphrase + SALT_OF_PASSPHRASE);\n if (encryptedIdKey === \"\") {\n const message = \"Failed to encrypt the ID derivation key. Settings were not saved.\";\n this._log(message, LOG_LEVEL_URGENT);\n throw new Error(message);\n }\n settings.encryptedIdDerivationKey = encryptedIdKey;\n settings.idDerivationKey = \"\";\n this.usedPassphrase = passphrase;\n } else {\n settings.encryptedIdDerivationKey = \"\";\n }\n settings.deviceAndVaultName = \"\";\n if (settings.P2P_DevicePeerName && settings.P2P_DevicePeerName.trim() !== \"\") {\n this._log(\"Saving device peer name to small config\");\n this.setSmallConfig(SETTING_KEY_P2P_DEVICE_NAME, settings.P2P_DevicePeerName.trim());\n settings.P2P_DevicePeerName = \"\";\n }\n delete settings.P2P_managedType;\n delete settings.P2P_managedId;\n delete settings.P2P_managedToken;\n if (this.usedPassphrase == \"\" && !(await this.getPassphrase(settings))) {\n if (\n Object.values(settings.remoteConfigurations).some((config) => this.hasManagedP2PProfileURI(config.uri))\n ) {\n const message = \"Failed to retrieve a passphrase for managed P2P source data. Settings were not saved.\";\n this._log(message, LOG_LEVEL_URGENT);\n throw new Error(message);\n }\n this._log(\"Failed to retrieve passphrase. data.json contains unencrypted items!\", LOG_LEVEL_NOTICE);\n } else {\n if (\n settings.couchDB_PASSWORD != \"\" ||\n settings.couchDB_URI != \"\" ||\n settings.couchDB_USER != \"\" ||\n settings.couchDB_DBNAME\n ) {\n const connectionSetting: CouchDBConnection & BucketSyncSetting = {\n couchDB_DBNAME: settings.couchDB_DBNAME,\n couchDB_PASSWORD: settings.couchDB_PASSWORD,\n couchDB_URI: settings.couchDB_URI,\n couchDB_USER: settings.couchDB_USER,\n accessKey: settings.accessKey,\n bucket: settings.bucket,\n endpoint: settings.endpoint,\n region: settings.region,\n secretKey: settings.secretKey,\n useCustomRequestHandler: settings.useCustomRequestHandler,\n bucketCustomHeaders: settings.bucketCustomHeaders,\n couchDB_CustomHeaders: settings.couchDB_CustomHeaders,\n useJWT: settings.useJWT,\n jwtKey: settings.jwtKey,\n jwtAlgorithm: settings.jwtAlgorithm,\n jwtKid: settings.jwtKid,\n jwtExpDuration: settings.jwtExpDuration,\n jwtSub: settings.jwtSub,\n useRequestAPI: settings.useRequestAPI,\n bucketPrefix: settings.bucketPrefix,\n forcePathStyle: settings.forcePathStyle,\n };\n settings.encryptedCouchDBConnection = await this.encryptConfigurationItem(\n JSON.stringify(connectionSetting),\n settings\n );\n settings.couchDB_PASSWORD = \"\";\n settings.couchDB_DBNAME = \"\";\n settings.couchDB_URI = \"\";\n settings.couchDB_USER = \"\";\n settings.accessKey = \"\";\n settings.bucket = \"\";\n settings.region = \"\";\n settings.secretKey = \"\";\n settings.endpoint = \"\";\n }\n if (settings.encrypt && settings.passphrase != \"\") {\n settings.encryptedPassphrase = await this.encryptPlainConfigurationItem(settings.passphrase, settings);\n settings.passphrase = \"\";\n }\n await this.encryptRemoteConfigurationUris(settings);\n }\n await this.saveData(settings);\n this._lastPersistedSettings = this.cloneSettings(this.settings);\n void this.onSettingSaved(settings);\n }\n\n private async encryptRemoteConfigurationUris(settings: ObsidianLiveSyncSettings): Promise<void> {\n const configs = settings.remoteConfigurations || {};\n for (const [id, config] of Object.entries(configs)) {\n if (config.isEncrypted || config.uri.trim() === \"\") {\n continue;\n }\n const managedP2PProfile = this.hasManagedP2PProfileURI(config.uri);\n let encryptedURI: string;\n try {\n encryptedURI = await this.encryptConfigurationItem(config.uri, settings);\n } catch (error) {\n if (managedP2PProfile) {\n const message = `Failed to encrypt managed P2P remote configuration '${id}'. Settings were not saved.`;\n this._log(message, LOG_LEVEL_URGENT);\n throw new Error(message);\n }\n throw error;\n }\n if (encryptedURI === \"\") {\n if (managedP2PProfile) {\n const message = `Failed to encrypt managed P2P remote configuration '${id}'. Settings were not saved.`;\n this._log(message, LOG_LEVEL_URGENT);\n throw new Error(message);\n }\n this._log(\n `Failed to encrypt remote configuration '${id}'. This entry will be saved in plain text.`,\n LOG_LEVEL_URGENT\n );\n continue;\n }\n configs[id] = {\n ...config,\n uri: encryptedURI,\n isEncrypted: true,\n };\n }\n }\n\n private hasManagedP2PProfileURI(uri: string): boolean {\n const trimmed = uri.trim();\n if (!trimmed.startsWith(\"sls+p2p://\")) return false;\n const queryStart = trimmed.indexOf(\"?\");\n if (queryStart < 0) return false;\n const query = trimmed.slice(queryStart + 1).split(\"#\", 1)[0];\n return (new URLSearchParams(query).get(\"managedType\") ?? \"\").trim().length > 0;\n }\n\n private async decryptRemoteConfigurationUris(\n settings: ObsidianLiveSyncSettings,\n passphrase: string\n ): Promise<void> {\n const configs = settings.remoteConfigurations || {};\n for (const [id, config] of Object.entries(configs)) {\n if (!config.isEncrypted) {\n continue;\n }\n const decryptedURI = await this.decryptConfigurationItem(config.uri, passphrase);\n if (decryptedURI === false) {\n try {\n ConnectionStringParser.parse(config.uri);\n configs[id] = {\n ...config,\n isEncrypted: false,\n };\n this._log(\n `Remote configuration '${id}' had a plain-text URI marked as encrypted. The flag has been repaired.`,\n LOG_LEVEL_NOTICE\n );\n continue;\n } catch {\n // If parsing also fails, keep the original entry and report the error below.\n }\n this._log(\n `Failed to decrypt remote configuration '${id}'. Verify passphrase and configuration.`,\n LOG_LEVEL_URGENT\n );\n continue;\n }\n configs[id] = {\n ...config,\n uri: decryptedURI,\n isEncrypted: false,\n };\n }\n }\n\n /**\n * Event triggered before realising the settings.\n * Handlers can return false to abort the realisation process.\n */\n readonly onBeforeRealiseSetting = handlers<ISettingService>().bailFirstFailure(\"onBeforeRealiseSetting\");\n\n /**\n * Event triggered after the settings have been realised.\n */\n readonly onSettingRealised = handlers<ISettingService>().bailFirstFailure(\"onSettingRealised\");\n\n /**\n * Event triggered to realise the settings.\n */\n readonly onRealiseSetting = handlers<ISettingService>().bailFirstFailure(\"onRealiseSetting\");\n\n /**\n * Suspend all synchronisation activities and save to the settings.\n */\n readonly suspendAllSync = handlers<ISettingService>().all(\"suspendAllSync\");\n\n /**\n * Suspend extra synchronisation activities, e.g., hidden files sync.\n */\n readonly suspendExtraSync = handlers<ISettingService>().all(\"suspendExtraSync\");\n\n /**\n * Enable an optional feature and save to the settings.\n * @param mode The optional feature to enable.\n */\n readonly enableOptionalFeature = handlers<ISettingService>().all(\"enableOptionalFeature\");\n readonly onSettingLoaded = handlers<ISettingService>().allParallel(\"onSettingLoaded\");\n readonly onSettingChanged = handlers<ISettingService>().allParallel(\"onSettingChanged\");\n readonly onSettingSaved = handlers<ISettingService>().allParallel(\"onSettingSaved\");\n readonly onBeforeSaveSettingData = handlers<ISettingService>().dispatchParallel(\"onBeforeSaveSettingData\");\n\n /**\n * Get the current settings.\n */\n currentSettings(): ObsidianLiveSyncSettings {\n return this.settings;\n }\n\n updateSettings(\n updateFn: (settings: ObsidianLiveSyncSettings) => ObsidianLiveSyncSettings,\n saveImmediately?: boolean\n ): Promise<void> {\n try {\n const updated = updateFn(this.settings);\n this.settings = updated;\n } catch (ex) {\n this._log(\"Error in update function: \", LOG_LEVEL_URGENT);\n this._log(ex, LOG_LEVEL_VERBOSE);\n return Promise.reject(ex instanceof Error ? ex : new Error(String(ex)));\n }\n if (saveImmediately) {\n return this.saveSettingData();\n }\n return Promise.resolve();\n }\n async applyExternalSettings(partial: Partial<ObsidianLiveSyncSettings>, saveImmediately?: boolean): Promise<void> {\n try {\n this.settings = await this.adjustSettings({\n ...this.settings,\n ...omitP2PRuntimeSettings(partial),\n });\n } catch (ex) {\n this._log(\"Error in applying external settings: \", LOG_LEVEL_URGENT);\n this._log(ex, LOG_LEVEL_VERBOSE);\n return Promise.reject(ex instanceof Error ? ex : new Error(String(ex)));\n }\n if (saveImmediately) {\n return this.saveSettingData();\n }\n return Promise.resolve();\n }\n applyPartial(partial: Partial<ObsidianLiveSyncSettings>, saveImmediately?: boolean): Promise<void> {\n try {\n this.settings = { ...this.settings, ...partial };\n } catch (ex) {\n this._log(\"Error in applying partial settings: \", LOG_LEVEL_URGENT);\n this._log(ex, LOG_LEVEL_VERBOSE);\n return Promise.reject(ex instanceof Error ? ex : new Error(String(ex)));\n }\n if (saveImmediately) {\n return this.saveSettingData();\n }\n return Promise.resolve();\n }\n getPassphrase(settings: ObsidianLiveSyncSettings) {\n const methods: Record<ConfigPassphraseStore, () => Promise<string | false>> = {\n \"\": () => Promise.resolve(\"*\"),\n LOCALSTORAGE: () => Promise.resolve(this.getDeviceLocalConfig(\"ls-setting-passphrase\") ?? false),\n ASK_AT_LAUNCH: () => this.APIService.confirm.askString(\"Passphrase\", \"passphrase\", \"\"),\n };\n const method = settings.configPassphraseStore;\n const methodFunc = method in methods ? methods[method] : methods[\"\"];\n return methodFunc();\n }\n\n private usedPassphrase = \"\";\n /**\n * Clear any used passphrase from memory.\n */\n clearUsedPassphrase(): void {\n this.usedPassphrase = \"\";\n }\n\n async decryptConfigurationItem(encrypted: string, passphrase: string) {\n try {\n const dec = await decryptString(encrypted, passphrase + SALT_OF_PASSPHRASE);\n if (dec) {\n this.usedPassphrase = passphrase;\n return dec;\n }\n } catch (ex) {\n this._log(`Failed to decrypt configuration item`, LOG_LEVEL_NOTICE);\n this._log(ex, LOG_LEVEL_VERBOSE);\n }\n return false;\n }\n async encryptConfigurationItem(src: string, settings: ObsidianLiveSyncSettings) {\n return this.encryptConfigurationItemWith(src, settings, encryptString);\n }\n private async encryptPlainConfigurationItem(src: string, settings: ObsidianLiveSyncSettings) {\n return this.encryptConfigurationItemWith(src, settings, encryptWithEphemeralSalt);\n }\n private async encryptConfigurationItemWith(\n src: string,\n settings: ObsidianLiveSyncSettings,\n encrypt: (source: string, passphrase: string) => Promise<string>\n ) {\n if (this.usedPassphrase != \"\") {\n return await encrypt(src, this.usedPassphrase + SALT_OF_PASSPHRASE);\n }\n\n const passphrase = await this.getPassphrase(settings);\n if (passphrase === false) {\n this._log(\n \"Failed to obtain passphrase when saving data.json! Please verify the configuration.\",\n LOG_LEVEL_URGENT\n );\n return \"\";\n }\n const dec = await encrypt(src, passphrase + SALT_OF_PASSPHRASE);\n if (dec) {\n this.usedPassphrase = passphrase;\n return dec;\n }\n\n return \"\";\n }\n\n /**\n * Decrypt the given settings.\n * @param settings The settings to decrypt.\n */\n async decryptSettings(settings: ObsidianLiveSyncSettings): Promise<ObsidianLiveSyncSettings> {\n if (settings.idDerivationVersion !== 1) {\n configuredIdKey(settings);\n } else if (!settings.encryptedIdDerivationKey) {\n throw new Error(\"The configured ID derivation key is missing or unavailable.\");\n }\n const passphrase = await this.getPassphrase(settings);\n if (settings.idDerivationVersion === 1) {\n if (passphrase === false || passphrase === \"\") {\n throw new Error(\"The configured ID derivation key cannot be decrypted without a passphrase.\");\n }\n const decryptedIdKey = await this.decryptConfigurationItem(settings.encryptedIdDerivationKey, passphrase);\n if (decryptedIdKey === false) {\n throw new Error(\"The configured ID derivation key could not be decrypted.\");\n }\n try {\n configuredIdKey({ ...settings, idDerivationKey: decryptedIdKey });\n } catch {\n throw new Error(\"The configured ID derivation key is invalid.\");\n }\n settings.idDerivationKey = decryptedIdKey;\n }\n if (passphrase === false) {\n this._log(\"No passphrase found for data.json! Verify configuration before syncing.\", LOG_LEVEL_URGENT);\n const hasEncryptedRemoteConfigurations = Object.values(settings.remoteConfigurations || {}).some(\n (config) => config.isEncrypted\n );\n if (hasEncryptedRemoteConfigurations) {\n this._log(\n \"Encrypted remote configurations found, but passphrase is unavailable. Verify configuration before syncing.\",\n LOG_LEVEL_URGENT\n );\n }\n } else {\n if (settings.encryptedCouchDBConnection) {\n const keys = [\n \"couchDB_URI\",\n \"couchDB_USER\",\n \"couchDB_PASSWORD\",\n \"couchDB_DBNAME\",\n \"accessKey\",\n \"bucket\",\n \"endpoint\",\n \"region\",\n \"secretKey\",\n ] as (keyof CouchDBConnection | keyof BucketSyncSetting)[];\n const decrypted = this.tryDecodeJson(\n await this.decryptConfigurationItem(settings.encryptedCouchDBConnection, passphrase)\n ) as CouchDBConnection & BucketSyncSetting;\n if (decrypted) {\n for (const key of keys) {\n if (key in decrypted) {\n //@ts-ignore\n settings[key] = decrypted[key];\n }\n }\n } else {\n this._log(\n \"Failed to decrypt passphrase from data.json! Ensure configuration is correct before syncing with remote.\",\n LOG_LEVEL_URGENT\n );\n for (const key of keys) {\n //@ts-ignore\n settings[key] = \"\";\n }\n }\n }\n if (settings.encrypt && settings.encryptedPassphrase) {\n const encrypted = settings.encryptedPassphrase;\n const decrypted = await this.decryptConfigurationItem(encrypted, passphrase);\n if (decrypted) {\n settings.passphrase = decrypted;\n } else {\n this._log(\n \"Failed to decrypt passphrase from data.json! Ensure configuration is correct before syncing with remote.\",\n LOG_LEVEL_URGENT\n );\n settings.passphrase = \"\";\n }\n }\n await this.decryptRemoteConfigurationUris(settings, passphrase);\n }\n return settings;\n }\n\n async loadSettings(): Promise<void> {\n const prepared = prepareSettingsForLoad(await this.loadData());\n const { settings, ...migrationState } = prepared;\n this._settingsMigrationState = migrationState;\n const hadRemoteConfigurations = Object.keys(settings.remoteConfigurations ?? {}).length > 0;\n\n if (typeof settings.isConfigured == \"undefined\") {\n if (!prepared.isNewVault) {\n settings.isConfigured = true;\n } else {\n const appId = this.APIService.getAppID();\n settings.additionalSuffixOfDatabaseName = appId;\n settings.isConfigured = false;\n }\n }\n\n this.settings = await this.decryptSettings(settings);\n\n // I wonder can we call here.\n this.onDisplayLanguageChanged?.(this.settings.displayLanguage);\n\n await this.adjustSettings(this.settings);\n const migratedLegacyRemoteConfigurations =\n !hadRemoteConfigurations && Object.keys(this.settings.remoteConfigurations ?? {}).length > 0;\n // Run this compatibility migration only when legacy remotes were migrated in this load.\n // This prevents repeatedly overriding an intentionally empty P2P active remote selection.\n const migratedP2PActiveRemoteConfiguration =\n migratedLegacyRemoteConfigurations && migrateP2PActiveRemoteConfigurationIdInPlace(this.settings);\n\n // Keep runtime legacy fields in sync with the active remote configuration.\n // Replication and status checks still consume these fields.\n const activeConfigurationId = this.settings.activeConfigurationId;\n if (activeConfigurationId && this.settings.remoteConfigurations?.[activeConfigurationId]) {\n const activated = activateRemoteConfiguration(this.settings, activeConfigurationId);\n if (!activated) {\n this._log(\n `Failed to activate the selected remote configuration: ${activeConfigurationId}`,\n LOG_LEVEL_NOTICE\n );\n } else {\n this._log(\n `Active remote configuration '${activeConfigurationId}' has been activated.`,\n LOG_LEVEL_VERBOSE\n );\n }\n }\n\n const p2pActiveConfigurationId = this.settings.P2P_ActiveRemoteConfigurationId;\n if (p2pActiveConfigurationId && this.settings.remoteConfigurations?.[p2pActiveConfigurationId]) {\n const activatedP2P = activateP2PRemoteConfiguration(this.settings, p2pActiveConfigurationId);\n if (!activatedP2P) {\n this._log(\n `Failed to activate the selected P2P remote configuration: ${p2pActiveConfigurationId}`,\n LOG_LEVEL_NOTICE\n );\n } else {\n this._log(\n `P2P active remote configuration '${p2pActiveConfigurationId}' has been activated.`,\n LOG_LEVEL_VERBOSE\n );\n }\n }\n\n const lsKey =\n \"obsidian-live-sync-vaultanddevicename-\" +\n this.APIService.getSystemVaultName() +\n this.additionalSuffixOfDatabaseName();\n if (this.settings.deviceAndVaultName != \"\") {\n if (!this.getDeviceLocalConfig(lsKey)) {\n this.setDeviceAndVaultName(this.settings.deviceAndVaultName);\n this.saveDeviceAndVaultName();\n this.settings.deviceAndVaultName = \"\";\n }\n }\n if (isCloudantURI(this.settings.couchDB_URI) && this.settings.customChunkSize != 0) {\n this._log(\n \"Configuration issues detected and automatically resolved. However, unsynchronized data may exist. Consider rebuilding if necessary.\",\n LOG_LEVEL_NOTICE\n );\n this.settings.customChunkSize = 0;\n }\n this.setDeviceAndVaultName(this.getDeviceLocalConfig(lsKey) || \"\");\n if (this.getDeviceAndVaultName() == \"\") {\n if (this.settings.usePluginSync) {\n this._log(\"Device name missing. Disabling plug-in sync.\", LOG_LEVEL_NOTICE);\n this.settings.usePluginSync = false;\n }\n }\n\n if (\n !prepared.isFromFutureSchema &&\n (prepared.changed || migratedLegacyRemoteConfigurations || migratedP2PActiveRemoteConfiguration)\n ) {\n await this.saveSettingData();\n }\n\n this._lastPersistedSettings = this.cloneSettings(this.settings);\n\n // this.core.ignoreFiles = this.settings.ignoreFiles.split(\",\").map(e => e.trim());\n const dispatch = this.settings;\n void this.onSettingLoaded(dispatch);\n void this.onSettingChanged(dispatch);\n }\n private tryDecodeJson(encoded: string | false): object | false {\n try {\n if (!encoded) return false;\n return JSON.parse(encoded) as object;\n } catch {\n return false;\n }\n }\n\n private cloneSettings(settings: ObsidianLiveSyncSettings): ObsidianLiveSyncSettings {\n return {\n ...omitP2PRuntimeSettings(settings),\n remoteConfigurations: Object.fromEntries(\n Object.entries(settings.remoteConfigurations || {}).map(([id, config]) => [id, { ...config }])\n ),\n } as ObsidianLiveSyncSettings;\n }\n}\n","import type { JWTAlgorithm } from \"@lib/common/models/auth.type\";\nimport type { CouchDBConnection, BucketSyncSetting, P2PConnectionInfo } from \"./models/setting.type\";\nimport {\n normaliseP2PConnectionPath,\n normaliseP2PMaxWirePayloadBytes,\n} from \"./models/setting.p2p\";\n\nexport type RemoteConfigurationResult =\n | { type: \"couchdb\"; settings: CouchDBConnection }\n | { type: \"s3\"; settings: BucketSyncSetting }\n | { type: \"p2p\"; settings: P2PConnectionInfo }\n | { type: \"webdav\"; settings: never }; // TODO: Define WebDAV settings\n\n// `sls+xxx://` is a non-special scheme per the WHATWG URL spec, which means\n// `URL.host`, `URL.username`, and `URL.password` cannot be read or written.\n// We therefore parse and build URLs against a proxy special scheme (`https`)\n// and swap the prefix in/out via string manipulation.\nconst PROXY_SCHEME = \"https\";\n\nfunction parseSlsUri(uriString: string): { url: URL; subscheme: string } {\n const match = uriString.match(/^sls\\+([^:]+):(.*)$/);\n if (!match) {\n throw new Error(\"Unsupported URI\");\n }\n const subscheme = match[1];\n const rest = match[2];\n return { url: new URL(`${PROXY_SCHEME}:${rest}`), subscheme };\n}\n\nfunction withSlsScheme(url: URL, subscheme: string): string {\n const out = url.toString();\n return `sls+${subscheme}:${out.slice(PROXY_SCHEME.length + 1)}`;\n}\n\nexport class ConnectionStringParser {\n /**\n * Restore settings from URI\n */\n static parse(uriString: string): RemoteConfigurationResult {\n const match = uriString.match(/^sls\\+([^:]+):/);\n if (!match) {\n throw new Error(\"Unsupported URI\");\n }\n const subscheme = match[1];\n\n // P2P keeps the original non-special-scheme parsing because the room ID\n // can contain characters that special-scheme URL hosts cannot represent.\n if (subscheme === \"p2p\") {\n return {\n type: \"p2p\",\n settings: this.parseP2P(uriString),\n };\n }\n\n const { url } = parseSlsUri(uriString);\n switch (subscheme) {\n case \"http\":\n case \"https\":\n return {\n type: \"couchdb\",\n settings: this.parseCouchDB(url, subscheme),\n };\n case \"s3\":\n return {\n type: \"s3\",\n settings: this.parseS3(url),\n };\n default:\n throw new Error(\"Unsupported protocol\");\n }\n }\n\n /**\n * 設定からURIを生成する\n */\n static serialize(config: RemoteConfigurationResult): string {\n switch (config.type) {\n case \"couchdb\":\n return this.serializeCouchDB(config.settings);\n case \"s3\":\n return this.serializeS3(config.settings);\n case \"p2p\":\n return this.serializeP2P(config.settings);\n default:\n throw new Error(`Unsupported type: ${config.type}`);\n }\n }\n\n private static parseCouchDB(url: URL, originalScheme: string): CouchDBConnection {\n return {\n couchDB_URI: `${originalScheme}://${url.host}${url.pathname === \"/\" ? \"\" : url.pathname}`,\n couchDB_USER: decodeURIComponent(url.username),\n couchDB_PASSWORD: decodeURIComponent(url.password),\n couchDB_DBNAME: url.searchParams.get(\"db\") || \"\",\n couchDB_CustomHeaders: url.searchParams.get(\"headers\") || \"\",\n useJWT: url.searchParams.get(\"useJWT\") === \"true\",\n jwtAlgorithm: (url.searchParams.get(\"jwtAlg\") as JWTAlgorithm) || \"\",\n jwtKey: url.searchParams.get(\"jwtKey\") || \"\",\n jwtKid: url.searchParams.get(\"jwtKid\") || \"\",\n jwtSub: url.searchParams.get(\"jwtSub\") || \"\",\n jwtExpDuration: parseInt(url.searchParams.get(\"jwtExp\") || \"5\"),\n useRequestAPI: url.searchParams.get(\"useRequestAPI\") === \"true\",\n };\n }\n\n private static serializeCouchDB(settings: CouchDBConnection): string {\n const url = new URL(settings.couchDB_URI);\n const subscheme = url.protocol.replace(\":\", \"\");\n // Build the URL using the standard scheme so username/password setters work,\n // then swap it for the sls+scheme prefix at the end.\n const newUrl = new URL(`${PROXY_SCHEME}://${url.host}${url.pathname}`);\n newUrl.username = encodeURIComponent(settings.couchDB_USER);\n newUrl.password = encodeURIComponent(settings.couchDB_PASSWORD);\n newUrl.searchParams.set(\"db\", settings.couchDB_DBNAME);\n if (settings.couchDB_CustomHeaders) newUrl.searchParams.set(\"headers\", settings.couchDB_CustomHeaders);\n if (settings.useJWT) {\n newUrl.searchParams.set(\"useJWT\", \"true\");\n newUrl.searchParams.set(\"jwtAlg\", settings.jwtAlgorithm);\n if (settings.jwtKey) newUrl.searchParams.set(\"jwtKey\", settings.jwtKey);\n if (settings.jwtKid) newUrl.searchParams.set(\"jwtKid\", settings.jwtKid);\n if (settings.jwtSub) newUrl.searchParams.set(\"jwtSub\", settings.jwtSub);\n newUrl.searchParams.set(\"jwtExp\", `${settings.jwtExpDuration || 5}`);\n }\n if (settings.useRequestAPI) newUrl.searchParams.set(\"useRequestAPI\", \"true\");\n return withSlsScheme(newUrl, subscheme);\n }\n\n private static parseS3(url: URL): BucketSyncSetting {\n const endpoint = url.searchParams.get(\"endpoint\") || `https://${url.host}`;\n return {\n accessKey: decodeURIComponent(url.username),\n secretKey: decodeURIComponent(url.password),\n endpoint,\n bucket: url.searchParams.get(\"bucket\") || \"\",\n region: url.searchParams.get(\"region\") || \"auto\",\n bucketPrefix: url.searchParams.get(\"prefix\") || \"\",\n useCustomRequestHandler: url.searchParams.get(\"useProxy\") === \"true\",\n bucketCustomHeaders: url.searchParams.get(\"headers\") || \"\",\n forcePathStyle: url.searchParams.get(\"pathStyle\") !== \"false\",\n };\n }\n\n private static serializeS3(settings: BucketSyncSetting): string {\n const url = new URL(settings.endpoint);\n const newUrl = new URL(`${PROXY_SCHEME}://${url.host}`);\n newUrl.username = encodeURIComponent(settings.accessKey);\n newUrl.password = encodeURIComponent(settings.secretKey);\n newUrl.searchParams.set(\"endpoint\", settings.endpoint);\n newUrl.searchParams.set(\"bucket\", settings.bucket);\n newUrl.searchParams.set(\"region\", settings.region);\n if (settings.bucketPrefix) newUrl.searchParams.set(\"prefix\", settings.bucketPrefix);\n if (settings.bucketCustomHeaders) newUrl.searchParams.set(\"headers\", settings.bucketCustomHeaders);\n if (settings.useCustomRequestHandler) newUrl.searchParams.set(\"useProxy\", \"true\");\n if (!settings.forcePathStyle) newUrl.searchParams.set(\"pathStyle\", \"false\");\n return withSlsScheme(newUrl, \"s3\");\n }\n\n private static parseP2P(uriString: string): P2PConnectionInfo {\n const match = uriString.match(/^sls\\+p2p:\\/\\/([^?#]+)(?:\\?([^#]*))?(?:#(.*))?$/);\n if (!match) throw new Error(\"Invalid P2P URI\");\n const authority = match[1];\n const queryString = match[2] || \"\";\n\n let userinfo = \"\";\n let host = authority;\n const lastAtIndex = authority.lastIndexOf(\"@\");\n if (lastAtIndex !== -1) {\n userinfo = authority.slice(0, lastAtIndex);\n host = authority.slice(lastAtIndex + 1);\n }\n\n let password = \"\";\n if (userinfo) {\n const colonIndex = userinfo.indexOf(\":\");\n if (colonIndex !== -1) {\n password = userinfo.slice(colonIndex + 1);\n }\n }\n\n const searchParams = new URLSearchParams(queryString);\n return {\n P2P_Enabled: searchParams.get(\"enabled\") !== \"false\",\n P2P_roomID: decodeURIComponent(host),\n P2P_passphrase: decodeURIComponent(password),\n P2P_relays: searchParams.get(\"relays\") || \"\",\n P2P_AppID: searchParams.get(\"appId\") || \"self-hosted-livesync\",\n P2P_AutoStart: searchParams.get(\"autoStart\") === \"true\",\n P2P_AutoBroadcast: searchParams.get(\"autoBroadcast\") === \"true\",\n P2P_turnServers: searchParams.get(\"turnServers\") || \"\",\n P2P_turnUsername: searchParams.get(\"turnUser\") || \"\",\n P2P_turnCredential: searchParams.get(\"turnPass\") || \"\",\n P2P_maxWirePayloadBytes: normaliseP2PMaxWirePayloadBytes(Number(searchParams.get(\"maxWirePayloadBytes\"))),\n P2P_connectionPath: normaliseP2PConnectionPath(searchParams.get(\"connectionPath\")),\n P2P_managedType: searchParams.get(\"managedType\") || undefined,\n P2P_managedId: searchParams.get(\"managedId\") || undefined,\n P2P_managedToken: searchParams.get(\"token\") || undefined,\n };\n }\n\n private static serializeP2P(settings: P2PConnectionInfo): string {\n const searchParams = new URLSearchParams();\n if (!settings.P2P_Enabled) searchParams.set(\"enabled\", \"false\");\n searchParams.set(\"relays\", settings.P2P_relays);\n searchParams.set(\"appId\", settings.P2P_AppID);\n if (settings.P2P_AutoStart) searchParams.set(\"autoStart\", \"true\");\n if (settings.P2P_AutoBroadcast) searchParams.set(\"autoBroadcast\", \"true\");\n if (settings.P2P_turnServers) searchParams.set(\"turnServers\", settings.P2P_turnServers);\n if (settings.P2P_turnUsername) searchParams.set(\"turnUser\", settings.P2P_turnUsername);\n if (settings.P2P_turnCredential) searchParams.set(\"turnPass\", settings.P2P_turnCredential);\n searchParams.set(\n \"maxWirePayloadBytes\",\n String(normaliseP2PMaxWirePayloadBytes(settings.P2P_maxWirePayloadBytes))\n );\n searchParams.set(\"connectionPath\", normaliseP2PConnectionPath(settings.P2P_connectionPath));\n if (settings.P2P_managedType) searchParams.set(\"managedType\", settings.P2P_managedType);\n if (settings.P2P_managedId) searchParams.set(\"managedId\", settings.P2P_managedId);\n if (settings.P2P_managedToken) searchParams.set(\"token\", settings.P2P_managedToken);\n\n const credentials = settings.P2P_passphrase ? `:${encodeURIComponent(settings.P2P_passphrase)}@` : \"\";\n const host = encodeURIComponent(settings.P2P_roomID);\n const query = searchParams.toString() ? `?${searchParams.toString()}` : \"\";\n return `sls+p2p://${credentials}${host}${query}`;\n }\n}\n","import { LOG_LEVEL_NOTICE, LOG_LEVEL_VERBOSE, type LOG_LEVEL } from \"@lib/common/logger\";\nimport { ConnectionStringParser, type RemoteConfigurationResult } from \"@lib/common/ConnectionString\";\nimport type { ObsidianLiveSyncSettings, RemoteConfiguration, RemoteDBSettings } from \"@lib/common/models/setting.type\";\nimport { REMOTE_COUCHDB, REMOTE_MINIO, REMOTE_P2P } from \"@lib/common/models/setting.const\";\nimport type { NecessaryServices } from \"@lib/interfaces/ServiceModule\";\nimport { createInstanceLogFunction } from \"@lib/services/lib/logUtils\";\n\nexport type RemoteConfigHost = NecessaryServices<\n \"setting\" | \"UI\" | \"replication\" | \"control\" | \"appLifecycle\" | \"API\",\n never\n>;\n\nexport function migrateLegacyRemoteConfigurationsInPlace(\n settings: ObsidianLiveSyncSettings,\n log?: (message: string, level?: LOG_LEVEL) => void\n): boolean {\n const hasText = (value: unknown): value is string => typeof value === \"string\" && value.trim() !== \"\";\n\n if (!settings.remoteConfigurations) {\n settings.remoteConfigurations = {};\n }\n\n if (Object.keys(settings.remoteConfigurations).length !== 0) {\n return false;\n }\n\n const hasCouchDB = hasText(settings.couchDB_URI);\n const hasS3 = hasText(settings.endpoint);\n const hasP2P = hasText(settings.P2P_roomID);\n\n if (!hasCouchDB && !hasS3 && !hasP2P) {\n return false;\n }\n\n log?.(\"Migrating existing remote configuration to sls+ format...\");\n\n const candidates: Array<{ id: string; name: string; type: \"couchdb\" | \"s3\" | \"p2p\"; enabled: boolean }> = [\n { id: \"legacy-couchdb\", name: \"CouchDB Remote\", type: \"couchdb\", enabled: hasCouchDB },\n { id: \"legacy-s3\", name: \"S3 Remote\", type: \"s3\", enabled: hasS3 },\n { id: \"legacy-p2p\", name: \"P2P Remote\", type: \"p2p\", enabled: hasP2P },\n ];\n\n for (const candidate of candidates) {\n if (!candidate.enabled) continue;\n try {\n const uri = ConnectionStringParser.serialize({\n type: candidate.type,\n settings: settings as RemoteDBSettings,\n });\n settings.remoteConfigurations[candidate.id] = {\n id: candidate.id,\n name: candidate.name,\n uri,\n isEncrypted: false,\n };\n } catch (e) {\n log?.(`Failed to migrate ${candidate.type} configuration!`);\n log?.(e as string, LOG_LEVEL_VERBOSE);\n }\n }\n\n const createdIds = Object.keys(settings.remoteConfigurations);\n if (createdIds.length === 0) {\n return false;\n }\n\n const preferredId =\n settings.remoteType === REMOTE_MINIO\n ? \"legacy-s3\"\n : settings.remoteType === REMOTE_P2P\n ? \"legacy-p2p\"\n : \"legacy-couchdb\";\n settings.activeConfigurationId = settings.remoteConfigurations[preferredId] ? preferredId : createdIds[0];\n if (settings.remoteConfigurations[\"legacy-p2p\"]) {\n settings.P2P_ActiveRemoteConfigurationId = \"legacy-p2p\";\n }\n return true;\n}\n\n/**\n * Generate a unique ID for a new remote configuration.\n * @returns A unique string identifier.\n */\nexport function createRemoteConfigurationId(): string {\n return `remote-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;\n}\n\nexport type SerializableRemoteConfigurationType = Exclude<RemoteConfigurationResult[\"type\"], \"webdav\">;\n\nexport interface UpsertRemoteConfigurationOptions {\n /**\n * Reuse this identifier to update a known profile. Omit it to allocate a new opaque identifier.\n */\n id?: string;\n /**\n * User-visible name. Omit it to derive a descriptive name from the connection settings.\n */\n name?: string;\n /**\n * Select this profile as the main remote and project it onto the compatibility fields.\n */\n activate?: boolean;\n /**\n * Select this profile for P2P features without changing the main remote selection.\n */\n activateForP2P?: boolean;\n}\n\nfunction toRemoteConfigurationResult(\n type: SerializableRemoteConfigurationType,\n settings: ObsidianLiveSyncSettings\n): RemoteConfigurationResult {\n if (type === \"couchdb\") {\n return { type, settings };\n }\n if (type === \"s3\") {\n return { type, settings };\n }\n return { type, settings };\n}\n\n/**\n * Suggest a concise display name from a serialisable remote configuration.\n *\n * The name is presentation only. Callers must continue to use the profile ID for identity and\n * `activeConfigurationId` for the selected main remote.\n */\nexport function suggestRemoteConfigurationName(configuration: RemoteConfigurationResult): string {\n if (configuration.type === \"couchdb\") {\n try {\n const host = new URL(configuration.settings.couchDB_URI).host;\n return host ? `CouchDB ${host}` : \"CouchDB remote\";\n } catch {\n return \"CouchDB remote\";\n }\n }\n if (configuration.type === \"s3\") {\n const bucket = configuration.settings.bucket.trim();\n if (bucket) {\n return `S3 ${bucket}`;\n }\n try {\n const host = new URL(configuration.settings.endpoint).host;\n return host ? `S3 ${host}` : \"Object Storage remote\";\n } catch {\n return \"Object Storage remote\";\n }\n }\n if (configuration.type === \"p2p\") {\n const room = configuration.settings.P2P_roomID.trim();\n return room ? `P2P ${room}` : \"P2P remote\";\n }\n return \"Remote configuration\";\n}\n\nfunction allocateRemoteConfigurationId(configurations: Record<string, RemoteConfiguration>): string {\n let id = createRemoteConfigurationId();\n while (configurations[id]) {\n id = createRemoteConfigurationId();\n }\n return id;\n}\n\nfunction allocateRemoteConfigurationName(\n configurations: Record<string, RemoteConfiguration>,\n baseName: string,\n updatingId?: string\n): string {\n const usedNames = new Set(\n Object.values(configurations)\n .filter((configuration) => configuration.id !== updatingId)\n .map((configuration) => configuration.name)\n );\n if (!usedNames.has(baseName)) {\n return baseName;\n }\n let suffix = 2;\n while (usedNames.has(`${baseName} (${suffix})`)) {\n suffix += 1;\n }\n return `${baseName} (${suffix})`;\n}\n\n/**\n * Create or update a multiple-remote profile from the corresponding compatibility fields.\n *\n * This mutates `settings`. Passing an existing `id` intentionally replaces that profile; omitting\n * it always allocates a new opaque ID and preserves all existing profiles. Generated display names\n * are made unique for readability, but names never act as identifiers. The stored connection URI is\n * plaintext at this boundary; `SettingService` applies configured at-rest encryption when saving it.\n */\nexport function upsertRemoteConfigurationInPlace(\n settings: ObsidianLiveSyncSettings,\n type: SerializableRemoteConfigurationType,\n options: UpsertRemoteConfigurationOptions = {}\n): RemoteConfiguration {\n if (options.activateForP2P && type !== \"p2p\") {\n throw new Error(\"Only a P2P remote configuration can be selected for P2P features.\");\n }\n const configurations = settings.remoteConfigurations ?? {};\n const requestedId = options.id?.trim();\n const id = requestedId || allocateRemoteConfigurationId(configurations);\n const existing = configurations[id];\n const serialisable = toRemoteConfigurationResult(type, settings);\n const suggestedName = suggestRemoteConfigurationName(serialisable);\n const requestedName = options.name?.trim();\n const name =\n requestedName || existing?.name || allocateRemoteConfigurationName(configurations, suggestedName, existing?.id);\n\n const configuration: RemoteConfiguration = {\n id,\n name,\n uri: ConnectionStringParser.serialize(serialisable),\n isEncrypted: false,\n };\n settings.remoteConfigurations ??= configurations;\n configurations[id] = configuration;\n\n if (options.activate) {\n if (!activateRemoteConfiguration(settings, id)) {\n throw new Error(`Failed to activate remote configuration '${id}'.`);\n }\n }\n if (options.activateForP2P) {\n if (!activateP2PRemoteConfiguration(settings, id)) {\n throw new Error(`Failed to activate P2P remote configuration '${id}'.`);\n }\n }\n return configuration;\n}\n\n/**\n * Keep compatibility for users who were already using P2P as their main active remote.\n */\nexport function migrateP2PActiveRemoteConfigurationIdInPlace(settings: ObsidianLiveSyncSettings): boolean {\n if ((settings.P2P_ActiveRemoteConfigurationId ?? \"\").trim() !== \"\") {\n return false;\n }\n const activeId = settings.activeConfigurationId;\n if (!activeId) {\n return false;\n }\n const config = settings.remoteConfigurations?.[activeId];\n if (!config) {\n return false;\n }\n if (settings.remoteType !== REMOTE_P2P) {\n return false;\n }\n try {\n const parsed = ConnectionStringParser.parse(config.uri);\n if (parsed.type !== \"p2p\") {\n return false;\n }\n } catch {\n return false;\n }\n settings.P2P_ActiveRemoteConfigurationId = activeId;\n return true;\n}\n\n/**\n * SF:RemoteConfig - Service Feature for Remote Configuration Management\n */\n\n/**\n * Migrates existing flat settings to the new multiple remote configurations list.\n */\nexport async function migrateToMultipleRemoteConfigurations(host: RemoteConfigHost): Promise<boolean> {\n const log = createInstanceLogFunction(\"SF:RemoteConfig\", host.services.API);\n const settings = host.services.setting.currentSettings();\n if (migrateLegacyRemoteConfigurationsInPlace(settings, log)) {\n await host.services.setting.saveSettingData();\n log(`Successfully migrated ${Object.keys(settings.remoteConfigurations).length} remote configuration(s).`);\n return true;\n }\n return false;\n}\n\n/**\n * Logic to switch the active configuration.\n */\nexport function activateRemoteConfiguration(\n settings: ObsidianLiveSyncSettings,\n id: string\n): ObsidianLiveSyncSettings | false {\n const config = settings.remoteConfigurations?.[id];\n if (!config) return false;\n\n settings.activeConfigurationId = id;\n\n try {\n const parsed = ConnectionStringParser.parse(config.uri);\n // Apply to legacy fields\n if (parsed.type === \"couchdb\") {\n settings.remoteType = REMOTE_COUCHDB;\n Object.assign(settings, parsed.settings);\n } else if (parsed.type === \"s3\") {\n settings.remoteType = REMOTE_MINIO;\n Object.assign(settings, parsed.settings);\n } else if (parsed.type === \"p2p\") {\n settings.remoteType = REMOTE_P2P;\n Object.assign(settings, parsed.settings);\n }\n return settings;\n } catch {\n return false;\n }\n}\n\n/**\n * Apply a dedicated P2P remote configuration onto runtime P2P-related fields,\n * while keeping the current `remoteType` unchanged.\n */\nexport function activateP2PRemoteConfiguration(\n settings: ObsidianLiveSyncSettings,\n id: string\n): ObsidianLiveSyncSettings | false {\n const config = settings.remoteConfigurations?.[id];\n if (!config) return false;\n\n try {\n const parsed = ConnectionStringParser.parse(config.uri);\n if (parsed.type !== \"p2p\") {\n return false;\n }\n const currentRemoteType = settings.remoteType;\n settings.P2P_ActiveRemoteConfigurationId = id;\n Object.assign(settings, parsed.settings);\n settings.remoteType = currentRemoteType;\n return settings;\n } catch {\n return false;\n }\n}\n\n/**\n * Command: Switch active connection\n */\nexport async function commandSwitchActiveRemote(host: RemoteConfigHost): Promise<void> {\n const settings = host.services.setting.currentSettings();\n const configs = settings.remoteConfigurations;\n if (!configs || Object.keys(configs).length === 0) {\n host.services.API.addLog(\"No remote configurations found.\", LOG_LEVEL_NOTICE, \"remote-config\");\n return;\n }\n\n const options = Object.values(configs).map((c: RemoteConfiguration) => ({\n label: `${c.name} (${c.id === settings.activeConfigurationId ? \"Active\" : \"Inactive\"})`,\n value: c.id,\n }));\n\n const selectedLabel = await host.services.UI.confirm.askSelectString(\n \"Select a remote configuration to activate\",\n options.map((o: { label: string }) => o.label)\n );\n\n if (selectedLabel) {\n const actualId = options.find((o: { label: string; value: string }) => o.label === selectedLabel)?.value;\n if (actualId) {\n let updated = false;\n await host.services.setting.updateSettings((currentSettings) => {\n const activated = activateRemoteConfiguration(currentSettings, actualId);\n if (activated) {\n updated = true;\n return activated;\n }\n return currentSettings;\n });\n if (updated) {\n host.services.API.addLog(`Switched to remote: ${selectedLabel}`, LOG_LEVEL_NOTICE, \"remote-config\");\n // control.applySettings may not necessarily trigger replication immediately.\n await host.services.control.applySettings();\n await host.services.setting.saveSettingData();\n }\n }\n }\n}\n\n/**\n * Command: Sync with a saved connection\n */\nexport async function commandReplicateWithSpecificRemote(host: RemoteConfigHost): Promise<void> {\n const settings = host.services.setting.currentSettings();\n const configs = settings.remoteConfigurations;\n if (!configs || Object.keys(configs).length === 0) {\n host.services.API.addLog(\"No remote configurations found.\", LOG_LEVEL_NOTICE, \"remote-config\");\n return;\n }\n\n const selectedName = await host.services.UI.confirm.askSelectString(\n \"Select a remote to replicate with\",\n Object.values(configs).map((c: RemoteConfiguration) => c.name)\n );\n\n if (selectedName) {\n const config = Object.values(configs).find((c: RemoteConfiguration) => c.name === selectedName);\n if (config) {\n try {\n let updated = false;\n await host.services.setting.updateSettings((currentSettings) => {\n const activated = activateRemoteConfiguration(currentSettings, config.id);\n if (activated) {\n updated = true;\n return activated;\n }\n return currentSettings;\n });\n if (updated) {\n host.services.API.addLog(\n `Switched to remote: ${selectedName} and starting replication...`,\n LOG_LEVEL_NOTICE,\n \"remote-config\"\n );\n await host.services.control.applySettings();\n await host.services.setting.saveSettingData();\n await host.services.replication.replicate(true);\n }\n } catch (e) {\n host.services.API.addLog(\n `Failed to parse remote! Detailed information is available in verbose logs.`,\n LOG_LEVEL_NOTICE,\n \"remote-config\"\n );\n host.services.API.addLog(e, LOG_LEVEL_VERBOSE, \"remote-config\");\n }\n }\n }\n}\n\n/**\n * Migration feature to be used during initialisation.\n */\nexport function useRemoteConfigurationMigration(host: RemoteConfigHost) {\n host.services.appLifecycle.onSettingLoaded.addHandler(async () => {\n try {\n await migrateToMultipleRemoteConfigurations(host);\n } catch (e) {\n host.services.API.addLog(\n `Migration failed! Detailed information is available in verbose logs.`,\n LOG_LEVEL_NOTICE,\n \"remote-config\"\n );\n host.services.API.addLog(e, LOG_LEVEL_VERBOSE, \"remote-config\");\n }\n return true;\n });\n}\n\n/**\n * Hook to set up remote configuration features (Commands).\n */\nexport function useRemoteConfiguration(host: RemoteConfigHost) {\n // Register commands\n host.services.API.addCommand({\n id: \"livesync-switch-remote\",\n name: \"Switch active connection\",\n callback: () => commandSwitchActiveRemote(host),\n });\n\n host.services.API.addCommand({\n id: \"livesync-replicate-with-specific\",\n name: \"Sync with a saved connection\",\n callback: () => commandReplicateWithSpecificRemote(host),\n });\n\n return true;\n}\n","import { EVENT_SETTING_SAVED } from \"@lib/events/coreEvents\";\nimport type { ServiceContext } from \"@lib/services/base/ServiceBase\";\nimport { SettingService, type SettingServiceDependencies } from \"@lib/services/base/SettingService\";\nimport { EVENT_REQUEST_RELOAD_SETTING_TAB } from \"@lib/events/coreEvents\";\n\nimport type { ObsidianLiveSyncSettings } from \"@lib/common/types\";\nimport { handlers } from \"@lib/services/lib/HandlerUtils\";\nimport { compatGlobal } from \"@lib/common/coreEnvFunctions\";\n\nexport class InjectableSettingService<T extends ServiceContext> extends SettingService<T> {\n constructor(context: T, dependencies: SettingServiceDependencies) {\n super(context, dependencies);\n this.onSettingSaved.addHandler((settings) => {\n this.context.events.emitEvent(EVENT_SETTING_SAVED, settings);\n return Promise.resolve(true);\n });\n this.onSettingLoaded.addHandler((settings) => {\n this.context.events.emitEvent(EVENT_REQUEST_RELOAD_SETTING_TAB);\n return Promise.resolve(true);\n });\n }\n protected setItem(key: string, value: string) {\n return compatGlobal.localStorage.setItem(key, value);\n }\n protected getItem(key: string): string {\n return compatGlobal.localStorage.getItem(key) ?? \"\";\n }\n protected deleteItem(key: string): void {\n compatGlobal.localStorage.removeItem(key);\n }\n\n // override currentSettings = handlers<SettingService<T>>().binder(\"currentSettings\");\n\n public saveData = handlers<{ saveData: (data: ObsidianLiveSyncSettings) => Promise<void> }>().binder(\"saveData\");\n public loadData = handlers<{ loadData: () => Promise<ObsidianLiveSyncSettings | undefined> }>().binder(\"loadData\");\n}\n","const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);\n\nlet idbProxyableTypes;\nlet cursorAdvanceMethods;\n// This is a function to prevent it throwing up in node environments.\nfunction getIdbProxyableTypes() {\n return (idbProxyableTypes ||\n (idbProxyableTypes = [\n IDBDatabase,\n IDBObjectStore,\n IDBIndex,\n IDBCursor,\n IDBTransaction,\n ]));\n}\n// This is a function to prevent it throwing up in node environments.\nfunction getCursorAdvanceMethods() {\n return (cursorAdvanceMethods ||\n (cursorAdvanceMethods = [\n IDBCursor.prototype.advance,\n IDBCursor.prototype.continue,\n IDBCursor.prototype.continuePrimaryKey,\n ]));\n}\nconst transactionDoneMap = new WeakMap();\nconst transformCache = new WeakMap();\nconst reverseTransformCache = new WeakMap();\nfunction promisifyRequest(request) {\n const promise = new Promise((resolve, reject) => {\n const unlisten = () => {\n request.removeEventListener('success', success);\n request.removeEventListener('error', error);\n };\n const success = () => {\n resolve(wrap(request.result));\n unlisten();\n };\n const error = () => {\n reject(request.error);\n unlisten();\n };\n request.addEventListener('success', success);\n request.addEventListener('error', error);\n });\n // This mapping exists in reverseTransformCache but doesn't exist in transformCache. This\n // is because we create many promises from a single IDBRequest.\n reverseTransformCache.set(promise, request);\n return promise;\n}\nfunction cacheDonePromiseForTransaction(tx) {\n // Early bail if we've already created a done promise for this transaction.\n if (transactionDoneMap.has(tx))\n return;\n const done = new Promise((resolve, reject) => {\n const unlisten = () => {\n tx.removeEventListener('complete', complete);\n tx.removeEventListener('error', error);\n tx.removeEventListener('abort', error);\n };\n const complete = () => {\n resolve();\n unlisten();\n };\n const error = () => {\n reject(tx.error || new DOMException('AbortError', 'AbortError'));\n unlisten();\n };\n tx.addEventListener('complete', complete);\n tx.addEventListener('error', error);\n tx.addEventListener('abort', error);\n });\n // Cache it for later retrieval.\n transactionDoneMap.set(tx, done);\n}\nlet idbProxyTraps = {\n get(target, prop, receiver) {\n if (target instanceof IDBTransaction) {\n // Special handling for transaction.done.\n if (prop === 'done')\n return transactionDoneMap.get(target);\n // Make tx.store return the only store in the transaction, or undefined if there are many.\n if (prop === 'store') {\n return receiver.objectStoreNames[1]\n ? undefined\n : receiver.objectStore(receiver.objectStoreNames[0]);\n }\n }\n // Else transform whatever we get back.\n return wrap(target[prop]);\n },\n set(target, prop, value) {\n target[prop] = value;\n return true;\n },\n has(target, prop) {\n if (target instanceof IDBTransaction &&\n (prop === 'done' || prop === 'store')) {\n return true;\n }\n return prop in target;\n },\n};\nfunction replaceTraps(callback) {\n idbProxyTraps = callback(idbProxyTraps);\n}\nfunction wrapFunction(func) {\n // Due to expected object equality (which is enforced by the caching in `wrap`), we\n // only create one new func per func.\n // Cursor methods are special, as the behaviour is a little more different to standard IDB. In\n // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the\n // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense\n // with real promises, so each advance methods returns a new promise for the cursor object, or\n // undefined if the end of the cursor has been reached.\n if (getCursorAdvanceMethods().includes(func)) {\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n func.apply(unwrap(this), args);\n return wrap(this.request);\n };\n }\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n return wrap(func.apply(unwrap(this), args));\n };\n}\nfunction transformCachableValue(value) {\n if (typeof value === 'function')\n return wrapFunction(value);\n // This doesn't return, it just creates a 'done' promise for the transaction,\n // which is later returned for transaction.done (see idbObjectHandler).\n if (value instanceof IDBTransaction)\n cacheDonePromiseForTransaction(value);\n if (instanceOfAny(value, getIdbProxyableTypes()))\n return new Proxy(value, idbProxyTraps);\n // Return the same value back if we're not going to transform it.\n return value;\n}\nfunction wrap(value) {\n // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because\n // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.\n if (value instanceof IDBRequest)\n return promisifyRequest(value);\n // If we've already transformed this value before, reuse the transformed value.\n // This is faster, but it also provides object equality.\n if (transformCache.has(value))\n return transformCache.get(value);\n const newValue = transformCachableValue(value);\n // Not all types are transformed.\n // These may be primitive types, so they can't be WeakMap keys.\n if (newValue !== value) {\n transformCache.set(value, newValue);\n reverseTransformCache.set(newValue, value);\n }\n return newValue;\n}\nconst unwrap = (value) => reverseTransformCache.get(value);\n\n/**\n * Open a database.\n *\n * @param name Name of the database.\n * @param version Schema version.\n * @param callbacks Additional callbacks.\n */\nfunction openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {\n const request = indexedDB.open(name, version);\n const openPromise = wrap(request);\n if (upgrade) {\n request.addEventListener('upgradeneeded', (event) => {\n upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction), event);\n });\n }\n if (blocked) {\n request.addEventListener('blocked', (event) => blocked(\n // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405\n event.oldVersion, event.newVersion, event));\n }\n openPromise\n .then((db) => {\n if (terminated)\n db.addEventListener('close', () => terminated());\n if (blocking) {\n db.addEventListener('versionchange', (event) => blocking(event.oldVersion, event.newVersion, event));\n }\n })\n .catch(() => { });\n return openPromise;\n}\n/**\n * Delete a database.\n *\n * @param name Name of the database.\n */\nfunction deleteDB(name, { blocked } = {}) {\n const request = indexedDB.deleteDatabase(name);\n if (blocked) {\n request.addEventListener('blocked', (event) => blocked(\n // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405\n event.oldVersion, event));\n }\n return wrap(request).then(() => undefined);\n}\n\nconst readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];\nconst writeMethods = ['put', 'add', 'delete', 'clear'];\nconst cachedMethods = new Map();\nfunction getMethod(target, prop) {\n if (!(target instanceof IDBDatabase &&\n !(prop in target) &&\n typeof prop === 'string')) {\n return;\n }\n if (cachedMethods.get(prop))\n return cachedMethods.get(prop);\n const targetFuncName = prop.replace(/FromIndex$/, '');\n const useIndex = prop !== targetFuncName;\n const isWrite = writeMethods.includes(targetFuncName);\n if (\n // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.\n !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||\n !(isWrite || readMethods.includes(targetFuncName))) {\n return;\n }\n const method = async function (storeName, ...args) {\n // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(\n const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');\n let target = tx.store;\n if (useIndex)\n target = target.index(args.shift());\n // Must reject if op rejects.\n // If it's a write operation, must reject if tx.done rejects.\n // Must reject with op rejection first.\n // Must resolve with op value.\n // Must handle both promises (no unhandled rejections)\n return (await Promise.all([\n target[targetFuncName](...args),\n isWrite && tx.done,\n ]))[0];\n };\n cachedMethods.set(prop, method);\n return method;\n}\nreplaceTraps((oldTraps) => ({\n ...oldTraps,\n get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),\n has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop),\n}));\n\nconst advanceMethodProps = ['continue', 'continuePrimaryKey', 'advance'];\nconst methodMap = {};\nconst advanceResults = new WeakMap();\nconst ittrProxiedCursorToOriginalProxy = new WeakMap();\nconst cursorIteratorTraps = {\n get(target, prop) {\n if (!advanceMethodProps.includes(prop))\n return target[prop];\n let cachedFunc = methodMap[prop];\n if (!cachedFunc) {\n cachedFunc = methodMap[prop] = function (...args) {\n advanceResults.set(this, ittrProxiedCursorToOriginalProxy.get(this)[prop](...args));\n };\n }\n return cachedFunc;\n },\n};\nasync function* iterate(...args) {\n // tslint:disable-next-line:no-this-assignment\n let cursor = this;\n if (!(cursor instanceof IDBCursor)) {\n cursor = await cursor.openCursor(...args);\n }\n if (!cursor)\n return;\n cursor = cursor;\n const proxiedCursor = new Proxy(cursor, cursorIteratorTraps);\n ittrProxiedCursorToOriginalProxy.set(proxiedCursor, cursor);\n // Map this double-proxy back to the original, so other cursor methods work.\n reverseTransformCache.set(proxiedCursor, unwrap(cursor));\n while (cursor) {\n yield proxiedCursor;\n // If one of the advancing methods was not called, call continue().\n cursor = await (advanceResults.get(proxiedCursor) || cursor.continue());\n advanceResults.delete(proxiedCursor);\n }\n}\nfunction isIteratorProp(target, prop) {\n return ((prop === Symbol.asyncIterator &&\n instanceOfAny(target, [IDBIndex, IDBObjectStore, IDBCursor])) ||\n (prop === 'iterate' && instanceOfAny(target, [IDBIndex, IDBObjectStore])));\n}\nreplaceTraps((oldTraps) => ({\n ...oldTraps,\n get(target, prop, receiver) {\n if (isIteratorProp(target, prop))\n return iterate;\n return oldTraps.get(target, prop, receiver);\n },\n has(target, prop) {\n return isIteratorProp(target, prop) || oldTraps.has(target, prop);\n },\n}));\n\nexport { deleteDB, openDB, unwrap, wrap };\n","import { deleteDB, openDB, type IDBPDatabase } from \"idb\";\nimport { serialized } from \"octagonal-wheels/concurrency/lock\";\n\nimport { LOG_LEVEL_VERBOSE, Logger } from \"@lib/common/logger\";\nimport type { KeyValueDatabase, KeyValueDatabaseFactory } from \"@lib/interfaces/KeyValueDatabase\";\n\n/** Creates an IndexedDB factory with a cache owned by the caller. */\nexport function createIndexedDBKeyValueDatabaseFactory(): KeyValueDatabaseFactory {\n const databaseCache = new Map<string, IndexedDBKeyValueDatabase>();\n\n return async (databaseKey: string): Promise<KeyValueDatabase> =>\n await serialized(`OpenKeyValueDatabase-${databaseKey}`, async () => {\n const cachedDatabase = databaseCache.get(databaseKey);\n if (cachedDatabase) {\n if (!cachedDatabase.isDestroyed) return cachedDatabase;\n await cachedDatabase.ensuredDestroyed;\n databaseCache.delete(databaseKey);\n }\n\n const database = new IndexedDBKeyValueDatabase(databaseKey);\n try {\n await database.getIsReady();\n databaseCache.set(databaseKey, database);\n return database;\n } catch (error) {\n databaseCache.delete(databaseKey);\n throw error;\n }\n });\n}\n\n/** Key-value adapter backed by one IndexedDB object store. */\nexport class IndexedDBKeyValueDatabase implements KeyValueDatabase {\n protected databasePromise: Promise<IDBPDatabase<unknown>> | null = null;\n protected readonly databaseKey: string;\n protected readonly storeKey: string;\n protected destroyed = false;\n protected destroyedPromise: Promise<void> | null = null;\n\n constructor(databaseKey: string) {\n this.databaseKey = databaseKey;\n this.storeKey = databaseKey;\n }\n\n get isDestroyed(): boolean {\n return this.destroyed;\n }\n\n get ensuredDestroyed(): Promise<void> {\n return this.destroyedPromise ?? Promise.resolve();\n }\n\n async getIsReady(): Promise<boolean> {\n await this.ensureDatabase();\n return !this.destroyed;\n }\n\n protected ensureDatabase(): Promise<IDBPDatabase<unknown>> {\n if (this.destroyed) throw new Error(\"Database is destroyed\");\n if (this.databasePromise) return this.databasePromise;\n\n this.databasePromise = openDB(this.databaseKey, undefined, {\n upgrade: (database) => {\n if (!database.objectStoreNames.contains(this.storeKey)) {\n return database.createObjectStore(this.storeKey);\n }\n },\n blocking: (currentVersion, blockedVersion) => {\n Logger(\n `Blocking database open for ${this.databaseKey}: currentVersion=${currentVersion}, blockedVersion=${blockedVersion}`,\n LOG_LEVEL_VERBOSE\n );\n void this.closeDatabase(true);\n },\n blocked: (currentVersion, blockedVersion) => {\n Logger(\n `Database open blocked for ${this.databaseKey}: currentVersion=${currentVersion}, blockedVersion=${blockedVersion}`,\n LOG_LEVEL_VERBOSE\n );\n },\n terminated: () => {\n Logger(`Database connection terminated for ${this.databaseKey}`, LOG_LEVEL_VERBOSE);\n this.databasePromise = null;\n },\n }).catch((error: unknown) => {\n this.databasePromise = null;\n throw error;\n });\n return this.databasePromise;\n }\n\n protected async closeDatabase(setDestroyed = false): Promise<void> {\n if (this.databasePromise) {\n const databasePromise = this.databasePromise;\n this.databasePromise = null;\n try {\n const database = await databasePromise;\n database.close();\n } catch (error) {\n Logger(\"Error closing database\");\n Logger(error, LOG_LEVEL_VERBOSE);\n }\n }\n if (setDestroyed) {\n this.destroyed = true;\n this.destroyedPromise = Promise.resolve();\n }\n }\n\n protected get database(): Promise<IDBPDatabase<unknown>> {\n if (this.destroyed) return Promise.reject(new Error(\"Database is destroyed\"));\n return this.ensureDatabase();\n }\n\n async get<T>(key: IDBValidKey): Promise<T> {\n return (await (await this.database).get(this.storeKey, key)) as T;\n }\n\n async set<T>(key: IDBValidKey, value: T): Promise<IDBValidKey> {\n await (await this.database).put(this.storeKey, value, key);\n return key;\n }\n\n async del(key: IDBValidKey): Promise<void> {\n await (await this.database).delete(this.storeKey, key);\n }\n\n async clear(): Promise<void> {\n await (await this.database).clear(this.storeKey);\n }\n\n async keys(query?: IDBValidKey | IDBKeyRange, count?: number): Promise<IDBValidKey[]> {\n return await (await this.database).getAllKeys(this.storeKey, query, count);\n }\n\n async close(): Promise<void> {\n await this.closeDatabase();\n }\n\n async destroy(): Promise<void> {\n this.destroyed = true;\n this.destroyedPromise = (async () => {\n await this.closeDatabase();\n await deleteDB(this.databaseKey, {\n blocked: () => Logger(`Database delete blocked for ${this.databaseKey}`),\n });\n })();\n await this.destroyedPromise;\n }\n}\n","import { type AppLifecycleService, type AppLifecycleServiceDependencies } from \"@lib/services/base/AppLifecycleService\";\n\nimport { InjectableAppLifecycleService } from \"@lib/services/implements/injectable/InjectableAppLifecycleService\";\nimport { InjectableConflictService } from \"@lib/services/implements/injectable/InjectableConflictService\";\nimport { InjectableDatabaseEventService } from \"@lib/services/implements/injectable/InjectableDatabaseEventService\";\nimport { InjectableFileProcessingService } from \"@lib/services/implements/injectable/InjectableFileProcessingService\";\nimport { PathServiceCompat } from \"@lib/services/implements/injectable/InjectablePathService\";\nimport { InjectableRemoteService } from \"@lib/services/implements/injectable/InjectableRemoteService\";\nimport { InjectableReplicationService } from \"@lib/services/implements/injectable/InjectableReplicationService\";\nimport { InjectableReplicatorService } from \"@lib/services/implements/injectable/InjectableReplicatorService\";\nimport { InjectableTestService } from \"@lib/services/implements/injectable/InjectableTestService\";\nimport { InjectableTweakValueService } from \"@lib/services/implements/injectable/InjectableTweakValueService\";\nimport { InjectableVaultServiceCompat } from \"@lib/services/implements/injectable/InjectableVaultService\";\nimport { ServiceContext } from \"@lib/services/base/ServiceBase\";\nimport { ConfigServiceBrowserCompat } from \"@lib/services/implements/browser/ConfigServiceBrowserCompat\";\nimport { InjectableServiceHub } from \"@lib/services/implements/injectable/InjectableServiceHub\";\nimport type { ServiceInstances } from \"@lib/services/ServiceHub\";\n\nimport { UIService } from \"@lib/services/implements/base/UIService\";\nimport { HeadlessAPIService } from \"./implements/headless/HeadlessAPIService\";\nimport { HeadlessDatabaseService, HeadlessKeyValueDBService } from \"./implements/headless/HeadlessDatabaseService\";\nimport type { ComponentHasResult, SvelteDialogManager } from \"./implements/base/SvelteDialog\";\nimport type { DatabaseService } from \"@lib/services/base/DatabaseService.ts\";\nimport { ControlService } from \"./base/ControlService\";\nimport { InjectableSettingService } from \"./implements/injectable/InjectableSettingService\";\nimport type { Constructor } from \"@lib/common/utils.type\";\nimport { createIndexedDBKeyValueDatabaseFactory } from \"@lib/databases/IndexedDBKeyValueDatabase\";\nimport type { KeyValueDatabaseFactory } from \"@lib/interfaces/KeyValueDatabase\";\nimport type { PouchDBConstructor } from \"@lib/pouchdb/PouchDBConstructor.ts\";\nimport type { ObsidianLiveSyncSettings } from \"@lib/common/types\";\n\nclass HeadlessAppLifecycleService<T extends ServiceContext> extends InjectableAppLifecycleService<T> {\n constructor(context: T, dependencies: AppLifecycleServiceDependencies) {\n super(context, dependencies);\n // The main entry point when the environment is ready\n // const onReady = this.onReady.bind(this);\n // In headless, we must call onReady externally when ready\n }\n}\n\nclass HeadlessSvelteDialogManager<T extends ServiceContext> implements SvelteDialogManager<T> {\n openSvelteDialog<T, U>(component: ComponentHasResult<T, U>, initialData?: U): Promise<T | undefined> {\n throw new Error(\"Method not implemented.\");\n }\n open<T, U = T>(component: ComponentHasResult<T, U>, initialData?: U): Promise<T | undefined> {\n return this.openSvelteDialog(component, initialData);\n }\n openWithExplicitCancel<T, U = T>(component: ComponentHasResult<T, U>, initialData?: U): Promise<T> {\n throw new Error(\"Method not implemented.\");\n }\n}\n\ntype HeadlessUIServiceDependencies<T extends ServiceContext = ServiceContext> = {\n APIService: HeadlessAPIService<T>;\n};\n\nclass HeadlessUIService<T extends ServiceContext> extends UIService<T> {\n override get dialogToCopy(): never {\n throw new Error(\"Method not implemented.\");\n }\n constructor(context: T, dependents: HeadlessUIServiceDependencies<T>) {\n const headlessSvelteDialogManager = new HeadlessSvelteDialogManager<T>();\n super(context, {\n dialogManager: headlessSvelteDialogManager,\n APIService: dependents.APIService,\n });\n }\n}\n// type Constructor<T> = new (...args: any[]) => T;\n\nexport class HeadlessServiceHub<T extends ServiceContext> extends InjectableServiceHub<T> {\n constructor(\n _context: T | undefined,\n overrideServiceConstructor: {\n /** PouchDB with the adapters required by this headless runtime. */\n pouchDB: PouchDBConstructor;\n database?: Constructor<DatabaseService<T>>;\n openKeyValueDatabase?: KeyValueDatabaseFactory;\n onDisplayLanguageChanged?: (language: ObsidianLiveSyncSettings[\"displayLanguage\"]) => void;\n /** Optional host capability when path obfuscation uses a secret distinct from content encryption. */\n getPathObfuscationPassphrase?: () => string | false;\n /** Direct database clients do not run application-level replication or key-value database lifecycles. */\n databaseLifecycleMode?: \"application\" | \"direct-access\";\n }\n ) {\n const context = (_context ?? new ServiceContext()) as T;\n const registerApplicationDatabaseLifecycle =\n (overrideServiceConstructor.databaseLifecycleMode ?? \"application\") === \"application\";\n const API = new HeadlessAPIService<T>(context);\n const conflict = new InjectableConflictService(context);\n const fileProcessing = new InjectableFileProcessingService(context);\n\n const setting = new InjectableSettingService(context, {\n APIService: API,\n onDisplayLanguageChanged: overrideServiceConstructor.onDisplayLanguageChanged,\n });\n const appLifecycle = new HeadlessAppLifecycleService<T>(context, {\n settingService: setting,\n });\n const remote = new InjectableRemoteService(context, {\n pouchDB: overrideServiceConstructor.pouchDB,\n APIService: API,\n appLifecycle: appLifecycle,\n setting: setting,\n });\n const tweakValue = new InjectableTweakValueService(context);\n const vault = new InjectableVaultServiceCompat(context, {\n settingService: setting,\n APIService: API,\n });\n const test = new InjectableTestService(context);\n const databaseEvents = new InjectableDatabaseEventService(context);\n const path = new PathServiceCompat(context, {\n settingService: setting,\n getPathObfuscationPassphrase: overrideServiceConstructor.getPathObfuscationPassphrase,\n });\n const database = new (overrideServiceConstructor.database ?? HeadlessDatabaseService<T>)(context, {\n pouchDB: overrideServiceConstructor.pouchDB,\n API: API,\n path: path,\n vault: vault,\n setting: setting,\n });\n const config = new ConfigServiceBrowserCompat<T>(context, {\n settingService: setting,\n APIService: API,\n });\n const replicator = new InjectableReplicatorService(context, {\n settingService: setting,\n appLifecycleService: appLifecycle,\n databaseEventService: databaseEvents,\n registerLifecycleHandlers: registerApplicationDatabaseLifecycle,\n });\n const replication = new InjectableReplicationService(context, {\n APIService: API,\n appLifecycleService: appLifecycle,\n replicatorService: replicator,\n settingService: setting,\n fileProcessingService: fileProcessing,\n databaseService: database,\n });\n\n const keyValueDB = new HeadlessKeyValueDBService(context, {\n openKeyValueDatabase:\n overrideServiceConstructor.openKeyValueDatabase ?? createIndexedDBKeyValueDatabaseFactory(),\n appLifecycle: appLifecycle,\n databaseEvents: databaseEvents,\n vault: vault,\n registerLifecycleHandlers: registerApplicationDatabaseLifecycle,\n });\n const control = new ControlService(context, {\n appLifecycleService: appLifecycle,\n settingService: setting,\n databaseService: database,\n fileProcessingService: fileProcessing,\n APIService: API,\n replicatorService: replicator,\n });\n const ui = new HeadlessUIService<T>(context, {\n APIService: API,\n });\n // Using 'satisfies' to ensure all services are provided\n const serviceInstancesToInit = {\n appLifecycle: appLifecycle,\n conflict: conflict,\n database: database,\n databaseEvents: databaseEvents,\n fileProcessing: fileProcessing,\n replication: replication,\n replicator: replicator,\n remote: remote,\n setting: setting,\n tweakValue: tweakValue,\n vault: vault,\n test: test,\n ui: ui,\n path: path,\n API: API,\n config: config,\n keyValueDB: keyValueDB,\n control: control,\n } satisfies Required<ServiceInstances<T>>;\n\n super(context, serviceInstancesToInit);\n }\n}\n","/**\n * Vault access layer — wraps DirectFileManipulator from livesync-commonlib.\n */\n\nimport { DirectFileManipulator } from \"../lib/livesync-commonlib/src/API/DirectFileManipulator.ts\";\nimport type { DirectFileManipulatorOptions } from \"../lib/livesync-commonlib/src/API/DirectFileManipulator.ts\";\nimport { createTextBlob } from \"../lib/livesync-commonlib/src/common/utils.ts\";\nimport type { FilePathWithPrefix } from \"../lib/livesync-commonlib/src/common/types.ts\";\nimport type { MetaEntry } from \"../lib/livesync-commonlib/src/API/DirectFileManipulatorV2.ts\";\nimport { isPathProbablyObfuscated, decrypt } from \"octagonal-wheels/encryption/encryption\";\nimport { clearHandlers } from \"../lib/livesync-commonlib/src/replication/SyncParamsHandler.ts\";\nimport { parseFrontmatterAndLinks } from \"./parse.js\";\nimport type { VaultBackend, NoteInfo, NoteListing } from \"./vault-backend.js\";\nimport { validateNotePath, isValidNotePath } from \"./note-path.js\";\nimport { deriveOrImportIdKey } from \"../lib/livesync-commonlib/src/common/idDerivation.ts\";\nimport { idDerivationOptions } from \"./id-derivation-config.js\";\nimport { deriveContent } from \"./index-sync.js\";\nimport { classifyIds, type IdFormat } from \"./id-format.js\";\nimport { checkDatabase } from \"./couchdb-preflight.js\";\n\nexport interface VaultConfig {\n couchdbUrl: string;\n couchdbUser: string;\n couchdbPassword: string;\n database: string;\n passphrase?: string;\n obfuscatePaths?: boolean;\n /**\n * LiveSync \"independent ID derivation\" key, as the recovery code\n * (`sls-id-v1:<hex>`) or a source string. Required to resolve paths to\n * document IDs on vaults created with LiveSync 1.0.33+ that use the new\n * keyed ID scheme. Leave unset for older (passphrase-derived) vaults.\n */\n idDerivationKey?: string;\n /**\n * Match LiveSync's \"Handle filenames as case-sensitive\" setting. Defaults\n * to false (the plugin default). Set true only if your vault was created\n * with that option on, otherwise obfuscated document IDs won't resolve.\n */\n caseSensitive?: boolean;\n}\n\nexport class Vault implements VaultBackend {\n // Created in init(): constructing it starts connecting, and PouchDB would\n // create a missing database, so the existence check has to come first.\n private manipulator!: DirectFileManipulator;\n private passphrase: string | undefined;\n private config: VaultConfig;\n // Resolved 64-hex ID key (from the recovery code / source string), or\n // undefined for legacy passphrase-derived vaults. Set in init().\n private idDerivationKey: string | undefined;\n // Obfuscation actually in effect after reconciling with the database, which\n // can differ from the configured value.\n private obfuscatePathsEffective = false;\n\n constructor(config: VaultConfig) {\n this.config = config;\n this.passphrase = config.passphrase;\n }\n\n private static buildOptions(config: VaultConfig, obfuscatePaths: boolean, idDerivationKey?: string): DirectFileManipulatorOptions {\n return {\n url: config.couchdbUrl,\n username: config.couchdbUser,\n password: config.couchdbPassword,\n database: config.database,\n passphrase: config.passphrase,\n obfuscatePassphrase: obfuscatePaths ? config.passphrase : undefined,\n useEden: false,\n enableCompression: false,\n handleFilenameCaseSensitive: !!config.caseSensitive,\n doNotUseFixedRevisionForChunks: false,\n ...idDerivationOptions(obfuscatePaths, idDerivationKey),\n };\n }\n\n async init(): Promise<void> {\n // Normalize the recovery code / source string to the 64-hex key once.\n if (this.config.idDerivationKey) {\n this.idDerivationKey = await deriveOrImportIdKey(this.config.idDerivationKey);\n }\n this.obfuscatePathsEffective = !!this.config.obfuscatePaths;\n await checkDatabase({\n url: this.config.couchdbUrl,\n database: this.config.database,\n username: this.config.couchdbUser,\n password: this.config.couchdbPassword,\n });\n this.manipulator = new DirectFileManipulator(Vault.buildOptions(this.config, this.obfuscatePathsEffective, this.idDerivationKey));\n await this.awaitManipulatorReady();\n await this.reconcileObfuscation();\n if (this.idDerivationKey && !this.obfuscatePathsEffective) {\n console.warn(\n \"Warning: COUCHDB_ID_DERIVATION_KEY is set but this vault does not use path obfuscation; \" +\n \"the ID key only applies to obfuscated vaults and is ignored.\",\n );\n }\n }\n\n /**\n * Await the manipulator's readiness, translating the library's ID-mismatch\n * error into actionable guidance. The library (0.1.34+) verifies at startup\n * that sampled document IDs match the configured derivation, so a v1 vault\n * with the wrong or missing key fails here instead of silently missing reads.\n */\n private async awaitManipulatorReady(): Promise<void> {\n try {\n await this.manipulator.ready.promise;\n } catch (err) {\n if (err instanceof Error && err.message.includes(\"do not match the configured ID key\")) {\n throw new Error(\n \"Vault document IDs do not match the configured ID scheme. \" +\n (this.idDerivationKey\n ? \"COUCHDB_ID_DERIVATION_KEY is set but does not match this vault; paste the exact recovery code (sls-id-v1:...) from LiveSync's \\\"Show current recovery code\\\". \"\n : \"If this vault was created with LiveSync 1.0.33+ with path obfuscation, set COUCHDB_ID_DERIVATION_KEY to the LiveSync recovery code (sls-id-v1:...). \") +\n \"If instead your LiveSync vault has \\\"Handle filenames as case-sensitive\\\" enabled, set COUCHDB_CASE_SENSITIVE=true to match it.\",\n );\n }\n throw err;\n }\n }\n\n /**\n * Detect whether the vault's document IDs are obfuscated and, if the\n * configured COUCHDB_OBFUSCATE_PROPERTIES doesn't match, correct it.\n * A mismatched setting can never work: path→id resolution misses every\n * existing note on read, and writes produce docs LiveSync clients ignore\n * (issues #4, #10). The database is the ground truth.\n */\n private async reconcileObfuscation(): Promise<void> {\n const configured = !!this.config.obfuscatePaths;\n const format = await this.detectIdFormat();\n if (format === \"empty\") return;\n if (format === \"mixed\") {\n console.warn(\n \"Warning: vault contains both obfuscated and plaintext document IDs. \" +\n `Keeping COUCHDB_OBFUSCATE_PROPERTIES=${configured}. ` +\n \"This usually means \\\"Obfuscate properties\\\" was toggled without rebuilding the database — consider rebuilding it from LiveSync.\",\n );\n return;\n }\n const actual = format === \"obfuscated\";\n if (actual === configured) return;\n if (actual && !this.passphrase) {\n throw new Error(\n \"Vault uses obfuscated document IDs (LiveSync \\\"Obfuscate properties\\\"), which requires the E2E passphrase. \" +\n \"Set COUCHDB_PASSPHRASE and COUCHDB_OBFUSCATE_PROPERTIES=true.\",\n );\n }\n console.warn(\n actual\n ? \"Warning: vault uses obfuscated document IDs but COUCHDB_OBFUSCATE_PROPERTIES is not set to true. \" +\n \"Enabling path obfuscation automatically — set COUCHDB_OBFUSCATE_PROPERTIES=true to silence this warning.\"\n : \"Warning: COUCHDB_OBFUSCATE_PROPERTIES=true but vault uses plaintext document IDs. \" +\n \"Disabling path obfuscation automatically — set COUCHDB_OBFUSCATE_PROPERTIES=false to silence this warning.\",\n );\n this.obfuscatePathsEffective = actual;\n await this.manipulator.close();\n this.manipulator = new DirectFileManipulator(Vault.buildOptions(this.config, actual, this.idDerivationKey));\n await this.awaitManipulatorReady();\n }\n\n /** Sample file-entry docs from the changes feed and classify their IDs. */\n private async detectIdFormat(): Promise<IdFormat> {\n const SAMPLE_TARGET = 20;\n const BATCH_SIZE = 100;\n const db = this.manipulator.liveSyncLocalDB.localDatabase;\n const ids: string[] = [];\n let since: string | number = 0;\n\n while (ids.length < SAMPLE_TARGET) {\n const result = await db.changes({\n since,\n limit: BATCH_SIZE,\n // Only real file entries — excludes chunks, versioninfo, milestones, sync params.\n selector: { type: { $in: [\"plain\", \"newnote\"] } },\n live: false,\n });\n for (const change of result.results) {\n if (ids.length >= SAMPLE_TARGET) break;\n ids.push(change.id);\n }\n if (result.results.length < BATCH_SIZE) break;\n since = result.last_seq;\n }\n return classifyIds(ids);\n }\n\n async close(): Promise<void> {\n this.manipulator.endWatch();\n await this.manipulator.close();\n }\n\n private static mdFilter(meta: any): boolean {\n return isValidNotePath(meta.path ?? \"\");\n }\n\n private static docToChange(doc: any, callback: (path: string, content: string | null, mtime?: number, seq?: string | number) => void, seq?: string | number) {\n const path = doc.path ?? \"\";\n if (!isValidNotePath(path)) return;\n // null => deleted (remove); \"\" => existing empty note (index it, don't drop)\n const content = deriveContent(doc);\n callback(path, content, content === null ? undefined : doc.mtime, seq);\n }\n\n async catchUp(\n since: string,\n callback: (path: string, content: string | null, mtime?: number) => void,\n onBatch?: (since: string, processed: number) => Promise<void>,\n stats?: { unreadable: number },\n ): Promise<string> {\n // Paginate _changes in batches to limit memory usage.\n const BATCH_SIZE = 50;\n const db = this.manipulator.liveSyncLocalDB.localDatabase;\n let currentSince = since;\n let totalProcessed = 0;\n\n while (true) {\n const result = await db.changes({\n include_docs: true,\n since: currentSince,\n selector: { type: { $ne: \"leaf\" } },\n live: false,\n limit: BATCH_SIZE,\n });\n\n for (const change of result.results) {\n if (!change.doc) continue;\n const meta = change.doc as any;\n // Skip chunks and system docs\n if (meta.type === \"leaf\" || meta.type === \"versioninfo\") continue;\n if (meta._id?.startsWith(\"h:\") || meta._id?.startsWith(\"_\")) continue;\n // Decrypt path to check .md BEFORE fetching chunks (avoids loading large attachments)\n let path = meta.path ?? \"\";\n if (isPathProbablyObfuscated(path) && this.passphrase) {\n try { path = await decrypt(path, this.passphrase, false); } catch {\n // Path could not be decrypted: the note is skipped and stays\n // invisible to the index. Counted so search_notes can say so.\n if (stats) stats.unreadable++;\n continue;\n }\n }\n // A deletion doesn't need the body — the decrypted path is enough\n // to remove the note. Short-circuit so a tombstone whose chunks were\n // already purged still removes it instead of silently lingering.\n if (meta.deleted) {\n if (isValidNotePath(path)) callback(path, null);\n continue;\n }\n if (!isValidNotePath(path)) continue;\n const doc = await this.manipulator.getByMeta(meta).catch(() => null);\n if (doc) {\n Vault.docToChange(doc, callback);\n } else if (stats) {\n // Chunks missing or undecryptable for a live note: a silent miss.\n stats.unreadable++;\n }\n }\n\n totalProcessed += result.results.length;\n currentSince = String(result.last_seq);\n\n // Release chunk cache between batches to prevent memory growth\n this.manipulator.liveSyncLocalDB.clearCaches();\n\n // Save checkpoint after each batch so crashes don't restart from zero\n if (onBatch && result.results.length > 0) {\n await onBatch(currentSince, totalProcessed);\n }\n\n // No more changes\n if (result.results.length < BATCH_SIZE) break;\n }\n\n this.manipulator.since = currentSince;\n return currentSince;\n }\n\n watchChanges(callback: (path: string, content: string | null, mtime?: number, seq?: string | number) => void): void {\n // catchUp already set this.manipulator.since to the right point\n this.manipulator.beginWatch(\n (doc, seq) => Vault.docToChange(doc, callback, seq),\n Vault.mdFilter,\n );\n }\n\n private validatePath(path: string): void {\n validateNotePath(path);\n }\n\n async readNote(path: string): Promise<string | null> {\n this.validatePath(path);\n const entry = await this.manipulator.get(path as FilePathWithPrefix);\n if (!entry) return null;\n if (\"data\" in entry && Array.isArray(entry.data)) {\n return entry.data.join(\"\");\n }\n return null;\n }\n\n async writeNote(path: string, content: string): Promise<boolean> {\n this.validatePath(path);\n // Clear cached PBKDF2 salt so we re-fetch from CouchDB before encrypting.\n // Prevents stale salt after Obsidian \"Overwrite remote\" rebuilds (issue #686).\n clearHandlers();\n\n // Preserve ctime if note already exists\n let ctime = Date.now();\n const existing = await this.manipulator.get(path as FilePathWithPrefix, true);\n if (existing && \"ctime\" in existing) {\n ctime = existing.ctime;\n }\n\n const blob = createTextBlob(content);\n return await this.manipulator.put(path, blob, {\n ctime,\n mtime: Date.now(),\n size: new TextEncoder().encode(content).byteLength,\n });\n }\n\n async deleteNote(path: string): Promise<boolean> {\n this.validatePath(path);\n clearHandlers();\n return await this.manipulator.delete(path);\n }\n\n async moveNote(from: string, to: string): Promise<boolean> {\n this.validatePath(from);\n this.validatePath(to);\n const content = await this.readNote(from);\n if (content === null) return false;\n const wrote = await this.writeNote(to, content);\n if (!wrote) return false;\n return await this.deleteNote(from);\n }\n\n async getMetadata(path: string): Promise<NoteInfo | null> {\n this.validatePath(path);\n const entry = await this.manipulator.get(path as FilePathWithPrefix);\n if (!entry) return null;\n const content = \"data\" in entry && Array.isArray(entry.data) ? entry.data.join(\"\") : \"\";\n return {\n path,\n size: entry.size,\n ctime: entry.ctime,\n mtime: entry.mtime,\n ...parseFrontmatterAndLinks(content),\n };\n }\n\n async listNotes(folder?: string): Promise<string[]> {\n const notes = await this.listNotesWithMtime(folder);\n return notes.map((n) => n.path);\n }\n\n async listNotesWithMtime(folder?: string): Promise<NoteListing[]> {\n if (folder && !folder.endsWith(\"/\")) folder += \"/\";\n const results: NoteListing[] = [];\n for await (const doc of this.manipulator.enumerateAllNormalDocs({ metaOnly: true })) {\n const entry = doc as MetaEntry;\n if (entry.deleted) continue;\n const notePath = entry.path ?? \"\";\n if (!isValidNotePath(notePath)) continue;\n if (folder && !notePath.startsWith(folder)) continue;\n results.push({ path: notePath, mtime: entry.mtime ?? 0 });\n }\n return results.sort((a, b) => a.path.localeCompare(b.path));\n }\n\n}\n","/**\n * Decide the manipulator's ID-derivation options from vault config.\n *\n * Kept dependency-free so the gating is unit-testable in isolation.\n *\n * The independent ID key (LiveSync 1.0.33+) only affects how an obfuscated\n * path maps to a document ID, so it must only be applied when path obfuscation\n * is actually in use. Applying it to a plaintext vault — or to a legacy\n * passphrase-derived obfuscated vault — would compute the wrong IDs. When no\n * key is configured the library keeps its legacy (version 0) scheme.\n */\nexport function idDerivationOptions(\n obfuscatePaths: boolean,\n idDerivationKey?: string,\n): { idDerivationVersion: 0 | 1; idDerivationKey?: string } {\n if (obfuscatePaths && idDerivationKey) {\n return { idDerivationVersion: 1, idDerivationKey };\n }\n return { idDerivationVersion: 0 };\n}\n","/**\n * Detection of LiveSync's \"Obfuscate properties\" from document IDs.\n *\n * With obfuscation on, file entries get hashed `_id`s prefixed `f:` instead of\n * path-based IDs, so a sample of IDs reveals which mode the vault actually\n * uses — regardless of what COUCHDB_OBFUSCATE_PROPERTIES claims.\n */\n\nexport type IdFormat = \"obfuscated\" | \"plain\" | \"mixed\" | \"empty\";\n\nexport function classifyIds(ids: string[]): IdFormat {\n let obfuscated = 0;\n let plain = 0;\n for (const id of ids) {\n if (id.startsWith(\"f:\")) obfuscated++;\n else plain++;\n }\n if (obfuscated === 0 && plain === 0) return \"empty\";\n if (obfuscated > 0 && plain > 0) return \"mixed\";\n return obfuscated > 0 ? \"obfuscated\" : \"plain\";\n}\n","/**\n * Database existence check before the LiveSync library connects.\n *\n * PouchDB's HTTP adapter sends `PUT /<db>` when the database is missing, so\n * with admin credentials a typo in COUCHDB_DATABASE silently created a new,\n * empty database. This server never creates databases: a missing database,\n * an unreachable CouchDB or an authentication error fails startup with a\n * clear message.\n * Kept free of livesync-commonlib imports so it is unit-testable in isolation.\n */\n\nexport interface DatabaseTarget {\n url: string;\n database: string;\n username: string;\n password: string;\n}\n\nexport interface CheckOptions {\n fetchImpl?: typeof fetch;\n timeoutMs?: number;\n}\n\n/**\n * Database URL with any userinfo removed (credentials go in the header, as PouchDB sends them).\n * The name goes into the path, so a query string in the base URL stays after it; a fragment is dropped.\n */\nexport function databaseUrl(url: string, database: string): string {\n const u = new URL(url);\n u.username = \"\";\n u.password = \"\";\n u.hash = \"\";\n u.pathname = `${u.pathname.replace(/\\/+$/, \"\")}/${encodeURIComponent(database)}`;\n return u.toString();\n}\n\n/** Short reason for a failed request: fetch() keeps the useful part (ECONNREFUSED, ...) in `cause`. */\nfunction networkReason(err: unknown): string {\n if (err instanceof Error) {\n if (err.name === \"TimeoutError\") return \"no response (timed out)\";\n const cause = err.cause;\n if (cause instanceof Error) return cause.message || String((cause as NodeJS.ErrnoException).code ?? cause.name);\n return err.message;\n }\n return String(err);\n}\n\n/** Resolve if the database exists; throw a readable error otherwise. Never creates anything. */\nexport async function checkDatabase(target: DatabaseTarget, options: CheckOptions = {}): Promise<void> {\n const { fetchImpl = fetch, timeoutMs = 10_000 } = options;\n if (!target.database) {\n throw new Error(\"COUCHDB_DATABASE is empty. Set it to the name of your LiveSync database.\");\n }\n const url = databaseUrl(target.url, target.database);\n const token = Buffer.from(`${target.username}:${target.password}`).toString(\"base64\");\n const headers = { Accept: \"application/json\", Authorization: `Basic ${token}` };\n\n let res: Response;\n try {\n res = await fetchImpl(url, { headers, signal: AbortSignal.timeout(timeoutMs) });\n } catch (err) {\n throw new Error(`Cannot reach CouchDB at ${url}: ${networkReason(err)}.`);\n }\n await res.body?.cancel();\n if (res.ok) return;\n if (res.status === 404) {\n throw new Error(\n `CouchDB database \"${target.database}\" does not exist at ${url}. ` +\n `This server never creates databases; check COUCHDB_DATABASE.`,\n );\n }\n if (res.status === 401 || res.status === 403) {\n throw new Error(\n `CouchDB at ${url} refused access to database \"${target.database}\" (HTTP ${res.status}). ` +\n `Check COUCHDB_USER and COUCHDB_PASSWORD, and that the user is a member of the database.`,\n );\n }\n throw new Error(`CouchDB at ${url} returned HTTP ${res.status} for database \"${target.database}\".`);\n}\n"],"mappings":";;;;;;;;;;;;;;AAIA;AAAA,EACI;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACG;AAEP,SAAS,kBAAkB,wBAAwB;;;ACV5C,IAAM,mBAAmB;AAIzB,IAAM,cAAc;AAEpB,IAAM,aAAa;AAAA,EACtB,aAAa;AAAA,EACb,aAAa;AAAA,EACb,YAAY;AAAA,EACZ,eAAe;AAAA,EACf,OAAO;AAAA,EACP,YAAY;AAAA,EACZ,cAAc;AAAA,EACd,WAAW;AAAA,EACX,iBAAiB;AAAA,EACjB,gBAAgB;AAAA,EAChB,WAAW;AACf;AAEO,IAAM,YAAY,CAAC,WAAW,aAAa,WAAW,aAAa,WAAW,UAAU;AACxF,IAAM,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,KAAK,EAAE,MAAM,UAAU,OAAO,MAAM,SAAS,EAAE,CAAC;AAAA,IAC5D;AACA,WAAO,QAAQ,KAAK,CAAC,GAAG,MAAM,EAAE,KAAK,cAAc,EAAE,IAAI,CAAC;AAAA,EAC9D;AAEJ;","names":["reviewReasons","module","crypto","crypto","error","promiseWithResolvers","promiseWithResolvers","FallbackWeakRef","unique","webcrypto","delay","unique","regExp","isTextBlob","isTextBlob","gen","promiseWithResolvers","changes","promiseWithResolvers","Logger","LOG_LEVEL_VERBOSE","Logger","LOG_LEVEL_VERBOSE","FallbackWeakRef","promiseWithResolvers","promiseWithResolvers","unique","unique","promiseWithResolvers","readString","decodeBinary","Logger","LOG_LEVEL_VERBOSE","LOG_LEVEL_INFO","readString","decodeBinary","Logger","LOG_LEVEL_VERBOSE","LOG_LEVEL_INFO","Logger","LOG_LEVEL_VERBOSE","LOG_LEVEL_NOTICE","Logger","LOG_LEVEL_VERBOSE","LOG_LEVEL_NOTICE","chunks","fallbackMixedHashEach","fallbackMixedHashEach","LOG_LEVEL_INFO","LOG_LEVEL_NOTICE","LOG_LEVEL_VERBOSE","Logger","APIService","FallbackWeakRef","doc","e","encrypt","decrypt","encryptHKDF","decryptHKDF","ex","LEVEL_INFO","LOG_LEVEL_INFO","LOG_LEVEL_NOTICE","LOG_LEVEL_VERBOSE","Logger","promiseWithResolvers","promiseWithResolvers","promiseWithResolvers","reactiveSource","reactiveSource","stripPrefix","reactiveSource","reactiveSource","reactiveSource","reactiveSource","LOG_LEVEL_URGENT","promiseWithResolvers","LOG_LEVEL_URGENT","reactiveSource","reactiveSource","webcrypto","delay","yieldMicrotask","yieldMicrotask","delay","decrypt","decrypt","encryptWithEphemeralSalt","encryptWithEphemeralSalt","encrypt","target","serialized","serialized","replication","promiseWithResolvers","stripPrefix","Logger","LOG_LEVEL_INFO","LOG_LEVEL_VERBOSE","LOG_LEVEL_NOTICE","LEVEL_INFO","isPathProbablyObfuscated","decrypt","BATCH_SIZE","isPathProbablyObfuscated","decrypt"]}