obsidian-sync-mcp 0.5.7 → 0.5.8
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.const.preferred.ts","../lib/livesync-commonlib/src/common/models/setting.const.defaults.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/pouchdb/pouchdb-http.ts","../lib/livesync-commonlib/src/common/logger.ts","../lib/livesync-commonlib/src/string_and_binary/convert.ts","../lib/livesync-commonlib/src/pouchdb/utils_couchdb.ts","../lib/livesync-commonlib/src/managers/ChunkFetcher.ts","../lib/livesync-commonlib/src/hub/hub.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/mods.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.mock.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/common/LSError.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/common/models/fileaccess.const.ts","../lib/livesync-commonlib/src/managers/EntryManager/EntryManager.ts","../lib/livesync-commonlib/src/managers/HashManager/HashManagerCore.ts","../lib/livesync-commonlib/src/string_and_binary/hash.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/services/lib/HandlerUtils.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","../src/stubs/common/events.ts","../lib/livesync-commonlib/src/services/base/UnresolvedErrorManager.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/common/messagesJson/en.json","../lib/livesync-commonlib/src/common/messages/def.ts","../lib/livesync-commonlib/src/common/messagesJson/es.json","../lib/livesync-commonlib/src/common/messages/es.ts","../lib/livesync-commonlib/src/common/messagesJson/ja.json","../lib/livesync-commonlib/src/common/messages/ja.ts","../lib/livesync-commonlib/src/common/messagesJson/ko.json","../lib/livesync-commonlib/src/common/messages/ko.ts","../lib/livesync-commonlib/src/common/messagesJson/ru.json","../lib/livesync-commonlib/src/common/messages/ru.ts","../lib/livesync-commonlib/src/common/messagesJson/zh.json","../lib/livesync-commonlib/src/common/messages/zh.ts","../lib/livesync-commonlib/src/common/messagesJson/zh-tw.json","../lib/livesync-commonlib/src/common/messages/zh-tw.ts","../lib/livesync-commonlib/src/common/messages/combinedMessages.dev.ts","../lib/livesync-commonlib/src/common/rosetta.ts","../lib/livesync-commonlib/src/common/i18n.ts","../lib/livesync-commonlib/src/services/implements/injectable/InjectableReplicationService.ts","../lib/livesync-commonlib/src/services/base/ReplicatorService.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/events/coreEvents.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","../src/stubs/common/KeyValueDB.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","../src/stubs/lib/src/common/logger.ts","../lib/livesync-commonlib/src/services/implements/base/SvelteDialog.ts","../lib/livesync-commonlib/src/encryption/stringEncryption.ts","../lib/livesync-commonlib/src/services/base/SettingService.ts","../lib/livesync-commonlib/src/services/implements/injectable/InjectableSettingService.ts","../lib/livesync-commonlib/src/services/HeadlessServices.ts","../src/vault.ts","../src/id-format.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} from \"./models/setting.const.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 { P2P_DEFAULT_SETTINGS, DEFAULT_SETTINGS } from \"./models/setting.const.defaults.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} 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 { RemoteTypes, REMOTE_COUCHDB, REMOTE_MINIO, REMOTE_P2P, type RemoteType, AutoAccepting };\nexport type { P2PConnectionInfo, P2PSyncSetting };\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 };\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 { DEVICE_ID_PREFERRED };\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 { SETTING_KEY_P2P_DEVICE_NAME, configURIBase, configURIBaseQR, SuffixDatabaseName, ExtraSuffixIndexedDB };\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;\nexport const LEAF_WAIT_TIMEOUT = 30000; // in synchronization, waiting missing leaf time out.\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\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 { 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 doNotUseFixedRevisionForChunks: false,\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: 50,\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 { ChunkAlgorithms, CURRENT_SETTING_VERSION, E2EEAlgorithms, REMOTE_COUCHDB } from \"./setting.const\";\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} as const;\n\nexport const DEFAULT_SETTINGS: 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 usePathObfuscation: 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 encryptedCouchDBConnection: \"\",\n permitEmptyPassphrase: false,\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 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 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 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};\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}\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,\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 const TweakValuesShouldMatchedTemplate: Partial<ObsidianLiveSyncSettings> = {\n minimumChunkSize: 20,\n longLineThreshold: 250,\n encrypt: false,\n usePathObfuscation: false,\n enableCompression: false,\n useEden: false,\n customChunkSize: 0,\n useDynamicIterationCount: false,\n hashAlg: \"xxhash64\",\n enableChunkSplitterV2: false,\n maxChunksInEden: 10,\n maxTotalLengthInEden: 1024,\n maxAgeInEden: 10,\n usePluginSyncV2: false,\n handleFilenameCaseSensitive: false,\n doNotUseFixedRevisionForChunks: true,\n useSegmenter: false,\n E2EEAlgorithm: E2EEAlgorithms.V2,\n chunkSplitterVersion: ChunkAlgorithms.RabinKarp,\n};\n\ntype TweakKeys = keyof TweakValues;\n\nexport const IncompatibleChanges: TweakKeys[] = [\n \"encrypt\",\n \"usePathObfuscation\",\n \"useDynamicIterationCount\",\n \"handleFilenameCaseSensitive\",\n] as const;\n\nexport const CompatibleButLossyChanges: TweakKeys[] = [\"hashAlg\"];\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 { key: \"doNotUseFixedRevisionForChunks\", from: true, to: false, isRecommendation: true },\n { key: \"doNotUseFixedRevisionForChunks\", to: true, isRecommendation: false },\n] as const;\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 doNotUseFixedRevisionForChunks: false,\n E2EEAlgorithm: E2EEAlgorithms.V2,\n chunkSplitterVersion: ChunkAlgorithms.RabinKarp,\n};\nexport const TweakValuesDefault: Partial<ObsidianLiveSyncSettings> = {\n usePluginSyncV2: false,\n E2EEAlgorithm: DEFAULT_SETTINGS.E2EEAlgorithm,\n chunkSplitterVersion: DEFAULT_SETTINGS.chunkSplitterVersion,\n};\n\nexport const TweakValuesTemplate = { ...TweakValuesRecommendedTemplate, ...TweakValuesShouldMatchedTemplate };\nexport type TweakValues = typeof TweakValuesTemplate;\n\nexport const DEVICE_ID_PREFERRED = \"PREFERRED\";\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","// @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 db\n .get(\"_local/purges\")\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 * 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","export * from \"octagonal-wheels/common/logger\";\nexport type * from \"octagonal-wheels/common/logger\";\n","// Misc\nimport {\n arrayBufferToBase64,\n base64ToArrayBuffer,\n base64ToArrayBufferInternalBrowser,\n arrayBufferToBase64Single as arrayBufferToBase64SingleInternal,\n readString,\n writeString,\n tryConvertBase64ToArrayBuffer,\n} from \"octagonal-wheels/binary\";\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 = (globalThis as any)?.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) => ((e as any) / 1) * 1000 ** i) // 45 23000 1000000\n .reduce((prev, current) => prev + current, 0); // 1023045\n}\n","import { writeString } from \"../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: any) {\n return (ex && ex?.status) == 404;\n}\n\nexport const _requestToCouchDBFetch = async (\n baseUri: string,\n username: string,\n password: string,\n path?: string,\n body?: string | any,\n method?: string\n) => {\n const utf8str = String.fromCharCode.apply(null, [...writeString(`${username}:${password}`)]);\n const encoded = globalThis.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 { delay } from \"octagonal-wheels/promises\";\nimport { unique } from \"octagonal-wheels/collection\";\nimport { LOG_LEVEL_VERBOSE, Logger } from \"../common/logger.ts\";\nimport { DEFAULT_SETTINGS, type DocumentID, type EntryLeaf } from \"../common/types.ts\";\n\nimport { type ChunkManager } from \"./ChunkManager.ts\";\n\nimport type { IReplicatorService, ISettingService } from \"../services/base/IService.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};\nconst BATCH_SIZE = 100; // Number of chunks to fetch in one request\n\nexport class ChunkFetcher {\n options: ChunkFetcherOptions;\n get chunkManager(): ChunkManager {\n return this.options.chunkManager;\n }\n\n queue = [] as DocumentID[];\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 // 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 this.abort.abort(); // Abort any ongoing requests.\n this.queue = []; // Clear the queue.\n }\n onEventHandler = this.onEvent.bind(this);\n\n onEvent(ids: DocumentID[]): void {\n this.queue = unique([...this.queue, ...ids]);\n if (this.canRequestMore()) {\n setTimeout(() => void this.requestMissingChunks(), 1);\n }\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.length > 0;\n }\n\n async requestMissingChunks(): Promise<void> {\n if (!this.canRequestMore()) {\n return; // Do not proceed if the concurrency limit is reached or the queue is empty.\n }\n try {\n // Logger(`Requesting missing chunks: ${this.queue.join(\", \")}`);\n this.currentProcessing++;\n const requestIDs = this.queue.splice(0, BATCH_SIZE);\n const now = Date.now();\n const timeSinceLastRequest = now - this.previousRequestTime;\n this.previousRequestTime = now;\n const timeToWait = Math.max(this.interval - timeSinceLastRequest, 0);\n if (timeToWait > 0) await delay(timeToWait);\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 // Request the replicator to fetch the missing chunks.\n const fetched = await replicator.fetchRemoteChunks(requestIDs, false);\n if (!fetched) {\n Logger(`No chunks were found for the following IDs: ${requestIDs.join(\", \")}`);\n for (const chunkID of requestIDs) {\n this.chunkManager.emitEvent(EVENT_MISSING_CHUNK_REMOTE, chunkID);\n }\n return;\n }\n // Validate fetched chunks (Now I am wondering why it happened...)\n function isValidChunk(chunk: Partial<EntryLeaf>): chunk is EntryLeaf {\n return chunk && typeof chunk?._id === \"string\" && typeof chunk?.data === \"string\";\n }\n const chunks = fetched.filter((chunk) => isValidChunk(chunk));\n if (chunks.length !== fetched.length) {\n Logger(\n `Some fetched chunks are invalid and will be ignored: (${fetched.length - chunks.length} / ${fetched.length}).`,\n LOG_LEVEL_VERBOSE\n );\n for (const chunk of fetched) {\n if (!isValidChunk(chunk)) {\n Logger(`Invalid chunk: ${JSON.stringify(chunk)}`, LOG_LEVEL_VERBOSE);\n }\n }\n }\n if (chunks.length === 0) {\n Logger(`No valid chunks were found for the following IDs: ${requestIDs.join(\", \")}`);\n }\n const missingIDs = requestIDs.filter((id) => !chunks.some((chunk) => chunk._id === id));\n try {\n if (chunks.length === 0) {\n return;\n }\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 if (result.result === true) {\n // Successfully written to the database\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 } catch (error) {\n Logger(`An error occurred while storing fetched chunks: ${error}`, LOG_LEVEL_VERBOSE);\n } finally {\n // Emitting fetched chunks and missing IDs regardless of write success (just only refetch will be triggered).\n for (const chunk of chunks) {\n this.chunkManager.emitEvent(EVENT_CHUNK_FETCHED, chunk);\n }\n for (const chunkID of missingIDs) {\n this.chunkManager.emitEvent(EVENT_MISSING_CHUNK_REMOTE, chunkID);\n }\n }\n // The queue is cleared after requesting.\n } finally {\n this.currentProcessing--;\n this.previousRequestTime = Date.now();\n if (this.queue.length > 0) {\n // If there are remaining items in the queue, trigger the next process.\n // Use setTimeout to release the call stack once.\n setTimeout(() => void this.requestMissingChunks(), 0);\n }\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\nexport const eventHub = new EventHub<LSEvents>();\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 \"../common/types.ts\";\nimport { Logger } from \"../common/logger.ts\";\nimport { isErrorOfMissingDoc } from \"./utils_couchdb.ts\";\n\nimport { EVENT_CHUNK_FETCHED } from \"../managers/ChunkFetcher.ts\";\nimport { eventHub } from \"../hub/hub.ts\";\nimport { FallbackWeakRef } from \"octagonal-wheels/common/polyfill\";\nimport { LiveSyncManagers } from \"../managers/LiveSyncManagers.ts\";\nimport type { AutoMergeResult } from \"../managers/ConflictManager.ts\";\nimport type { IServiceHub } from \"../services/base/IService.ts\";\nimport type { APIService } from \"../services/base/APIService.ts\";\nimport { createInstanceLogFunction, type LogFunction } from \"../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}\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 onunload() {\n //this.kvDB.close();\n void this.env.services.databaseEvents.onUnloadDatabase(this);\n this.localDatabase.removeAllListeners();\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<typeof eventHub.onEvent>;\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 async close() {\n this._log(\"Database closed (by close)\");\n this.isReady = false;\n this.offRemoteChunkFetchedHandler?.();\n if (this.localDatabase != null) {\n await this.localDatabase.close();\n }\n await this.env.services.databaseEvents.onUnloadDatabase(this);\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\n const manager = new LiveSyncManagers({\n database: this.localDatabase,\n APIService: this.env.services.API as APIService,\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 // await this.managers.initManagers();\n if (!(await this.env.services.databaseEvents.onDatabaseInitialisation(this))) {\n this._log(\"Initializing Database has been failed on some module\", LOG_LEVEL_NOTICE);\n // TODO ask for continue or disable all.\n // return false;\n }\n this._log(\"Opening Database...\");\n this._log(\"Database info\", LOG_LEVEL_VERBOSE);\n this._log(JSON.stringify(await this.localDatabase.info(), null, 2), LOG_LEVEL_VERBOSE);\n await this.managers.initialise();\n this.localDatabase.on(\"close\", () => {\n this._log(\"Database closed.\");\n this.isReady = false;\n this.localDatabase.removeAllListeners();\n this.env.services.replicator.getActiveReplicator()?.closeReplication();\n void this.managers.teardownManagers();\n });\n const _instance = new FallbackWeakRef(this);\n const unload = eventHub.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 if (!(await this.env.services.databaseEvents.onDatabaseHasReady())) {\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 }\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 await this.managers.teardownManagers();\n this.env.services.replicator.getActiveReplicator()?.closeReplication();\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 Logger(\"Database closed for reset Database.\");\n this.isReady = false;\n await this.localDatabase.destroy();\n //@ts-ignore\n this.localDatabase = null;\n await this.initializeDatabase();\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 ): Promise<false | LoadedEntry> {\n return await this.managers.entryManager.getDBEntry(path, opt, dump, waitForReady, includeDeleted);\n }\n async getDBEntryFromMeta(\n meta: LoadedEntry | MetaEntry,\n dump = false,\n waitForReady = true\n ): Promise<false | LoadedEntry> {\n return await this.managers.entryManager.getDBEntryFromMeta(meta, dump, waitForReady);\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 putDBEntry(note: SavingEntry, onlyChunks?: boolean) {\n return await this.managers.entryManager.putDBEntry(note, onlyChunks);\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 \"../string_and_binary/path.ts\";\nimport { Semaphore } from \"octagonal-wheels/concurrency/semaphore\";\nimport { arrayBufferToBase64Single, decodeBinary, writeString } from \"../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 { isErrorOfMissingDoc } from \"../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\";\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(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 globalThis?.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 globalThis.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 Array<any>, 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}\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(value: any) {\n if (typeof value === \"string\") {\n return replaceAllPairs(value, [\"|\", \"\\\\|\"], [\"`\", \"\\\\`\"]);\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: any) {\n if (ex instanceof Error) {\n return ex;\n }\n return new Error(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, any>();\nexport function isDirty(key: string, value: any) {\n const prev = previousValues.get(key);\n if (prev === value) return false;\n previousValues.set(key, value);\n return true;\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\nexport function tryParseJSON(str: string, fallbackValue?: any) {\n try {\n return JSON.parse(str);\n } catch {\n return fallbackValue;\n }\n}\n\nconst MARK_OPERATOR = `\\u{0001}`;\nconst MARK_DELETED = `${MARK_OPERATOR}__DELETED`;\nconst MARK_ISARRAY = `${MARK_OPERATOR}__ARRAY`;\nconst MARK_SWAPPED = `${MARK_OPERATOR}__SWAP`;\n\nfunction unorderedArrayToObject(obj: Array<any>) {\n return obj.map((e) => ({ [e.id as string]: e })).reduce((p, c) => ({ ...p, ...c }), {});\n}\nfunction objectToUnorderedArray(obj: object) {\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(from: Array<any>, to: Array<any>) {\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, any>,\n to: Record<string | number | symbol, any>\n) {\n const entries = Object.entries(from);\n const tempMap = new Map<string | number | symbol, any>(entries);\n const ret = {} as Record<string | number | symbol, any>;\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(v, value);\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(from: Record<string | number | symbol, any>, patch: Record<string | number | symbol, any>) {\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[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]);\n const appliedObject = applyPatch(orgArrayObject, value[MARK_ISARRAY]);\n const appliedArray = objectToUnorderedArray(appliedObject);\n ret[key] = [...appliedArray];\n } else {\n if (!(key in ret)) {\n ret[key] = value;\n continue;\n }\n ret[key] = applyPatch(ret[key], value);\n }\n } else {\n ret[key] = value;\n }\n }\n return ret;\n}\n\nexport function mergeObject(\n objA: Record<string | number | symbol, any> | [any],\n objB: Record<string | number | symbol, any> | [any]\n) {\n const newEntries = Object.entries(objB);\n const ret: any = { ...objA };\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 ret[key] = mergeObject(v, value);\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, ...value])];\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(obj: Record<string | number | symbol, any>, path: string[] = []): [string, any][] {\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, [...path, key]);\n ret.push(...p);\n }\n return ret;\n}\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 items = list\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 return list.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 };\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 };\n}\n\nexport function wrapByDefault<T, U>(func: () => T, onError: (err: Error) => U): T | U {\n try {\n return func();\n } catch (ex: any) {\n return onError(ex);\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","import { minimatch, type MinimatchOptions } from \"minimatch\";\nimport { getWebCrypto } from \"../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 \"../common/types.ts\";\nimport { memorizeFuncWithLRUCache } from \"../common/utils.ts\";\nimport { uint8ArrayToHexString, writeString } from \"./convert.ts\";\nimport { unique } from \"octagonal-wheels/collection.js\";\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 // In the specification, `:` could be accepted, LiveSync should ignore this for make things simple.\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 if (path.indexOf(\":\") === -1) return true;\n return false;\n}\nexport function stripAllPrefixes(prefixedPath: FilePathWithPrefix): FilePath {\n if (isFilePath(prefixedPath)) return prefixedPath;\n const [, body] = expandFilePathPrefix(prefixedPath);\n return stripAllPrefixes(body);\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 let [prefix, body] = path.split(\":\", 2);\n if (!body) {\n body = prefix;\n prefix = \"\";\n } else {\n prefix = prefix + \":\";\n }\n return [prefix, body as FilePathWithPrefix];\n}\nexport function expandDocumentIDPrefix(id: DocumentID): [string, FilePathWithPrefix] {\n let [prefix, body] = id.split(\":\", 2);\n if (!body) {\n body = prefix;\n prefix = \"\";\n } else {\n prefix = prefix + \":\";\n }\n return [prefix, body as FilePathWithPrefix];\n}\n\nconst _hashString = memorizeFuncWithLRUCache(async (key: string) => {\n const buff = writeString(key);\n const webcrypto = await getWebCrypto();\n let digest = await webcrypto.subtle.digest(\"SHA-256\", buff);\n const len = key.length;\n for (let i = 0; i < len; i++) {\n // Stretching\n digest = await webcrypto.subtle.digest(\"SHA-256\", buff);\n }\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): 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() as FilePathWithPrefix;\n }\n\n let x = filename;\n if (x.startsWith(\"_\")) x = (\"/\" + x) as FilePathWithPrefix;\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 hashedPassphrase = await hashString(obfuscatePassphrase);\n // Hash it!\n const out = await hashString(`${hashedPassphrase}:${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 const [prefix, body] = prefixedPath.split(\":\", 2);\n if (!body) {\n return prefix as FilePath;\n }\n return body 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 };\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 (minimatch(path, `${pattern}**`, matchOpts)) {\n return false;\n }\n }\n const newResult = pattern.startsWith(\"!\");\n const matched =\n minimatch(path, pattern, matchOpts) ||\n (!pattern.endsWith(\"/\") && minimatch(path, pattern + \"/**\", matchOpts));\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","let webcrypto: Crypto;\nexport async function getWebCrypto() {\n if (webcrypto) {\n return webcrypto;\n }\n if (globalThis.crypto) {\n webcrypto = globalThis.crypto;\n return webcrypto;\n } else {\n const module = await import(\"crypto\");\n webcrypto = module.webcrypto as Crypto;\n return webcrypto;\n }\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 \"../common/types.ts\";\nimport type { ISettingService } from \"../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 \"../common/types.ts\";\nimport { createTextBlob } from \"../common/utils.ts\";\nimport { shouldSplitAsPlainText } from \"../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 \"../common/logger.ts\";\nimport { arrayBufferToBase64Single, readString } from \"./convert.ts\";\nimport { wrapByDefault } from \"../common/utils.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\nconst segmenter =\n \"Segmenter\" in Intl\n ? wrapByDefault(\n //@ts-ignore Segmenter is not available in all browsers yet.\n () => new Intl.Segmenter(navigator.language, { granularity: \"sentence\" }),\n (err) => {\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) as [{ segment: string }];\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, any, 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, any, 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) {\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 \"../string_and_binary/chunks.ts\";\nimport type { EncryptHKDFProcessItem, EncryptProcessItem, SplitProcessItem, ProcessItem } from \"./universalTypes.ts\";\nimport { promiseWithResolvers } from \"octagonal-wheels/promises\";\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 | null>();\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() {}\n","import { ChunkAlgorithms } from \"../common/types.ts\";\nimport { splitPiecesRabinKarp } from \"../string_and_binary/chunks.ts\";\nimport { splitPieces2WorkerRabinKarp } from \"@lib/worker/bgWorker.ts\";\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 splitPieces2WorkerRabinKarp(\n options.blob,\n options.pieceSize,\n options.plainSplit,\n options.minimumChunkSize,\n options.path\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 \"../common/types\";\nimport { splitPieces2 } from \"../string_and_binary/chunks\";\nimport { splitPieces2Worker } from \"@lib/worker/bgWorker.ts\";\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 splitPieces2Worker(\n options.blob,\n options.pieceSize,\n options.plainSplit,\n options.minimumChunkSize,\n options.path,\n options.useSegmenter\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 \"../common/types.ts\";\nimport { splitPieces2V2 } from \"../string_and_binary/chunks.ts\";\nimport { splitPieces2WorkerV2 } from \"@lib/worker/bgWorker.ts\";\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 splitPieces2WorkerV2(\n options.blob,\n options.pieceSize,\n options.plainSplit,\n options.minimumChunkSize,\n options.path,\n options.useSegmenter\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 \"../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 _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 \"../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;\n}\n\nexport type ChangeManagerCallback = (change: PouchDB.Core.ChangesResponseChange<any>) => 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>[] = [];\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): () => 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): 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\";\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 readLayers: IReadLayer[];\n private writeLayers: IWriteLayer[];\n private arrivalWaitLayer: ArrivalWaitLayer;\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]) => any,\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\n // Initialise arrival wait layer\n this.arrivalWaitLayer = new ArrivalWaitLayer((eventName: string, data: DocumentID[]) => {\n if (eventName === \"missingChunks\") {\n this.emitEvent(EVENT_MISSING_CHUNKS, data);\n }\n });\n\n // Build read layers pipeline: Cache → Database → ArrivalWait\n // Cache layer implements IReadLayer interface\n this.readLayers = [this.cacheLayer, new DatabaseReadLayer(this.database), 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 }\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: any): doc is EntryLeaf {\n return doc && typeof doc._id === \"string\" && doc.type === \"leaf\";\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<EntryLeaf>): 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 \"../../common/LSError\";\nimport type { EntryLeaf, DocumentID } from \"../../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<any>) {}\n\n private isChunkDoc(doc: any): doc is EntryLeaf {\n return doc && typeof doc._id === \"string\" && doc.type === \"leaf\";\n }\n\n private getError(error: any) {\n if (error instanceof Error) {\n return error;\n }\n if (\"error\" in error && error.error instanceof Error) {\n return error.error;\n }\n return undefined;\n }\n\n private isMissingError(error: any): boolean {\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: ${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","interface ErrorWithCause extends Error {\n cause?: unknown;\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 cause?: Error;\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 && \"status\" in this.cause) {\n return this.cause.status as number;\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 this.cause = options.cause instanceof Error ? options.cause : new Error(`${options.cause}`);\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: any, errorClass: new (...args: any[]) => T): boolean {\n if (!error) {\n return false;\n }\n if (error instanceof errorClass) {\n return true;\n }\n if (error.cause) {\n return LiveSyncError.isCausedBy(error.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: any): InstanceType<T> {\n if (error instanceof this) {\n return error as InstanceType<T>;\n }\n const instance = new this(`${this.name}: ${error?.message}`, { cause: error }) as InstanceType<T>;\n if (error?.stack) {\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 { FallbackWeakRef } from \"octagonal-wheels/common/polyfill\";\nimport type { DocumentID, EntryLeaf } from \"../../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 \"../../common/types\";\nimport type { IReadLayer } from \"./ChunkLayerInterfaces\";\nimport type { ChunkReadOptions } from \"./types.ts\";\n\n/**\n * Arrival wait layer - emits events for fetcher, and waits for chunks to arrive\n */\n\nexport class ArrivalWaitLayer implements IReadLayer {\n private waitingMap = new Map<\n DocumentID,\n {\n resolver: PromiseWithResolvers<EntryLeaf | false>;\n }\n >();\n private readonly DEFAULT_TIMEOUT = 15000;\n private readonly eventEmitter: (eventName: string, data: DocumentID[]) => void;\n\n constructor(eventEmitter: (eventName: string, data: DocumentID[]) => void) {\n this.eventEmitter = eventEmitter;\n }\n\n private enqueueWaiting(id: DocumentID, timeout: number): Promise<EntryLeaf | false> {\n const previous = this.waitingMap.get(id);\n if (previous) {\n return previous.resolver.promise;\n }\n\n const resolver = promiseWithResolvers<EntryLeaf | false>();\n this.waitingMap.set(id, { resolver });\n\n return this.withTimeout(resolver.promise, timeout, () => {\n const current = this.waitingMap.get(id);\n if (current && current.resolver === resolver) {\n this.waitingMap.delete(id);\n }\n return false;\n });\n }\n\n private withTimeout<T>(proc: Promise<T>, timeout: number, onTimedOut: () => T): Promise<T> {\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n resolve(onTimedOut());\n }, timeout);\n proc.then(resolve)\n .catch(reject)\n .finally(() => {\n clearTimeout(timer);\n });\n });\n }\n\n /**\n * Handle chunk arrival (called when a chunk document arrives)\n */\n onChunkArrived(doc: EntryLeaf, deleted: boolean = false): void {\n const id = doc._id;\n if (this.waitingMap.has(id)) {\n const queue = this.waitingMap.get(id)!;\n this.waitingMap.delete(id);\n if (doc._deleted || deleted) {\n queue.resolver.resolve(false);\n } else {\n queue.resolver.resolve(doc);\n }\n }\n }\n\n /**\n * Handle missing chunk (called when a chunk is confirmed missing)\n */\n onMissingChunk(id: DocumentID): void {\n if (this.waitingMap.has(id)) {\n const queue = this.waitingMap.get(id)!;\n this.waitingMap.delete(id);\n queue.resolver.resolve(false);\n }\n }\n\n async read(\n ids: DocumentID[],\n options: ChunkReadOptions,\n next: (remaining: DocumentID[]) => Promise<(EntryLeaf | false)[]>\n ): Promise<(EntryLeaf | false)[]> {\n const timeout = options.timeout ?? this.DEFAULT_TIMEOUT;\n\n if (timeout <= 0 || ids.length === 0) {\n return ids.map(() => false);\n }\n\n // Wait for chunks to arrive\n const tasks = ids.map((id) => this.enqueueWaiting(id, timeout));\n\n if (!options.preventRemoteRequest) {\n this.eventEmitter(\"missingChunks\", ids);\n }\n\n const results = await Promise.all(tasks);\n return results;\n }\n\n /**\n * Clear all waiting requests\n */\n clearWaiting(): void {\n for (const [, queue] of this.waitingMap.entries()) {\n queue.resolver.resolve(false);\n }\n this.waitingMap.clear();\n }\n\n tearDown(): void {\n this.clearWaiting();\n }\n /**\n * Get count of waiting chunks\n */\n getWaitingCount(): number {\n return this.waitingMap.size;\n }\n}\n","import { LiveSyncError } from \"../../common/LSError\";\nimport type { EntryLeaf, DocumentID } from \"../../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<any>) {}\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: ${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 \"../common/types.ts\";\nimport {\n getDocData,\n tryParseJSON,\n generatePatchObj,\n flattenObject,\n applyPatch,\n isSensibleMargeApplicable,\n isObjectMargeApplicable,\n} from \"../common/utils.ts\";\nimport type { EntryManager } from \"../managers/EntryManager/EntryManager.ts\";\nimport { isErrorOfMissingDoc } from \"../pouchdb/utils_couchdb.ts\";\nimport type { IPathService } from \"../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\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 // Both are 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 // when completely same, leave it .\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 // when deleted evenly,\n const nextLeftIdx = leftIdx;\n const nextRightIdx = rightIdx;\n const [nextLeftItem, nextRightItem] = [\n diffLeft[nextLeftIdx] ?? [0, \"\"],\n diffRight[nextRightIdx] ?? [0, \"\"],\n ];\n if (\n nextLeftItem[0] == DIFF_INSERT &&\n nextRightItem[0] == DIFF_INSERT &&\n nextLeftItem[1] != nextRightItem[1]\n ) {\n //but next line looks like different\n autoMerge = false;\n break;\n } else {\n merged.push(leftItem);\n continue;\n }\n }\n // when inserted evenly\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 // when on inserting, index should be fixed again.\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 // except insertion, the line should not be different.\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 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 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(`Both are deleted`, LOG_LEVEL_VERBOSE);\n return false;\n }\n const baseObj = { data: tryParseJSON(baseLeaf.data, {}) } as Record<string | number | symbol, any>;\n const leftObj = { data: tryParseJSON(leftLeaf.data, {}) } as Record<string | number | symbol, any>;\n const rightObj = { data: tryParseJSON(rightLeaf.data, {}) } as Record<string | number | symbol, any>;\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 const conflictedRevNo = Number(conflictedRev.split(\"-\")[0]);\n //Search\n const revFrom = await this.database.get<EntryDoc>(await this.options.pathService.path2id(path), {\n revs_info: true,\n });\n const commonBase =\n (revFrom._revs_info || []).filter(\n (e) => e.status == \"available\" && Number(e.rev.split(\"-\")[0]) < conflictedRevNo\n )?.[0]?.rev ?? \"\";\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 conflicts = test._conflicts.sort((a, b) => Number(a.split(\"-\")[0]) - Number(b.split(\"-\")[0]));\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 const leftLeaf = await this.getConflictedDoc(path, test._rev!);\n const rightLeaf = await this.getConflictedDoc(path, conflicts[0]);\n return { leftRev: test._rev!, rightRev: conflicts[0], leftLeaf, rightLeaf };\n }\n}\n","import { 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 LEAF_WAIT_ONLY_REMOTE,\n LEAF_WAIT_TIMEOUT,\n LEAF_WAIT_TIMEOUT_SEQUENTIAL_REPLICATOR,\n RemoteTypes,\n type NoteEntry,\n} from \"@lib/common/types\";\nimport type { ContentSplitter } from \"@lib/ContentSplitter/ContentSplitters\";\nimport type { HashManager } from \"../HashManager/HashManager\";\nimport type { LayeredChunkManager as ChunkManager } from \"../LayeredChunkManager\";\nimport type { ChunkWriteOptions } from \"../LayeredChunkManager/types\";\nimport { serialized } from \"octagonal-wheels/concurrency/lock\";\nimport { createTextBlob, getFileRegExp, isTextBlob } from \"@lib/common/utils\";\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\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\", any>,\n managers: NecessaryManagers<\"localDatabase\" | \"chunkManager\" | \"hashManager\" | \"splitter\">,\n note: SavingEntry,\n onlyChunks?: boolean\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 try {\n const old = await localDatabase.get(newDoc._id);\n newDoc._rev = old._rev;\n } catch (ex: any) {\n if (isErrorOfMissingDoc(ex)) {\n // NO OP/\n } else {\n throw ex;\n }\n }\n const r = 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\", any>, 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.includes(\":\")) {\n return false;\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 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\", any>,\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 = (obj as any)?.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 type: type,\n eden: \"eden\" in obj ? obj.eden : {},\n };\n return doc;\n }\n } catch (ex: any) {\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 waitForReady flag.\n * When waitForReady is true, it will wait for a certain time to retrieve chunks from the remote source if they are not available locally, depending on the settings.\n */\nfunction computeChunkRetrievalMethod(waitForReady: boolean, settings: ObsidianLiveSyncSettings) {\n const isOnDemandFetchEnabled = canFetchRemotely(settings);\n const isSequentialReplicator = settings.remoteType === RemoteTypes.REMOTE_MINIO;\n if (!waitForReady) {\n // if waitForReady=false, basically, we should respond immediately.\n // However, while on-demand chunking is enabled, we do not have chunks on local database until they are fetched from the remote source.\n if (isOnDemandFetchEnabled) {\n return {\n timeout: LEAF_WAIT_ONLY_REMOTE,\n preventRemoteRequest: false,\n };\n }\n return {\n timeout: 0,\n preventRemoteRequest: true,\n };\n }\n // if waitForReady=true, we can wait for a certain time to retrieve chunks from the remote source if they are not available locally, depending on the settings.\n if (isSequentialReplicator) {\n // if sequential replicator is used, we can wait longer because chunks will be corrected incrementally, so the chance to get chunks from local database will increase over time while waiting.\n return {\n timeout: LEAF_WAIT_TIMEOUT_SEQUENTIAL_REPLICATOR,\n preventRemoteRequest: true, // Sequential replicator may not use on-demand fetching\n };\n }\n // on-demand fetch behaviour.\n return {\n timeout: LEAF_WAIT_TIMEOUT,\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) {\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 isChunksCorrectedIncrementally = settings.remoteType !== RemoteTypes.REMOTE_MINIO;\n // const isNetworkEnabled = isOnDemandChunkEnabled(settings)\n // && settings.remoteType !== RemoteTypes.REMOTE_MINIO;\n // const timeout = waitForReady\n // ? isChunksCorrectedIncrementally\n // ? LEAF_WAIT_TIMEOUT\n // : LEAF_WAIT_TIMEOUT_SEQUENTIAL_REPLICATOR\n // : isNetworkEnabled\n // ? LEAF_WAIT_ONLY_REMOTE\n // : 0;\n const { timeout, preventRemoteRequest } = computeChunkRetrievalMethod(waitForReady, settings);\n\n const childrenKeys = [...meta.children] as DocumentID[];\n const chunks = await chunkManager.read(\n childrenKeys,\n {\n skipCache: false,\n timeout: timeout,\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: any) {\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\", any>,\n { localDatabase, chunkManager }: NecessaryManagers<\"localDatabase\" | \"chunkManager\">,\n meta: LoadedEntry | MetaEntry,\n dump = false,\n waitForReady = true\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 );\n }\n return false;\n}\nexport async function getDBEntryByPath(\n host: NecessaryServicesInterfaces<\"path\" | \"setting\", any>,\n managers: NecessaryManagers<\"localDatabase\" | \"chunkManager\">,\n path: FilePathWithPrefix | FilePath,\n opt?: PouchDB.Core.GetOptions,\n dump = false,\n waitForReady = true,\n includeDeleted = false\n) {\n const meta = await getDBEntryMetaByPath(host, managers, path, opt, includeDeleted);\n if (meta) {\n return await getDBEntryFromMeta(host, managers, meta, dump, waitForReady);\n } else {\n return false;\n }\n}\nexport async function deleteDBEntryByPath(\n host: NecessaryServicesInterfaces<\"path\" | \"setting\", any>,\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: any) {\n if (isErrorOfMissingDoc(ex)) {\n return false;\n }\n throw ex;\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 {\n type FilePathWithPrefix,\n type FilePath,\n type LoadedEntry,\n type EntryDoc,\n REMOTE_COUCHDB,\n type SavingEntry,\n type MetaEntry,\n} from \"../../common/types\";\nimport type { ChunkManager } from \"../ChunkManager\";\nimport type { ContentSplitter } from \"../../ContentSplitter/ContentSplitters\";\nimport type { HashManager } from \"../HashManager/HashManager\";\nimport type { GeneratedChunk } from \"../../pouchdb/LiveSyncLocalDB\";\nimport type { IPathService, ISettingService } from \"../../services/base/IService\";\nimport {\n deleteDBEntryByPath,\n getDBEntryByPath,\n getDBEntryFromMeta,\n getDBEntryMetaByPath,\n isTargetFile,\n prepareChunk,\n putDBEntry,\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 ): Promise<false | LoadedEntry> {\n return await getDBEntryByPath(this.serviceHost, this, path, opt, dump, waitForReady, includeDeleted);\n }\n async getDBEntryFromMeta(\n meta: LoadedEntry | MetaEntry,\n dump = false,\n waitForReady = true\n ): Promise<false | LoadedEntry> {\n return await getDBEntryFromMeta(this.serviceHost, this, meta, dump, waitForReady);\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 putDBEntry(note: SavingEntry, onlyChunks?: boolean) {\n return await putDBEntry(this.serviceHost, this, note, onlyChunks);\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 await this.initialiseTask;\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","export * from \"octagonal-wheels/hash/xxhash.js\";\nexport type * from \"octagonal-wheels/hash/xxhash.js\";\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 { HashManagerCore, type HashManagerCoreOptions } from \"./HashManagerCore.ts\";\nimport { LOG_LEVEL_VERBOSE, Logger } from \"../../common/logger.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\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 computeHash(piece: string): Promise<string> {\n return this.manager.computeHash(piece);\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 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 \"../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: any, 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 \"../common/types\";\nimport { ContentSplitter } from \"../ContentSplitter/ContentSplitters.ts\";\nimport { ChangeManager } from \"../managers/ChangeManager.ts\";\nimport { ChunkFetcher } from \"../managers/ChunkFetcher.ts\";\nimport { ChunkManager } from \"../managers/ChunkManager.ts\";\nimport { ConflictManager } from \"../managers/ConflictManager.ts\";\nimport { EntryManager } from \"../managers/EntryManager/EntryManager.ts\";\nimport { HashManager } from \"../managers/HashManager/HashManager.ts\";\nimport type { APIService } from \"../services/base/APIService.ts\";\nimport type { IDatabaseService, IPathService, IReplicatorService, ISettingService } from \"../services/base/IService.ts\";\nimport { createInstanceLogFunction, type LogFunction } from \"../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: APIService;\n}\nexport class LiveSyncManagers {\n protected _pathService: IPathService;\n protected _replicatorService: IReplicatorService;\n protected _settingService: ISettingService;\n protected _APIService: APIService;\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 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.databaseService.localDatabase.localDatabase;\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 });\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 }\n\n async prepareHashFunction() {\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 \"../string_and_binary/convert\";\nimport type { EntryDoc } from \"../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) => any\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 \"../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 \"../common/types\";\nimport { isEncryptedChunkEntry, isSyncInfoEntry, isObfuscatedEntry } from \"../common/utils\";\nimport { isPathProbablyObfuscated, obfuscatePath } from \"octagonal-wheels/encryption/encryption\";\n// import { encryptHKDF, decryptHKDF } from \"../encryption/encryptHKDF.ts\";\nimport { getPath } from \"../string_and_binary/path.ts\";\nimport { encryptWorker, decryptWorker, encryptHKDFWorker, decryptHKDFWorker } from \"@lib/worker/bgWorker.ts\";\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}\ntype EncryptProps = {\n path: string;\n mtime: number;\n ctime: number;\n size: number;\n children?: any[];\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): 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)) {\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)) {\n const path = getPath(loadDoc);\n if (isEncryptedMeta(loadDoc)) {\n const pbkdf2salt = await getPBKDF2Salt();\n try {\n const metadata = await decryptMetaWithHKDF(path, passphrase, pbkdf2salt);\n for (const key of Object.keys(metadata)) {\n (loadDoc as any)[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 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 unknown as FilePathWithPrefix;\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 any).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 } as 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 any).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 any).e_;\n } else if (\"e_\" in loadDoc) {\n (loadDoc as any).data = await decrypt((loadDoc as any).data, passphrase, useDynamicIterationCount);\n delete (loadDoc as any).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: any) {\n if (migrationDecrypt && ex.name == \"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 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) => {\n const decrypted = new Map();\n\n const incoming = (doc: AnyEntry | EntryLeaf) =>\n algorithm === E2EEAlgorithms.V2\n ? incomingEncryptHKDF(doc, passphrase, useDynamicIterationCount, getPBKDF2Salt)\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(doc, migrationDecrypt, decrypted, passphrase, useDynamicIterationCount, getPBKDF2Salt)\n : outgoingDecryptV1(doc, migrationDecrypt, decrypted, passphrase, useDynamicIterationCount);\n preprocessOutgoing = incoming;\n preprocessIncoming = outgoing;\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 RemoteDBSettings,\n type ChunkSplitterVersion,\n type SyncParameters,\n DEFAULT_SYNC_PARAMETERS,\n ProtocolVersions,\n DOCID_SYNC_PARAMETERS,\n type E2EEAlgorithm,\n E2EEAlgorithms,\n} from \"../common/types.ts\";\n\nimport { PouchDB } from \"../pouchdb/pouchdb-http.ts\";\nimport { LiveSyncLocalDB, type LiveSyncLocalDBEnv } from \"../pouchdb/LiveSyncLocalDB.ts\";\nimport { isErrorOfMissingDoc } from \"../pouchdb/utils_couchdb.ts\";\nimport { replicationFilter } from \"../pouchdb/compress.ts\";\nimport { disableEncryption } from \"../pouchdb/encryption.ts\";\nimport { enableEncryption } from \"../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 \"../common/utils.ts\";\nimport { promiseWithResolvers } from \"octagonal-wheels/promises\";\nimport {\n createSyncParamsHanderForServer,\n SyncParamsFetchError,\n SyncParamsNotFoundError,\n SyncParamsUpdateError,\n} from \"../replication/SyncParamsHandler.ts\";\n\nimport { HeadlessServiceHub } from \"../services/HeadlessServices.ts\";\nimport { HeadlessDatabaseService } from \"../services/implements/headless/HeadlessDatabaseService.ts\";\nimport { ServiceContext } from \"../services/base/ServiceBase.ts\";\nimport type { InjectableSettingService } from \"../services/implements/injectable/InjectableSettingService.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 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 doNotUseFixedRevisionForChunks?: boolean;\n chunkSplitterVersion?: ChunkSplitterVersion;\n E2EEAlgorithm?: E2EEAlgorithm;\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 ready = promiseWithResolvers<void>();\n services: HeadlessServiceHub<ServiceContext>;\n public async init() {\n await this.services.appLifecycle.onReady();\n await this.liveSyncLocalDB.initializeDatabase();\n this.ready.resolve();\n this.liveSyncLocalDB.refreshSettings();\n }\n getBoundDatabaseService(options: () => DirectFileManipulatorOptions) {\n const _option = options;\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 return new PouchDB(option.url + \"/\" + option.database, {\n auth: { username: option.username, password: option.password },\n });\n }\n };\n }\n\n constructor(options: DirectFileManipulatorOptions) {\n this.options = options;\n const getSettings = () => this.settings as any;\n const context = new ServiceContext();\n this.services = new HeadlessServiceHub(context, {\n database: this.getBoundDatabaseService(() => this.options),\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.database.createPouchDBInstance.setHandler(this.$$createPouchDBInstance.bind(this));\n (this.services.API as InjectableAPIService<ServiceContext>).addLog.setHandler(() => {});\n // Initialize settings on the service so managers can access them during construction.\n this.services.setting.settings = this.settings as any;\n this.services.databaseEvents.onDatabaseInitialisation.addHandler(this.$everyOnInitializeDatabase.bind(this));\n this.liveSyncLocalDB = new LiveSyncLocalDB(this.options.url, this);\n // Register the LiveSyncLocalDB with the database service so LiveSyncManagers\n // can access it via databaseService.localDatabase during initialization.\n (this.services.database as any)._localDatabase = this.liveSyncLocalDB;\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}/${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 );\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: RemoteDBSettings = {\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 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 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: DECRYPT 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 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 \"../common/logger.ts\";\nimport type { SyncParameters } from \"../common/types.ts\";\nimport { arrayBufferToBase64Single, base64ToArrayBufferInternalBrowser } from \"../string_and_binary/convert.ts\";\nimport { LiveSyncError } from \"../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\nfunction 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: any) {\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: any) {\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 { promiseWithResolvers } from \"octagonal-wheels/promises\";\nimport { LOG_LEVEL_VERBOSE, Logger } from \"@lib/common/logger\";\n\n/**\n * A function type that can be used as a handler.\n */\ntype HandlerFunc<TArg extends any[], 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 any[], 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 any[], 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 any[]> = 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 any[], 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 any[], 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 any[], 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 any[], U> extends DispatcherHandler<T, U>, MultiRegisterHandler<T, U> {}\n/**\n * A binder that allows assigning and invoking a single handler function.\n */\nexport class Binder<T extends HandlerFunc<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 */\nexport class LazyBinder<T extends HandlerFunc<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 */\nexport class MultiBinder<T extends HandlerFunc<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 any[], U> extends MultiBinder<HandlerFunc<T, U>> implements DispatcherHandler<T, U> {\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 any[], 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 any[], 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 any[]> 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: ${error}`, LOG_LEVEL_VERBOSE);\n Logger(error, LOG_LEVEL_VERBOSE);\n return false;\n }\n }\n return true;\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 any[]> 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: ${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 any[]> 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: ${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 any[], 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: ${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 */\nexport interface HandlerFunction<TFunc extends (...args: any[]) => any | Promise<any>> {\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 */\nexport interface LazyHandlerFunction<TFunc extends (...args: any[]) => any | Promise<any>> {\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 */\nexport interface MultipleHandlerFunction<TFunc extends (...args: any[]) => any | Promise<any>> {\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) => () => 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 */\nexport type CollectorFunction<TFunc extends (...args: any[]) => any | Promise<any>> = (\n ...args: Parameters<TFunc>\n) => Promise<Awaited<ReturnType<TFunc>>[number]>;\n\n/**\n * A Handler function type that can have multiple handlers added or removed, and collects their results into an array.\n */\nexport interface CollectiveHandlerFunction<TFunc extends (...args: any[]) => any[] | Promise<any[]>> {\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\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// interface BinderInstance<T extends any[], U> extends InvokableHandler<T, U>, BinderHandler<T, U> { }\nexport interface MultiBinderInstance<T extends any[], U> extends InvokableHandler<T, U>, MultiRegisterHandler<T, U> {}\nexport interface BooleanMultiBinderInstance<T extends any[]>\n extends InvokableBooleanHandler<T>, MultiRegisterHandler<T, boolean> {}\n\nfunction getMultipleBound<T extends BooleanMultiBinderInstance<any>>(\n handler: T\n): BooleanMultipleHandlerFunction<T[\"invoke\"]>;\nfunction getMultipleBound<T extends MultiBinderInstance<any, any>>(handler: T): MultipleHandlerFunction<T[\"invoke\"]>;\nfunction getMultipleBound<T extends DispatchHandler<any, any>>(handler: T): CollectiveHandlerFunction<T[\"dispatch\"]>;\nfunction getMultipleBound<T extends MultiBinderInstance<any, any> | DispatchHandler<any, any>>(handler: T) {\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\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\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\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\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\nexport function firstResultFunction<TFunc extends (...args: any[]) => Promise<any>>(\n name?: string\n): MultipleHandlerFunction<TFunc> {\n const handler = new FirstResultHandler<Parameters<TFunc>, ReturnType<TFunc>>(name ?? \"firstResultFunction\");\n return getMultipleBound(handler);\n}\n\nexport function dispatchParallelFunction<TFunc extends (...args: any[]) => Promise<any[]>>(\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);\n}\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}\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> = {\n [K in keyof T]: T[K] extends (...args: any[]) => any ? K : never;\n}[keyof T];\n\nexport function handlers<T extends Record<keyof T, ((...args: any[]) => any) | any>>() {\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>>(name: K): BooleanMultipleHandlerFunction<T[K]> {\n return allFunction<T[K]>(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>>(name: K): BooleanMultipleHandlerFunction<T[K]> {\n return allParallelFunction<T[K]>(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>>(name: K): BooleanMultipleHandlerFunction<T[K]> {\n return bailFirstFailureFunction<T[K]>(String(name));\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>>(name: K): BooleanMultipleHandlerFunction<T[K]> {\n return anySuccessFunction<T[K]>(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>>(name: K): MultipleHandlerFunction<T[K]> {\n return firstResultFunction<T[K]>(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>>(name: K): CollectiveHandlerFunction<T[K]> {\n return dispatchParallelFunction<T[K]>(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>>(name: K): HandlerFunction<T[K]> {\n return bindableFunction<T[K]>(String(name));\n },\n lazyBinder<K extends FunctionKeys<T>>(name: K): LazyHandlerFunction<T[K]> {\n return lazyBindableFunction<T[K]>(String(name));\n },\n };\n}\n","export class ServiceContext {\n // Placeholder for future context properties\n}\nexport abstract class ServiceBase<T extends ServiceContext> {\n protected context: T;\n constructor(context: T) {\n this.context = context;\n }\n}\n","import { 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 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 */\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 */\n markIsReady(): void {\n this._isReady = true;\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 \"../../base/AppLifecycleService\";\nimport type { IAppLifecycleService } from \"../../base/IService\";\nimport type { ServiceContext } from \"../../base/ServiceBase\";\nimport { handlers } from \"../../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 \"../../base/ConflictService\";\nimport type { IConflictService } from \"../../base/IService\";\nimport type { ServiceContext } from \"../../base/ServiceBase\";\nimport { handlers } from \"../../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>().all(\"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>().bailFirstFailure(\"initialiseDatabase\");\n}\n","import { DatabaseEventService } from \"../../base/DatabaseEventService\";\nimport type { ServiceContext } from \"../../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 \"../../base/FileProcessingService\";\nimport type { ServiceContext } from \"../../base/ServiceBase\";\n\nexport class InjectableFileProcessingService<T extends ServiceContext> extends FileProcessingService<T> {}\n","import { stripAllPrefixes } from \"../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 UXFileInfo,\n UXFileInfoStub,\n} from \"@lib/common/types\";\nimport type { IPathService, ISettingService } from \"./IService\";\nimport { ServiceBase, type ServiceContext } from \"./ServiceBase\";\nimport { addPrefix, id2path_base, path2id_base } from \"../../string_and_binary/path\";\nimport { isInternalMetadata, stripInternalMetadataPrefix } from \"../../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/**\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 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 }\n private _id2path(id: DocumentID, entry?: EntryHasPath): FilePathWithPrefix {\n const filename = id2path_base(id, entry);\n const temp = filename.split(\":\");\n const path = temp.pop();\n const normalizedPath = this.normalizePath(path as FilePath);\n temp.push(normalizedPath);\n const fixedPath = temp.join(\":\") as FilePathWithPrefix;\n return fixedPath;\n }\n private async _path2id(\n filename: FilePathWithPrefix | FilePath,\n obfuscatePassphrase: string | false,\n caseInsensitive: boolean\n ): Promise<DocumentID> {\n const temp = filename.split(\":\");\n const path = temp.pop();\n const normalizedPath = this.normalizePath(path as FilePath);\n temp.push(normalizedPath);\n const fixedPath = temp.join(\":\") as FilePathWithPrefix;\n\n const out = await path2id_base(fixedPath, obfuscatePassphrase, caseInsensitive);\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 const destPath = addPrefix(filename, prefix ?? \"\");\n const setting = this.settings;\n return await this._path2id(\n destPath,\n setting.usePathObfuscation ? setting.passphrase : \"\",\n !setting.handleFilenameCaseSensitive\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 \"../../base/PathService\";\nimport type { ServiceContext } from \"../../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 \"../common/types\";\nimport { arrayBufferToBase64Single, writeString } from \"../string_and_binary/convert\";\nimport { Computed } from \"octagonal-wheels/dataobject/Computed\";\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 = window.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 = window.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 } as 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","// Stub: browser events not used in Node\nexport const eventHub = { on: () => {}, off: () => {}, emit: () => {}, once: () => {} };\nexport const EVENT_ON_UNRESOLVED_ERROR = \"on-unresolved-error\";\nexport const EVENT_REQUEST_RELOAD_SETTING_TAB = \"reload-setting-tab\";\nexport const EVENT_PLUGIN_UNLOADED = \"plugin-unloaded\";\n","import { eventHub, EVENT_ON_UNRESOLVED_ERROR } from \"@/common/events\";\nimport { type LOG_LEVEL, LEVEL_NOTICE, LEVEL_INFO } from \"octagonal-wheels/common/logger\";\nimport { createInstanceLogFunction } from \"../lib/logUtils\";\nimport type { AppLifecycleService } from \"./AppLifecycleService\";\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 eventHub.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 eventHub.emitEvent(EVENT_ON_UNRESOLVED_ERROR);\n }\n clearErrors() {\n this._occurredErrors.clear();\n eventHub.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(appLifecycleService: AppLifecycleService) {\n this.appLifecycleService = appLifecycleService;\n this.appLifecycleService.getUnresolvedMessages.addHandler(this._reportUnresolvedMessages.bind(this));\n }\n}\n","import type { CouchDBCredentials, EntryDoc } from \"@lib/common/types\";\nimport type { IRemoteService } from \"./IService\";\nimport { ServiceBase, type ServiceContext } from \"./ServiceBase\";\nimport { LOG_LEVEL_DEBUG, LOG_LEVEL_NOTICE, LOG_LEVEL_VERBOSE, type LOG_LEVEL } 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 { PouchDB } from \"@lib/pouchdb/pouchdb-browser.ts\";\nexport interface RemoteServiceDependencies {\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 /**\n * Connect to the remote database with the provided settings.\n * @param uri The URI of the remote database.\n * @param auth The authentication credentials for the remote database.\n * @param disableRequestURI Whether to disable the request URI.\n * @param passphrase The passphrase for the remote database.\n * @param useDynamicIterationCount Whether to use dynamic iteration count.\n * @param performSetup Whether to perform setup.\n * @param skipInfo Whether to skip information retrieval.\n * @param compression Whether to enable compression.\n * @param customHeaders Custom headers to include in the request.\n * @param useRequestAPI Whether to use the request API.\n * @param getPBKDF2Salt Function to retrieve the PBKDF2 salt.\n * Note that this function is used for CouchDB and compatible only.\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 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._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);\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 this._APIService.requestCount.value = this._APIService.requestCount.value + 1;\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 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 ): Promise<string | { db: PouchDB.Database<EntryDoc>; info: PouchDB.Core.DatabaseInfo }> {\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 // 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 (url: string | Request, opts?: RequestInit) => {\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 opts_length = opts.body.toString().length;\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 this._APIService.requestCount.value = this._APIService.requestCount.value + 1;\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 response = await this.performFetch(\n url,\n { ...opts, headers },\n useRequestAPI ? FetchMethod.native : FetchMethod.webCompat\n );\n return response;\n } catch (ex) {\n if (ex instanceof TypeError) {\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(url, { ...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: any) {\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 this.showError(`${MARK_LOG_NETWORK_ERROR}Network Error: Failed to fetch: ${msg}`); // Do not show notice, due to throwing below\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 } finally {\n this._APIService.responseCount.value = this._APIService.responseCount.value + 1;\n }\n // return await fetch(url, opts);\n },\n };\n const setting = this._settingService.currentSettings();\n const db: PouchDB.Database<EntryDoc> = new PouchDB<EntryDoc>(uri, conf);\n replicationFilter(db, compression);\n disableEncryption();\n if (passphrase !== \"false\" && typeof passphrase === \"string\") {\n enableEncryption(db, passphrase, useDynamicIterationCount, false, getPBKDF2Salt, setting.E2EEAlgorithm);\n }\n if (skipInfo) {\n return { db: db, info: { db_name: \"\", doc_count: 0, update_seq: \"\" } };\n }\n try {\n const info = await db.info();\n return { db: db, info: info };\n } catch (ex: any) {\n const msg = `${ex?.name}:${ex?.message}`;\n this._log(ex, LOG_LEVEL_VERBOSE);\n return msg;\n }\n }\n}\n","import { RemoteService } from \"../../base/RemoteService\";\nimport type { ServiceContext } from \"../../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} 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, MARK_LOG_NETWORK_ERROR, type LogFunction } from \"../lib/logUtils\";\nimport { $msg } from \"../../common/i18n\";\nimport type { LiveSyncAbstractReplicator } from \"../../replication/LiveSyncAbstractReplicator\";\nimport { UnresolvedErrorManager } from \"./UnresolvedErrorManager\";\nimport type { AppLifecycleService } from \"./AppLifecycleService\";\nimport { isLockAcquired, shareRunningResult } from \"octagonal-wheels/concurrency/lock\";\n\n/**\n * Event-triggered replication interval forecasted time.\n */\nconst REPLICATION_ON_EVENT_FORECASTED_TIME = 5000;\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 * The ReplicationService provides methods for managing replication processes.\n */\nexport abstract class ReplicationService<T extends ServiceContext = ServiceContext>\n extends ServiceBase<T>\n implements IReplicationService\n{\n private _unresolvedErrorManager: UnresolvedErrorManager;\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(dependencies.appLifecycleService);\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 /**\n *\n */\n readonly onCheckReplicationReady = handlers<IReplicationService>().bailFirstFailure(\"onCheckReplicationReady\");\n\n /**\n * Check if the replication is ready to start.\n * @param showMessage Whether to show messages to the user.\n */\n async isReplicationReady(showMessage: boolean = false): Promise<boolean> {\n if (!this.appLifecycleService.isReady()) {\n this._log(`Not ready`);\n return false;\n }\n const currentSettings = this.settingService.currentSettings();\n\n if (isLockAcquired(\"cleanup\")) {\n this._log($msg(\"Replicator.Message.Cleaned\"), LOG_LEVEL_NOTICE);\n return false;\n }\n\n if (currentSettings.versionUpFlash != \"\") {\n this._log($msg(\"Replicator.Message.VersionUpFlash\"), LOG_LEVEL_NOTICE);\n return false;\n }\n\n if (!(await this.fileProcessing.commitPendingFileEvents())) {\n this.showError($msg(\"Replicator.Message.Pending\"), LOG_LEVEL_NOTICE);\n return false;\n }\n\n if (!this.APIService.isOnline) {\n this.showError(\"Network is offline\", showMessage ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO);\n return false;\n }\n if (!(await this.onBeforeReplicate(showMessage))) {\n // check for tagged network errors for filtering by NetworkWarningStyles\n const hasNetworkError = (await this.appLifecycleService.getUnresolvedMessages())\n .flat()\n .some((e) => typeof e == \"string\" && e.indexOf(MARK_LOG_NETWORK_ERROR) !== -1);\n if (!hasNetworkError) {\n this.showError($msg(\"Replicator.Message.SomeModuleFailed\"), LOG_LEVEL_NOTICE);\n } else {\n this._log($msg(\"Replicator.Message.SomeModuleFailed\"), LOG_LEVEL_INFO);\n }\n return false;\n }\n this.clearErrors();\n return true;\n }\n\n onReplicationFailed = handlers<IReplicationService>().bailFirstFailure(\"onReplicationFailed\");\n\n /**\n * perform replication. The actual replication logic should be implemented in the handler of this event.\n * @param showMessage\n */\n async performReplication(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 const ret = await activeReplicator.openReplication(settings, false, !!showMessage, false);\n if (!ret) {\n return await this.onReplicationFailed(showMessage);\n }\n return ret;\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 try {\n const checkBeforeReplicate = await this.isReplicationReady(showMessage);\n if (!checkBeforeReplicate) return false;\n return await this.performReplication(showMessage);\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 replicateByEvent(showMessage?: boolean): Promise<boolean | void> {\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 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 async replicateAllToRemote(\n showingNotice: boolean = false,\n sendChunksInBulkDisabled: boolean = false\n ): Promise<boolean> {\n if (!this.appLifecycleService.isReady()) return false;\n if (!(await this.onBeforeReplicate(showingNotice))) {\n this._log($msg(\"Replicator.Message.SomeModuleFailed\"), LOG_LEVEL_NOTICE);\n return false;\n }\n const currentSettings = this.settingService.currentSettings();\n const activeReplicator = this.getActiveReplicatorFor(\"sending data to remote\");\n if (!activeReplicator) {\n return false;\n }\n if (!sendChunksInBulkDisabled) {\n if (activeReplicator?.isChunkSendingSupported) {\n if (\n (await this.APIService.confirm.askYesNoDialog(\n \"Do you want to send all chunks before replication?\",\n {\n defaultOption: \"No\",\n timeout: 20,\n }\n )) == \"yes\"\n ) {\n await activeReplicator.sendChunks(currentSettings, undefined, true, 0);\n }\n }\n }\n const ret = await activeReplicator.replicateAllToServer(currentSettings, showingNotice);\n if (ret) return true;\n const checkResult = await this.checkConnectionFailure();\n if (checkResult == \"CHECKAGAIN\")\n return await activeReplicator.replicateAllToServer(currentSettings, showingNotice);\n return !checkResult;\n }\n\n async replicateAllFromRemote(showingNotice: boolean = false): Promise<boolean> {\n if (!this.appLifecycleService.isReady()) return false;\n const activeReplicator = this.getActiveReplicatorFor(\"fetching data from remote\");\n if (!activeReplicator) {\n return false;\n }\n const currentSettings = this.settingService.currentSettings();\n const ret = await activeReplicator.replicateAllFromServer(currentSettings, showingNotice);\n if (ret) return true;\n const checkResult = await this.checkConnectionFailure();\n if (checkResult == \"CHECKAGAIN\")\n return await activeReplicator.replicateAllFromServer(currentSettings, showingNotice);\n return !checkResult;\n }\n\n private _getReplicatorAndPerform(\n action: string,\n perform: (setting: ObsidianLiveSyncSettings, replicator: LiveSyncAbstractReplicator) => Promise<void>\n ) {\n const activeReplicator = this.getActiveReplicatorFor(action);\n if (!activeReplicator) {\n return Promise.resolve();\n }\n const currentSettings = this.settingService.currentSettings();\n return perform(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 return await activeReplicator.markRemoteLocked(currentSettings, true, lockByClean);\n }\n );\n }\n\n async markUnlocked(): Promise<void> {\n return await this._getReplicatorAndPerform(\n \"marking remote unlocked\",\n async (currentSettings, activeReplicator) => {\n return await activeReplicator.markRemoteLocked(currentSettings, false, false);\n }\n );\n }\n\n async markResolved(): Promise<void> {\n return await this._getReplicatorAndPerform(\n \"marking remote resolved\",\n async (currentSettings, activeReplicator) => {\n return await activeReplicator.markRemoteResolved(currentSettings);\n }\n );\n }\n}\n","{\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 \"(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.\": \"(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 \"(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.\": \"(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.\": \"(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 \"Access Key\": \"Access Key\",\n \"Active Remote Configuration\": \"Active Remote Configuration\",\n \"Always prompt merge conflicts\": \"Always prompt merge conflicts\",\n \"Analyse\": \"Analyse\",\n \"Analyse database usage\": \"Analyse database usage\",\n \"Analyse database usage and generate a TSV report for diagnosis yourself. You can paste the generated report with any spreadsheet you like.\": \"Analyse database usage and generate a TSV report for diagnosis yourself. You can paste the generated report with any spreadsheet you like.\",\n \"Apply Latest Change if Conflicting\": \"Apply Latest Change if Conflicting\",\n \"Apply preset configuration\": \"Apply preset configuration\",\n \"Automatically Sync all files when opening Obsidian.\": \"Automatically Sync all files when opening Obsidian.\",\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.\": \"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 \"Check\": \"Check\",\n \"cmdConfigSync.showCustomizationSync\": \"Show Customization sync\",\n \"Comma separated `.gitignore, .dockerignore`\": \"Comma separated `.gitignore, .dockerignore`\",\n \"Compute revisions for chunks\": \"Compute revisions for chunks\",\n \"Copy Report to clipboard\": \"Copy Report to clipboard\",\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 \"Device name\": \"Device name\",\n \"dialog.yourLanguageAvailable\": \"Self-hosted LiveSync had translations for your language, so the %{Display language} setting was enabled.\\n\\nNote: Not all messages are translated. We are waiting for your contributions!\\nNote 2: If you create an Issue, **please revert to %{lang-def}** and then take screenshots, messages and logs. This can be done in the setting dialogue.\\nMay you find it easy to use!\",\n \"dialog.yourLanguageAvailable.btnRevertToDefault\": \"Keep %{lang-def}\",\n \"dialog.yourLanguageAvailable.Title\": \" Translation is available!\",\n \"Disables logging, only shows notifications. Please disable if you report an issue.\": \"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\": \"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## ${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\": \"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 \"Enable advanced features\": \"Enable advanced features\",\n \"Enable customization sync\": \"Enable customization sync\",\n \"Enable Developers' Debug Tools.\": \"Enable Developers' Debug Tools.\",\n \"Enable edge case treatment features\": \"Enable edge case treatment features\",\n \"Enable poweruser features\": \"Enable poweruser features\",\n \"Enable this if your Object Storage doesn't support CORS\": \"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\": \"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.\": \"Encrypt contents on the remote database. If you use the plugin's synchronization feature, enabling this is recommended.\",\n \"Encrypting sensitive configuration items\": \"Encrypting sensitive configuration items\",\n \"Encryption phassphrase. If changed, you should overwrite the server's database with the new (encrypted) files.\": \"Encryption phassphrase. If changed, you should overwrite the server's database with the new (encrypted) files.\",\n \"End-to-End Encryption\": \"End-to-End Encryption\",\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 \"Filename\": \"Filename\",\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 \"If disabled(toggled), chunks will be split on the UI thread (Previous behaviour).\": \"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.\": \"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, chunks will be split into no more than 100 items. However, dedupe is slightly weaker.\": \"If enabled, chunks will be split into no more than 100 items. However, dedupe is slightly weaker.\",\n \"If enabled, newly created chunks are temporarily kept within the document, and graduated to become independent chunks once stabilised.\": \"If enabled, newly created chunks are temporarily kept within the document, and graduated to become independent chunks once stabilised.\",\n \"If enabled, the ⛔ icon will be shown inside the status instead of the file warnings banner. No details will be shown.\": \"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 file under 1kb will be processed in the UI thread.\": \"If enabled, the file under 1kb will be processed in the UI thread.\",\n \"If enabled, the notification of hidden files change will be suppressed.\": \"If enabled, the notification of hidden files change will be suppressed.\",\n \"If this enabled, all chunks will be stored with the revision made from its content. (Previous behaviour)\": \"If this enabled, all chunks will be stored with the revision made from its content. (Previous behaviour)\",\n \"If this enabled, All files are handled as case-Sensitive (Previous behaviour).\": \"If this enabled, All files are handled as case-Sensitive (Previous behaviour).\",\n \"If this enabled, chunks will be split into semantically meaningful segments. Not all platforms support this feature.\": \"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.\": \"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.\": \"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 \"Interval (sec)\": \"Interval (sec)\",\n \"K.exp\": \"Experimental\",\n \"K.long_p2p_sync\": \"%{title_p2p_sync}\",\n \"K.P2P\": \"%{Peer}-to-%{Peer}\",\n \"K.Peer\": \"Peer\",\n \"K.ScanCustomization\": \"Scan customization\",\n \"K.short_p2p_sync\": \"P2P Sync\",\n \"K.title_p2p_sync\": \"Peer-to-Peer Sync\",\n \"Keep empty folder\": \"Keep empty folder\",\n \"lang_def\": \"Default\",\n \"lang-de\": \"Deutsche\",\n \"lang-def\": \"%{lang_def}\",\n \"lang-es\": \"Español\",\n \"lang-ja\": \"日本語\",\n \"lang-ko\": \"한국어\",\n \"lang-ru\": \"Русский\",\n \"lang-zh\": \"简体中文\",\n \"lang-zh-tw\": \"繁體中文\",\n \"LiveSync could not handle multiple vaults which have same name without different prefix, This should be automatically configured.\": \"LiveSync could not handle multiple vaults which have same name without different prefix, This should be automatically configured.\",\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\": \"Could not connect to server.\",\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.oneShotSyncBegin\": \"OneShot Sync begin... (${syncMode})\",\n \"liveSyncReplicator.remoteDbCorrupted\": \"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.remoteDbDestroyed\": \"Remote Database Destroyed\",\n \"liveSyncReplicator.remoteDbDestroyError\": \"Something happened on Remote Database Destroy:\",\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 \"liveSyncSetting.errorNoSuchSettingItem\": \"No such setting item: ${key}\",\n \"liveSyncSetting.originalValue\": \"Original: ${value}\",\n \"liveSyncSetting.valueShouldBeInRange\": \"The value should ${min} < value < ${max}\",\n \"liveSyncSettings.btnApply\": \"Apply\",\n \"logPane.autoScroll\": \"Auto scroll\",\n \"logPane.logWindowOpened\": \"Log window opened\",\n \"logPane.pause\": \"Pause\",\n \"logPane.title\": \"Self-hosted LiveSync Log\",\n \"logPane.wrap\": \"Wrap\",\n \"Maximum delay for batch database updating\": \"Maximum delay for batch database updating\",\n \"Maximum file size\": \"Maximum file size\",\n \"Maximum Incubating Chunk Size\": \"Maximum Incubating Chunk Size\",\n \"Maximum Incubating Chunks\": \"Maximum Incubating Chunks\",\n \"Maximum Incubation Period\": \"Maximum Incubation Period\",\n \"MB (0 to disable).\": \"MB (0 to disable).\",\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 delay for batch database updating\": \"Minimum delay for batch database updating\",\n \"Minimum interval for syncing\": \"Minimum interval for syncing\",\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\": \"This may take a bit of a long time. Do you really want to rebuild everything now?\",\n \"moduleCheckRemoteSize.msgDatabaseGrowing\": \"**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\": \"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.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.titleDatabaseSizeLimitExceeded\": \"Remote storage size exceeded the limit\",\n \"moduleCheckRemoteSize.titleDatabaseSizeNotify\": \"Setting up database size notification\",\n \"moduleInputUIObsidian.defaultTitleConfirmation\": \"Confirmation\",\n \"moduleInputUIObsidian.defaultTitleSelect\": \"Select\",\n \"moduleInputUIObsidian.optionNo\": \"No\",\n \"moduleInputUIObsidian.optionYes\": \"Yes\",\n \"moduleLiveSyncMain.logAdditionalSafetyScan\": \"Additional safety scan...\",\n \"moduleLiveSyncMain.logLoadingPlugin\": \"Loading plugin...\",\n \"moduleLiveSyncMain.logPluginInitCancelled\": \"Plugin initialisation was cancelled by a module\",\n \"moduleLiveSyncMain.logPluginVersion\": \"Self-hosted LiveSync v${manifestVersion} ${packageVersion}\",\n \"moduleLiveSyncMain.logReadChangelog\": \"LiveSync has updated, please read the changelog!\",\n \"moduleLiveSyncMain.logSafetyScanCompleted\": \"Additional safety scan completed\",\n \"moduleLiveSyncMain.logSafetyScanFailed\": \"Additional safety scan has failed on a module\",\n \"moduleLiveSyncMain.logUnloadingPlugin\": \"Unloading plugin...\",\n \"moduleLiveSyncMain.logVersionUpdate\": \"LiveSync has been updated, In case of breaking updates, all automatic synchronization has been temporarily disabled. Ensure that all devices are up to date before enabling.\",\n \"moduleLiveSyncMain.msgScramEnabled\": \"Self-hosted LiveSync has been configured to ignore some events. Is this correct?\\n\\n| Type | Status | Note |\\n|:---:|:---:|---|\\n| Storage Events | ${fileWatchingStatus} | Every modification will be ignored |\\n| Database Events | ${parseReplicationStatus} | Every synchronised change will be postponed |\\n\\nDo you want to resume them and restart Obsidian?\\n\\n> [!DETAILS]-\\n> These flags are set by the plug-in while rebuilding, or fetching. If the process ends abnormally, it may be kept unintended.\\n> If you are not sure, you can try to rerun these processes. Make sure to back your vault up.\\n\",\n \"moduleLiveSyncMain.optionKeepLiveSyncDisabled\": \"Keep LiveSync disabled\",\n \"moduleLiveSyncMain.optionResumeAndRestart\": \"Resume and restart Obsidian\",\n \"moduleLiveSyncMain.titleScramEnabled\": \"Scram Enabled\",\n \"moduleLocalDatabase.logWaitingForReady\": \"Waiting for ready...\",\n \"moduleLog.showLog\": \"Show Log\",\n \"moduleMigration.docUri\": \"https://github.com/vrtmrz/obsidian-livesync/blob/main/README.md#how-to-use\",\n \"moduleMigration.fix0256.buttons.checkItLater\": \"Check it later\",\n \"moduleMigration.fix0256.buttons.DismissForever\": \"I have fixed it, and do not ask again\",\n \"moduleMigration.fix0256.buttons.fix\": \"Fix\",\n \"moduleMigration.fix0256.message\": \"Due to a recent bug (in v0.25.6), some files may not have been saved correctly in the sync database.\\nWe have scanned our files and found some that need to be fixed.\\n\\n**Files ready to be fixed:**\\n\\n${files}\\n\\nThese files have size-matched original file on the storage, and are likely to be recoverable.\\nWe can use them to fix the database, please click the \\\"Fix\\\" button below to fix them.\\n\\n${messageUnrecoverable}\\n\\nIf you want to run it again, you can do so from Hatch.\\n\",\n \"moduleMigration.fix0256.messageUnrecoverable\": \"**Files cannot be fixed on this device:**\\n\\n${filesNotRecoverable}\\n\\nThese files have inconsistent metadata, and cannot be fixed on this device (mostly we cannot determine which is correct).\\nTo restore them, please check your other devices (also by this feature) or restore them manually from a backup.\\n\",\n \"moduleMigration.fix0256.title\": \"Broken files has been detected\",\n \"moduleMigration.insecureChunkExist.buttons.fetch\": \"I already rebuilt the remote. Fetch from the remote\",\n \"moduleMigration.insecureChunkExist.buttons.later\": \"I will do it later\",\n \"moduleMigration.insecureChunkExist.buttons.rebuild\": \"Rebuild Everything\",\n \"moduleMigration.insecureChunkExist.laterMessage\": \"We strongly recommend to treat this as soon as possible!\",\n \"moduleMigration.insecureChunkExist.message\": \"Some chunks are not securely stored and are not encrypted in databases.\\n**Please rebuild the database to fix this issue**.\\n\\nIf your Remote Database is not configured with SSL, or using less-secure credentials, **you are at risk of exposing sensitive data**.\\n\\nNote: Please upgrade your Self-hosted LiveSync v0.25.6 or higher on all your devices, and back your vault up surely.\\nNote2: Rebuild Everything and Fetch consumes a bit of time and traffic, please do it in off-peak hours and ensure a stable network connection.\\n\",\n \"moduleMigration.insecureChunkExist.title\": \"Insecure chunks found!\",\n \"moduleMigration.logBulkSendCorrupted\": \"Send chunks in bulk has been enabled, however, this feature had been corrupted. Sorry for your inconvenience. Automatically disabled.\",\n \"moduleMigration.logFetchRemoteTweakFailed\": \"Failed to fetch remote tweak values\",\n \"moduleMigration.logLocalDatabaseNotReady\": \"Something went wrong! The local database is not ready\",\n \"moduleMigration.logMigratedSameBehaviour\": \"Migrated to db:${current} with the same behaviour as before\",\n \"moduleMigration.logMigrationFailed\": \"Migration failed or cancelled from ${old} to ${current}\",\n \"moduleMigration.logRedflag2CreationFail\": \"Failed to create redflag2\",\n \"moduleMigration.logRemoteTweakUnavailable\": \"Could not get remote tweak values\",\n \"moduleMigration.logSetupCancelled\": \"The setup has been cancelled, Self-hosted LiveSync waiting for your setup!\",\n \"moduleMigration.msgFetchRemoteAgain\": \"As you may already know, the self-hosted LiveSync has changed its default behaviour and database structure.\\n\\nAnd thankfully, with your time and efforts, the remote database appears to have already been migrated. Congratulations!\\n\\nHowever, we need a bit more. The configuration of this device is not compatible with the remote database. We will need to fetch the remote database again. Should we fetch from the remote again now?\\n\\n___Note: We cannot synchronise until the configuration has been changed and the database has been fetched again.___\\n___Note2: The chunks are completely immutable, we can fetch only the metadata and difference.___\",\n \"moduleMigration.msgInitialSetup\": \"Your device has **not been set up yet**. Let me guide you through the setup process.\\n\\nPlease keep in mind that every dialogue content can be copied to the clipboard. If you need to refer to it later, you can paste it into a note in Obsidian. You can also translate it into your language using a translation tool.\\n\\nFirst, do you have **Setup URI**?\\n\\nNote: If you do not know what it is, please refer to the [documentation](${URI_DOC}).\",\n \"moduleMigration.msgRecommendSetupUri\": \"We strongly recommend that you generate a set-up URI and use it.\\nIf you do not have knowledge about it, please refer to the [documentation](${URI_DOC}) (Sorry again, but it is important).\\n\\nHow do you want to set it up manually?\",\n \"moduleMigration.msgSinceV02321\": \"Since v0.23.21, the self-hosted LiveSync has changed the default behaviour and database structure. The following changes have been made:\\n\\n1. **Case sensitivity of filenames**\\n The handling of filenames is now case-insensitive. This is a beneficial change for most platforms, other than Linux and iOS, which do not manage filename case sensitivity effectively.\\n (On These, a warning will be displayed for files with the same name but different cases).\\n\\n2. **Revision handling of the chunks**\\n Chunks are immutable, which allows their revisions to be fixed. This change will enhance the performance of file saving.\\n\\n___However, to enable either of these changes, both remote and local databases need to be rebuilt. This process takes a few minutes, and we recommend doing it when you have ample time.___\\n\\n- If you wish to maintain the previous behaviour, you can skip this process by using `${KEEP}`.\\n- If you do not have enough time, please choose `${DISMISS}`. You will be prompted again later.\\n- If you have rebuilt the database on another device, please select `${DISMISS}` and try synchronizing again. Since a difference has been detected, you will be prompted again.\",\n \"moduleMigration.optionAdjustRemote\": \"Adjust to remote\",\n \"moduleMigration.optionDecideLater\": \"Decide it later\",\n \"moduleMigration.optionEnableBoth\": \"Enable both\",\n \"moduleMigration.optionEnableFilenameCaseInsensitive\": \"Enable only #1\",\n \"moduleMigration.optionEnableFixedRevisionForChunks\": \"Enable only #2\",\n \"moduleMigration.optionHaveSetupUri\": \"Yes, I have\",\n \"moduleMigration.optionKeepPreviousBehaviour\": \"Keep previous behaviour\",\n \"moduleMigration.optionManualSetup\": \"Set it up all manually\",\n \"moduleMigration.optionNoAskAgain\": \"No, please ask again\",\n \"moduleMigration.optionNoSetupUri\": \"No, I do not have\",\n \"moduleMigration.optionRemindNextLaunch\": \"Remind me at the next launch\",\n \"moduleMigration.optionSetupViaP2P\": \"Use %{short_p2p_sync} to set up\",\n \"moduleMigration.optionSetupWizard\": \"Take me into the setup wizard\",\n \"moduleMigration.optionYesFetchAgain\": \"Yes, fetch again\",\n \"moduleMigration.titleCaseSensitivity\": \"Case Sensitivity\",\n \"moduleMigration.titleRecommendSetupUri\": \"Recommendation to use Setup URI\",\n \"moduleMigration.titleWelcome\": \"Welcome to Self-hosted LiveSync\",\n \"moduleObsidianMenu.replicate\": \"Replicate\",\n \"Move remotely deleted files to the trash, instead of deleting.\": \"Move remotely deleted files to the trash, instead of deleting.\",\n \"Not all messages have been translated. And, please revert to \\\"Default\\\" when reporting errors.\": \"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\": \"Notify when the estimated remote storage size exceeds on start up\",\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.\": \"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.\": \"Number of changes to sync at a time. Defaults to 50. Minimum is 2.\",\n \"obsidianLiveSyncSettingTab.btnApply\": \"Apply\",\n \"obsidianLiveSyncSettingTab.btnCheck\": \"Check\",\n \"obsidianLiveSyncSettingTab.btnCopy\": \"Copy\",\n \"obsidianLiveSyncSettingTab.btnDisable\": \"Disable\",\n \"obsidianLiveSyncSettingTab.btnDiscard\": \"Discard\",\n \"obsidianLiveSyncSettingTab.btnEnable\": \"Enable\",\n \"obsidianLiveSyncSettingTab.btnFix\": \"Fix\",\n \"obsidianLiveSyncSettingTab.btnGotItAndUpdated\": \"I got it and updated.\",\n \"obsidianLiveSyncSettingTab.btnNext\": \"Next\",\n \"obsidianLiveSyncSettingTab.btnStart\": \"Start\",\n \"obsidianLiveSyncSettingTab.btnTest\": \"Test\",\n \"obsidianLiveSyncSettingTab.btnUse\": \"Use\",\n \"obsidianLiveSyncSettingTab.buttonFetch\": \"Fetch\",\n \"obsidianLiveSyncSettingTab.buttonNext\": \"Next\",\n \"obsidianLiveSyncSettingTab.defaultLanguage\": \"Default\",\n \"obsidianLiveSyncSettingTab.descConnectSetupURI\": \"This is the recommended method to set up Self-hosted LiveSync with a Setup URI.\",\n \"obsidianLiveSyncSettingTab.descCopySetupURI\": \"Perfect for setting up a new device!\",\n \"obsidianLiveSyncSettingTab.descEnableLiveSync\": \"Only enable this after configuring either of the above two options or completing all configuration manually.\",\n \"obsidianLiveSyncSettingTab.descFetchConfigFromRemote\": \"Fetch necessary settings from already configured remote server.\",\n \"obsidianLiveSyncSettingTab.descManualSetup\": \"Not recommended, but useful if you don't have a Setup URI\",\n \"obsidianLiveSyncSettingTab.descTestDatabaseConnection\": \"Open database connection. If the remote database is not found and you have permission to create a database, the database will be created.\",\n \"obsidianLiveSyncSettingTab.descValidateDatabaseConfig\": \"Checks and fixes any potential issues with the database config.\",\n \"obsidianLiveSyncSettingTab.errAccessForbidden\": \"❗ Access forbidden.\",\n \"obsidianLiveSyncSettingTab.errCannotContinueTest\": \"We could not continue the test.\",\n \"obsidianLiveSyncSettingTab.errCorsCredentials\": \"❗ cors.credentials is wrong\",\n \"obsidianLiveSyncSettingTab.errCorsNotAllowingCredentials\": \"❗ CORS is not allowing credentials\",\n \"obsidianLiveSyncSettingTab.errCorsOrigins\": \"❗ cors.origins is wrong\",\n \"obsidianLiveSyncSettingTab.errEnableCors\": \"❗ httpd.enable_cors is wrong\",\n \"obsidianLiveSyncSettingTab.errEnableCorsChttpd\": \"❗ chttpd.enable_cors is wrong\",\n \"obsidianLiveSyncSettingTab.errMaxDocumentSize\": \"❗ couchdb.max_document_size is low)\",\n \"obsidianLiveSyncSettingTab.errMaxRequestSize\": \"❗ chttpd.max_http_request_size is low)\",\n \"obsidianLiveSyncSettingTab.errMissingWwwAuth\": \"❗ httpd.WWW-Authenticate is missing\",\n \"obsidianLiveSyncSettingTab.errRequireValidUser\": \"❗ chttpd.require_valid_user is wrong.\",\n \"obsidianLiveSyncSettingTab.errRequireValidUserAuth\": \"❗ chttpd_auth.require_valid_user is wrong.\",\n \"obsidianLiveSyncSettingTab.labelDisabled\": \"⏹️ : Disabled\",\n \"obsidianLiveSyncSettingTab.labelEnabled\": \"🔁 : Enabled\",\n \"obsidianLiveSyncSettingTab.levelAdvanced\": \" (Advanced)\",\n \"obsidianLiveSyncSettingTab.levelEdgeCase\": \" (Edge Case)\",\n \"obsidianLiveSyncSettingTab.levelPowerUser\": \" (Power User)\",\n \"obsidianLiveSyncSettingTab.linkOpenInBrowser\": \"Open in browser\",\n \"obsidianLiveSyncSettingTab.linkPageTop\": \"Page Top\",\n \"obsidianLiveSyncSettingTab.linkTipsAndTroubleshooting\": \"Tips and Troubleshooting\",\n \"obsidianLiveSyncSettingTab.linkTroubleshooting\": \"/docs/troubleshooting.md\",\n \"obsidianLiveSyncSettingTab.logCannotUseCloudant\": \"This feature cannot be used with IBM Cloudant.\",\n \"obsidianLiveSyncSettingTab.logCheckingConfigDone\": \"Checking configuration done\",\n \"obsidianLiveSyncSettingTab.logCheckingConfigFailed\": \"Checking configuration failed\",\n \"obsidianLiveSyncSettingTab.logCheckingDbConfig\": \"Checking database configuration\",\n \"obsidianLiveSyncSettingTab.logCheckPassphraseFailed\": \"ERROR: Failed to check passphrase with the remote server:\\n${db}.\",\n \"obsidianLiveSyncSettingTab.logConfiguredDisabled\": \"Configured synchronization mode: DISABLED\",\n \"obsidianLiveSyncSettingTab.logConfiguredLiveSync\": \"Configured synchronization mode: LiveSync\",\n \"obsidianLiveSyncSettingTab.logConfiguredPeriodic\": \"Configured synchronization mode: Periodic\",\n \"obsidianLiveSyncSettingTab.logCouchDbConfigFail\": \"CouchDB Configuration: ${title} failed\",\n \"obsidianLiveSyncSettingTab.logCouchDbConfigSet\": \"CouchDB Configuration: ${title} -> Set ${key} to ${value}\",\n \"obsidianLiveSyncSettingTab.logCouchDbConfigUpdated\": \"CouchDB Configuration: ${title} successfully updated\",\n \"obsidianLiveSyncSettingTab.logDatabaseConnected\": \"Database connected\",\n \"obsidianLiveSyncSettingTab.logEncryptionNoPassphrase\": \"You cannot enable encryption without a passphrase\",\n \"obsidianLiveSyncSettingTab.logEncryptionNoSupport\": \"Your device does not support encryption.\",\n \"obsidianLiveSyncSettingTab.logErrorOccurred\": \"An error occurred!!\",\n \"obsidianLiveSyncSettingTab.logEstimatedSize\": \"Estimated size: ${size}\",\n \"obsidianLiveSyncSettingTab.logPassphraseInvalid\": \"Passphrase is not valid, please fix it.\",\n \"obsidianLiveSyncSettingTab.logPassphraseNotCompatible\": \"ERROR: Passphrase is not compatible with the remote server! Please check it again!\",\n \"obsidianLiveSyncSettingTab.logRebuildNote\": \"Syncing has been disabled, fetch and re-enabled if desired.\",\n \"obsidianLiveSyncSettingTab.logSelectAnyPreset\": \"Select any preset.\",\n \"obsidianLiveSyncSettingTab.msgAreYouSureProceed\": \"Are you sure to proceed?\",\n \"obsidianLiveSyncSettingTab.msgChangesNeedToBeApplied\": \"Changes need to be applied!\",\n \"obsidianLiveSyncSettingTab.msgConfigCheck\": \"--Config check--\",\n \"obsidianLiveSyncSettingTab.msgConfigCheckFailed\": \"The configuration check has failed. Do you want to continue anyway?\",\n \"obsidianLiveSyncSettingTab.msgConnectionCheck\": \"--Connection check--\",\n \"obsidianLiveSyncSettingTab.msgConnectionProxyNote\": \"If you're having trouble with the Connection-check (even after checking config), please check your reverse proxy configuration.\",\n \"obsidianLiveSyncSettingTab.msgCurrentOrigin\": \"Current origin: ${origin}\",\n \"obsidianLiveSyncSettingTab.msgDiscardConfirmation\": \"Do you really want to discard existing settings and databases?\",\n \"obsidianLiveSyncSettingTab.msgDone\": \"--Done--\",\n \"obsidianLiveSyncSettingTab.msgEnableCors\": \"Set httpd.enable_cors\",\n \"obsidianLiveSyncSettingTab.msgEnableCorsChttpd\": \"Set chttpd.enable_cors\",\n \"obsidianLiveSyncSettingTab.msgEnableEncryptionRecommendation\": \"We recommend enabling End-To-End Encryption, and Path Obfuscation. Are you sure you want to continue without encryption?\",\n \"obsidianLiveSyncSettingTab.msgFetchConfigFromRemote\": \"Do you want to fetch the config from the remote server?\",\n \"obsidianLiveSyncSettingTab.msgGenerateSetupURI\": \"All done! Do you want to generate a setup URI to set up other devices?\",\n \"obsidianLiveSyncSettingTab.msgIfConfigNotPersistent\": \"If the server configuration is not persistent (e.g., running on docker), the values here may change. Once you are able to connect, please update the settings in the server's local.ini.\",\n \"obsidianLiveSyncSettingTab.msgInvalidPassphrase\": \"Your encryption passphrase might be invalid. Are you sure you want to continue?\",\n \"obsidianLiveSyncSettingTab.msgNewVersionNote\": \"Here due to an upgrade notification? Please review the version history. If you're satisfied, click the button. A new update will prompt this again.\",\n \"obsidianLiveSyncSettingTab.msgNonHTTPSInfo\": \"Configured as non-HTTPS URI. Be warned that this may not work on mobile devices.\",\n \"obsidianLiveSyncSettingTab.msgNonHTTPSWarning\": \"Cannot connect to non-HTTPS URI. Please update your config and try again.\",\n \"obsidianLiveSyncSettingTab.msgNotice\": \"---Notice---\",\n \"obsidianLiveSyncSettingTab.msgObjectStorageWarning\": \"WARNING: This feature is a Work In Progress, so please keep in mind the following:\\n- Append only architecture. A rebuild is required to shrink the storage.\\n- A bit fragile.\\n- When first syncing, all history will be transferred from the remote. Be mindful of data caps and slow speeds.\\n- Only differences are synced live.\\n\\nIf you run into any issues, or have ideas about this feature, please create a issue on GitHub.\\nI appreciate you for your great dedication.\",\n \"obsidianLiveSyncSettingTab.msgOriginCheck\": \"Origin check: ${org}\",\n \"obsidianLiveSyncSettingTab.msgRebuildRequired\": \"Rebuilding Databases are required to apply the changes.. Please select the method to apply the changes.\\n\\n<details>\\n<summary>Legends</summary>\\n\\n| Symbol | Meaning |\\n|: ------ :| ------- |\\n| ⇔ | Up to Date |\\n| ⇄ | Synchronise to balance |\\n| ⇐,⇒ | Transfer to overwrite |\\n| ⇠,⇢ | Transfer to overwrite from other side |\\n\\n</details>\\n\\n## ${OPTION_REBUILD_BOTH}\\nAt a glance: 📄 ⇒¹ 💻 ⇒² 🛰️ ⇢ⁿ 💻 ⇄ⁿ⁺¹ 📄\\nReconstruct both the local and remote databases using existing files from this device.\\nThis causes a lockout other devices, and they need to perform fetching.\\n## ${OPTION_FETCH}\\nAt a glance: 📄 ⇄² 💻 ⇐¹ 🛰️ ⇔ 💻 ⇔ 📄\\nInitialise the local database and reconstruct it using data fetched from the remote database.\\nThis case includes the case which you have rebuilt the remote database.\\n## ${OPTION_ONLY_SETTING}\\nStore only the settings. **Caution: This may lead to data corruption**; database reconstruction is generally necessary.\",\n \"obsidianLiveSyncSettingTab.msgSelectAndApplyPreset\": \"Please select and apply any preset item to complete the wizard.\",\n \"obsidianLiveSyncSettingTab.msgSetCorsCredentials\": \"Set cors.credentials\",\n \"obsidianLiveSyncSettingTab.msgSetCorsOrigins\": \"Set cors.origins\",\n \"obsidianLiveSyncSettingTab.msgSetMaxDocSize\": \"Set couchdb.max_document_size\",\n \"obsidianLiveSyncSettingTab.msgSetMaxRequestSize\": \"Set chttpd.max_http_request_size\",\n \"obsidianLiveSyncSettingTab.msgSetRequireValidUser\": \"Set chttpd.require_valid_user = true\",\n \"obsidianLiveSyncSettingTab.msgSetRequireValidUserAuth\": \"Set chttpd_auth.require_valid_user = true\",\n \"obsidianLiveSyncSettingTab.msgSettingModified\": \"The setting \\\"${setting}\\\" was modified from another device. Click {HERE} to reload settings. Click elsewhere to ignore changes.\",\n \"obsidianLiveSyncSettingTab.msgSettingsUnchangeableDuringSync\": \"These settings are unable to be changed during synchronization. Please disable all syncing in the \\\"Sync Settings\\\" to unlock.\",\n \"obsidianLiveSyncSettingTab.msgSetWwwAuth\": \"Set httpd.WWW-Authenticate\",\n \"obsidianLiveSyncSettingTab.nameApplySettings\": \"Apply Settings\",\n \"obsidianLiveSyncSettingTab.nameConnectSetupURI\": \"Connect with Setup URI\",\n \"obsidianLiveSyncSettingTab.nameCopySetupURI\": \"Copy the current settings to a Setup URI\",\n \"obsidianLiveSyncSettingTab.nameDisableHiddenFileSync\": \"Disable Hidden files sync\",\n \"obsidianLiveSyncSettingTab.nameDiscardSettings\": \"Discard existing settings and databases\",\n \"obsidianLiveSyncSettingTab.nameEnableHiddenFileSync\": \"Enable Hidden files sync\",\n \"obsidianLiveSyncSettingTab.nameEnableLiveSync\": \"Enable LiveSync\",\n \"obsidianLiveSyncSettingTab.nameHiddenFileSynchronization\": \"Hidden file synchronization\",\n \"obsidianLiveSyncSettingTab.nameManualSetup\": \"Manual Setup\",\n \"obsidianLiveSyncSettingTab.nameTestConnection\": \"Test Connection\",\n \"obsidianLiveSyncSettingTab.nameTestDatabaseConnection\": \"Test Database Connection\",\n \"obsidianLiveSyncSettingTab.nameValidateDatabaseConfig\": \"Validate Database Configuration\",\n \"obsidianLiveSyncSettingTab.okAdminPrivileges\": \"✔ You have administrator privileges.\",\n \"obsidianLiveSyncSettingTab.okCorsCredentials\": \"✔ cors.credentials is ok.\",\n \"obsidianLiveSyncSettingTab.okCorsCredentialsForOrigin\": \"CORS credentials OK\",\n \"obsidianLiveSyncSettingTab.okCorsOriginMatched\": \"✔ CORS origin OK\",\n \"obsidianLiveSyncSettingTab.okCorsOrigins\": \"✔ cors.origins is ok.\",\n \"obsidianLiveSyncSettingTab.okEnableCors\": \"✔ httpd.enable_cors is ok.\",\n \"obsidianLiveSyncSettingTab.okEnableCorsChttpd\": \"✔ chttpd.enable_cors is ok.\",\n \"obsidianLiveSyncSettingTab.okMaxDocumentSize\": \"✔ couchdb.max_document_size is ok.\",\n \"obsidianLiveSyncSettingTab.okMaxRequestSize\": \"✔ chttpd.max_http_request_size is ok.\",\n \"obsidianLiveSyncSettingTab.okRequireValidUser\": \"✔ chttpd.require_valid_user is ok.\",\n \"obsidianLiveSyncSettingTab.okRequireValidUserAuth\": \"✔ chttpd_auth.require_valid_user is ok.\",\n \"obsidianLiveSyncSettingTab.okWwwAuth\": \"✔ httpd.WWW-Authenticate is ok.\",\n \"obsidianLiveSyncSettingTab.optionApply\": \"Apply\",\n \"obsidianLiveSyncSettingTab.optionCancel\": \"Cancel\",\n \"obsidianLiveSyncSettingTab.optionCouchDB\": \"CouchDB\",\n \"obsidianLiveSyncSettingTab.optionDisableAllAutomatic\": \"Disable all automatic\",\n \"obsidianLiveSyncSettingTab.optionFetchFromRemote\": \"Fetch from Remote\",\n \"obsidianLiveSyncSettingTab.optionHere\": \"HERE\",\n \"obsidianLiveSyncSettingTab.optionLiveSync\": \"LiveSync\",\n \"obsidianLiveSyncSettingTab.optionMinioS3R2\": \"Minio,S3,R2\",\n \"obsidianLiveSyncSettingTab.optionOkReadEverything\": \"OK, I have read everything.\",\n \"obsidianLiveSyncSettingTab.optionOnEvents\": \"On events\",\n \"obsidianLiveSyncSettingTab.optionPeriodicAndEvents\": \"Periodic and on events\",\n \"obsidianLiveSyncSettingTab.optionPeriodicWithBatch\": \"Periodic w/ batch\",\n \"obsidianLiveSyncSettingTab.optionRebuildBoth\": \"Rebuild Both from This Device\",\n \"obsidianLiveSyncSettingTab.optionSaveOnlySettings\": \"(Danger) Save Only Settings\",\n \"obsidianLiveSyncSettingTab.panelChangeLog\": \"Change Log\",\n \"obsidianLiveSyncSettingTab.panelGeneralSettings\": \"General Settings\",\n \"obsidianLiveSyncSettingTab.panelPrivacyEncryption\": \"Privacy & Encryption\",\n \"obsidianLiveSyncSettingTab.panelRemoteConfiguration\": \"Remote Configuration\",\n \"obsidianLiveSyncSettingTab.panelSetup\": \"Setup\",\n \"obsidianLiveSyncSettingTab.serverVersion\": \"Server info: ${info}\",\n \"obsidianLiveSyncSettingTab.titleActiveRemoteServer\": \"Active Remote Server\",\n \"obsidianLiveSyncSettingTab.titleAppearance\": \"Appearance\",\n \"obsidianLiveSyncSettingTab.titleConflictResolution\": \"Conflict resolution\",\n \"obsidianLiveSyncSettingTab.titleCongratulations\": \"Congratulations!\",\n \"obsidianLiveSyncSettingTab.titleCouchDB\": \"CouchDB\",\n \"obsidianLiveSyncSettingTab.titleDeletionPropagation\": \"Deletion Propagation\",\n \"obsidianLiveSyncSettingTab.titleEncryptionNotEnabled\": \"Encryption is not enabled\",\n \"obsidianLiveSyncSettingTab.titleEncryptionPassphraseInvalid\": \"Encryption Passphrase Invalid\",\n \"obsidianLiveSyncSettingTab.titleExtraFeatures\": \"Enable extra and advanced features\",\n \"obsidianLiveSyncSettingTab.titleFetchConfig\": \"Fetch Config\",\n \"obsidianLiveSyncSettingTab.titleFetchConfigFromRemote\": \"Fetch config from remote server\",\n \"obsidianLiveSyncSettingTab.titleFetchSettings\": \"Fetch Settings\",\n \"obsidianLiveSyncSettingTab.titleHiddenFiles\": \"Hidden Files\",\n \"obsidianLiveSyncSettingTab.titleLogging\": \"Logging\",\n \"obsidianLiveSyncSettingTab.titleMinioS3R2\": \"Minio,S3,R2\",\n \"obsidianLiveSyncSettingTab.titleNotification\": \"Notification\",\n \"obsidianLiveSyncSettingTab.titleOnlineTips\": \"Online Tips\",\n \"obsidianLiveSyncSettingTab.titleQuickSetup\": \"Quick Setup\",\n \"obsidianLiveSyncSettingTab.titleRebuildRequired\": \"Rebuild Required\",\n \"obsidianLiveSyncSettingTab.titleRemoteConfigCheckFailed\": \"Remote Configuration Check Failed\",\n \"obsidianLiveSyncSettingTab.titleRemoteServer\": \"Remote Server\",\n \"obsidianLiveSyncSettingTab.titleReset\": \"Reset\",\n \"obsidianLiveSyncSettingTab.titleSetupOtherDevices\": \"To setup other devices\",\n \"obsidianLiveSyncSettingTab.titleSynchronizationMethod\": \"Synchronization Method\",\n \"obsidianLiveSyncSettingTab.titleSynchronizationPreset\": \"Synchronization Preset\",\n \"obsidianLiveSyncSettingTab.titleSyncSettings\": \"Sync Settings\",\n \"obsidianLiveSyncSettingTab.titleSyncSettingsViaMarkdown\": \"Sync Settings via Markdown\",\n \"obsidianLiveSyncSettingTab.titleUpdateThinning\": \"Update Thinning\",\n \"obsidianLiveSyncSettingTab.warnCorsOriginUnmatched\": \"⚠ CORS Origin is unmatched ${from}->${to}\",\n \"obsidianLiveSyncSettingTab.warnNoAdmin\": \"⚠ You do not have administrator privileges.\",\n \"P2P.AskPassphraseForDecrypt\": \"The remote peer shared the configuration. Please input the passphrase to decrypt the configuration.\",\n \"P2P.AskPassphraseForShare\": \"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.FailedToOpen\": \"Failed to open P2P connection to the signalling server.\",\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.Note.description\": \" This replicator allows us to synchronise our vault with other devices\\nusing a peer-to-peer connection. We can use this to synchronise our vault with our other devices without using a cloud service.\\nThis replicator is based on Trystero. It also uses a signalling server to establish a connection between devices. The signalling server is used to exchange connection information between devices. It does (or,should) not know or store any of our data.\\n\\nThe signalling server can be hosted by anyone. This is just a Nostr relay. For the sake of simplicity and checking the behaviour of the replicator, an instance of the signalling server is hosted by vrtmrz. You can use the experimental server provided by vrtmrz, or you can use any other server.\\n\\nBy the way, even if the signalling server does not store our data, it can see the connection information of some of our devices. Please be aware of this. Also, be cautious when using the server provided by someone else.\",\n \"P2P.Note.important_note\": \"Peer-to-Peer Replicator.\",\n \"P2P.Note.important_note_sub\": \"This feature is still on the bleeding edge. Please be aware that ensure your data is backed up before using this feature. And, we would be so happy if you could contribute to the development of this feature.\",\n \"P2P.Note.Summary\": \"What is this feature? (and some important notes, please read once)\",\n \"P2P.NotEnabled\": \"%{title_p2p_sync} is not enabled. We cannot open a new connection.\",\n \"P2P.P2PReplication\": \"%{P2P} Replication\",\n \"P2P.PaneTitle\": \"%{long_p2p_sync}\",\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 \"Password\": \"Password\",\n \"Path Obfuscation\": \"Path Obfuscation\",\n \"Per-file-saved customization sync\": \"Per-file-saved customization sync\",\n \"Periodic Sync interval\": \"Periodic Sync interval\",\n \"Prepare the 'report' to create an issue\": \"Prepare the 'report' to create an issue\",\n \"Presets\": \"Presets\",\n \"Process small files in the foreground\": \"Process small files in the foreground\",\n \"Property Encryption\": \"Property Encryption\",\n \"RedFlag.Fetch.Method.Desc\": \"How do you want to fetch?\\n- %{RedFlag.Fetch.Method.FetchSafer}.\\n **Low Traffic**, **High CPU**, **Low Risk**\\n Recommended if ...\\n - Files possibly inconsistent\\n - Files were not so much\\n- %{RedFlag.Fetch.Method.FetchSmoother}.\\n **Low Traffic**, **Moderate CPU**, **Low to Moderate Risk**\\n Recommended if ...\\n - Files probably consistent\\n - You have a lot of files.\\n- %{RedFlag.Fetch.Method.FetchTraditional}.\\n **High Traffic**, **Low CPU**, **Low to Moderate Risk**\\n\\n>[!INFO]- Details\\n> ## %{RedFlag.Fetch.Method.FetchSafer}.\\n> **Low Traffic**, **High CPU**, **Low Risk**\\n> This option first creates a local database using existing local files before fetching data from the remote source.\\n> If matching files exist both locally and remotely, only the differences between them will be transferred.\\n> However, files present in both locations will initially be handled as conflicted files. They will be resolved automatically if they are not actually conflicted, but this process may take time.\\n> This is generally the safest method, minimizing data loss risk.\\n> ## %{RedFlag.Fetch.Method.FetchSmoother}.\\n> **Low Traffic**, **Moderate CPU**, **Low to Moderate Risk** (depending operation)\\n> This option first creates chunks from local files for the database, then fetches data. Consequently, only chunks missing locally are transferred. However, all metadata is taken from the remote source.\\n> Local files are then compared against this metadata at launch. The content considered newer will overwrite the older one (by modified time). This outcome is then synchronised back to the remote database.\\n> This is generally safe if local files are genuinely the latest timestamp. However, it can cause problems if a file has a newer timestamp but older content (like the initial `welcome.md`).\\n> This uses less CPU and faster than \\\"%{RedFlag.Fetch.Method.FetchSafer}\\\", but it may lead to data loss if not used carefully.\\n> ## %{RedFlag.Fetch.Method.FetchTraditional}.\\n> **High Traffic**, **Low CPU**, **Low to Moderate Risk** (depending operation)\\n> All things will be fetched from the remote.\\n> Similar to the %{RedFlag.Fetch.Method.FetchSmoother}, but all chunks are fetched from the remote source.\\n> This is the most traditional way to fetch, typically consuming the most network traffic and time. It also carries a similar risk of overwriting remote files to the '%{RedFlag.Fetch.Method.FetchSmoother}' option.\\n> However, it is often considered the most stable method because it is the longest-established and most straightforward approach.\",\n \"RedFlag.Fetch.Method.FetchSafer\": \"Create a local database once before fetching\",\n \"RedFlag.Fetch.Method.FetchSmoother\": \"Create local file chunks before fetching\",\n \"RedFlag.Fetch.Method.FetchTraditional\": \"Fetch everything from the remote\",\n \"RedFlag.Fetch.Method.Title\": \"How do you want to fetch?\",\n \"RedFlag.FetchRemoteConfig.Buttons.Cancel\": \"No, use local settings\",\n \"RedFlag.FetchRemoteConfig.Buttons.Fetch\": \"Yes, fetch and apply remote settings\",\n \"RedFlag.FetchRemoteConfig.Message\": \"Do you want to fetch and apply remotely stored preference settings to the device?\",\n \"RedFlag.FetchRemoteConfig.Title\": \"Fetch Remote Configuration\",\n \"Reducing the frequency with which on-disk changes are reflected into the DB\": \"Reducing the frequency with which on-disk changes are reflected into the DB\",\n \"Region\": \"Region\",\n \"Remote server type\": \"Remote server type\",\n \"Remote Type\": \"Remote Type\",\n \"Replicator.Dialogue.Locked.Action.Dismiss\": \"Cancel for reconfirmation\",\n \"Replicator.Dialogue.Locked.Action.Fetch\": \"Reset Synchronisation on This Device\",\n \"Replicator.Dialogue.Locked.Action.Unlock\": \"Unlock the remote database\",\n \"Replicator.Dialogue.Locked.Message\": \"Remote database is locked. This is due to a rebuild on one of the terminals.\\nThe device is therefore asked to withhold the connection to avoid database corruption.\\n\\nThere are three options that we can do:\\n\\n- %{Replicator.Dialogue.Locked.Action.Fetch}\\n The most preferred and reliable way. This will dispose the local database once, and reset all synchronisation information from the remote database again, In most case, we can perform this safely. However, it takes some time and should be done in stable network.\\n- %{Replicator.Dialogue.Locked.Action.Unlock}\\n This method can only be used if we are already reliably synchronised by other replication methods. This does not simply mean that we have the same files. If you are not sure, you should avoid it.\\n- %{Replicator.Dialogue.Locked.Action.Dismiss}\\n This will cancel the operation. And we will asked again on next request.\\n\",\n \"Replicator.Dialogue.Locked.Message.Fetch\": \"Fetch all has been scheduled. Plug-in will be restarted to perform it.\",\n \"Replicator.Dialogue.Locked.Message.Unlocked\": \"The remote database has been unlocked. Please retry the operation.\",\n \"Replicator.Dialogue.Locked.Title\": \"Locked\",\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\": \"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 \"Requires restart of Obsidian.\": \"Requires restart of Obsidian.\",\n \"Rerun Onboarding Wizard\": \"Rerun Onboarding Wizard\",\n \"Rerun the onboarding wizard to set up Self-hosted LiveSync again.\": \"Rerun the onboarding wizard to set up Self-hosted LiveSync again.\",\n \"Rerun Wizard\": \"Rerun Wizard\",\n \"Reset notification threshold and check the remote database usage\": \"Reset notification threshold and check the remote database usage\",\n \"Reset the remote storage size threshold and check the remote storage size again.\": \"Reset the remote storage size threshold and check the remote storage size again.\",\n \"Run Doctor\": \"Run Doctor\",\n \"Save settings to a markdown file. You will be notified when new settings arrive. You can set different files by the platform.\": \"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.\": \"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.\": \"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 \"Setting.GenerateKeyPair.Desc\": \"We have generated a key pair!\\n\\nNote: This key pair will never be shown again. Please save it in a safe place. If you have lost it, you need to generate a new key pair.\\nNote 2: The public key is in spki format, and the Private key is in pkcs8 format. For the sake of convenience, newlines are converted to `\\\\n` in public key.\\nNote 3: The public key should be configured in the remote database, and the private key should be configured in local devices.\\n\\n>[!FOR YOUR EYES ONLY]-\\n> <div class=\\\"sls-keypair\\\">\\n>\\n> ### Public Key\\n> ```\\n${public_key}\\n> ```\\n>\\n> ### Private Key\\n> ```\\n${private_key}\\n> ```\\n>\\n> </div>\\n\\n>[!Both for copying]-\\n>\\n> <div class=\\\"sls-keypair\\\">\\n>\\n> ```\\n${public_key}\\n${private_key}\\n> ```\\n>\\n> </div>\\n\\n\",\n \"Setting.GenerateKeyPair.Title\": \"New key pair has been generated!\",\n \"Setting.TroubleShooting\": \"TroubleShooting\",\n \"Setting.TroubleShooting.Doctor\": \"Setting Doctor\",\n \"Setting.TroubleShooting.Doctor.Desc\": \"Detects non optimal settings. (Same as during migration)\",\n \"Setting.TroubleShooting.ScanBrokenFiles\": \"Scan for broken files\",\n \"Setting.TroubleShooting.ScanBrokenFiles.Desc\": \"Scans for files that are not stored correctly in the database.\",\n \"SettingTab.Message.AskRebuild\": \"Your changes require fetching from the remote database. Do you want to proceed?\",\n \"Setup.Apply.Buttons.ApplyAndFetch\": \"Apply and Fetch\",\n \"Setup.Apply.Buttons.ApplyAndMerge\": \"Apply and Merge\",\n \"Setup.Apply.Buttons.ApplyAndRebuild\": \"Apply and Rebuild\",\n \"Setup.Apply.Buttons.Cancel\": \"Discard and Cancel\",\n \"Setup.Apply.Buttons.OnlyApply\": \"Only Apply\",\n \"Setup.Apply.Message\": \"The new configuration is ready. Let us proceed to apply it.\\nThere are several ways to apply this:\\n\\n- Apply and Fetch\\n Configure this device as a new client. After applying, synchronise from the remote server.\\n- Apply and Merge\\n Configure on a device that already has the file. It processes the local files and transfers the differences. Conflicts may arise.\\n- Apply and Rebuild\\n Rebuild the remote using local files. This is typically done if the server becomes corrupted or we wish to start from scratch.\\n Other devices will be locked and required to re-fetch.\\n- Only Apply\\n Apply only. Conflicts may arise if a rebuild is required.\",\n \"Setup.Apply.Title\": \"Apply new configuration from the ${method}\",\n \"Setup.Apply.WarningRebuildRecommended\": \"NOTE: after adjusting the settings, it has been determined that a rebuild is required; Just Import is not recommended.\",\n \"Setup.Doctor.Buttons.No\": \"No, please use the settings in the URI as is\",\n \"Setup.Doctor.Buttons.Yes\": \"Yes, please consult the doctor\",\n \"Setup.Doctor.Message\": \"Self-hosted LiveSync has gradually become longer in history and some recommended settings have changed.\\n\\nNow, setup is a very good time to do this.\\n\\nDo you want to run Doctor to check if the imported settings are optimal compared to the latest state?\",\n \"Setup.Doctor.Title\": \"Do you want to consult the doctor?\",\n \"Setup.FetchRemoteConf.Buttons.Fetch\": \"Yes, please fetch the configuration\",\n \"Setup.FetchRemoteConf.Buttons.Skip\": \"No, please use the settings in the URI\",\n \"Setup.FetchRemoteConf.Message\": \"If we have already synchronised once with another device, the remote database stores the suitable configuration values between the synchronised devices. The plug-in would like to retrieve them for robust configuration.\\n\\nHowever, we have to make sure the one thing. Are we currently in a situation where we can access the network safely and retrieve the settings?\\n\\nNote: Mostly, you are safe to do this, that your remote database is hosted with a SSL certificate, and your network is not compromised.\",\n \"Setup.FetchRemoteConf.Title\": \"Fetch configuration from remote database?\",\n \"Setup.QRCode\": \"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 \"Setup.ShowQRCode\": \"Show QR code\",\n \"Setup.ShowQRCode.Desc\": \"Show QR code to transfer the settings.\",\n \"Should we keep folders that don't have any files inside?\": \"Should we keep folders that don't have any files inside?\",\n \"Should we only check for conflicts when a file is opened?\": \"Should we only check for conflicts when a file is opened?\",\n \"Should we prompt you about conflicting files when a file is opened?\": \"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?\": \"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.\": \"Show verbose log. Please enable if you report an issue.\",\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 \"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 after merging file\": \"Sync after merging file\",\n \"Sync automatically after merging files\": \"Sync automatically after merging files\",\n \"Sync Mode\": \"Sync Mode\",\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 \"Testing only - Resolve file conflicts by syncing newer copies of the file, this can overwrite modified files. Be Warned.\": \"Testing only - Resolve file conflicts by syncing newer copies of the file, this can overwrite modified files. Be Warned.\",\n \"The delay for consecutive on-demand fetches\": \"The delay for consecutive on-demand fetches\",\n \"The Hash algorithm for chunk IDs\": \"The Hash algorithm for chunk IDs\",\n \"The maximum duration for which chunks can be incubated within the document. Chunks exceeding this period will graduate to independent chunks.\": \"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.\": \"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.\": \"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.\": \"The minimum interval for automatic synchronisation on event.\",\n \"This passphrase will not be copied to another device. It will be set to `Default` until you configure it again.\": \"This passphrase will not be copied to another device. It will be set to `Default` until you configure it again.\",\n \"TweakMismatchResolve.Action.Dismiss\": \"Dismiss\",\n \"TweakMismatchResolve.Action.UseConfigured\": \"Use configured settings\",\n \"TweakMismatchResolve.Action.UseMine\": \"Update remote database settings\",\n \"TweakMismatchResolve.Action.UseMineAcceptIncompatible\": \"Update remote database settings but keep as is\",\n \"TweakMismatchResolve.Action.UseMineWithRebuild\": \"Update remote database settings and rebuild again\",\n \"TweakMismatchResolve.Action.UseRemote\": \"Apply settings to this device\",\n \"TweakMismatchResolve.Action.UseRemoteAcceptIncompatible\": \"Apply settings to this device, but and ignore incompatibility\",\n \"TweakMismatchResolve.Action.UseRemoteWithRebuild\": \"Apply settings to this device, and fetch again\",\n \"TweakMismatchResolve.Message.Main\": \"\\nThe settings in the remote database are as follows. These values are configured by other devices, which are synchronised with this device at least once.\\n\\nIf you want to use these settings, please select %{TweakMismatchResolve.Action.UseConfigured}.\\nIf you want to keep the settings of this device, please select %{TweakMismatchResolve.Action.Dismiss}.\\n\\n${table}\\n\\n>[!TIP]\\n> If you want to synchronise all settings, please use `Sync settings via markdown` after applying minimal configuration with this feature.\\n\\n${additionalMessage}\",\n \"TweakMismatchResolve.Message.MainTweakResolving\": \"Your configuration has not been matched with the one on the remote server.\\n\\nFollowing configuration should be matched:\\n\\n${table}\\n\\nLet us know your decision.\\n\\n${additionalMessage}\",\n \"TweakMismatchResolve.Message.UseRemote.WarningRebuildRecommended\": \"\\n>[!NOTICE]\\n> Some changes are compatible but may consume extra storage and transfer volumes. A rebuild is recommended. However, a rebuild may not be performed at present, but may be implemented in future maintenance.\\n> ***Please ensure that you have time and are connected to a stable network to apply!***\",\n \"TweakMismatchResolve.Message.UseRemote.WarningRebuildRequired\": \"\\n>[!WARNING]\\n> Some remote configurations are not compatible with the local database of this device. Rebuilding the local database will be required.\\n> ***Please ensure that you have time and are connected to a stable network to apply!***\",\n \"TweakMismatchResolve.Message.WarningIncompatibleRebuildRecommended\": \"\\n>[!NOTICE]\\n> We have detected that some of the values are different to make incompatible the local database with the remote database.\\n> Some changes are compatible but may consume extra storage and transfer volumes. A rebuild is recommended. However, a rebuild may not be performed at present, but may be implemented in future maintenance.\\n> If you want to rebuild, it takes a few minutes or more. **Make sure it is safe to perform it now.**\",\n \"TweakMismatchResolve.Message.WarningIncompatibleRebuildRequired\": \"\\n>[!WARNING]\\n> We have detected that some of the values are different to make incompatible the local database with the remote database.\\n> Either local or remote rebuilds are required. Both of them takes a few minutes or more. **Make sure it is safe to perform it now.**\",\n \"TweakMismatchResolve.Table\": \"| Value name | This device | On Remote |\\n|: --- |: ---- :|: ---- :|\\n${rows}\\n\\n\",\n \"TweakMismatchResolve.Table.Row\": \"| ${name} | ${self} | ${remote} |\",\n \"TweakMismatchResolve.Title\": \"Configuration Mismatch Detected\",\n \"TweakMismatchResolve.Title.TweakResolving\": \"Configuration Mismatch Detected\",\n \"TweakMismatchResolve.Title.UseRemoteConfig\": \"Use Remote Configuration\",\n \"Unique name between all synchronized devices. To edit this setting, please disable customization sync once.\": \"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 dynamic iteration count\": \"Use dynamic iteration count\",\n \"Use Segmented-splitter\": \"Use Segmented-splitter\",\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 \"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.\": \"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\": \"When you save a file in the editor, start a sync automatically\",\n \"Write credentials in the file\": \"Write credentials in the file\",\n \"Write logs into the file\": \"Write logs into the file\"\n}\n","import def from \"../messagesJson/en.json\";\nexport const PartialMessages = {\n def,\n} as const;\n","{\n \"(BETA) Always overwrite with a newer file\": \"(BETA) Sobrescribir siempre con archivo más nuevo\",\n \"(Beta) Use ignore files\": \"(Beta) Usar archivos de ignorar\",\n \"(Days passed, 0 to disable automatic-deletion)\": \"(Días transcurridos, 0 para desactivar)\",\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.\": \"(Ej: Leer chunks online) Lee chunks directamente en línea. Aumente tamaño de chunks personalizados\",\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.\": \"(MB) Saltar cambios en archivos locales/remotos mayores a este tamaño. Si se reduce, se usará versión nueva\",\n \"(Mega chars)\": \"(Millones de caracteres)\",\n \"(Not recommended) If set, credentials will be stored in the file.\": \"(No recomendado) Almacena credenciales en el archivo\",\n \"(Obsolete) Use an old adapter for compatibility\": \"(Obsoleto) Usar adaptador antiguo\",\n \"Access Key\": \"Clave de acceso\",\n \"Always prompt merge conflicts\": \"Siempre preguntar en conflictos\",\n \"Apply Latest Change if Conflicting\": \"Aplicar último cambio en conflictos\",\n \"Apply preset configuration\": \"Aplicar configuración predefinida\",\n \"Automatically Sync all files when opening Obsidian.\": \"Sincronizar automáticamente todos los archivos al abrir Obsidian\",\n \"Batch database update\": \"Actualización por lotes de BD\",\n \"Batch limit\": \"Límite de lotes\",\n \"Batch size\": \"Tamaño de lote\",\n \"Batch size of on-demand fetching\": \"Tamaño de lote para obtención bajo demanda\",\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.\": \"Antes de v0.17.16 usábamos adaptador antiguo. Nuevo adaptador requiere reconstruir BD local. Desactive cuando pueda\",\n \"Bucket Name\": \"Nombre del bucket\",\n \"cmdConfigSync.showCustomizationSync\": \"Mostrar sincronización de personalización\",\n \"Comma separated `.gitignore, .dockerignore`\": \"Separados por comas: `.gitignore, .dockerignore`\",\n \"Compute revisions for chunks (Previous behaviour)\": \"Calcular revisiones para chunks (comportamiento anterior)\",\n \"Data Compression\": \"Compresión de datos\",\n \"Database Name\": \"Nombre de la base de datos\",\n \"Database suffix\": \"Sufijo de base de datos\",\n \"Delay conflict resolution of inactive files\": \"Retrasar resolución de conflictos en archivos inactivos\",\n \"Delay merge conflict prompt for inactive files.\": \"Retrasar aviso de fusión para archivos inactivos\",\n \"Delete old metadata of deleted files on start-up\": \"Borrar metadatos viejos al iniciar\",\n \"Device name\": \"Nombre del dispositivo\",\n \"Disables logging, only shows notifications. Please disable if you report an issue.\": \"Desactiva registros, solo muestra notificaciones. Desactívelo si reporta un problema.\",\n \"Display Language\": \"Idioma de visualización\",\n \"Do not check configuration mismatch before replication\": \"No verificar incompatibilidades antes de replicar\",\n \"Do not keep metadata of deleted files.\": \"No conservar metadatos de archivos borrados\",\n \"Do not split chunks in the background\": \"No dividir chunks en segundo plano\",\n \"Do not use internal API\": \"No usar API interna\",\n \"Enable advanced features\": \"Habilitar características avanzadas\",\n \"Enable customization sync\": \"Habilitar sincronización de personalización\",\n \"Enable Developers' Debug Tools.\": \"Habilitar herramientas de depuración\",\n \"Enable edge case treatment features\": \"Habilitar manejo de casos límite\",\n \"Enable poweruser features\": \"Habilitar funciones para usuarios avanzados\",\n \"Enable this if your Object Storage doesn't support CORS\": \"Habilitar si su almacenamiento no soporta CORS\",\n \"Enable this option to automatically apply the most recent change to documents even when it conflicts\": \"Aplicar cambios recientes automáticamente aunque generen conflictos\",\n \"Encrypt contents on the remote database. If you use the plugin's synchronization feature, enabling this is recommended.\": \"Cifrar contenido en la base de datos remota. Se recomienda habilitar si usa la sincronización del plugin.\",\n \"Encrypting sensitive configuration items\": \"Cifrando elementos sensibles\",\n \"Encryption phassphrase. If changed, you should overwrite the server's database with the new (encrypted) files.\": \"Frase de cifrado. Si la cambia, sobrescriba la base del servidor con los nuevos archivos cifrados.\",\n \"End-to-End Encryption\": \"Cifrado de extremo a extremo\",\n \"Endpoint URL\": \"URL del endpoint\",\n \"Enhance chunk size\": \"Mejorar tamaño de chunks\",\n \"Fetch chunks on demand\": \"Obtener chunks bajo demanda\",\n \"Fetch database with previous behaviour\": \"Obtener BD con comportamiento anterior\",\n \"Filename\": \"Nombre de archivo\",\n \"Forces the file to be synced when opened.\": \"Forzar sincronización al abrir archivo\",\n \"Handle files as Case-Sensitive\": \"Manejar archivos como sensibles a mayúsculas\",\n \"If disabled(toggled), chunks will be split on the UI thread (Previous behaviour).\": \"Si se desactiva, chunks se dividen en hilo UI (comportamiento anterior)\",\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.\": \"Habilita sincronización eficiente por archivo. Requiere migración y actualizar todos dispositivos a v0.23.18. Pierde compatibilidad con versiones antiguas\",\n \"If enabled, chunks will be split into no more than 100 items. However, dedupe is slightly weaker.\": \"Divide chunks en máximo 100 ítems. Menos eficiente en deduplicación\",\n \"If enabled, newly created chunks are temporarily kept within the document, and graduated to become independent chunks once stabilised.\": \"Chunks nuevos se mantienen temporalmente en el documento hasta estabilizarse\",\n \"If enabled, the file under 1kb will be processed in the UI thread.\": \"Archivos <1kb se procesan en hilo UI\",\n \"If enabled, the notification of hidden files change will be suppressed.\": \"Si se habilita, se suprimirá la notificación de cambios en archivos ocultos.\",\n \"If this enabled, all chunks will be stored with the revision made from its content. (Previous behaviour)\": \"Si se habilita, todos los chunks se almacenan con la revisión hecha desde su contenido. (comportamiento anterior)\",\n \"If this enabled, All files are handled as case-Sensitive (Previous behaviour).\": \"Si se habilita, todos los archivos se manejan como sensibles a mayúsculas (comportamiento anterior)\",\n \"If this enabled, chunks will be split into semantically meaningful segments. Not all platforms support this feature.\": \"Divide chunks en segmentos semánticos. No todos los sistemas lo soportan\",\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.\": \"Saltar cambios en archivos locales que coincidan con ignore files. Cambios remotos usan ignore files locales\",\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.\": \"Mantiene conexión 60s. Si no hay cambios, reinicia socket. Útil con proxies limitantes\",\n \"Ignore files\": \"Archivos a ignorar\",\n \"Incubate Chunks in Document\": \"Incubar chunks en documento\",\n \"Interval (sec)\": \"Intervalo (segundos)\",\n \"Keep empty folder\": \"Mantener carpetas vacías\",\n \"lang-de\": \"Alemán\",\n \"lang-es\": \"Español\",\n \"lang-ja\": \"Japonés\",\n \"lang-ru\": \"Ruso\",\n \"lang-zh\": \"Chino simplificado\",\n \"lang-zh-tw\": \"Chino tradicional\",\n \"LiveSync could not handle multiple vaults which have same name without different prefix, This should be automatically configured.\": \"LiveSync no puede manejar múltiples bóvedas con mismo nombre sin prefijo. Se configura automáticamente\",\n \"liveSyncReplicator.beforeLiveSync\": \"Antes de LiveSync, inicia OneShot...\",\n \"liveSyncReplicator.cantReplicateLowerValue\": \"No podemos replicar un valor más bajo.\",\n \"liveSyncReplicator.checkingLastSyncPoint\": \"Buscando el último punto sincronizado.\",\n \"liveSyncReplicator.couldNotConnectTo\": \"No se pudo conectar a ${uri} : ${name} \\n(${db})\",\n \"liveSyncReplicator.couldNotConnectToRemoteDb\": \"No se pudo conectar a base de datos remota: ${d}\",\n \"liveSyncReplicator.couldNotConnectToServer\": \"No se pudo conectar al servidor.\",\n \"liveSyncReplicator.couldNotConnectToURI\": \"No se pudo conectar a ${uri}:${dbRet}\",\n \"liveSyncReplicator.couldNotMarkResolveRemoteDb\": \"No se pudo marcar como resuelta la base de datos remota.\",\n \"liveSyncReplicator.liveSyncBegin\": \"Inicio de LiveSync...\",\n \"liveSyncReplicator.lockRemoteDb\": \"Bloquear base de datos remota para prevenir corrupción de datos\",\n \"liveSyncReplicator.markDeviceResolved\": \"Marcar este dispositivo como 'resuelto'.\",\n \"liveSyncReplicator.oneShotSyncBegin\": \"Inicio de sincronización OneShot... (${syncMode})\",\n \"liveSyncReplicator.remoteDbCorrupted\": \"La base de datos remota es más nueva o está dañada, asegúrese de tener la última versión de self-hosted-livesync instalada\",\n \"liveSyncReplicator.remoteDbCreatedOrConnected\": \"Base de datos remota creada o conectada\",\n \"liveSyncReplicator.remoteDbDestroyed\": \"Base de datos remota destruida\",\n \"liveSyncReplicator.remoteDbDestroyError\": \"Algo ocurrió al destruir base de datos remota:\",\n \"liveSyncReplicator.remoteDbMarkedResolved\": \"Base de datos remota marcada como resuelta.\",\n \"liveSyncReplicator.replicationClosed\": \"Replicación cerrada\",\n \"liveSyncReplicator.replicationInProgress\": \"Replicación en curso\",\n \"liveSyncReplicator.retryLowerBatchSize\": \"Reintentar con tamaño de lote más bajo:${batch_size}/${batches_limit}\",\n \"liveSyncReplicator.unlockRemoteDb\": \"Desbloquear base de datos remota para prevenir corrupción de datos\",\n \"liveSyncSetting.errorNoSuchSettingItem\": \"No existe el ajuste: ${key}\",\n \"liveSyncSetting.originalValue\": \"Original: ${value}\",\n \"liveSyncSetting.valueShouldBeInRange\": \"El valor debe estar entre ${min} y ${max}\",\n \"liveSyncSettings.btnApply\": \"Aplicar\",\n \"logPane.autoScroll\": \"Autodesplazamiento\",\n \"logPane.logWindowOpened\": \"Ventana de registro abierta\",\n \"logPane.pause\": \"Pausar\",\n \"logPane.title\": \"Registro de Self-hosted LiveSync\",\n \"logPane.wrap\": \"Ajustar\",\n \"Maximum delay for batch database updating\": \"Retraso máximo para actualización por lotes\",\n \"Maximum file size\": \"Tamaño máximo de archivo\",\n \"Maximum Incubating Chunk Size\": \"Tamaño máximo de chunks incubados\",\n \"Maximum Incubating Chunks\": \"Máximo de chunks incubados\",\n \"Maximum Incubation Period\": \"Periodo máximo de incubación\",\n \"MB (0 to disable).\": \"MB (0 para desactivar)\",\n \"Memory cache size (by total characters)\": \"Tamaño caché memoria (por caracteres)\",\n \"Memory cache size (by total items)\": \"Tamaño caché memoria (por ítems)\",\n \"Minimum delay for batch database updating\": \"Retraso mínimo para actualización por lotes\",\n \"moduleCheckRemoteSize.logCheckingStorageSizes\": \"Comprobando tamaños de almacenamiento\",\n \"moduleCheckRemoteSize.logCurrentStorageSize\": \"Tamaño del almacenamiento remoto: ${measuredSize}\",\n \"moduleCheckRemoteSize.logExceededWarning\": \"Tamaño del almacenamiento remoto: ${measuredSize} superó ${notifySize}\",\n \"moduleCheckRemoteSize.logThresholdEnlarged\": \"El umbral se ha ampliado a ${size}MB\",\n \"moduleCheckRemoteSize.msgConfirmRebuild\": \"Esto puede llevar un poco de tiempo. ¿Realmente quieres reconstruir todo ahora?\",\n \"moduleCheckRemoteSize.msgDatabaseGrowing\": \"**¡Tu base de datos está creciendo!** Pero no te preocupes, podemos abordarlo ahora. El tiempo antes de quedarse sin espacio en el almacenamiento remoto.\\n\\n| Tamaño medido | Tamaño configurado |\\n| --- | --- |\\n| ${estimatedSize} | ${maxSize} |\\n\\n> [!MORE]-\\n> Si lo has estado utilizando durante muchos años, puede haber fragmentos no referenciados - es decir, basura - acumulándose en la base de datos. Por lo tanto, recomendamos reconstruir todo. Probablemente se volverá mucho más pequeño.\\n>\\n> Si el volumen de tu bóveda simplemente está aumentando, es mejor reconstruir todo después de organizar los archivos. Self-hosted LiveSync no elimina los datos reales incluso si los eliminas para acelerar el proceso. Está aproximadamente [documentado](https://github.com/vrtmrz/obsidian-livesync/blob/main/docs/tech_info.md).\\n>\\n> Si no te importa el aumento, puedes aumentar el límite de notificación en 100 MB. Este es el caso si lo estás ejecutando en tu propio servidor. Sin embargo, es mejor reconstruir todo de vez en cuando.\\n>\\n\\n> [!WARNING]\\n> Si realizas la reconstrucción completa, asegúrate de que todos los dispositivos estén sincronizados. El complemento fusionará tanto como sea posible, sin embargo.\\n\",\n \"moduleCheckRemoteSize.msgSetDBCapacity\": \"Podemos configurar una advertencia de capacidad máxima de base de datos, **para tomar medidas antes de quedarse sin espacio en el almacenamiento remoto**.\\n¿Quieres habilitar esto?\\n\\n> [!MORE]-\\n> - 0: No advertir sobre el tamaño del almacenamiento.\\n> Esto es recomendado si tienes suficiente espacio en el almacenamiento remoto, especialmente si lo tienes autoalojado. Y puedes comprobar el tamaño del almacenamiento y reconstruir manualmente.\\n> - 800: Advertir si el tamaño del almacenamiento remoto supera los 800 MB.\\n> Esto es recomendado si estás usando fly.io con un límite de 1 GB o IBM Cloudant.\\n> - 2000: Advertir si el tamaño del almacenamiento remoto supera los 2 GB.\\n\\nSi hemos alcanzado el límite, se nos pedirá que aumentemos el límite paso a paso.\\n\",\n \"moduleCheckRemoteSize.option2GB\": \"2GB (Estándar)\",\n \"moduleCheckRemoteSize.option800MB\": \"800MB (Cloudant, fly.io)\",\n \"moduleCheckRemoteSize.optionAskMeLater\": \"Pregúntame más tarde\",\n \"moduleCheckRemoteSize.optionDismiss\": \"Descartar\",\n \"moduleCheckRemoteSize.optionIncreaseLimit\": \"aumentar a ${newMax}MB\",\n \"moduleCheckRemoteSize.optionNoWarn\": \"No, nunca advertir por favor\",\n \"moduleCheckRemoteSize.optionRebuildAll\": \"Reconstruir todo ahora\",\n \"moduleCheckRemoteSize.titleDatabaseSizeLimitExceeded\": \"El tamaño del almacenamiento remoto superó el límite\",\n \"moduleCheckRemoteSize.titleDatabaseSizeNotify\": \"Configuración de notificación de tamaño de base de datos\",\n \"moduleInputUIObsidian.defaultTitleConfirmation\": \"Confirmación\",\n \"moduleInputUIObsidian.defaultTitleSelect\": \"Seleccionar\",\n \"moduleInputUIObsidian.optionNo\": \"No\",\n \"moduleInputUIObsidian.optionYes\": \"Sí\",\n \"moduleLiveSyncMain.logAdditionalSafetyScan\": \"Escanéo de seguridad adicional...\",\n \"moduleLiveSyncMain.logLoadingPlugin\": \"Cargando complemento...\",\n \"moduleLiveSyncMain.logPluginInitCancelled\": \"La inicialización del complemento fue cancelada por un módulo\",\n \"moduleLiveSyncMain.logPluginVersion\": \"Self-hosted LiveSync v${manifestVersion} ${packageVersion}\",\n \"moduleLiveSyncMain.logReadChangelog\": \"LiveSync se ha actualizado, ¡por favor lee el registro de cambios!\",\n \"moduleLiveSyncMain.logSafetyScanCompleted\": \"Escanéo de seguridad adicional completado\",\n \"moduleLiveSyncMain.logSafetyScanFailed\": \"El escaneo de seguridad adicional ha fallado en un módulo\",\n \"moduleLiveSyncMain.logUnloadingPlugin\": \"Descargando complemento...\",\n \"moduleLiveSyncMain.logVersionUpdate\": \"LiveSync se ha actualizado, en caso de actualizaciones que rompan, toda la sincronización automática se ha desactivado temporalmente. Asegúrate de que todos los dispositivos estén actualizados antes de habilitar.\",\n \"moduleLiveSyncMain.msgScramEnabled\": \"Self-hosted LiveSync se ha configurado para ignorar algunos eventos. ¿Es esto correcto?\\n\\n| Tipo | Estado | Nota |\\n|:---:|:---:|---|\\n| Eventos de almacenamiento | ${fileWatchingStatus} | Se ignorará cada modificación |\\n| Eventos de base de datos | ${parseReplicationStatus} | Cada cambio sincronizado se pospondrá |\\n\\n¿Quieres reanudarlos y reiniciar Obsidian?\\n\\n> [!DETAILS]-\\n> Estas banderas son establecidas por el complemento mientras se reconstruye o se obtiene. Si el proceso termina de forma anormal, puede mantenerse sin querer.\\n> Si no estás seguro, puedes intentar volver a ejecutar estos procesos. Asegúrate de hacer una copia de seguridad de tu bóveda.\\n\",\n \"moduleLiveSyncMain.optionKeepLiveSyncDisabled\": \"Mantener LiveSync desactivado\",\n \"moduleLiveSyncMain.optionResumeAndRestart\": \"Reanudar y reiniciar Obsidian\",\n \"moduleLiveSyncMain.titleScramEnabled\": \"Scram habilitado\",\n \"moduleLocalDatabase.logWaitingForReady\": \"Esperando a que la base de datos esté lista...\",\n \"moduleLog.showLog\": \"Mostrar registro\",\n \"moduleMigration.docUri\": \"https://github.com/vrtmrz/obsidian-livesync/blob/main/README_ES.md#how-to-use\",\n \"moduleMigration.logBulkSendCorrupted\": \"El envío de fragmentos en bloque se ha habilitado, sin embargo, esta función se ha corrompido. Disculpe las molestias. Deshabilitado automáticamente.\",\n \"moduleMigration.logFetchRemoteTweakFailed\": \"Error al obtener los valores de ajuste remoto\",\n \"moduleMigration.logLocalDatabaseNotReady\": \"¡Algo salió mal! La base de datos local no está lista\",\n \"moduleMigration.logMigratedSameBehaviour\": \"Migrado a db:${current} con el mismo comportamiento que antes\",\n \"moduleMigration.logMigrationFailed\": \"La migración falló o se canceló de ${old} a ${current}\",\n \"moduleMigration.logRedflag2CreationFail\": \"Error al crear redflag2\",\n \"moduleMigration.logRemoteTweakUnavailable\": \"No se pudieron obtener los valores de ajuste remoto\",\n \"moduleMigration.logSetupCancelled\": \"La configuración ha sido cancelada, ¡Self-hosted LiveSync está esperando tu configuración!\",\n \"moduleMigration.msgFetchRemoteAgain\": \"Como ya sabrás, Self-hosted LiveSync ha cambiado su comportamiento predeterminado y la estructura de la base de datos.\\n\\nAfortunadamente, con tu tiempo y esfuerzo, la base de datos remota parece haber sido ya migrada. ¡Felicidades!\\n\\nSin embargo, necesitamos un poco más. La configuración de este dispositivo no es compatible con la base de datos remota. Necesitaremos volver a obtener la base de datos remota. ¿Debemos obtenerla nuevamente ahora?\\n\\n___Nota: No podemos sincronizar hasta que la configuración haya sido cambiada y la base de datos haya sido obtenida nuevamente.___\\n___Nota2: Los fragmentos son completamente inmutables, solo podemos obtener los metadatos y diferencias.___\",\n \"moduleMigration.msgInitialSetup\": \"Tu dispositivo **aún no ha sido configurado**. Permíteme guiarte a través del proceso de configuración.\\n\\nTen en cuenta que todo el contenido del diálogo se puede copiar al portapapeles. Si necesitas consultarlo más tarde, puedes pegarlo en una nota en Obsidian. También puedes traducirlo a tu idioma utilizando una herramienta de traducción.\\n\\nPrimero, ¿tienes **URI de configuración**?\\n\\nNota: Si no sabes qué es, consulta la [documentación](${URI_DOC}).\",\n \"moduleMigration.msgRecommendSetupUri\": \"Te recomendamos encarecidamente que generes una URI de configuración y la utilices.\\nSi no tienes conocimientos al respecto, consulta la [documentación](${URI_DOC}) (Lo siento de nuevo, pero es importante).\\n\\n¿Cómo quieres configurarlo manualmente?\",\n \"moduleMigration.msgSinceV02321\": \"Desde la versión v0.23.21, Self-hosted LiveSync ha cambiado el comportamiento predeterminado y la estructura de la base de datos. Se han realizado los siguientes cambios:\\n\\n1. **Sensibilidad a mayúsculas de los nombres de archivo**\\n El manejo de los nombres de archivo ahora no distingue entre mayúsculas y minúsculas. Este cambio es beneficioso para la mayoría de las plataformas, excepto Linux y iOS, que no gestionan efectivamente la sensibilidad a mayúsculas de los nombres de archivo.\\n (En estos, se mostrará una advertencia para archivos con el mismo nombre pero diferentes mayúsculas).\\n\\n2. **Manejo de revisiones de los fragmentos**\\n Los fragmentos son inmutables, lo que permite que sus revisiones sean fijas. Este cambio mejorará el rendimiento al guardar archivos.\\n\\n___Sin embargo, para habilitar cualquiera de estos cambios, es necesario reconstruir tanto las bases de datos remota como la local. Este proceso toma unos minutos, y recomendamos hacerlo cuando tengas tiempo suficiente.___\\n\\n- Si deseas mantener el comportamiento anterior, puedes omitir este proceso usando `${KEEP}`.\\n- Si no tienes suficiente tiempo, por favor elige `${DISMISS}`. Se te pedirá nuevamente más tarde.\\n- Si has reconstruido la base de datos en otro dispositivo, selecciona `${DISMISS}` e intenta sincronizar nuevamente. Dado que se ha detectado una diferencia, se te solicitará nuevamente.\",\n \"moduleMigration.optionAdjustRemote\": \"Ajustar al remoto\",\n \"moduleMigration.optionDecideLater\": \"Decidirlo más tarde\",\n \"moduleMigration.optionEnableBoth\": \"Habilitar ambos\",\n \"moduleMigration.optionEnableFilenameCaseInsensitive\": \"Habilitar solo #1\",\n \"moduleMigration.optionEnableFixedRevisionForChunks\": \"Habilitar solo #2\",\n \"moduleMigration.optionHaveSetupUri\": \"Sí, tengo\",\n \"moduleMigration.optionKeepPreviousBehaviour\": \"Mantener comportamiento anterior\",\n \"moduleMigration.optionManualSetup\": \"Configurarlo todo manualmente\",\n \"moduleMigration.optionNoAskAgain\": \"No, por favor pregúntame de nuevo\",\n \"moduleMigration.optionNoSetupUri\": \"No, no tengo\",\n \"moduleMigration.optionRemindNextLaunch\": \"Recordármelo en el próximo inicio\",\n \"moduleMigration.optionSetupWizard\": \"Llévame al asistente de configuración\",\n \"moduleMigration.optionYesFetchAgain\": \"Sí, obtener nuevamente\",\n \"moduleMigration.titleCaseSensitivity\": \"Sensibilidad a mayúsculas\",\n \"moduleMigration.titleRecommendSetupUri\": \"Recomendación de uso de URI de configuración\",\n \"moduleMigration.titleWelcome\": \"Bienvenido a Self-hosted LiveSync\",\n \"moduleObsidianMenu.replicate\": \"Replicar\",\n \"Move remotely deleted files to the trash, instead of deleting.\": \"Mover archivos borrados remotos a papelera en lugar de eliminarlos\",\n \"Not all messages have been translated. And, please revert to \\\"Default\\\" when reporting errors.\": \"No todos los mensajes están traducidos. Por favor, vuelva a \\\"Predeterminado\\\" al reportar errores.\",\n \"Notify all setting files\": \"Notificar todos los archivos de configuración\",\n \"Notify customized\": \"Notificar personalizaciones\",\n \"Notify when other device has newly customized.\": \"Notificar cuando otro dispositivo personalice\",\n \"Notify when the estimated remote storage size exceeds on start up\": \"Notificar cuando el tamaño estimado del almacenamiento remoto exceda al iniciar\",\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úmero de lotes a procesar. Default 40, mínimo 2. Controla documentos en memoria\",\n \"Number of changes to sync at a time. Defaults to 50. Minimum is 2.\": \"Número de cambios a sincronizar simultáneamente. Default 50, mínimo 2\",\n \"obsidianLiveSyncSettingTab.btnApply\": \"Aplicar\",\n \"obsidianLiveSyncSettingTab.btnCheck\": \"Verificar\",\n \"obsidianLiveSyncSettingTab.btnCopy\": \"Copiar\",\n \"obsidianLiveSyncSettingTab.btnDisable\": \"Desactivar\",\n \"obsidianLiveSyncSettingTab.btnDiscard\": \"Descartar\",\n \"obsidianLiveSyncSettingTab.btnEnable\": \"Activar\",\n \"obsidianLiveSyncSettingTab.btnFix\": \"Corregir\",\n \"obsidianLiveSyncSettingTab.btnGotItAndUpdated\": \"Lo entendí y actualicé.\",\n \"obsidianLiveSyncSettingTab.btnNext\": \"Siguiente\",\n \"obsidianLiveSyncSettingTab.btnStart\": \"Iniciar\",\n \"obsidianLiveSyncSettingTab.btnTest\": \"Probar\",\n \"obsidianLiveSyncSettingTab.btnUse\": \"Usar\",\n \"obsidianLiveSyncSettingTab.buttonFetch\": \"Obtener\",\n \"obsidianLiveSyncSettingTab.buttonNext\": \"Siguiente\",\n \"obsidianLiveSyncSettingTab.defaultLanguage\": \"Predeterminado\",\n \"obsidianLiveSyncSettingTab.descConnectSetupURI\": \"Este es el método recomendado para configurar Self-hosted LiveSync con una URI de configuración.\",\n \"obsidianLiveSyncSettingTab.descCopySetupURI\": \"¡Perfecto para configurar un nuevo dispositivo!\",\n \"obsidianLiveSyncSettingTab.descEnableLiveSync\": \"Solo habilita esto después de configurar cualquiera de las dos opciones anteriores o completar toda la configuración manualmente.\",\n \"obsidianLiveSyncSettingTab.descFetchConfigFromRemote\": \"Obtener las configuraciones necesarias del servidor remoto ya configurado.\",\n \"obsidianLiveSyncSettingTab.descManualSetup\": \"No recomendado, pero útil si no tienes una URI de configuración\",\n \"obsidianLiveSyncSettingTab.descTestDatabaseConnection\": \"Abrir conexión a la base de datos. Si no se encuentra la base de datos remota y tienes permiso para crear una base de datos, se creará la base de datos.\",\n \"obsidianLiveSyncSettingTab.descValidateDatabaseConfig\": \"Verifica y soluciona cualquier problema potencial con la configuración de la base de datos.\",\n \"obsidianLiveSyncSettingTab.errAccessForbidden\": \"Acceso prohibido.\",\n \"obsidianLiveSyncSettingTab.errCannotContinueTest\": \"No se pudo continuar con la prueba.\",\n \"obsidianLiveSyncSettingTab.errCorsCredentials\": \"❗ cors.credentials es incorrecto\",\n \"obsidianLiveSyncSettingTab.errCorsNotAllowingCredentials\": \"CORS no permite credenciales\",\n \"obsidianLiveSyncSettingTab.errCorsOrigins\": \"❗ cors.origins es incorrecto\",\n \"obsidianLiveSyncSettingTab.errEnableCors\": \"❗ httpd.enable_cors es incorrecto\",\n \"obsidianLiveSyncSettingTab.errMaxDocumentSize\": \"❗ couchdb.max_document_size es bajo)\",\n \"obsidianLiveSyncSettingTab.errMaxRequestSize\": \"❗ chttpd.max_http_request_size es bajo)\",\n \"obsidianLiveSyncSettingTab.errMissingWwwAuth\": \"❗ httpd.WWW-Authenticate falta\",\n \"obsidianLiveSyncSettingTab.errRequireValidUser\": \"❗ chttpd.require_valid_user es incorrecto.\",\n \"obsidianLiveSyncSettingTab.errRequireValidUserAuth\": \"❗ chttpd_auth.require_valid_user es incorrecto.\",\n \"obsidianLiveSyncSettingTab.labelDisabled\": \"⏹️ : Desactivado\",\n \"obsidianLiveSyncSettingTab.labelEnabled\": \"🔁 : Activado\",\n \"obsidianLiveSyncSettingTab.levelAdvanced\": \" (avanzado)\",\n \"obsidianLiveSyncSettingTab.levelEdgeCase\": \" (excepción)\",\n \"obsidianLiveSyncSettingTab.levelPowerUser\": \" (experto)\",\n \"obsidianLiveSyncSettingTab.linkOpenInBrowser\": \"Abrir en el navegador\",\n \"obsidianLiveSyncSettingTab.linkPageTop\": \"Ir arriba\",\n \"obsidianLiveSyncSettingTab.linkTipsAndTroubleshooting\": \"Consejos y solución de problemas\",\n \"obsidianLiveSyncSettingTab.linkTroubleshooting\": \"/docs/es/troubleshooting.md\",\n \"obsidianLiveSyncSettingTab.logCannotUseCloudant\": \"Esta función no se puede utilizar con IBM Cloudant.\",\n \"obsidianLiveSyncSettingTab.logCheckingConfigDone\": \"Verificación de configuración completada\",\n \"obsidianLiveSyncSettingTab.logCheckingConfigFailed\": \"La verificación de configuración falló\",\n \"obsidianLiveSyncSettingTab.logCheckingDbConfig\": \"Verificando la configuración de la base de datos\",\n \"obsidianLiveSyncSettingTab.logCheckPassphraseFailed\": \"ERROR: Error al comprobar la frase de contraseña con el servidor remoto: \\n${db}.\",\n \"obsidianLiveSyncSettingTab.logConfiguredDisabled\": \"Modo de sincronización configurado: DESACTIVADO\",\n \"obsidianLiveSyncSettingTab.logConfiguredLiveSync\": \"Modo de sincronización configurado: Sincronización en Vivo\",\n \"obsidianLiveSyncSettingTab.logConfiguredPeriodic\": \"Modo de sincronización configurado: Periódico\",\n \"obsidianLiveSyncSettingTab.logCouchDbConfigFail\": \"Configuración de CouchDB: ${title} falló\",\n \"obsidianLiveSyncSettingTab.logCouchDbConfigSet\": \"Configuración de CouchDB: ${title} -> Establecer ${key} en ${value}\",\n \"obsidianLiveSyncSettingTab.logCouchDbConfigUpdated\": \"Configuración de CouchDB: ${title} actualizado correctamente\",\n \"obsidianLiveSyncSettingTab.logDatabaseConnected\": \"Base de datos conectada\",\n \"obsidianLiveSyncSettingTab.logEncryptionNoPassphrase\": \"No puedes habilitar el cifrado sin una frase de contraseña\",\n \"obsidianLiveSyncSettingTab.logEncryptionNoSupport\": \"Tu dispositivo no admite el cifrado.\",\n \"obsidianLiveSyncSettingTab.logErrorOccurred\": \"¡Ocurrió un error!\",\n \"obsidianLiveSyncSettingTab.logEstimatedSize\": \"Tamaño estimado: ${size}\",\n \"obsidianLiveSyncSettingTab.logPassphraseInvalid\": \"La frase de contraseña no es válida, por favor corrígela.\",\n \"obsidianLiveSyncSettingTab.logPassphraseNotCompatible\": \"ERROR: ¡La frase de contraseña no es compatible con el servidor remoto! ¡Por favor, revísala de nuevo!\",\n \"obsidianLiveSyncSettingTab.logRebuildNote\": \"La sincronización ha sido desactivada, obtén y vuelve a activar si lo deseas.\",\n \"obsidianLiveSyncSettingTab.logSelectAnyPreset\": \"Selecciona cualquier preestablecido.\",\n \"obsidianLiveSyncSettingTab.msgAreYouSureProceed\": \"¿Estás seguro de proceder?\",\n \"obsidianLiveSyncSettingTab.msgChangesNeedToBeApplied\": \"¡Los cambios deben aplicarse!\",\n \"obsidianLiveSyncSettingTab.msgConfigCheck\": \"--Verificación de configuración--\",\n \"obsidianLiveSyncSettingTab.msgConfigCheckFailed\": \"La verificación de configuración ha fallado. ¿Quieres continuar de todos modos?\",\n \"obsidianLiveSyncSettingTab.msgConnectionCheck\": \"--Verificación de conexión--\",\n \"obsidianLiveSyncSettingTab.msgConnectionProxyNote\": \"Si tienes problemas con la verificación de conexión (incluso después de verificar la configuración), por favor verifica la configuración de tu proxy reverso.\",\n \"obsidianLiveSyncSettingTab.msgCurrentOrigin\": \"Origen actual: {origin}\",\n \"obsidianLiveSyncSettingTab.msgDiscardConfirmation\": \"¿Realmente deseas descartar las configuraciones y bases de datos existentes?\",\n \"obsidianLiveSyncSettingTab.msgDone\": \"--Hecho--\",\n \"obsidianLiveSyncSettingTab.msgEnableCors\": \"Configurar httpd.enable_cors\",\n \"obsidianLiveSyncSettingTab.msgEnableEncryptionRecommendation\": \"Recomendamos habilitar el cifrado de extremo a extremo y la obfuscación de ruta. ¿Estás seguro de querer continuar sin cifrado?\",\n \"obsidianLiveSyncSettingTab.msgFetchConfigFromRemote\": \"¿Quieres obtener la configuración del servidor remoto?\",\n \"obsidianLiveSyncSettingTab.msgGenerateSetupURI\": \"¡Todo listo! ¿Quieres generar un URI de configuración para configurar otros dispositivos?\",\n \"obsidianLiveSyncSettingTab.msgIfConfigNotPersistent\": \"Si la configuración del servidor no es persistente (por ejemplo, ejecutándose en docker), los valores aquí pueden cambiar. Una vez que puedas conectarte, por favor actualiza las configuraciones en el local.ini del servidor.\",\n \"obsidianLiveSyncSettingTab.msgInvalidPassphrase\": \"Tu frase de contraseña de cifrado podría ser inválida. ¿Estás seguro de querer continuar?\",\n \"obsidianLiveSyncSettingTab.msgNewVersionNote\": \"¿Aquí debido a una notificación de actualización? Por favor, revise el historial de versiones. Si está satisfecho, haga clic en el botón. Una nueva actualización volverá a mostrar esto.\",\n \"obsidianLiveSyncSettingTab.msgNonHTTPSInfo\": \"Configurado como URI que no es HTTPS. Ten en cuenta que esto puede no funcionar en dispositivos móviles.\",\n \"obsidianLiveSyncSettingTab.msgNonHTTPSWarning\": \"No se puede conectar a URI que no sean HTTPS. Por favor, actualiza tu configuración y vuelve a intentarlo.\",\n \"obsidianLiveSyncSettingTab.msgNotice\": \"---Aviso---\",\n \"obsidianLiveSyncSettingTab.msgObjectStorageWarning\": \"ADVERTENCIA: Esta característica está en desarrollo, así que por favor ten en cuenta lo siguiente:\\n- Arquitectura de solo anexado. Se requiere una reconstrucción para reducir el almacenamiento.\\n- Un poco frágil.\\n- Al sincronizar por primera vez, todo el historial será transferido desde el remoto. Ten en cuenta los límites de datos y las velocidades lentas.\\n- Solo las diferencias se sincronizan en vivo.\\n\\nSi encuentras algún problema o tienes ideas sobre esta característica, por favor crea un issue en GitHub.\\nAprecio mucho tu gran dedicación.\",\n \"obsidianLiveSyncSettingTab.msgOriginCheck\": \"Verificación de origen: {org}\",\n \"obsidianLiveSyncSettingTab.msgRebuildRequired\": \"Es necesario reconstruir las bases de datos para aplicar los cambios. Por favor selecciona el método para aplicar los cambios.\\n\\n<details>\\n<summary>Legendas</summary>\\n\\n| Símbolo | Significado |\\n|: ------ :| ------- |\\n| ⇔ | Actualizado |\\n| ⇄ | Sincronizar para equilibrar |\\n| ⇐,⇒ | Transferir para sobrescribir |\\n| ⇠,⇢ | Transferir para sobrescribir desde otro lado |\\n\\n</details>\\n\\n## ${OPTION_REBUILD_BOTH}\\nA simple vista: 📄 ⇒¹ 💻 ⇒² 🛰️ ⇢ⁿ 💻 ⇄ⁿ⁺¹ 📄\\nReconstruir tanto la base de datos local como la remota utilizando los archivos existentes de este dispositivo.\\nEsto bloquea a otros dispositivos, y necesitan realizar la obtención.\\n## ${OPTION_FETCH}\\nA simple vista: 📄 ⇄² 💻 ⇐¹ 🛰️ ⇔ 💻 ⇔ 📄\\nInicializa la base de datos local y la reconstruye utilizando los datos obtenidos de la base de datos remota.\\nEste caso incluye el caso en el que has reconstruido la base de datos remota.\\n## ${OPTION_ONLY_SETTING}\\nAlmacena solo la configuración. **Precaución: esto puede provocar corrupción de datos**; generalmente es necesario reconstruir la base de datos.\",\n \"obsidianLiveSyncSettingTab.msgSelectAndApplyPreset\": \"Por favor, selecciona y aplica cualquier elemento preestablecido para completar el asistente.\",\n \"obsidianLiveSyncSettingTab.msgSetCorsCredentials\": \"Configurar cors.credentials\",\n \"obsidianLiveSyncSettingTab.msgSetCorsOrigins\": \"Configurar cors.origins\",\n \"obsidianLiveSyncSettingTab.msgSetMaxDocSize\": \"Configurar couchdb.max_document_size\",\n \"obsidianLiveSyncSettingTab.msgSetMaxRequestSize\": \"Configurar chttpd.max_http_request_size\",\n \"obsidianLiveSyncSettingTab.msgSetRequireValidUser\": \"Configurar chttpd.require_valid_user = true\",\n \"obsidianLiveSyncSettingTab.msgSetRequireValidUserAuth\": \"Configurar chttpd_auth.require_valid_user = true\",\n \"obsidianLiveSyncSettingTab.msgSettingModified\": \"La configuración \\\"${setting}\\\" fue modificada desde otro dispositivo. Haz clic {HERE} para recargar la configuración. Haz clic en otro lugar para ignorar los cambios.\",\n \"obsidianLiveSyncSettingTab.msgSettingsUnchangeableDuringSync\": \"Estas configuraciones no se pueden cambiar durante la sincronización. Por favor, deshabilita toda la sincronización en las \\\"Configuraciones de Sincronización\\\" para desbloquear.\",\n \"obsidianLiveSyncSettingTab.msgSetWwwAuth\": \"Configurar httpd.WWW-Authenticate\",\n \"obsidianLiveSyncSettingTab.nameApplySettings\": \"Aplicar configuraciones\",\n \"obsidianLiveSyncSettingTab.nameConnectSetupURI\": \"Conectar con URI de configuración\",\n \"obsidianLiveSyncSettingTab.nameCopySetupURI\": \"Copiar la configuración actual a una URI de configuración\",\n \"obsidianLiveSyncSettingTab.nameDisableHiddenFileSync\": \"Desactivar sincronización de archivos ocultos\",\n \"obsidianLiveSyncSettingTab.nameDiscardSettings\": \"Descartar configuraciones y bases de datos existentes\",\n \"obsidianLiveSyncSettingTab.nameEnableHiddenFileSync\": \"Activar sincronización de archivos ocultos\",\n \"obsidianLiveSyncSettingTab.nameEnableLiveSync\": \"Activar LiveSync\",\n \"obsidianLiveSyncSettingTab.nameHiddenFileSynchronization\": \"Sincronización de archivos ocultos\",\n \"obsidianLiveSyncSettingTab.nameManualSetup\": \"Configuración manual\",\n \"obsidianLiveSyncSettingTab.nameTestConnection\": \"Probar conexión\",\n \"obsidianLiveSyncSettingTab.nameTestDatabaseConnection\": \"Probar Conexión de Base de Datos\",\n \"obsidianLiveSyncSettingTab.nameValidateDatabaseConfig\": \"Validar Configuración de la Base de Datos\",\n \"obsidianLiveSyncSettingTab.okAdminPrivileges\": \"✔ Tienes privilegios de administrador.\",\n \"obsidianLiveSyncSettingTab.okCorsCredentials\": \"✔ cors.credentials está correcto.\",\n \"obsidianLiveSyncSettingTab.okCorsCredentialsForOrigin\": \"CORS credenciales OK\",\n \"obsidianLiveSyncSettingTab.okCorsOriginMatched\": \"✔ Origen de CORS correcto\",\n \"obsidianLiveSyncSettingTab.okCorsOrigins\": \"✔ cors.origins está correcto.\",\n \"obsidianLiveSyncSettingTab.okEnableCors\": \"✔ httpd.enable_cors está correcto.\",\n \"obsidianLiveSyncSettingTab.okMaxDocumentSize\": \"✔ couchdb.max_document_size está correcto.\",\n \"obsidianLiveSyncSettingTab.okMaxRequestSize\": \"✔ chttpd.max_http_request_size está correcto.\",\n \"obsidianLiveSyncSettingTab.okRequireValidUser\": \"✔ chttpd.require_valid_user está correcto.\",\n \"obsidianLiveSyncSettingTab.okRequireValidUserAuth\": \"✔ chttpd_auth.require_valid_user está correcto.\",\n \"obsidianLiveSyncSettingTab.okWwwAuth\": \"✔ httpd.WWW-Authenticate está correcto.\",\n \"obsidianLiveSyncSettingTab.optionApply\": \"Aplicar\",\n \"obsidianLiveSyncSettingTab.optionCancel\": \"Cancelar\",\n \"obsidianLiveSyncSettingTab.optionCouchDB\": \"CouchDB\",\n \"obsidianLiveSyncSettingTab.optionDisableAllAutomatic\": \"Desactivar lo automático\",\n \"obsidianLiveSyncSettingTab.optionFetchFromRemote\": \"Obtener del remoto\",\n \"obsidianLiveSyncSettingTab.optionHere\": \"AQUÍ\",\n \"obsidianLiveSyncSettingTab.optionLiveSync\": \"LiveSync\",\n \"obsidianLiveSyncSettingTab.optionMinioS3R2\": \"Minio,S3,R2\",\n \"obsidianLiveSyncSettingTab.optionOkReadEverything\": \"OK, he leído todo.\",\n \"obsidianLiveSyncSettingTab.optionOnEvents\": \"En eventos\",\n \"obsidianLiveSyncSettingTab.optionPeriodicAndEvents\": \"Periódico y en eventos\",\n \"obsidianLiveSyncSettingTab.optionPeriodicWithBatch\": \"Periódico con lote\",\n \"obsidianLiveSyncSettingTab.optionRebuildBoth\": \"Reconstructuir ambos desde este dispositivo\",\n \"obsidianLiveSyncSettingTab.optionSaveOnlySettings\": \"(Peligro) Guardar solo configuración\",\n \"obsidianLiveSyncSettingTab.panelChangeLog\": \"Registro de cambios\",\n \"obsidianLiveSyncSettingTab.panelGeneralSettings\": \"Configuraciones Generales\",\n \"obsidianLiveSyncSettingTab.panelPrivacyEncryption\": \"Privacidad y Cifrado\",\n \"obsidianLiveSyncSettingTab.panelRemoteConfiguration\": \"Configuración remota\",\n \"obsidianLiveSyncSettingTab.panelSetup\": \"Configuración\",\n \"obsidianLiveSyncSettingTab.titleAppearance\": \"Apariencia\",\n \"obsidianLiveSyncSettingTab.titleConflictResolution\": \"Resolución de conflictos\",\n \"obsidianLiveSyncSettingTab.titleCongratulations\": \"¡Felicidades!\",\n \"obsidianLiveSyncSettingTab.titleCouchDB\": \"CouchDB\",\n \"obsidianLiveSyncSettingTab.titleDeletionPropagation\": \"Propagación de eliminación\",\n \"obsidianLiveSyncSettingTab.titleEncryptionNotEnabled\": \"El cifrado no está habilitado\",\n \"obsidianLiveSyncSettingTab.titleEncryptionPassphraseInvalid\": \"La frase de contraseña de cifrado es inválida\",\n \"obsidianLiveSyncSettingTab.titleExtraFeatures\": \"Habilitar funciones extras y avanzadas\",\n \"obsidianLiveSyncSettingTab.titleFetchConfig\": \"Obtener configuración\",\n \"obsidianLiveSyncSettingTab.titleFetchConfigFromRemote\": \"Obtener configuración del servidor remoto\",\n \"obsidianLiveSyncSettingTab.titleFetchSettings\": \"Obtener configuraciones\",\n \"obsidianLiveSyncSettingTab.titleHiddenFiles\": \"Archivos ocultos\",\n \"obsidianLiveSyncSettingTab.titleLogging\": \"Registro\",\n \"obsidianLiveSyncSettingTab.titleMinioS3R2\": \"Minio,S3,R2\",\n \"obsidianLiveSyncSettingTab.titleNotification\": \"Notificación\",\n \"obsidianLiveSyncSettingTab.titleOnlineTips\": \"Consejos en línea\",\n \"obsidianLiveSyncSettingTab.titleQuickSetup\": \"Configuración rápida\",\n \"obsidianLiveSyncSettingTab.titleRebuildRequired\": \"Reconstrucción necesaria\",\n \"obsidianLiveSyncSettingTab.titleRemoteConfigCheckFailed\": \"La verificación de configuración remota falló\",\n \"obsidianLiveSyncSettingTab.titleRemoteServer\": \"Servidor remoto\",\n \"obsidianLiveSyncSettingTab.titleReset\": \"Reiniciar\",\n \"obsidianLiveSyncSettingTab.titleSetupOtherDevices\": \"Para configurar otros dispositivos\",\n \"obsidianLiveSyncSettingTab.titleSynchronizationMethod\": \"Método de sincronización\",\n \"obsidianLiveSyncSettingTab.titleSynchronizationPreset\": \"Preestablecimiento de sincronización\",\n \"obsidianLiveSyncSettingTab.titleSyncSettings\": \"Configuraciones de Sincronización\",\n \"obsidianLiveSyncSettingTab.titleSyncSettingsViaMarkdown\": \"Configuración de sincronización a través de Markdown\",\n \"obsidianLiveSyncSettingTab.titleUpdateThinning\": \"Actualización de adelgazamiento\",\n \"obsidianLiveSyncSettingTab.warnCorsOriginUnmatched\": \"⚠ El origen de CORS no coincide: {from}->{to}\",\n \"obsidianLiveSyncSettingTab.warnNoAdmin\": \"⚠ No tienes privilegios de administrador.\",\n \"Passphrase\": \"Frase de contraseña\",\n \"Passphrase of sensitive configuration items\": \"Frase para elementos sensibles\",\n \"password\": \"contraseña\",\n \"Password\": \"Contraseña\",\n \"Path Obfuscation\": \"Ofuscación de rutas\",\n \"Per-file-saved customization sync\": \"Sincronización de personalización por archivo\",\n \"Periodic Sync interval\": \"Intervalo de sincronización periódica\",\n \"Presets\": \"Preconfiguraciones\",\n \"Process small files in the foreground\": \"Procesar archivos pequeños en primer plano\",\n \"Reducing the frequency with which on-disk changes are reflected into the DB\": \"Reducir frecuencia de actualizaciones de disco a BD\",\n \"Region\": \"Región\",\n \"Remote server type\": \"Tipo de servidor remoto\",\n \"Remote Type\": \"Tipo de remoto\",\n \"Requires restart of Obsidian\": \"Requiere reiniciar Obsidian\",\n \"Requires restart of Obsidian.\": \"Requiere reiniciar Obsidian\",\n \"Save settings to a markdown file. You will be notified when new settings arrive. You can set different files by the platform.\": \"Guardar configuración en archivo markdown. Se notificarán nuevos ajustes. Puede definir diferentes archivos por plataforma\",\n \"Saving will be performed forcefully after this number of seconds.\": \"Guardado forzado tras esta cantidad de segundos\",\n \"Scan changes on customization sync\": \"Escanear cambios en sincronización de personalización\",\n \"Scan customization automatically\": \"Escanear personalización automáticamente\",\n \"Scan customization before replicating.\": \"Escanear personalización antes de replicar\",\n \"Scan customization every 1 minute.\": \"Escanear personalización cada 1 minuto\",\n \"Scan customization periodically\": \"Escanear personalización periódicamente\",\n \"Scan for hidden files before replication\": \"Escanear archivos ocultos antes de replicar\",\n \"Scan hidden files periodically\": \"Escanear archivos ocultos periódicamente\",\n \"Seconds, 0 to disable\": \"Segundos, 0 para desactivar\",\n \"Seconds. Saving to the local database will be delayed until this value after we stop typing or saving.\": \"Segundos. Guardado en BD local se retrasará hasta este valor tras dejar de escribir/guardar\",\n \"Secret Key\": \"Clave secreta\",\n \"Server URI\": \"URI del servidor\",\n \"Should we keep folders that don't have any files inside?\": \"¿Mantener carpetas vacías?\",\n \"Should we only check for conflicts when a file is opened?\": \"¿Solo comprobar conflictos al abrir archivo?\",\n \"Should we prompt you about conflicting files when a file is opened?\": \"¿Notificar sobre conflictos al abrir archivo?\",\n \"Should we prompt you for every single merge, even if we can safely merge automatcially?\": \"¿Preguntar en cada fusión aunque sea automática?\",\n \"Show only notifications\": \"Mostrar solo notificaciones\",\n \"Show status as icons only\": \"Mostrar estado solo con íconos\",\n \"Show status inside the editor\": \"Mostrar estado dentro del editor\",\n \"Show status on the status bar\": \"Mostrar estado en la barra de estado\",\n \"Show verbose log. Please enable if you report an issue.\": \"Mostrar registro detallado. Actívelo si reporta un problema.\",\n \"Starts synchronisation when a file is saved.\": \"Inicia sincronización al guardar un archivo\",\n \"Stop reflecting database changes to storage files.\": \"Dejar de reflejar cambios de BD en archivos\",\n \"Stop watching for file changes.\": \"Dejar de monitorear cambios en archivos\",\n \"Suppress notification of hidden files change\": \"Suprimir notificaciones de cambios en archivos ocultos\",\n \"Suspend database reflecting\": \"Suspender reflejo de base de datos\",\n \"Suspend file watching\": \"Suspender monitorización de archivos\",\n \"Sync after merging file\": \"Sincronizar tras fusionar archivo\",\n \"Sync automatically after merging files\": \"Sincronizar automáticamente tras fusionar archivos\",\n \"Sync Mode\": \"Modo de sincronización\",\n \"Sync on Editor Save\": \"Sincronizar al guardar en editor\",\n \"Sync on File Open\": \"Sincronizar al abrir archivo\",\n \"Sync on Save\": \"Sincronizar al guardar\",\n \"Sync on Startup\": \"Sincronizar al iniciar\",\n \"Testing only - Resolve file conflicts by syncing newer copies of the file, this can overwrite modified files. Be Warned.\": \"Solo pruebas - Resolver conflictos sincronizando copias nuevas (puede sobrescribir modificaciones)\",\n \"The delay for consecutive on-demand fetches\": \"Retraso entre obtenciones consecutivas\",\n \"The Hash algorithm for chunk IDs\": \"Algoritmo hash para IDs de chunks\",\n \"The maximum duration for which chunks can be incubated within the document. Chunks exceeding this period will graduate to independent chunks.\": \"Duración máxima para incubar chunks. Excedentes se independizan\",\n \"The maximum number of chunks that can be incubated within the document. Chunks exceeding this number will immediately graduate to independent chunks.\": \"Número máximo de chunks que pueden incubarse en el documento. Excedentes se independizan\",\n \"The maximum total size of chunks that can be incubated within the document. Chunks exceeding this size will immediately graduate to independent chunks.\": \"Tamaño total máximo de chunks incubados. Excedentes se independizan\",\n \"This passphrase will not be copied to another device. It will be set to `Default` until you configure it again.\": \"Esta frase no se copia a otros dispositivos. Usará `Default` hasta reconfigurar\",\n \"Unique name between all synchronized devices. To edit this setting, please disable customization sync once.\": \"Nombre único entre dispositivos sincronizados. Para editarlo, desactive sincronización de personalización\",\n \"Use Custom HTTP Handler\": \"Usar manejador HTTP personalizado\",\n \"Use dynamic iteration count\": \"Usar conteo de iteraciones dinámico\",\n \"Use Segmented-splitter\": \"Usar divisor segmentado\",\n \"Use splitting-limit-capped chunk splitter\": \"Usar divisor de chunks con límite\",\n \"Use the trash bin\": \"Usar papelera\",\n \"Use timeouts instead of heartbeats\": \"Usar timeouts en lugar de latidos\",\n \"username\": \"nombre de usuario\",\n \"Username\": \"Usuario\",\n \"Verbose Log\": \"Registro detallado\",\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.\": \"¡Advertencia! Impacta rendimiento. Los logs no se sincronizan con nombre predeterminado. Contienen información confidencial\",\n \"When you save a file in the editor, start a sync automatically\": \"Iniciar sincronización automática al guardar en editor\",\n \"Write credentials in the file\": \"Escribir credenciales en archivo\",\n \"Write logs into the file\": \"Escribir logs en archivo\"\n}\n","import es from \"../messagesJson/es.json\";\nexport const PartialMessages = {\n es,\n} as const;\n","{\n \"(BETA) Always overwrite with a newer file\": \"(ベータ機能) 常に新しいファイルで上書きする\",\n \"(Beta) Use ignore files\": \"(ベータ機能) 除外ファイル(ignore)の使用\",\n \"(Days passed, 0 to disable automatic-deletion)\": \"(経過日数、0で自動削除を無効化)\",\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.\": \"(例: チャンクをオンラインで読む) このオプションを有効にすると、LiveSyncはチャンクをローカルに複製せず、直接オンラインで読み込みます。カスタムチャンクサイズを増やすことをお勧めします。\",\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.\": \"(MB) この値を設定すると、これより大きいサイズのローカルファイルやリモートファイルの変更はスキップされます。ファイルが再び小さくなった場合は、新しいものが使用されます。\",\n \"(Mega chars)\": \"(メガ文字)\",\n \"(Not recommended) If set, credentials will be stored in the file.\": \"(非推奨) 設定した場合、認証情報がファイルに保存されます。\",\n \"(Obsolete) Use an old adapter for compatibility\": \"(廃止済み)古いアダプターを互換性のために利用\",\n \"Access Key\": \"アクセスキー\",\n \"Always prompt merge conflicts\": \"常に競合は手動で解決する\",\n \"Apply Latest Change if Conflicting\": \"競合がある場合は最新の変更を適用する\",\n \"Apply preset configuration\": \"プリセットを適用する\",\n \"Automatically Sync all files when opening Obsidian.\": \"Obsidian起動時にすべてのファイルを自動同期します。\",\n \"Batch database update\": \"データベースのバッチ更新\",\n \"Batch limit\": \"バッチの上限\",\n \"Batch size\": \"バッチ容量\",\n \"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.\": \"v0.17.6までは古いアダプターをローカル用のデータベースに使用していましたが、現在は新しいアダプターを推奨しています。しかし、新しいアダプターに変更するにはローカルデータベースの再構築が必要です。有効のままにしておくと、リモートデータベースからフェッチする場合に、この設定を無効にするかの質問が表示されます。\",\n \"Bucket Name\": \"バケット名\",\n \"cmdConfigSync.showCustomizationSync\": \"カスタマイズ同期を表示\",\n \"Comma separated `.gitignore, .dockerignore`\": \"カンマ区切り `.gitignore, .dockerignore`\",\n \"Compute revisions for chunks\": \"チャンクの修正(リビジョン)を計算\",\n \"Data Compression\": \"データ圧縮\",\n \"Database Name\": \"データベース名\",\n \"Database suffix\": \"データベースの接尾辞(suffix)\",\n \"Delay conflict resolution of inactive files\": \"非アクティブなファイルは、競合解決を先送りする\",\n \"Delay merge conflict prompt for inactive files.\": \"非アクティブなファイルの競合解決のプロンプトの表示を遅延させる\",\n \"Delete old metadata of deleted files on start-up\": \"削除済みデータのメタデータをクリーンナップする\",\n \"Device name\": \"デバイス名\",\n \"dialog.yourLanguageAvailable\": \"Self-hosted LiveSync に設定されている言語の翻訳がありましたので、%{Display Language}が適用されました。\\n\\n注意: 全てのメッセージは翻訳されていません。あなたの貢献をお待ちしています!\\nGithubにIssueを作成する際には、 %{Display Language} を一旦 %{lang-def} に戻してから、スクショやメッセージ、ログを収集してください。これは設定から変更できます。\\n\\n便利に使用できれば幸いです。\",\n \"dialog.yourLanguageAvailable.btnRevertToDefault\": \"Keep %{lang-def}\",\n \"dialog.yourLanguageAvailable.Title\": \"翻訳が利用可能です!\",\n \"Disables logging, only shows notifications. Please disable if you report an issue.\": \"ログを無効にし、通知のみを表示します。Issueを報告する場合は無効にしてください。\",\n \"Display Language\": \"インターフェースの表示言語\",\n \"Do not check configuration mismatch before replication\": \"サーバーから同期する前に設定の不一致を確認しない\",\n \"Do not keep metadata of deleted files.\": \"削除済みファイルのメタデータを保持しない\",\n \"Do not split chunks in the background\": \"バックグラウンドでチャンクを分割しない\",\n \"Do not use internal API\": \"内部APIを使用しない\",\n \"Doctor.Button.DismissThisVersion\": \"いいえ、次のリリースまで再度確認しない\",\n \"Doctor.Button.Fix\": \"修正する\",\n \"Doctor.Button.FixButNoRebuild\": \"修正するが再構築はしない\",\n \"Doctor.Button.No\": \"いいえ\",\n \"Doctor.Button.Skip\": \"そのままにする\",\n \"Doctor.Button.Yes\": \"はい\",\n \"Doctor.Dialogue.Main\": \"こんにちは!${activateReason}のため、設定診断ツールが起動しました!\\n残念ながら、いくつかの設定が潜在的な問題として検出されました。\\nご安心ください。一つずつ解決していきましょう。\\n\\n事前にお知らせしますと、以下の項目についてお尋ねします。\\n\\n${issues}\\n\\n始めていいですか?\",\n \"Doctor.Dialogue.MainFix\": \"\\n## ${name}\\n\\n| 現在の値 | 理想値 |\\n|:---:|:---:|\\n| ${current} | ${ideal} |\\n\\n**推奨レベル:** ${level}\\n\\n### 診断理由?\\n\\n${reason}\\n\\n${note}\\n\\nこれを理想値に修正しますか?\",\n \"Doctor.Dialogue.Title\": \"Self-hosted LiveSync 設定診断ツール\",\n \"Doctor.Dialogue.TitleAlmostDone\": \"あと少しです!\",\n \"Doctor.Dialogue.TitleFix\": \"問題の修正 ${current}/${total}\",\n \"Doctor.Level.Must\": \"必須\",\n \"Doctor.Level.Necessary\": \"必要\",\n \"Doctor.Level.Optional\": \"任意\",\n \"Doctor.Level.Recommended\": \"推奨\",\n \"Doctor.Message.NoIssues\": \"問題は検出されませんでした!\",\n \"Doctor.Message.RebuildLocalRequired\": \"注意!これを適用するにはローカルデータベースの再構築が必要です!\",\n \"Doctor.Message.RebuildRequired\": \"注意!これを適用するには再構築が必要です!\",\n \"Doctor.Message.SomeSkipped\": \"いくつかの問題をそのままにしました。次回起動時に再度確認しますか?\",\n \"Doctor.RULES.E2EE_V02500.REASON\": \"エンドツーエンド暗号化がより堅牢で高速になりました。また、以前のE2EEは再コードレビューにより脆弱性が発見されました。できるだけ早く適用することをお勧めします。ご不便をおかけして申し訳ありません。また、この設定は下位互換性がありません。すべての同期デバイスをv0.25.0以降にアップデートする必要があります。再構築は必須ではなく、新しい転送から新しいフォーマットに変換されますが、可能な限り再構築をお勧めします。\",\n \"Enable advanced features\": \"高度な機能を有効にする\",\n \"Enable customization sync\": \"カスタマイズ同期を有効\",\n \"Enable Developers' Debug Tools.\": \"開発者用デバッグツールを有効にする\",\n \"Enable edge case treatment features\": \"エッジケース対応機能を有効にする\",\n \"Enable poweruser features\": \"エキスパート機能を有効にする\",\n \"Enable this if your Object Storage doesn't support CORS\": \"オブジェクトストレージがCORSをサポートしていない場合は有効にしてください\",\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 \"Encrypting sensitive configuration items\": \"機密性の高い設定項目の暗号化\",\n \"Encryption phassphrase. If changed, you should overwrite the server's database with the new (encrypted) files.\": \"暗号化パスフレーズ。変更した場合、新しい(暗号化された)ファイルでサーバーのデータベースを上書きする必要があります。\",\n \"End-to-End Encryption\": \"E2E暗号化\",\n \"Endpoint URL\": \"エンドポイントURL\",\n \"Enhance chunk size\": \"チャンクサイズを最適化する\",\n \"Fetch chunks on demand\": \"ユーザーのタイミングでチャンクの更新を確認する\",\n \"Fetch database with previous behaviour\": \"以前の動作でデータベースを取得\",\n \"Filename\": \"ファイル名\",\n \"Forces the file to be synced when opened.\": \"ファイルを開いたときに強制的に同期します。\",\n \"Handle files as Case-Sensitive\": \"ファイルの大文字・小文字を区別する\",\n \"If disabled(toggled), chunks will be split on the UI thread (Previous behaviour).\": \"無効(トグル)にすると、チャンクはUIスレッドで分割されます(以前の動作)。\",\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.\": \"有効にすると、ファイルごとの効率的なカスタマイズ同期が使用されます。有効化時に小規模な移行が必要です。また、すべてのデバイスをv0.23.18にアップデートする必要があります。一度有効にすると、古いバージョンとの互換性がなくなります。\",\n \"If enabled, chunks will be split into no more than 100 items. However, dedupe is slightly weaker.\": \"有効にすると、チャンクは最大100項目に分割されます。ただし、重複除去の精度は落ちます。\",\n \"If enabled, newly created chunks are temporarily kept within the document, and graduated to become independent chunks once stabilised.\": \"有効にすると、新しく作成されたチャンクはドキュメント内に一時的に保持され、安定したら独立したチャンクになります。\",\n \"If enabled, the file under 1kb will be processed in the UI thread.\": \"有効にすると、1kb未満のファイルはUIスレッドで処理されます。\",\n \"If enabled, the notification of hidden files change will be suppressed.\": \"有効にすると、隠しファイルの変更通知が抑制されます。\",\n \"If this enabled, all chunks will be stored with the revision made from its content. (Previous behaviour)\": \"有効にすると、すべてのチャンクはコンテンツから作成されたリビジョンと共に保存されます(以前の動作)。\",\n \"If this enabled, All files are handled as case-Sensitive (Previous behaviour).\": \"有効にすると、すべてのファイルは大文字小文字を区別して処理されます(以前の動作)。\",\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 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.\": \"このオプションを有効にすると、PouchDBは接続を60秒間保持し、その間に通信がない場合、一度接続を閉じて再接続します。接続を無期限に保持する代わりにこの動作を行います。プロキシ(Cloudflareなど)がリクエストの持続時間を制限している場合に有用ですが、リソース使用量が増加する可能性があります。\",\n \"Ignore files\": \"除外ファイル\",\n \"Incubate Chunks in Document\": \"ドキュメント内でチャンクを一時保管する\",\n \"Interval (sec)\": \"秒\",\n \"K.exp\": \"試験機能\",\n \"K.long_p2p_sync\": \"%{title_p2p_sync} (%{exp})\",\n \"K.P2P\": \"%{Peer}-to-%{Peer}\",\n \"K.Peer\": \"Peer\",\n \"K.ScanCustomization\": \"Scan customization\",\n \"K.short_p2p_sync\": \"P2P Sync (%{exp})\",\n \"K.title_p2p_sync\": \"Peer-to-Peer Sync\",\n \"Keep empty folder\": \"空フォルダの維持\",\n \"lang_def\": \"Default\",\n \"lang-de\": \"Deutsche\",\n \"lang-def\": \"%{lang_def}\",\n \"lang-es\": \"Español\",\n \"lang-ja\": \"日本語\",\n \"lang-ko\": \"한국어\",\n \"lang-ru\": \"Русский\",\n \"lang-zh\": \"简体中文\",\n \"lang-zh-tw\": \"繁體中文\",\n \"LiveSync could not handle multiple vaults which have same name without different prefix, This should be automatically configured.\": \"LiveSyncは、接頭辞(プレフィックス)のない同名の保管庫(Vault)を扱うことができません。これは自動的に設定されます。\",\n \"liveSyncReplicator.beforeLiveSync\": \"LiveSyncの前に、まずOneShotを開始します...\",\n \"liveSyncReplicator.cantReplicateLowerValue\": \"これ以上低い値ではレプリケーション(複製)できません。\",\n \"liveSyncReplicator.checkingLastSyncPoint\": \"最後に同期したポイントを探しています。\",\n \"liveSyncReplicator.couldNotConnectTo\": \"${uri} : ${name}に接続できませんでした\\n(${db})\",\n \"liveSyncReplicator.couldNotConnectToRemoteDb\": \"リモートデータベースに接続できませんでした: ${d}\",\n \"liveSyncReplicator.couldNotConnectToServer\": \"サーバーに接続できませんでした。\",\n \"liveSyncReplicator.couldNotConnectToURI\": \"${uri}に接続できませんでした: ${dbRet}\",\n \"liveSyncReplicator.couldNotMarkResolveRemoteDb\": \"リモートデータベースを解決済みとしてマークできませんでした。\",\n \"liveSyncReplicator.liveSyncBegin\": \"LiveSyncを開始...\",\n \"liveSyncReplicator.lockRemoteDb\": \"データ破損を防ぐためリモートデータベースをロック\",\n \"liveSyncReplicator.markDeviceResolved\": \"このデバイスを『解決済み』としてマーク。\",\n \"liveSyncReplicator.oneShotSyncBegin\": \"OneShot同期を開始... (${syncMode})\",\n \"liveSyncReplicator.remoteDbCorrupted\": \"リモートデータベースが新しいか破損しています。self-hosted-livesyncの最新バージョンがインストールされていることを確認してください\",\n \"liveSyncReplicator.remoteDbCreatedOrConnected\": \"リモートデータベースが作成または接続されました\",\n \"liveSyncReplicator.remoteDbDestroyed\": \"リモートデータベースが削除されました\",\n \"liveSyncReplicator.remoteDbDestroyError\": \"リモートデータベースの削除中に問題が発生しました:\",\n \"liveSyncReplicator.remoteDbMarkedResolved\": \"リモートデータベースが解決済みとしてマークされました。\",\n \"liveSyncReplicator.replicationClosed\": \"レプリケーション(複製)が終了しました\",\n \"liveSyncReplicator.replicationInProgress\": \"レプリケーション(複製)は既に進行中です\",\n \"liveSyncReplicator.retryLowerBatchSize\": \"より小さいバッチサイズで再試行: ${batch_size}/${batches_limit}\",\n \"liveSyncReplicator.unlockRemoteDb\": \"データ破損を防ぐためリモートデータベースをアンロック\",\n \"liveSyncSetting.errorNoSuchSettingItem\": \"その設定項目は存在しません: ${key}\",\n \"liveSyncSetting.originalValue\": \"元の値: ${value}\",\n \"liveSyncSetting.valueShouldBeInRange\": \"値は ${min} < 値 < ${max} の範囲である必要があります\",\n \"liveSyncSettings.btnApply\": \"適用\",\n \"logPane.autoScroll\": \"自動スクロール\",\n \"logPane.logWindowOpened\": \"ログウィンドウが開かれました\",\n \"logPane.pause\": \"一時停止\",\n \"logPane.title\": \"Self-hosted LiveSync ログ\",\n \"logPane.wrap\": \"折り返し\",\n \"Maximum delay for batch database updating\": \"バッチデータベース更新の最大遅延\",\n \"Maximum file size\": \"最大ファイル容量\",\n \"Maximum Incubating Chunk Size\": \"保持するチャンクの最大サイズ\",\n \"Maximum Incubating Chunks\": \"一時保管する最大チャンク数\",\n \"Maximum Incubation Period\": \"最大保持期限\",\n \"MB (0 to disable).\": \"MB (0で無効化)。\",\n \"Memory cache size (by total characters)\": \"全体でキャッシュする文字数\",\n \"Memory cache size (by total items)\": \"全体のキャッシュサイズ\",\n \"Minimum delay for batch database updating\": \"バッチデータベース更新の最小遅延\",\n \"moduleCheckRemoteSize.logCheckingStorageSizes\": \"ストレージサイズを確認中\",\n \"moduleCheckRemoteSize.logCurrentStorageSize\": \"リモートストレージサイズ: ${measuredSize}\",\n \"moduleCheckRemoteSize.logExceededWarning\": \"リモートストレージサイズ: ${measuredSize} が ${notifySize} を超過しました\",\n \"moduleCheckRemoteSize.logThresholdEnlarged\": \"しきい値が ${size}MB に設定されました\",\n \"moduleCheckRemoteSize.msgConfirmRebuild\": \"これは少し時間がかかる場合があります。本当に今すべてを再構築しますか?\",\n \"moduleCheckRemoteSize.msgDatabaseGrowing\": \"**データベースが大きくなっています!** でも心配しないでください。リモートストレージの容量が不足する前に対応できます。\\n\\n| 測定サイズ | 設定サイズ |\\n| --- | --- |\\n| ${estimatedSize} | ${maxSize} |\\n\\n> [!MORE]-\\n> 長年使用している場合、参照されていないチャンク(つまりゴミ)がデータベースに蓄積している可能性があります。そのため、すべてを再構築することをお勧めします。おそらくかなり小さくなるでしょう。\\n>\\n> 単純に保管庫の容量が増えている場合は、事前にファイルを整理してからすべてを再構築するのが良いでしょう。Self-hosted LiveSyncは処理速度を上げるため、削除しても実際のデータを削除しません。これはおおまかに[documentation](https://github.com/vrtmrz/obsidian-livesync/blob/main/docs/tech_info.md)に記載されています。\\n>\\n> 増加を気にしない場合は、通知制限を100MB単位で増やすことができます。これは自分のサーバーで実行している場合に適しています。ただし、定期的にすべてを再構築する方が良いでしょう。\\n>\\n\\n> [!WARNING]\\n> すべてを再構築する場合は、すべてのデバイスが同期されていることを確認してください。もちろん、プラグインは可能な限り解決しようと努力はしますけど...\\n\",\n \"moduleCheckRemoteSize.msgSetDBCapacity\": \"リモートストレージの容量が不足する前に対策を講じるため、**最大データベース容量の警告**を設定できます。\\nこれを有効にしますか?\\n\\n> [!MORE]-\\n> - 0: ストレージサイズについて警告しない。\\n> 自宅サーバーなど、リモートストレージに十分な容量がある場合に推奨されます。ストレージサイズを確認し、手動で再構築できます。\\n> - 800: リモートストレージサイズが800MBを超えたら警告。\\n> 1GB制限のfly.ioやIBM Cloudantを使用している場合に推奨されます。\\n> - 2000: リモートストレージサイズが2GBを超えたら警告。\\n\\n制限に達した場合、段階的に制限を増やすよう求められます。\\n\",\n \"moduleCheckRemoteSize.option2GB\": \"2GB (標準)\",\n \"moduleCheckRemoteSize.option800MB\": \"800MB (Cloudant, fly.io)\",\n \"moduleCheckRemoteSize.optionAskMeLater\": \"後で確認する\",\n \"moduleCheckRemoteSize.optionDismiss\": \"無視\",\n \"moduleCheckRemoteSize.optionIncreaseLimit\": \"${newMax}MBに設定\",\n \"moduleCheckRemoteSize.optionNoWarn\": \"いいえ、警告しないでください\",\n \"moduleCheckRemoteSize.optionRebuildAll\": \"今すべてを再構築\",\n \"moduleCheckRemoteSize.titleDatabaseSizeLimitExceeded\": \"リモートストレージサイズが制限を超過しました\",\n \"moduleCheckRemoteSize.titleDatabaseSizeNotify\": \"データベースサイズ通知の設定\",\n \"moduleInputUIObsidian.defaultTitleConfirmation\": \"確認\",\n \"moduleInputUIObsidian.defaultTitleSelect\": \"選択\",\n \"moduleInputUIObsidian.optionNo\": \"いいえ\",\n \"moduleInputUIObsidian.optionYes\": \"はい\",\n \"moduleLiveSyncMain.logAdditionalSafetyScan\": \"追加の安全スキャン中...\",\n \"moduleLiveSyncMain.logLoadingPlugin\": \"プラグインをロード中...\",\n \"moduleLiveSyncMain.logPluginInitCancelled\": \"プラグインの初期化がモジュールによってキャンセルされました\",\n \"moduleLiveSyncMain.logPluginVersion\": \"Self-hosted LiveSync v${manifestVersion} ${packageVersion}\",\n \"moduleLiveSyncMain.logReadChangelog\": \"LiveSyncが更新されました。変更履歴をお読みください!\",\n \"moduleLiveSyncMain.logSafetyScanCompleted\": \"追加の安全スキャンが完了しました\",\n \"moduleLiveSyncMain.logSafetyScanFailed\": \"モジュールで追加の安全スキャンが失敗しました\",\n \"moduleLiveSyncMain.logUnloadingPlugin\": \"プラグインをアンロード中...\",\n \"moduleLiveSyncMain.logVersionUpdate\": \"LiveSyncが更新されました。互換性のない更新の場合、すべての自動同期が一時的に無効化されています。有効にする前に、すべてのデバイスが最新の状態であることを確認してください。\",\n \"moduleLiveSyncMain.msgScramEnabled\": \"Self-hosted LiveSyncは一部のイベントを無視するように設定されています。これは正しいですか?\\n\\n| タイプ | ステータス | メモ |\\n|:---:|:---:|---|\\n| ストレージイベント | ${fileWatchingStatus} | すべての変更が無視されます |\\n| データベースイベント | ${parseReplicationStatus} | すべての同期された変更が延期されます |\\n\\nこれらを再開してObsidianを再起動しますか?\\n\\n> [!DETAILS]-\\n> これらのフラグは、プラグインが再構築またはフェッチ中に設定されます。プロセスが異常終了した場合、意図せず保持されることがあります。\\n> 不明な場合は、これらのプロセスを再実行してみてください。必ず保管庫をバックアップしてください。\\n\",\n \"moduleLiveSyncMain.optionKeepLiveSyncDisabled\": \"LiveSyncを無効のままにする\",\n \"moduleLiveSyncMain.optionResumeAndRestart\": \"再開してObsidianを再起動\",\n \"moduleLiveSyncMain.titleScramEnabled\": \"緊急停止(Scram)が有効\",\n \"moduleLocalDatabase.logWaitingForReady\": \"しばらくお待ちください...\",\n \"moduleLog.showLog\": \"ログを表示\",\n \"moduleMigration.docUri\": \"https://github.com/vrtmrz/obsidian-livesync/blob/main/README.md#how-to-use\",\n \"moduleMigration.fix0256.buttons.checkItLater\": \"後で確認する\",\n \"moduleMigration.fix0256.buttons.DismissForever\": \"修正済み、今後確認しない\",\n \"moduleMigration.fix0256.buttons.fix\": \"修正\",\n \"moduleMigration.fix0256.message\": \"最近のバグ(v0.25.6)により、一部のファイルが同期データベースに正しく保存されていない可能性があります。\\nファイルをスキャンし、修正が必要なものが見つかりました。\\n\\n**修正準備ができたファイル:**\\n\\n${files}\\n\\nこれらのファイルはストレージ上の元ファイルとサイズが一致しており、復元可能です。\\n「修正」ボタンをクリックしてデータベースを修正できます。\\n\\n${messageUnrecoverable}\\n\\n再実行したい場合は、Hatchから実行できます。\\n\",\n \"moduleMigration.fix0256.messageUnrecoverable\": \"**このデバイスで修正できないファイル:**\\n\\n${filesNotRecoverable}\\n\\nこれらのファイルはメタデータに不整合があり、このデバイスでは修正できません(ほとんどの場合、どちらが正しいか判定できません)。\\n復元するには、他のデバイスで確認するか、バックアップから手動で復元してください。\\n\",\n \"moduleMigration.fix0256.title\": \"破損ファイルが検出されました\",\n \"moduleMigration.insecureChunkExist.buttons.fetch\": \"リモートを既に再構築した。リモートからフェッチ\",\n \"moduleMigration.insecureChunkExist.buttons.later\": \"後で行う\",\n \"moduleMigration.insecureChunkExist.buttons.rebuild\": \"すべてを再構築\",\n \"moduleMigration.insecureChunkExist.laterMessage\": \"できるだけ早く対処することを強くお勧めします!\",\n \"moduleMigration.insecureChunkExist.message\": \"一部のチャンクが安全に保存されておらず、データベースで暗号化されていません。\\n**この問題を修正するにはデータベースを再構築してください**。\\n\\nリモートデータベースがSSLで設定されていない、または安全性の低い認証情報を使用している場合、**機密データが漏洩するリスクがあります**。\\n\\n注意: すべてのデバイスでSelf-hosted LiveSync v0.25.6以降にアップグレードし、必ず保管庫をバックアップしてください。\\n注意2: すべてを再構築とフェッチは時間とトラフィックを消費します。オフピーク時間に安定したネットワークで実行してください。\\n\",\n \"moduleMigration.insecureChunkExist.title\": \"安全でないチャンクが見つかりました!\",\n \"moduleMigration.logBulkSendCorrupted\": \"チャンクの一括送信が有効にされていましたが、この機能に問題がありました。ご不便をおかけして申し訳ありません。自動的に無効化されました。\",\n \"moduleMigration.logFetchRemoteTweakFailed\": \"リモートの調整値の取得に失敗しました\",\n \"moduleMigration.logLocalDatabaseNotReady\": \"何か問題が発生しました!ローカルデータベースが準備できていません\",\n \"moduleMigration.logMigratedSameBehaviour\": \"以前と同じ動作でdb:${current}に移行しました\",\n \"moduleMigration.logMigrationFailed\": \"${old}から${current}への移行が失敗またはキャンセルされました\",\n \"moduleMigration.logRedflag2CreationFail\": \"redflag2の作成に失敗しました\",\n \"moduleMigration.logRemoteTweakUnavailable\": \"リモートの調整値を取得できませんでした\",\n \"moduleMigration.logSetupCancelled\": \"セットアップがキャンセルされました。Self-hosted LiveSyncはセットアップを待っています!\",\n \"moduleMigration.msgFetchRemoteAgain\": \"ご存知のとおり、self-hosted LiveSyncはデフォルトの動作とデータベース構造を変更しました。\\n\\nご協力のおかげで、リモートデータベースはすでに移行されているようです。おめでとうございます!\\n\\nしかし、もう少し必要です。このデバイスの設定はリモートデータベースと互換性がありません。リモートデータベースを再度フェッチする必要があります。今すぐリモートから再フェッチしますか?\\n\\n___注意: 設定が変更され、データベースが再フェッチされるまで同期できません。___\\n___注意2: チャンクは完全に不変なので、メタデータと差分のみフェッチできます。___\",\n \"moduleMigration.msgInitialSetup\": \"このデバイスは**まだセットアップされていません**。セットアッププロセスをご案内します。\\n\\nすべてのダイアログの内容はクリップボードにコピーできます。後で参照する必要があれば、Obsidianのノートに貼り付けてください。翻訳ツールを使ってお使いの言語に翻訳することもできます。\\n\\nまず、**セットアップURI**をお持ちですか?\\n\\n注意: それが何か分からない場合は、[documentation](${URI_DOC})を参照してください。\",\n \"moduleMigration.msgRecommendSetupUri\": \"セットアップURIを生成して使用することを強くお勧めします。\\nこれについて知識がない場合は、[documentation](${URI_DOC})を参照してください(重要です)。\\n\\n手動でセットアップしますか?\",\n \"moduleMigration.msgSinceV02321\": \"v0.23.21以降、self-hosted LiveSyncはデフォルトの動作とデータベース構造を変更しました。以下の変更が行われました:\\n\\n1. **ファイル名の大文字小文字の区別**\\n ファイル名の処理が大文字小文字を区別しなくなりました。これは、ファイル名の大文字小文字を効果的に管理しないLinuxとiOS以外のほとんどのプラットフォームにとって有益な変更です。\\n (これらの環境では、同じ名前で大文字小文字が異なるファイルに対して警告が表示されます)。\\n\\n2. **チャンクのリビジョン処理**\\n チャンクは不変であり、リビジョンを固定できます。この変更により、ファイル保存のパフォーマンスが向上します。\\n\\n___しかし、これらの変更を有効にするには、リモートとローカルの両方のデータベースを再構築する必要があります。このプロセスは数分かかります。時間に余裕があるときに行うことをお勧めします。___\\n\\n- 以前の動作を維持したい場合は、`${KEEP}`を使用してこのプロセスをスキップできます。\\n- 時間がない場合は、`${DISMISS}`を選択してください。後で再度確認されます。\\n- 別のデバイスでデータベースを再構築した場合は、`${DISMISS}`を選択して再度同期してみてください。差異が検出されたため、再度確認されます。\",\n \"moduleMigration.optionAdjustRemote\": \"リモートに合わせる\",\n \"moduleMigration.optionDecideLater\": \"後で決める\",\n \"moduleMigration.optionEnableBoth\": \"両方を有効にする\",\n \"moduleMigration.optionEnableFilenameCaseInsensitive\": \"#1のみ有効にする\",\n \"moduleMigration.optionEnableFixedRevisionForChunks\": \"#2のみ有効にする\",\n \"moduleMigration.optionHaveSetupUri\": \"はい、持っています\",\n \"moduleMigration.optionKeepPreviousBehaviour\": \"以前の動作を維持\",\n \"moduleMigration.optionManualSetup\": \"すべて手動でセットアップ\",\n \"moduleMigration.optionNoAskAgain\": \"いいえ、後で確認する\",\n \"moduleMigration.optionNoSetupUri\": \"いいえ、持っていません\",\n \"moduleMigration.optionRemindNextLaunch\": \"次回起動時にリマインド\",\n \"moduleMigration.optionSetupViaP2P\": \"%{short_p2p_sync}を使ってセットアップ\",\n \"moduleMigration.optionSetupWizard\": \"セットアップウィザードへ\",\n \"moduleMigration.optionYesFetchAgain\": \"はい、再フェッチする\",\n \"moduleMigration.titleCaseSensitivity\": \"大文字小文字の区別\",\n \"moduleMigration.titleRecommendSetupUri\": \"セットアップURIの使用を推奨\",\n \"moduleMigration.titleWelcome\": \"Self-hosted LiveSyncへようこそ\",\n \"moduleObsidianMenu.replicate\": \"レプリケート\",\n \"Move remotely deleted files to the trash, instead of deleting.\": \"リモートで削除されたファイルを削除せずにゴミ箱に移動する。\",\n \"Not all messages have been translated. And, please revert to \\\"Default\\\" when reporting errors.\": \"すべてのメッセージが翻訳されているわけではありません。また、Issue報告の際にはいったん\\\"Default\\\"に戻してください\",\n \"Notify all setting files\": \"すべての設定を通知\",\n \"Notify customized\": \"カスタマイズが行われたら通知する\",\n \"Notify when other device has newly customized.\": \"別の端末がカスタマイズを行なったら通知する\",\n \"Notify when the estimated remote storage size exceeds on start up\": \"起動時に予想リモートストレージサイズを超えたら通知\",\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.\": \"1度に処理するバッチの数。デフォルトは40、最小は2。この数値は、どれだけの容量の書類がメモリに保存されるかも定義します。\",\n \"Number of changes to sync at a time. Defaults to 50. Minimum is 2.\": \"一度に同期する変更の数。デフォルトは50、最小は2。\",\n \"obsidianLiveSyncSettingTab.btnApply\": \"適用\",\n \"obsidianLiveSyncSettingTab.btnCheck\": \"確認\",\n \"obsidianLiveSyncSettingTab.btnCopy\": \"コピー\",\n \"obsidianLiveSyncSettingTab.btnDisable\": \"無効化\",\n \"obsidianLiveSyncSettingTab.btnDiscard\": \"破棄\",\n \"obsidianLiveSyncSettingTab.btnEnable\": \"有効化\",\n \"obsidianLiveSyncSettingTab.btnFix\": \"修正\",\n \"obsidianLiveSyncSettingTab.btnGotItAndUpdated\": \"理解しました、更新しました。\",\n \"obsidianLiveSyncSettingTab.btnNext\": \"次へ\",\n \"obsidianLiveSyncSettingTab.btnStart\": \"開始\",\n \"obsidianLiveSyncSettingTab.btnTest\": \"テスト\",\n \"obsidianLiveSyncSettingTab.btnUse\": \"使用\",\n \"obsidianLiveSyncSettingTab.buttonFetch\": \"フェッチ\",\n \"obsidianLiveSyncSettingTab.buttonNext\": \"次へ\",\n \"obsidianLiveSyncSettingTab.defaultLanguage\": \"デフォルト\",\n \"obsidianLiveSyncSettingTab.descConnectSetupURI\": \"セットアップURIを使用してSelf-hosted LiveSyncをセットアップする推奨方法です。\",\n \"obsidianLiveSyncSettingTab.descCopySetupURI\": \"新しいデバイスのセットアップにおすすめ!\",\n \"obsidianLiveSyncSettingTab.descEnableLiveSync\": \"上記の2つのオプションのいずれかを設定するか、すべての設定を手動で完了した後にのみ有効にしてください。\",\n \"obsidianLiveSyncSettingTab.descFetchConfigFromRemote\": \"既に設定済みのリモートサーバーから必要な設定を取得します。\",\n \"obsidianLiveSyncSettingTab.descManualSetup\": \"推奨しませんが、セットアップURIがない場合に便利です\",\n \"obsidianLiveSyncSettingTab.descTestDatabaseConnection\": \"データベース接続を開きます。リモートデータベースが見つからず、データベースを作成する権限がある場合は、データベースが作成されます。\",\n \"obsidianLiveSyncSettingTab.descValidateDatabaseConfig\": \"データベース設定の潜在的な問題を確認し、修正します。\",\n \"obsidianLiveSyncSettingTab.errAccessForbidden\": \"❗ アクセスが禁止されています。\",\n \"obsidianLiveSyncSettingTab.errCannotContinueTest\": \"テストを続行できませんでした。\",\n \"obsidianLiveSyncSettingTab.errCorsCredentials\": \"❗ cors.credentialsが不正です\",\n \"obsidianLiveSyncSettingTab.errCorsNotAllowingCredentials\": \"❗ CORSが認証情報を許可していません\",\n \"obsidianLiveSyncSettingTab.errCorsOrigins\": \"❗ cors.originsが不正です\",\n \"obsidianLiveSyncSettingTab.errEnableCors\": \"❗ httpd.enable_corsが不正です\",\n \"obsidianLiveSyncSettingTab.errEnableCorsChttpd\": \"❗ chttpd.enable_corsが不正です\",\n \"obsidianLiveSyncSettingTab.errMaxDocumentSize\": \"❗ couchdb.max_document_sizeが低すぎます\",\n \"obsidianLiveSyncSettingTab.errMaxRequestSize\": \"❗ chttpd.max_http_request_sizeが低すぎます\",\n \"obsidianLiveSyncSettingTab.errMissingWwwAuth\": \"❗ httpd.WWW-Authenticateが不足しています\",\n \"obsidianLiveSyncSettingTab.errRequireValidUser\": \"❗ chttpd.require_valid_userが不正です。\",\n \"obsidianLiveSyncSettingTab.errRequireValidUserAuth\": \"❗ chttpd_auth.require_valid_userが不正です。\",\n \"obsidianLiveSyncSettingTab.labelDisabled\": \"⏹️ : 無効\",\n \"obsidianLiveSyncSettingTab.labelEnabled\": \"🔁 : 有効\",\n \"obsidianLiveSyncSettingTab.levelAdvanced\": \" (上級)\",\n \"obsidianLiveSyncSettingTab.levelEdgeCase\": \" (エッジケース)\",\n \"obsidianLiveSyncSettingTab.levelPowerUser\": \" (エキスパート)\",\n \"obsidianLiveSyncSettingTab.linkOpenInBrowser\": \"ブラウザで開く\",\n \"obsidianLiveSyncSettingTab.linkPageTop\": \"ページトップ\",\n \"obsidianLiveSyncSettingTab.linkTipsAndTroubleshooting\": \"ヒントとトラブルシューティング\",\n \"obsidianLiveSyncSettingTab.linkTroubleshooting\": \"/docs/troubleshooting.md\",\n \"obsidianLiveSyncSettingTab.logCannotUseCloudant\": \"この機能はIBM Cloudantでは使用できません。\",\n \"obsidianLiveSyncSettingTab.logCheckingConfigDone\": \"設定の確認が完了しました\",\n \"obsidianLiveSyncSettingTab.logCheckingConfigFailed\": \"設定の確認に失敗しました\",\n \"obsidianLiveSyncSettingTab.logCheckingDbConfig\": \"データベース設定を確認中\",\n \"obsidianLiveSyncSettingTab.logCheckPassphraseFailed\": \"エラー: リモートサーバーとのパスフレーズ確認に失敗しました:\\n${db}。\",\n \"obsidianLiveSyncSettingTab.logConfiguredDisabled\": \"設定された同期モード: 無効\",\n \"obsidianLiveSyncSettingTab.logConfiguredLiveSync\": \"設定された同期モード: LiveSync\",\n \"obsidianLiveSyncSettingTab.logConfiguredPeriodic\": \"設定された同期モード: 定期\",\n \"obsidianLiveSyncSettingTab.logCouchDbConfigFail\": \"CouchDB設定: ${title} 失敗\",\n \"obsidianLiveSyncSettingTab.logCouchDbConfigSet\": \"CouchDB設定: ${title} -> ${key}を${value}に設定\",\n \"obsidianLiveSyncSettingTab.logCouchDbConfigUpdated\": \"CouchDB設定: ${title} 正常に更新されました\",\n \"obsidianLiveSyncSettingTab.logDatabaseConnected\": \"データベースに接続しました\",\n \"obsidianLiveSyncSettingTab.logEncryptionNoPassphrase\": \"パスフレーズなしでは暗号化を有効にできません\",\n \"obsidianLiveSyncSettingTab.logEncryptionNoSupport\": \"お使いのデバイスは暗号化をサポートしていません。\",\n \"obsidianLiveSyncSettingTab.logErrorOccurred\": \"エラーが発生しました!!\",\n \"obsidianLiveSyncSettingTab.logEstimatedSize\": \"推定サイズ: ${size}\",\n \"obsidianLiveSyncSettingTab.logPassphraseInvalid\": \"パスフレーズが無効です、修正してください。\",\n \"obsidianLiveSyncSettingTab.logPassphraseNotCompatible\": \"エラー: パスフレーズがリモートサーバーと適合しません!再度確認してください!\",\n \"obsidianLiveSyncSettingTab.logRebuildNote\": \"同期が無効になりました。必要に応じてフェッチして再有効化してください。\",\n \"obsidianLiveSyncSettingTab.logSelectAnyPreset\": \"プリセットを選択してください。\",\n \"obsidianLiveSyncSettingTab.msgAreYouSureProceed\": \"本当に続行しますか?\",\n \"obsidianLiveSyncSettingTab.msgChangesNeedToBeApplied\": \"変更を適用する必要があります!\",\n \"obsidianLiveSyncSettingTab.msgConfigCheck\": \"--設定確認--\",\n \"obsidianLiveSyncSettingTab.msgConfigCheckFailed\": \"設定確認に失敗しました。それでも続行しますか?\",\n \"obsidianLiveSyncSettingTab.msgConnectionCheck\": \"--接続確認--\",\n \"obsidianLiveSyncSettingTab.msgConnectionProxyNote\": \"設定確認後も接続確認に問題がある場合は、リバースプロキシの設定を確認してください。\",\n \"obsidianLiveSyncSettingTab.msgCurrentOrigin\": \"現在のオリジン: ${origin}\",\n \"obsidianLiveSyncSettingTab.msgDiscardConfirmation\": \"本当に既存の設定とデータベースを破棄しますか?\",\n \"obsidianLiveSyncSettingTab.msgDone\": \"--完了--\",\n \"obsidianLiveSyncSettingTab.msgEnableCors\": \"httpd.enable_corsを設定\",\n \"obsidianLiveSyncSettingTab.msgEnableCorsChttpd\": \"chttpd.enable_corsを設定\",\n \"obsidianLiveSyncSettingTab.msgEnableEncryptionRecommendation\": \"エンドツーエンド暗号化とパス難読化を有効にすることをお勧めします。暗号化なしで続行してもよろしいですか?\",\n \"obsidianLiveSyncSettingTab.msgFetchConfigFromRemote\": \"リモートサーバーから設定を取得しますか?\",\n \"obsidianLiveSyncSettingTab.msgGenerateSetupURI\": \"完了!他のデバイスをセットアップするためのセットアップURIを生成しますか?\",\n \"obsidianLiveSyncSettingTab.msgIfConfigNotPersistent\": \"サーバー設定が永続的でない場合(例: Dockerで実行中)、ここの値は変更される可能性があります。接続できるようになったら、サーバーのlocal.iniの設定を更新してください。\",\n \"obsidianLiveSyncSettingTab.msgInvalidPassphrase\": \"暗号化パスフレーズが無効かもしれません。続行してもよろしいですか?\",\n \"obsidianLiveSyncSettingTab.msgNewVersionNote\": \"アップグレード通知でここに来ましたか?バージョン履歴を確認してください。納得したらボタンをクリックしてください。新しい更新があると再度確認されます。\",\n \"obsidianLiveSyncSettingTab.msgNonHTTPSInfo\": \"非HTTPS URIとして設定されています。モバイルデバイスでは動作しない可能性があります。\",\n \"obsidianLiveSyncSettingTab.msgNonHTTPSWarning\": \"非HTTPS URIに接続できません。設定を更新して再試行してください。\",\n \"obsidianLiveSyncSettingTab.msgNotice\": \"---お知らせ---\",\n \"obsidianLiveSyncSettingTab.msgObjectStorageWarning\": \"警告: この機能は開発中です。以下の点にご注意ください:\\n- 追記専用アーキテクチャ。ストレージを縮小するには再構築が必要です。\\n- やや不安定です。\\n- 初回同期時、すべての履歴がリモートから転送されます。データ制限と速度に注意してください。\\n- ライブ同期は差分のみです。\\n\\n問題があれば、またはこの機能についてアイデアがあれば、GitHubにIssueを作成してください。\\nご協力に感謝します。\",\n \"obsidianLiveSyncSettingTab.msgOriginCheck\": \"オリジン確認: ${org}\",\n \"obsidianLiveSyncSettingTab.msgRebuildRequired\": \"変更を適用するにはデータベースの再構築が必要です。変更を適用する方法を選択してください。\\n\\n<details>\\n<summary>凡例</summary>\\n\\n| 記号 | 意味 |\\n|: ------ :| ------- |\\n| ⇔ | 最新 |\\n| ⇄ | 同期してバランスを取る |\\n| ⇐,⇒ | 上書きするため転送 |\\n| ⇠,⇢ | 反対側から上書きするため転送 |\\n\\n</details>\\n\\n## ${OPTION_REBUILD_BOTH}\\n概要: 📄 ⇒¹ 💻 ⇒² 🛰️ ⇢ⁿ 💻 ⇄ⁿ⁺¹ 📄\\nこのデバイスの既存ファイルを使用してローカルとリモートの両方のデータベースを再構築します。\\n他のデバイスはロックアウトされ、フェッチが必要です。\\n## ${OPTION_FETCH}\\n概要: 📄 ⇄² 💻 ⇐¹ 🛰️ ⇔ 💻 ⇔ 📄\\nローカルデータベースを初期化し、リモートデータベースから取得したデータを使用して再構築します。\\nリモートデータベースを再構築した場合も含まれます。\\n## ${OPTION_ONLY_SETTING}\\n設定のみを保存します。**注意: データ破損につながる可能性があります**。通常、データベースの再構築が必要です。\",\n \"obsidianLiveSyncSettingTab.msgSelectAndApplyPreset\": \"ウィザードを完了するには、プリセット項目を選択して適用してください。\",\n \"obsidianLiveSyncSettingTab.msgSetCorsCredentials\": \"cors.credentialsを設定\",\n \"obsidianLiveSyncSettingTab.msgSetCorsOrigins\": \"cors.originsを設定\",\n \"obsidianLiveSyncSettingTab.msgSetMaxDocSize\": \"couchdb.max_document_sizeを設定\",\n \"obsidianLiveSyncSettingTab.msgSetMaxRequestSize\": \"chttpd.max_http_request_sizeを設定\",\n \"obsidianLiveSyncSettingTab.msgSetRequireValidUser\": \"chttpd.require_valid_user = trueを設定\",\n \"obsidianLiveSyncSettingTab.msgSetRequireValidUserAuth\": \"chttpd_auth.require_valid_user = trueを設定\",\n \"obsidianLiveSyncSettingTab.msgSettingModified\": \"設定\\\"${setting}\\\"が別のデバイスから変更されました。{HERE}をクリックして設定を再読み込みしてください。変更を無視するには他の場所をクリックしてください。\",\n \"obsidianLiveSyncSettingTab.msgSettingsUnchangeableDuringSync\": \"これらの設定は同期中に変更できません。ロックを解除するには、\\\"同期設定\\\"ですべての同期を無効にしてください。\",\n \"obsidianLiveSyncSettingTab.msgSetWwwAuth\": \"httpd.WWW-Authenticateを設定\",\n \"obsidianLiveSyncSettingTab.nameApplySettings\": \"設定を適用\",\n \"obsidianLiveSyncSettingTab.nameConnectSetupURI\": \"セットアップURIで接続\",\n \"obsidianLiveSyncSettingTab.nameCopySetupURI\": \"現在の設定をセットアップURIにコピー\",\n \"obsidianLiveSyncSettingTab.nameDisableHiddenFileSync\": \"隠しファイル同期を無効化\",\n \"obsidianLiveSyncSettingTab.nameDiscardSettings\": \"既存の設定とデータベースを破棄\",\n \"obsidianLiveSyncSettingTab.nameEnableHiddenFileSync\": \"隠しファイル同期を有効化\",\n \"obsidianLiveSyncSettingTab.nameEnableLiveSync\": \"LiveSyncを有効化\",\n \"obsidianLiveSyncSettingTab.nameHiddenFileSynchronization\": \"隠しファイル同期\",\n \"obsidianLiveSyncSettingTab.nameManualSetup\": \"手動セットアップ\",\n \"obsidianLiveSyncSettingTab.nameTestConnection\": \"接続テスト\",\n \"obsidianLiveSyncSettingTab.nameTestDatabaseConnection\": \"データベース接続テスト\",\n \"obsidianLiveSyncSettingTab.nameValidateDatabaseConfig\": \"データベース設定を検証\",\n \"obsidianLiveSyncSettingTab.okAdminPrivileges\": \"✔ 管理者権限があります。\",\n \"obsidianLiveSyncSettingTab.okCorsCredentials\": \"✔ cors.credentialsは正常です。\",\n \"obsidianLiveSyncSettingTab.okCorsCredentialsForOrigin\": \"CORS認証情報OK\",\n \"obsidianLiveSyncSettingTab.okCorsOriginMatched\": \"✔ CORSオリジンOK\",\n \"obsidianLiveSyncSettingTab.okCorsOrigins\": \"✔ cors.originsは正常です。\",\n \"obsidianLiveSyncSettingTab.okEnableCors\": \"✔ httpd.enable_corsは正常です。\",\n \"obsidianLiveSyncSettingTab.okEnableCorsChttpd\": \"✔ chttpd.enable_corsは正常です。\",\n \"obsidianLiveSyncSettingTab.okMaxDocumentSize\": \"✔ couchdb.max_document_sizeは正常です。\",\n \"obsidianLiveSyncSettingTab.okMaxRequestSize\": \"✔ chttpd.max_http_request_sizeは正常です。\",\n \"obsidianLiveSyncSettingTab.okRequireValidUser\": \"✔ chttpd.require_valid_userは正常です。\",\n \"obsidianLiveSyncSettingTab.okRequireValidUserAuth\": \"✔ chttpd_auth.require_valid_userは正常です。\",\n \"obsidianLiveSyncSettingTab.okWwwAuth\": \"✔ httpd.WWW-Authenticateは正常です。\",\n \"obsidianLiveSyncSettingTab.optionApply\": \"適用\",\n \"obsidianLiveSyncSettingTab.optionCancel\": \"キャンセル\",\n \"obsidianLiveSyncSettingTab.optionCouchDB\": \"CouchDB\",\n \"obsidianLiveSyncSettingTab.optionDisableAllAutomatic\": \"すべての自動を無効化\",\n \"obsidianLiveSyncSettingTab.optionFetchFromRemote\": \"リモートからフェッチ\",\n \"obsidianLiveSyncSettingTab.optionHere\": \"ここ\",\n \"obsidianLiveSyncSettingTab.optionLiveSync\": \"LiveSync\",\n \"obsidianLiveSyncSettingTab.optionMinioS3R2\": \"Minio,S3,R2\",\n \"obsidianLiveSyncSettingTab.optionOkReadEverything\": \"OK、すべて読みました。\",\n \"obsidianLiveSyncSettingTab.optionOnEvents\": \"イベント時\",\n \"obsidianLiveSyncSettingTab.optionPeriodicAndEvents\": \"定期およびイベント時\",\n \"obsidianLiveSyncSettingTab.optionPeriodicWithBatch\": \"バッチ付き定期\",\n \"obsidianLiveSyncSettingTab.optionRebuildBoth\": \"このデバイスから両方を再構築\",\n \"obsidianLiveSyncSettingTab.optionSaveOnlySettings\": \"(危険) 設定のみ保存\",\n \"obsidianLiveSyncSettingTab.panelChangeLog\": \"変更履歴\",\n \"obsidianLiveSyncSettingTab.panelGeneralSettings\": \"一般設定\",\n \"obsidianLiveSyncSettingTab.panelPrivacyEncryption\": \"プライバシーと暗号化\",\n \"obsidianLiveSyncSettingTab.panelRemoteConfiguration\": \"リモート設定\",\n \"obsidianLiveSyncSettingTab.panelSetup\": \"セットアップ\",\n \"obsidianLiveSyncSettingTab.serverVersion\": \"サーバー情報: ${info}\",\n \"obsidianLiveSyncSettingTab.titleActiveRemoteServer\": \"アクティブなリモートサーバー\",\n \"obsidianLiveSyncSettingTab.titleAppearance\": \"外観\",\n \"obsidianLiveSyncSettingTab.titleConflictResolution\": \"競合解決\",\n \"obsidianLiveSyncSettingTab.titleCongratulations\": \"おめでとうございます!\",\n \"obsidianLiveSyncSettingTab.titleCouchDB\": \"CouchDB\",\n \"obsidianLiveSyncSettingTab.titleDeletionPropagation\": \"削除の伝播\",\n \"obsidianLiveSyncSettingTab.titleEncryptionNotEnabled\": \"暗号化が有効になっていません\",\n \"obsidianLiveSyncSettingTab.titleEncryptionPassphraseInvalid\": \"暗号化パスフレーズが無効です\",\n \"obsidianLiveSyncSettingTab.titleExtraFeatures\": \"追加および上級機能を有効化\",\n \"obsidianLiveSyncSettingTab.titleFetchConfig\": \"設定を取得\",\n \"obsidianLiveSyncSettingTab.titleFetchConfigFromRemote\": \"リモートサーバーから設定を取得\",\n \"obsidianLiveSyncSettingTab.titleFetchSettings\": \"設定の取得\",\n \"obsidianLiveSyncSettingTab.titleHiddenFiles\": \"隠しファイル\",\n \"obsidianLiveSyncSettingTab.titleLogging\": \"ログ\",\n \"obsidianLiveSyncSettingTab.titleMinioS3R2\": \"Minio,S3,R2\",\n \"obsidianLiveSyncSettingTab.titleNotification\": \"通知\",\n \"obsidianLiveSyncSettingTab.titleOnlineTips\": \"オンラインヒント\",\n \"obsidianLiveSyncSettingTab.titleQuickSetup\": \"クイックセットアップ\",\n \"obsidianLiveSyncSettingTab.titleRebuildRequired\": \"再構築が必要\",\n \"obsidianLiveSyncSettingTab.titleRemoteConfigCheckFailed\": \"リモート設定の確認に失敗\",\n \"obsidianLiveSyncSettingTab.titleRemoteServer\": \"リモートサーバー\",\n \"obsidianLiveSyncSettingTab.titleReset\": \"リセット\",\n \"obsidianLiveSyncSettingTab.titleSetupOtherDevices\": \"他のデバイスのセットアップ\",\n \"obsidianLiveSyncSettingTab.titleSynchronizationMethod\": \"同期方法\",\n \"obsidianLiveSyncSettingTab.titleSynchronizationPreset\": \"同期プリセット\",\n \"obsidianLiveSyncSettingTab.titleSyncSettings\": \"同期設定\",\n \"obsidianLiveSyncSettingTab.titleSyncSettingsViaMarkdown\": \"Markdown経由で設定を同期\",\n \"obsidianLiveSyncSettingTab.titleUpdateThinning\": \"更新の間引き\",\n \"obsidianLiveSyncSettingTab.warnCorsOriginUnmatched\": \"⚠ CORS Originが一致しません ${from}->${to}\",\n \"obsidianLiveSyncSettingTab.warnNoAdmin\": \"⚠ 管理者権限がありません。\",\n \"P2P.AskPassphraseForDecrypt\": \"リモートピアから設定が共有されました。設定を復号するためのパスフレーズを入力してください。\",\n \"P2P.AskPassphraseForShare\": \"リモートピアからこのデバイスの設定が要求されました。設定を共有するためのパスフレーズを入力してください。このダイアログをキャンセルすることでリクエストを無視できます。\",\n \"P2P.DisabledButNeed\": \"%{title_p2p_sync}は無効になっています。本当に有効にしますか?\",\n \"P2P.FailedToOpen\": \"シグナリングサーバーへのP2P接続を開けませんでした。\",\n \"P2P.NoAutoSyncPeers\": \"自動同期ピアが見つかりません。%{long_p2p_sync}ペインでピアを設定してください。\",\n \"P2P.NoKnownPeers\": \"ピアが検出されていません。他のピアからの接続を待機中...\",\n \"P2P.Note.description\": \"このレプリケーターは、ピアツーピア接続を使用して、Vaultを他のデバイスと同期することができます。クラウドサービスを使用せずに、他のデバイスとVaultを同期することができます。\\nこのレプリケーターはTrysteroをベースにしています。デバイス間の接続を確立するためにシグナリングサーバーを使用します。シグナリングサーバーはデバイス間で接続情報を交換するために使用されます。私たちのデータを知ったり保存したりすることはありません(または、そうあるべきではありません)。\\n\\nシグナリングサーバーは誰でもホストできます。これは単なるNostrリレーです。簡便さとレプリケーターの動作確認のために、vrtmrzがシグナリングサーバーのインスタンスをホストしています。vrtmrzが提供する実験用サーバーを使用することも、他のサーバーを使用することもできます。\\n\\nなお、シグナリングサーバーが私たちのデータを保存しなくても、一部のデバイスの接続情報を見ることができます。これにご注意ください。また、他の人が提供するサーバーを使用する場合は注意してください。\",\n \"P2P.Note.important_note\": \"ピアツーピアレプリケーターの実験的実装\",\n \"P2P.Note.important_note_sub\": \"この機能はまだ実験段階です。期待通りに動作しない可能性があることにご注意ください。さらに、バグ、セキュリティの問題、その他の問題がある可能性があります。この機能は自己責任でご使用ください。この機能の開発にご協力ください。\",\n \"P2P.Note.Summary\": \"この機能について(重要な注意事項を含む、一度お読みください)\",\n \"P2P.NotEnabled\": \"%{title_p2p_sync}が有効になっていません。新しい接続を開くことができません。\",\n \"P2P.P2PReplication\": \"%{P2P}レプリケーション(複製)\",\n \"P2P.PaneTitle\": \"%{long_p2p_sync}\",\n \"P2P.ReplicatorInstanceMissing\": \"P2P同期レプリケーターが見つかりません。設定または有効化されていない可能性があります。\",\n \"P2P.SeemsOffline\": \"ピア${name}はオフラインのようです。スキップしました。\",\n \"P2P.SyncAlreadyRunning\": \"P2P同期はすでに実行中です。\",\n \"P2P.SyncCompleted\": \"P2P同期が完了しました。\",\n \"P2P.SyncStartedWith\": \"${name}とのP2P同期を開始しました。\",\n \"Passphrase\": \"パスフレーズ\",\n \"Passphrase of sensitive configuration items\": \"機密性の高い設定項目にパスフレーズを使用\",\n \"password\": \"パスワード\",\n \"Password\": \"パスワード\",\n \"Path Obfuscation\": \"パスの難読化\",\n \"Per-file-saved customization sync\": \"ファイルごとのカスタマイズ同期\",\n \"Periodic Sync interval\": \"定時同期の感覚\",\n \"Presets\": \"プリセット\",\n \"Process small files in the foreground\": \"小さいファイルを最前面で処理\",\n \"RedFlag.Fetch.Method.Desc\": \"どのようにフェッチしますか?\\n- %{RedFlag.Fetch.Method.FetchSafer}\\n **低トラフィック**, **高CPU負荷**, **低リスク**\\n 推奨条件...\\n - ファイルの整合性に不安がある\\n - ファイル数がそれほど多くない\\n- %{RedFlag.Fetch.Method.FetchSmoother}\\n **低トラフィック**, **中程CPU負荷**, **低~中リスク**\\n 推奨条件...\\n - ファイルがおそらく整合している\\n - ファイル数が多い\\n- %{RedFlag.Fetch.Method.FetchTraditional}\\n **高トラフィック**, **低CPU負荷**, **低~中リスク**\\n\\n>[!INFO]- 詳細\\n> ## %{RedFlag.Fetch.Method.FetchSafer}\\n> **低トラフィック**, **高CPU負荷**, **低リスク**\\n> このオプションは、リモートからデータをフェッチする前に、既存のローカルファイルを使用してローカルデータベースを作成します。\\n> ローカルとリモートの両方に一致するファイルがある場合、差分のみが転送されます。\\n> ただし、両方の場所に存在するファイルは最初は競合ファイルとして処理されます。実際に競合していなければ自動的に解決されますが、この処理には時間がかかる場合があります。\\n> これは一般的に最も安全な方法で、データ損失のリスクを最小限に抑えます。\\n> ## %{RedFlag.Fetch.Method.FetchSmoother}\\n> **低トラフィック**, **中程CPU負荷**, **低~中リスク**(操作による)\\n> このオプションは、最初にローカルファイルからデータベース用のチャンクを作成し、その後データをフェッチします。そのため、ローカルにないチャンクのみが転送されます。ただし、すべてのメタデータはリモートから取得されます。\\n> ローカルファイルは起動時にこのメタデータと比較されます。新しいと判断されたコンテンツ(更新日時による)が古いものを上書きします。この結果はリモートデータベースに同期されます。\\n> ローカルファイルが本当に最新のタイムスタンプであれば一般的に安全です。ただし、ファイルのタイムスタンプが新しくてもコンテンツが古い場合(初期の`welcome.md`など)は問題が発生する可能性があります。\\n> これは\\\"%{RedFlag.Fetch.Method.FetchSafer}\\\"よりCPU使用量が少なく高速ですが、注意しないとデータ損失につながる可能性があります。\\n> ## %{RedFlag.Fetch.Method.FetchTraditional}\\n> **高トラフィック**, **低CPU負荷**, **低~中リスク**(操作による)\\n> すべてのデータがリモートからフェッチされます。\\n> %{RedFlag.Fetch.Method.FetchSmoother}と似ていますが、すべてのチャンクがリモートからフェッチされます。\\n> これは最も従来のフェッチ方法で、通常最もネットワークトラフィックと時間を消費します。'%{RedFlag.Fetch.Method.FetchSmoother}'オプションと同様のリモートファイル上書きのリスクがあります。\\n> ただし、最も歴史があり簡単なアプローチであるため、最も安定した方法と見なされることが多いです。\",\n \"RedFlag.Fetch.Method.FetchSafer\": \"フェッチ前にローカルデータベースを作成\",\n \"RedFlag.Fetch.Method.FetchSmoother\": \"フェッチ前にローカルファイルチャンクを作成\",\n \"RedFlag.Fetch.Method.FetchTraditional\": \"リモートからすべてをフェッチ\",\n \"RedFlag.Fetch.Method.Title\": \"どのようにフェッチしますか?\",\n \"RedFlag.FetchRemoteConfig.Buttons.Cancel\": \"いいえ、ローカル設定を使用\",\n \"RedFlag.FetchRemoteConfig.Buttons.Fetch\": \"はい、リモート設定を取得して適用\",\n \"RedFlag.FetchRemoteConfig.Message\": \"リモートに保存された設定を取得して、このデバイスに適用しますか?\",\n \"RedFlag.FetchRemoteConfig.Title\": \"リモート設定の取得\",\n \"Reducing the frequency with which on-disk changes are reflected into the DB\": \"ローカルでの変更がデータベースに反映される頻度を下げる(所定の回数まとめて同期する、逐一反映しない)\",\n \"Region\": \"リージョン\",\n \"Remote server type\": \"リモートの種別\",\n \"Remote Type\": \"同期方式\",\n \"Replicator.Dialogue.Locked.Action.Dismiss\": \"再確認のためキャンセル\",\n \"Replicator.Dialogue.Locked.Action.Fetch\": \"このデバイスの同期をリセット\",\n \"Replicator.Dialogue.Locked.Action.Unlock\": \"リモートデータベースのロックを解除\",\n \"Replicator.Dialogue.Locked.Message\": \"リモートデータベースがロックされています。これはいずれかの端末での再構築が原因です。\\nデータベースの破損を避けるため、このデバイスは接続を保留するよう求められています。\\n\\n3つのオプションがあります:\\n\\n- %{Replicator.Dialogue.Locked.Action.Fetch}\\n 最も推奨される信頼性の高い方法です。ローカルデータベースを一度破棄し、リモートデータベースからすべての同期情報を再取得します。ほとんどの場合、これは安全に実行できます。ただし、時間がかかり、安定したネットワークで実行する必要があります。\\n- %{Replicator.Dialogue.Locked.Action.Unlock}\\n この方法は、他のレプリケーション(複製)方法ですでに確実に同期されている場合のみ使用できます。単に同じファイルがあるという意味ではありません。確信がない場合は避けてください。\\n- %{Replicator.Dialogue.Locked.Action.Dismiss}\\n 操作をキャンセルします。次回のリクエスト時に再度確認されます。\\n\",\n \"Replicator.Dialogue.Locked.Message.Fetch\": \"全フェッチがスケジュールされました。プラグインは実行のために再起動されます。\",\n \"Replicator.Dialogue.Locked.Message.Unlocked\": \"リモートデータベースのロックが解除されました。操作を再試行してください。\",\n \"Replicator.Dialogue.Locked.Title\": \"ロック中\",\n \"Replicator.Message.Cleaned\": \"データベースのクリーナップ中です。レプリケーション(複製)はキャンセルされました。\",\n \"Replicator.Message.InitialiseFatalError\": \"レプリケーターが利用できません。これは致命的なエラーです。\",\n \"Replicator.Message.Pending\": \"ファイルイベントが保留中です。レプリケーション(複製)はキャンセルされました。\",\n \"Replicator.Message.SomeModuleFailed\": \"一部のモジュールの失敗によりレプリケーション(複製)がキャンセルされました。\",\n \"Replicator.Message.VersionUpFlash\": \"更新が検出されました。設定ダイアログを開いて変更ログを確認してください。レプリケーション(複製)はキャンセルされました。\",\n \"Requires restart of Obsidian\": \"Obsidianの再起動が必要です\",\n \"Requires restart of Obsidian.\": \"Obsidianの再起動が必要です。\",\n \"Save settings to a markdown file. You will be notified when new settings arrive. You can set different files by the platform.\": \"Markdownファイルに設定を保存します。新しい設定が到着すると通知されます。プラットフォームごとに異なるファイルを設定できます。\",\n \"Saving will be performed forcefully after this number of seconds.\": \"この秒数後に強制的に保存されます。\",\n \"Scan changes on customization sync\": \"カスタマイズされた同期時に、変更をスキャンする\",\n \"Scan customization automatically\": \"自動的にカスタマイズをスキャン\",\n \"Scan customization before replicating.\": \"レプリケーション(複製)前に、カスタマイズをスキャン\",\n \"Scan customization every 1 minute.\": \"カスタマイズのスキャンを1分ごとに行う\",\n \"Scan customization periodically\": \"定期的にカスタマイズをスキャン\",\n \"Scan for hidden files before replication\": \"レプリケーション(複製)開始前に、隠しファイルのスキャンを行う\",\n \"Scan hidden files periodically\": \"定期的に隠しファイルのスキャンを行う\",\n \"Seconds, 0 to disable\": \"秒数、0で無効\",\n \"Seconds. Saving to the local database will be delayed until this value after we stop typing or saving.\": \"秒。入力や保存を停止してからこの値の間、ローカルデータベースへの保存が遅延されます。\",\n \"Secret Key\": \"シークレットキー\",\n \"Server URI\": \"URI\",\n \"Setting.GenerateKeyPair.Desc\": \"キーペアを生成しました!\\n\\n注意: このキーペアは再度表示されません。安全な場所に保存してください。紛失した場合は、新しいキーペアを生成する必要があります。\\n注意2: 公開鍵はspki形式、秘密鍵はpkcs8形式です。利便性のため、公開鍵の改行は`\\\\n`に変換されています。\\n注意3: 公開鍵はリモートデータベースに、秘密鍵はローカルデバイスに設定してください。\\n\\n>[!FOR YOUR EYES ONLY]-\\n> <div class=\\\"sls-keypair\\\">\\n>\\n> ### 公開鍵\\n> ```\\n${public_key}\\n> ```\\n>\\n> ### 秘密鍵\\n> ```\\n${private_key}\\n> ```\\n>\\n> </div>\\n\\n>[!Both for copying]-\\n>\\n> <div class=\\\"sls-keypair\\\">\\n>\\n> ```\\n${public_key}\\n${private_key}\\n> ```\\n>\\n> </div>\\n\\n\",\n \"Setting.GenerateKeyPair.Title\": \"新しいキーペアが生成されました!\",\n \"Setting.TroubleShooting\": \"トラブルシューティング\",\n \"Setting.TroubleShooting.Doctor\": \"設定診断ツール\",\n \"Setting.TroubleShooting.Doctor.Desc\": \"最適でない設定を検出します。(マイグレーション時と同じ)\",\n \"Setting.TroubleShooting.ScanBrokenFiles\": \"破損ファイルのスキャン\",\n \"Setting.TroubleShooting.ScanBrokenFiles.Desc\": \"データベースに正しく保存されていないファイルをスキャンします。\",\n \"SettingTab.Message.AskRebuild\": \"変更にはリモートデータベースからのフェッチが必要です。続行しますか?\",\n \"Setup.Apply.Buttons.ApplyAndFetch\": \"適用してフェッチ\",\n \"Setup.Apply.Buttons.ApplyAndMerge\": \"適用してマージ\",\n \"Setup.Apply.Buttons.ApplyAndRebuild\": \"適用して再構築\",\n \"Setup.Apply.Buttons.Cancel\": \"破棄してキャンセル\",\n \"Setup.Apply.Buttons.OnlyApply\": \"適用のみ\",\n \"Setup.Apply.Message\": \"新しい設定の準備ができました。適用に進みましょう。\\n適用方法はいくつかあります:\\n\\n- 適用してフェッチ\\n このデバイスを新しいクライアントとして設定します。適用後、リモートサーバーから同期します。\\n- 適用してマージ\\n 既にファイルがあるデバイスで設定します。ローカルファイルを処理し、差分を転送します。競合が発生する場合があります。\\n- 適用して再構築\\n ローカルファイルを使用してリモートを再構築します。これは通常、サーバーが破損した場合や最初からやり直したい場合に行います。\\n 他のデバイスはロックされ、再フェッチが必要になります。\\n- 適用のみ\\n 適用のみを行います。再構築が必要な場合、競合が発生する可能性があります。\",\n \"Setup.Apply.Title\": \"${method}からの新しい設定を適用\",\n \"Setup.Apply.WarningRebuildRecommended\": \"注意: 設定の調整後、再構築が必要と判断されました。インポートのみは推奨されません。\",\n \"Setup.Doctor.Buttons.No\": \"いいえ、URIの設定をそのまま使用\",\n \"Setup.Doctor.Buttons.Yes\": \"はい、診断ツールに相談する\",\n \"Setup.Doctor.Message\": \"Self-hosted LiveSyncは徐々に歴史が長くなり、一部の推奨設定が変更されています。\\n\\nセットアップは、これを行う非常に良い機会です。\\n\\nインポートされた設定が最新の状態と比較して最適かどうかを確認するために、診断ツールを実行しますか?\",\n \"Setup.Doctor.Title\": \"診断ツールに相談しますか?\",\n \"Setup.FetchRemoteConf.Buttons.Fetch\": \"はい、設定を取得\",\n \"Setup.FetchRemoteConf.Buttons.Skip\": \"いいえ、URIの設定を使用\",\n \"Setup.FetchRemoteConf.Message\": \"既に他のデバイスと同期したことがある場合、リモートデータベースには同期されたデバイス間の適切な設定値が保存されています。プラグインは堅牢な設定のためにそれらを取得したいと考えています。\\n\\nただし、1つ確認が必要です。現在、ネットワークに安全にアクセスして設定を取得できる状況ですか?\\n\\n注意: リモートデータベースがSSL証明書でホストされており、ネットワークが侵害されていなければ、ほとんどの場合安全に実行できます。\",\n \"Setup.FetchRemoteConf.Title\": \"リモートデータベースから設定を取得しますか?\",\n \"Setup.QRCode\": \"設定を転送するためのQRコードを生成しました。スマートフォンや他のデバイスでQRコードをスキャンしてください。\\n注意: QRコードは暗号化されていないため、開く際は注意してください。\\n\\n>[!FOR YOUR EYES ONLY]-\\n> <div class=\\\"sls-qr\\\">${qr_image}</div>\",\n \"Setup.ShowQRCode\": \"QRコードを表示\",\n \"Setup.ShowQRCode.Desc\": \"設定を転送するためのQRコードを表示します。\",\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 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 \"Show only notifications\": \"通知のみ表示\",\n \"Show status as icons only\": \"ステータス表示をアイコンのみにする\",\n \"Show status inside the editor\": \"ステータスをエディタ内に表示\",\n \"Show status on the status bar\": \"ステータスバーに、ステータスを表示\",\n \"Show verbose log. Please enable if you report an issue.\": \"エラー以外の詳細ログ項目も表示する。問題が発生した場合は有効にしてください。\",\n \"Starts synchronisation when a file is saved.\": \"ファイルが保存されたときに同期を開始します。\",\n \"Stop reflecting database changes to storage files.\": \"データベースの変更をストレージファイルに反映させない\",\n \"Stop watching for file changes.\": \"監視の停止\",\n \"Suppress notification of hidden files change\": \"隠しファイルの変更通知を抑制\",\n \"Suspend database reflecting\": \"データベース反映の一時停止\",\n \"Suspend file watching\": \"監視の一時停止\",\n \"Sync after merging file\": \"ファイルがマージ(統合)された時に同期\",\n \"Sync automatically after merging files\": \"ファイルのマージ後に自動的に同期\",\n \"Sync Mode\": \"同期モード\",\n \"Sync on Editor Save\": \"エディタでの保存時に、同期されます\",\n \"Sync on File Open\": \"ファイルを開いた時に同期\",\n \"Sync on Save\": \"保存時に同期\",\n \"Sync on Startup\": \"起動時同期\",\n \"Testing only - Resolve file conflicts by syncing newer copies of the file, this can overwrite modified files. Be Warned.\": \"テスト用 - ファイルの新しいコピーを同期してファイル競合を解決します。これにより変更されたファイルが上書きされる可能性があります。注意してください。\",\n \"The delay for consecutive on-demand fetches\": \"連続したオンデマンドフェッチの遅延\",\n \"The Hash algorithm for chunk IDs\": \"チャンクIDのハッシュアルゴリズム\",\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 total size of chunks that can be incubated within the document. Chunks exceeding this size will immediately graduate to independent chunks.\": \"ドキュメント内で保持できるチャンクの最大合計サイズ。このサイズを超えたチャンクは即座に独立したチャンクに昇格します。\",\n \"This passphrase will not be copied to another device. It will be set to `Default` until you configure it again.\": \"このパスフレーズは他のデバイスにコピーされません。再度設定するまで`Default`に設定されます。\",\n \"TweakMismatchResolve.Action.Dismiss\": \"無視\",\n \"TweakMismatchResolve.Action.UseConfigured\": \"設定済みの設定を使用\",\n \"TweakMismatchResolve.Action.UseMine\": \"リモートデータベースの設定を更新\",\n \"TweakMismatchResolve.Action.UseMineAcceptIncompatible\": \"リモートデータベースの設定を更新するがそのまま維持\",\n \"TweakMismatchResolve.Action.UseMineWithRebuild\": \"リモートデータベースの設定を更新して再構築\",\n \"TweakMismatchResolve.Action.UseRemote\": \"このデバイスに設定を適用\",\n \"TweakMismatchResolve.Action.UseRemoteAcceptIncompatible\": \"このデバイスに設定を適用し、非互換性を無視\",\n \"TweakMismatchResolve.Action.UseRemoteWithRebuild\": \"このデバイスに設定を適用し、再フェッチ\",\n \"TweakMismatchResolve.Message.Main\": \"\\nリモートデータベースの設定は以下の通りです。これらの値は、このデバイスと少なくとも1回同期された他のデバイスによって設定されています。\\n\\nこれらの設定を使用する場合は、%{TweakMismatchResolve.Action.UseConfigured}を選択してください。\\nこのデバイスの設定を維持する場合は、%{TweakMismatchResolve.Action.Dismiss}を選択してください。\\n\\n${table}\\n\\n>[!TIP]\\n> すべての設定を同期したい場合は、この機能で最小限の設定を適用した後、`Sync settings via markdown`を使用してください。\\n\\n${additionalMessage}\",\n \"TweakMismatchResolve.Message.MainTweakResolving\": \"設定がリモートサーバーの設定と一致しません。\\n\\n以下の設定が一致している必要があります:\\n\\n${table}\\n\\n判断をお知らせください。\\n\\n${additionalMessage}\",\n \"TweakMismatchResolve.Message.UseRemote.WarningRebuildRecommended\": \"\\n>[!NOTICE]\\n> 一部の変更は互換性がありますが、追加のストレージと転送量を消費する可能性があります。再構築をお勧めします。ただし、再構築は現時点では実行されない場合がありますが、将来のメンテナンスで実装される可能性があります。\\n> ***適用には時間と安定したネットワーク接続が必要です!***\",\n \"TweakMismatchResolve.Message.UseRemote.WarningRebuildRequired\": \"\\n>[!WARNING]\\n> 一部のリモート設定はこのデバイスのローカルデータベースと互換性がありません。ローカルデータベースの再構築が必要です。\\n> ***適用には時間と安定したネットワーク接続が必要です!***\",\n \"TweakMismatchResolve.Message.WarningIncompatibleRebuildRecommended\": \"\\n>[!NOTICE]\\n> ローカルデータベースとリモートデータベースの非互換性を引き起こす値の違いが検出されました。\\n> 一部の変更は互換性がありますが、追加のストレージと転送量を消費する可能性があります。再構築をお勧めします。ただし、再構築は現時点では実行されない場合がありますが、将来のメンテナンスで実装される可能性があります。\\n> 再構築を行う場合は数分以上かかります。**今実行しても安全か確認してください。**\",\n \"TweakMismatchResolve.Message.WarningIncompatibleRebuildRequired\": \"\\n>[!WARNING]\\n> ローカルデータベースとリモートデータベースの非互換性を引き起こす値の違いが検出されました。\\n> ローカルまたはリモートの再構築が必要です。どちらも数分以上かかります。**今実行しても安全か確認してください。**\",\n \"TweakMismatchResolve.Table\": \"| 値の名前 | このデバイス | リモート |\\n|: --- |: ---- :|: ---- :|\\n${rows}\\n\\n\",\n \"TweakMismatchResolve.Table.Row\": \"| ${name} | ${self} | ${remote} |\",\n \"TweakMismatchResolve.Title\": \"設定の不一致が検出されました\",\n \"TweakMismatchResolve.Title.TweakResolving\": \"設定の不一致が検出されました\",\n \"TweakMismatchResolve.Title.UseRemoteConfig\": \"リモート設定を使用\",\n \"Unique name between all synchronized devices. To edit this setting, please disable customization sync once.\": \"同期するすべての端末間で重複しない(一意の)名前。この設定を変更する場合、カスタマイズ同期を無効にしてください。\",\n \"Use Custom HTTP Handler\": \"カスタムHTTPハンドラーの利用\",\n \"Use dynamic iteration count\": \"動的な繰り返し回数\",\n \"Use Segmented-splitter\": \"セグメント分割を使用\",\n \"Use splitting-limit-capped chunk splitter\": \"分割制限付きチャンク分割を使用\",\n \"Use the trash bin\": \"ゴミ箱を使用\",\n \"Use timeouts instead of heartbeats\": \"ハートビートの代わりにタイムアウトを使用\",\n \"username\": \"ユーザー名\",\n \"Username\": \"ユーザー名\",\n \"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 \"When you save a file in the editor, start a sync automatically\": \"エディタでファイルを保存すると、自動的に同期を開始します\",\n \"Write credentials in the file\": \"認証情報のファイル内保存\",\n \"Write logs into the file\": \"ファイルにログを記録\"\n}\n","import ja from \"../messagesJson/ja.json\";\nexport const PartialMessages = {\n ja,\n} as const;\n","{\n \"(BETA) Always overwrite with a newer file\": \"(베타) 항상 새로운 파일로 덮어쓰기\",\n \"(Beta) Use ignore files\": \"(베타) 제외 규칙 파일 사용\",\n \"(Days passed, 0 to disable automatic-deletion)\": \"(지난 일수, 0으로 설정하면 자동 삭제 비활성화)\",\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.\": \"(예: 청크를 원격에서 읽음) 이 옵션을 활성화하면, LiveSync는 청크를 로컬에 복제하지 않고 원격에서 직접 읽습니다. 커스텀 청크 크기를 키우는 것을 권장합니다.\",\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.\": \"(MB) 이 값이 설정되면, 이보다 큰 로컬 및 원격 파일의 변경 사항은 건너뜁니다. 파일이 다시 작아지면 더 새로운 파일이 사용됩니다.\",\n \"(Mega chars)\": \"(메가 문자)\",\n \"(Not recommended) If set, credentials will be stored in the file.\": \"(권장하지 않음) 설정한 경우 자격 증명이 파일에 저장됩니다.\",\n \"(Obsolete) Use an old adapter for compatibility\": \"(사용 중단) 호환성을 위해 이전 어댑터 사용\",\n \"Access Key\": \"액세스 키\",\n \"Always prompt merge conflicts\": \"항상 병합 충돌 알림\",\n \"Apply Latest Change if Conflicting\": \"충돌 시 최신 변경 사항 적용\",\n \"Apply preset configuration\": \"프리셋 구성 적용\",\n \"Automatically Sync all files when opening Obsidian.\": \"Obsidian을 열 때 모든 파일을 자동으로 동기화합니다.\",\n \"Batch database update\": \"일괄 데이터베이스 업데이트\",\n \"Batch limit\": \"일괄 제한\",\n \"Batch size\": \"일괄 크기\",\n \"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.\": \"v0.17.16 이전에는 로컬 데이터베이스에 이전 어댑터를 사용했습니다. 이제는 새로운 어댑터를 권장합니다. 하지만 로컬 데이터베이스 재구축이 필요합니다. 충분한 시간이 있을 때 이 토글을 비활성화해 주세요. 활성화된 상태로 두면 원격 데이터베이스에서 가져올 때도 이를 비활성화하라는 메시지가 나타납니다.\",\n \"Bucket Name\": \"버킷 이름\",\n \"cmdConfigSync.showCustomizationSync\": \"사용자 설정 동기화 표시\",\n \"Comma separated `.gitignore, .dockerignore`\": \"쉼표로 구분된 `.gitignore, .dockerignore`\",\n \"Compute revisions for chunks\": \"청크에 대한 리비전 계산\",\n \"Data Compression\": \"데이터 압축\",\n \"Database Name\": \"데이터베이스 이름\",\n \"Database suffix\": \"데이터베이스 접미사\",\n \"Delay conflict resolution of inactive files\": \"비활성 파일의 충돌 해결 지연\",\n \"Delay merge conflict prompt for inactive files.\": \"비활성 파일의 병합 충돌 프롬프트 지연.\",\n \"Delete old metadata of deleted files on start-up\": \"시작 시 삭제된 파일의 오래된 메타데이터 삭제\",\n \"Device name\": \"기기 이름\",\n \"dialog.yourLanguageAvailable\": \"Self-hosted LiveSync에서 귀하의 언어로 번역을 제공하므로 %{Display language} 설정이 활성화되었습니다.\\n\\n참고: 모든 메시지가 번역되지는 않습니다. 귀하의 기여를 기다리고 있습니다!\\n참고 2: 이슈를 생성하는 경우 **%{lang-def}로 되돌린 후** 스크린샷, 메시지, 로그를 가져와 주세요. 이는 설정 대화 상자에서 할 수 있습니다.\\n간편하게 사용하실 수 있었으면 좋겠습니다!\",\n \"dialog.yourLanguageAvailable.btnRevertToDefault\": \"%{lang-def} 유지\",\n \"dialog.yourLanguageAvailable.Title\": \" 번역을 사용할 수 있습니다!\",\n \"Disables logging, only shows notifications. Please disable if you report an issue.\": \"로깅을 비활성화하고 알림만 표시합니다. 문제를 신고하는 경우 비활성화해 주세요.\",\n \"Display Language\": \"표시 언어\",\n \"Do not check configuration mismatch before replication\": \"복제 전 구성 불일치 확인 안 함\",\n \"Do not keep metadata of deleted files.\": \"삭제된 파일의 메타데이터를 보관하지 않습니다.\",\n \"Do not split chunks in the background\": \"백그라운드에서 청크 분할 안 함\",\n \"Do not use internal API\": \"내부 API 사용 안 함\",\n \"Doctor.Button.DismissThisVersion\": \"아니요, 다음 릴리스까지 다시 묻지 않음\",\n \"Doctor.Button.Fix\": \"수정\",\n \"Doctor.Button.FixButNoRebuild\": \"수정하지만 재구축하지 않음\",\n \"Doctor.Button.No\": \"아니요\",\n \"Doctor.Button.Skip\": \"그대로 두기\",\n \"Doctor.Button.Yes\": \"예\",\n \"Doctor.Dialogue.Main\": \"안녕하세요! ${activateReason} 로 인해 구성 진단 마법사가 활성화되었습니다!\\n그리고 일부 구성이 잠재적인 문제로 감지되었습니다.\\n안심하세요. 하나씩 해결해 봅시다.\\n\\n대상 항목은 다음과 같습니다.\\n\\n${issues}\\n\\n시작하시겠습니까?\",\n \"Doctor.Dialogue.MainFix\": \"**구성 이름:** `${name}`\\n**현재 값:** `${current}`, **이상적인 값:** `${ideal}`\\n**권장 수준:** ${level}\\n**왜 이것이 감지되었나요?**\\n${reason}\\n\\n\\n${note}\\n\\n이상적인 값으로 수정하시겠습니까?\",\n \"Doctor.Dialogue.Title\": \"Self-hosted LiveSync 구성 진단 마법사\",\n \"Doctor.Dialogue.TitleAlmostDone\": \"거의 완료되었습니다!\",\n \"Doctor.Dialogue.TitleFix\": \"문제 해결 ${current}/${total}\",\n \"Doctor.Level.Must\": \"필수\",\n \"Doctor.Level.Necessary\": \"필수\",\n \"Doctor.Level.Optional\": \"선택사항\",\n \"Doctor.Level.Recommended\": \"권장\",\n \"Doctor.Message.NoIssues\": \"문제가 감지되지 않았습니다!\",\n \"Doctor.Message.RebuildLocalRequired\": \"주의! 이를 적용하려면 로컬 데이터베이스 재구축이 필요합니다!\",\n \"Doctor.Message.RebuildRequired\": \"주의! 이를 적용하려면 재구축이 필요합니다!\",\n \"Doctor.Message.SomeSkipped\": \"일부 문제를 그대로 두었습니다. 다음 시작 시 다시 질문할까요?\",\n \"Enable advanced features\": \"고급 기능 활성화\",\n \"Enable customization sync\": \"사용자 설정 동기화 활성화\",\n \"Enable Developers' Debug Tools.\": \"개발자 디버그 도구 활성화\",\n \"Enable edge case treatment features\": \"특수 사례 처리 기능 활성화\",\n \"Enable poweruser features\": \"파워 유저 기능 활성화\",\n \"Enable this if your Object Storage doesn't support CORS\": \"객체 스토리지가 CORS를 지원하지 않는 경우 활성화하세요\",\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 \"Encrypting sensitive configuration items\": \"민감한 구성 항목 암호화\",\n \"Encryption phassphrase. If changed, you should overwrite the server's database with the new (encrypted) files.\": \"패스프레이즈는 암호화에 사용되는 긴 암호 문구입니다. 변경한 경우, 암호화된 새 파일로 서버의 데이터베이스를 덮어써야 합니다.\",\n \"End-to-End Encryption\": \"종단간 암호화\",\n \"Endpoint URL\": \"엔드포인트 URL\",\n \"Enhance chunk size\": \"청크 크기 향상\",\n \"Fetch chunks on demand\": \"필요 시 청크 원격 가져오기\",\n \"Fetch database with previous behaviour\": \"이전 동작으로 데이터베이스 가져오기\",\n \"Filename\": \"파일명\",\n \"Forces the file to be synced when opened.\": \"파일을 열 때 강제로 동기화합니다.\",\n \"Handle files as Case-Sensitive\": \"파일을 대소문자 구분으로 처리\",\n \"If disabled(toggled), chunks will be split on the UI thread (Previous behaviour).\": \"비활성화(토글)되면 청크는 UI 스레드에서 분할됩니다 (이전 동작).\",\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.\": \"활성화하면 파일별 효율적인 사용자 설정 동기화가 사용됩니다. 이를 활성화할 때 소규모 데이터 구조 전환이 필요합니다. 모든 기기를 v0.23.18로 업데이트해야 합니다. 이를 활성화하면 이전 버전과의 호환성이 사라집니다.\",\n \"If enabled, chunks will be split into no more than 100 items. However, dedupe is slightly weaker.\": \"활성화하면 청크는 최대 100개 항목으로 분할됩니다. 하지만 중복 제거 기능이 약간 약해집니다.\",\n \"If enabled, newly created chunks are temporarily kept within the document, and graduated to become independent chunks once stabilised.\": \"활성화하면 새로 생성된 변경 기록(청크)은 문서 안에 임시로 보관되며, 일정 조건을 만족하면 자동으로 문서 밖으로 분리되어 저장됩니다.\",\n \"If enabled, the file under 1kb will be processed in the UI thread.\": \"활성화하면 1kb 미만의 파일은 UI 스레드에서 처리됩니다.\",\n \"If enabled, the notification of hidden files change will be suppressed.\": \"활성화하면 숨겨진 파일 변경 알림이 억제됩니다.\",\n \"If this enabled, all chunks will be stored with the revision made from its content. (Previous behaviour)\": \"이 옵션이 활성화되면 모든 청크는 콘텐츠에서 생성된 리비전과 함께 저장됩니다. (이전 동작)\",\n \"If this enabled, All files are handled as case-Sensitive (Previous behaviour).\": \"이 옵션이 활성화되면 모든 파일이 대소문자를 구분하여 처리됩니다 (이전 동작).\",\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 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.\": \"이 옵션이 활성화되면 PouchDB는 연결을 더이상 무한히 열어두지 않고 60초 동안 유지합니다. 그 시간 내에 변경 사항이 없으면 소켓을 닫고 다시 엽니다. 프록시가 요청 지속 시간을 제한할 때 유용하지만 리소스 사용량이 증가할 수 있습니다.\",\n \"Ignore files\": \"제외 규칙 파일\",\n \"Incubate Chunks in Document\": \"문서 내 변경 기록 임시 보관\",\n \"Interval (sec)\": \"간격 (초)\",\n \"K.exp\": \"실험 기능\",\n \"K.long_p2p_sync\": \"%{title_p2p_sync} (%{exp})\",\n \"K.P2P\": \"%{Peer}-to-%{Peer}\",\n \"K.Peer\": \"피어\",\n \"K.ScanCustomization\": \"사용자 설정 검색\",\n \"K.short_p2p_sync\": \"P2P 동기화 (%{exp})\",\n \"K.title_p2p_sync\": \"피어 투 피어(P2P) 동기화\",\n \"Keep empty folder\": \"빈 폴더 유지\",\n \"lang_def\": \"Default\",\n \"lang-de\": \"Deutsche\",\n \"lang-def\": \"%{lang_def}\",\n \"lang-es\": \"Español\",\n \"lang-ja\": \"日本語\",\n \"lang-ko\": \"한국어\",\n \"lang-ru\": \"Русский\",\n \"lang-zh\": \"简体中文\",\n \"lang-zh-tw\": \"繁體中文\",\n \"LiveSync could not handle multiple vaults which have same name without different prefix, This should be automatically configured.\": \"LiveSync는 서로 다른 접두사 없이 동일한 이름을 가진 여러 볼트를 처리할 수 없습니다. 이는 자동으로 구성되어야 합니다.\",\n \"liveSyncReplicator.beforeLiveSync\": \"LiveSync 전에 OneShot을 먼저 시작합니다...\",\n \"liveSyncReplicator.cantReplicateLowerValue\": \"더 낮은 값으로 복제할 수 없습니다.\",\n \"liveSyncReplicator.checkingLastSyncPoint\": \"마지막으로 동기화된 지점을 찾고 있습니다.\",\n \"liveSyncReplicator.couldNotConnectTo\": \"${uri}에 연결할 수 없습니다: ${name} \\n(${db})\",\n \"liveSyncReplicator.couldNotConnectToRemoteDb\": \"원격 데이터베이스에 연결할 수 없습니다: ${d}\",\n \"liveSyncReplicator.couldNotConnectToServer\": \"서버에 연결할 수 없습니다.\",\n \"liveSyncReplicator.couldNotConnectToURI\": \"${uri}에 연결할 수 없습니다: ${dbRet}\",\n \"liveSyncReplicator.couldNotMarkResolveRemoteDb\": \"원격 데이터베이스를 해결됨으로 표시할 수 없습니다.\",\n \"liveSyncReplicator.liveSyncBegin\": \"LiveSync 시작...\",\n \"liveSyncReplicator.lockRemoteDb\": \"데이터 손상을 방지하기 위해 원격 데이터베이스를 잠급니다\",\n \"liveSyncReplicator.markDeviceResolved\": \"이 기기를 '해결됨'으로 표시합니다.\",\n \"liveSyncReplicator.oneShotSyncBegin\": \"OneShot 동기화 시작... (${syncMode})\",\n \"liveSyncReplicator.remoteDbCorrupted\": \"원격 데이터베이스가 더 최신이거나 손상되었습니다. 최신 버전의 self-hosted-livesync가 설치되어 있는지 확인하세요\",\n \"liveSyncReplicator.remoteDbCreatedOrConnected\": \"원격 데이터베이스가 생성되거나 연결되었습니다\",\n \"liveSyncReplicator.remoteDbDestroyed\": \"원격 데이터베이스가 삭제되었습니다\",\n \"liveSyncReplicator.remoteDbDestroyError\": \"원격 데이터베이스 삭제 중 오류가 발생했습니다:\",\n \"liveSyncReplicator.remoteDbMarkedResolved\": \"원격 데이터베이스가 해결됨으로 표시되었습니다.\",\n \"liveSyncReplicator.replicationClosed\": \"복제가 종료되었습니다\",\n \"liveSyncReplicator.replicationInProgress\": \"복제가 이미 진행 중입니다\",\n \"liveSyncReplicator.retryLowerBatchSize\": \"더 낮은 일괄 크기로 재시도: ${batch_size}/${batches_limit}\",\n \"liveSyncReplicator.unlockRemoteDb\": \"데이터 손상을 방지하기 위해 원격 데이터베이스를 잠금 해제합니다\",\n \"liveSyncSetting.errorNoSuchSettingItem\": \"해당 설정 항목이 없습니다: ${key}\",\n \"liveSyncSetting.originalValue\": \"원본: ${value}\",\n \"liveSyncSetting.valueShouldBeInRange\": \"값은 ${min} < 값 < ${max} 범위에 있어야 합니다\",\n \"liveSyncSettings.btnApply\": \"적용\",\n \"logPane.autoScroll\": \"자동 스크롤\",\n \"logPane.logWindowOpened\": \"로그 창이 열렸습니다\",\n \"logPane.pause\": \"일시 중단\",\n \"logPane.title\": \"Self-hosted LiveSync 로그\",\n \"logPane.wrap\": \"줄 바꿈\",\n \"Maximum delay for batch database updating\": \"일괄 데이터베이스 업데이트 최대 지연\",\n \"Maximum file size\": \"최대 파일 크기\",\n \"Maximum Incubating Chunk Size\": \"임시 보관 변경 기록의 최대 크기\",\n \"Maximum Incubating Chunks\": \"임시 보관 중인 변경 기록 최대 수\",\n \"Maximum Incubation Period\": \"변경 기록 임시 보관 최대 시간\",\n \"MB (0 to disable).\": \"MB (0으로 설정하면 비활성화).\",\n \"Memory cache size (by total characters)\": \"메모리 캐시 크기 (총 문자 수)\",\n \"Memory cache size (by total items)\": \"메모리 캐시 크기 (총 항목 수)\",\n \"Minimum delay for batch database updating\": \"일괄 데이터베이스 업데이트 최소 지연\",\n \"moduleCheckRemoteSize.logCheckingStorageSizes\": \"스토리지 크기 확인 중\",\n \"moduleCheckRemoteSize.logCurrentStorageSize\": \"원격 스토리지 크기: ${measuredSize}\",\n \"moduleCheckRemoteSize.logExceededWarning\": \"원격 스토리지 크기: ${measuredSize}가 ${notifySize}를 초과했습니다\",\n \"moduleCheckRemoteSize.logThresholdEnlarged\": \"임계값이 ${size}MB로 증가되었습니다\",\n \"moduleCheckRemoteSize.msgConfirmRebuild\": \"시간이 꽤 오래 걸릴 수 있습니다. 정말 지금 모든 것을 재구축하시겠습니까?\",\n \"moduleCheckRemoteSize.msgDatabaseGrowing\": \"**데이터베이스 용량이 점점 커지고 있습니다!** 하지만 걱정하지 마세요. 아직 원격 스토리지 공간이 완전히 부족해진 건 아닙니다.\\n\\n| 측정된 크기 | 설정된 한도 |\\n| --- | --- |\\n| ${estimatedSize} | ${maxSize} |\\n\\n> [!MORE]-\\n> 오랜 기간 사용했다면 참조되지 않는 청크, 즉 '쓰레기 데이터'가 쌓였을 수 있습니다. 이 경우 전체 재구성을 권장합니다. 용량이 훨씬 줄어들 수 있습니다.\\n> \\n> 단순히 볼트 자체 용량이 커지고 있는 것이라면, 먼저 파일을 정리한 후 전체를 재구성하는 것이 좋습니다. Self-hosted LiveSync는 처리 속도를 위해 삭제해도 실제 데이터를 바로 지우지 않습니다. 이 내용은 [기술 문서](https://github.com/vrtmrz/obsidian-livesync/blob/main/docs/tech_info.md)에 간략히 정리되어 있습니다.\\n> \\n> 용량 증가가 괜찮다면 알림 임계치를 100MB 단위로 높일 수 있습니다. 직접 서버를 운영하는 경우에 적합한 방법입니다. 다만, 가끔은 전체 재구성을 해주는 것이 바람직합니다.\\n\\n> [!WARNING]\\n> 전체 재구성을 실행할 경우, 모든 기기가 반드시 동기화되어 있어야 합니다. 플러그인이 최대한 병합하려고 시도하긴 하지만 완전하지 않을 수 있습니다.\",\n \"moduleCheckRemoteSize.msgSetDBCapacity\": \"**원격 스토리지 공간이 부족해지기 전에 미리 조치할 수 있도록** 데이터베이스 용량 경고를 설정할 수 있습니다.\\n이 기능을 활성화하시겠습니까?\\n\\n> [!MORE]-\\n> - 0: 스토리지 용량에 대한 경고 없음\\n> 자체 서버를 사용하는 등 여유 공간이 충분한 경우에 권장됩니다. 스토리지 용량을 직접 확인하고 수동으로 재구성할 수 있습니다.\\n> - 800: 원격 스토리지 용량이 800MB를 초과하면 경고\\n> 1GB 제한이 있는 fly.io나 IBM Cloudant 사용 시 권장됩니다.\\n> - 2000: 원격 스토리지 용량이 2GB를 초과하면 경고\\n\\n설정한 용량 한도에 도달하면, 단계적으로 경고 한도를 늘릴지 여부를 묻게 됩니다.\\n\",\n \"moduleCheckRemoteSize.option2GB\": \"2GB (표준)\",\n \"moduleCheckRemoteSize.option800MB\": \"800MB (Cloudant, fly.io)\",\n \"moduleCheckRemoteSize.optionAskMeLater\": \"나중에 물어보기\",\n \"moduleCheckRemoteSize.optionDismiss\": \"무시\",\n \"moduleCheckRemoteSize.optionIncreaseLimit\": \"${newMax}MB로 증가\",\n \"moduleCheckRemoteSize.optionNoWarn\": \"아니요, 경고하지 마세요\",\n \"moduleCheckRemoteSize.optionRebuildAll\": \"지금 모든 것 재구축\",\n \"moduleCheckRemoteSize.titleDatabaseSizeLimitExceeded\": \"원격 스토리지 크기가 제한을 초과했습니다\",\n \"moduleCheckRemoteSize.titleDatabaseSizeNotify\": \"데이터베이스 크기 알림 설정\",\n \"moduleInputUIObsidian.defaultTitleConfirmation\": \"확인\",\n \"moduleInputUIObsidian.defaultTitleSelect\": \"선택\",\n \"moduleInputUIObsidian.optionNo\": \"아니요\",\n \"moduleInputUIObsidian.optionYes\": \"예\",\n \"moduleLiveSyncMain.logAdditionalSafetyScan\": \"추가 안전 검사 중...\",\n \"moduleLiveSyncMain.logLoadingPlugin\": \"플러그인 로딩 중...\",\n \"moduleLiveSyncMain.logPluginInitCancelled\": \"모듈에 의해 플러그인 초기화가 취소되었습니다\",\n \"moduleLiveSyncMain.logPluginVersion\": \"Self-hosted LiveSync v${manifestVersion} ${packageVersion}\",\n \"moduleLiveSyncMain.logReadChangelog\": \"LiveSync가 업데이트되었습니다. 변경사항을 읽어보세요!\",\n \"moduleLiveSyncMain.logSafetyScanCompleted\": \"추가 안전 검사가 완료되었습니다\",\n \"moduleLiveSyncMain.logSafetyScanFailed\": \"모듈에서 추가 안전 검사가 실패했습니다\",\n \"moduleLiveSyncMain.logUnloadingPlugin\": \"플러그인 언로딩 중...\",\n \"moduleLiveSyncMain.logVersionUpdate\": \"LiveSync가 업데이트되었습니다. 호환성 문제가 있는 업데이트의 경우 모든 자동 동기화가 일시적으로 비활성화되었습니다. 활성화하기 전에 모든 기기가 최신 상태인지 확인하세요.\",\n \"moduleLiveSyncMain.msgScramEnabled\": \"Self-hosted LiveSync가 일부 이벤트를 무시하도록 설정되어 있습니다. 이 설정이 맞습니까?\\n\\n| 유형 | 상태 | 설명 |\\n|:---:|:---:|---|\\n| 스토리지 이벤트 | ${fileWatchingStatus} | 모든 수정 사항이 무시됩니다 |\\n| 데이터베이스 이벤트 | ${parseReplicationStatus} | 모든 동기화 변경이 지연됩니다 |\\n\\n이벤트 감지를 다시 활성화하고 Obsidian을 재시작하시겠습니까?\\n\\n> [!DETAILS]-\\n> 이러한 설정은 플러그인이 재구성 또는 데이터 가져오기 중에 자동으로 설정한 것입니다. 프로세스가 비정상적으로 종료되면 이 상태가 의도치 않게 유지될 수 있습니다.\\n> 상태가 확실하지 않다면 이 과정을 다시 실행해 보세요. 재시작 전에 반드시 볼트를 백업해 주세요.\",\n \"moduleLiveSyncMain.optionKeepLiveSyncDisabled\": \"LiveSync 비활성화 유지\",\n \"moduleLiveSyncMain.optionResumeAndRestart\": \"재개 후 Obsidian 재시작\",\n \"moduleLiveSyncMain.titleScramEnabled\": \"Scram 활성화됨\",\n \"moduleLocalDatabase.logWaitingForReady\": \"준비 대기 중...\",\n \"moduleLog.showLog\": \"로그 표시\",\n \"moduleMigration.docUri\": \"https://github.com/vrtmrz/obsidian-livesync/blob/main/README.md#how-to-use\",\n \"moduleMigration.logBulkSendCorrupted\": \"청크 일괄 전송이 활성화되었지만, 이 기능에 문제가 있었습니다. 불편을 드려 죄송합니다. 자동으로 비활성화되었습니다.\",\n \"moduleMigration.logFetchRemoteTweakFailed\": \"원격 조정 값을 가져오는데 실패했습니다\",\n \"moduleMigration.logLocalDatabaseNotReady\": \"문제가 발생했습니다! 로컬 데이터베이스가 준비되지 않았습니다\",\n \"moduleMigration.logMigratedSameBehaviour\": \"이전과 같은 방식으로 동작하도록 db:${current}로 데이터 구조 전환이 완료되었습니다\",\n \"moduleMigration.logMigrationFailed\": \"${old}에서 ${current}로의 데이터 구조 전환이 실패했거나 중단되었습니다\",\n \"moduleMigration.logRedflag2CreationFail\": \"redflag2 생성에 실패했습니다\",\n \"moduleMigration.logRemoteTweakUnavailable\": \"원격 조정 값을 가져올 수 없습니다\",\n \"moduleMigration.logSetupCancelled\": \"설정이 취소되었습니다. Self-hosted LiveSync가 설정을 기다리고 있습니다!\",\n \"moduleMigration.msgFetchRemoteAgain\": \"이미 알고 계시겠지만, Self-hosted LiveSync의 기본 동작 방식과 데이터베이스 구조가 변경되었습니다.\\n\\n다행히도 여러분의 노력 덕분에 원격 데이터베이스는 이미 성공적으로 데이터 구조 전환이 완료된 것으로 보입니다. 축하드립니다!\\n\\n하지만 아직 일부 추가 작업이 필요합니다. 이 기기의 설정이 원격 데이터베이스와 호환되지 않으므로, 원격 데이터를 다시 가져와야 합니다. 지금 원격 데이터베이스를 다시 가져오시겠습니까?\\n\\n___참고: 설정이 변경되고 데이터베이스를 다시 불러오기 전까지는 동기화가 불가능합니다.___\\n___참고2: 청크는 변경이 불가능한 구조이므로, 메타데이터와 차이점만 가져올 수 있습니다.___\",\n \"moduleMigration.msgInitialSetup\": \"이 기기는 **아직 초기 설정이 완료되지 않았습니다**. 지금부터 설정 과정을 안내해 드리겠습니다.\\n\\n모든 대화 내용은 클립보드에 복사할 수 있습니다. 나중에 참고하려면 Obsidian 노트에 붙여넣거나 번역 도구를 활용해 번역하셔도 됩니다.\\n\\n먼저, **Setup URI**를 가지고 계신가요?\\n\\n참고: Setup URI가 무엇인지 잘 모르시겠다면 [문서](${URI_DOC})를 참고해 주세요.\",\n \"moduleMigration.msgRecommendSetupUri\": \"Setup URI를 생성해 사용하는 것을 강력히 권장합니다.\\nSetup URI가 무엇인지 잘 모르시겠다면 [문서](${URI_DOC})를 참고해 주세요. 중요한 내용이니 꼭 확인하시기 바랍니다.\\n\\n직접 수동 설정을 진행하시겠습니까?\",\n \"moduleMigration.msgSinceV02321\": \"v0.23.21부터 Self-hosted LiveSync의 기본 동작 방식과 데이터베이스 구조가 변경되었습니다. 주요 변경사항은 다음과 같습니다:\\n\\n1. **파일명 대소문자 구분 처리**\\n 이제 파일명은 대소문자를 구분하지 않고 처리됩니다. 이는 파일명 구분을 제대로 지원하지 않는 Linux 및 iOS를 제외한 대부분의 플랫폼에서 유리한 변화입니다.\\n (Linux나 iOS에서는 대소문자만 다른 파일이 존재할 경우 경고가 표시됩니다)\\n\\n2. **청크 리비전 관리 방식 개선**\\n 청크는 변경 불가능한(immutable) 구조로 고정되며, 이를 통해 리비전 처리가 안정화되고 파일 저장 성능이 향상됩니다.\\n\\n___단, 위 기능을 활성화하려면 원격 및 로컬 데이터베이스를 모두 재구성해야 합니다. 이 과정은 수 분이 소요되므로 여유가 있을 때 실행하시는 것을 권장합니다.___\\n\\n- 기존 방식대로 유지하려면 `${KEEP}`을 선택해 이 과정을 건너뛸 수 있습니다.\\n- 시간이 부족하다면 `${DISMISS}`를 눌러주시면 나중에 다시 안내드리겠습니다.\\n- 이미 다른 기기에서 데이터베이스를 재구성하셨다면 `${DISMISS}`를 선택한 뒤 다시 동기화해 보세요. 차이점이 감지되면 다시 안내드리겠습니다.\",\n \"moduleMigration.optionAdjustRemote\": \"원격에 맞추기\",\n \"moduleMigration.optionDecideLater\": \"나중에 결정하기\",\n \"moduleMigration.optionEnableBoth\": \"둘 다 활성화\",\n \"moduleMigration.optionEnableFilenameCaseInsensitive\": \"#1만 활성화\",\n \"moduleMigration.optionEnableFixedRevisionForChunks\": \"#2만 활성화\",\n \"moduleMigration.optionHaveSetupUri\": \"예, 있습니다\",\n \"moduleMigration.optionKeepPreviousBehaviour\": \"이전 동작 유지\",\n \"moduleMigration.optionManualSetup\": \"모든 것을 수동으로 설정\",\n \"moduleMigration.optionNoAskAgain\": \"아니요 (나중에 다시 물어보기)\",\n \"moduleMigration.optionNoSetupUri\": \"아니요, 없습니다\",\n \"moduleMigration.optionRemindNextLaunch\": \"다음 시작 시 알림\",\n \"moduleMigration.optionSetupViaP2P\": \"%{short_p2p_sync}를 사용하여 설정\",\n \"moduleMigration.optionSetupWizard\": \"설정 마법사로 안내\",\n \"moduleMigration.optionYesFetchAgain\": \"예 (다시 가져오기)\",\n \"moduleMigration.titleCaseSensitivity\": \"대소문자 구분\",\n \"moduleMigration.titleRecommendSetupUri\": \"Setup URI 사용 권장\",\n \"moduleMigration.titleWelcome\": \"Self-hosted LiveSync에 오신 것을 환영합니다\",\n \"moduleObsidianMenu.replicate\": \"복제\",\n \"Move remotely deleted files to the trash, instead of deleting.\": \"원격에서 삭제된 파일을 삭제하는 대신 휴지통으로 이동합니다.\",\n \"Not all messages have been translated. And, please revert to \\\"Default\\\" when reporting errors.\": \"모든 메시지가 번역되지 않았습니다. 오류 신고 시 \\\"기본값\\\"으로 되돌려 주세요.\",\n \"Notify all setting files\": \"모든 설정 파일 알림\",\n \"Notify customized\": \"사용자 설정 알림\",\n \"Notify when other device has newly customized.\": \"다른 기기에서 새로운 사용자 설정이 있을 때 알림을 받습니다.\",\n \"Notify when the estimated remote storage size exceeds on start up\": \"시작 시 예상 원격 스토리지 크기가 초과되면 알림\",\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.\": \"한 번에 처리할 일괄 처리 수입니다. 기본값은 40입니다. 최소값은 2입니다. 이는 일괄 크기와 함께 메모리에 보관되는 문서 수를 제어합니다.\",\n \"Number of changes to sync at a time. Defaults to 50. Minimum is 2.\": \"한 번에 동기화할 변경 사항의 수입니다. 기본값은 50입니다. 최소값은 2입니다.\",\n \"obsidianLiveSyncSettingTab.btnApply\": \"적용\",\n \"obsidianLiveSyncSettingTab.btnCheck\": \"확인\",\n \"obsidianLiveSyncSettingTab.btnCopy\": \"복사\",\n \"obsidianLiveSyncSettingTab.btnDisable\": \"비활성화\",\n \"obsidianLiveSyncSettingTab.btnDiscard\": \"삭제\",\n \"obsidianLiveSyncSettingTab.btnEnable\": \"활성화\",\n \"obsidianLiveSyncSettingTab.btnFix\": \"수정\",\n \"obsidianLiveSyncSettingTab.btnGotItAndUpdated\": \"알겠습니다. 업데이트했습니다.\",\n \"obsidianLiveSyncSettingTab.btnNext\": \"다음\",\n \"obsidianLiveSyncSettingTab.btnStart\": \"시작\",\n \"obsidianLiveSyncSettingTab.btnTest\": \"테스트\",\n \"obsidianLiveSyncSettingTab.btnUse\": \"사용\",\n \"obsidianLiveSyncSettingTab.buttonFetch\": \"가져오기\",\n \"obsidianLiveSyncSettingTab.buttonNext\": \"다음\",\n \"obsidianLiveSyncSettingTab.defaultLanguage\": \"기본값\",\n \"obsidianLiveSyncSettingTab.descConnectSetupURI\": \"이것은 Setup URI로 Self-hosted LiveSync를 설정하는 권장 방법입니다.\",\n \"obsidianLiveSyncSettingTab.descCopySetupURI\": \"새 기기 설정에 완벽합니다!\",\n \"obsidianLiveSyncSettingTab.descEnableLiveSync\": \"위의 두 옵션 중 하나를 구성하거나 모든 구성을 수동으로 완료한 후에만 활성화하세요.\",\n \"obsidianLiveSyncSettingTab.descFetchConfigFromRemote\": \"이미 구성된 원격 서버에서 필요한 설정을 가져옵니다.\",\n \"obsidianLiveSyncSettingTab.descManualSetup\": \"권장하지 않지만 Setup URI가 없는 경우에 유용합니다\",\n \"obsidianLiveSyncSettingTab.descTestDatabaseConnection\": \"데이터베이스 연결을 엽니다. 원격 데이터베이스를 찾을 수 없고 데이터베이스 생성 권한이 있는 경우, 데이터베이스가 생성됩니다.\",\n \"obsidianLiveSyncSettingTab.descValidateDatabaseConfig\": \"데이터베이스 구성의 잠재적 문제를 확인하고 수정합니다.\",\n \"obsidianLiveSyncSettingTab.errAccessForbidden\": \"❗ 액세스가 금지되었습니다.\",\n \"obsidianLiveSyncSettingTab.errCannotContinueTest\": \"테스트를 계속할 수 없습니다.\",\n \"obsidianLiveSyncSettingTab.errCorsCredentials\": \"❗ cors.credentials가 잘못되었습니다\",\n \"obsidianLiveSyncSettingTab.errCorsNotAllowingCredentials\": \"❗ CORS에서 자격 증명을 허용하지 않습니다\",\n \"obsidianLiveSyncSettingTab.errCorsOrigins\": \"❗ cors.origins가 잘못되었습니다\",\n \"obsidianLiveSyncSettingTab.errEnableCors\": \"❗ httpd.enable_cors가 잘못되었습니다\",\n \"obsidianLiveSyncSettingTab.errMaxDocumentSize\": \"❗ couchdb.max_document_size가 낮습니다)\",\n \"obsidianLiveSyncSettingTab.errMaxRequestSize\": \"❗ chttpd.max_http_request_size가 낮습니다)\",\n \"obsidianLiveSyncSettingTab.errMissingWwwAuth\": \"❗ httpd.WWW-Authenticate가 누락되었습니다\",\n \"obsidianLiveSyncSettingTab.errRequireValidUser\": \"❗ chttpd.require_valid_user가 잘못되었습니다.\",\n \"obsidianLiveSyncSettingTab.errRequireValidUserAuth\": \"❗ chttpd_auth.require_valid_user가 잘못되었습니다.\",\n \"obsidianLiveSyncSettingTab.labelDisabled\": \"⏹️ : 비활성화됨\",\n \"obsidianLiveSyncSettingTab.labelEnabled\": \"🔁 : 활성화됨\",\n \"obsidianLiveSyncSettingTab.levelAdvanced\": \" (고급)\",\n \"obsidianLiveSyncSettingTab.levelEdgeCase\": \" (특수 사례)\",\n \"obsidianLiveSyncSettingTab.levelPowerUser\": \" (파워 유저)\",\n \"obsidianLiveSyncSettingTab.linkOpenInBrowser\": \"브라우저에서 열기\",\n \"obsidianLiveSyncSettingTab.linkPageTop\": \"페이지 상단\",\n \"obsidianLiveSyncSettingTab.linkTipsAndTroubleshooting\": \"팁 및 문제 해결\",\n \"obsidianLiveSyncSettingTab.linkTroubleshooting\": \"/docs/troubleshooting.md\",\n \"obsidianLiveSyncSettingTab.logCannotUseCloudant\": \"이 기능은 IBM Cloudant와 함께 사용할 수 없습니다.\",\n \"obsidianLiveSyncSettingTab.logCheckingConfigDone\": \"구성 확인 완료\",\n \"obsidianLiveSyncSettingTab.logCheckingConfigFailed\": \"구성 확인 실패\",\n \"obsidianLiveSyncSettingTab.logCheckingDbConfig\": \"데이터베이스 구성 확인 중\",\n \"obsidianLiveSyncSettingTab.logCheckPassphraseFailed\": \"오류: 원격 서버와 패스프레이즈 확인에 실패했습니다: \\n${db}.\",\n \"obsidianLiveSyncSettingTab.logConfiguredDisabled\": \"구성된 동기화 모드: 비활성화됨\",\n \"obsidianLiveSyncSettingTab.logConfiguredLiveSync\": \"구성된 동기화 모드: LiveSync\",\n \"obsidianLiveSyncSettingTab.logConfiguredPeriodic\": \"구성된 동기화 모드: 주기적\",\n \"obsidianLiveSyncSettingTab.logCouchDbConfigFail\": \"CouchDB 구성: ${title} 실패\",\n \"obsidianLiveSyncSettingTab.logCouchDbConfigSet\": \"CouchDB 구성: ${title} -> ${key}를 ${value}로 설정\",\n \"obsidianLiveSyncSettingTab.logCouchDbConfigUpdated\": \"CouchDB 구성: ${title} 성공적으로 업데이트됨\",\n \"obsidianLiveSyncSettingTab.logDatabaseConnected\": \"데이터베이스 연결됨\",\n \"obsidianLiveSyncSettingTab.logEncryptionNoPassphrase\": \"패스프레이즈 없이는 암호화를 활성화할 수 없습니다\",\n \"obsidianLiveSyncSettingTab.logEncryptionNoSupport\": \"기기가 암호화를 지원하지 않습니다.\",\n \"obsidianLiveSyncSettingTab.logErrorOccurred\": \"오류가 발생했습니다!\",\n \"obsidianLiveSyncSettingTab.logEstimatedSize\": \"예상 크기: ${size}\",\n \"obsidianLiveSyncSettingTab.logPassphraseInvalid\": \"패스프레이즈가 유효하지 않습니다. 수정해 주세요.\",\n \"obsidianLiveSyncSettingTab.logPassphraseNotCompatible\": \"오류: 패스프레이즈가 원격 서버와 호환되지 않습니다! 다시 확인해 주세요!\",\n \"obsidianLiveSyncSettingTab.logRebuildNote\": \"동기화가 비활성화되었습니다. 원하는 경우 가져오기 후 다시 활성화하세요.\",\n \"obsidianLiveSyncSettingTab.logSelectAnyPreset\": \"프리셋을 선택하세요.\",\n \"obsidianLiveSyncSettingTab.msgAreYouSureProceed\": \"정말로 진행하시겠습니까?\",\n \"obsidianLiveSyncSettingTab.msgChangesNeedToBeApplied\": \"변경사항을 적용해야 합니다!\",\n \"obsidianLiveSyncSettingTab.msgConfigCheck\": \"--구성 확인--\",\n \"obsidianLiveSyncSettingTab.msgConfigCheckFailed\": \"구성 확인에 실패했습니다. 그래도 계속하시겠습니까?\",\n \"obsidianLiveSyncSettingTab.msgConnectionCheck\": \"--연결 확인--\",\n \"obsidianLiveSyncSettingTab.msgConnectionProxyNote\": \"구성 확인 후에도 연결 확인에 문제가 있는 경우, 리버스 프록시 구성을 확인해 주세요.\",\n \"obsidianLiveSyncSettingTab.msgCurrentOrigin\": \"현재 원점: {origin}\",\n \"obsidianLiveSyncSettingTab.msgDiscardConfirmation\": \"정말로 기존 설정과 데이터베이스를 삭제하시겠습니까?\",\n \"obsidianLiveSyncSettingTab.msgDone\": \"--완료--\",\n \"obsidianLiveSyncSettingTab.msgEnableCors\": \"httpd.enable_cors 설정\",\n \"obsidianLiveSyncSettingTab.msgEnableEncryptionRecommendation\": \"종단간 암호화와 경로 난독화를 활성화하는 것을 권장합니다. 정말로 암호화 없이 계속하시겠습니까?\",\n \"obsidianLiveSyncSettingTab.msgFetchConfigFromRemote\": \"원격 서버에서 구성을 가져오시겠습니까?\",\n \"obsidianLiveSyncSettingTab.msgGenerateSetupURI\": \"모든 작업이 완료되었습니다! 다른 기기를 설정하기 위해 Setup URI를 생성하시겠습니까?\",\n \"obsidianLiveSyncSettingTab.msgIfConfigNotPersistent\": \"서버 설정이 영구적으로 저장되지 않는 환경(예: Docker에서 실행 중)에서는 이곳의 값들이 변경될 수 있습니다. 연결이 가능해지면 서버의 local.ini 파일에서 설정을 수동으로 업데이트해 주세요.\",\n \"obsidianLiveSyncSettingTab.msgInvalidPassphrase\": \"암호화 패스프레이즈가 유효하지 않을 수 있습니다. 정말로 계속하시겠습니까?\",\n \"obsidianLiveSyncSettingTab.msgNewVersionNote\": \"업그레이드 알림으로 여기에 오셨나요? 버전 기록을 검토해 주세요. 만족하신다면 버튼을 클릭하세요. 새로운 업데이트 시 다시 안내됩니다.\",\n \"obsidianLiveSyncSettingTab.msgNonHTTPSInfo\": \"비 HTTPS URI로 구성되었습니다. 모바일 기기에서는 작동하지 않을 수 있으니 주의하세요.\",\n \"obsidianLiveSyncSettingTab.msgNonHTTPSWarning\": \"비 HTTPS URI에 연결할 수 없습니다. 구성을 업데이트하고 다시 시도해 주세요.\",\n \"obsidianLiveSyncSettingTab.msgNotice\": \"---공지사항---\",\n \"obsidianLiveSyncSettingTab.msgObjectStorageWarning\": \"⚠️ 주의: 이 기능은 아직 개발 중(WIP)입니다. 다음 사항을 유의해 주세요:\\n- 추가 전용 구조(append-only)로 동작합니다. 저장 용량을 줄이려면 데이터 재구성이 필요합니다.\\n- 기능이 다소 불안정할 수 있습니다.\\n- 최초 동기화 시, 전체 히스토리가 원격 서버에서 전송됩니다. 데이터 용량 제한 및 느린 속도에 유의해 주세요.\\n- 실시간 동기화는 변경된 부분만 처리됩니다.\\n\\n문제가 발생했거나 개선 아이디어가 있으시면 GitHub에 이슈를 등록해 주세요.\\n기여에 깊이 감사드립니다.\",\n \"obsidianLiveSyncSettingTab.msgOriginCheck\": \"원점 확인: {org}\",\n \"obsidianLiveSyncSettingTab.msgRebuildRequired\": \"변경사항을 적용하려면 데이터베이스를 재구축해야 합니다. 아래 중 한 가지 방법을 선택해 주세요.\\n\\n<details>\\n<summary>범례</summary>\\n\\n| 기호 | 의미 |\\n|: ------ :| ------- |\\n| ⇔ | 최신 상태 |\\n| ⇄ | 동기화 균형 유지 |\\n| ⇐,⇒ | 덮어쓰기 방식의 전송 |\\n| ⇠,⇢ | 상대편에서 가져와 덮어쓰기 |\\n\\n</details>\\n\\n## ${OPTION_REBUILD_BOTH}\\n개요: 📄 ⇒¹ 💻 ⇒² 🛰️ ⇢ⁿ 💻 ⇄ⁿ⁺¹ 📄\\n이 기기의 기존 파일을 기반으로 로컬과 원격 데이터베이스를 모두 재구축합니다.\\n이 과정에서 다른 기기는 일시적으로 접근이 제한되며, 가져오기 작업을 별도로 수행해야 합니다.\\n\\n## ${OPTION_FETCH}\\n개요: 📄 ⇄² 💻 ⇐¹ 🛰️ ⇔ 💻 ⇔ 📄\\n로컬 데이터베이스를 초기화한 후, 원격 데이터베이스에서 데이터를 가져와 재구축합니다.\\n이는 원격 측에서 데이터베이스를 먼저 재구축한 경우에도 해당됩니다.\\n\\n## ${OPTION_ONLY_SETTING}\\n설정만 저장합니다. **⚠️ 주의: 이 방법은 데이터 손상을 일으킬 수 있습니다.** 일반적으로는 전체 데이터베이스 재구축이 필요합니다.\",\n \"obsidianLiveSyncSettingTab.msgSelectAndApplyPreset\": \"마법사를 완료하려면 프리셋 항목을 선택하고 적용해 주세요.\",\n \"obsidianLiveSyncSettingTab.msgSetCorsCredentials\": \"cors.credentials 설정\",\n \"obsidianLiveSyncSettingTab.msgSetCorsOrigins\": \"cors.origins 설정\",\n \"obsidianLiveSyncSettingTab.msgSetMaxDocSize\": \"couchdb.max_document_size 설정\",\n \"obsidianLiveSyncSettingTab.msgSetMaxRequestSize\": \"chttpd.max_http_request_size 설정\",\n \"obsidianLiveSyncSettingTab.msgSetRequireValidUser\": \"chttpd.require_valid_user = true로 설정\",\n \"obsidianLiveSyncSettingTab.msgSetRequireValidUserAuth\": \"chttpd_auth.require_valid_user = true로 설정\",\n \"obsidianLiveSyncSettingTab.msgSettingModified\": \"\\\"${setting}\\\" 설정이 다른 기기에서 수정되었습니다. 설정을 다시 로드하려면 {HERE}를 클릭하세요. 변경사항을 무시하려면 다른 곳을 클릭하세요.\",\n \"obsidianLiveSyncSettingTab.msgSettingsUnchangeableDuringSync\": \"동기화 중에는 이 설정들을 변경할 수 없습니다. 잠금을 해제하려면 \\\"동기화 설정\\\"에서 모든 동기화를 비활성화해 주세요.\",\n \"obsidianLiveSyncSettingTab.msgSetWwwAuth\": \"httpd.WWW-Authenticate 설정\",\n \"obsidianLiveSyncSettingTab.nameApplySettings\": \"설정 적용\",\n \"obsidianLiveSyncSettingTab.nameConnectSetupURI\": \"Setup URI로 연결\",\n \"obsidianLiveSyncSettingTab.nameCopySetupURI\": \"현재 설정을 Setup URI로 복사\",\n \"obsidianLiveSyncSettingTab.nameDisableHiddenFileSync\": \"숨김 파일 동기화 비활성화\",\n \"obsidianLiveSyncSettingTab.nameDiscardSettings\": \"기존 설정 및 데이터베이스 삭제\",\n \"obsidianLiveSyncSettingTab.nameEnableHiddenFileSync\": \"숨김 파일 동기화 활성화\",\n \"obsidianLiveSyncSettingTab.nameEnableLiveSync\": \"LiveSync 활성화\",\n \"obsidianLiveSyncSettingTab.nameHiddenFileSynchronization\": \"숨김 파일 동기화\",\n \"obsidianLiveSyncSettingTab.nameManualSetup\": \"수동 설정\",\n \"obsidianLiveSyncSettingTab.nameTestConnection\": \"연결 테스트\",\n \"obsidianLiveSyncSettingTab.nameTestDatabaseConnection\": \"데이터베이스 연결 테스트\",\n \"obsidianLiveSyncSettingTab.nameValidateDatabaseConfig\": \"데이터베이스 구성 검증\",\n \"obsidianLiveSyncSettingTab.okAdminPrivileges\": \"✔ 관리자 권한이 있습니다.\",\n \"obsidianLiveSyncSettingTab.okCorsCredentials\": \"✔ cors.credentials가 정상입니다.\",\n \"obsidianLiveSyncSettingTab.okCorsCredentialsForOrigin\": \"CORS 자격 증명 정상\",\n \"obsidianLiveSyncSettingTab.okCorsOriginMatched\": \"✔ CORS 원점 정상\",\n \"obsidianLiveSyncSettingTab.okCorsOrigins\": \"✔ cors.origins가 정상입니다.\",\n \"obsidianLiveSyncSettingTab.okEnableCors\": \"✔ httpd.enable_cors가 정상입니다.\",\n \"obsidianLiveSyncSettingTab.okMaxDocumentSize\": \"✔ couchdb.max_document_size가 정상입니다.\",\n \"obsidianLiveSyncSettingTab.okMaxRequestSize\": \"✔ chttpd.max_http_request_size가 정상입니다.\",\n \"obsidianLiveSyncSettingTab.okRequireValidUser\": \"✔ chttpd.require_valid_user가 정상입니다.\",\n \"obsidianLiveSyncSettingTab.okRequireValidUserAuth\": \"✔ chttpd_auth.require_valid_user가 정상입니다.\",\n \"obsidianLiveSyncSettingTab.okWwwAuth\": \"✔ httpd.WWW-Authenticate가 정상입니다.\",\n \"obsidianLiveSyncSettingTab.optionApply\": \"적용\",\n \"obsidianLiveSyncSettingTab.optionCancel\": \"취소\",\n \"obsidianLiveSyncSettingTab.optionCouchDB\": \"CouchDB\",\n \"obsidianLiveSyncSettingTab.optionDisableAllAutomatic\": \"모든 자동 비활성화\",\n \"obsidianLiveSyncSettingTab.optionFetchFromRemote\": \"원격에서 가져오기\",\n \"obsidianLiveSyncSettingTab.optionHere\": \"여기\",\n \"obsidianLiveSyncSettingTab.optionLiveSync\": \"LiveSync\",\n \"obsidianLiveSyncSettingTab.optionMinioS3R2\": \"Minio,S3,R2\",\n \"obsidianLiveSyncSettingTab.optionOkReadEverything\": \"네, 모든 것을 읽었습니다.\",\n \"obsidianLiveSyncSettingTab.optionOnEvents\": \"이벤트 시\",\n \"obsidianLiveSyncSettingTab.optionPeriodicAndEvents\": \"주기적 및 이벤트 시\",\n \"obsidianLiveSyncSettingTab.optionPeriodicWithBatch\": \"주기적 w/ 일괄\",\n \"obsidianLiveSyncSettingTab.optionRebuildBoth\": \"이 기기에서 둘 다 재구축\",\n \"obsidianLiveSyncSettingTab.optionSaveOnlySettings\": \"(위험) 설정만 저장\",\n \"obsidianLiveSyncSettingTab.panelChangeLog\": \"변경 로그\",\n \"obsidianLiveSyncSettingTab.panelGeneralSettings\": \"일반 설정\",\n \"obsidianLiveSyncSettingTab.panelPrivacyEncryption\": \"개인정보 보호 및 암호화\",\n \"obsidianLiveSyncSettingTab.panelRemoteConfiguration\": \"원격 구성\",\n \"obsidianLiveSyncSettingTab.panelSetup\": \"설정\",\n \"obsidianLiveSyncSettingTab.titleAppearance\": \"외관\",\n \"obsidianLiveSyncSettingTab.titleConflictResolution\": \"충돌 해결\",\n \"obsidianLiveSyncSettingTab.titleCongratulations\": \"축하합니다!\",\n \"obsidianLiveSyncSettingTab.titleCouchDB\": \"CouchDB\",\n \"obsidianLiveSyncSettingTab.titleDeletionPropagation\": \"삭제 전파\",\n \"obsidianLiveSyncSettingTab.titleEncryptionNotEnabled\": \"암호화가 활성화되지 않음\",\n \"obsidianLiveSyncSettingTab.titleEncryptionPassphraseInvalid\": \"암호화 패스프레이즈 유효하지 않음\",\n \"obsidianLiveSyncSettingTab.titleExtraFeatures\": \"추가 및 고급 기능 활성화\",\n \"obsidianLiveSyncSettingTab.titleFetchConfig\": \"구성 가져오기\",\n \"obsidianLiveSyncSettingTab.titleFetchConfigFromRemote\": \"원격 서버에서 구성 가져오기\",\n \"obsidianLiveSyncSettingTab.titleFetchSettings\": \"설정 가져오기\",\n \"obsidianLiveSyncSettingTab.titleHiddenFiles\": \"숨김 파일\",\n \"obsidianLiveSyncSettingTab.titleLogging\": \"로깅\",\n \"obsidianLiveSyncSettingTab.titleMinioS3R2\": \"Minio,S3,R2\",\n \"obsidianLiveSyncSettingTab.titleNotification\": \"알림\",\n \"obsidianLiveSyncSettingTab.titleOnlineTips\": \"온라인 팁\",\n \"obsidianLiveSyncSettingTab.titleQuickSetup\": \"빠른 설정\",\n \"obsidianLiveSyncSettingTab.titleRebuildRequired\": \"재구축 필요\",\n \"obsidianLiveSyncSettingTab.titleRemoteConfigCheckFailed\": \"원격 구성 확인 실패\",\n \"obsidianLiveSyncSettingTab.titleRemoteServer\": \"원격 서버\",\n \"obsidianLiveSyncSettingTab.titleReset\": \"리셋\",\n \"obsidianLiveSyncSettingTab.titleSetupOtherDevices\": \"다른 기기 설정\",\n \"obsidianLiveSyncSettingTab.titleSynchronizationMethod\": \"동기화 방법\",\n \"obsidianLiveSyncSettingTab.titleSynchronizationPreset\": \"동기화 프리셋\",\n \"obsidianLiveSyncSettingTab.titleSyncSettings\": \"동기화 설정\",\n \"obsidianLiveSyncSettingTab.titleSyncSettingsViaMarkdown\": \"마크다운을 통한 동기화 설정\",\n \"obsidianLiveSyncSettingTab.titleUpdateThinning\": \"업데이트 솎아내기\",\n \"obsidianLiveSyncSettingTab.warnCorsOriginUnmatched\": \"⚠ CORS 원점이 일치하지 않습니다 {from}->{to}\",\n \"obsidianLiveSyncSettingTab.warnNoAdmin\": \"⚠ 관리자 권한이 없습니다.\",\n \"P2P.AskPassphraseForDecrypt\": \"원격 피어가 구성을 공유했습니다. 구성을 복호화하려면 패스프레이즈를 입력해 주세요.\",\n \"P2P.AskPassphraseForShare\": \"원격 피어가 이 기기의 구성을 요청했습니다. 구성을 공유하려면 패스프레이즈를 입력해 주세요. 이 대화상자를 취소하여 요청을 무시할 수 있습니다.\",\n \"P2P.DisabledButNeed\": \"%{title_p2p_sync}가 비활성화되어 있습니다. 정말로 활성화하시겠습니까?\",\n \"P2P.FailedToOpen\": \"시그널링 서버에 P2P 연결을 열 수 없습니다.\",\n \"P2P.NoAutoSyncPeers\": \"자동 동기화 피어를 찾을 수 없습니다. %{long_p2p_sync} 창에서 피어를 설정해 주세요.\",\n \"P2P.NoKnownPeers\": \"피어가 감지되지 않았습니다. 다른 피어의 접속을 기다리고 있습니다...\",\n \"P2P.Note.description\": \"이 복제기는 피어 투 피어(P2P) 연결을 통해 다른 기기들과 볼트를 동기화할 수 있도록 합니다. 클라우드 서비스를 거치지 않고도 기기간 동기화를 구현할 수 있습니다.\\n\\n이 복제기는 Trystero를 기반으로 하며, 기기 간 연결을 설정하기 위해 시그널링 서버를 사용합니다. 시그널링 서버는 단순히 연결 정보를 교환하는 용도로만 사용되며, 사용자 데이터를 저장하거나 접근하지 않습니다 (또는 그래야만 합니다).\\n\\n시그널링 서버는 누구나 운영할 수 있으며, 이는 단순한 Nostr 릴레이입니다. 편의성과 복제기의 작동 확인을 위해 `vrtmrz`가 자체적으로 시그널링 서버 인스턴스를 운영 중입니다. 사용자는 `vrtmrz`가 제공하는 실험용 서버를 사용할 수도 있고, 별도로 자신만의 서버를 설정할 수도 있습니다.\\n\\n참고로, 시그널링 서버는 사용자 데이터를 저장하지 않더라도 일부 기기의 연결 정보는 볼 수 있습니다. 이 점을 유의해 주세요. 특히 타인이 운영하는 서버를 사용할 경우 주의가 필요합니다.\",\n \"P2P.Note.important_note\": \"피어 투 피어(P2P) 복제기의 실험적 구현입니다.\",\n \"P2P.Note.important_note_sub\": \"이 기능은 아직 실험 단계에 있습니다. 이 기능이 예상대로 작동하지 않을 수 있음을 알아주세요. 또한 버그, 보안 문제 및 기타 문제가 있을 수 있습니다. 이 기능을 사용할 때는 본인의 책임 하에 사용하세요. 이 기능의 개발에 기여해 주세요.\",\n \"P2P.Note.Summary\": \"이 기능은 무엇인가요? (설명과 참고사항이 적혀있습니다. 한 번 읽어보세요!)\",\n \"P2P.NotEnabled\": \"%{title_p2p_sync}가 활성화되지 않았습니다. 새로운 연결을 열 수 없습니다.\",\n \"P2P.P2PReplication\": \"%{P2P} 복제\",\n \"P2P.PaneTitle\": \"%{long_p2p_sync}\",\n \"P2P.ReplicatorInstanceMissing\": \"P2P 동기화 복제기를 찾을 수 없습니다. 구성되지 않았거나 활성화되지 않았을 수 있습니다.\",\n \"P2P.SeemsOffline\": \"피어 ${name}이(가) 오프라인인 것 같습니다. 건너뜁니다.\",\n \"P2P.SyncAlreadyRunning\": \"P2P 동기화가 이미 실행 중입니다.\",\n \"P2P.SyncCompleted\": \"P2P 동기화가 완료되었습니다.\",\n \"P2P.SyncStartedWith\": \"${name}과의 P2P 동기화가 시작되었습니다.\",\n \"Passphrase\": \"패스프레이즈\",\n \"Passphrase of sensitive configuration items\": \"민감한 구성 항목의 패스프레이즈\",\n \"password\": \"비밀번호\",\n \"Password\": \"비밀번호\",\n \"Path Obfuscation\": \"경로 난독화\",\n \"Per-file-saved customization sync\": \"파일별 저장 사용자 설정 동기화\",\n \"Periodic Sync interval\": \"주기적 동기화 간격\",\n \"Presets\": \"프리셋\",\n \"Process small files in the foreground\": \"포그라운드에서 작은 파일 처리\",\n \"RedFlag.Fetch.Method.Desc\": \"어떻게 가져오시겠습니까?\\n- %{RedFlag.Fetch.Method.FetchSafer}. (권장)\\n **낮은 트래픽**, **높은 CPU**, **낮은 위험**\\n- %{RedFlag.Fetch.Method.FetchSmoother}.\\n **낮은 트래픽**, **보통 CPU**, **낮음에서 보통 위험**\\n- %{RedFlag.Fetch.Method.FetchTraditional}.\\n **높은 트래픽**, **낮은 CPU**, **낮음에서 보통 위험**\\n\\n>[!INFO]- 세부 사항\\n> ## %{RedFlag.Fetch.Method.FetchSafer}. (권장)\\n> **낮은 트래픽**, **높은 CPU**, **낮은 위험**\\n> 이 옵션은 원격 소스에서 데이터를 가져오기 전에 기존 로컬 파일을 사용하여 로컬 데이터베이스를 먼저 생성합니다.\\n> 로컬과 원격 모두에 일치하는 파일이 있으면 둘 사이의 차이점만 전송됩니다.\\n> 하지만 두 위치 모두에 있는 파일은 초기에 충돌 파일로 처리됩니다. 실제로 충돌하지 않는다면 자동으로 해결되지만 이 과정은 시간이 걸릴 수 있습니다.\\n> 이는 일반적으로 가장 안전한 방법으로 데이터 손실 위험을 최소화합니다.\\n> ## %{RedFlag.Fetch.Method.FetchSmoother}.\\n> **낮은 트래픽**, **보통 CPU**, **낮음에서 보통 위험** (작업에 따라)\\n> 이 옵션은 먼저 로컬 파일에서 데이터베이스용 청크를 생성한 다음 데이터를 가져옵니다. 따라서 로컬에 없는 청크만 전송됩니다. 하지만 모든 메타데이터는 원격 소스에서 가져옵니다.\\n> 그런 다음 로컬 파일이 시작 시 이 메타데이터와 비교됩니다. 더 새로운 것으로 간주되는 콘텐츠가 오래된 것을 덮어씁니다(수정 시간 기준). 이 결과는 원격 데이터베이스에 다시 동기화됩니다.\\n> 로컬 파일이 실제로 최신 타임스탬프라면 일반적으로 안전합니다. 하지만 파일이 더 새로운 타임스탬프를 가지고 있지만 더 오래된 콘텐츠를 가지고 있다면(초기 `welcome.md`처럼) 문제가 발생할 수 있습니다.\\n> 이는 \\\"%{RedFlag.Fetch.Method.FetchSafer}\\\"보다 CPU를 덜 사용하고 더 빠르지만 주의 깊게 사용하지 않으면 데이터 손실로 이어질 수 있습니다.\\n> ## %{RedFlag.Fetch.Method.FetchTraditional}.\\n> **높은 트래픽**, **낮은 CPU**, **낮음에서 보통 위험** (작업에 따라)\\n> 모든 것이 원격에서 가져와집니다.\\n> %{RedFlag.Fetch.Method.FetchSmoother}와 유사하지만 모든 청크가 원격 소스에서 가져와집니다.\\n> 이는 가장 전통적인 가져오기 방법으로 일반적으로 가장 많은 네트워크 트래픽과 시간을 소모합니다. 또한 '%{RedFlag.Fetch.Method.FetchSmoother}' 옵션과 유사하게 원격 파일을 덮어쓸 위험이 있습니다.\\n> 하지만 가장 오래되고 가장 직접적인 접근 방식이기 때문에 종종 가장 안정적인 방법으로 간주됩니다.\",\n \"RedFlag.Fetch.Method.FetchSafer\": \"가져오기 전에 로컬 데이터베이스를 한 번 생성\",\n \"RedFlag.Fetch.Method.FetchSmoother\": \"가져오기 전에 로컬 파일 청크 생성\",\n \"RedFlag.Fetch.Method.FetchTraditional\": \"원격에서 모든 것 가져오기\",\n \"RedFlag.Fetch.Method.Title\": \"어떻게 가져오시겠습니까?\",\n \"Reducing the frequency with which on-disk changes are reflected into the DB\": \"디스크 변경 사항이 데이터베이스에 반영되는 빈도를 줄입니다\",\n \"Region\": \"지역\",\n \"Remote server type\": \"원격 서버 유형\",\n \"Remote Type\": \"원격 유형\",\n \"Replicator.Dialogue.Locked.Action.Dismiss\": \"재확인을 위해 취소\",\n \"Replicator.Dialogue.Locked.Action.Fetch\": \"원격 데이터베이스에서 모든 것을 다시 가져오기\",\n \"Replicator.Dialogue.Locked.Action.Unlock\": \"원격 데이터베이스 잠금 해제\",\n \"Replicator.Dialogue.Locked.Message\": \"원격 데이터베이스가 잠겨 있습니다. 이는 일부 터미널에서 데이터베이스를 재구축했기 때문입니다.\\n따라서 현재 기기는 데이터베이스 손상을 방지하기 위해 연결을 일시적으로 보류해야 합니다.\\n\\n선택할 수 있는 세 가지 방법이 있습니다:\\n\\n- %{Replicator.Dialogue.Locked.Action.Fetch}\\n 가장 권장되고 신뢰할 수 있는 방법입니다. 로컬 데이터베이스를 초기화한 뒤, 원격 데이터베이스의 전체 데이터를 다시 가져옵니다. 대부분의 경우 안전하게 수행할 수 있으나, 시간이 다소 걸리며 안정적인 네트워크 환경에서 진행해야 합니다.\\n- %{Replicator.Dialogue.Locked.Action.Unlock}\\n 이 방법은 다른 동기화 방식으로 이미 완전하고 안정적으로 동기화된 경우에만 사용할 수 있습니다. 단순히 파일이 같다는 의미가 아니므로, 확신이 없다면 사용을 피하는 것이 좋습니다.\\n- %{Replicator.Dialogue.Locked.Action.Dismiss}\\n 이번 작업을 취소하고, 다음 요청 시 다시 안내받습니다.\\n\",\n \"Replicator.Dialogue.Locked.Message.Fetch\": \"모든 것 가져오기가 예약되었습니다. 이를 수행하기 위해 플러그인이 재시작됩니다.\",\n \"Replicator.Dialogue.Locked.Message.Unlocked\": \"원격 데이터베이스 잠금이 해제되었습니다. 작업을 다시 시도해 주세요.\",\n \"Replicator.Dialogue.Locked.Title\": \"잠김\",\n \"Replicator.Message.Cleaned\": \"데이터베이스 정리가 진행 중입니다. 복제가 취소되었습니다\",\n \"Replicator.Message.InitialiseFatalError\": \"사용 가능한 복제기가 없습니다. 치명적인 오류입니다.\",\n \"Replicator.Message.Pending\": \"일부 파일 이벤트가 대기 중입니다. 복제가 취소되었습니다.\",\n \"Replicator.Message.SomeModuleFailed\": \"일부 모듈 실패로 복제가 취소되었습니다\",\n \"Replicator.Message.VersionUpFlash\": \"설정을 열고 메시지를 확인해 주세요. 복제가 취소되었습니다.\",\n \"Requires restart of Obsidian\": \"Obsidian 재시작 필요\",\n \"Requires restart of Obsidian.\": \"Obsidian 재시작이 필요합니다.\",\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 \"Scan changes on customization sync\": \"사용자 설정 동기화 시 변경 사항 검색\",\n \"Scan customization automatically\": \"사용자 설정 자동 검색\",\n \"Scan customization before replicating.\": \"복제하기 전에 사용자 설정을 검색합니다.\",\n \"Scan customization every 1 minute.\": \"1분마다 사용자 설정을 검색합니다.\",\n \"Scan customization periodically\": \"주기적으로 사용자 설정 검색\",\n \"Scan for hidden files before replication\": \"복제 전 숨겨진 파일 검색\",\n \"Scan hidden files periodically\": \"주기적으로 숨겨진 파일 검색\",\n \"Seconds, 0 to disable\": \"초 단위, 0으로 설정하면 비활성화\",\n \"Seconds. Saving to the local database will be delayed until this value after we stop typing or saving.\": \"초 단위입니다. 타이핑이나 저장을 중단한 후 이 시간동안 로컬 데이터베이스 저장이 지연됩니다.\",\n \"Secret Key\": \"시크릿 키\",\n \"Server URI\": \"서버 URI\",\n \"Setting.GenerateKeyPair.Desc\": \"키 페어를 생성했습니다!\\n\\n참고: 이 키 페어는 다시 표시되지 않습니다. 안전한 곳에 저장해 주세요. 분실하면 새 키 페어를 생성해야 합니다.\\n참고 2: 공개 키는 spki 형식이고, 개인 키는 pkcs8 형식입니다. 편의상 공개 키의 줄 바꿈은 `\\\\n`으로 변환됩니다.\\n참고 3: 공개 키는 원격 데이터베이스에서 구성되어야 하고, 개인 키는 로컬 기기에서 구성되어야 합니다.\\n\\n>[!FOR YOUR EYES ONLY]-\\n> <div class=\\\"sls-keypair\\\">\\n>\\n> ### 공개 키\\n> ```\\n${public_key}\\n> ```\\n>\\n> ### 개인 키\\n> ```\\n${private_key}\\n> ```\\n>\\n> </div>\\n\\n>[!Both for copying]-\\n>\\n> <div class=\\\"sls-keypair\\\">\\n>\\n> ```\\n${public_key}\\n${private_key}\\n> ```\\n>\\n> </div>\\n\\n\\n\",\n \"Setting.GenerateKeyPair.Title\": \"새 키 페어가 생성되었습니다!\",\n \"Setting.TroubleShooting\": \"문제 해결\",\n \"Setting.TroubleShooting.Doctor\": \"설정 진단 마법사\",\n \"Setting.TroubleShooting.Doctor.Desc\": \"최적화되지 않은 설정을 감지합니다. (데이터 구조 전환 시와 동일)\",\n \"SettingTab.Message.AskRebuild\": \"변경 사항을 적용하려면 원격 데이터베이스에서 가져와야 합니다. 계속 진행하시겠습니까?\",\n \"Setup.QRCode\": \"설정을 전송하기 위한 QR 코드를 생성했습니다. 휴대폰이나 다른 기기로 QR 코드를 스캔해 주세요.\\n참고: QR 코드는 암호화되지 않았으므로 열 때 주의하세요.\\n\\n>[!FOR YOUR EYES ONLY]-\\n> <div class=\\\"sls-qr\\\">${qr_image}</div>\",\n \"Setup.ShowQRCode\": \"QR 코드 표시\",\n \"Setup.ShowQRCode.Desc\": \"설정을 전송하기 위한 QR 코드를 표시합니다.\",\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 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 \"Show only notifications\": \"알림만 표시\",\n \"Show status as icons only\": \"아이콘으로만 상태 표시\",\n \"Show status inside the editor\": \"편집기 내부에 상태 표시\",\n \"Show status on the status bar\": \"상태 바에 상태 표시\",\n \"Show verbose log. Please enable if you report an issue.\": \"자세한 로그를 표시합니다. 문제를 신고하는 경우 활성화해 주세요.\",\n \"Starts synchronisation when a file is saved.\": \"파일이 저장될 때 동기화를 시작합니다.\",\n \"Stop reflecting database changes to storage files.\": \"데이터베이스 변경 사항을 스토리지 파일에 반영하는 것을 중단합니다.\",\n \"Stop watching for file changes.\": \"파일 변경 사항 감시를 중단합니다.\",\n \"Suppress notification of hidden files change\": \"숨겨진 파일 변경 알림 억제\",\n \"Suspend database reflecting\": \"데이터베이스 반영 일시 중단\",\n \"Suspend file watching\": \"파일 감시 일시 중단\",\n \"Sync after merging file\": \"파일 병합 후 동기화\",\n \"Sync automatically after merging files\": \"파일 병합 후 자동으로 동기화\",\n \"Sync Mode\": \"동기화 모드\",\n \"Sync on Editor Save\": \"편집기 저장 시 동기화\",\n \"Sync on File Open\": \"파일 열기 시 동기화\",\n \"Sync on Save\": \"저장 시 동기화\",\n \"Sync on Startup\": \"시작 시 동기화\",\n \"Testing only - Resolve file conflicts by syncing newer copies of the file, this can overwrite modified files. Be Warned.\": \"테스트 전용 - 파일의 새로운 사본을 동기화하여 파일 충돌을 해결하며, 수정된 파일을 덮어쓸 수 있습니다. 주의하세요.\",\n \"The delay for consecutive on-demand fetches\": \"연속 청크 요청 간 대기 시간\",\n \"The Hash algorithm for chunk IDs\": \"청크 ID용 해시 알고리즘\",\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 total size of chunks that can be incubated within the document. Chunks exceeding this size will immediately graduate to independent chunks.\": \"문서 안에 임시로 보관할 수 있는 변경 기록의 전체 크기 제한입니다. 초과 시 자동으로 분리됩니다.\",\n \"This passphrase will not be copied to another device. It will be set to `Default` until you configure it again.\": \"이 패스프레이즈는 다른 기기로 복사되지 않습니다. 다시 구성할 때까지 `기본값`으로 설정됩니다.\",\n \"TweakMismatchResolve.Action.Dismiss\": \"무시\",\n \"TweakMismatchResolve.Action.UseConfigured\": \"구성된 설정 사용\",\n \"TweakMismatchResolve.Action.UseMine\": \"원격 데이터베이스 설정 업데이트\",\n \"TweakMismatchResolve.Action.UseMineAcceptIncompatible\": \"원격 데이터베이스 설정 업데이트하지만 그대로 유지\",\n \"TweakMismatchResolve.Action.UseMineWithRebuild\": \"원격 데이터베이스 설정 업데이트하고 다시 재구축\",\n \"TweakMismatchResolve.Action.UseRemote\": \"이 기기에 설정 적용\",\n \"TweakMismatchResolve.Action.UseRemoteAcceptIncompatible\": \"이 기기에 설정 적용하지만 호환성 문제 무시\",\n \"TweakMismatchResolve.Action.UseRemoteWithRebuild\": \"이 기기에 설정 적용하고 다시 가져오기\",\n \"TweakMismatchResolve.Message.Main\": \"\\n원격 데이터베이스의 설정은 다음과 같습니다. 이 값들은 이 기기와 최소 한 번 동기화된 다른 기기에서 구성된 것입니다.\\n\\n이 설정을 사용하려면 %{TweakMismatchResolve.Action.UseConfigured}를 선택해 주세요.\\n이 기기의 설정을 유지하려면 %{TweakMismatchResolve.Action.Dismiss}를 선택해 주세요.\\n\\n${table}\\n\\n>[!TIP]\\n> 모든 설정을 동기화하려면 이 기능으로 최소 구성을 적용한 후 `마크다운을 통한 설정 동기화`를 사용해 주세요.\\n\\n${additionalMessage}\",\n \"TweakMismatchResolve.Message.MainTweakResolving\": \"구성이 원격 서버의 것과 일치하지 않습니다.\\n\\n다음 구성이 일치해야 합니다:\\n\\n${table}\\n\\n결정을 알려주세요.\\n\\n${additionalMessage}\",\n \"TweakMismatchResolve.Message.UseRemote.WarningRebuildRecommended\": \"\\n>[!NOTICE]\\n> 일부 변경사항은 호환 가능하지만 추가 스토리지 및 전송량을 소모할 수 있습니다. 재구축을 권장합니다. 하지만 현재 재구축을 수행하지 않더라도 향후 유지보수에서 구현될 수 있습니다.\\n> ***시간적 여유가 있고 안정적인 네트워크에 연결된 상태에서 적용해 주세요!***\",\n \"TweakMismatchResolve.Message.UseRemote.WarningRebuildRequired\": \"\\n>[!WARNING]\\n> 일부 원격 구성이 이 기기의 로컬 데이터베이스와 호환되지 않습니다. 로컬 데이터베이스 재구축이 필요합니다.\\n> ***시간적 여유가 있고 안정적인 네트워크에 연결된 상태에서 적용해 주세요!***\",\n \"TweakMismatchResolve.Message.WarningIncompatibleRebuildRecommended\": \"\\n>[!NOTICE]\\n> 로컬 데이터베이스와 원격 데이터베이스가 호환되지 않도록 만드는 값들이 다른 것을 감지했습니다.\\n> 일부 변경사항은 호환 가능하지만 추가 스토리지 및 전송량을 소모할 수 있습니다. 재구축을 권장합니다. 하지만 현재 재구축을 수행하지 않더라도 향후 유지보수에서 구현될 수 있습니다.\\n> 재구축을 원한다면 몇 분 이상 소요됩니다. **지금 수행해도 안전한지 확인해 주세요.**\",\n \"TweakMismatchResolve.Message.WarningIncompatibleRebuildRequired\": \"\\n>[!WARNING]\\n> 로컬 데이터베이스와 원격 데이터베이스가 호환되지 않도록 만드는 값들이 다른 것을 감지했습니다.\\n> 로컬 또는 원격 재구축이 필요합니다. 둘 다 몇 분 이상 소요됩니다. **지금 수행해도 안전한지 확인해 주세요.**\",\n \"TweakMismatchResolve.Table\": \"| 값 이름 | 이 기기 | 원격 |\\n|: --- |: ---- :|: ---- :|\\n${rows}\\n\\n\",\n \"TweakMismatchResolve.Table.Row\": \"| ${name} | ${self} | ${remote} |\",\n \"TweakMismatchResolve.Title\": \"구성 불일치 감지\",\n \"TweakMismatchResolve.Title.TweakResolving\": \"구성 불일치 감지\",\n \"TweakMismatchResolve.Title.UseRemoteConfig\": \"원격 구성 사용\",\n \"Unique name between all synchronized devices. To edit this setting, please disable customization sync once.\": \"모든 동기화된 기기 간 고유 이름입니다. 이 설정을 편집하려면 사용자 설정 동기화를 한 번 비활성화해 주세요.\",\n \"Use Custom HTTP Handler\": \"커스텀 HTTP 핸들러 사용\",\n \"Use dynamic iteration count\": \"동적 반복 횟수 사용\",\n \"Use Segmented-splitter\": \"의미 기반 분할 사용\",\n \"Use splitting-limit-capped chunk splitter\": \"분할 제한 상한 청크 분할기 사용\",\n \"Use the trash bin\": \"휴지통 사용\",\n \"Use timeouts instead of heartbeats\": \"하트비트 대신 타임아웃 사용\",\n \"username\": \"사용자명\",\n \"Username\": \"사용자명\",\n \"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 \"When you save a file in the editor, start a sync automatically\": \"편집기에서 파일을 저장할 때 자동으로 동기화를 시작합니다\",\n \"Write credentials in the file\": \"파일에 자격 증명 저장\",\n \"Write logs into the file\": \"파일에 로그 기록\"\n}\n","import ko from \"../messagesJson/ko.json\";\nexport const PartialMessages = {\n ko,\n} as const;\n","{}\n","import ru from \"../messagesJson/ru.json\";\nexport const PartialMessages = {\n ru,\n} as const;\n","{\n \"(BETA) Always overwrite with a newer file\": \"始终使用更新的文件覆盖(测试版)\",\n \"(Beta) Use ignore files\": \"(测试版)使用忽略文件\",\n \"(Days passed, 0 to disable automatic-deletion)\": \"(已过天数,0为禁用自动删除)\",\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.\": \"(例如,在线读取块)如果启用此选项,LiveSync 将直接在线读取块,而不是在本地复制块。建议增加自定义块大小\",\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.\": \"(MB)如果设置了此项,大于此大小的本地和远程文件的更改将被跳过。如果文件再次变小,将使用更新的文件\",\n \"(Mega chars)\": \"(百万字符)\",\n \"(Not recommended) If set, credentials will be stored in the file.\": \"(不建议)如果设置,凭据将存储在文件中\",\n \"(Obsolete) Use an old adapter for compatibility\": \"(已弃用)为兼容性使用旧适配器\",\n \"Access Key\": \"访问密钥\",\n \"Active Remote Configuration\": \"生效中的远程配置\",\n \"Always prompt merge conflicts\": \"始终提示合并冲突\",\n \"Analyse\": \"立即分析\",\n \"Analyse database usage\": \"分析数据库使用情况\",\n \"Analyse database usage and generate a TSV report for diagnosis yourself. You can paste the generated report with any spreadsheet you like.\": \"分析数据库使用情况并生成 TSV 报告以供您自行诊断。您可以将生成的报告粘贴到您喜欢的任何电子表格中。\",\n \"Apply Latest Change if Conflicting\": \"如果冲突则应用最新更改\",\n \"Apply preset configuration\": \"应用预设配置\",\n \"Automatically Sync all files when opening Obsidian.\": \"打开 Obsidian 时自动同步所有文件\",\n \"Batch database update\": \"批量数据库更新\",\n \"Batch limit\": \"批量限制\",\n \"Batch size\": \"批量大小\",\n \"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.\": \"在 v0.17.16 之前,我们使用旧适配器作为本地数据库。现在首选新适配器。但是,它需要重建本地数据库。请在有足够时间时禁用此开关。如果保持启用状态,并且在从远程数据库获取时,系统将要求您禁用此开关。\",\n \"Bucket Name\": \"存储桶名称\",\n \"Check\": \"立即检查\",\n \"cmdConfigSync.showCustomizationSync\": \"显示自定义同步\",\n \"Comma separated `.gitignore, .dockerignore`\": \"用逗号分隔,例如 `.gitignore, .dockerignore`\",\n \"Compute revisions for chunks\": \"为 chunks 计算修订版本(以前的行为)\",\n \"Copy Report to clipboard\": \"将报告复制到剪贴板\",\n \"Data Compression\": \"数据压缩\",\n \"Database Name\": \"数据库名称\",\n \"Database suffix\": \"数据库后缀\",\n \"Delay conflict resolution of inactive files\": \"推迟解决不活动文件\",\n \"Delay merge conflict prompt for inactive files.\": \"推迟手动解决不活动文件\",\n \"Delete old metadata of deleted files on start-up\": \"启动时删除已删除文件的旧元数据\",\n \"Device name\": \"设备名称\",\n \"dialog.yourLanguageAvailable\": \"Self-hosted LiveSync已提供您语言的翻译,因此启用了%{Display language}\\n\\n注意:并非所有消息都已翻译。我们期待您的贡献!\\n注意 2:若您创建问题报告, **请切换回%{lang-def}** ,然后截取屏幕截图、消息和日志,此操作可在设置对话框中完成\\n愿您使用顺心!\",\n \"dialog.yourLanguageAvailable.btnRevertToDefault\": \"保持%{lang-def}\",\n \"dialog.yourLanguageAvailable.Title\": \" 翻译可用!\",\n \"Disables logging, only shows notifications. Please disable if you report an issue.\": \"禁用日志记录,仅显示通知。如果您报告问题,请禁用此选项\",\n \"Display Language\": \"显示语言\",\n \"Do not check configuration mismatch before replication\": \"在复制前不检查配置不匹配\",\n \"Do not keep metadata of deleted files.\": \"不保留已删除文件的元数据 \",\n \"Do not split chunks in the background\": \"不在后台分割 chunks\",\n \"Do not use internal API\": \"不使用内部 API\",\n \"Doctor.Button.DismissThisVersion\": \"拒绝,并且直到下个版本前不再询问\",\n \"Doctor.Button.Fix\": \"修复\",\n \"Doctor.Button.FixButNoRebuild\": \"修复但不重建\",\n \"Doctor.Button.No\": \"拒绝\",\n \"Doctor.Button.Skip\": \"保持不变\",\n \"Doctor.Button.Yes\": \"确定\",\n \"Doctor.Dialogue.Main\": \"您好!配置医生已根据您的要求启动(感谢您)!!遗憾的是,检测到部分配置存在潜在问题。请放心,我们将逐一解决这些问题。\\n\\n提前告知您,我们将就以下事项进行确认:\\n\\n为数据块计算修订版本(此前行为)\\n增强块大小\\n\\n我们开始处理吗?\",\n \"Doctor.Dialogue.MainFix\": \"\\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 配置诊断\",\n \"Doctor.Dialogue.TitleAlmostDone\": \"全部完成!\",\n \"Doctor.Dialogue.TitleFix\": \"修复问题 ${current}/${total}\",\n \"Doctor.Level.Must\": \"必须\",\n \"Doctor.Level.Necessary\": \"必要\",\n \"Doctor.Level.Optional\": \"可选\",\n \"Doctor.Level.Recommended\": \"推荐\",\n \"Doctor.Message.NoIssues\": \"未发现问题!\",\n \"Doctor.Message.RebuildLocalRequired\": \"注意!需要重建本地数据库以应用此项!\",\n \"Doctor.Message.RebuildRequired\": \"注意!需要重建才能应用此项!\",\n \"Doctor.Message.SomeSkipped\": \"我们将某些问题留给了以后处理。是否要在下次启动时再次询问您?\",\n \"Doctor.RULES.E2EE_V02500.REASON\": \"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 \"Enable advanced features\": \"启用高级功能\",\n \"Enable customization sync\": \"启用自定义同步\",\n \"Enable Developers' Debug Tools.\": \"启用开发者调试工具 \",\n \"Enable edge case treatment features\": \"启用边缘情况处理功能\",\n \"Enable poweruser features\": \"启用高级用户功能\",\n \"Enable this if your Object Storage doesn't support CORS\": \"如果您的对象存储不支持 CORS,请启用此功能 \",\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 \"Encrypting sensitive configuration items\": \"加密敏感配置项\",\n \"Encryption phassphrase. If changed, you should overwrite the server's database with the new (encrypted) files.\": \"加密密码。如果更改,您应该用新的(加密的)文件覆盖服务器的数据库 \",\n \"End-to-End Encryption\": \"端到端加密\",\n \"Endpoint URL\": \"终端URL\",\n \"Enhance chunk size\": \"增大块大小\",\n \"Fetch chunks on demand\": \"按需获取块\",\n \"Fetch database with previous behaviour\": \"使用以前的行为获取数据库\",\n \"Filename\": \"文件名\",\n \"Forces the file to be synced when opened.\": \"打开文件时强制同步该文件 \",\n \"Handle files as Case-Sensitive\": \"将文件视为区分大小写\",\n \"If disabled(toggled), chunks will be split on the UI thread (Previous behaviour).\": \"如果禁用(切换),chunks 将在 UI 线程上分割(以前的行为)\",\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.\": \"如果启用,将使用基于文件的、高效的自定义同步。启用此功能需要进行一次小的迁移。所有设备都应更新到 v0.23.18。一旦启用此功能,我们将失去与旧版本的兼容性\",\n \"If enabled, chunks will be split into no more than 100 items. However, dedupe is slightly weaker.\": \"如果启用,数据块将被分割成不超过 100 项。但是,去重效果会稍弱\",\n \"If enabled, newly created chunks are temporarily kept within the document, and graduated to become independent chunks once stabilised.\": \"如果启用,新创建的数据块将暂时保留在文档中,并在稳定后成为独立数据块\",\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 file under 1kb will be processed in the UI thread.\": \"如果启用,小于 1kb 的文件将在 UI 线程中处理\",\n \"If enabled, the notification of hidden files change will be suppressed.\": \"如果启用,将不再通知隐藏文件被更改\",\n \"If this enabled, all chunks will be stored with the revision made from its content. (Previous behaviour)\": \"如果启用,所有 chunks 将使用根据其内容生成的修订版本存储(以前的行为)\",\n \"If this enabled, All files are handled as case-Sensitive (Previous behaviour).\": \"如果启用,所有文件都将视为区分大小写(以前的行为)\",\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 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.\": \"如果启用此选项,PouchDB 将保持连接打开 60 秒,如果在此时间内没有更改到达,则关闭并重新打开套接字,而不是无限期保持打开。当代理限制请求持续时间时有用,但可能会增加资源使用ß\",\n \"Ignore files\": \"忽略文件\",\n \"Incubate Chunks in Document\": \"在文档中孵化块\",\n \"Interval (sec)\": \"间隔(秒)\",\n \"K.exp\": \"实验性\",\n \"K.long_p2p_sync\": \"%{title_p2p_sync} (%{exp})\",\n \"K.P2P\": \"%{Peer}-to-%{Peer}\",\n \"K.Peer\": \"Peer\",\n \"K.ScanCustomization\": \"扫描自定义\",\n \"K.short_p2p_sync\": \"P2P同步(%{exp})\",\n \"K.title_p2p_sync\": \"Peer-to-Peer同步\",\n \"Keep empty folder\": \"保留空文件夹\",\n \"lang_def\": \"Default\",\n \"lang-de\": \"Deutsche\",\n \"lang-def\": \"%{lang_def}\",\n \"lang-es\": \"Español\",\n \"lang-ja\": \"日本語\",\n \"lang-ko\": \"한국어\",\n \"lang-ru\": \"Русский\",\n \"lang-zh\": \"简体中文\",\n \"lang-zh-tw\": \"繁體中文\",\n \"LiveSync could not handle multiple vaults which have same name without different prefix, This should be automatically configured.\": \"LiveSync 无法处理具有相同名称但没有不同前缀的多个库。这应该自动配置\",\n \"liveSyncReplicator.beforeLiveSync\": \"在LiveSync前,先启动OneShot一次...\",\n \"liveSyncReplicator.cantReplicateLowerValue\": \"我们无法复制更小的值\",\n \"liveSyncReplicator.checkingLastSyncPoint\": \"查找上次同步点\",\n \"liveSyncReplicator.couldNotConnectTo\": \"无法连接到 ${uri} : ${name}\\n(${db})\",\n \"liveSyncReplicator.couldNotConnectToRemoteDb\": \"无法连接到远程数据库:${d}\",\n \"liveSyncReplicator.couldNotConnectToServer\": \"无法连接到服务器\",\n \"liveSyncReplicator.couldNotConnectToURI\": \"无法连接到 ${uri}:${dbRet}\",\n \"liveSyncReplicator.couldNotMarkResolveRemoteDb\": \"无法标记并解决远程数据库\",\n \"liveSyncReplicator.liveSyncBegin\": \"LiveSync 开始...\",\n \"liveSyncReplicator.lockRemoteDb\": \"锁定远程数据库以防止数据损坏\",\n \"liveSyncReplicator.markDeviceResolved\": \"将此设备标记为“已解决”\",\n \"liveSyncReplicator.oneShotSyncBegin\": \"OneShot同步开始...(${syncMode})\",\n \"liveSyncReplicator.remoteDbCorrupted\": \"远程数据库较新或已损坏,请确保已安装最新版本的self-hosted-livesync\",\n \"liveSyncReplicator.remoteDbCreatedOrConnected\": \"远程数据库已创建或连接\",\n \"liveSyncReplicator.remoteDbDestroyed\": \"远程数据库已销毁\",\n \"liveSyncReplicator.remoteDbDestroyError\": \"远程数据库销毁时发生错误:\",\n \"liveSyncReplicator.remoteDbMarkedResolved\": \"远程数据库已标记为已解决\",\n \"liveSyncReplicator.replicationClosed\": \"同步已关闭\",\n \"liveSyncReplicator.replicationInProgress\": \"同步正在进行中\",\n \"liveSyncReplicator.retryLowerBatchSize\": \"使用更小的批量大小重试:${batch_size}/${batches_limit}\",\n \"liveSyncReplicator.unlockRemoteDb\": \"解锁远程数据库以防止数据损坏\",\n \"liveSyncSetting.errorNoSuchSettingItem\": \"没有此设置项:${key}\",\n \"liveSyncSetting.originalValue\": \"原始值:${value}\",\n \"liveSyncSetting.valueShouldBeInRange\": \"值应该在 ${min} < value < ${max} 之间\",\n \"liveSyncSettings.btnApply\": \"应用\",\n \"logPane.autoScroll\": \"自动滚动\",\n \"logPane.logWindowOpened\": \"日志窗口已打开\",\n \"logPane.pause\": \"暂停\",\n \"logPane.title\": \"Self-hosted LiveSync 日志\",\n \"logPane.wrap\": \"自动换行\",\n \"Maximum delay for batch database updating\": \"批量数据库更新的最大延迟\",\n \"Maximum file size\": \"最大文件大小\",\n \"Maximum Incubating Chunk Size\": \"最大孵化块大小\",\n \"Maximum Incubating Chunks\": \"最大孵化块数\",\n \"Maximum Incubation Period\": \"最大孵化期\",\n \"MB (0 to disable).\": \"MB(0为禁用)\",\n \"Memory cache size (by total characters)\": \"内存缓存大小(按总字符数)\",\n \"Memory cache size (by total items)\": \"内存缓存大小(按总项目数)\",\n \"Minimum delay for batch database updating\": \"批量数据库更新的最小延迟\",\n \"Minimum interval for syncing\": \"同步最小间隔\",\n \"moduleCheckRemoteSize.logCheckingStorageSizes\": \"正在检查存储大小\",\n \"moduleCheckRemoteSize.logCurrentStorageSize\": \"远程存储大小:${measuredSize}\",\n \"moduleCheckRemoteSize.logExceededWarning\": \"远程存储大小:${measuredSize} 超过 ${notifySize}\",\n \"moduleCheckRemoteSize.logThresholdEnlarged\": \"阈值已扩大到 ${size}MB\",\n \"moduleCheckRemoteSize.msgConfirmRebuild\": \"这可能需要一些时间。您真的想现在重建所有内容吗?\",\n \"moduleCheckRemoteSize.msgDatabaseGrowing\": \"**您的数据库正在变大!** 但别担心,我们现在可以解决它。在远程存储空间用完之前还有时间。\\n\\n| 测量大小 | 配置大小 |\\n| --- | --- |\\n| ${estimatedSize} | ${maxSize} |\\n\\n> [!MORE]-\\n> 如果您已经使用了很多年,数据库中可能会积累未引用的 chunks——也就是垃圾。因此,我们建议重建所有内容。它可能会变得小得多。\\n> \\n> 如果您的库容量只是在增加,最好在整理文件后重建所有内容。即使您为了加速过程删除了文件,Self-hosted LiveSync 也不会删除实际数据。这大致[有文档记录](https://github.com/vrtmrz/obsidian-livesync/blob/main/docs/tech_info.md)。\\n> \\n> 如果您不介意增加,可以将通知限制增加 100MB。如果您在自己的服务器上运行,就是这种情况。但是,最好还是不时地重建所有内容。\\n> \\n\\n> [!WARNING]\\n> 如果您执行重建所有内容,请确保所有设备都已同步。尽管如此,插件会尽可能地合并\\n\",\n \"moduleCheckRemoteSize.msgSetDBCapacity\": \"我们可以设置一个最大数据库容量警告,**以便在远程存储空间耗尽前采取行动**。\\n您想启用这个功能吗?\\n\\n> [!MORE]-\\n> - 0: 不警告存储大小。\\n> 如果您在远程存储(尤其是自托管)上有足够的空间,则推荐此选项。您可以手动检查存储大小并重建。\\n> - 800: 如果远程存储大小超过 800MB 则发出警告。\\n> 如果您使用的是 fly.io(1GB 限制) 或 IBM Cloudant,则推荐此选项。\\n> - 2000: 如果远程存储大小超过 2GB 则发出警告。\\n\\n如果达到限制,系统会要求我们逐步增大限制\\n\",\n \"moduleCheckRemoteSize.option2GB\": \"2GB (标准)\",\n \"moduleCheckRemoteSize.option800MB\": \"800MB (Cloudant, fly.io)\",\n \"moduleCheckRemoteSize.optionAskMeLater\": \"稍后问我\",\n \"moduleCheckRemoteSize.optionDismiss\": \"忽略\",\n \"moduleCheckRemoteSize.optionIncreaseLimit\": \"增加到 ${newMax}MB\",\n \"moduleCheckRemoteSize.optionNoWarn\": \"不,请永远不要警告\",\n \"moduleCheckRemoteSize.optionRebuildAll\": \"立即重建所有内容\",\n \"moduleCheckRemoteSize.titleDatabaseSizeLimitExceeded\": \"远程存储大小超出限制\",\n \"moduleCheckRemoteSize.titleDatabaseSizeNotify\": \"设置数据库大小通知\",\n \"moduleInputUIObsidian.defaultTitleConfirmation\": \"确认\",\n \"moduleInputUIObsidian.defaultTitleSelect\": \"选择\",\n \"moduleInputUIObsidian.optionNo\": \"否\",\n \"moduleInputUIObsidian.optionYes\": \"是\",\n \"moduleLiveSyncMain.logAdditionalSafetyScan\": \"额外的安全扫描...\",\n \"moduleLiveSyncMain.logLoadingPlugin\": \"正在加载插件...\",\n \"moduleLiveSyncMain.logPluginInitCancelled\": \"插件初始化被某个模块取消\",\n \"moduleLiveSyncMain.logPluginVersion\": \"Self-hosted LiveSync v${manifestVersion} ${packageVersion}\",\n \"moduleLiveSyncMain.logReadChangelog\": \"LiveSync 已更新,请阅读更新日志!\",\n \"moduleLiveSyncMain.logSafetyScanCompleted\": \"额外的安全扫描完成\",\n \"moduleLiveSyncMain.logSafetyScanFailed\": \"额外的安全扫描在某个模块上失败\",\n \"moduleLiveSyncMain.logUnloadingPlugin\": \"正在卸载插件...\",\n \"moduleLiveSyncMain.logVersionUpdate\": \"LiveSync 已更新,如果存在破坏性更新,所有自动同步已暂时禁用。请确保所有设备都更新到最新版本后再启用\",\n \"moduleLiveSyncMain.msgScramEnabled\": \"Self-hosted LiveSync 已被配置为忽略某些事件。这样对吗?\\n\\n| 类型 | 状态 | 说明 |\\n|:---:|:---:|---|\\n| 存储事件 | ${fileWatchingStatus} | 所有修改都将被忽略 |\\n| 数据库事件 | ${parseReplicationStatus} | 所有同步的更改都将被推迟 |\\n\\n您想恢复它们并重启 Obsidian 吗?\\n\\n> [!DETAILS]-\\n> 这些标志是在重建或获取时由插件设置的。如果过程异常结束,它们可能会被无意中保留。\\n> 如果您不确定,可以尝试重新运行这些过程。请确保备份您的库。\\n\",\n \"moduleLiveSyncMain.optionKeepLiveSyncDisabled\": \"保持 LiveSync 禁用\",\n \"moduleLiveSyncMain.optionResumeAndRestart\": \"恢复并重启 Obsidian\",\n \"moduleLiveSyncMain.titleScramEnabled\": \"紧急停止已启用\",\n \"moduleLocalDatabase.logWaitingForReady\": \"等待就绪...\",\n \"moduleLog.showLog\": \"显示日志\",\n \"moduleMigration.docUri\": \"https://github.com/vrtmrz/obsidian-livesync/blob/main/docs/zh/README_zh.md#%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8\",\n \"moduleMigration.fix0256.buttons.checkItLater\": \"稍后检查\",\n \"moduleMigration.fix0256.buttons.DismissForever\": \"我已经修复了,不再询问\",\n \"moduleMigration.fix0256.buttons.fix\": \"修复\",\n \"moduleMigration.fix0256.message\": \"由于最近的一个 bug(在 v0.25.6 版本中),某些文件可能未正确保存到同步数据库中\\n我们已经扫描了文件,并发现一些需要修复的文件\\n\\n**准备修复的文件:**\\n\\n${files}\\n\\n这些文件在存储中与原文件的大小匹配,可能是可恢复的\\n我们可以使用它们修复数据库,请点击下方的“修复”按钮进行修复\\n\\n${messageUnrecoverable}\\n\\n\\n如果你希望再次执行此操作,可以前往 Hatch 页面进行操作\\n\",\n \"moduleMigration.fix0256.messageUnrecoverable\": \"**无法在此设备上修复的文件:**\\n\\n${filesNotRecoverable}\\n\\n这些文件的元数据不一致,无法在此设备上修复(大多数情况下我们无法确定哪一个是正确的)\\n要恢复它们,请检查你的其他设备(同样使用此功能),或从备份中手动恢复\\n\",\n \"moduleMigration.fix0256.title\": \"检测到损坏的文件\",\n \"moduleMigration.insecureChunkExist.buttons.fetch\": \"我已经重建了远程数据库,将从远程获取\",\n \"moduleMigration.insecureChunkExist.buttons.later\": \"我稍后再做\",\n \"moduleMigration.insecureChunkExist.buttons.rebuild\": \"重建所有内容\",\n \"moduleMigration.insecureChunkExist.laterMessage\": \"我们强烈建议尽快处理此问题!\",\n \"moduleMigration.insecureChunkExist.message\": \"一些块未安全存储,并且在数据库中未加密\\n**请重建数据库以修复此问题**.\\n\\n如果你的远程数据库未配置 SSL,或者使用了不安全的凭据 **你可能面临暴露敏感数据的风险**.\\n\\n注意:请在所有设备上将 Self-hosted LiveSync 升级到 v0.25.6 或更高版本,并确保备份你的保险库\\n\\n注意2:重建所有内容和获取操作会消耗一些时间和流量,请在非高峰时段进行,并确保网络连接稳定\\n\",\n \"moduleMigration.insecureChunkExist.title\": \"发现不安全的块!\",\n \"moduleMigration.logBulkSendCorrupted\": \"已启用批量发送 chunks,但此功能已损坏。给您带来不便,我们深表歉意。已自动禁用\",\n \"moduleMigration.logFetchRemoteTweakFailed\": \"获取远程调整值失败\",\n \"moduleMigration.logLocalDatabaseNotReady\": \"出错了!本地数据库尚未准备好\",\n \"moduleMigration.logMigratedSameBehaviour\": \"已迁移到 db:${current},行为与之前相同\",\n \"moduleMigration.logMigrationFailed\": \"从 ${old} 到 ${current} 的迁移失败或已取消\",\n \"moduleMigration.logRedflag2CreationFail\": \"创建 redflag2 失败\",\n \"moduleMigration.logRemoteTweakUnavailable\": \"无法获取远程调整值\",\n \"moduleMigration.logSetupCancelled\": \"设置已取消,Self-hosted LiveSync 正在等待您的设置!\",\n \"moduleMigration.msgFetchRemoteAgain\": \"您可能已经知道,Self-hosted LiveSync 更改了其默认行为和数据库结构。\\n\\n值得庆幸的是,在您的时间和努力下,远程数据库似乎已经迁移完成。恭喜!\\n\\n但是,我们还需要一点点操作。此设备的配置与远程数据库不兼容。我们需要再次从远程数据库获取。我们现在应该再次从远程获取吗?\\n\\n___注意:在更改配置并再次获取数据库之前,我们无法进行同步。___\\n___注意2:chunks 是完全不可变的,我们只能获取元数据和差异\",\n \"moduleMigration.msgInitialSetup\": \"您的设备**尚未设置**。让我引导您完成设置过程。\\n\\n请记住,每个对话框内容都可以复制到剪贴板。如果以后需要参考,可以将其粘贴到 Obsidian 的笔记中。您也可以使用翻译工具将其翻译成您的语言。\\n\\n首先,您有**设置 URI** 吗?\\n\\n注意:如果您不知道这是什么,请参阅[文档](${URI_DOC})\",\n \"moduleMigration.msgRecommendSetupUri\": \"我们强烈建议您生成一个设置 URI 并使用它。\\n如果您对此不了解,请参阅[文档](${URI_DOC})(再次抱歉,但这很重要)。\\n\\n您想如何手动设置?\",\n \"moduleMigration.msgSinceV02321\": \"自 v0.23.21 起,Self-hosted LiveSync 更改了默认行为和数据库结构。进行了以下更改:\\n\\n1. **文件名的区分大小写** \\n现在处理文件名时不区分大小写。这对于大多数平台来说是一个有益的更改,除了 Linux 和 iOS,它们不能有效地管理文件名的大小写敏感性。\\n(在这些平台上,对于名称相同但大小写不同的文件将显示警告)。\\n\\n2. **chunks 的版本处理** \\nchunks 是不可变的,这使得它们的版本可以固定。此更改将提高文件保存的性能。\\n\\n___然而,要启用这些更改中的任何一个,都需要重建远程和本地数据库。这个过程需要几分钟,我们建议您在有充足时间时进行。___\\n\\n- 如果您希望保持以前的行为,可以使用 `${KEEP}` 跳过此过程。\\n- 如果您没有足够的时间,请选择 `${DISMISS}`。稍后会再次提示您。\\n- 如果您已在另一台设备上重建了数据库,请选择 `${DISMISS}` 并尝试再次同步。由于检测到差异,系统会再次提示您\",\n \"moduleMigration.optionAdjustRemote\": \"调整到远程设置\",\n \"moduleMigration.optionDecideLater\": \"稍后决定\",\n \"moduleMigration.optionEnableBoth\": \"启用两者\",\n \"moduleMigration.optionEnableFilenameCaseInsensitive\": \"仅启用 #1\",\n \"moduleMigration.optionEnableFixedRevisionForChunks\": \"仅启用 #2\",\n \"moduleMigration.optionHaveSetupUri\": \"是的,我有\",\n \"moduleMigration.optionKeepPreviousBehaviour\": \"保持以前的行为\",\n \"moduleMigration.optionManualSetup\": \"全部手动设置\",\n \"moduleMigration.optionNoAskAgain\": \"不,请稍后再次询问\",\n \"moduleMigration.optionNoSetupUri\": \"不,我没有\",\n \"moduleMigration.optionRemindNextLaunch\": \"下次启动时提醒我\",\n \"moduleMigration.optionSetupViaP2P\": \"Use %{short_p2p_sync} to set up\",\n \"moduleMigration.optionSetupWizard\": \"带我进入设置向导\",\n \"moduleMigration.optionYesFetchAgain\": \"是的,再次获取\",\n \"moduleMigration.titleCaseSensitivity\": \"大小写敏感性\",\n \"moduleMigration.titleRecommendSetupUri\": \"推荐使用设置 URI\",\n \"moduleMigration.titleWelcome\": \"欢迎使用 Self-hosted LiveSync\",\n \"moduleObsidianMenu.replicate\": \"复制\",\n \"Move remotely deleted files to the trash, instead of deleting.\": \"将远程删除的文件移至回收站,而不是直接删除\",\n \"Not all messages have been translated. And, please revert to \\\"Default\\\" when reporting errors.\": \"并非所有消息都已翻译。请在报告错误时恢复为\\\"默认\\\"\",\n \"Notify all setting files\": \"通知所有设置文件\",\n \"Notify customized\": \"通知自定义设置\",\n \"Notify when other device has newly customized.\": \"当其他设备有新的自定义设置时通知 \",\n \"Notify when the estimated remote storage size exceeds on start up\": \"启动时当估计的远程存储大小超出时通知\",\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.\": \"一次处理的批量数量。默认为 40。最小为 2。此设置与批量大小一起控制一次在内存中保留多少文档\",\n \"Number of changes to sync at a time. Defaults to 50. Minimum is 2.\": \"一次同步的更改数量。默认为 50。最小为 2。\",\n \"obsidianLiveSyncSettingTab.btnApply\": \"应用\",\n \"obsidianLiveSyncSettingTab.btnCheck\": \"检查\",\n \"obsidianLiveSyncSettingTab.btnCopy\": \"复制\",\n \"obsidianLiveSyncSettingTab.btnDisable\": \"禁用\",\n \"obsidianLiveSyncSettingTab.btnDiscard\": \"丢弃\",\n \"obsidianLiveSyncSettingTab.btnEnable\": \"启用\",\n \"obsidianLiveSyncSettingTab.btnFix\": \"修复\",\n \"obsidianLiveSyncSettingTab.btnGotItAndUpdated\": \"我明白了并且已更新\",\n \"obsidianLiveSyncSettingTab.btnNext\": \"下一步\",\n \"obsidianLiveSyncSettingTab.btnStart\": \"开始\",\n \"obsidianLiveSyncSettingTab.btnTest\": \"测试\",\n \"obsidianLiveSyncSettingTab.btnUse\": \"使用\",\n \"obsidianLiveSyncSettingTab.buttonFetch\": \"获取\",\n \"obsidianLiveSyncSettingTab.buttonNext\": \"下一步\",\n \"obsidianLiveSyncSettingTab.defaultLanguage\": \"默认\",\n \"obsidianLiveSyncSettingTab.descConnectSetupURI\": \"这是使用设置 URI 设置 Self-hosted LiveSync 的推荐方法\",\n \"obsidianLiveSyncSettingTab.descCopySetupURI\": \"非常适合设置新设备!\",\n \"obsidianLiveSyncSettingTab.descEnableLiveSync\": \"仅在配置了上述两个选项之一或手动完成所有配置后启用此选项\",\n \"obsidianLiveSyncSettingTab.descFetchConfigFromRemote\": \"从已配置的远程服务器获取必要的设置\",\n \"obsidianLiveSyncSettingTab.descManualSetup\": \"不推荐,但如果您没有设置 URI 则很有用\",\n \"obsidianLiveSyncSettingTab.descTestDatabaseConnection\": \"打开数据库连接。如果未找到远程数据库并且您有创建数据库的权限,则将创建数据库\",\n \"obsidianLiveSyncSettingTab.descValidateDatabaseConfig\": \"检查并修复数据库配置中的任何潜在问题\",\n \"obsidianLiveSyncSettingTab.errAccessForbidden\": \"❗ 访问被禁止\",\n \"obsidianLiveSyncSettingTab.errCannotContinueTest\": \"我们无法继续测试。\",\n \"obsidianLiveSyncSettingTab.errCorsCredentials\": \"❗ cors.credentials 设置错误\",\n \"obsidianLiveSyncSettingTab.errCorsNotAllowingCredentials\": \"❗ CORS 不允许凭据\",\n \"obsidianLiveSyncSettingTab.errCorsOrigins\": \"❗ cors.origins 设置错误\",\n \"obsidianLiveSyncSettingTab.errEnableCors\": \"❗ httpd.enable_cors 设置错误\",\n \"obsidianLiveSyncSettingTab.errEnableCorsChttpd\": \"❗ chttpd.enable_cors 设置错误\",\n \"obsidianLiveSyncSettingTab.errMaxDocumentSize\": \"❗ couchdb.max_document_size 设置过低)\",\n \"obsidianLiveSyncSettingTab.errMaxRequestSize\": \"❗ chttpd.max_http_request_size 设置过低)\",\n \"obsidianLiveSyncSettingTab.errMissingWwwAuth\": \"❗ 缺少 httpd.WWW-Authenticate 设置\",\n \"obsidianLiveSyncSettingTab.errRequireValidUser\": \"❗ chttpd.require_valid_user 设置错误\",\n \"obsidianLiveSyncSettingTab.errRequireValidUserAuth\": \"❗ chttpd_auth.require_valid_user 设置错误\",\n \"obsidianLiveSyncSettingTab.labelDisabled\": \"⏹️ : 已禁用\",\n \"obsidianLiveSyncSettingTab.labelEnabled\": \"🔁 : 已启用\",\n \"obsidianLiveSyncSettingTab.levelAdvanced\": \"(进阶)\",\n \"obsidianLiveSyncSettingTab.levelEdgeCase\": \"(边缘情况)\",\n \"obsidianLiveSyncSettingTab.levelPowerUser\": \"(高级用户)\",\n \"obsidianLiveSyncSettingTab.linkOpenInBrowser\": \"在浏览器中打开\",\n \"obsidianLiveSyncSettingTab.linkPageTop\": \"页面顶部\",\n \"obsidianLiveSyncSettingTab.linkTipsAndTroubleshooting\": \"提示和故障排除\",\n \"obsidianLiveSyncSettingTab.linkTroubleshooting\": \"/docs/troubleshooting.md\",\n \"obsidianLiveSyncSettingTab.logCannotUseCloudant\": \"此功能不能与 IBM Cloudant 一起使用 \",\n \"obsidianLiveSyncSettingTab.logCheckingConfigDone\": \"配置检查完成\",\n \"obsidianLiveSyncSettingTab.logCheckingConfigFailed\": \"配置检查失败\",\n \"obsidianLiveSyncSettingTab.logCheckingDbConfig\": \"正在检查数据库配置\",\n \"obsidianLiveSyncSettingTab.logCheckPassphraseFailed\": \"错误:无法使用远程服务器检查密码:\\n${db} \",\n \"obsidianLiveSyncSettingTab.logConfiguredDisabled\": \"配置的同步模式:已禁用\",\n \"obsidianLiveSyncSettingTab.logConfiguredLiveSync\": \"配置的同步模式:LiveSync\",\n \"obsidianLiveSyncSettingTab.logConfiguredPeriodic\": \"配置的同步模式:定期\",\n \"obsidianLiveSyncSettingTab.logCouchDbConfigFail\": \"CouchDB 配置:${title} 失败\",\n \"obsidianLiveSyncSettingTab.logCouchDbConfigSet\": \"CouchDB 配置:${title} -> 设置 ${key} 为 ${value}\",\n \"obsidianLiveSyncSettingTab.logCouchDbConfigUpdated\": \"CouchDB 配置:${title} 成功更新\",\n \"obsidianLiveSyncSettingTab.logDatabaseConnected\": \"数据库已连接\",\n \"obsidianLiveSyncSettingTab.logEncryptionNoPassphrase\": \"没有密码无法启用加密\",\n \"obsidianLiveSyncSettingTab.logEncryptionNoSupport\": \"您的设备不支持加密 \",\n \"obsidianLiveSyncSettingTab.logErrorOccurred\": \"发生错误!!\",\n \"obsidianLiveSyncSettingTab.logEstimatedSize\": \"估计大小:${size}\",\n \"obsidianLiveSyncSettingTab.logPassphraseInvalid\": \"密码无效,请修正\",\n \"obsidianLiveSyncSettingTab.logPassphraseNotCompatible\": \"错误:密码与远程服务器不兼容!请再次检查!\",\n \"obsidianLiveSyncSettingTab.logRebuildNote\": \"同步已禁用,如果需要,请获取并重新启用\",\n \"obsidianLiveSyncSettingTab.logSelectAnyPreset\": \"选择任何预设\",\n \"obsidianLiveSyncSettingTab.msgAreYouSureProceed\": \"您确定要继续吗?\",\n \"obsidianLiveSyncSettingTab.msgChangesNeedToBeApplied\": \"需要应用更改!\",\n \"obsidianLiveSyncSettingTab.msgConfigCheck\": \"--配置检查--\",\n \"obsidianLiveSyncSettingTab.msgConfigCheckFailed\": \"配置检查失败。您仍要继续吗?\",\n \"obsidianLiveSyncSettingTab.msgConnectionCheck\": \"--连接检查--\",\n \"obsidianLiveSyncSettingTab.msgConnectionProxyNote\": \"如果您在连接检查时遇到问题(即使检查了配置后),请检查您的反向代理配置\",\n \"obsidianLiveSyncSettingTab.msgCurrentOrigin\": \"当前源: {origin}\",\n \"obsidianLiveSyncSettingTab.msgDiscardConfirmation\": \"您真的要丢弃现有的设置和数据库吗?\",\n \"obsidianLiveSyncSettingTab.msgDone\": \"--完成--\",\n \"obsidianLiveSyncSettingTab.msgEnableCors\": \"设置 httpd.enable_cors\",\n \"obsidianLiveSyncSettingTab.msgEnableCorsChttpd\": \"设置 chttpd.enable_cors\",\n \"obsidianLiveSyncSettingTab.msgEnableEncryptionRecommendation\": \"我们建议启用端到端加密和路径混淆。您确定要在没有加密的情况下继续吗?\",\n \"obsidianLiveSyncSettingTab.msgFetchConfigFromRemote\": \"您想从远程服务器获取配置吗?\",\n \"obsidianLiveSyncSettingTab.msgGenerateSetupURI\": \"全部完成!您想生成一个设置 URI 来设置其他设备吗?\",\n \"obsidianLiveSyncSettingTab.msgIfConfigNotPersistent\": \"如果服务器配置不是持久的(例如,在 docker 上运行),此处的值可能会更改。一旦能够连接,请更新服务器 local.ini 中的设置\",\n \"obsidianLiveSyncSettingTab.msgInvalidPassphrase\": \"您的加密密码可能无效。您确定要继续吗?\",\n \"obsidianLiveSyncSettingTab.msgNewVersionNote\": \"因为升级通知来到这里?请查看版本历史。如果您满意,请点击按钮。新的更新将再次提示此信息\",\n \"obsidianLiveSyncSettingTab.msgNonHTTPSInfo\": \"配置为非 HTTPS URI。请注意,这可能在移动设备上无法工作\",\n \"obsidianLiveSyncSettingTab.msgNonHTTPSWarning\": \"无法连接到非 HTTPS URI。请更新您的配置并重试\",\n \"obsidianLiveSyncSettingTab.msgNotice\": \"---注意---\",\n \"obsidianLiveSyncSettingTab.msgObjectStorageWarning\": \"警告:此功能仍在开发中,请注意以下几点:\\n- 仅追加架构。需要重建才能缩小存储空间。\\n- 有点脆弱。\\n- 首次同步时,所有历史记录将从远程传输。注意数据上限和慢速。\\n- 只有差异会实时同步。\\n\\n如果您遇到任何问题,或对此功能有任何想法,请在 GitHub 上创建 issue。\\n感谢您的巨大贡献\",\n \"obsidianLiveSyncSettingTab.msgOriginCheck\": \"源检查: {org}\",\n \"obsidianLiveSyncSettingTab.msgRebuildRequired\": \"需要重建数据库以应用更改。请选择应用更改的方法。\\n\\n<details>\\n<summary>图例</summary>\\n\\n| 符号 | 含义 |\\n|: ------ :| ------- |\\n| ⇔ | 最新 |\\n| ⇄ | 同步以平衡 |\\n| ⇐,⇒ | 传输以覆盖 |\\n| ⇠,⇢ | 从另一侧传输以覆盖 |\\n\\n</details>\\n\\n## ${OPTION_REBUILD_BOTH}\\n概览:📄 ⇒¹ 💻 ⇒² 🛰️ ⇢ⁿ 💻 ⇄ⁿ⁺¹ 📄\\n使用此设备的现有文件重建本地和远程数据库。\\n这将导致其他设备被锁定,并且它们需要执行获取操作。\\n## ${OPTION_FETCH}\\n概览:📄 ⇄² 💻 ⇐¹ 🛰️ ⇔ 💻 ⇔ 📄\\n初始化本地数据库并使用从远程数据库获取的数据重建它。\\n这种情况包括您已经重建了远程数据库的情况。\\n## ${OPTION_ONLY_SETTING}\\n仅存储设置。**注意:这可能导致数据损坏**;通常需要重建数据库\",\n \"obsidianLiveSyncSettingTab.msgSelectAndApplyPreset\": \"请选择并应用任何预设项以完成向导\",\n \"obsidianLiveSyncSettingTab.msgSetCorsCredentials\": \"设置 cors.credentials\",\n \"obsidianLiveSyncSettingTab.msgSetCorsOrigins\": \"设置 cors.origins\",\n \"obsidianLiveSyncSettingTab.msgSetMaxDocSize\": \"设置 couchdb.max_document_size\",\n \"obsidianLiveSyncSettingTab.msgSetMaxRequestSize\": \"设置 chttpd.max_http_request_size\",\n \"obsidianLiveSyncSettingTab.msgSetRequireValidUser\": \"设置 chttpd.require_valid_user = true\",\n \"obsidianLiveSyncSettingTab.msgSetRequireValidUserAuth\": \"设置 chttpd_auth.require_valid_user = true\",\n \"obsidianLiveSyncSettingTab.msgSettingModified\": \"设置 \\\"${setting}\\\" 已从另一台设备修改。点击 {HERE} 重新加载设置。点击其他地方忽略更改\",\n \"obsidianLiveSyncSettingTab.msgSettingsUnchangeableDuringSync\": \"这些设置在同步期间无法更改。请在“同步设置”中禁用所有同步以解锁\",\n \"obsidianLiveSyncSettingTab.msgSetWwwAuth\": \"设置 httpd.WWW-Authenticate\",\n \"obsidianLiveSyncSettingTab.nameApplySettings\": \"应用设置\",\n \"obsidianLiveSyncSettingTab.nameConnectSetupURI\": \"使用设置 URI 连接\",\n \"obsidianLiveSyncSettingTab.nameCopySetupURI\": \"将当前设置复制为设置 URI\",\n \"obsidianLiveSyncSettingTab.nameDisableHiddenFileSync\": \"禁用隐藏文件同步\",\n \"obsidianLiveSyncSettingTab.nameDiscardSettings\": \"丢弃现有设置和数据库\",\n \"obsidianLiveSyncSettingTab.nameEnableHiddenFileSync\": \"启用隐藏文件同步\",\n \"obsidianLiveSyncSettingTab.nameEnableLiveSync\": \"启用 LiveSync\",\n \"obsidianLiveSyncSettingTab.nameHiddenFileSynchronization\": \"隐藏文件同步\",\n \"obsidianLiveSyncSettingTab.nameManualSetup\": \"手动设置\",\n \"obsidianLiveSyncSettingTab.nameTestConnection\": \"测试连接\",\n \"obsidianLiveSyncSettingTab.nameTestDatabaseConnection\": \"测试数据库连接\",\n \"obsidianLiveSyncSettingTab.nameValidateDatabaseConfig\": \"验证数据库配置\",\n \"obsidianLiveSyncSettingTab.okAdminPrivileges\": \"✔ 您拥有管理员权限\",\n \"obsidianLiveSyncSettingTab.okCorsCredentials\": \"✔ cors.credentials 设置正确\",\n \"obsidianLiveSyncSettingTab.okCorsCredentialsForOrigin\": \"CORS 凭据正常\",\n \"obsidianLiveSyncSettingTab.okCorsOriginMatched\": \"✔ CORS 源正常\",\n \"obsidianLiveSyncSettingTab.okCorsOrigins\": \"✔ cors.origins 设置正确\",\n \"obsidianLiveSyncSettingTab.okEnableCors\": \"✔ httpd.enable_cors 设置正确\",\n \"obsidianLiveSyncSettingTab.okEnableCorsChttpd\": \"✔ chttpd.enable_cors is ok.\",\n \"obsidianLiveSyncSettingTab.okMaxDocumentSize\": \"✔ couchdb.max_document_size 设置正确\",\n \"obsidianLiveSyncSettingTab.okMaxRequestSize\": \"✔ chttpd.max_http_request_size 设置正确\",\n \"obsidianLiveSyncSettingTab.okRequireValidUser\": \"✔ chttpd.require_valid_user 设置正确\",\n \"obsidianLiveSyncSettingTab.okRequireValidUserAuth\": \"✔ chttpd_auth.require_valid_user 设置正确\",\n \"obsidianLiveSyncSettingTab.okWwwAuth\": \"✔ httpd.WWW-Authenticate 设置正确\",\n \"obsidianLiveSyncSettingTab.optionApply\": \"应用\",\n \"obsidianLiveSyncSettingTab.optionCancel\": \"取消\",\n \"obsidianLiveSyncSettingTab.optionCouchDB\": \"CouchDB\",\n \"obsidianLiveSyncSettingTab.optionDisableAllAutomatic\": \"禁用所有自动同步\",\n \"obsidianLiveSyncSettingTab.optionFetchFromRemote\": \"从远程获取\",\n \"obsidianLiveSyncSettingTab.optionHere\": \"这里\",\n \"obsidianLiveSyncSettingTab.optionLiveSync\": \"LiveSync\",\n \"obsidianLiveSyncSettingTab.optionMinioS3R2\": \"Minio, S3, R2\",\n \"obsidianLiveSyncSettingTab.optionOkReadEverything\": \"好的,我已经阅读了所有内容 \",\n \"obsidianLiveSyncSettingTab.optionOnEvents\": \"基于事件\",\n \"obsidianLiveSyncSettingTab.optionPeriodicAndEvents\": \"定期和基于事件\",\n \"obsidianLiveSyncSettingTab.optionPeriodicWithBatch\": \"定期与批量\",\n \"obsidianLiveSyncSettingTab.optionRebuildBoth\": \"从此设备重建两者\",\n \"obsidianLiveSyncSettingTab.optionSaveOnlySettings\": \"(危险)仅保存设置\",\n \"obsidianLiveSyncSettingTab.panelChangeLog\": \"更新日志\",\n \"obsidianLiveSyncSettingTab.panelGeneralSettings\": \"常规设置\",\n \"obsidianLiveSyncSettingTab.panelPrivacyEncryption\": \"隐私与加密\",\n \"obsidianLiveSyncSettingTab.panelRemoteConfiguration\": \"远程配置\",\n \"obsidianLiveSyncSettingTab.panelSetup\": \"设置\",\n \"obsidianLiveSyncSettingTab.serverVersion\": \"服务器信息: ${info}\",\n \"obsidianLiveSyncSettingTab.titleActiveRemoteServer\": \"活动远程服务器\",\n \"obsidianLiveSyncSettingTab.titleAppearance\": \"外观\",\n \"obsidianLiveSyncSettingTab.titleConflictResolution\": \"冲突解决\",\n \"obsidianLiveSyncSettingTab.titleCongratulations\": \"恭喜!\",\n \"obsidianLiveSyncSettingTab.titleCouchDB\": \"CouchDB\",\n \"obsidianLiveSyncSettingTab.titleDeletionPropagation\": \"删除传播\",\n \"obsidianLiveSyncSettingTab.titleEncryptionNotEnabled\": \"未启用加密\",\n \"obsidianLiveSyncSettingTab.titleEncryptionPassphraseInvalid\": \"加密密码无效\",\n \"obsidianLiveSyncSettingTab.titleExtraFeatures\": \"启用额外和高级功能\",\n \"obsidianLiveSyncSettingTab.titleFetchConfig\": \"获取配置\",\n \"obsidianLiveSyncSettingTab.titleFetchConfigFromRemote\": \"从远程服务器获取配置\",\n \"obsidianLiveSyncSettingTab.titleFetchSettings\": \"获取设置\",\n \"obsidianLiveSyncSettingTab.titleHiddenFiles\": \"隐藏文件\",\n \"obsidianLiveSyncSettingTab.titleLogging\": \"日志记录\",\n \"obsidianLiveSyncSettingTab.titleMinioS3R2\": \"Minio, S3, R2\",\n \"obsidianLiveSyncSettingTab.titleNotification\": \"通知\",\n \"obsidianLiveSyncSettingTab.titleOnlineTips\": \"在线提示\",\n \"obsidianLiveSyncSettingTab.titleQuickSetup\": \"快速设置\",\n \"obsidianLiveSyncSettingTab.titleRebuildRequired\": \"需要重建\",\n \"obsidianLiveSyncSettingTab.titleRemoteConfigCheckFailed\": \"远程配置检查失败\",\n \"obsidianLiveSyncSettingTab.titleRemoteServer\": \"远程服务器\",\n \"obsidianLiveSyncSettingTab.titleReset\": \"重置\",\n \"obsidianLiveSyncSettingTab.titleSetupOtherDevices\": \"设置其他设备\",\n \"obsidianLiveSyncSettingTab.titleSynchronizationMethod\": \"同步方法\",\n \"obsidianLiveSyncSettingTab.titleSynchronizationPreset\": \"同步预设\",\n \"obsidianLiveSyncSettingTab.titleSyncSettings\": \"同步设置\",\n \"obsidianLiveSyncSettingTab.titleSyncSettingsViaMarkdown\": \"通过 Markdown 同步设置\",\n \"obsidianLiveSyncSettingTab.titleUpdateThinning\": \"更新频率限制\",\n \"obsidianLiveSyncSettingTab.warnCorsOriginUnmatched\": \"⚠ CORS 源不匹配 {from}->{to}\",\n \"obsidianLiveSyncSettingTab.warnNoAdmin\": \"⚠ 您没有管理员权限\",\n \"P2P.AskPassphraseForDecrypt\": \"远程对等方共享了配置,请输入密码短语以解密配置\",\n \"P2P.AskPassphraseForShare\": \"远程对等方请求此设备配置,请输入密码短语以共享配置。你可以通过取消此对话框来忽略此请求\",\n \"P2P.DisabledButNeed\": \"%{title_p2p_sync} 已禁用。你确定要启用它吗?\",\n \"P2P.FailedToOpen\": \"无法打开 P2P 连接到信令服务器\",\n \"P2P.NoAutoSyncPeers\": \"未找到自动同步的对等方,请在 %{long_p2p_sync} 面板中设置对等方\",\n \"P2P.NoKnownPeers\": \"未检测到对等方,正在等待其他对等方的连接...\",\n \"P2P.Note.description\": \" This replicator allows us to synchronise our vault with other devices\\nusing a peer-to-peer connection. We can use this to synchronise our vault with our other devices without using a cloud service.\\nThis replicator is based on Trystero. It also uses a signaling server to establish a connection between devices. The signaling server is used to exchange connection information between devices. It does (or,should) not know or store any of our data.\\n\\nThe signaling server can be hosted by anyone. This is just a Nostr relay. For the sake of simplicity and checking the behaviour of the replicator, an instance of the signaling server is hosted by vrtmrz. You can use the experimental server provided by vrtmrz, or you can use any other server.\\n\\nBy the way, even if the signaling server does not store our data, it can see the connection information of some of our devices. Please be aware of this. Also, be cautious when using the server provided by someone else.\",\n \"P2P.Note.important_note\": \"The Experimental Implementation of the Peer-to-Peer Replicator.\",\n \"P2P.Note.important_note_sub\": \"This feature is still in the experimental stage. Please be aware that this feature may not work as expected. Furthermore, it may have some bugs, security issues, and other issues. Please use this feature at your own risk. Please contribute to the development of this feature.\",\n \"P2P.Note.Summary\": \"What is this feature? (and some important notes, please read once)\",\n \"P2P.NotEnabled\": \"%{title_p2p_sync} is not enabled. We cannot open a new connection.\",\n \"P2P.P2PReplication\": \"%{P2P} Replication\",\n \"P2P.PaneTitle\": \"%{long_p2p_sync}\",\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\": \"密码\",\n \"Passphrase of sensitive configuration items\": \"敏感配置项的密码\",\n \"password\": \"密码\",\n \"Password\": \"密码\",\n \"Path Obfuscation\": \"路径混淆\",\n \"Per-file-saved customization sync\": \"按文件保存的自定义同步\",\n \"Periodic Sync interval\": \"定期同步间隔\",\n \"Prepare the 'report' to create an issue\": \"准备 '报告' 以创建问题单\",\n \"Presets\": \"预设\",\n \"Process small files in the foreground\": \"在前台处理小文件\",\n \"Property Encryption\": \"属性加密\",\n \"RedFlag.Fetch.Method.Desc\": \"How do you want to fetch?\\n- %{RedFlag.Fetch.Method.FetchSafer}.\\n **Low Traffic**, **High CPU**, **Low Risk**\\n Recommended if ...\\n - Files possibly inconsistent\\n - Files were not so much\\n- %{RedFlag.Fetch.Method.FetchSmoother}.\\n **Low Traffic**, **Moderate CPU**, **Low to Moderate Risk**\\n Recommended if ...\\n - Files probably consistent\\n - You have a lot of files.\\n- %{RedFlag.Fetch.Method.FetchTraditional}.\\n **High Traffic**, **Low CPU**, **Low to Moderate Risk**\\n\\n>[!INFO]- Details\\n> ## %{RedFlag.Fetch.Method.FetchSafer}.\\n> **Low Traffic**, **High CPU**, **Low Risk**\\n> This option first creates a local database using existing local files before fetching data from the remote source.\\n> If matching files exist both locally and remotely, only the differences between them will be transferred.\\n> However, files present in both locations will initially be handled as conflicted files. They will be resolved automatically if they are not actually conflicted, but this process may take time.\\n> This is generally the safest method, minimizing data loss risk.\\n> ## %{RedFlag.Fetch.Method.FetchSmoother}.\\n> **Low Traffic**, **Moderate CPU**, **Low to Moderate Risk** (depending operation)\\n> This option first creates chunks from local files for the database, then fetches data. Consequently, only chunks missing locally are transferred. However, all metadata is taken from the remote source.\\n> Local files are then compared against this metadata at launch. The content considered newer will overwrite the older one (by modified time). This outcome is then synchronised back to the remote database.\\n> This is generally safe if local files are genuinely the latest timestamp. However, it can cause problems if a file has a newer timestamp but older content (like the initial `welcome.md`).\\n> This uses less CPU and faster than \\\"%{RedFlag.Fetch.Method.FetchSafer}\\\", but it may lead to data loss if not used carefully.\\n> ## %{RedFlag.Fetch.Method.FetchTraditional}.\\n> **High Traffic**, **Low CPU**, **Low to Moderate Risk** (depending operation)\\n> All things will be fetched from the remote.\\n> Similar to the %{RedFlag.Fetch.Method.FetchSmoother}, but all chunks are fetched from the remote source.\\n> This is the most traditional way to fetch, typically consuming the most network traffic and time. It also carries a similar risk of overwriting remote files to the '%{RedFlag.Fetch.Method.FetchSmoother}' option.\\n> However, it is often considered the most stable method because it is the longest-established and most straightforward approach.\",\n \"RedFlag.Fetch.Method.FetchSafer\": \"Create a local database once before fetching\",\n \"RedFlag.Fetch.Method.FetchSmoother\": \"Create local file chunks before fetching\",\n \"RedFlag.Fetch.Method.FetchTraditional\": \"Fetch everything from the remote\",\n \"RedFlag.Fetch.Method.Title\": \"How do you want to fetch?\",\n \"RedFlag.FetchRemoteConfig.Buttons.Cancel\": \"No, use local settings\",\n \"RedFlag.FetchRemoteConfig.Buttons.Fetch\": \"Yes, fetch and apply remote settings\",\n \"RedFlag.FetchRemoteConfig.Message\": \"Do you want to fetch and apply remotely stored preference settings to the device?\",\n \"RedFlag.FetchRemoteConfig.Title\": \"Fetch Remote Configuration\",\n \"Reducing the frequency with which on-disk changes are reflected into the DB\": \"降低将磁盘上的更改反映到数据库中的频率\",\n \"Region\": \"区域\",\n \"Remote server type\": \"远程服务器类型\",\n \"Remote Type\": \"远程类型\",\n \"Replicator.Dialogue.Locked.Action.Dismiss\": \"Cancel for reconfirmation\",\n \"Replicator.Dialogue.Locked.Action.Fetch\": \"Reset Synchronisation on This Device\",\n \"Replicator.Dialogue.Locked.Action.Unlock\": \"Unlock the remote database\",\n \"Replicator.Dialogue.Locked.Message\": \"Remote database is locked. This is due to a rebuild on one of the terminals.\\nThe device is therefore asked to withhold the connection to avoid database corruption.\\n\\nThere are three options that we can do:\\n\\n- %{Replicator.Dialogue.Locked.Action.Fetch}\\n The most preferred and reliable way. This will dispose the local database once, and fetch all from the remote database again, In most case, we can perform this safely. However, it takes some time and should be done in stable network.\\n- %{Replicator.Dialogue.Locked.Action.Unlock}\\n This method can only be used if we are already reliably synchronised by other replication methods. This does not simply mean that we have the same files. If you are not sure, you should avoid it.\\n- %{Replicator.Dialogue.Locked.Action.Dismiss}\\n This will cancel the operation. And we will asked again on next request.\\n\",\n \"Replicator.Dialogue.Locked.Message.Fetch\": \"Fetch all has been scheduled. Plug-in will be restarted to perform it.\",\n \"Replicator.Dialogue.Locked.Message.Unlocked\": \"The remote database has been unlocked. Please retry the operation.\",\n \"Replicator.Dialogue.Locked.Title\": \"Locked\",\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\": \"An update has been detected. Please open the Settings dialogue and check the Change Log. Replication has been cancelled.\",\n \"Requires restart of Obsidian\": \"需要重启 Obsidian\",\n \"Requires restart of Obsidian.\": \"需要重启 Obsidian \",\n \"Rerun Onboarding Wizard\": \"重新运行引导向导\",\n \"Rerun the onboarding wizard to set up Self-hosted LiveSync again.\": \"重新运行引导向导以再次设置 Self-hosted LiveSync。\",\n \"Rerun Wizard\": \"重新运行向导\",\n \"Reset notification threshold and check the remote database usage\": \"重置通知阈值并检查远程数据库使用情况\",\n \"Reset the remote storage size threshold and check the remote storage size again.\": \"重置远程存储大小阈值并再次检查远程存储大小。\",\n \"Run Doctor\": \"立即诊断\",\n \"Save settings to a markdown file. You will be notified when new settings arrive. You can set different files by the platform.\": \"将设置保存到一个 Markdown 文件中。当新设置到达时,您将收到通知。您可以根据平台设置不同的文件 \",\n \"Saving will be performed forcefully after this number of seconds.\": \"在此秒数后将强制执行保存 \",\n \"Scan changes on customization sync\": \"在自定义同步时扫描更改\",\n \"Scan customization automatically\": \"自动扫描自定义设置\",\n \"Scan customization before replicating.\": \"在复制前扫描自定义设置 \",\n \"Scan customization every 1 minute.\": \"每1分钟扫描自定义设置 \",\n \"Scan customization periodically\": \"定期扫描自定义设置\",\n \"Scan for hidden files before replication\": \"复制前扫描隐藏文件\",\n \"Scan hidden files periodically\": \"定期扫描隐藏文件\",\n \"Seconds, 0 to disable\": \"秒,0为禁用\",\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\": \"服务器 URI\",\n \"Setting.GenerateKeyPair.Desc\": \"We have generated a key pair!\\n\\nNote: This key pair will never be shown again. Please save it in a safe place. If you have lost it, you need to generate a new key pair.\\nNote 2: The public key is in spki format, and the Private key is in pkcs8 format. For the sake of convenience, newlines are converted to `\\\\n` in public key.\\nNote 3: The public key should be configured in the remote database, and the private key should be configured in local devices.\\n\\n>[!FOR YOUR EYES ONLY]-\\n> <div class=\\\"sls-keypair\\\">\\n>\\n> ### Public Key\\n> ```\\n${public_key}\\n> ```\\n>\\n> ### Private Key\\n> ```\\n${private_key}\\n> ```\\n>\\n> </div>\\n\\n>[!Both for copying]-\\n>\\n> <div class=\\\"sls-keypair\\\">\\n>\\n> ```\\n${public_key}\\n${private_key}\\n> ```\\n>\\n> </div>\\n\\n\",\n \"Setting.GenerateKeyPair.Title\": \"New key pair has been generated!\",\n \"Setting.TroubleShooting\": \"故障排除\",\n \"Setting.TroubleShooting.Doctor\": \"设置诊断\",\n \"Setting.TroubleShooting.Doctor.Desc\": \"检测系统中不合理的设置。(与迁移期间逻辑相同)\",\n \"Setting.TroubleShooting.ScanBrokenFiles\": \"扫描损坏或异常的文件\",\n \"Setting.TroubleShooting.ScanBrokenFiles.Desc\": \"扫描数据库中未正确存储的文件。\",\n \"SettingTab.Message.AskRebuild\": \"Your changes require fetching from the remote database. Do you want to proceed?\",\n \"Setup.Apply.Buttons.ApplyAndFetch\": \"Apply and Fetch\",\n \"Setup.Apply.Buttons.ApplyAndMerge\": \"Apply and Merge\",\n \"Setup.Apply.Buttons.ApplyAndRebuild\": \"Apply and Rebuild\",\n \"Setup.Apply.Buttons.Cancel\": \"Discard and Cancel\",\n \"Setup.Apply.Buttons.OnlyApply\": \"Only Apply\",\n \"Setup.Apply.Message\": \"The new configuration is ready. Let us proceed to apply it.\\nThere are several ways to apply this:\\n\\n- Apply and Fetch\\n Configure this device as a new client. After applying, synchronise from the remote server.\\n- Apply and Merge\\n Configure on a device that already has the file. It processes the local files and transfers the differences. Conflicts may arise.\\n- Apply and Rebuild\\n Rebuild the remote using local files. This is typically done if the server becomes corrupted or we wish to start from scratch.\\n Other devices will be locked and required to re-fetch.\\n- Only Apply\\n Apply only. Conflicts may arise if a rebuild is required.\",\n \"Setup.Apply.Title\": \"Apply new configuration from the ${method}\",\n \"Setup.Apply.WarningRebuildRecommended\": \"NOTE: after adjusting the settings, it has been determined that a rebuild is required; Just Import is not recommended.\",\n \"Setup.Doctor.Buttons.No\": \"No, please use the settings in the URI as is\",\n \"Setup.Doctor.Buttons.Yes\": \"Yes, please consult the doctor\",\n \"Setup.Doctor.Message\": \"Self-hosted LiveSync has gradually become longer in history and some recommended settings have changed.\\n\\nNow, setup is a very good time to do this.\\n\\nDo you want to run Doctor to check if the imported settings are optimal compared to the latest state?\",\n \"Setup.Doctor.Title\": \"Do you want to consult the doctor?\",\n \"Setup.FetchRemoteConf.Buttons.Fetch\": \"Yes, please fetch the configuration\",\n \"Setup.FetchRemoteConf.Buttons.Skip\": \"No, please use the settings in the URI\",\n \"Setup.FetchRemoteConf.Message\": \"If we have already synchronised once with another device, the remote database stores the suitable configuration values between the synchronised devices. The plug-in would like to retrieve them for robust configuration.\\n\\nHowever, we have to make sure the one thing. Are we currently in a situation where we can access the network safely and retrieve the settings?\\n\\nNote: Mostly, you are safe to do this, that your remote database is hosted with a SSL certificate, and your network is not compromised.\",\n \"Setup.FetchRemoteConf.Title\": \"Fetch configuration from remote database?\",\n \"Setup.QRCode\": \"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 \"Setup.ShowQRCode\": \"使用QR码\",\n \"Setup.ShowQRCode.Desc\": \"使用QR码来传递配置\",\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 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 \"Show only notifications\": \"仅显示通知\",\n \"Show status as icons only\": \"仅以图标显示状态\",\n \"Show status icon instead of file warnings banner\": \"显示状态图标,而非文件警告横幅\",\n \"Show status inside the editor\": \"在编辑器内显示状态\",\n \"Show status on the status bar\": \"在状态栏上显示状态\",\n \"Show verbose log. Please enable if you report an issue.\": \"显示详细日志。如果您报告问题,请启用此选项 \",\n \"Starts synchronisation when a file is saved.\": \"当文件保存时启动同步 \",\n \"Stop reflecting database changes to storage files.\": \"停止将数据库更改反映到存储文件 \",\n \"Stop watching for file changes.\": \"停止监视文件更改 \",\n \"Suppress notification of hidden files change\": \"暂停隐藏文件更改的通知\",\n \"Suspend database reflecting\": \"暂停数据库反映\",\n \"Suspend file watching\": \"暂停文件监视\",\n \"Sync after merging file\": \"合并文件后同步\",\n \"Sync automatically after merging files\": \"合并文件后自动同步\",\n \"Sync Mode\": \"同步模式\",\n \"Sync on Editor Save\": \"编辑器保存时同步\",\n \"Sync on File Open\": \"打开文件时同步\",\n \"Sync on Save\": \"保存时同步\",\n \"Sync on Startup\": \"启动时同步\",\n \"Testing only - Resolve file conflicts by syncing newer copies of the file, this can overwrite modified files. Be Warned.\": \"仅供测试 - 通过同步文件的较新副本来解决文件冲突,这可能会覆盖修改过的文件。请注意 \",\n \"The delay for consecutive on-demand fetches\": \"连续按需获取的延迟\",\n \"The Hash algorithm for chunk IDs\": \"块 ID 的哈希算法(实验性)\",\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 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 \"This passphrase will not be copied to another device. It will be set to `Default` until you configure it again.\": \"此密码不会复制到另一台设备。在您再次配置之前,它将设置为 `Default` \",\n \"TweakMismatchResolve.Action.Dismiss\": \"Dismiss\",\n \"TweakMismatchResolve.Action.UseConfigured\": \"Use configured settings\",\n \"TweakMismatchResolve.Action.UseMine\": \"Update remote database settings\",\n \"TweakMismatchResolve.Action.UseMineAcceptIncompatible\": \"Update remote database settings but keep as is\",\n \"TweakMismatchResolve.Action.UseMineWithRebuild\": \"Update remote database settings and rebuild again\",\n \"TweakMismatchResolve.Action.UseRemote\": \"Apply settings to this device\",\n \"TweakMismatchResolve.Action.UseRemoteAcceptIncompatible\": \"Apply settings to this device, but and ignore incompatibility\",\n \"TweakMismatchResolve.Action.UseRemoteWithRebuild\": \"Apply settings to this device, and fetch again\",\n \"TweakMismatchResolve.Message.Main\": \"\\nThe settings in the remote database are as follows. These values are configured by other devices, which are synchronised with this device at least once.\\n\\nIf you want to use these settings, please select %{TweakMismatchResolve.Action.UseConfigured}.\\nIf you want to keep the settings of this device, please select %{TweakMismatchResolve.Action.Dismiss}.\\n\\n${table}\\n\\n>[!TIP]\\n> If you want to synchronise all settings, please use `Sync settings via markdown` after applying minimal configuration with this feature.\\n\\n${additionalMessage}\",\n \"TweakMismatchResolve.Message.MainTweakResolving\": \"Your configuration has not been matched with the one on the remote server.\\n\\nFollowing configuration should be matched:\\n\\n${table}\\n\\nLet us know your decision.\\n\\n${additionalMessage}\",\n \"TweakMismatchResolve.Message.UseRemote.WarningRebuildRecommended\": \"\\n>[!NOTICE]\\n> Some changes are compatible but may consume extra storage and transfer volumes. A rebuild is recommended. However, a rebuild may not be performed at present, but may be implemented in future maintenance.\\n> ***Please ensure that you have time and are connected to a stable network to apply!***\",\n \"TweakMismatchResolve.Message.UseRemote.WarningRebuildRequired\": \"\\n>[!WARNING]\\n> Some remote configurations are not compatible with the local database of this device. Rebuilding the local database will be required.\\n> ***Please ensure that you have time and are connected to a stable network to apply!***\",\n \"TweakMismatchResolve.Message.WarningIncompatibleRebuildRecommended\": \"\\n>[!NOTICE]\\n> We have detected that some of the values are different to make incompatible the local database with the remote database.\\n> Some changes are compatible but may consume extra storage and transfer volumes. A rebuild is recommended. However, a rebuild may not be performed at present, but may be implemented in future maintenance.\\n> If you want to rebuild, it takes a few minutes or more. **Make sure it is safe to perform it now.**\",\n \"TweakMismatchResolve.Message.WarningIncompatibleRebuildRequired\": \"\\n>[!WARNING]\\n> We have detected that some of the values are different to make incompatible the local database with the remote database.\\n> Either local or remote rebuilds are required. Both of them takes a few minutes or more. **Make sure it is safe to perform it now.**\",\n \"TweakMismatchResolve.Table\": \"| Value name | This device | On Remote |\\n|: --- |: ---- :|: ---- :|\\n${rows}\\n\\n\",\n \"TweakMismatchResolve.Table.Row\": \"| ${name} | ${self} | ${remote} |\",\n \"TweakMismatchResolve.Title\": \"Configuration Mismatch Detected\",\n \"TweakMismatchResolve.Title.TweakResolving\": \"Configuration Mismatch Detected\",\n \"TweakMismatchResolve.Title.UseRemoteConfig\": \"Use Remote Configuration\",\n \"Unique name between all synchronized devices. To edit this setting, please disable customization sync once.\": \"所有同步设备之间的唯一名称。要编辑此设置,请首先禁用自定义同步\",\n \"Use Custom HTTP Handler\": \"使用自定义 HTTP 处理程序\",\n \"Use dynamic iteration count\": \"使用动态迭代次数\",\n \"Use Segmented-splitter\": \"使用分段分割器\",\n \"Use splitting-limit-capped chunk splitter\": \"使用分割限制上限的块分割器\",\n \"Use the trash bin\": \"使用回收站\",\n \"Use timeouts instead of heartbeats\": \"使用超时而不是心跳\",\n \"username\": \"用户名\",\n \"Username\": \"用户名\",\n \"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 \"When you save a file in the editor, start a sync automatically\": \"当您在编辑器中保存文件时,自动开始同步\",\n \"Write credentials in the file\": \"将凭据写入文件\",\n \"Write logs into the file\": \"将日志写入文件\"\n}\n","import zh from \"../messagesJson/zh.json\";\nexport const PartialMessages = {\n zh,\n} as const;\n","{}\n","import zwTh from \"../messagesJson/zh-tw.json\";\nexport const PartialMessages = {\n \"zw-th\": zwTh,\n} as const;\n","import { PartialMessages as def } from \"./def.ts\";\nimport { PartialMessages as es } from \"./es.ts\";\nimport { PartialMessages as ja } from \"./ja.ts\";\nimport { PartialMessages as ko } from \"./ko.ts\";\nimport { PartialMessages as ru } from \"./ru.ts\";\nimport { PartialMessages as zh } from \"./zh.ts\";\nimport { PartialMessages as zhTw } from \"./zh-tw.ts\";\n\ntype MessageKeys = keyof typeof def.def;\n\nconst messages = {\n ...def,\n ...es,\n ...ja,\n ...ko,\n ...ru,\n ...zh,\n ...zhTw,\n};\nconst w = Object.entries(messages)\n .map(([lang, messageDefs]) =>\n Object.entries(messageDefs).map(([key, value]) => [key, [lang, value] as [string, string]] as const)\n )\n .flat();\n\nconst _allMessages = w.reduce(\n (acc, [key, value]) => {\n if (!acc[key]) acc[key] = {};\n acc[key][value[0]] = value[1];\n return acc;\n },\n {} as Record<string, Record<string, string>>\n) as Record<MessageKeys, { [key: string]: string }>;\n\nexport { _allMessages, type MessageKeys };\n","/**\n# Rosetta stone\n- To localise messages to your language, please write a translation to this file and submit a PR.\n- Please order languages in alphabetic order, if you write multiple items.\n\n## Notice to ensure that your favours are not wasted.\n\nIf you plan to utilise machine translation engines to contribute translated resources,\nplease ensure the engine's terms of service are compatible with our project's license.\nYour diligence in this matter helps maintain compliance and avoid potential licensing issues.\nThank you for your consideration.\n\nUsually, our projects (Self-hosted LiveSync and its families) are licensed under MIT License.\nTo see details, please refer to the LICENSES file on each repository.\n\n## How to internationalise untranslated items?\n1. Change the message literal to use `$msg`\n \"Could not parse YAML\" -> $msg('anyKey')\n2. Create `ls-debug` folder under the `.obsidian` folder of your vault.\n3. Run Self-hosted LiveSync in dev mode (npm run dev).\n4. You will get the `missing-translation-YYYY-MM-DD.jsonl` under `ls-debug`. Please copy and paste inside `allMessages` and write the translations.\n5. Send me the PR!\n*/\n\nconst LANG_DE = \"de\";\nconst LANG_ES = \"es\";\nconst LANG_JA = \"ja\";\nconst LANG_RU = \"ru\";\nconst LANG_ZH = \"zh\";\nconst LANG_KO = \"ko\";\nconst LANG_ZH_TW = \"zh-tw\";\nconst LANG_DEF = \"def\"; // Default language: English\n\n// Also please order in alphabetic order except for the default language.\n\nexport const SUPPORTED_I18N_LANGS = [LANG_DEF, LANG_DE, LANG_ES, LANG_JA, LANG_KO, LANG_RU, LANG_ZH, LANG_ZH_TW];\n\n// Also this.\nexport type I18N_LANGS =\n | typeof LANG_DEF // Default language: English\n | typeof LANG_DE\n | typeof LANG_ES\n | typeof LANG_JA\n | typeof LANG_KO\n | typeof LANG_RU\n | typeof LANG_ZH\n | typeof LANG_ZH_TW\n | \"\";\n\ntype MESSAGE = { [key in I18N_LANGS]?: string };\n\nimport { Logger } from \"./logger.ts\";\n// deno-lint-ignore no-sloppy-imports\nimport { _allMessages, type MessageKeys } from \"./messages/combinedMessages.dev\"; // This sloppy-imports are used to replace the messages with the combined messages.\nconst expandedMessage = {\n ...expandKeywords(_allMessages, \"def\"),\n ...expandKeywords(_allMessages, \"es\"),\n ...expandKeywords(_allMessages, \"ja\"),\n ...expandKeywords(_allMessages, \"ko\"),\n ...expandKeywords(_allMessages, \"ru\"),\n ...expandKeywords(_allMessages, \"zh\"),\n ...expandKeywords(_allMessages, \"zh-tw\"),\n};\n\nfunction expandKeywords<T extends Record<string, U>, U extends Record<string, string>>(\n message: T,\n lang: I18N_LANGS,\n recurseLimit = 10\n): T {\n if (recurseLimit <= 0) {\n Logger(\n `ExpandKeywords hit the recursion limit, returning the current state. but this is not expected. May recursive referenced.`\n );\n return message;\n }\n // const DEFAULT_ENGLISH = \"en-GB\"; //This is to balance the books with existing messages.\n // const langCode = (lang == \"def\" || lang == \"\") ? DEFAULT_ENGLISH : lang;\n\n // Generate keywords from all messages\n // This can handles the case where the message itself contains a keyword:\n // - task:`Some procedure`\n // - check: `%{task} checking`\n // - checkfailed: `%{check} failed`\n // If in this case `checkfailed` may `Some procedure checking failed`.\n // And, it can compress the rosetta stone: the message table.\n const keywords = Object.entries(message)\n .map(([key, value]) => [key, value[lang]])\n // Use all messages as keywords, but traditional keyword prefix should be trimmed.\n .map(([key, value]) => [`${key.startsWith(\"K.\") ? key.substring(\"K.\".length) : key}`, value])\n .map(\n ([key, value]) =>\n [\n [`%{${key}}`, value],\n // [`%{${key}.upper}`, [value[0].toLocaleUpperCase(langCode) + value.substring(1)]],\n // [`%{${key}.lower}`, [value[0].toLocaleLowerCase(langCode) + value.substring(1)]],\n ] as [key: string, value: string][]\n )\n .flat()\n .sort((a, b) => (a[1]?.length ?? 0) - (b[1]?.length ?? 0));\n\n const ret = {\n ...message,\n } as Record<string, Record<string, string>>;\n let isChanged = false;\n for (const key of Object.keys(message)) {\n if (!(lang in ret[key])) continue;\n for (const [keyword, replacement] of keywords) {\n if (ret[key][lang].includes(keyword)) {\n ret[key][lang] = ret[key][lang].split(keyword).join(replacement);\n isChanged = true;\n }\n }\n }\n if (isChanged) return expandKeywords(ret, lang, recurseLimit--) as T;\n\n return ret as T;\n}\n\nexport const allMessages = expandedMessage as { [key: string]: MESSAGE };\nexport type AllMessageKeys = MessageKeys;\n","import type { AllMessageKeys, I18N_LANGS } from \"./rosetta\";\nimport { allMessages } from \"./rosetta\";\nimport type { TaggedType } from \"./types\";\nexport let currentLang: I18N_LANGS = \"\";\nconst missingTranslations = [] as string[];\n\nexport function __getMissingTranslations() {\n return missingTranslations;\n}\n\nlet __onMissingTranslations = (key: string) => console.warn(key);\nexport function __onMissingTranslation(callback: (key: string) => void) {\n __onMissingTranslations = callback;\n}\n\nconst msgCache = new Map<string, string>();\n\nexport function setLang(lang: I18N_LANGS) {\n if (lang === currentLang) return;\n currentLang = lang;\n msgCache.clear();\n}\n\nfunction _getMessage(key: string, lang: I18N_LANGS) {\n if (key.trim() == \"\") return key;\n\n const msgs = allMessages[key] ?? undefined;\n\n if (lang == \"\") {\n lang = \"def\";\n }\n let msg = msgs?.[lang];\n\n if (!msg) {\n if (missingTranslations.indexOf(key) === -1) {\n __onMissingTranslations(key);\n missingTranslations.push(key);\n }\n msg = msgs?.def;\n }\n return msg ?? key;\n}\n\nfunction getMessage(key: string) {\n if (msgCache.has(key)) return msgCache.get(key) as string;\n const msg = _getMessage(key, currentLang);\n msgCache.set(key, msg);\n return msg;\n}\n\n/**\n * Translate message to each locale\n * @param message {string} Message to translate\n * @param lang {I18N_LANGS} (Optional) Language. If supplied, this result cannot be cached. Do not use this in tight loop.\n * @returns Translated message\n */\nexport function $t(message: string, lang?: I18N_LANGS) {\n if (lang !== undefined) {\n return _getMessage(message, lang);\n }\n return getMessage(message);\n}\n\n/**\n * TagFunction to Automatically translate.\n * @param strings\n * @param values\n * @returns\n */\nexport function $f(strings: TemplateStringsArray, ...values: string[]) {\n let result = \"\";\n for (let i = 0; i < values.length; i++) {\n result += getMessage(strings[i]) + values[i];\n }\n result += getMessage(strings[strings.length - 1]);\n return result;\n}\n\n/**\n * Translate message to each locale and replace placeholders.\n * @param key {string} Message identifier.\n * @param params {Record<string, string>} Parameters to replace placeholders.\n * @param lang {I18N_LANGS} (Optional) Language.\n * @returns Translated and formatted message.\n */\nexport function $msg<T extends AllMessageKeys>(\n key: T,\n params: Record<string, string> = {},\n lang?: I18N_LANGS\n): TaggedType<string, T> {\n let msg = $t(key, lang);\n for (const [placeholder, value] of Object.entries(params)) {\n const regex = new RegExp(`\\\\\\${${placeholder}}`, \"g\");\n msg = msg.replace(regex, value);\n }\n return msg as TaggedType<string, T>;\n}\n","import { ReplicationService } from \"../../base/ReplicationService\";\nimport type { ServiceContext } from \"../../base/ServiceBase\";\n\nexport class InjectableReplicationService<T extends ServiceContext> extends ReplicationService<T> {}\n","import type { LiveSyncAbstractReplicator } from \"@lib/replication/LiveSyncAbstractReplicator\";\nimport { handlers } from \"@lib/services/lib/HandlerUtils\";\nimport type { IReplicatorService } from \"./IService\";\nimport { ServiceBase, type ServiceContext } from \"./ServiceBase\";\nimport type { SettingService } from \"./SettingService\";\nimport { createInstanceLogFunction } from \"../lib/logUtils\";\nimport type { AppLifecycleService } from \"./AppLifecycleService\";\nimport { UnresolvedErrorManager } from \"./UnresolvedErrorManager\";\nimport { $msg } from \"@lib/common/i18n\";\nimport { yieldMicrotask } from \"octagonal-wheels/promises\";\nimport type { DatabaseEventService } from \"./DatabaseEventService\";\nimport { LOG_LEVEL_NOTICE, LOG_LEVEL_VERBOSE } from \"@lib/common/logger\";\nimport { RemoteTypes } from \"@lib/common/types\";\nimport { DEFAULT_REPLICATION_STATICS } from \"../../common/models/shared.definition\";\nimport { reactiveSource } from \"octagonal-wheels/dataobject/reactive\";\n\nexport interface ReplicatorServiceDependencies {\n settingService: SettingService;\n appLifecycleService: AppLifecycleService;\n databaseEventService: DatabaseEventService;\n}\n/**\n * The ReplicatorService provides methods for managing replication.\n */\nexport abstract class ReplicatorService<T extends ServiceContext = ServiceContext>\n extends ServiceBase<T>\n implements IReplicatorService\n{\n _log = createInstanceLogFunction(\"ReplicatorService\");\n\n private settingService: SettingService;\n private databaseEventService: DatabaseEventService;\n private _activeReplicator: LiveSyncAbstractReplicator | undefined;\n private _replicatorType: string | undefined;\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(dependencies.appLifecycleService);\n this.settingService = dependencies.settingService;\n this.settingService.onRealiseSetting.addHandler(this._initialiseReplicator.bind(this));\n this.databaseEventService = dependencies.databaseEventService;\n this.databaseEventService.onResetDatabase.addHandler(this.disposeReplicator.bind(this));\n this.databaseEventService.onDatabaseInitialisation.addHandler(this.disposeReplicator.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 }\n\n private suspendReplication() {\n const activeReplicator = this.getActiveReplicator();\n if (activeReplicator) {\n activeReplicator.closeReplication();\n }\n return Promise.resolve(true);\n }\n\n private async reinitialiseReplicator() {\n await this.disposeReplicator();\n await yieldMicrotask();\n return this._initialiseReplicator();\n }\n private async disposeReplicator() {\n this._log(\"Detect database reset, closing active replicator if exists.\");\n if (this._activeReplicator) {\n await this._activeReplicator.closeReplication();\n }\n // To flush e2ee salts, device id, and other information kept in the replicator instance, to avoid potential database corruption after reset.\n\n this._activeReplicator = undefined;\n this._replicatorType = undefined;\n return true;\n }\n\n private async _initialiseReplicator() {\n const message = $msg(\"Replicator.Message.InitialiseFatalError\");\n const setting = this.settingService.currentSettings();\n if (!setting) {\n this._activeReplicator = undefined;\n this._replicatorType = undefined;\n this._unresolvedErrorManager.showError(message, LOG_LEVEL_NOTICE);\n return false;\n }\n const replicatorType = setting.remoteType;\n if (replicatorType === this._replicatorType && this._activeReplicator) {\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 const newReplicator = await this.getNewReplicator();\n if (!newReplicator) {\n this._unresolvedErrorManager.showError(message, LOG_LEVEL_NOTICE);\n return false;\n }\n // Check existing replicator and close it if exists.\n if (this._activeReplicator) {\n await this._activeReplicator.closeReplication();\n this._log(\"Active replicator closed\", LOG_LEVEL_VERBOSE);\n }\n this._activeReplicator = newReplicator;\n this._replicatorType = replicatorType;\n\n // Reset replication statics when replicator changes.\n this.replicationStatics.value = { ...DEFAULT_REPLICATION_STATICS };\n await yieldMicrotask();\n // Probably we need to clear all synchronising parameters handlers\n // Note that parameters handler keeps an key-deriving salt in memory,\n // so we need to clear them when the replicator changes, to avoid potential database corruption.\n if (!(await this.onReplicatorInitialised())) {\n this._log(\"Failed to initialise the replicator, onReplicatorInitialised reported some problems.\");\n this._activeReplicator = undefined;\n this._replicatorType = undefined;\n this._unresolvedErrorManager.showError(message, LOG_LEVEL_NOTICE);\n return false;\n }\n const remoteTypeDisplay = replicatorType === RemoteTypes.REMOTE_COUCHDB ? \"CouchDB\" : replicatorType;\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 * Close the active replication if any.\n * Not used currently.\n */\n readonly onCloseActiveReplication = handlers<IReplicatorService>().anySuccess(\"onCloseActiveReplication\");\n\n /**\n * Get a new replicator instance based on the provided settings.\n */\n readonly getNewReplicator = handlers<IReplicatorService>().firstResult(\"getNewReplicator\");\n\n readonly onReplicatorInitialised = handlers<IReplicatorService>().bailFirstFailure(\"onReplicatorInitialised\");\n\n /**\n * Get the currently active replicator instance.\n * If no active replicator, return undefined but that is the fatal situation (on Obsidian).\n */\n getActiveReplicator(): LiveSyncAbstractReplicator | undefined {\n const message = \"No replicator has been activated or has not been initialised yet.\";\n if (!this._activeReplicator) {\n this._unresolvedErrorManager.showError(message, LOG_LEVEL_NOTICE);\n return undefined;\n }\n this._unresolvedErrorManager.clearError(message);\n return this._activeReplicator;\n }\n\n replicationStatics = reactiveSource({ ...DEFAULT_REPLICATION_STATICS });\n}\n","import { ReplicatorService } from \"../../base/ReplicatorService\";\nimport type { ServiceContext } from \"../../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 \"../../base/IService\";\nimport type { ServiceContext } from \"../../base/ServiceBase\";\nimport { TestService } from \"../../base/TestService\";\nimport { handlers } from \"../../lib/HandlerUtils\";\n\nexport class InjectableTestService<T extends ServiceContext> extends TestService<T> {\n addTestResult = handlers<ITestService>().binder(\"addTestResult\");\n}\n","import type { RemoteDBSettings, TweakValues } 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<TweakValues | false>;\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 */\n abstract checkAndAskResolvingMismatched(preferred: Partial<TweakValues>): 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 */\n abstract askResolvingMismatched(preferredSource: TweakValues): 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 \"../../base/IService\";\nimport type { ServiceContext } from \"../../base/ServiceBase\";\nimport { TweakValueService } from \"../../base/TweakValueService\";\nimport { handlers } from \"../../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/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>().bailFirstFailure(\"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 keepFileCheckList Whether to keep the file in the check list.\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 \"../../base/IService\";\nimport type { ServiceContext } from \"../../base/ServiceBase\";\nimport { VaultService } from \"../../base/VaultService\";\nimport { handlers } from \"../../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/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 { eventHub } from \"../../hub/hub\";\nimport { EVENT_PLATFORM_UNLOADED, EVENT_PLUGIN_UNLOADED } from \"../../events/coreEvents\";\nimport { cancelAllPeriodicTask, cancelAllTasks } from \"octagonal-wheels/concurrency/task\";\nimport { stopAllRunningProcessors } from \"octagonal-wheels/concurrency/processor\";\nimport { $msg } from \"../../common/i18n\";\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 eventHub.emitEvent(EVENT_PLUGIN_UNLOADED);\n await this.services.appLifecycleService.onBeforeUnload();\n await 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 const activeReplicator = this.services.replicatorService.getActiveReplicator();\n if (activeReplicator) {\n activeReplicator.closeReplication();\n }\n localDatabase.onunload();\n await localDatabase.close();\n }\n eventHub.emitEvent(EVENT_PLATFORM_UNLOADED);\n eventHub.offAll();\n this._log($msg(\"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 { FilePathWithPrefix, ObsidianLiveSyncSettings } from \"../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\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\";\nexport const EVENT_DOCUMENT_STUB_CREATED = \"document-stub-created\";\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\";\n\n// export const EVENT_FILE_CHANGED = \"file-changed\";\n\ndeclare global {\n interface LSEvents {\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_DOCUMENT_STUB_CREATED]: {\n toc: Set<string>;\n stub: { [key: string]: { [key: string]: Map<string, Record<string, string>> } };\n };\n [EVENT_FILE_RENAMED]: { newPath: FilePathWithPrefix; old: FilePathWithPrefix };\n\n [EVENT_DATABASE_REBUILT]: undefined;\n [EVENT_REQUEST_OPEN_P2P_SETTINGS]: 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 }\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 protected 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 \"../../base/ConfigService\";\nimport { ControlService } from \"../../base/ControlService\";\nimport type { KeyValueDBService } from \"../../base/KeyValueDBService\";\nimport { PathService } from \"../../base/PathService\";\nimport type { ServiceContext } from \"../../base/ServiceBase\";\nimport type { SettingService } from \"../../base/SettingService\";\nimport { ServiceHub } from \"../../ServiceHub\";\nimport type { UIService } from \"../base/UIService\";\nimport { InjectableAPIService } from \"./InjectableAPIService\";\nimport { type AppLifecycleServiceBase } from \"./InjectableAppLifecycleService\";\nimport { InjectableConflictService } from \"./InjectableConflictService\";\nimport { InjectableDatabaseEventService } from \"./InjectableDatabaseEventService\";\nimport { InjectableFileProcessingService } from \"./InjectableFileProcessingService\";\nimport { 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 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 =\n services.remote ??\n new InjectableRemoteService<T>(context, {\n APIService: this._api,\n appLifecycle: this._appLifecycle,\n setting: this._setting,\n });\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, SvelteDialogManagerBase } from \"@lib/UI/svelteDialog\";\nimport type { IAPIService, IUIService } from \"@lib/services/base/IService\";\n\nimport { type AppLifecycleService } from \"@lib/services/base/AppLifecycleService.ts\";\nimport { ServiceBase, type ServiceContext } from \"@lib/services/base/ServiceBase\";\n\nexport type UIServiceDependencies<T extends ServiceContext = ServiceContext> = {\n appLifecycle: AppLifecycleService<T>;\n dialogManager: SvelteDialogManagerBase<T>;\n APIService: IAPIService;\n};\n\nexport abstract class UIService<T extends ServiceContext = ServiceContext>\n extends ServiceBase<T>\n implements IUIService\n{\n private _dialogManager: SvelteDialogManagerBase<T>;\n protected _APIService: IAPIService;\n abstract get dialogToCopy(): ComponentHasResult<\"ok\" | \"cancel\", { title: string; dataToCopy: string }>;\n constructor(context: T, dependents: UIServiceDependencies<T>) {\n super(context);\n this._dialogManager = dependents.dialogManager;\n this._APIService = dependents.APIService;\n }\n get dialogManager(): SvelteDialogManagerBase<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(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 \"../../interfaces/Confirm\";\nimport { reactiveSource } from \"octagonal-wheels/dataobject/reactive\";\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: any, 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 * 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(type: string, factory: (leaf: any) => any): 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) => any): 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>) => any): 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 globalThis) {\n return 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 globalThis.setInterval(handler, timeout) as unknown as number;\n }\n\n clearInterval(timerId: number): void {\n globalThis.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 \"../../base/APIService\";\nimport type { IAPIService } from \"../../base/IService\";\nimport type { ServiceContext } from \"../../base/ServiceBase\";\nimport { handlers } from \"../../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 \"../../base/IService\";\nimport type { Confirm } from \"@lib/interfaces/Confirm\";\n// const module = await import(\"node:crypto\");\nimport module from \"node:crypto\";\ndeclare const MANIFEST_VERSION: string | undefined;\n// declare const PACKAGE_VERSION: string | undefined;\nexport class HeadlessConfirm implements Confirm {\n askYesNo(message: string): Promise<\"yes\" | \"no\"> {\n throw new Error(\"Method not implemented.\");\n }\n askString(title: string, key: string, placeholder: string, isPassword?: boolean): Promise<string | false> {\n throw new Error(\"Method not implemented.\");\n }\n askYesNoDialog(\n message: string,\n opt: { title?: string; defaultOption?: \"Yes\" | \"No\"; timeout?: number }\n ): Promise<\"yes\" | \"no\"> {\n throw new Error(\"Method not implemented.\");\n }\n askSelectString(message: string, items: string[]): Promise<string> {\n throw new Error(\"Method not implemented.\");\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 throw new Error(\"Method not implemented.\");\n }\n askInPopup(key: string, dialogText: string, anchorCallback: (anchor: HTMLAnchorElement) => void): void {\n throw new Error(\"Method not implemented.\");\n }\n confirmWithMessage(\n title: string,\n contentMd: string,\n buttons: string[],\n defaultAction: (typeof buttons)[number],\n timeout?: number\n ): Promise<(typeof buttons)[number] | false> {\n throw new Error(\"Method not implemented.\");\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 }\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 document?.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","// Stub: KeyValueDB not used in Node (uses IndexedDB in browser)\nexport function OpenKeyValueDatabase(_name: string): any {\n return {\n get: async () => undefined,\n set: async () => {},\n del: async () => {},\n keys: async () => [],\n close: async () => {},\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 } from \"../../interfaces/KeyValueDatabase\";\nimport { OpenKeyValueDatabase } from \"@/common/KeyValueDB\";\nimport { delay, yieldMicrotask } from \"octagonal-wheels/promises\";\nimport { LOG_LEVEL_NOTICE, LOG_LEVEL_VERBOSE } from \"../../common/logger\";\nimport { createInstanceLogFunction } from \"../lib/logUtils\";\nimport type { InjectableDatabaseEventService } from \"../implements/injectable/InjectableDatabaseEventService\";\nimport type { AppLifecycleServiceBase } from \"../implements/injectable/InjectableAppLifecycleService\";\n\nexport interface KeyValueDBDependencies<T extends ServiceContext = ServiceContext> {\n databaseEvents: InjectableDatabaseEventService<T>;\n vault: IVaultService;\n appLifecycle: AppLifecycleServiceBase<T>;\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<any> | 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 _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 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 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<any>(\"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.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 openSimpleStore<T>(kind: string) {\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: any): 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 (\n from: string | undefined,\n to: string | undefined,\n count?: number | undefined\n ): Promise<string[]> => {\n const ret = await getDB().keys(\n IDBKeyRange.bound(`${prefix}${from || \"\"}`, `${prefix}${to || \"\"}`),\n count\n );\n return ret\n .map((e) => e.toString())\n .filter((e) => e.startsWith(prefix))\n .map((e) => e.substring(prefix.length));\n },\n db: Promise.resolve(getDB()),\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/HandlerUtils\";\nimport { createInstanceLogFunction } from \"@lib/services/lib/logUtils.ts\";\nimport { PouchDB } from \"@lib/pouchdb/pouchdb-browser.ts\";\nimport { ExtraSuffixIndexedDB } from \"@lib/common/models/shared.const.ts\";\nimport { $msg } from \"@lib/common/i18n.ts\";\nimport type { SettingService } from \"./SettingService\";\nimport type { APIService } from \"./APIService\";\nimport type { ObsidianLiveSyncSettings } from \"../../common/models/setting.type\";\n\nexport type DatabaseServiceDependencies = {\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 /**\n * Called after the local database has been reset.\n */\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 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($msg(\"moduleLocalDatabase.logWaitingForReady\"));\n const env = {\n services: {\n ...this.services,\n ...params,\n database: this,\n },\n };\n this._localDatabase = new LiveSyncLocalDB(vaultName, env);\n await this.onOpenDatabase(vaultName);\n\n return await this.localDatabase.initializeDatabase();\n }\n\n isDatabaseReady(): boolean {\n return this._localDatabase != null && this._localDatabase.isReady;\n }\n\n async resetDatabase(): Promise<boolean> {\n if (!this._localDatabase) {\n return Promise.resolve(true);\n }\n return await this._localDatabase.resetDatabase();\n }\n}\n","import { KeyValueDBService } from \"../../base/KeyValueDBService\";\nimport type { ServiceContext } from \"../../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","// Stub: re-export from octagonal-wheels\nexport { Logger, LOG_LEVEL_NOTICE, LOG_LEVEL_INFO, LOG_LEVEL_VERBOSE } from \"octagonal-wheels/common/logger\";\n","import type { ConfigService } from \"@lib/services/base/ConfigService\";\nimport type { AppLifecycleService } from \"@lib/services/base/AppLifecycleService\";\nimport type { ReplicatorService } from \"@lib/services/base/ReplicatorService\";\nimport type { Confirm } from \"@/lib/src/interfaces/Confirm\";\nimport { getContext, mount, setContext, unmount, type Component } from \"svelte\";\nimport { LOG_LEVEL_NOTICE, Logger } from \"@/lib/src/common/logger\";\nimport { fireAndForget, promiseWithResolvers, type PromiseWithResolvers } from \"octagonal-wheels/promises\";\nimport { eventHub } from \"@/lib/src/hub/hub\";\nimport { EVENT_PLUGIN_UNLOADED } from \"@/lib/src/events/coreEvents\";\n\nimport type { ServiceContext } from \"@lib/services/base/ServiceBase\";\nimport type { IControlService } from \"../../base/IService\";\n\nexport type SvelteDialogManagerDependencies<T extends ServiceContext = ServiceContext> = {\n appLifecycle: AppLifecycleService<T>;\n replicator: ReplicatorService<T>;\n config: ConfigService<T>;\n confirm: Confirm;\n control: IControlService;\n};\n\nexport type HasSetResult<T = any> = {\n setResult: (result: T) => void;\n};\nexport type HasGetInitialData<T = any> = {\n getInitialData?: () => T | undefined;\n};\nexport type ComponentHasResult<T = any, U = any> = Component<HasSetResult<T> & HasGetInitialData<U>>;\nexport type GuestDialogProps<T = any, U = any> = HasSetResult<T> & HasGetInitialData<U>;\nexport type DialogSvelteComponentBaseProps = {\n // component: Component;\n setTitle: (title: string) => void;\n closeDialog: () => void;\n} & HasSetResult &\n HasGetInitialData;\n\nexport type DialogControlBase<T = any, U = any> = {\n setTitle: (title: string) => void;\n closeDialog: () => void;\n} & HasSetResult<T> &\n HasGetInitialData<U>;\nexport type DialogHostProps = DialogSvelteComponentBaseProps & {\n /**\n * The Svelte component to mount inside the dialog host\n */\n mountComponent: ComponentHasResult<any>;\n /**\n * Callback function to setup the dialog context\n * @param props\n */\n onSetupContext?(props: DialogSvelteComponentBaseProps): void;\n};\nexport type DialogContext<C extends ServiceContext = ServiceContext, T = any, U = any> = DialogControlBase<T, U> & {\n context: C;\n services: SvelteDialogManagerDependencies<C>;\n};\n\nexport const CONTEXT_DIALOG_CONTROLS = \"svelte-dialog-controls\";\nexport function setupDialogContext<T extends DialogContext>(controls: T) {\n setContext(CONTEXT_DIALOG_CONTROLS, controls);\n}\nexport function getDialogContext<T = any, U = any>(): DialogContext<ServiceContext, T, U> {\n return getContext<DialogContext<ServiceContext, T, U>>(CONTEXT_DIALOG_CONTROLS);\n}\n\ntype Constructor<TResult> = new (...args: any[]) => TResult;\n\nexport interface IModalBase {\n // context: C;\n contentEl: HTMLElement;\n // result?: T;\n // initialData?: U;\n close(): void;\n setTitle(title: string): void;\n onOpen(): void;\n onClose(): void;\n open(): void;\n}\nexport function SvelteDialogMixIn<TBase extends Constructor<IModalBase>>(TBase: TBase, d: Component<DialogHostProps>) {\n return class SvelteDialog<\n T,\n U,\n C extends ServiceContext = ServiceContext,\n > extends (TBase as Constructor<IModalBase>) {\n constructor(...args: any[]) {\n super(...args);\n }\n // plugin: ObsidianLiveSyncPlugin;\n private _context!: C;\n get context(): C {\n return this._context;\n }\n private dependents!: SvelteDialogManagerDependencies<C>;\n mountedComponent?: ReturnType<typeof mount>;\n component!: ComponentHasResult<T, U>;\n result?: T;\n initialData?: U;\n title: string = \"Self-hosted LiveSync - Setup Wizard\";\n\n initDialog(\n context: C,\n dependents: SvelteDialogManagerDependencies<C>,\n component: ComponentHasResult<T, U>,\n initialData?: U\n ) {\n this._context = context;\n this.dependents = dependents;\n this.component = component;\n this.initialData = initialData;\n }\n resolveResult() {\n this.resultPromiseWithResolvers?.resolve(this.result);\n this.resultPromiseWithResolvers = undefined;\n }\n resultPromiseWithResolvers?: PromiseWithResolvers<T | undefined>;\n override onOpen() {\n const { contentEl } = this;\n contentEl.empty();\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const dialog = this;\n\n if (this.resultPromiseWithResolvers) {\n this.resultPromiseWithResolvers.reject(\"Dialog opened again\");\n }\n const pr = promiseWithResolvers<any>();\n eventHub.once(EVENT_PLUGIN_UNLOADED, () => {\n if (this.resultPromiseWithResolvers === pr) {\n pr.reject(\"Plugin unloaded\");\n this.close();\n }\n });\n this.resultPromiseWithResolvers = pr;\n this.mountedComponent = mount(d, {\n target: contentEl,\n props: {\n onSetupContext: (props: DialogSvelteComponentBaseProps) => {\n setupDialogContext({\n ...props,\n context: this.context,\n services: this.dependents,\n } satisfies DialogContext<C>);\n },\n setTitle: (title: string) => {\n dialog.setTitle(title);\n },\n closeDialog: () => {\n dialog.close();\n },\n setResult: (result: T) => {\n this.result = result;\n },\n getInitialData: () => this.initialData,\n mountComponent: this.component,\n },\n });\n }\n waitForClose(): Promise<T | undefined> {\n if (!this.resultPromiseWithResolvers) {\n throw new Error(\"Dialog not opened yet\");\n }\n return this.resultPromiseWithResolvers.promise;\n }\n override onClose() {\n this.resolveResult();\n fireAndForget(async () => {\n if (this.mountedComponent) {\n await unmount(this.mountedComponent);\n }\n });\n }\n };\n}\n\nexport abstract class SvelteDialogManagerBase<T extends ServiceContext> {\n abstract openSvelteDialog<T, U>(component: ComponentHasResult<T, U>, initialData?: U): Promise<T | undefined>;\n\n protected _context: T;\n protected _dependents: SvelteDialogManagerDependencies<T>;\n get context(): T {\n return this._context;\n }\n\n get dependents(): SvelteDialogManagerDependencies<T> {\n return this._dependents;\n }\n\n constructor(c: T, dependents: SvelteDialogManagerDependencies<T>) {\n this._context = c;\n this._dependents = dependents;\n }\n async open<T, U>(component: ComponentHasResult<T, U>, initialData?: U): Promise<T | undefined> {\n return await this.openSvelteDialog<T, U>(component, initialData);\n }\n async openWithExplicitCancel<T, U>(component: ComponentHasResult<T, U>, initialData?: U): Promise<T> {\n for (let i = 0; i < 10; i++) {\n const ret = await this.openSvelteDialog<T, U>(component, initialData);\n if (ret !== undefined) {\n return ret;\n }\n if (this.dependents.control.hasUnloaded()) {\n throw new Error(\"Operation cancelled due to app shutdown.\");\n }\n Logger(\"Please select 'Cancel' explicitly to cancel this operation.\", LOG_LEVEL_NOTICE);\n }\n throw new Error(\"Operation Forcibly cancelled by user.\");\n }\n}\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 \"../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: ${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: ${error}`, LOG_LEVEL_VERBOSE);\n return false;\n }\n}\n","import {\n ChunkAlgorithmNames,\n DEFAULT_SETTINGS,\n LOG_LEVEL_NOTICE,\n LOG_LEVEL_URGENT,\n SALT_OF_PASSPHRASE,\n SETTING_KEY_P2P_DEVICE_NAME,\n type BucketSyncSetting,\n type ConfigPassphraseStore,\n type CouchDBConnection,\n type ObsidianLiveSyncSettings,\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/logUtils\";\nimport { isCloudantURI } from \"../../pouchdb/utils_couchdb\";\nimport { decryptString, encryptString } from \"../../encryption/stringEncryption\";\nimport { setLang } from \"../../common/i18n\";\n\nexport interface SettingServiceDependencies {\n APIService: IAPIService;\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\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 _log: ReturnType<typeof createInstanceLogFunction>;\n constructor(context: T, dependencies: SettingServiceDependencies) {\n super(context);\n this.APIService = dependencies.APIService;\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 // Adjust settings as needed\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 if (settings.enableChunkSplitterV2) {\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.setItem(lsKey, this.deviceAndVaultName);\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.setItem(dbKey, value);\n }\n getSmallConfig(key: string): string {\n const dbKey = this.getKey(key);\n return this.getItem(dbKey);\n }\n deleteSmallConfig(key: string): void {\n const dbKey = this.getKey(key);\n this.deleteItem(dbKey);\n }\n\n /**\n * Save the current settings to storage.\n */\n async saveSettingData() {\n this.saveDeviceAndVaultName();\n const settings = { ...this.settings };\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 if (this.usedPassphrase == \"\" && !(await this.getPassphrase(settings))) {\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.encryptConfigurationItem(settings.passphrase, settings);\n settings.passphrase = \"\";\n }\n }\n await this.saveData(settings);\n void this.onSettingSaved(settings);\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 * Suggest enabling optional features to the user.\n */\n readonly suggestOptionalFeatures = handlers<ISettingService>().all(\"suggestOptionalFeatures\");\n\n /**\n * Enable an optional feature and save to the settings.\n * It may also raised from `handleSuggestOptionalFeatures` if the user agrees.\n * @param mode The optional feature to enable.\n */\n readonly enableOptionalFeature = handlers<ISettingService>().all(\"enableOptionalFeature\");\n readonly onSettingLoaded = handlers<ISettingService>().dispatchParallel(\"onSettingLoaded\");\n readonly onSettingChanged = handlers<ISettingService>().dispatchParallel(\"onSettingChanged\");\n readonly onSettingSaved = handlers<ISettingService>().dispatchParallel(\"onSettingSaved\");\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: \" + ex, LOG_LEVEL_URGENT);\n return Promise.reject(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: \" + ex, LOG_LEVEL_URGENT);\n return Promise.reject(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.getItem(\"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 const dec = await decryptString(encrypted, passphrase + SALT_OF_PASSPHRASE);\n if (dec) {\n this.usedPassphrase = passphrase;\n return dec;\n }\n return false;\n }\n async encryptConfigurationItem(src: string, settings: ObsidianLiveSyncSettings) {\n if (this.usedPassphrase != \"\") {\n return await encryptString(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 encryptString(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 const passphrase = await this.getPassphrase(settings);\n if (passphrase === false) {\n this._log(\"No passphrase found for data.json! Verify configuration before syncing.\", LOG_LEVEL_URGENT);\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 }\n return settings;\n }\n\n async loadSettings(): Promise<void> {\n const settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()) as ObsidianLiveSyncSettings;\n\n if (typeof settings.isConfigured == \"undefined\") {\n // If migrated, mark true\n if (JSON.stringify(settings) !== JSON.stringify(DEFAULT_SETTINGS)) {\n settings.isConfigured = true;\n } else {\n //\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 setLang(this.settings.displayLanguage);\n\n await this.adjustSettings(this.settings);\n\n const lsKey =\n \"obsidian-live-sync-vaultanddevicename-\" +\n this.APIService.getSystemVaultName() +\n this.additionalSuffixOfDatabaseName();\n if (this.settings.deviceAndVaultName != \"\") {\n if (!this.getItem(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.getItem(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 // this.core.ignoreFiles = this.settings.ignoreFiles.split(\",\").map(e => e.trim());\n // eventHub.emitEvent(EVENT_REQUEST_RELOAD_SETTING_TAB);\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);\n } catch {\n return false;\n }\n }\n}\n","import { EVENT_SETTING_SAVED } from \"@lib/events/coreEvents\";\nimport type { ServiceContext } from \"../../base/ServiceBase\";\nimport { SettingService, type SettingServiceDependencies } from \"../../base/SettingService\";\nimport { EVENT_REQUEST_RELOAD_SETTING_TAB } from \"@/common/events\";\n\nimport { eventHub } from \"@lib/hub/hub\";\nimport type { ObsidianLiveSyncSettings } from \"@lib/common/types\";\nimport { handlers } from \"../../lib/HandlerUtils\";\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 eventHub.emitEvent(EVENT_SETTING_SAVED, settings);\n return Promise.resolve(true);\n });\n this.onSettingLoaded.addHandler((settings) => {\n eventHub.emitEvent(EVENT_REQUEST_RELOAD_SETTING_TAB);\n return Promise.resolve(true);\n });\n }\n protected setItem(key: string, value: string) {\n return localStorage.setItem(key, value);\n }\n protected getItem(key: string): string {\n return localStorage.getItem(key) ?? \"\";\n }\n protected deleteItem(key: string): void {\n 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","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 { SvelteDialogManagerBase, type ComponentHasResult } 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 { IControlService } from \"./base/IService\";\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> extends SvelteDialogManagerBase<T> {\n openSvelteDialog<T, U>(component: ComponentHasResult<T, U>, initialData?: U): Promise<T | undefined> {\n throw new Error(\"Method not implemented.\");\n }\n}\n\ntype HeadlessUIServiceDependencies<T extends ServiceContext = ServiceContext> = {\n appLifecycle: AppLifecycleService<T>;\n config: ConfigServiceBrowserCompat<T>;\n replicator: InjectableReplicatorService<T>;\n APIService: HeadlessAPIService<T>;\n control: IControlService;\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 headlessConfirm = dependents.APIService.confirm;\n const headlessSvelteDialogManager = new HeadlessSvelteDialogManager<T>(context, {\n confirm: headlessConfirm,\n appLifecycle: dependents.appLifecycle,\n config: dependents.config,\n replicator: dependents.replicator,\n control: dependents.control,\n });\n super(context, {\n appLifecycle: dependents.appLifecycle,\n dialogManager: headlessSvelteDialogManager,\n APIService: dependents.APIService,\n });\n }\n}\ntype Constructor<T> = new (...args: any[]) => T;\n\nexport class HeadlessServiceHub<T extends ServiceContext> extends InjectableServiceHub<T> {\n constructor(\n _context?: T,\n overrideServiceConstructor: {\n database?: Constructor<DatabaseService<T>>;\n } = {}\n ) {\n const context = (_context ?? new ServiceContext()) as T;\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 });\n const appLifecycle = new HeadlessAppLifecycleService<T>(context, {\n settingService: setting,\n });\n const remote = new InjectableRemoteService(context, {\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 });\n const database = new (overrideServiceConstructor.database ?? HeadlessDatabaseService<T>)(context, {\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 });\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 appLifecycle: appLifecycle,\n databaseEvents: databaseEvents,\n vault: vault,\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 appLifecycle,\n config,\n replicator,\n APIService: API,\n control: control,\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 { deriveContent } from \"./index-sync.js\";\nimport { classifyIds, type IdFormat } from \"./id-format.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\nexport class Vault implements VaultBackend {\n private manipulator: DirectFileManipulator;\n private passphrase: string | undefined;\n private config: VaultConfig;\n\n constructor(config: VaultConfig) {\n this.config = config;\n this.passphrase = config.passphrase;\n this.manipulator = new DirectFileManipulator(Vault.buildOptions(config, !!config.obfuscatePaths));\n }\n\n private static buildOptions(config: VaultConfig, obfuscatePaths: boolean): 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: false,\n doNotUseFixedRevisionForChunks: false,\n };\n }\n\n async init(): Promise<void> {\n await this.manipulator.ready.promise;\n await this.reconcileObfuscation();\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 await this.manipulator.close();\n this.manipulator = new DirectFileManipulator(Vault.buildOptions(this.config, actual));\n await this.manipulator.ready.promise;\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 (meta.path ?? \"\").endsWith(\".md\");\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 (!path.endsWith(\".md\")) 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 ): 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 { continue; }\n }\n if (!path.endsWith(\".md\") && !meta.deleted) continue;\n const doc = await this.manipulator.getByMeta(meta).catch(() => null);\n if (doc) Vault.docToChange(doc, callback);\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 if (!path || path.startsWith(\"/\") || path.includes(\"\\0\") || path.includes(\"..\") || path.length > 1000) {\n throw new Error(\"Invalid path\");\n }\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 (!notePath.endsWith(\".md\")) 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 * 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"],"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,aAAa,CAAC,WAAW,OAAO,WAAW,UAAU;;;ACnB3D,IAAM,iBAAiB,uBAAO,gBAAgB;AAC9C,IAAM,mBAAmB,uBAAO,kBAAkB;AAKlD,IAAM,cAAc,uBAAO,MAAM;AACjC,IAAM,gBAAgB,uBAAO,QAAQ;AACrC,IAAM,OAAO,uBAAO,MAAM;;;ACR1B,IAAM,mBAAmB;AAIzB,IAAM,oBAAoB;AAC1B,IAAM,wBAAwB;AAC9B,IAAM,0CAA0C;AAGhD,IAAM,qBAAqB;AAC3B,IAAM,aAAa;AACnB,IAAM,kBAAkB;AAExB,IAAM,aAAa;AAAA,EACtB,YAAY;AAAA,EACZ,OAAO;AAAA,EACP,gBAAgB;AACpB;AAIO,IAAM,oBAAoB;AAQ1B,I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D;AAEJ;","names":["error","isValidChunk","FallbackWeakRef","module","unique","webcrypto","delay","unique","regExp","isTextBlob","isTextBlob","gen","w","changes","promiseWithResolvers","Logger","LOG_LEVEL_VERBOSE","Logger","LOG_LEVEL_VERBOSE","FallbackWeakRef","promiseWithResolvers","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","eventHub","eventHub","reactiveSource","PartialMessages","PartialMessages","PartialMessages","PartialMessages","PartialMessages","PartialMessages","PartialMessages","reactiveSource","reactiveSource","LOG_LEVEL_URGENT","promiseWithResolvers","LOG_LEVEL_URGENT","reactiveSource","webcrypto","delay","yieldMicrotask","yieldMicrotask","delay","Logger","LOG_LEVEL_NOTICE","LOG_LEVEL_INFO","LOG_LEVEL_VERBOSE","fireAndForget","promiseWithResolvers","Logger","LOG_LEVEL_NOTICE","decrypt","decrypt","replication","promiseWithResolvers","Logger","LOG_LEVEL_INFO","LOG_LEVEL_VERBOSE","LOG_LEVEL_NOTICE","LEVEL_INFO","isPathProbablyObfuscated","decrypt","BATCH_SIZE","isPathProbablyObfuscated","decrypt"]}
|