@dittolive/ditto 4.13.0 → 4.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- import{NativeModules,Platform}from"react-native";const REGISTRY_SWEEP_INTERVAL=1e4;class WeakRefBasedFinalizationRegistry{[Symbol.toStringTag]="FinalizationRegistry";counter=0;registrations=new Map;constructor(t){this.finalize=t}register(t,e,i){this.registrations.set(this.counter,{targetRef:new WeakRef(t),tokenRef:i?new WeakRef(i):void 0,value:e}),this.counter++,this.scheduleSweep()}unregister(t){if(!t)return!1;let e=!1;return this.registrations.forEach(((i,n)=>{i.tokenRef?.deref()===t&&(this.registrations.delete(n),e=!0)})),e}sweep=()=>{clearTimeout(this.sweepTimeout),this.sweepTimeout=void 0,this.registrations.forEach(((t,e)=>{if(void 0!==t.targetRef.deref())return;const i=t.value;this.registrations.delete(e),this.finalize(i)})),this.registrations.size>0&&this.scheduleSweep()};scheduleSweep(){this.sweepTimeout||(this.sweepTimeout=setTimeout(this.sweep,1e4))}}class WeakRefMock{[Symbol.toStringTag]="WeakRef";constructor(t){this.target=t}deref(){return this.target}static get[Symbol.toStringTag](){return"WeakRef"}}!function(t){function x(){}function y(){}var e=String.fromCharCode,i={}.toString,n=i.call(t.SharedArrayBuffer),r=i(),o=t.Uint8Array,s=o||Array,a=o?ArrayBuffer:s,c=a.isView||function(t){return t&&"length"in t},d=i.call(a.prototype);a=y.prototype;var l=t.TextEncoder,u=t.TextDecoder,f=new(o?Uint16Array:s)(32);x.prototype.decode=function(t){if(!c(t)){var a=i.call(t);if(a!==d&&a!==n&&a!==r)throw TypeError("Failed to execute 'decode' on 'TextDecoder': The provided value is not of type '(ArrayBuffer or ArrayBufferView)'");t=o?new s(t):t||[]}for(var l,u,h,_=a="",g=0,p=0|t.length,m=p-32|0,b=0,w=0,v=0,I=-1;g<p;){for(l=g<=m?32:p-g|0;v<l;g=g+1|0,v=v+1|0){switch((u=255&t[g])>>4){case 15:if(2!=(h=255&t[g=g+1|0])>>6||247<u){g=g-1|0;break}b=(7&u)<<6|63&h,w=5,u=256;case 14:b<<=6,b|=(15&u)<<6|63&(h=255&t[g=g+1|0]),w=2==h>>6?w+4|0:24,u=u+256&768;case 13:case 12:b<<=6,b|=(31&u)<<6|63&(h=255&t[g=g+1|0]),w=w+7|0,g<p&&2==h>>6&&b>>w&&1114112>b?(u=b,0<=(b=b-65536|0)&&(I=55296+(b>>10)|0,u=56320+(1023&b)|0,31>v?(f[v]=I,v=v+1|0,I=-1):(h=I,I=u,u=h))):(g=g-(u>>=8)-1|0,u=65533),b=w=0,l=g<=m?32:p-g|0;default:f[v]=u;continue;case 11:case 10:case 9:case 8:}f[v]=65533}if(_+=e(f[0],f[1],f[2],f[3],f[4],f[5],f[6],f[7],f[8],f[9],f[10],f[11],f[12],f[13],f[14],f[15],f[16],f[17],f[18],f[19],f[20],f[21],f[22],f[23],f[24],f[25],f[26],f[27],f[28],f[29],f[30],f[31]),32>v&&(_=_.slice(0,v-32|0)),g<p){if(f[0]=I,v=~I>>>31,I=-1,_.length<a.length)continue}else-1!==I&&(_+=e(I));a+=_,_=""}return a},a.encode=function(t){var e,i=0|(t=void 0===t?"":""+t).length,n=new s(8+(i<<1)|0),r=0,a=!o;for(e=0;e<i;e=e+1|0,r=r+1|0){var c=0|t.charCodeAt(e);if(127>=c)n[r]=c;else{if(2047>=c)n[r]=192|c>>6;else{t:{if(55296<=c)if(56319>=c){var d=0|t.charCodeAt(e=e+1|0);if(56320<=d&&57343>=d){if(65535<(c=(c<<10)+d-56613888|0)){n[r]=240|c>>18,n[r=r+1|0]=128|c>>12&63,n[r=r+1|0]=128|c>>6&63,n[r=r+1|0]=128|63&c;continue}break t}c=65533}else 57343>=c&&(c=65533);!a&&e<<1<r&&e<<1<(r-7|0)&&(a=!0,(d=new s(3*i)).set(n),n=d)}n[r]=224|c>>12,n[r=r+1|0]=128|c>>6&63}n[r=r+1|0]=128|63&c}}return o?n.subarray(0,r):n.slice(0,r)},l||(t.TextEncoder=y),u||(t.TextDecoder=x)}(""+void 0==typeof global?""+void 0==typeof self?void 0:self:global);const dittoCore=global,isLoaded="function"==typeof dittoCore.ditto_sdk_transports_init;if(!isLoaded){const t=NativeModules.DittoRNSDK?.install();if(!t)throw new Error("JSI bindings were not installed for: DittoRNSDK Module");if("android"===Platform.OS){if(!dittoCore.ditto_sdk_transports_set_android_context())throw new Error("Couldn't set Android context early. This is required for proper initialization.")}Platform.constants.reactNativeVersion.minor<=75&&setInterval((()=>{dittoCore.ditto_tick()}),50),"undefined"==typeof WeakRef&&(global.WeakRef=WeakRefMock),void 0===global.FinalizationRegistry&&(global.FinalizationRegistry=WeakRefBasedFinalizationRegistry);const e=Platform.select({ios:"iOS",android:"Android",macos:"macOS",default:"Unknown"});dittoCore.ditto_init_sdk_version(e,"JavaScript","4.13.0")}function ditto_sdk_transports_init(t){return dittoCore.ditto_sdk_transports_init(t)}function getMissingAndroidPermissions(){return"android"!==Platform.OS?[]:dittoCore.ditto_sdk_transports_android_missing_permissions()}function getPlatform(){return Platform.OS}function boxCBytesIntoBuffer(t){const e=dittoCore.sliceBoxedToUInt8Array(t);return e?new Uint8Array(e):null}function refCBytesIntoBuffer(t){const e=dittoCore.sliceRefToUInt8Array(t);return e?new Uint8Array(e):null}function dittoffi_differ_diff(...t){return boxCBytesIntoBuffer(dittoCore.dittoffi_differ_diff(...t))}function ditto_identity_config_make_online_playground(...t){return dittoCore.ditto_identity_config_make_online_playground(...t)}function ditto_identity_config_make_offline_playground(...t){return dittoCore.ditto_identity_config_make_offline_playground(...t)}function ditto_identity_config_make_shared_key(...t){return dittoCore.ditto_identity_config_make_shared_key(...t)}function ditto_identity_config_make_online_with_authentication(...t){return dittoCore.ditto_identity_config_make_online_with_authentication(...t)}function dittoffi_ditto_try_new_blocking(...t){return dittoCore.dittoffi_ditto_try_new_blocking(...t)}function dittoffi_DEFAULT_DATABASE_ID(...t){return dittoCore.dittoffi_DEFAULT_DATABASE_ID(...t)}function dittoffi_DITTO_DEVELOPMENT_PROVIDER(...t){return dittoCore.dittoffi_DITTO_DEVELOPMENT_PROVIDER(...t)}function dittoffi_ditto_config_default(...t){return dittoCore.dittoffi_ditto_config_default(...t)}function dittoffi_ditto_open_throws(...t){return dittoCore.dittoffi_ditto_open_throws(...t)}function ditto_shutdown(...t){return dittoCore.ditto_shutdown(...t)}function ditto_free(...t){return dittoCore.ditto_free(...t)}function dittoffi_ditto_is_activated(...t){return dittoCore.dittoffi_ditto_is_activated(...t)}function dittoffi_ditto_is_sync_active(...t){return dittoCore.dittoffi_ditto_is_sync_active(...t)}function dittoffi_ditto_try_start_sync(...t){return dittoCore.dittoffi_ditto_try_start_sync(...t)}function dittoffi_ditto_stop_sync(...t){return dittoCore.dittoffi_ditto_stop_sync(...t)}function dittoffi_ditto_try_set_transport_config(...t){return dittoCore.dittoffi_ditto_try_set_transport_config(...t)}function dittoffi_ditto_transport_config(...t){return dittoCore.dittoffi_ditto_transport_config(...t)}function dittoffi_ditto_set_cloud_sync_enabled(...t){return dittoCore.dittoffi_ditto_set_cloud_sync_enabled(...t)}function refCStringToString(...t){return dittoCore.refCStringToString(...t)}function boxCStringIntoString(...t){return dittoCore.boxCStringIntoString(...t)}function withOutBoxCBytes(...t){return dittoCore.withOutBoxCBytes(...t)}function ditto_auth_client_get_app_id(...t){return dittoCore.ditto_auth_client_get_app_id(...t)}function ditto_auth_client_is_web_valid(...t){return dittoCore.ditto_auth_client_is_web_valid(...t)}function ditto_auth_client_get_site_id(...t){return dittoCore.ditto_auth_client_get_site_id(...t)}function ditto_auth_client_make_login_provider(...t){return dittoCore.ditto_auth_client_make_login_provider(...t)}function ditto_auth_set_login_provider(...t){return dittoCore.ditto_auth_set_login_provider(...t)}function ditto_auth_client_login_with_token(...t){return dittoCore.ditto_auth_client_login_with_token(...t)}function ditto_auth_client_login_with_token_and_feedback(...t){return dittoCore.ditto_auth_client_login_with_token_and_feedback(...t)}function ditto_auth_client_login_with_credentials(...t){return dittoCore.ditto_auth_client_login_with_credentials(...t)}function ditto_auth_client_logout(...t){return dittoCore.ditto_auth_client_logout(...t)}function ditto_auth_client_user_id(...t){return dittoCore.ditto_auth_client_user_id(...t)}function dittoffi_ditto_set_authentication_status_handler(...t){return dittoCore.dittoffi_ditto_set_authentication_status_handler(...t)}function dittoffi_authentication_status_is_authenticated(...t){return dittoCore.dittoffi_authentication_status_is_authenticated(...t)}function dittoffi_authentication_status_user_id(...t){return dittoCore.dittoffi_authentication_status_user_id(...t)}function dittoffi_authentication_status_free(...t){return dittoCore.dittoffi_authentication_status_free(...t)}function dittoffi_try_experimental_register_change_observer_str_detached(...t){return dittoCore.dittoffi_try_experimental_register_change_observer_str_detached(...t)}function dittoffi_try_add_sync_subscription(...t){return dittoCore.dittoffi_try_add_sync_subscription(...t)}function dittoffi_try_remove_sync_subscription(...t){return dittoCore.dittoffi_try_remove_sync_subscription(...t)}function dittoffi_try_exec_statement(...t){return dittoCore.dittoffi_try_exec_statement(...t)}function dittoffi_query_result_item_count(...t){return dittoCore.dittoffi_query_result_item_count(...t)}function dittoffi_query_result_item_at(...t){return dittoCore.dittoffi_query_result_item_at(...t)}function dittoffi_query_result_item_new(...t){return dittoCore.dittoffi_query_result_item_new(...t)}function dittoffi_query_result_has_commit_id(...t){return dittoCore.dittoffi_query_result_has_commit_id(...t)}function dittoffi_query_result_commit_id(...t){return dittoCore.dittoffi_query_result_commit_id(...t)}function dittoffi_query_result_mutated_document_id_count(...t){return dittoCore.dittoffi_query_result_mutated_document_id_count(...t)}function dittoffi_query_result_mutated_document_id_at(...t){return dittoCore.dittoffi_query_result_mutated_document_id_at(...t)}function dittoffi_query_result_item_cbor(...t){return dittoCore.dittoffi_query_result_item_cbor(...t)}function dittoffi_query_result_item_json(...t){return dittoCore.dittoffi_query_result_item_json(...t)}function ditto_document_id_query_compatible(...t){return dittoCore.ditto_document_id_query_compatible(...t)}function ditto_document_id(...t){return dittoCore.ditto_document_id(...t)}function ditto_document_free(...t){return dittoCore.ditto_document_free(...t)}function ditto_validate_document_id(...t){return dittoCore.ditto_validate_document_id(...t)}function ditto_presence_v3(...t){return dittoCore.ditto_presence_v3(...t)}function ditto_register_presence_v3_callback(...t){return dittoCore.ditto_register_presence_v3_callback(...t)}function ditto_clear_presence_v3_callback(...t){return dittoCore.ditto_clear_presence_v3_callback(...t)}function dittoffi_presence_peer_metadata_json(...t){return dittoCore.dittoffi_presence_peer_metadata_json(...t)}function dittoffi_presence_try_set_peer_metadata_json(...t){return dittoCore.dittoffi_presence_try_set_peer_metadata_json(...t)}function dittoffi_presence_set_connection_request_handler(...t){return dittoCore.dittoffi_presence_set_connection_request_handler(...t)}function ditto_new_attachment_from_file(...t){return dittoCore.ditto_new_attachment_from_file(...t)}function ditto_new_attachment_from_bytes(...t){return dittoCore.ditto_new_attachment_from_bytes(...t)}function ditto_resolve_attachment(...t){return dittoCore.ditto_resolve_attachment(...t)}function ditto_cancel_resolve_attachment(...t){return dittoCore.ditto_cancel_resolve_attachment(...t)}function ditto_free_attachment_handle(...t){return dittoCore.ditto_free_attachment_handle(...t)}function ditto_get_complete_attachment_path(...t){return dittoCore.ditto_get_complete_attachment_path(...t)}function ditto_live_query_start(...t){return dittoCore.ditto_live_query_start(...t)}function ditto_live_query_stop(...t){return dittoCore.ditto_live_query_stop(...t)}function ditto_live_query_signal_available_next(...t){return dittoCore.ditto_live_query_signal_available_next(...t)}function ditto_log(...t){return dittoCore.ditto_log(...t)}function ditto_logger_init(...t){return dittoCore.ditto_logger_init(...t)}function ditto_logger_set_log_file(...t){return dittoCore.ditto_logger_set_log_file(...t)}function ditto_logger_minimum_log_level_get(...t){return dittoCore.ditto_logger_minimum_log_level_get(...t)}function ditto_logger_minimum_log_level(...t){return dittoCore.ditto_logger_minimum_log_level(...t)}function ditto_logger_emoji_headings_enabled_get(...t){return dittoCore.ditto_logger_emoji_headings_enabled_get(...t)}function ditto_logger_emoji_headings_enabled(...t){return dittoCore.ditto_logger_emoji_headings_enabled(...t)}function ditto_logger_enabled_get(...t){return dittoCore.ditto_logger_enabled_get(...t)}function ditto_logger_enabled(...t){return dittoCore.ditto_logger_enabled(...t)}function ditto_small_peer_info_get_is_enabled(...t){return dittoCore.ditto_small_peer_info_get_is_enabled(...t)}function ditto_small_peer_info_set_enabled(...t){return dittoCore.ditto_small_peer_info_set_enabled(...t)}function ditto_small_peer_info_get_sync_scope(...t){return dittoCore.ditto_small_peer_info_get_sync_scope(...t)}function ditto_small_peer_info_set_sync_scope(...t){return dittoCore.ditto_small_peer_info_set_sync_scope(...t)}function ditto_small_peer_info_get_metadata(...t){return dittoCore.ditto_small_peer_info_get_metadata(...t)}function ditto_small_peer_info_set_metadata(...t){return dittoCore.ditto_small_peer_info_set_metadata(...t)}function ditto_sdk_transports_error_new(...t){return dittoCore.ditto_sdk_transports_error_new(...t)}function ditto_sdk_transports_error_value(...t){return dittoCore.ditto_sdk_transports_error_value(...t)}function ditto_sdk_transports_error_free(...t){return dittoCore.ditto_sdk_transports_error_free(...t)}function dittoffi_connection_request_peer_key_string(...t){return dittoCore.dittoffi_connection_request_peer_key_string(...t)}function dittoffi_connection_request_peer_metadata_json(...t){return dittoCore.dittoffi_connection_request_peer_metadata_json(...t)}function dittoffi_connection_request_authorize(...t){return dittoCore.dittoffi_connection_request_authorize(...t)}function dittoffi_connection_request_free(...t){return dittoCore.dittoffi_connection_request_free(...t)}function dittoffi_connection_request_connection_type(...t){return dittoCore.dittoffi_connection_request_connection_type(...t)}function ditto_set_device_name(...t){return dittoCore.ditto_set_device_name(...t)}function ditto_get_sdk_version(...t){return dittoCore.ditto_get_sdk_version(...t)}function dittoffi_get_sdk_semver(...t){return dittoCore.dittoffi_get_sdk_semver(...t)}function ditto_error_message(...t){return dittoCore.ditto_error_message(...t)}function dittoffi_error_code(...t){return dittoCore.dittoffi_error_code(...t)}function dittoffi_error_description(...t){return dittoCore.dittoffi_error_description(...t)}function dittoffi_error_free(...t){return dittoCore.dittoffi_error_free(...t)}function dittoffi_try_verify_license(...t){return dittoCore.dittoffi_try_verify_license(...t)}function ditto_run_garbage_collection(...t){return dittoCore.ditto_run_garbage_collection(...t)}function ditto_disable_sync_with_v3(...t){return dittoCore.ditto_disable_sync_with_v3(...t)}function dittoffi_base64_encode(...t){return dittoCore.dittoffi_base64_encode(...t)}function dittoffi_try_base64_decode(...t){return dittoCore.dittoffi_try_base64_decode(...t)}function dittoffi_crypto_generate_secure_random_token(...t){return dittoCore.dittoffi_crypto_generate_secure_random_token(...t)}function readFile(...t){return dittoCore.readFile(...t)}function copyFile(...t){return dittoCore.copyFile(...t)}function getDefaultDirectory(){return dittoCore.defaultDirectory}function defaultDeviceName$1(...t){return dittoCore.defaultDeviceName(...t)}function dittoffi_ditto_absolute_persistence_directory(...t){return dittoCore.dittoffi_ditto_absolute_persistence_directory(...t)}function dittoffi_logger_try_export_to_file_async(...t){return dittoCore.dittoffi_logger_try_export_to_file_async(...t)}function ditto_logger_set_custom_log_cb(...t){return dittoCore.ditto_logger_set_custom_log_cb(...t)}function dittoffi_query_result_free(...t){return dittoCore.dittoffi_query_result_free(...t)}function dittoffi_query_result_item_free(...t){return dittoCore.dittoffi_query_result_item_free(...t)}function ditto_register_presence_v1_callback(...t){return dittoCore.ditto_register_presence_v1_callback(...t)}function ditto_clear_presence_callback(...t){return dittoCore.ditto_clear_presence_callback(...t)}function ditto_presence_v1(...t){return dittoCore.ditto_presence_v1(...t)}function dittoffi_differ_new(...t){return dittoCore.dittoffi_differ_new(...t)}function dittoffi_differ_free(...t){return dittoCore.dittoffi_differ_free(...t)}function dittoffi_store_transactions(...t){return dittoCore.dittoffi_store_transactions(...t)}function dittoffi_store_begin_transaction_async_throws(...t){return dittoCore.dittoffi_store_begin_transaction_async_throws(...t)}function dittoffi_transaction_complete_async_throws(...t){return dittoCore.dittoffi_transaction_complete_async_throws(...t)}function dittoffi_transaction_execute_async_throws(...t){return dittoCore.dittoffi_transaction_execute_async_throws(...t)}function dittoffi_transaction_info(...t){return dittoCore.dittoffi_transaction_info(...t)}function dittoffi_transaction_free(...t){return dittoCore.dittoffi_transaction_free(...t)}function ditto_register_transport_condition_changed_callback(...t){return dittoCore.ditto_register_transport_condition_changed_callback(...t)}function ditto_add_subscription(){throw new Error("ditto_add_subscription is not implemented in React Native.")}function ditto_remove_subscription(){throw new Error("ditto_remove_subscription is not implemented in React Native.")}function dittoffi_connection_request_identity_service_metadata_json(){throw new Error("Not implemented in React Native.")}const PREFIX_REGEX=new RegExp(/^<.*?>\s*/);class DittoFFIError extends Error{constructor(t,e,i){const n=ffiErrorMessage();super(e||n||i),this.code=t}}function throwOnErrorResult(t,e){if(null!==t){let i,n;try{i=dittoffi_error_code(t),n=boxCStringIntoString(dittoffi_error_description(t)),dittoffi_error_free(t)}catch(t){throw new DittoFFIError(-1,`Failed to retrieve Ditto core error message: ${t.message}`)}throw n=null==n?`${e}() failed with error code: ${i}`:n.replace(PREFIX_REGEX,""),new DittoFFIError(i,n)}}function ffiErrorMessage(){return boxCStringIntoString(ditto_error_message())}const DittoCRDTTypeKey="_ditto_internal_type_jkb12973t4b",DittoCRDTValueKey="_value";var DittoCRDTType;function DITTO_DEVELOPMENT_PROVIDER(){ensureInitialized();return refCStringToString(dittoffi_DITTO_DEVELOPMENT_PROVIDER())}function DEFAULT_DATABASE_ID(){ensureInitialized();return refCStringToString(dittoffi_DEFAULT_DATABASE_ID())}function differNew(){return ensureInitialized(),dittoffi_differ_new()}function differDiff(t,e){return ensureInitialized(),dittoffi_differ_diff(t,e)}function differFree(t){ensureInitialized(),dittoffi_differ_free(t)}function dittoPointerToStorePointer(t){return{addr:t.addr,type:"dittoffi_store_t const *"}}function documentID(t){ensureInitialized();return boxCBytesIntoBuffer(ditto_document_id(t))}function documentFree(t){ensureInitialized(),ditto_document_free(t)}function documentIDQueryCompatible(t,e){ensureInitialized();return boxCStringIntoString(ditto_document_id_query_compatible(t,e))}function validateDocumentID(t){ensureInitialized();return boxCBytesIntoBuffer(withOutBoxCBytes((e=>{const i=ditto_validate_document_id(t,e);if(0!==i)throw new Error(errorMessage()||`ditto_validate_document_id() failed with error code: ${i}`);return e})))}async function tryExecStatement(t,e,i){ensureInitialized();const n=bytesFromString(e),r=await dittoffi_try_exec_statement(t,n,i);return throwOnErrorResult(r.error,"dittoffi_try_exec_statement"),r.success}function addSubscription(t,e,i,n,r,o,s){ensureInitialized(),bytesFromString(e),bytesFromString(i);const a=ditto_add_subscription();if(0!==a)throw new Error(errorMessage()||`ditto_add_subscription() failed with error code: ${a}`)}function removeSubscription(t,e,i,n,r,o,s){ensureInitialized(),bytesFromString(e),bytesFromString(i);const a=ditto_remove_subscription();if(0!==a)throw new Error(errorMessage()||`ditto_remove_subscription() failed with error code: ${a}`)}function tryAddSyncSubscription(t,e,i){ensureInitialized();throwOnErrorResult(dittoffi_try_add_sync_subscription(t,bytesFromString(e),i).error,"dittoffi_try_add_sync_subscription")}function tryRemoveSyncSubscription(t,e,i){ensureInitialized();throwOnErrorResult(dittoffi_try_remove_sync_subscription(t,bytesFromString(e),i).error,"dittoffi_try_remove_sync_subscription")}function queryResultFree(t){ensureInitialized(),dittoffi_query_result_free(t)}function queryResultItemFree(t){ensureInitialized(),dittoffi_query_result_item_free(t)}function queryResultItems(t){ensureInitialized();const e=[],i=dittoffi_query_result_item_count(t);for(let n=0;n<i;n++)e.push(dittoffi_query_result_item_at(t,n));return e}function queryResultMutatedDocumentIDs(t){ensureInitialized();const e=[],i=dittoffi_query_result_mutated_document_id_count(t);for(let n=0;n<i;n++){const i=dittoffi_query_result_mutated_document_id_at(t,n);e.push(boxCBytesIntoBuffer(i))}return e}function queryResultHasCommitID(t){return ensureInitialized(),dittoffi_query_result_has_commit_id(t)}function queryResultCommitID(t){ensureInitialized();const e=dittoffi_query_result_commit_id(t);return BigInt(e)}function queryResultItemCBOR(t){ensureInitialized();return boxCBytesIntoBuffer(dittoffi_query_result_item_cbor(t))}function queryResultItemJSON(t){ensureInitialized();return boxCStringIntoString(dittoffi_query_result_item_json(t))}function queryResultItemNew(t){ensureInitialized();const e=dittoffi_query_result_item_new(t);return throwOnErrorResult(e.error,"dittoffi_query_result_item_new"),e.success}function tryExperimentalRegisterChangeObserver(t,e,i,n){ensureInitialized();const r=wrapBackgroundCbForFFI((t=>log("Error",`The registered store observer callback failed with ${t}`)),n),o=dittoffi_try_experimental_register_change_observer_str_detached(t,bytesFromString(e),i,r);return throwOnErrorResult(o.error,"dittoffi_try_experimental_register_change_observer_str_detached"),o.success}async function liveQueryStart(t,e){ensureInitialized();const i=await ditto_live_query_start(t,e);if(0!==i)throw new Error(errorMessage()||`\`ditto_live_query_start()\` failed with error code: ${i}`)}function liveQueryStop(t,e){ensureInitialized(),ditto_live_query_stop(t,e)}async function liveQuerySignalAvailableNext(t,e){ensureInitialized(),await ditto_live_query_signal_available_next(t,e)}function loggerInit(){ensureInitialized(),ditto_logger_init()}async function loggerSetCustomLogCb(t){if(ensureInitialized(),null===t)await ditto_logger_set_custom_log_cb(null);else{const e=wrapBackgroundCbForFFI(null,((e,i)=>{try{const n=boxCStringIntoString(i);t(e,n)}catch(t){log("Error",`The registered cb in \`ditto_logger_set_custom_log_cb()\` failed with: ${t}`)}}));await ditto_logger_set_custom_log_cb(e)}}function loggerEnabled(t){ensureInitialized(),ditto_logger_enabled(!!t)}function loggerEnabledGet(){return ensureInitialized(),!!ditto_logger_enabled_get()}function loggerEmojiHeadingsEnabled(t){ensureInitialized(),ditto_logger_emoji_headings_enabled(t)}function loggerEmojiHeadingsEnabledGet(){return ensureInitialized(),ditto_logger_emoji_headings_enabled_get()}function loggerMinimumLogLevel(t){ensureInitialized(),ditto_logger_minimum_log_level(t)}function loggerMinimumLogLevelGet(){return ensureInitialized(),ditto_logger_minimum_log_level_get()}function loggerSetLogFile(t){ensureInitialized();if(0!==ditto_logger_set_log_file(t?bytesFromString(t):null)){const t=errorMessage();throw new Error(`Can't set log file, due to error: ${t}`)}}async function loggerTryExportToFile(t){ensureInitialized();const e=bytesFromString(t),i=await new Promise(((t,i)=>{const n=wrapBackgroundCbForFFI(i,t);dittoffi_logger_try_export_to_file_async(e,n)}));return throwOnErrorResult(i.error,"dittoffi_logger_try_export_to_file_async"),i.success}function log(t,e){ensureInitialized();ditto_log(t,bytesFromString(e))}function dittoIdentityConfigMakeOnlinePlayground(t,e,i){ensureInitialized();const n=bytesFromString(t),r=bytesFromString(e),o=bytesFromString(i),{status_code:s,identity_config:a}=ditto_identity_config_make_online_playground(n,r,o);if(0!==s)throw new Error(errorMessage()||`ditto_identity_config_make_online_playground() failed with error code: ${s}`);return a}function dittoIdentityConfigMakeOnlineWithAuthentication(t,e){ensureInitialized();const i=bytesFromString(t),n=bytesFromString(e),{status_code:r,identity_config:o}=ditto_identity_config_make_online_with_authentication(i,n);if(0!==r)throw new Error(errorMessage()||`ditto_identity_config_make_online_with_authentication() failed with error code: ${r}`);return o}function dittoIdentityConfigMakeOfflinePlayground(t,e){ensureInitialized();const i=bytesFromString(t),n=Number(e),{status_code:r,identity_config:o}=ditto_identity_config_make_offline_playground(i,n);if(0!==r)throw new Error(errorMessage()||`ditto_identity_config_make_offline_playground() failed with error code: ${r}`);return o}function dittoIdentityConfigMakeSharedKey(t,e,i){ensureInitialized();const n=bytesFromString(t),r=bytesFromString(e),o=Number(i),{status_code:s,identity_config:a}=ditto_identity_config_make_shared_key(n,r,o);if(0!==s)throw new Error(errorMessage()||`ditto_identity_config_make_shared_key() failed with error code: ${s}`);return a}function dittoAuthClientGetSiteID(t){return ensureInitialized(),ditto_auth_client_get_site_id(t)}function dittoAuthClientGetAppID(t){ensureInitialized();return boxCStringIntoString(ditto_auth_client_get_app_id(t))}function dittoAuthClientUserID(t){ensureInitialized();return boxCStringIntoString(ditto_auth_client_user_id(t))}function dittoAuthClientIsWebValid(t){return ensureInitialized(),0!==ditto_auth_client_is_web_valid(t)}async function dittoAuthClientLoginWithTokenAndFeedback(t,e,i){ensureInitialized();const n=bytesFromString(e),r=bytesFromString(i),o=await ditto_auth_client_login_with_token_and_feedback(t,n,r);return{error:0===o.status_code?null:new DittoFFIError(o.status_code,void 0,"Ditto failed to authenticate."),clientInfo:o.c_string?boxCStringIntoString(o.c_string):null}}async function dittoAuthClientLoginWithToken(t,e,i){ensureInitialized();const n=bytesFromString(e),r=bytesFromString(i),o=await ditto_auth_client_login_with_token(t,n,r);if(0!==o)throw new Error(errorMessage()||`Ditto failed to authenticate (error code: ${o}).`)}async function dittoAuthClientLoginWithUsernameAndPassword(t,e,i,n){ensureInitialized();const r=bytesFromString(e),o=bytesFromString(i),s=bytesFromString(n),a=await ditto_auth_client_login_with_credentials(t,r,o,s);if(0!==a)throw new Error(errorMessage()||`Ditto failed to authenticate (error code: ${a}).`)}async function dittoAuthClientLogout(t){ensureInitialized();const e=await ditto_auth_client_logout(t);if(0!==e)throw new Error(errorMessage()||`Ditto failed to logout (error code: ${e}).`)}function dittoSetAuthenticationStatusHandler(t,e,i){ensureInitialized(),dittoffi_ditto_set_authentication_status_handler(t,wrapBackgroundCbForFFI(i,e))}function authenticationStatusUserID(t){return ensureInitialized(),boxCStringIntoString(dittoffi_authentication_status_user_id(t))}function authenticationStatusIsAuthenticated(t){return ensureInitialized(),dittoffi_authentication_status_is_authenticated(t)}function authenticationStatusFree(t){ensureInitialized(),dittoffi_authentication_status_free(t)}function storeTransactions(t){ensureInitialized();return boxCBytesIntoBuffer(dittoffi_store_transactions(t))}async function storeBeginTransaction(t,e){ensureInitialized();const i={is_read_only:e.isReadOnly,hint:bytesFromString(e.hint)};return new Promise(((e,n)=>{const r=wrapBackgroundCbForFFI(n,(t=>{throwOnErrorResult(t.error,"dittoffi_store_begin_transaction_async_throws"),e(t.success)}));dittoffi_store_begin_transaction_async_throws(t,i,r)}))}async function transactionCompleteAsync(t,e){return ensureInitialized(),new Promise(((i,n)=>{const r=wrapBackgroundCbForFFI(n,(t=>{throwOnErrorResult(t.error,"dittoffi_transaction_complete_async_throws");const e=t.success;i(e)}));dittoffi_transaction_complete_async_throws(t,e,r)}))}async function transactionExecuteAsync(t,e,i){return ensureInitialized(),new Promise(((n,r)=>{const o=wrapBackgroundCbForFFI(r,(t=>{throwOnErrorResult(t.error,"dittoffi_transaction_execute_async_throws"),n(t.success)})),s=bytesFromString(e);dittoffi_transaction_execute_async_throws(t,s,i,o)}))}function transactionInfo(t){ensureInitialized();return boxCBytesIntoBuffer(dittoffi_transaction_info(t))}function transactionFree(t){ensureInitialized(),dittoffi_transaction_free(t)}function dittoConfigDefault(){ensureInitialized();return boxCBytesIntoBuffer(dittoffi_ditto_config_default())}function dittoAbsolutePersistenceDirectory(t){ensureInitialized();return boxCStringIntoString(dittoffi_ditto_absolute_persistence_directory(t))}function dittoOpenThrows(t,e,i){ensureInitialized();const n=dittoffi_ditto_open_throws(t,e,bytesFromString(i));return throwOnErrorResult(n.error,"dittoffi_ditto_open_throws"),n.success}function dittoTryNewBlocking(t,e,i,n){ensureInitialized();const r=dittoffi_ditto_try_new_blocking(bytesFromString(t),e,i,bytesFromString(null),n);return throwOnErrorResult(r.error,"dittoffi_ditto_try_new_blocking"),r.success}function dittoFree(t){return ensureInitialized(),ditto_free(t)}function cryptoGenerateSecureRandomToken(){ensureInitialized();return boxCStringIntoString(dittoffi_crypto_generate_secure_random_token())}function dittoRegisterPresenceV1Callback(t,e){ensureInitialized(),ditto_register_presence_v1_callback(t,wrapBackgroundCbForFFI((t=>log("Error",`The registered presence callback v1 errored with ${t}`)),(t=>{const i=refCStringToString(t);e(i)})))}async function dittoClearPresenceCallback(t){return ensureInitialized(),ditto_clear_presence_callback(t)}function dittoRegisterPresenceV3Callback(t,e){ensureInitialized(),ditto_register_presence_v3_callback(t,wrapBackgroundCbForFFI((t=>log("Error",`The registered presence callback v3 errored with ${t}`)),(t=>{const i=refCStringToString(t);e(i)})))}async function dittoClearPresenceV3Callback(t){return ensureInitialized(),ditto_clear_presence_v3_callback(t)}function presencePeerMetadataJSON(t){ensureInitialized();const e=boxCBytesIntoBuffer(dittoffi_presence_peer_metadata_json(t));return(new TextDecoder).decode(e)}async function presenceTrySetPeerMetadataJSON(t,e){ensureInitialized();const i=bytesFromString(e);throwOnErrorResult((await dittoffi_presence_try_set_peer_metadata_json(t,i)).error,"dittoffi_presence_try_set_peer_metadata_json")}function connectionRequestPeerKeyString(t){ensureInitialized();return boxCStringIntoString(dittoffi_connection_request_peer_key_string(t))}function connectionRequestPeerMetadataJSON(t){ensureInitialized();const e=refCBytesIntoBuffer(dittoffi_connection_request_peer_metadata_json(t));return(new TextDecoder).decode(e)}function connectionRequestIdentityServiceMetadataJSON(t){ensureInitialized();const e=refCBytesIntoBuffer(dittoffi_connection_request_identity_service_metadata_json());return(new TextDecoder).decode(e)}function connectionRequestConnectionType(t){return ensureInitialized(),dittoffi_connection_request_connection_type(t)}function connectionRequestAuthorize(t,e){ensureInitialized(),dittoffi_connection_request_authorize(t,e)}function connectionRequestFree(t){ensureInitialized(),dittoffi_connection_request_free(t)}function presenceSetConnectionRequestHandler(t,e,i){if(ensureInitialized(),null==e)dittoffi_presence_set_connection_request_handler(t,null);else{dittoffi_presence_set_connection_request_handler(t,wrapAsyncBackgroundCbForFFI(i,e))}}function dittoIsActivated(t){return ensureInitialized(),dittoffi_ditto_is_activated(t)}function dittoIsSyncActive(t){return ensureInitialized(),dittoffi_ditto_is_sync_active(t)}function dittoTryStartSync(t){ensureInitialized();throwOnErrorResult(dittoffi_ditto_try_start_sync(t).error,"dittoffi_ditto_try_start_sync")}function dittoStopSync(t){return ensureInitialized(),dittoffi_ditto_stop_sync(t)}function dittoSetTransportConfig(t,e){ensureInitialized();throwOnErrorResult(dittoffi_ditto_try_set_transport_config(t,e,!0).error,"dittoffi_ditto_try_set_transport_config")}function dittoTransportConfig(t){ensureInitialized();return boxCBytesIntoBuffer(dittoffi_ditto_transport_config(t))}function dittoSetCloudSyncEnabled(t,e){ensureInitialized(),dittoffi_ditto_set_cloud_sync_enabled(t,e)}function dittoSmallPeerInfoGetIsEnabled(t){return ensureInitialized(),ditto_small_peer_info_get_is_enabled(t)}function dittoSmallPeerInfoSetEnabled(t,e){return ensureInitialized(),ditto_small_peer_info_set_enabled(t,e)}function dittoSmallPeerInfoGetSyncScope(t){return ensureInitialized(),ditto_small_peer_info_get_sync_scope(t)}function dittoSmallPeerInfoSetSyncScope(t,e){return ensureInitialized(),ditto_small_peer_info_set_sync_scope(t,e)}function dittoSmallPeerInfoGetMetadata(t){ensureInitialized();return boxCStringIntoString(ditto_small_peer_info_get_metadata(t))}function dittoSmallPeerInfoSetMetadata(t,e){ensureInitialized();const i=ditto_small_peer_info_set_metadata(t,bytesFromString(e));switch(i){case 0:return;case-1:throw new Error("Internal inconsistency, the observability subsystem is unavailable.");case 1:throw new Error(`Validation error, size limit exceeded: ${errorMessage()||"metadata is too big"}`);case 2:throw new Error(`Validation error, ${errorMessage()||"depth limit for metadata object exceeded"}`);case 3:throw new Error(`Validation error, ${errorMessage()||`'${e}' is not a valid JSON object`}`);default:throw new Error(errorMessage()||`Internal inconsistency, ditto_small_peer_info_set_metadata() returned an unknown error code: ${i}`)}}function dittoRegisterTransportConditionChangedCallback(t,e){ensureInitialized(),ditto_register_transport_condition_changed_callback(t,e?wrapBackgroundCbForFFI((t=>log("Error",`The registered "transport condition changed" callback errored with ${t}`)),e):null)}function dittoSetDeviceName(t,e){ensureInitialized();return boxCStringIntoString(ditto_set_device_name(t,bytesFromString(e)))}function dittoNewAttachmentFromFile(t,e,i){ensureInitialized();const n={},r=ditto_new_attachment_from_file(t,bytesFromString(e),i,n);if(0!==r)throw new DittoFFIError(r,null,`ditto_new_attachment_from_file() failed with error code: ${r}`);return n}async function dittoNewAttachmentFromBytes(t,e){ensureInitialized();const i={},n=await ditto_new_attachment_from_bytes(t,e,i);if(0!==n)throw new DittoFFIError(n,null,`ditto_new_attachment_from_bytes() failed with error code: ${n}`);return i}async function dittoResolveAttachment(t,e,i,n){ensureInitialized();const{onComplete:r,onProgress:o,onDelete:s}=i,a=wrapBackgroundCbForFFI(n,r),c=wrapBackgroundCbForFFI(n,o),d=wrapBackgroundCbForFFI(n,s),{status_code:l,cancel_token:u}=await ditto_resolve_attachment(t,e,a,c,d);if(0!==l)throw new DittoFFIError(l,null,`ditto_resolve_attachment() failed with error code: ${l}`);return u}function dittoCancelResolveAttachment(t,e,i){ensureInitialized();const n=ditto_cancel_resolve_attachment(t,e,i);if(0!==n)throw new Error(errorMessage()||`ditto_cancel_resolve_attachment() failed with error code: ${n}`)}function freeAttachmentHandle(t){ensureInitialized(),ditto_free_attachment_handle(t)}function dittoGetCompleteAttachmentPath(t,e){ensureInitialized();return refCStringToString(ditto_get_complete_attachment_path(t,e))}function dittoGetSDKVersion(t){ensureInitialized();return boxCStringIntoString(ditto_get_sdk_version(t))}function dittoGetSDKSemver(){ensureInitialized();return boxCStringIntoString(dittoffi_get_sdk_semver())}function dittoPresenceV1(t){ensureInitialized();return boxCStringIntoString(ditto_presence_v1(t))}function dittoPresenceV3(t){ensureInitialized();return boxCStringIntoString(ditto_presence_v3(t))}async function dittoShutdown(t){return ensureInitialized(),await ditto_shutdown(t)}async function dittoRunGarbageCollection(t){ensureInitialized();const e=await ditto_run_garbage_collection(t);if(0!==e)throw new Error(errorMessage()||`ditto_run_garbage_collection() failed with error code: ${e}`)}async function dittoDisableSyncWithV3(t){ensureInitialized();const e=await ditto_disable_sync_with_v3(t);if(0!==e)throw new Error(errorMessage()||`ditto_disable_sync_with_v3() failed with error code: ${e}`)}function base64encode(t,e){return boxCStringIntoString(dittoffi_base64_encode(t,e))}function tryBase64Decode(t,e){const i=dittoffi_try_base64_decode(bytesFromString(t),e);return throwOnErrorResult(i.error,"dittoffi_try_base64_decode"),boxCBytesIntoBuffer(i.success)}async function dittoAuthSetLoginProvider(t,e){return ensureInitialized(),await ditto_auth_set_login_provider(t,e)}function dittoAuthClientMakeLoginProvider(t,e){return ensureInitialized(),ditto_auth_client_make_login_provider(wrapBackgroundCbForFFI(e,t))}function transportsInit(){ensureInitialized();const{output:t,errorType:e}=withTransportsError(ditto_sdk_transports_init);if(!1===t)throw new Error(`Failed to initialize transports (${e} error)`)}function withTransportsError(t,...e){const i=ditto_sdk_transports_error_new(),n=t(...e,i),r=ditto_sdk_transports_error_value(i);return ditto_sdk_transports_error_free(i),{output:n,errorType:r}}!function(t){t[t.counter=0]="counter",t[t.register=1]="register",t[t.attachment=2]="attachment",t[t.rga=3]="rga",t[t.rwMap=4]="rwMap"}(DittoCRDTType||(DittoCRDTType={}));let isInitialized$1=!1;function tryVerifyLicense(t,e){ensureInitialized();throwOnErrorResult(dittoffi_try_verify_license(t,bytesFromString(e)).error,"dittoffi_try_verify_license")}function defaultDeviceName(){return rnOnlyDefaultDeviceName()}function rnOnlyGetPlatform(){return getPlatform()}function rnOnlyDefaultDeviceName(){return defaultDeviceName$1()}function rnOnlyGetDefaultDirectory(){return getDefaultDirectory()}function rnOnlyReadFile(t){return readFile(t)}function rnOnlyCopyFile(t,e,i){return copyFile(t,e,i)}function wrapBackgroundCbForFFI(t,e){return e}function wrapAsyncBackgroundCbForFFI(t,e){return e}function bytesFromString(t){if(void 0===t)return;if(null===t)return null;if("string"!=typeof t)throw new Error(`Can't convert string to Uint8Array, not a string: ${t}`);return(new TextEncoder).encode(`${t}\0`)}function errorMessage(){ensureInitialized();return boxCStringIntoString(ditto_error_message())}function ensureInitialized(){if(!isInitialized$1)throw new Error("Ditto needs to be initialized before using any of its API, please make sure to call `await init()` first.")}isInitialized$1=!0;const ERROR_CODES={internal:"An unexpected internal error occurred. Please get in touch with Ditto customer service to report this incident.","internal/unknown-error":"An unexpected internal error occurred. Please get in touch with Ditto customer service to report this incident.","sdk/unsupported":"The feature is not supported by the current environment.","authentication/failed-to-authenticate":"Ditto failed to authenticate.","authentication/expiration-handler-missing":"The expiration handler must be set before starting sync.","io/already-exists":"A file or directory already exists.","io/not-found":"A file or directory could not be found.","io/permission-denied":"The operation failed due to insufficient permissions.","io/operation-failed":"The operation failed.","query/arguments-invalid":"The query arguments were invalid.","query/evaluation":"The query could not be evaluated.","query/execution":"The query could not be executed.","query/invalid":"The query was invalid.","query/unsupported":"The query contains unsupported features.","query/parameter":"The query to update system parameters failed.","store/backend":"An error occurred with the storage backend.","store/crdt":"An error occurred processing a CRDT.","store/document-not-found":"The document with the provided ID could not be found.","store/transaction-read-only":"A mutating DQL query was attempted using a read-only transaction.","store/document-id":"The document ID is invalid.","store/persistence-directory-locked":"The chosen persistence directory is already in use by another Ditto instance.","store/attachment-file-permission-denied":"Permission has been denied for a file operation when working with attachments.","store/attachment-file-not-found":"The source file for the attachment does not exist.","store/attachment-not-found":"The attachment could not be found.","store/attachment-token-invalid":"The attachment token is invalid.","store/failed-to-create-attachment":"The attachment could not be created.","store/failed-to-fetch-attachment":"The attachment could not be fetched.","activation/license-token-verification-failed":"Please provide a valid license token.","activation/license-token-expired":"The license token expired. Please renew it.","activation/license-token-unsupported-future-version":"The provided license token is in an unsupported future format.","activation/not-activated":"The operation failed because the Ditto instance has not yet been activated.","activation/unnecessary":"Activation is unnecessary for this Ditto instance, because of its identity.","validation/depth-limit-exceeded":"The maximum depth limit has been exceeded.","validation/invalid-cbor":"The value provided is not valid CBOR.","validation/invalid-json":"The value provided is not valid JSON.","validation/invalid-transport-config":"The TransportConfig is invalid for the active platform.","validation/invalid-ditto-config":"The DittoConfig provided is invalid.","validation/not-an-object":"The value provided is not of type object.","validation/not-json-compatible":"Value is not serializable as JSON.","validation/size-limit-exceeded":"The size limit has been exceeded.","encryption/extraneous-passphrase-given":"Unexpected passphrase provided for the currently unencrypted store.","differ/identity-key-path-invalid":"A provided identity key path is invalid."},DEFAULT_STATUS_CODE_MAPPING={ActivationLicenseTokenExpired:["activation/license-token-expired"],ActivationLicenseTokenInvalid:["activation/license-token-verification-failed"],ActivationLicenseUnsupportedFutureVersion:["activation/license-token-unsupported-future-version"],ActivationNotActivated:["activation/not-activated"],ActivationUnnecessary:["activation/unnecessary"],AuthenticationExpirationHandlerMissing:["authentication/expiration-handler-missing"],IoAlreadyExists:["io/already-exists"],IoNotFound:["io/not-found"],IoPermissionDenied:["io/permission-denied"],IoOperationFailed:["io/operation-failed"],JsFloatingStoreOperation:["internal","Internal inconsistency, an outstanding store operation was not awaited."],DqlEvaluationError:["query/evaluation"],DqlQueryCompilation:["query/invalid"],DqlInvalidQueryArgs:["query/arguments-invalid"],DqlUnsupported:["query/unsupported"],StoreQuery:["query/execution"],ParameterQuery:["query/parameter"],EncryptionExtraneousPassphraseGiven:["encryption/extraneous-passphrase-given"],StoreDatabase:["store/backend"],StoreDocumentId:["store/document-id"],StoreDocumentNotFound:["store/document-not-found"],StoreTransactionReadOnly:["store/transaction-read-only"],Crdt:["store/crdt"],LockedDittoWorkingDirectory:["store/persistence-directory-locked"],Base64Invalid:["internal","Invalid base64 encoding."],CborInvalid:["internal","Invalid CBOR encoding."],CborUnsupported:["internal","Unsupported CBOR encoding."],ValidationDepthLimitExceeded:["validation/depth-limit-exceeded"],ValidationInvalidCbor:["validation/invalid-cbor"],ValidationInvalidDittoConfig:["validation/invalid-ditto-config"],ValidationInvalidJson:["validation/invalid-json"],ValidationInvalidTransportConfig:["validation/invalid-transport-config"],ValidationNotAMap:["validation/not-an-object"],ValidationSizeLimitExceeded:["validation/size-limit-exceeded"],DifferIdentityKeyPathInvalid:["differ/identity-key-path-invalid"],Transport:["internal","Transport error."],Unsupported:["sdk/unsupported"],Unknown:["internal/unknown-error"],default:["internal/unknown-error"]};class DittoError extends Error{constructor(t,e,i={}){if(null==ERROR_CODES[t])throw new DittoError("internal",`Invalid error code: ${t}`);super(e||ERROR_CODES[t]),this.code="internal",this.code=t,this.context=Object.freeze({...i})}static fromFFIError(t,e,i,n){const r=i||t.message,o={coreError:t.code,coreErrorMessage:t.message,...n},s=new DittoError(e,r,o);return null!=t.stack&&(s.stack=t.stack),s}}function mapFFIErrors(t,e,i){try{return t()}catch(t){if(t instanceof DittoFFIError)throw translateFFIError(t,e,i);throw t}}async function mapFFIErrorsAsync(t,e,i){try{return await t()}catch(t){if(t instanceof DittoFFIError)throw translateFFIError(t,e,i);throw t}}const translateFFIError=(t,e,i)=>{var n;const r=t.code.toString();let o,s;return null!=e&&null!=e[r]?[o,s]=e[r]:[o,s]=null!==(n=DEFAULT_STATUS_CODE_MAPPING[r])&&void 0!==n?n:DEFAULT_STATUS_CODE_MAPPING.default,DittoError.fromFFIError(t,o,s,i)};class AttachmentToken{constructor(t){let e,i,n;null!=t[DittoCRDTTypeKey]?({id:e,len:i,meta:n}=AttachmentToken.validateTypedInput(t)):({id:e,len:i,meta:n}=AttachmentToken.validateUntypedInput(t)),this.id=mapFFIErrors((()=>base64encode(e,"Unpadded"))),this.idBytes=e,this.len=i,this.metadata=n}static validateTypedInput(t){if(t[DittoCRDTTypeKey]!==DittoCRDTType.attachment)throw new Error("Invalid attachment token");const e=t._id;if(!(e instanceof Uint8Array))throw new Error("Invalid attachment token id");const i=t._len;if("number"!=typeof i&&"bigint"!=typeof i||i<0)throw new Error("Invalid attachment token length, must be a non-negative number or bigint");const n=t._meta;if("object"!=typeof n)throw new Error("Invalid attachment token meta");return{id:e,len:i,meta:n}}static validateUntypedInput(t){const e=t.id;if("string"!=typeof e)throw new Error("Invalid attachment token id");const i=mapFFIErrors((()=>tryBase64Decode(e,"Unpadded")),{Base64Invalid:["store/attachment-token-invalid","Failed to decode attachment token id from base64 input"]},{attachmentTokenID:e}),n=t.len;if("number"!=typeof n&&"bigint"!=typeof n||n<0)throw new Error("Invalid attachment token length, must be a non-negative number or bigint");const r=t.metadata;if("object"!=typeof r)throw new Error("Invalid attachment token meta");return{id:i,len:n,meta:r}}}class Logger{static get logFile(){return this._logFile}static setLogFile(t){t?(loggerSetLogFile(t),this._logFile=t):(loggerSetLogFile(void 0),delete this._logFile)}static setLogFileURL(t){var e;this.setLogFile(null!==(e=null==t?void 0:t.pathname)&&void 0!==e?e:null)}static get enabled(){return loggerEnabledGet()}static set enabled(t){loggerEnabled(t)}static get emojiLogLevelHeadingsEnabled(){return loggerEmojiHeadingsEnabledGet()}static set emojiLogLevelHeadingsEnabled(t){loggerEmojiHeadingsEnabled(t)}static get minimumLogLevel(){return loggerMinimumLogLevelGet()}static set minimumLogLevel(t){loggerMinimumLogLevel(t)}static get customLogCallback(){return this._customLogCallback}static async setCustomLogCallback(t){if(null!=t&&"function"!=typeof t)throw new TypeError(`Expected parameter 'callback' to be a function or undefined, but got ${typeof t}.`);null!=t?(await loggerSetCustomLogCb(t),this._customLogCallback=t):(await loggerSetCustomLogCb(null),delete this._customLogCallback)}static async exportToFile(t){if("string"!=typeof t)throw new TypeError(`Expected parameter 'path' to be a string, but got ${typeof t}.`);let e=t;return mapFFIErrorsAsync((()=>loggerTryExportToFile(e)))}static log(t,e){log(t,e)}static error(t){this.log("Error",t)}static warning(t){this.log("Warning",t)}static info(t){this.log("Info",t)}static debug(t){this.log("Debug",t)}static verbose(t){this.log("Verbose",t)}constructor(){throw new Error("Logger can't be instantiated, use its static properties & methods directly instead.")}}var _a;const DEBUG_TYPE_NAMES=[],DEBUG_ALL_TYPES=!1;class Handle{constructor(t,e,i){this.isClosed=!1,this.isFinalized=!1,this.isUnregistered=!1,this.bridge=t,this.objectWeakRef=new WeakRef(e),this.pointer=i}get type(){return this.bridge.type}deref(){if(this.isClosed)throw new Error("Bridging error: can't get pointer for an object that has been closed.");if(this.isFinalized)throw new Error("Bridging error: can't get pointer for an object that has been finalized.");if(this.isUnregistered)throw new Error("Bridging error: can't get pointer for an object that has been unregistered.");return this.pointer}derefOrNull(){var t;return this.isClosed||this.isFinalized||this.isUnregistered?null:null!==(t=this.pointer)&&void 0!==t?t:null}object(){const t=this.objectWeakRef.deref();if(null==t)throw new Error(`Bridging error: ${this.bridge.type.name} object has been garbage collected.`);if(this.isClosed)throw new Error(`Bridging error: ${this.bridge.type.name} object has been closed.`);if(this.isUnregistered)throw new Error(`Bridging error: ${this.bridge.type.name} object has been unregistered.`);return t}objectOrNull(){var t;return null!==(t=this.objectWeakRef.deref())&&void 0!==t?t:null}toString(){const t=this.derefOrNull();return`{ Handle | type: ${this.bridge.type}, object: ${this.objectWeakRef.deref()}, FFI address: ${null==t?void 0:t.addr}, FFI type: ${null==t?void 0:t.type} }`}bridgeWillClose(){this.isClosed=!0}bridgeDidClose(){this.pointer=null}bridgeWillFinalize(){this.isFinalized=!0}bridgeDidFinalize(){this.pointer=null}bridgeWillUnregister(){this.isUnregistered=!0}bridgeDidUnregister(){this.pointer=null}}class Handles{constructor(t,e){this.handles=e.map((e=>t.handleFor(e)))}deref(){return this.handles.map((t=>t.deref()))}}class Bridge{constructor(t){this.internalType=null,this.release=t,this.handlesByAddress={},this.handlesByObject=new WeakMap,this.finalizationRegistry=new FinalizationRegistry(this.finalize.bind(this)),_a.all.push(new WeakRef(this))}get type(){if(null==this.internalType)throw new Error("Bridge type has not been registered yet.");return this.internalType}registerType(t){if(this.internalType!==t){if(this.internalType)throw new Error(`Can't register bridged type '${t.name}', another type was already registered: ${this.internalType}`);this.internalType=t}}handleFor(t){const e=this.handlesByObject.get(t);if(null==e)throw new Error(`Bridging error: ${this.type.name} object is not currently registered in this bridge.`);return e}handlesFor(t){return new Handles(this,t)}objectFor(t){const e=this.handlesByAddress[t.addr];if(e){if(e.type!==this.type)throw new Error(`Can't return object for pointer, pointer is associated with an object of type ${e.type} but this bridge is configured for ${this.type}`);return e.object()}}bridge(t,e){const i=this.objectFor(t);if(i)return i;let n;if(e||(e=()=>Reflect.construct(this.type,[])),"function"==typeof e){if(n=e(),!(n instanceof this.type))throw new Error(`Can't bridge, expected passed in create function to return a ${this.type.name} object but got: ${n}`)}else n=e;return this.register(n,t),n}register(t,e){const i=t.constructor;if(i!==this.type)throw new Error(`Can't register, bridge is configured for type ${this.type.name} but passed in object is of type ${i.name}`);const n=this.handlesByObject.get(t),r=n?n.pointer:null;if(null!=r&&null!=n)throw new Error(`Can't register, an object for the passed in pointer has previously been registered: ${n.object()}`);if(null!=r&&null==n)throw new Error(`Internal inconsistency, trying to register an object which has an associated pointer but no handle entry: ${i.name} at ${r.type} ${r.addr}`);if(null==r&&null!=n)throw new Error(`Internal inconsistency, trying to register an object which has a handle entry but no associated pointer: ${i.name} ${t}`);const o=new Handle(this,t,e);this.handlesByAddress[e.addr]=o,this.handlesByObject.set(t,o),this.finalizationRegistry.register(t,o,t),DEBUG_TYPE_NAMES.includes(this.type.name)&&Logger.debug(`[VERBOSE] Bridge REGISTERED a new instance of ${this.type.name}, current count: ${Object.keys(this.handlesByAddress).length}`)}unregister(t){const e=t.constructor,i=this.type;if(e!==i)throw new Error(`Can't unregister, bridge is configured for type ${i.name} but passed in object is of type ${e.name}`);const n=this.handlesByObject.get(t);if(null==n)throw new Error(`Can't unregister, object has not been registered before: ${t}`);if(n.type!==i)throw new Error(`Internal inconsistency, trying to unregister an object that has a handle with a different type than that of the bridge: ${n}`);if(n.objectOrNull()!==t)throw new Error(`Internal inconsistency, trying to unregister an object whose associated handle holds a different object: ${n}`);if(n.isClosed)throw new Error(`Can't unregister, object has been closed before: ${t}`);if(n.isFinalized)throw new Error(`Can't unregister, object has been finalized before: ${t}`);if(n.isUnregistered)throw new Error(`Can't unregister, object has been unregistered already: ${t}`);n.bridgeWillUnregister(),this.finalizationRegistry.unregister(t),delete this.handlesByAddress[n.pointer.addr],this.handlesByObject.delete(t),n.bridgeDidUnregister(),DEBUG_TYPE_NAMES.includes(this.type.name)&&Logger.debug(`[VERBOSE] Bridge UNREGISTERED an instance of ${this.type.name}, current count: ${Object.keys(this.handlesByAddress).length}`)}unregisterAll(){DEBUG_TYPE_NAMES.includes(this.type.name)&&Logger.debug(`[VERBOSE] Unregistering ALL bridged instances of type ${this.type.name}.`);for(const t of Object.values(this.handlesByAddress)){const e=t.object();e&&this.unregister(e)}}async close(t){const e=t.constructor,i=this.type;if(e!==i)throw new Error(`Can't close, bridge is configured for type ${i.name} but passed in object is of type ${e.name}`);const n=this.handlesByObject.get(t);if(null==n)throw new Error(`Can't close an object that has not been registered before: ${t}`);if(n.type!==i)throw new Error(`Internal inconsistency, trying to close an object that has a handle with a different type than that of the bridge: ${n}`);if(n.isUnregistered)throw new Error("Can't close object, object has been unregistered.");if(n.isFinalized)throw new Error("Internal inconsistency, trying to close an object that has already been finalized.");if(n.isClosed)return;const r=n.pointer;if(!r)throw new Error("Internal inconsistency, trying to close an object whose pointer is null.");n.bridgeWillClose(),delete this.handlesByAddress[r.addr],await this.release(r),n.bridgeDidClose(),DEBUG_TYPE_NAMES.includes(this.type.name)&&Logger.debug(`[VERBOSE] Bridge CLOSED an instance of ${this.type.name}, current count: ${Object.keys(this.handlesByAddress).length}`)}get count(){return Object.keys(this.handlesByAddress).length}async finalize(t){if(t.isFinalized)throw new Error("Internal inconsistency, trying to finalize an object that has already been finalized.");if(t.isUnregistered)throw new Error("Internal inconsistency, trying to finalize an object that has been unregistered before.");if(t.bridgeWillFinalize(),!t.isClosed){const e=t.pointer;if(!e)throw new Error("Internal inconsistency, trying to finalize an object whose pointer is null.");delete this.handlesByAddress[e.addr],await this.release(e)}t.bridgeDidFinalize(),DEBUG_TYPE_NAMES.includes(this.type.name)&&Logger.debug(`[VERBOSE] Bridge FINALIZED an instance of ${this.type.name}, current count: ${Object.keys(this.handlesByAddress).length}`)}}_a=Bridge,Bridge.all=[],Bridge.attachment=new _a(freeAttachmentHandle),Bridge.connectionRequest=new _a(connectionRequestFree),Bridge.document=new _a(documentFree),Bridge.mutableDocument=new _a(documentFree),Bridge.queryResult=new _a(queryResultFree),Bridge.queryResultItem=new _a(queryResultItemFree),Bridge.transaction=new _a(transactionFree),Bridge.differ=new _a(differFree),Bridge.ditto=new _a((async t=>{await dittoClearPresenceCallback(t),await dittoShutdown(t),dittoFree(t)}));class Attachment{get id(){return this.token.id}get len(){return this.token.len}get metadata(){return this.token.metadata}data(){return this.ditto.deferCloseAsync((async t=>{{const e=Bridge.attachment.handleFor(this),i=dittoGetCompleteAttachmentPath(t.deref(),e.deref());return await rnOnlyReadFile(i)}}))}getData(){return this.data()}copyToPath(t){return this.ditto.deferCloseAsync((async e=>{{const i=Bridge.attachment.handleFor(this);rnOnlyCopyFile(dittoGetCompleteAttachmentPath(e.deref(),i.deref()),t,this.ditto.absolutePersistenceDirectory)}}))}constructor(t,e){this.ditto=t,this.token=e}}function validateAttachmentMetadata(t){if("object"!=typeof t)throw new DittoError("store/failed-to-create-attachment",`Invalid attachment metadata: expected a value of type object but got ${typeof t}.`);for(const e in t)if("string"!=typeof t[e])throw new DittoError("store/failed-to-create-attachment",`Invalid attachment metadata: metadata values must be strings but key '${e}' has a value of type ${typeof t[e]}.`)}const defaultDittoCloudDomain="cloud.ditto.live";function defaultAuthURL(t){return`https://${t}.cloud.ditto.live`}function customInspectRepresentation(t,e){return void 0===e?`${t.constructor.name} ${JSON.stringify({value:t.value},null,2)}`:`${t.constructor.name} ${e({value:t.value})}`}function sleep(t){return new Promise(((e,i)=>{setTimeout(e,t)}))}async function step(t){return await sleep(0),t()}const performAsyncToWorkaroundNonAsyncFFIAPI=step;function capitalize(t){return t.charAt(0).toUpperCase()+t.slice(1)}class AttachmentFetcher{stop(){if(null==this.manager){this.isStopped||(this.rejectPendingFetch(),this.rejectPendingFetch=null),this.ditto.store.removeAttachmentFetcher(this);const t=Bridge.ditto.handleFor(this.ditto);this.ditto.deferCloseAsync((async()=>{const e=await this.cancelTokenPromise;e&&dittoCancelResolveAttachment(t.deref(),this.token.idBytes,e)}))}else step((async()=>{await this.manager.stopAttachmentFetcher(this),null!=this.rejectPendingFetch&&(this.rejectPendingFetch(),this.rejectPendingFetch=null)}))}then(t,e){return this.attachment.then(t,e)}constructor(t,e,i,n){this.cancelTokenPromise=null,this.rejectPendingFetch=null,this.ditto=t,this.token=e,this.manager=i,this.id=cryptoGenerateSecureRandomToken();const r=n||function(){},o=Bridge.ditto.handleFor(t);this.attachment=new Promise(((t,i)=>{const onComplete=e=>{const i=new Attachment(this.ditto,this.token);Bridge.attachment.bridge(e,(()=>i)),r({type:"Completed",attachment:i}),this.rejectPendingFetch=null,t(i)},onProgress=(t,e)=>{r({type:"Progress",totalBytes:e,downloadedBytes:t})},onDelete=()=>{r({type:"Deleted"}),null!=this.manager?(this.rejectPendingFetch=null,t(null)):(this.rejectPendingFetch=null,i(new DittoError("store/attachment-not-found","The attachment was deleted while being fetched.")))},onError=()=>{};this.rejectPendingFetch=()=>{const t=null!=this.manager?new Error("Attachment fetch was canceled"):new DittoError("store/failed-to-fetch-attachment","Attachment fetch was canceled");i(t)};const n=new WeakRef(this);this.cancelTokenPromise=(async()=>{try{return await mapFFIErrorsAsync((async()=>dittoResolveAttachment(o.deref(),e.idBytes,{onComplete:onComplete,onProgress:onProgress,onDelete:onDelete},onError)),{1:["store/failed-to-fetch-attachment","Failed to fetch the attachment."],2:["store/attachment-token-invalid","The attachment token was invalid."],3:["store/attachment-not-found","The attachment was not found."]})}catch(e){let o=!1;e instanceof DittoError&&"store/attachment-not-found"===e.code&&(o=!0,r({type:"Deleted"})),Logger.error(e.message);const s=n.deref();return null==s||(null!=s.manager&&e instanceof DittoError&&(e=new Error(e.message)),s.rejectPendingFetch=null,null!=s.manager&&o?t(null):i(e)),null}})()})),null==i&&this.attachment.then((()=>{this.rejectPendingFetch=null,this.ditto.store.removeAttachmentFetcher(this)})).catch((()=>{this.rejectPendingFetch=null,this.ditto.store.removeAttachmentFetcher(this)}))}get isStopped(){return null==this.rejectPendingFetch}}let isInitialized=!1,initPromise=null;function init(t={}){return isInitialized?initPromise:initPromise||(initPromise=(async()=>{isInitialized=!0})(),initPromise)}const CBOR_OPTIONS=Object.freeze({dictionary:"object",mode:"strict"}),EMPTY_KEY=Symbol("EMPTY_KEY"),OMIT_VALUE=Symbol("OMIT_VALUE"),POW_2_24=5.960464477539063e-8,POW_2_32=4294967296,POW_2_53=9007199254740992,MAX_SAFE_INTEGER=18446744073709551616n,DECODE_CHUNK_SIZE=8192,kCborTag=6,kCborTagUint8=64,kCborTagUint16=69,kCborTagUint32=70,kCborTagInt8=72,kCborTagInt16=77,kCborTagInt32=78,kCborTagFloat32=85,kCborTagFloat64=86;function objectIs(t,e){return"function"==typeof Object.is?Object.is(t,e):t===e?0!==t||1/t==1/e:t!=t&&e!=e}function options(t){const e={...CBOR_OPTIONS};return"object"==typeof t&&(e.dictionary=function isDictionary(t){return"string"==typeof t&&["object","map"].includes(t)}(t.dictionary)?t.dictionary:CBOR_OPTIONS.dictionary,e.mode=function isMode(t){return"string"==typeof t&&["loose","strict","sequence"].includes(t)}(t.mode)?t.mode:CBOR_OPTIONS.mode),Object.freeze(e)}function lexicographicalCompare(t,e){const i=Math.min(t.byteLength,e.byteLength);for(let n=0;n<i;n++){const i=t[n]-e[n];if(0!==i)return i}return t.byteLength-e.byteLength}var _Sequence_instances,_Sequence_toInspectString,__classPrivateFieldGet=function(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)};class Sequence{static from(t){return new Sequence(Array.from(t))}constructor(t){_Sequence_instances.add(this),Object.defineProperty(this,"_data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._data=t||[]}add(t){return this._data.push(t)-1}remove(t){return this._data.splice(t,1)[0]}get(t){return this._data[t]}clone(){return new Sequence(this.data)}get data(){return Array.from(this._data)}get size(){return this._data.length}[(_Sequence_instances=new WeakSet,Symbol.toStringTag)](){return"Sequence"}[(_Sequence_toInspectString=function _Sequence_toInspectString(t){return`${this[Symbol.toStringTag]()}(${this.size}) ${t(this._data)}`},Symbol.for("Deno.customInspect"))](t){return __classPrivateFieldGet(this,_Sequence_instances,"m",_Sequence_toInspectString).call(this,t)}[Symbol.for("nodejs.util.inspect.custom")](t,e,i){return __classPrivateFieldGet(this,_Sequence_instances,"m",_Sequence_toInspectString).call(this,i)}}class SimpleValue{static create(t){if(void 0===t)return new SimpleValue(23);if(null===t)return new SimpleValue(22);if(!0===t)return new SimpleValue(21);if(!1===t)return new SimpleValue(20);if("number"==typeof t&&t>=0&&t<=255)return new SimpleValue(t);throw new Error("CBORError: Value out of range or not a simple value.")}constructor(t){switch(Object.defineProperty(this,"semantic",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),!0){case 20===t:this.semantic="false";break;case 21===t:this.semantic="true";break;case 22===t:this.semantic="null";break;case 23===t:this.semantic="undefined";break;case t>23&&t<32:this.semantic="reserved";break;default:this.semantic="unassigned"}this.value=t}toPrimitive(){switch(this.semantic){case"false":return!1;case"true":return!0;case"null":return null;default:return}}}class TaggedValue{constructor(t,e){Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tag",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.value=t,this.tag=e}}function decode(t,e,i={}){const{dictionary:n,mode:r}=options(i),o="sequence"===r||"strict"===r,s=new DataView(t),a=new Uint8Array(t);let c=0,reviverFunction=function(t,e){return e};function commitRead(t,e){return c+=t,e}function readArrayBuffer(e){return commitRead(e,new Uint8Array(t,c,e))}function readUint8(){return commitRead(1,a[c])}function readUint16(){return commitRead(2,s.getUint16(c))}function readBreak(){return 255===a[c]&&(c+=1,!0)}function readLength(t){if(t<24)return t;if(24===t)return readUint8();if(25===t)return readUint16();if(26===t)return function readUint32(){return commitRead(4,s.getUint32(c))}();if(27===t){const t=function readUint64(){return commitRead(8,s.getBigUint64(c))}();return t<POW_2_53?Number(t):t}if(31===t)return-1;throw new Error("CBORError: Invalid length encoding")}function readIndefiniteStringLength(t){const e=readUint8();if(255===e)return-1;const i=readLength(31&e);if(i<0||e>>5!==t)throw new Error("CBORError: Invalid indefinite length element");return Number(i)}function appendUtf16Data(t,e){for(let i=0;i<e;++i){let i=readUint8();128&i&&(i<224?(i=(31&i)<<6|63&readUint8(),e-=1):i<240?(i=(15&i)<<12|(63&readUint8())<<6|63&readUint8(),e-=2):(i=(15&i)<<18|(63&readUint8())<<12|(63&readUint8())<<6|63&readUint8(),e-=3)),i<65536?t.push(i):(i-=65536,t.push(55296|i>>10),t.push(56320|1023&i))}}function decodeItem(){const t=readUint8(),e=t>>5,i=31&t;let r,a;if(7===e)switch(i){case 25:return function readFloat16(){const t=new ArrayBuffer(4),e=new DataView(t),i=readUint16(),n=32768&i;let r=31744&i;const o=1023&i;if(31744===r)r=261120;else if(0!==r)r+=114688;else if(0!==o)return(n?-1:1)*o*POW_2_24;return e.setUint32(0,n<<16|r<<13|o<<13),e.getFloat32(0)}();case 26:return function readFloat32(){return commitRead(4,s.getFloat32(c))}();case 27:return function readFloat64(){return commitRead(8,s.getFloat64(c))}()}if(a=readLength(i),a<0&&(e<2||6<e))throw new Error("CBORError: Invalid length");switch(e){case 0:return reviverFunction(EMPTY_KEY,a);case 1:return reviverFunction(EMPTY_KEY,"number"==typeof a?-1-a:-1n-a);case 2:if(a<0){const t=[];let i=0;for(;(a=readIndefiniteStringLength(e))>=0;)i+=a,t.push(readArrayBuffer(a));const n=new Uint8Array(i);let o=0;for(r=0;r<t.length;++r)n.set(t[r],o),o+=t[r].length;return reviverFunction(EMPTY_KEY,n)}return reviverFunction(EMPTY_KEY,readArrayBuffer(a));case 3:{const t=[];if(a<0)for(;(a=readIndefiniteStringLength(e))>=0;)appendUtf16Data(t,a);else appendUtf16Data(t,a);let i="";for(r=0;r<t.length;r+=8192)i+=String.fromCharCode.apply(null,t.slice(r,r+8192));return reviverFunction(EMPTY_KEY,i)}case 4:{let t;if(a<0){t=[];let e=0;for(;!readBreak();)t.push(reviverFunction(e++,decodeItem()))}else for(t=new Array(a),r=0;r<a;++r)t[r]=reviverFunction(r,decodeItem());return reviverFunction(EMPTY_KEY,t)}case 5:{if("map"===n){const t=new Map;for(r=0;r<a||a<0&&!readBreak();++r){const e=decodeItem();if(o&&t.has(e))throw new Error("CBORError: Duplicate key encountered");t.set(e,reviverFunction(e,decodeItem()))}return reviverFunction(EMPTY_KEY,t)}const t={};for(r=0;r<a||a<0&&!readBreak();++r){const e=decodeItem();if(o&&Object.prototype.hasOwnProperty.call(t,e))throw new Error("CBORError: Duplicate key encountered");t[e]=reviverFunction(e,decodeItem())}return reviverFunction(EMPTY_KEY,t)}case 6:{const t=decodeItem(),e=a;if(t instanceof Uint8Array){const i=t.buffer.slice(t.byteOffset,t.byteLength+t.byteOffset);switch(e){case 64:return reviverFunction(EMPTY_KEY,new Uint8Array(i));case 72:return reviverFunction(EMPTY_KEY,new Int8Array(i));case 69:return reviverFunction(EMPTY_KEY,new Uint16Array(i));case 77:return reviverFunction(EMPTY_KEY,new Int16Array(i));case 70:return reviverFunction(EMPTY_KEY,new Uint32Array(i));case 78:return reviverFunction(EMPTY_KEY,new Int32Array(i));case 85:return reviverFunction(EMPTY_KEY,new Float32Array(i));case 86:return reviverFunction(EMPTY_KEY,new Float64Array(i))}}return reviverFunction(EMPTY_KEY,new TaggedValue(t,e))}case 7:switch(a){case 20:return reviverFunction(EMPTY_KEY,!1);case 21:return reviverFunction(EMPTY_KEY,!0);case 22:return reviverFunction(EMPTY_KEY,null);case 23:return reviverFunction(EMPTY_KEY,void 0);default:return reviverFunction(EMPTY_KEY,new SimpleValue(a))}}}"function"==typeof e&&(reviverFunction=e);const d=decodeItem();if(c!==t.byteLength){if("sequence"!==r)throw new Error("CBORError: Remaining bytes");const e=new Sequence([d]);for(;c<t.byteLength;)e.add(reviverFunction(EMPTY_KEY,decodeItem()));return e}return"sequence"===r?new Sequence([d]):d}function parse(t,e,i){return decode(t,e,i)}function encode(t,e){let i,n=new ArrayBuffer(256),r=new DataView(n),o=new Uint8Array(n),s=0,replacerFunction=(t,e)=>e;if("function"==typeof e&&(replacerFunction=e),Array.isArray(e)){const t=e.slice();replacerFunction=(e,i)=>e===EMPTY_KEY||t.includes(e)?i:OMIT_VALUE}function prepareWrite(t){let e=n.byteLength;const a=s+t;for(;e<a;)e<<=1;if(e!==n.byteLength){const t=r;n=new ArrayBuffer(e),r=new DataView(n),o=new Uint8Array(n);const i=s+3>>2;for(let e=0;e<i;++e)r.setUint32(e<<2,t.getUint32(e<<2))}return i=t,r}function commitWrite(...t){s+=i}function writeUint8(t){commitWrite(prepareWrite(1).setUint8(s,t))}function writeUint8Array(t){prepareWrite(t.length),o.set(t,s),commitWrite()}function writeUint16(t){commitWrite(prepareWrite(2).setUint16(s,t))}function writeUint32(t){commitWrite(prepareWrite(4).setUint32(s,t))}function writeUint64(t){const e=t%POW_2_32,i=(t-e)/POW_2_32,n=prepareWrite(8);n.setUint32(s,i),n.setUint32(s+4,e),commitWrite()}function writeBigUint64(t){commitWrite(prepareWrite(8).setBigUint64(s,t))}function writeVarUint(t,e){t<=255?t<24?writeUint8(Number(t)|e):(writeUint8(24|e),writeUint8(Number(t))):t<=65535?(writeUint8(25|e),writeUint16(Number(t))):t<=4294967295?(writeUint8(26|e),writeUint32(Number(t))):(writeUint8(27|e),"number"==typeof t?writeUint64(t):writeBigUint64(t))}function writeTypeAndLength(t,e){e<24?writeUint8(t<<5|e):e<256?(writeUint8(t<<5|24),writeUint8(e)):e<65536?(writeUint8(t<<5|25),writeUint16(e)):e<4294967296?(writeUint8(t<<5|26),writeUint32(e)):(writeUint8(t<<5|27),writeUint64(e))}function encodeItem(t){if(t!==OMIT_VALUE){if(!1===t)return writeUint8(244);if(!0===t)return writeUint8(245);if(null===t)return writeUint8(246);if(void 0===t)return writeUint8(247);if(objectIs(t,-0))return writeUint8Array([249,128,0]);switch(typeof t){case"bigint":return function writeBigInteger(t){let e=0;if(0<=t&&t<=MAX_SAFE_INTEGER)e=0;else{if(!(-MAX_SAFE_INTEGER<=t&&t<0))throw new Error("CBORError: Encountered unsafe integer outside of valid CBOR range.");e=1,t=-(t+1n)}if(t<0x100000000n)return writeTypeAndLength(e,Number(t));writeUint8(e<<5|27),writeBigUint64(t)}(t);case"number":if(Math.floor(t)===t){if(0<=t&&t<=POW_2_53)return writeTypeAndLength(0,t);if(-POW_2_53<=t&&t<0)return writeTypeAndLength(1,-(t+1))}return writeUint8(251),function writeFloat64(t){commitWrite(prepareWrite(8).setFloat64(s,t))}(t);case"string":{const e=[],i=t.length;for(let n=0;n<i;++n){let i=t.charCodeAt(n);i<128?e.push(i):i<2048?(e.push(192|i>>6),e.push(128|63&i)):i<55296||i>=57344?(e.push(224|i>>12),e.push(128|i>>6&63),e.push(128|63&i)):(i=(1023&i)<<10,i|=1023&t.charCodeAt(++n),i+=65536,e.push(240|i>>18),e.push(128|i>>12&63),e.push(128|i>>6&63),e.push(128|63&i))}return writeTypeAndLength(3,e.length),writeUint8Array(e)}default:{let e;if(Array.isArray(t))!function writeArray(t){const e=s,i=t.length;let n=0;writeTypeAndLength(4,i);const r=s;for(let e=0;e<i;e+=1){const i=replacerFunction(e,t[e]);i!==OMIT_VALUE&&(encodeItem(i),n+=1)}if(i>n){const t=o.slice(r,s);s=e,writeTypeAndLength(4,n),writeUint8Array(t)}}(t);else if(t instanceof Uint8Array)writeVarUint(64,192),writeTypeAndLength(2,t.length),writeUint8Array(t);else if(t instanceof Int8Array)writeVarUint(72,192),writeTypeAndLength(2,t.byteLength),writeUint8Array(new Uint8Array(t.buffer));else if(t instanceof Uint16Array)writeVarUint(69,192),writeTypeAndLength(2,t.byteLength),writeUint8Array(new Uint8Array(t.buffer));else if(t instanceof Int16Array)writeVarUint(77,192),writeTypeAndLength(2,t.byteLength),writeUint8Array(new Uint8Array(t.buffer));else if(t instanceof Uint32Array)writeVarUint(70,192),writeTypeAndLength(2,t.byteLength),writeUint8Array(new Uint8Array(t.buffer));else if(t instanceof Int32Array)writeVarUint(78,192),writeTypeAndLength(2,t.byteLength),writeUint8Array(new Uint8Array(t.buffer));else if(t instanceof Float32Array)writeVarUint(85,192),writeTypeAndLength(2,t.byteLength),writeUint8Array(new Uint8Array(t.buffer));else if(t instanceof Float64Array)writeVarUint(86,192),writeTypeAndLength(2,t.byteLength),writeUint8Array(new Uint8Array(t.buffer));else if(ArrayBuffer.isView(t))e=new Uint8Array(t.buffer),writeTypeAndLength(2,e.length),writeUint8Array(e);else if(t instanceof ArrayBuffer||"function"==typeof SharedArrayBuffer&&t instanceof SharedArrayBuffer)e=new Uint8Array(t),writeTypeAndLength(2,e.length),writeUint8Array(e);else if(t instanceof TaggedValue)writeVarUint(t.tag,192),encodeItem(t.value);else if(t instanceof SimpleValue)writeTypeAndLength(7,t.value);else if(t instanceof Sequence){if(0!==s)throw new Error("CBORError: A CBOR Sequence may not be nested.");const e=t.size;for(let i=0;i<e;i+=1)encodeItem(t.get(i))}else!function writeDictionary(t){const e=[],i=s;let n=s,r=0,a=0;if(t instanceof Map){r=t.size,writeTypeAndLength(5,r),n=s;for(const[i,n]of t.entries()){const t=replacerFunction(i,n);if(t===OMIT_VALUE)continue;let r=s;encodeItem(i);const c=o.slice(r,s);r=s,encodeItem(t);const d=o.slice(r,s);a+=1,e.push([c,d])}}else{const i=Object.keys(t);r=i.length,writeTypeAndLength(5,r),n=s;for(let n=0;n<r;n+=1){const r=i[n],c=replacerFunction(r,t[r]);if(c===OMIT_VALUE)continue;let d=s;encodeItem(r);const l=o.slice(d,s);d=s,encodeItem(c);const u=o.slice(d,s);a+=1,e.push([l,u])}}function sortEncodedKeys(t){s=i,writeTypeAndLength(5,a),e.sort((([t],[e])=>lexicographicalCompare(t,e)));for(let i=0;i<t;i+=1){const[t,n]=e[i];writeUint8Array(t),writeUint8Array(n)}}if(r>a){const t=e.length;if(t>1)sortEncodedKeys(t);else{const t=o.slice(n,s);s=i,writeTypeAndLength(5,a),writeUint8Array(t)}}else{const t=e.length;t>1&&sortEncodedKeys(t)}}(t)}}}}if(encodeItem(replacerFunction(EMPTY_KEY,t)),"slice"in n)return n.slice(0,s);const a=new ArrayBuffer(s),c=new DataView(a);for(let t=0;t<s;++t)c.setUint8(t,r.getUint8(t));return a}function binarify(t,e){return encode(t,e)}const CBOR$1={binarify:binarify,decode:decode,encode:encode,parse:parse};class CBOR{static encode(t){const e=CBOR$1.encode(t);return new Uint8Array(e)}static decode(t,e){const i=t.buffer;return CBOR$1.decode(i,e)}}class DocumentID{get value(){let t=this["@ditto.value"];return void 0===t&&(t=CBOR.decode(this["@ditto.cbor"]),this["@ditto.value"]=t),t}constructor(t,e=!1,i=!1){const n=e?t:CBOR.encode(t),r=i?n:validateDocumentIDCBOR(n);if(!r)throw new Error(`Can't create DocumentID, passed in value is not valid: ${t}`);this.isValidated=!i,this["@ditto.cbor"]=r}equals(t){const e=this["@ditto.cbor"],i=t["@ditto.cbor"];if(e===i)return!0;if(!(e instanceof Uint8Array))return!1;if(!(i instanceof Uint8Array))return!1;if(e.length!==i.length)return!1;for(let t=0;t<e.length;t+=1)if(e[t]!==i[t])return!1;return!0}toString(){return documentIDQueryCompatible(this["@ditto.cbor"],"WithoutQuotes")}toBase64String(){return mapFFIErrors((()=>base64encode(this["@ditto.cbor"],"Padded")))}toQueryCompatibleString(){return documentIDQueryCompatible(this["@ditto.cbor"],"WithQuotes")}toCBOR(){return this["@ditto.cbor"]}}function validateDocumentIDValue(t){if(void 0===t)throw new Error(`Invalid document ID: ${t}`);return t}function validateDocumentIDCBOR(t){const e=validateDocumentID(t);return null!=e?e:t}class Observer{get token(){return this._token}constructor(t,e,i={}){this.observerManager=t,this._token=e,this.options=i,i.stopsWhenFinalized&&Observer.finalizationRegistry.register(this,{observerManager:t,token:e},this)}get isStopped(){return void 0!==this.token&&this.observerManager.hasObserver(this.token)}stop(){const t=this.token;t&&(delete this._token,Observer.finalizationRegistry.unregister(this),this.observerManager.removeObserver(t))}static finalize(t){const{observerManager:e,token:i}=t;e.removeObserver(i)}}Observer.finalizationRegistry=new FinalizationRegistry(Observer.finalize);class Diff{constructor(t){const e=CBOR.decode(t);this.insertions=e.insertions,this.deletions=e.deletions,this.updates=e.updates,this.moves=e.moves.map((([t,e])=>({from:t,to:e})))}}class Differ{constructor(){const t=differNew();return Bridge.differ.bridge(t,this)}diff(t){const e=t.map((t=>t.deref())),i=differDiff(this.deref(),e);return new Diff(i)}deref(){return Bridge.differ.handleFor(this).deref()}}class ObserverManager{constructor(t,e={}){var i,n,r,o;const s=null!==(i=e.keepAlive)&&void 0!==i?i:null,a=null!==(n=e.register)&&void 0!==n?n:null,c=null!==(r=e.unregister)&&void 0!==r?r:null,d=null!==(o=e.process)&&void 0!==o?o:null;this.id=t,this.keepAlive=s,this.isClosed=!1,this.isRegistered=!1,this.callbacksByToken={},null!==a&&(this.register=a),null!==c&&(this.unregister=c),null!==d&&(this.process=d)}addObserver(t){var e;if(this.isClosed)throw new Error(`Internal inconsistency, can't add '${this.id}' observer, observer mananger close()-ed.`);this.registerIfNeeded();const i=cryptoGenerateSecureRandomToken();return this.callbacksByToken[i]=t,null===(e=this.keepAlive)||void 0===e||e.retain(`${this.id}.${i}`),i}removeObserver(t){var e;const i=this.callbacksByToken[t];if(void 0===i)throw new Error(`Can't remove '${this.id}' observer, token '${t}' has never been registered before.`);null!==i&&(this.callbacksByToken[t]=null,null===(e=this.keepAlive)||void 0===e||e.release(`${this.id}.${t}`),this.unregisterIfNeeded())}hasObserver(t){return void 0!==this.callbacksByToken[t]}notify(...t){if(this.isClosed)return;const e=this.process(...t);for(const t in this.callbacksByToken){const i=this.callbacksByToken[t];i&&i(...e)}}close(){this.isClosed=!0;for(const t in this.callbacksByToken)this.removeObserver(t)}register(t){}unregister(){}process(...t){return t}hasObservers(){return Object.keys(this.callbacksByToken).length>0}registerIfNeeded(){if(!this.isRegistered){const t=new WeakRef(this);this.isRegistered=!0,this.register((function(...e){const i=t.deref();i&&i.notify(...e)}))}}unregisterIfNeeded(){!this.hasObservers()&&this.isRegistered&&(this.isRegistered=!1,this.unregister())}}function authenticationStatusFromFFI(t){const e=authenticationStatusIsAuthenticated(t),i=authenticationStatusUserID(t);return authenticationStatusFree(t),{isAuthenticated:e,userID:i}}class Authenticator{static get DEVELOPMENT_PROVIDER(){return DITTO_DEVELOPMENT_PROVIDER()}get expirationHandler(){throw new Error("Authenticator.expirationHandler is only available when using a DittoConfig with a ConfigConnectServer.")}async setExpirationHandler(t){throw new Error("Authenticator.expirationHandler is only available when using a DittoConfig with a ConfigConnectServer.")}get status(){return this._status}async login(t,e){if("string"!=typeof t)throw new TypeError(`Expected parameter token to have type string, but got '${typeof t}'`);if("string"!=typeof e)throw new TypeError(`Expected parameter provider to have type string, but got '${typeof e}'`);throw new Error("Authenticator.login() is abstract and must be implemented by subclasses.")}loginWithToken(t,e){if("string"!=typeof t)throw new TypeError(`Expected parameter token to have type string, but got '${typeof t}'`);if("string"!=typeof e)throw new TypeError(`Expected parameter provider to have type string, but got '${typeof e}'`);throw new Error("Authenticator.loginWithToken() is abstract and must be implemented by subclasses.")}loginWithUsernameAndPassword(t,e,i){if("string"!=typeof t)throw new TypeError(`Expected parameter username to have type string, but got '${typeof t}'`);if("string"!=typeof e)throw new TypeError(`Expected parameter password to have type string, but got '${typeof e}'`);if("string"!=typeof i)throw new TypeError(`Expected parameter provider to have type string, but got '${typeof i}'`);throw new Error("Authenticator.loginWithUsernameAndPassword() is abstract and must be implemented by subclasses.")}logout(t){if(void 0!==t&&"function"!=typeof t)throw new TypeError(`Expected parameter cleanupFn to have type function, but got '${typeof t}'`);throw new Error("Authenticator.logout() is abstract and must be implemented by subclasses.")}observeStatus(t){if("function"!=typeof t)throw new TypeError(`Expected parameter callback to have type function, but got '${typeof t}'`);const e=this.observerManager.addObserver(t);return new Observer(this.observerManager,e,{stopsWhenFinalized:!0})}constructor(t){this.keepAlive=t,this._status={isAuthenticated:!1,userID:null},this.loginSupported=!1,this.observerManager=new ObserverManager("AuthenticationStatusObservation",{keepAlive:t})}"@ditto.authenticationExpiring"(t){throw new Error("Authenticator['@ditto.authenticationExpiring']() is abstract and must be implemented by subclasses.")}close(){this.observerManager.close()}}class OnlineAuthenticator extends Authenticator{async login(t,e){if("string"!=typeof t)throw new TypeError(`Expected parameter token to have type string, but got '${typeof t}'`);if("string"!=typeof e)throw new TypeError(`Expected parameter provider to have type string, but got '${typeof e}'`);const i=this.ditto.deref();if(!i||i.isClosed)throw new DittoError("authentication/failed-to-authenticate","Ditto instance is closed");return i.deferCloseAsync((async i=>{const{clientInfo:n,error:r}=await dittoAuthClientLoginWithTokenAndFeedback(i.deref(),t,e);return{clientInfo:n,error:null!=r?DittoError.fromFFIError(r,"authentication/failed-to-authenticate"):null}}))}async loginWithToken(t,e){if("string"!=typeof t)throw new TypeError(`Expected parameter token to have type string, but got '${typeof t}'`);if("string"!=typeof e)throw new TypeError(`Expected parameter provider to have type string, but got '${typeof e}'`);const i=this.ditto.deref();if(i&&!i.isClosed)return i.deferCloseAsync((async i=>{await dittoAuthClientLoginWithToken(i.deref(),t,e)}))}async loginWithUsernameAndPassword(t,e,i){if("string"!=typeof t)throw new TypeError(`Expected parameter username to have type string, but got '${typeof t}'`);if("string"!=typeof e)throw new TypeError(`Expected parameter password to have type string, but got '${typeof e}'`);if("string"!=typeof i)throw new TypeError(`Expected parameter provider to have type string, but got '${typeof i}'`);const n=this.ditto.deref();if(n&&!n.isClosed)return n.deferCloseAsync((async n=>{await dittoAuthClientLoginWithUsernameAndPassword(n.deref(),t,e,i)}))}async logout(t){if(void 0!==t&&"function"!=typeof t)throw new TypeError(`Expected parameter cleanupFn to have type function, but got '${typeof t}'`);const e=this.ditto.deref();if(e&&!e.isClosed)return e.deferCloseAsync((async i=>{await dittoAuthClientLogout(i.deref()),e.stopSync(),null==t||t(e)}))}constructor(t,e,i){super(t),this.loginSupported=!0,this._status={isAuthenticated:!1,userID:null},this.ditto=new WeakRef(e),this.authenticationHandler=i;const n=new WeakRef(this);e.deferClose((t=>{dittoSetAuthenticationStatusHandler(t.deref(),(function(t){const e=n.deref();if(null==e)return void Logger.info("Authenticator is null, ignoring authentication status change");const i=authenticationStatusFromFFI(t);e.authenticationStatusUpdated(i)}))})),this.updateAndNotify(!1)}"@ditto.authenticationExpiring"(t){const e=this.ditto.deref();if(!(null!==e&&e.configOrParameters.isParameters))return void e.deferCloseAsync((async()=>{try{await this.expirationHandler(e,t)}catch(t){Logger.error(`Authentication expiration handler failed: ${t.message}`)}}));const i=this.authenticationHandler;t>0?i.authenticationExpiringSoon(this,t):i.authenticationRequired(this)}authenticationStatusUpdated(t){var e;const i=this.status;this._status=t;!!i.isAuthenticated==!!t.isAuthenticated&&i.userID===t.userID||(null===(e=this.authenticationHandler.authenticationStatusDidChange)||void 0===e||e.call(this.authenticationHandler,this),this.observerManager.notify(t))}updateAndNotify(t){const e=this.ditto.deref();if(!e)return void Logger.debug("Unable to update auth status and notify, related Ditto object does not exist anymore.");const i=Bridge.ditto.handleFor(e).derefOrNull();if(!i)return void Logger.debug("Unable to update auth status and notify, related Ditto object does not exist anymore.");const n={isAuthenticated:dittoAuthClientIsWebValid(i),userID:dittoAuthClientUserID(i)};t?this.authenticationStatusUpdated(n):this._status=n}}class OnlineAuthenticatorV2 extends Authenticator{get expirationHandler(){const t=this.ditto.deref();return!t||t.isClosed?(Logger.error("Ditto instance is closed, cannot get authentication expiration handler."),null):this._expirationHandler}async setExpirationHandler(t){if(null!==t&&"function"!=typeof t)throw new TypeError(`Expected parameter handler to have type function or null, but got '${typeof t}'`);const e=this.ditto.deref();return e&&!e.isClosed||Logger.error("Ditto instance is closed, cannot set authentication expiration handler."),this._expirationHandler=t,e.deferCloseAsync((async t=>{try{const e=dittoAuthClientMakeLoginProvider(this.makeFFFIAuthenticationExpirationHandler());await dittoAuthSetLoginProvider(t.deref(),e)}catch(t){Logger.error(`Failed to set authentication expiration handler: ${t.message}`)}}))}constructor(t,e){if(super(t),this._expirationHandler=null,e.configOrParameters.isParameters)throw new Error("OnlineAuthenticatorV2 can only be used with the new DittoConfig-based API.");this.loginSupported="server"===e.config.connect.mode,this.ditto=new WeakRef(e);const i=new WeakRef(this);e.deferClose((t=>{dittoSetAuthenticationStatusHandler(t.deref(),(function(t){const e=i.deref();if(null==e)return void Logger.info("Authenticator is null, ignoring authentication status change");const n=authenticationStatusFromFFI(t);e.authenticationStatusUpdated(n)}))})),this.updateAndNotify(!1)}async login(t,e){if("string"!=typeof t)throw new TypeError(`Expected parameter token to have type string, but got '${typeof t}'`);if("string"!=typeof e)throw new TypeError(`Expected parameter provider to have type string, but got '${typeof e}'`);const i=this.ditto.deref();if(!i||i.isClosed)throw new DittoError("authentication/failed-to-authenticate","Ditto instance is closed");return i.deferCloseAsync((async i=>{const{clientInfo:n,error:r}=await dittoAuthClientLoginWithTokenAndFeedback(i.deref(),t,e);return{clientInfo:n,error:null!=r?DittoError.fromFFIError(r,"authentication/failed-to-authenticate"):null}}))}async loginWithToken(t,e){if("string"!=typeof t)throw new TypeError(`Expected parameter token to have type string, but got '${typeof t}'`);if("string"!=typeof e)throw new TypeError(`Expected parameter provider to have type string, but got '${typeof e}'`);const i=this.ditto.deref();if(i&&!i.isClosed)return i.deferCloseAsync((async i=>{await dittoAuthClientLoginWithToken(i.deref(),t,e)}))}async loginWithUsernameAndPassword(t,e,i){if("string"!=typeof t)throw new TypeError(`Expected parameter username to have type string, but got '${typeof t}'`);if("string"!=typeof e)throw new TypeError(`Expected parameter password to have type string, but got '${typeof e}'`);if("string"!=typeof i)throw new TypeError(`Expected parameter provider to have type string, but got '${typeof i}'`);const n=this.ditto.deref();if(n&&!n.isClosed)return n.deferCloseAsync((async n=>{await dittoAuthClientLoginWithUsernameAndPassword(n.deref(),t,e,i)}))}async logout(t){if(void 0!==t&&"function"!=typeof t)throw new TypeError(`Expected parameter cleanupFn to have type function, but got '${typeof t}'`);const e=this.ditto.deref();if(e&&!e.isClosed)return e.deferCloseAsync((async i=>{await dittoAuthClientLogout(i.deref()),e.stopSync(),null==t||t(e)}))}authenticationStatusUpdated(t){const e=this.status;this._status=t;!!e.isAuthenticated==!!t.isAuthenticated&&e.userID===t.userID||this.observerManager.notify(t)}updateAndNotify(t){const e=this.ditto.deref();if(!e)return void Logger.debug("Unable to update auth status and notify, related Ditto object does not exist anymore.");const i=Bridge.ditto.handleFor(e).derefOrNull();if(!i)return void Logger.debug("Unable to update auth status and notify, related Ditto object does not exist anymore.");const n={isAuthenticated:dittoAuthClientIsWebValid(i),userID:dittoAuthClientUserID(i)};t?this.authenticationStatusUpdated(n):this._status=n}makeFFFIAuthenticationExpirationHandler(){const t=new WeakRef(this);return e=>{const i=t.deref();if(!i)return;const n=i.ditto.deref();n&&(null!=i.expirationHandler?n.deferCloseAsync((async()=>{try{await i.expirationHandler(n,e)}catch(t){Logger.error(`The authentication handler set via \`ditto.auth.setExpirationHandler()\` failed: ${t.message}`)}})):Logger.error("Authentication required but no expiration handler is set. Please set an expiration handler using `ditto.auth.setExpirationHandler()`."))}}}class NotAvailableAuthenticator extends Authenticator{async login(t,e){throw new Error("Can't login, authentication is not supported for the identity in use, please use an onlineWithAuthentication identity.")}async loginWithToken(t,e){throw new Error("Can't login, authentication is not supported for the identity in use, please use an onlineWithAuthentication identity.")}async loginWithUsernameAndPassword(t,e,i){throw new Error("Can't login, authentication is not supported for the identity in use, please use an onlineWithAuthentication identity.")}logout(t){throw new Error("Can't logout, authentication is not supported for the identity in use, please use an onlineWithAuthentication identity.")}"@ditto.authenticationExpiring"(t){throw new Error(`Internal inconsistency, authentication is not available, yet the @ditto.authenticationExpiring() was called on authenticator: ${this}`)}}const IdentityTypesRequiringOfflineLicenseToken=["manual","sharedKey","offlinePlayground"];function makeIdentityConfig(t){var e,i,n;if("offlinePlayground"===t.type)return dittoIdentityConfigMakeOfflinePlayground(t.appID,null!==(e=t.siteID)&&void 0!==e?e:0);if("manual"===t.type)throw new Error("Manual Identify is currently not implemented for React Native.");if("sharedKey"===t.type)return dittoIdentityConfigMakeSharedKey(t.appID,t.sharedKey,t.siteID);if("onlinePlayground"===t.type){const e=null!==(i=t.customAuthURL)&&void 0!==i?i:defaultAuthURL(t.appID);return dittoIdentityConfigMakeOnlinePlayground(t.appID,t.token,e)}if("onlineWithAuthentication"===t.type){const e=null!==(n=t.customAuthURL)&&void 0!==n?n:defaultAuthURL(t.appID);return dittoIdentityConfigMakeOnlineWithAuthentication(t.appID,e)}}const DEFAULT_IDENTITY={type:"offlinePlayground",appID:""};class DittoConfig{static get DEFAULT_DATABASE_ID(){return DEFAULT_DATABASE_ID()}static get default(){const t=dittoConfigDefault();return fromFFICBORData(CBOR.decode(t))}constructor(t,e,i){if(this._isFrozen=!1,loggerInit(),"string"!=typeof t)throw new TypeError("Expected id to be a string, but got: "+typeof t);if("object"!=typeof e)throw new TypeError("Expected connect to be an object, but got: "+typeof e);if(null!=i&&"string"!=typeof i)throw new TypeError("Expected persistenceDirectory to be undefined or a string, but got: "+typeof i);this.databaseID=t,this.connect=e,this.persistenceDirectory=i,this.validate()}get isFrozen(){return this._isFrozen}freeze(){return this.isFrozen||(this._isFrozen=!0,Object.freeze(this.connect),Object.freeze(this)),this}copy(){return new DittoConfig(this.databaseID,{...this.connect},this.persistenceDirectory)}toCBOR(){try{const t=toFFICBORData(this);return CBOR.encode(t)}catch(t){throw new DittoError("validation/invalid-ditto-config",`Failed to convert DittoConfig to CBOR: ${t.message}`)}}validate(){if(!this.databaseID)throw new DittoError("validation/invalid-ditto-config","`id` must be provided for DittoConfig.");if("string"!=typeof this.databaseID)throw new DittoError("validation/invalid-ditto-config",`\`id\` must be of type string, but is of type '${typeof this.databaseID}': ${this.databaseID}`);if(!this.connect)throw new DittoError("validation/invalid-ditto-config","`connect` must be provided for DittoConfig.");if("object"!=typeof this.connect)throw new DittoError("validation/invalid-ditto-config",`\`connect\` must be an object, but is of type '${typeof this.connect}'.`)}}function toFFICBORData(t){var e;let i;if("server"===t.connect.mode)i={type:"server",url:t.connect.url};else{if("smallPeersOnly"!==t.connect.mode)throw new DittoError("validation/invalid-ditto-config",`Unsupported connect mode: ${t.connect.mode}`);i={type:"small_peers_only"},t.connect.privateKey&&(i.private_key=t.connect.privateKey)}return{database_id:t.databaseID,connect:i,persistence_directory:null!==(e=t.persistenceDirectory)&&void 0!==e?e:null,experimental:{}}}function fromFFICBORData(t){let e;return"server"===t.connect.type?e={mode:"server",url:t.connect.url}:(e={mode:"smallPeersOnly"},t.connect.private_key&&(e.privateKey=t.connect.private_key)),new DittoConfig(t.database_id,e,t.persistence_directory)}const AUTH_HANDLER_NOOP={authenticationRequired(t){},authenticationExpiringSoon(t,e){},authenticationStatusDidChange(t){}},DEFAULT_PERSISTENCE_DIRECTORY="ditto";class ConfigOrParameters{get isConfig(){return void 0!==this._config}get isParameters(){return void 0!==this._parameters}get kind(){if(this.isConfig&&!this.isParameters)return"config";if(this.isParameters&&!this.isConfig)return"parameters";throw new DittoError("internal","ConfigOrParameters is neither a config nor parameters")}get config(){switch(this.kind){case"config":return this._config;case"parameters":const t=this._parameters.identity;switch(t.type){case"onlineWithAuthentication":case"onlinePlayground":return new DittoConfig(t.appID,{mode:"server",url:this.urlFrom(t.customAuthURL,t.appID)},this._parameters.persistenceDirectory);case"sharedKey":return new DittoConfig(t.appID,{mode:"smallPeersOnly",privateKey:t.sharedKey},this._parameters.persistenceDirectory);case"offlinePlayground":return new DittoConfig(t.appID,{mode:"smallPeersOnly"},this._parameters.persistenceDirectory);case"manual":return Logger.warning("Can't create a `DittoConfig` from a `manual` identity, manual identities are being phased out and not supported with the `DittoConfig`-based APIs anymore. Mapping onto `{ mode: 'smallPeersOnly' }`."),new DittoConfig(DittoConfig.DEFAULT_DATABASE_ID,{mode:"smallPeersOnly"},this._parameters.persistenceDirectory)}}}get identity(){switch(this.kind){case"parameters":return this._parameters.identity;case"config":const{databaseID:t,connect:e}=this._config;switch(e.mode){case"server":return{type:"onlineWithAuthentication",appID:t,authHandler:AUTH_HANDLER_NOOP,enableDittoCloudSync:!1,customAuthURL:e.url};case"smallPeersOnly":return e.privateKey?{type:"sharedKey",appID:t,sharedKey:e.privateKey}:{type:"offlinePlayground",appID:t}}}}get persistenceDirectory(){switch(this.kind){case"parameters":return this._parameters.persistenceDirectory;case"config":return this._config.persistenceDirectory}}constructor(t,e){if(this.passphrase=null,this.historyTrackingEnabled=!1,t instanceof DittoConfig)this._config=t,this._parameters=void 0;else{const i=this.validatePersistenceDirectory(e);this.validateIdentity(t),this._parameters={identity:t,persistenceDirectory:i},this._config=void 0}}redactingSensitiveData(){switch(this.kind){case"config":const t=this._config.copy();return"smallPeersOnly"===t.connect.mode&&null!=t.connect.privateKey&&(t.connect.privateKey="[REDACTED]"),new ConfigOrParameters(t);case"parameters":const e={...this._parameters.identity};return"sharedKey"===e.type&&(e.sharedKey="[REDACTED]"),new ConfigOrParameters(e,this._parameters.persistenceDirectory)}}validateIdentity(t){var e,i;if(!t||"object"!=typeof t)throw new TypeError("Expected `identity` to be an object, but got: "+typeof t);const n={...t},r=t.appID;if(!["offlinePlayground","sharedKey","manual","onlinePlayground","onlineWithAuthentication"].includes(t.type))throw new Error(`Unknown identity type: ${t.type}`);if(("offlinePlayground"===t.type||"sharedKey"===t.type||"onlinePlayground"===t.type||"onlineWithAuthentication"===t.type)&&void 0===r)throw new Error("Property .appID must be given for identity, but isn't.");if(void 0!==r&&"string"!=typeof r)throw new Error(`Property .appID must be be of type string, but is of type '${typeof r}': ${r}`);if(("offlinePlayground"===t.type||"sharedKey"===t.type)&&void 0!==t.siteID){const e=t.siteID;if(!("number"==typeof e||"bigint"==typeof e))throw new Error("siteID must be a number or BigInt");if(e<0)throw new Error("siteID must be >= 0");if(e>BigInt("0xffffffffffffffff"))throw new Error("siteID must be < 2^64")}if("offlinePlayground"===t.type&&void 0!==t.siteID&&Logger.warning("Property .siteID is deprecated and should no longer be specified in an offline playground identity."),"sharedKey"===t.type&&void 0!==t.siteID&&Logger.warning("Property .siteID is deprecated and should no longer be specified in a shared key identity."),t.type,"onlinePlayground"===t.type){const e=t.token;if(void 0===e)throw new Error("Property .token must be given for identity but isn't. You can find the corresponding token on the Ditto Portal.");if(void 0!==e&&"string"!=typeof e)throw new Error(`Property .token of identity must be be of type string, but is of type '${typeof e}': ${e}`)}if("onlineWithAuthentication"===t.type){const n=typeof t.authHandler;if("object"!==n)throw new TypeError(`Property .authHandler on identity of type onlineWithAuthentication must be an object, but is of type '${n}'.`);const r=typeof(null===(e=t.authHandler)||void 0===e?void 0:e.authenticationExpiringSoon),o=typeof(null===(i=t.authHandler)||void 0===i?void 0:i.authenticationRequired);if("function"!==r)throw new TypeError(`Property .authHandler.authenticationExpiringSoon on identity of type onlineWithAuthentication must be a function, but is of type '${r}'.`);if("function"!==o)throw new TypeError(`Property .authHandler.authenticationRequired on identity of type onlineWithAuthentication must be a function, but is of type '${o}'.`)}return n}validatePersistenceDirectory(t){if(null==t)return"ditto";if(0===t.trim().length)throw new Error(`Invalid persistenceDirectory: '${t}'`);return t}urlFrom(t,e){return null!=t?t:`https://${e}.cloud.ditto.live`}}function transportConfigFromDeserializable(t){const e=t.peer_to_peer,i=e.bluetooth_le.enabled,n=e.awdl.enabled,r=e.lan,o=r.enabled,s=r.mdns_enabled,a=r.multicast_enabled,c=e.wifi_aware.enabled,d=t.connect,l=d.tcp_servers,u=d.websocket_urls,f=d.retry_interval,h=t.listen,_=h.tcp,g=_.enabled,p=_.interface_ip,m=_.port,b=h.http,w=b.enabled,v=b.interface_ip,I=b.port,C=b.static_content_path,E=b.websocket_sync,D=b.tls_key_path,A=b.tls_certificate_path,S=t.global,T=S.sync_group,k=S.routing_hint,F=new TransportConfig;return F.peerToPeer.bluetoothLE.isEnabled=i,F.peerToPeer.awdl.isEnabled=n,F.peerToPeer.lan.isEnabled=o,F.peerToPeer.lan.isMdnsEnabled=s,F.peerToPeer.lan.isMulticastEnabled=a,F.peerToPeer.wifiAware.isEnabled=c,F.connect.tcpServers=l,F.connect.websocketURLs=u,F.connect.retryInterval=f,F.listen.tcp.isEnabled=g,F.listen.tcp.interfaceIP=p,F.listen.tcp.port=m,F.listen.http.isEnabled=w,F.listen.http.interfaceIP=v,F.listen.http.port=I,F.listen.http.staticContentPath=C,F.listen.http.websocketSync=E,F.listen.http.tlsKeyPath=D,F.listen.http.tlsCertificatePath=A,F.global.syncGroup=T,F.global.routingHint=k,F}function transportConfigToSerializable(t){const e=t.peerToPeer,i=t.connect,n=t.listen,r=t.global,o={peer_to_peer:{bluetooth_le:{enabled:e.bluetoothLE.isEnabled},awdl:{enabled:e.awdl.isEnabled},wifi_aware:{enabled:e.wifiAware.isEnabled},lan:{enabled:e.lan.isEnabled,mdns_enabled:e.lan.isMdnsEnabled,multicast_enabled:e.lan.isMulticastEnabled}},connect:{tcp_servers:i.tcpServers,websocket_urls:i.websocketURLs,retry_interval:i.retryInterval},listen:{tcp:{enabled:n.tcp.isEnabled,interface_ip:n.tcp.interfaceIP,port:n.tcp.port},http:{enabled:n.http.isEnabled,interface_ip:n.http.interfaceIP,port:n.http.port,websocket_sync:n.http.websocketSync}},global:{sync_group:r.syncGroup,routing_hint:r.routingHint}};return n.http.staticContentPath&&(o.listen.http.static_content_path=n.http.staticContentPath),n.http.tlsKeyPath&&(o.listen.http.tls_key_path=n.http.tlsKeyPath),n.http.tlsCertificatePath&&(o.listen.http.tls_certificate_path=n.http.tlsCertificatePath),o}const NO_PREFERRED_ROUTE_HINT=0;class TransportConfig{constructor(){this._isFrozen=!1,this.peerToPeer={bluetoothLE:{isEnabled:!1},awdl:{isEnabled:!1},lan:{isEnabled:!1,isMdnsEnabled:!0,isMulticastEnabled:!0},wifiAware:{isEnabled:!1}},this.connect={tcpServers:[],websocketURLs:[],retryInterval:5e3},this.listen={tcp:{isEnabled:!1,interfaceIP:"[::]",port:4040},http:{isEnabled:!1,interfaceIP:"[::]",port:80,websocketSync:!0}},this.global={syncGroup:0,routingHint:0}}setAllPeerToPeerEnabled(t){this.peerToPeer.bluetoothLE.isEnabled=t,this.peerToPeer.lan.isEnabled=t,this.peerToPeer.awdl.isEnabled=t,this.peerToPeer.wifiAware.isEnabled=t}setAvailablePeerToPeerEnabled(t){const e="android"===rnOnlyGetPlatform(),i="ios"===rnOnlyGetPlatform(),n="macos"===rnOnlyGetPlatform();this.peerToPeer.bluetoothLE.isEnabled=t,this.peerToPeer.lan.isEnabled=t,this.peerToPeer.wifiAware.isEnabled=!!e&&t,this.peerToPeer.awdl.isEnabled=!(!i&&!n)&&t}get isFrozen(){return this._isFrozen}freeze(){return this.isFrozen||(this._isFrozen=!0,Object.freeze(this.peerToPeer.bluetoothLE),Object.freeze(this.peerToPeer.awdl),Object.freeze(this.peerToPeer.lan),Object.freeze(this.peerToPeer.wifiAware),Object.freeze(this.peerToPeer),Object.freeze(this.connect.tcpServers),Object.freeze(this.connect.websocketURLs),Object.freeze(this.connect),Object.freeze(this.listen.tcp),Object.freeze(this.listen.http),Object.freeze(this.listen),Object.freeze(this.global),Object.freeze(this)),this}copy(){const t=new TransportConfig;return t.peerToPeer.bluetoothLE.isEnabled=this.peerToPeer.bluetoothLE.isEnabled,t.peerToPeer.awdl.isEnabled=this.peerToPeer.awdl.isEnabled,t.peerToPeer.lan.isEnabled=this.peerToPeer.lan.isEnabled,t.peerToPeer.lan.isMdnsEnabled=this.peerToPeer.lan.isMdnsEnabled,t.peerToPeer.lan.isMulticastEnabled=this.peerToPeer.lan.isMulticastEnabled,t.peerToPeer.wifiAware.isEnabled=this.peerToPeer.wifiAware.isEnabled,t.connect.tcpServers=this.connect.tcpServers.slice(),t.connect.websocketURLs=this.connect.websocketURLs.slice(),t.connect.retryInterval=this.connect.retryInterval,t.listen.tcp={...this.listen.tcp},t.listen.http={...this.listen.http},t.global.syncGroup=this.global.syncGroup,t.global.routingHint=this.global.routingHint,t}static areListenTCPsEqual(t,e){return t.isEnabled===e.isEnabled&&t.interfaceIP===e.interfaceIP&&t.port===e.port}static areListenHTTPsEqual(t,e){return t.isEnabled===e.isEnabled&&t.interfaceIP===e.interfaceIP&&t.port===e.port&&t.staticContentPath===e.staticContentPath&&t.websocketSync===e.websocketSync&&t.tlsKeyPath===e.tlsKeyPath&&t.tlsCertificatePath===e.tlsCertificatePath}}const privateToken$1=Symbol("privateConstructorToken");class Counter{get value(){return this._value}constructor(){this._value=0}static"@ditto.create"(t,e,i){const n=t?new MutableCounter(privateToken$1):new Counter;return n.mutDoc=t,n.path=e,n._value=i,n}}class MutableCounter extends Counter{increment(t){throw new Error("This API is not available in React Native environments. Please use 'ditto.store.registerObserver(…)' instead. For more details and guidance, visit: https://ditto.com/link/dql.")}constructor(){if(arguments[0]!==privateToken$1)throw new Error("MutableCounter constructor is for internal use only.");super()}}const privateToken="@ditto.ff82dae89821c5ab822a8b539056bce4";class Register{get value(){return this["@ditto.value"]}constructor(t){this["@ditto.value"]=t}static"@ditto.create"(t,e,i){const n=t?new MutableRegister(i,privateToken):new Register(i);return n["@ditto.mutableDocument"]=t,n["@ditto.path"]=e,n["@ditto.value"]=i,n}}class MutableRegister extends Register{get value(){return super.value}set value(t){this.set(t)}set(t){const e=this["@ditto.mutableDocument"],i=this["@ditto.path"];e.at(i)["@ditto.set"](t),this["@ditto.value"]=t}constructor(t){if(arguments[1]!==privateToken)throw new Error("MutableRegister constructor is for internal use only.");super(t)}}function desugarJSObject(t){if(t&&"object"==typeof t){if(Array.isArray(t))return t.map(((t,e)=>desugarJSObject(t)));if(t instanceof DocumentID)return t.value;if(t instanceof Counter){const e={};return e[DittoCRDTTypeKey]=DittoCRDTType.counter,e._value=t.value,e}if(t instanceof Register){const e={};return e[DittoCRDTTypeKey]=DittoCRDTType.register,e._value=t.value,e}if(t instanceof Attachment){const e={_id:t.token.idBytes,_len:t.token.len,_meta:t.token.metadata};return e[DittoCRDTTypeKey]=DittoCRDTType.attachment,e}{const e={};for(const[i,n]of Object.entries(t))e[i]=desugarJSObject(n);return e}}return checkForUnsupportedValues(t),t}function checkForUnsupportedValues(t){if(Number.isNaN(t)||t===1/0||t===-1/0)throw new Error("Non-finite float values are not supported")}const CUSTOM_INSPECT_SYMBOL$1=Symbol.for("nodejs.util.inspect.custom");class Document{static hash(t){throw new Error("This API is not available in React Native environments. Please use 'ditto.store.registerObserver(…)' instead. For more information see: https://ditto.com/link/dql-legacy-to-dql-adoption")}static hashMnemonic(t){throw new Error("This API is not available in React Native environments. Please use 'ditto.store.registerObserver(…)' instead. For more information see: https://ditto.com/link/dql-legacy-to-dql-adoption")}get id(){throw new Error("This API is not available in React Native environments. Please use 'ditto.store.registerObserver(…)' instead. For more information see: https://ditto.com/link/dql-legacy-to-dql-adoption")}get path(){throw new Error("This API is not available in React Native environments. Please use 'ditto.store.registerObserver(…)' instead. For more information see: https://ditto.com/link/dql-legacy-to-dql-adoption")}get value(){throw new Error("This API is not available in React Native environments. Please use 'ditto.store.registerObserver(…)' instead. For more information see: https://ditto.com/link/dql-legacy-to-dql-adoption")}at(t){throw new Error("This API is not available in React Native environments. Please use 'ditto.store.registerObserver(…)' instead. For more information see: https://ditto.com/link/dql-legacy-to-dql-adoption")}constructor(){}static idCBOR(t){return documentID(Bridge.document.handleFor(t).deref())}static canonicalizedIDCBOR(t){return validateDocumentIDCBOR(t)}static isIDCBORCanonical(t){return t===this.canonicalizedIDCBOR(t)}toString(){return`${this.constructor.name}(${this.id})`}[CUSTOM_INSPECT_SYMBOL$1](t,e,i){return customInspectRepresentation(this,i)}}class MutableDocument{get id(){throw new Error("This API is not available in React Native environments. Please use 'ditto.store.registerObserver(…)' instead. For more information see: https://ditto.com/link/dql-legacy-to-dql-adoption")}get path(){throw new Error("This API is not available in React Native environments. Please use 'ditto.store.registerObserver(…)' instead. For more information see: https://ditto.com/link/dql-legacy-to-dql-adoption")}get value(){throw new Error("This API is not available in React Native environments. Please use 'ditto.store.registerObserver(…)' instead. For more information see: https://ditto.com/link/dql-legacy-to-dql-adoption")}at(t){throw new Error("This API is not available in React Native environments. Please use 'ditto.store.registerObserver(…)' instead. For more information see: https://ditto.com/link/dql-legacy-to-dql-adoption")}constructor(){this["@ditto.updateResults"]=[]}static idCBOR(t){return documentID(Bridge.mutableDocument.handleFor(t).deref())}toString(){return`${this.constructor.name}(${this.id})`}[CUSTOM_INSPECT_SYMBOL$1](t,e,i){return customInspectRepresentation(this,i)}}MutableDocument.canonicalizedIDCBOR=Document.canonicalizedIDCBOR,MutableDocument.isIDCBORCanonical=Document.isIDCBORCanonical;class QueryResult{mutatedDocumentIDs(){return queryResultMutatedDocumentIDs(Bridge.queryResult.handleFor(this).deref()).map((t=>new DocumentID(t,!0)))}mutatedDocumentIDsV2(){return queryResultMutatedDocumentIDs(Bridge.queryResult.handleFor(this).deref()).map((t=>CBOR.decode(t)))}get commitID(){const t=Bridge.queryResult.handleFor(this);return queryResultHasCommitID(t.deref())?queryResultCommitID(t.deref()):null}constructor(t){if(null==t)throw new Error("Internal inconsistency, failed to initialize query result without a response pointer");const e=queryResultItems(t);this.items=e.map((t=>Bridge.queryResultItem.bridge(t)))}}class StoreObserver{get isCancelled(){return this._isCancelled}cancel(){this._isCancelled||(this._isCancelled=!0,this.ditto.store.unregisterObserver(this))}constructor(t,e,i,n){this._isCancelled=!1,this.queryString=e,this.queryArguments=i?Object.freeze({...i}):void 0,this.ditto=t;let r,o=null;if(null!=i)try{const t=desugarJSObject(i);o=CBOR.encode(t)}catch(t){throw new DittoError("query/arguments-invalid")}if(this.ditto.deferClose((t=>{const i=new WeakRef(this);function wrappedObservationHandler(t){const e=i.deref();if(null==e)return void Logger.debug(`Ignoring change event received by store observer ${r} after it was cancelled`);const o=Bridge.queryResult.bridge(t.query_result,(()=>new QueryResult(t.query_result)));Logger.debug(`Invoking user event handler with new event for store observer ${r}`),n(o,(()=>e.signalNext()))}mapFFIErrors((()=>{r=tryExperimentalRegisterChangeObserver(t.deref(),e,o,wrappedObservationHandler)}))})),null==r)throw new DittoError("internal","Internal inconsistency, store observer ID is undefined after registering");this.liveQueryID=r}async signalNext(){const t=this.ditto;if(t&&!t.isClosed){if(null==this.liveQueryID)throw new Error("live query ID is null while signaling ready for next event");return t.deferCloseAsync((async t=>{Logger.debug(`Signaling availability for live query ${this.liveQueryID}`),await liveQuerySignalAvailableNext(t.deref(),this.liveQueryID)}))}}}class TransactionInfo{constructor(t,e,i){this.id=t,this.hint=i,this.isReadOnly=e}}class Transaction{constructor(t){this.store=t}get info(){const t=transactionInfo(Bridge.transaction.handleFor(this).deref()),e=CBOR.decode(t);return new TransactionInfo(e.id,e.is_read_only,e.hint)}async execute(t,e){if("string"!=typeof t)throw new DittoError("query/invalid","Expected parameter 'query' to be of type 'string', found: "+typeof t);return this.store.ditto.deferCloseAsync((async()=>{let i=null;if(e)try{const t=desugarJSObject(e);i=CBOR.encode(t)}catch(t){throw new DittoError("query/arguments-invalid",`Unable to encode query arguments: ${t.message}`)}const n=Bridge.transaction.handleFor(this),r=await mapFFIErrorsAsync((async()=>transactionExecuteAsync(n.deref(),t,i)));return Bridge.queryResult.bridge(r,(()=>new QueryResult(r)))}))}async complete(t){const e=Bridge.transaction.handleFor(this);return(await mapFFIErrorsAsync((async()=>await transactionCompleteAsync(e.deref(),capitalize(t))))).toLowerCase()}}class Store{get transactions(){return this.ditto.deferClose((t=>{const e=storeTransactions(dittoPointerToStorePointer(t.deref()));return CBOR.decode(e).map((t=>new TransactionInfo(t.id,t.is_read_only,t.hint)))}))}registerObserver(t,e,i){return this.registerObserverWithSignalNext(t,((t,i)=>{try{e(t)}finally{i()}}),i)}registerObserverWithSignalNext(t,e,i){if("string"!=typeof t)throw new DittoError("query/invalid","Expected parameter 'query' to be of type 'string', found: "+typeof t);const n=new StoreObserver(this.ditto,t,null!=i?i:null,e);return this.observers=Object.freeze([...this.observers,n]),this.ditto.deferCloseAsync((async t=>new Promise((e=>{step((async()=>{try{await mapFFIErrorsAsync((async()=>await liveQueryStart(t.deref(),n.liveQueryID)))}catch(t){Logger.error(`Failed to start live query: ${t.message}`)}e()}))})))),n}collection(t){throw new Error("This API is not available in React Native environments. Please use 'ditto.store.registerObserver(…)' instead. For more information see: https://ditto.com/link/dql-legacy-to-dql-adoption")}collections(){throw new Error("This API is not available in React Native environments. Please use 'ditto.store.registerObserver(…)' instead. For more information see: https://ditto.com/link/dql-legacy-to-dql-adoption")}collectionNames(){throw new Error("This API is not available in React Native environments. Please use 'ditto.store.registerObserver(…)' instead. For more information see: https://ditto.com/link/dql-legacy-to-dql-adoption")}async execute(t,e){if("string"!=typeof t)throw new DittoError("query/invalid","Expected parameter 'query' to be of type 'string', found: "+typeof t);return this.ditto.deferCloseAsync((async i=>{let n=null;if(null!=e)try{const t=desugarJSObject(e);n=CBOR.encode(t)}catch(t){throw new DittoError("query/arguments-invalid",`Unable to encode query arguments: ${t.message}`)}const r=await mapFFIErrorsAsync((async()=>await performAsyncToWorkaroundNonAsyncFFIAPI((()=>tryExecStatement(i.deref(),t,n)))));return Bridge.queryResult.bridge(r,(()=>new QueryResult(r)))}))}async write(t){throw new Error("This API is not available in React Native environments. Please use 'ditto.store.registerObserver(…)' instead. For more information see: https://ditto.com/link/dql-legacy-to-dql-adoption")}async newAttachment(t,e){return null!=e&&validateAttachmentMetadata(e),this.ditto.deferCloseAsync((async i=>{const{id:n,len:r,handle:o}=await(async()=>{if("string"==typeof t)return mapFFIErrors((()=>dittoNewAttachmentFromFile(i.deref(),t,"Copy")),{1:["store/failed-to-create-attachment"],2:["store/attachment-file-not-found"],3:["store/attachment-file-permission-denied"]});if(t instanceof Uint8Array)return mapFFIErrorsAsync((async()=>await dittoNewAttachmentFromBytes(i.deref(),t)),{1:["store/failed-to-create-attachment"]});throw new Error(`Can't create new attachment, only file path as string or raw data as Uint8Array are supported, but got: ${typeof t}, ${t}`)})(),s={_id:n,_len:r,_meta:{...e},[DittoCRDTTypeKey]:DittoCRDTType.attachment},a=new AttachmentToken(s),c=new Attachment(this.ditto,a);return Bridge.attachment.bridge(o,(()=>c))}))}fetchAttachment(t,e){if(null==t)throw new Error("Missing required parameter 'token'");let i;return i=t instanceof AttachmentToken?t:new AttachmentToken(t),this.ditto.deferClose((()=>{const t=new AttachmentFetcher(this.ditto,i,null,e);return this.attachmentFetchers=Object.freeze([...this.attachmentFetchers,t]),t}))}constructor(t){this.observers=Object.freeze([]),this.attachmentFetchers=Object.freeze([]),this.ditto=t}unregisterObserver(t){if(t.ditto!==this.ditto)throw new DittoError("internal","Internal inconsistency, can't remove store observer that does not belong to this store");if(!t.isCancelled)throw new DittoError("internal","Internal inconsistency, can't remove store observer that has not been cancelled");const e=this.observers.findIndex((e=>e===t));if(-1===e)return!1;const i=[...this.observers];i.splice(e,1),this.observers=Object.freeze(i);const n=Bridge.ditto.handleFor(this.ditto);return this.ditto.deferClose((()=>{mapFFIErrors((()=>liveQueryStop(n.deref(),t.liveQueryID)))})),!0}removeAttachmentFetcher(t){if(t.ditto!==this.ditto)throw new DittoError("internal","Internal inconsistency, can't finalize attachment fetcher that does not belong to this store");if(null!=t.manager)throw new DittoError("internal","Internal inconsistency, store can't remove attachment fetcher that is owned by the attachment fetcher manager");if(!t.isStopped)throw new DittoError("internal","Internal inconsistency, can't remove attachment fetcher that has not stopped");const e=this.attachmentFetchers.findIndex((e=>e===t));if(-1===e)return!1;const i=[...this.attachmentFetchers];return i.splice(e,1),this.attachmentFetchers=Object.freeze(i),!0}async transaction(t,e={}){return this.ditto.deferCloseAsync((async()=>{if((null==e?void 0:e.isReadOnly)&&"boolean"!=typeof e.isReadOnly)throw new TypeError("Expected 'options.isReadOnly' to be a boolean");if((null==e?void 0:e.hint)&&"string"!=typeof e.hint)throw new TypeError("Expected 'options.hint' to be a string");const i=await this.beginTransaction(e);let n;try{n=await t(i)}catch(t){throw await i.complete("rollback"),t}return"rollback"===n||"commit"===n?await i.complete(n):(await i.complete("commit"),n)}))}async beginTransaction(t={}){return this.ditto.deferCloseAsync((async e=>{var i,n;const r=null!==(i=t.isReadOnly)&&void 0!==i&&i,o=null!==(n=t.hint)&&void 0!==n?n:null,s=dittoPointerToStorePointer(e.deref()),a=await storeBeginTransaction(s,{isReadOnly:r,hint:o});return Bridge.transaction.bridge(a,(()=>new Transaction(this)))}))}close(){for(const t of this.observers)t.cancel();for(const t of this.attachmentFetchers)t.stop()}}class KeepAlive{get isActive(){return null!==this.intervalID}constructor(){this.countsByID={},this.intervalID=null}retain(t){if(void 0===this.countsByID[t]&&(this.countsByID[t]=0),this.countsByID[t]+=1,null===this.intervalID){const t=2147483647;this.intervalID=setInterval((()=>{}),t),KeepAlive.finalizationRegistry.register(this,this.intervalID,this)}}release(t){if(void 0===this.countsByID[t])throw new Error(`Internal inconsistency, trying to release a keep-alive ID that hasn't been retained before or isn't tracked anymore: ${t}`);this.countsByID[t]-=1,0===this.countsByID[t]&&delete this.countsByID[t],0===Object.keys(this.countsByID).length&&(KeepAlive.finalizationRegistry.unregister(this),clearInterval(this.intervalID),this.intervalID=null)}currentIDs(){return Object.keys(this.countsByID)}countForID(t){var e;return null!==(e=this.countsByID[t])&&void 0!==e?e:null}}function addressToString(t){return`${t.siteId}-${t.pubkey}`}KeepAlive.finalizationRegistry=new FinalizationRegistry(clearInterval);class Presence{get connectionRequestHandler(){return this._connectionRequestHandler}set connectionRequestHandler(t){let e=null;if(null!=t){if("function"!=typeof t)throw new TypeError(`Expected parameter 'handler' to be a function but got ${typeof t} instead`);e=async e=>{const i=Bridge.connectionRequest.bridge(e),n=await t(i);if("allow"!==n&&"deny"!==n)return Logger.error(`The connection request handler must return "allow" or "deny" but returned "${n}" instead. The connection request will be denied.`),"Deny";connectionRequestAuthorize(e,"allow"===n?"Allow":"Deny")}}this._connectionRequestHandler=t;const handleError=t=>{Logger.error(`The connection request handler threw an error while handling a connection request, the connection request will be denied. ${t}`)},i=Bridge.ditto.handleFor(this.ditto);this.ditto.deferClose((()=>{presenceSetConnectionRequestHandler(i.deref(),e,handleError)}))}get graph(){return this.ditto.deferClose((t=>{const e=dittoPresenceV3(t.deref());return JSON.parse(e)}))}get peerMetadataJSONString(){return this.ditto.deferClose((t=>mapFFIErrors((()=>presencePeerMetadataJSON(t.deref())))))}async setPeerMetadataJSONString(t){await this.ditto.deferCloseAsync((async e=>mapFFIErrorsAsync((async()=>presenceTrySetPeerMetadataJSON(e.deref(),t)))))}get peerMetadata(){return JSON.parse(this.peerMetadataJSONString)}async setPeerMetadata(t){let e;try{e=JSON.stringify(t)}catch(t){throw new DittoError("validation/not-json-compatible",`Failed encoding peer metadata to JSON. ${t}`)}await this.setPeerMetadataJSONString(e)}observe(t){const e=this.observerManager.addObserver(t),i=new Observer(this.observerManager,e,{stopsWhenFinalized:!0});return t(this.graph),i}constructor(t){this._connectionRequestHandler=null,this.ditto=t,this.observerManager=new ObserverManager("PresenceObservation",{keepAlive:t.keepAlive,register:t=>{this.ditto.deferClose((e=>{dittoRegisterPresenceV3Callback(e.deref(),t)}))},unregister:()=>{t.deferCloseAsync((async t=>dittoClearPresenceV3Callback(t.deref())))},process:t=>[JSON.parse(t)]})}close(){this.observerManager.close()}}class LiveQueryManager{constructor(t,e){this.finalizationRegistry=new FinalizationRegistry(this.finalize),this.ditto=t,this.keepAlive=e,this.liveQueriesByID={}}startLiveQuery(t){this.ditto.deferCloseAsync((async e=>{const i=t.liveQueryID;if(!i)throw new Error("Internal inconsistency, tried to add a live query that doesn't have a live query ID (probably stopped).");if(this.liveQueriesByID[i])throw new Error("Internal inconsistency, tried to add a live query with an ID that has already been added.");const n=new WeakRef(t);return this.liveQueriesByID[i]=n,this.finalizationRegistry.register(t,i,this.finalize),t.liveQueryManager=this,this.ditto.keepAlive.retain(`LiveQuery.${i}`),new Promise(((t,n)=>{step((async()=>{await liveQueryStart(e.deref(),i),t()}))}))}))}stopLiveQuery(t){this.finalizationRegistry.unregister(t);const e=t.liveQueryID;if(!e)throw new Error("Internal inconsistency, tried to remove a live query that doesn't have a live query ID (probably stopped).");t.liveQueryManager=null,this.stopLiveQueryWithID(e)}close(){for(const t in this.liveQueriesByID){const e=this.liveQueriesByID[t].deref();e&&this.stopLiveQuery(e)}}stopLiveQueryWithID(t){this.ditto.deferClose((e=>{liveQueryStop(e.deref(),t),this.keepAlive.release(`LiveQuery.${t}`),delete this.liveQueriesByID[t]}))}finalize(t){this.stopLiveQueryWithID(t)}}class PresenceManager{constructor(t){this.ditto=t,this.isClosed=!1,this.isRegistered=!1,this.currentRemotePeers=[],this.callbacksByPresenceToken={}}addObserver(t){if(this.isClosed)throw new Error("Internal inconsistency, can't add presence observer, observer mananger close()-ed.");this.registerIfNeeded();const e=cryptoGenerateSecureRandomToken();return this.callbacksByPresenceToken[e]=t,this.ditto.keepAlive.retain(`PresenceObservation.${e}`),t(this.currentRemotePeers),e}async removeObserver(t){const e=this.callbacksByPresenceToken[t];if(void 0===e)throw new Error(`Can't remove presence observer, token '${t}' has never been registered before.`);if(null!==e)return void 0!==this.callbacksByPresenceToken[t]?(this.ditto.keepAlive.release(`PresenceObservation.${t}`),this.callbacksByPresenceToken[t]=null,this.unregisterIfNeeded()):void 0}hasObserver(t){return void 0!==this.callbacksByPresenceToken[t]}async close(){this.isClosed=!0;const t=Object.keys(this.callbacksByPresenceToken);return Promise.all(t.map((t=>this.removeObserver(t))))}hasObservers(){return Object.keys(this.callbacksByPresenceToken).length>0}registerIfNeeded(){this.ditto.deferClose((t=>{if(!this.isRegistered){this.isRegistered=!0;const e=dittoPresenceV1(t.deref());this.currentRemotePeers=this.decode(e).sort(this.compareRemotePeers),dittoRegisterPresenceV1Callback(t.deref(),this.handlePresenceV1Callback.bind(this))}}))}unregisterIfNeeded(){return this.ditto.deferCloseAsync((async t=>{!this.hasObservers()&&this.isRegistered&&(this.isRegistered=!1,await dittoClearPresenceCallback(t.deref()),this.currentRemotePeers=[])}))}handlePresenceV1Callback(t){const e=this.decode(t).sort(this.compareRemotePeers);this.currentRemotePeers=e,this.notify()}notify(){if(!this.isClosed)for(const t in this.callbacksByPresenceToken){const e=this.callbacksByPresenceToken[t];e&&e(this.currentRemotePeers)}}decode(t){return JSON.parse(t).map((t=>{var e,i;return{networkID:t.network_id,deviceName:t.device_name,rssi:null!==(e=t.rssi)&&void 0!==e?e:void 0,approximateDistanceInMeters:null!==(i=t.approximate_distance_in_meters)&&void 0!==i?i:void 0,connections:t.connections}}))}compareRemotePeers(t,e){return 0===t.connections.length&&e.connections.length>0?1:t.connections.length>0&&0===e.connections.length||t.deviceName<e.deviceName?-1:t.deviceName>e.deviceName?1:0}}class TransportConditionsManager extends ObserverManager{constructor(t){super("TransportConditionsObservation",{keepAlive:t.keepAlive}),this.ditto=t}register(t){return this.ditto.deferClose((e=>dittoRegisterTransportConditionChangedCallback(e.deref(),t)))}unregister(){return this.ditto.deferClose((t=>dittoRegisterTransportConditionChangedCallback(t.deref(),null)))}process(t,e){let i,n;switch(t){case"Bluetooth":i="BLE";break;case"Tcp":i="TCP";break;case"Awdl":i="AWDL";break;case"Mdns":i="MDNS";break;case"WiFiAware":i="WiFiAware"}switch(e){case"Unknown":n="Unknown";break;case"Ok":n="OK";break;case"GenericFailure":n="GenericFailure";break;case"AppInBackground":n="AppInBackground";break;case"MdnsFailure":n="MDNSFailure";break;case"TcpListenFailure":n="TCPListenFailure";break;case"NoBleCentralPermission":n="NoBLECentralPermission";break;case"NoBlePeripheralPermission":n="NoBLEPeripheralPermission";break;case"CannotEstablishConnection":n="CannotEstablishConnection";break;case"BleDisabled":n="BLEDisabled";break;case"NoBleHardware":n="NoBLEHardware";break;case"WifiDisabled":n="WiFiDisabled";break;case"TemporarilyUnavailable":n="TemporarilyUnavailable"}return[n,i]}}class SyncSubscription{get isCancelled(){return this._isCancelled}cancel(){this._isCancelled||(this._isCancelled=!0,this.ditto.sync.unregisterSubscription(this))}constructor(t,e,i,n){if(this._isCancelled=!1,null==i!=(null==n))throw new DittoError("internal","Internal inconsistency, query arguments and query arguments CBOR must be both null or both non-null",{queryArguments:i,queryArgumentsCBOR:n});this.ditto=t,this.queryString=e,this.queryArguments=i?Object.freeze({...i}):void 0,this.queryArgumentsCBOR=n}}class Sync{get isActive(){return this.ditto.isSyncActive}start(){this.ditto.startSync()}stop(){this.ditto.stopSync()}registerSubscription(t,e){if("string"!=typeof t)throw new DittoError("query/invalid","Expected parameter 'query' to be of type 'string', found: "+typeof t);let i=null;if(null!=e)try{const t=desugarJSObject(e);i=CBOR.encode(t)}catch(t){throw new DittoError("query/arguments-invalid",`Unable to encode query arguments: ${t.message}`)}this.ditto.deferClose((e=>{mapFFIErrors((()=>tryAddSyncSubscription(e.deref(),t,i)))}));const n=new SyncSubscription(this.ditto,t,e||null,i);return this.subscriptions=Object.freeze([...this.subscriptions,n]),n}constructor(t){this.subscriptions=Object.freeze([]),this.ditto=t}unregisterSubscription(t){if(t.ditto!==this.ditto)throw new DittoError("internal","Can't remove replication subscription that does not belong to this store");if(!t.isCancelled)throw new DittoError("internal","Internal inconsistency, can't remove replication subscription that has not been cancelled");const e=this.subscriptions.findIndex((e=>e===t));if(-1===e)return!1;const i=[...this.subscriptions];return i.splice(e,1),this.subscriptions=Object.freeze(i),this.ditto.deferClose((e=>{mapFFIErrors((()=>tryRemoveSyncSubscription(e.deref(),t.queryString,t.queryArgumentsCBOR)))})),!0}close(){for(const t of this.subscriptions)t.cancel()}}class SubscriptionManager{constructor(t){this.ditto=t,this.subscriptions={},this.finalizationRegistry=new FinalizationRegistry(this.removeWithContextInfo.bind(this))}add(t){const e=t.contextInfo;this.ditto.deferClose((i=>{this.subscriptions[e.id]=new WeakRef(t),this.finalizationRegistry.register(t,t.contextInfo,t),addSubscription(i.deref(),e.collectionName,e.query,e.queryArgsCBOR,e.orderBys,e.limit,e.offset)}))}remove(t){if(null==this.subscriptions[t.contextInfo.id])throw new Error(`Internal inconsistency, tried to remove a subscription that is not tracked: ${t.contextInfo.id}`);this.finalizationRegistry.unregister(t),this.removeWithContextInfo(t.contextInfo)}close(){this.ditto.deferClose((()=>{for(const t in this.subscriptions){const e=this.subscriptions[t].deref();null==e||e.cancel()}}))}removeWithContextInfo(t){this.ditto.deferClose((e=>{delete this.subscriptions[t.id],removeSubscription(e.deref(),t.collectionName,t.query,t.queryArgsCBOR,t.orderBys,t.limit,t.offset)}))}}class AttachmentFetcherManager{constructor(t){this.contextInfoByID={},this.finalizationRegistry=new FinalizationRegistry(this.stopWithContextInfo.bind(this)),this.ditto=t}startAttachmentFetcher(t,e){return this.ditto.deferClose((()=>{const i=new AttachmentFetcher(this.ditto,t,this,e),n={id:i.id,attachmentTokenID:t.idBytes,cancelTokenPromise:i.cancelTokenPromise,attachmentFetcher:new WeakRef(i)};this.finalizationRegistry.register(i,n,i),this.contextInfoByID[i.id]=n;const resetCancelToken=()=>{null!=this.contextInfoByID[i.id]&&(this.contextInfoByID[i.id].cancelTokenPromise=null)};return i.attachment.then((t=>(resetCancelToken(),t)),(t=>(resetCancelToken(),t))),this.ditto.keepAlive.retain(`AttachmentFetcher.${i.id})`),i}))}async stopAttachmentFetcher(t){this.finalizationRegistry.unregister(t);const e=this.contextInfoByID[t.id];if(null==e)throw new Error(`Internal inconsistency: cannot stop attachment fetcher ${t.id}, which is not registered.`);await this.stopWithContextInfo(e)}close(){this.ditto.deferCloseAsync((async()=>{const t=Object.values(this.contextInfoByID).map((async t=>{const e=t.attachmentFetcher.deref();null!=e&&await this.stopAttachmentFetcher(e)}));await Promise.all(t)}))}stopWithContextInfo(t){return this.ditto.deferCloseAsync((async e=>{if(null==this.contextInfoByID[t.id])throw new Error(`Internal inconsistency: attachment fetcher ${t.id} not found in active attachment fetchers.`);delete this.contextInfoByID[t.id],this.ditto.keepAlive.release(`AttachmentFetcher.${t.id})`);const i=await t.cancelTokenPromise;i&&dittoCancelResolveAttachment(e.deref(),t.attachmentTokenID,i)}))}}class SmallPeerInfo{get isEnabled(){return this.ditto.deferClose((t=>dittoSmallPeerInfoGetIsEnabled(t.deref())))}set isEnabled(t){if("boolean"!=typeof t)throw new TypeError("Expected boolean, got "+typeof t);this.ditto.deferClose((e=>{dittoSmallPeerInfoSetEnabled(e.deref(),t)}))}get metadata(){return JSON.parse(this.metadataJSONString)}set metadata(t){this.metadataJSONString=JSON.stringify(t)}get metadataJSONString(){return this.ditto.deferClose((t=>dittoSmallPeerInfoGetMetadata(t.deref())))}set metadataJSONString(t){if("string"!=typeof t)throw new TypeError("Expected string, got "+typeof t);this.ditto.deferClose((e=>{dittoSmallPeerInfoSetMetadata(e.deref(),t)}))}get syncScope(){return this.ditto.deferClose((t=>dittoSmallPeerInfoGetSyncScope(t.deref())))}set syncScope(t){this.ditto.deferClose((e=>dittoSmallPeerInfoSetSyncScope(e.deref(),t)))}async getSyncScope(){return this.ditto.deferClose((t=>dittoSmallPeerInfoGetSyncScope(t.deref())))}async setSyncScope(t){return this.ditto.deferClose((e=>dittoSmallPeerInfoSetSyncScope(e.deref(),t)))}constructor(t){this.ditto=t}}class Ditto{static get VERSION(){return dittoGetSDKSemver()}static get DEFAULT_ROOT_DIRECTORY(){return rnOnlyGetDefaultDirectory()}static async open(t=DittoConfig.default){if(!(t instanceof DittoConfig))throw new TypeError("Ditto.open() expects a DittoConfig, but got "+typeof t);if("object"!=typeof t.connect)throw new TypeError("Ditto.open() expects a DittoConfig with a `connect` property, but got "+typeof t.connect);if(!Ditto.isEnvironmentSupported())throw new Error("Ditto does not support this JavaScript environment. Please consult the Ditto JavaScript documentation for a list of supported environments and browsers. You can use `Ditto.isEnvironmentSupported()` to run this check anytime.");const e=mapFFIErrors((()=>dittoOpenThrows(t.toCBOR(),"PlatformDependent",Ditto.DEFAULT_ROOT_DIRECTORY)));return new Ditto(null,null,t,e)}static openSync(t=DittoConfig.default){if(!(t instanceof DittoConfig))throw new TypeError("Ditto.openSync() expects a DittoConfig, but got "+typeof t);if("object"!=typeof t.connect)throw new TypeError("Ditto.open() expects a DittoConfig with a `connect` property, but got "+typeof t.connect);if(!Ditto.isEnvironmentSupported())throw new Error("Ditto does not support this JavaScript environment. Please consult the Ditto JavaScript documentation for a list of supported environments and browsers. You can use `Ditto.isEnvironmentSupported()` to run this check anytime.");const e=mapFFIErrors((()=>dittoOpenThrows(t.toCBOR(),"PlatformDependent",Ditto.DEFAULT_ROOT_DIRECTORY)));return new Ditto(null,null,t,e)}get deviceName(){return this._deviceName}set deviceName(t){this.isSyncActive&&Logger.warning("Changes to the device name take effect when sync is restarted."),this._deviceName=t}get sdkVersion(){return this.deferClose((t=>dittoGetSDKVersion(t.deref())))}get identity(){return this.configOrParameters.isConfig&&Logger.warning("Accessing legacy `identity` property on a Ditto instance initialized with the new DittoConfig API. The mapping may not be exact."),this.configOrParameters.identity}get path(){return Logger.warning("'Ditto.path' is deprecated. Use 'Ditto.persistenceDirectory' instead."),this.persistenceDirectory}get config(){return this.configOrParameters.isParameters&&Logger.warning("Attempted to access property 'config' of a 'Ditto' instance initialized using the deprecated parameter-based APIs. Since there is no exact 1:1 mapping between the old parameters and the new 'DittoConfig', the returned configuration will be an incomplete approximation."),this.configOrParameters.config}get absolutePersistenceDirectory(){return this.deferClose((t=>dittoAbsolutePersistenceDirectory(t.deref())))}get persistenceDirectory(){return this.configOrParameters.persistenceDirectory}get isActivated(){return this.deferClose((t=>dittoIsActivated(t.deref())))}get isClosed(){var t;return null!==(t=this._isClosed)&&void 0!==t&&t}get isSyncActive(){return this.deferClose((t=>dittoIsSyncActive(t.deref())))}constructor(t,e){var i,n,r,o,s;if(this.deferCloseAllowed=!0,this._isClosed=!1,this.pendingOperations=new Set,!Ditto.isEnvironmentSupported())throw new Error("Ditto does not support this JavaScript environment. Please consult the Ditto JavaScript documentation for a list of supported environments and browsers. You can use `Ditto.isEnvironmentSupported()` to run this check anytime.");let a,c=null;if(4===arguments.length&&arguments[2]instanceof DittoConfig){if(null!=t||null!=e)throw new DittoError("internal","identity and persistenceDirectory params must be null when constructing Ditto with DittoConfig");a=new ConfigOrParameters(arguments[2]),c=arguments[3]}else{a=new ConfigOrParameters(null!=t?t:DEFAULT_IDENTITY,e)}if(this.configOrParameters=a.redactingSensitiveData(),null==c){const t=makeIdentityConfig(a.identity),e="Disabled",i="PlatformDependent";c=mapFFIErrors((()=>dittoTryNewBlocking(a.persistenceDirectory,t,e,i)))}Bridge.ditto.bridge(c,this),this._deviceName=defaultDeviceName(),dittoDisableSyncWithV3(c).catch((t=>{Logger.error(`Failed to disable sync with V3: ${null==t?void 0:t.message}`)}));let d=null,l=!1;if(this.keepAlive=new KeepAlive,a.isConfig)this.auth=new OnlineAuthenticatorV2(this.keepAlive,this);else if("onlineWithAuthentication"===(null===(i=a.identity)||void 0===i?void 0:i.type)){l=null===(r=null===(n=a.identity)||void 0===n?void 0:n.enableDittoCloudSync)||void 0===r||r,this.auth=new OnlineAuthenticator(this.keepAlive,this,a.identity.authHandler);const t=new WeakRef(this);dittoAuthSetLoginProvider(c,dittoAuthClientMakeLoginProvider((function(e){const i=t.deref();i?i.auth?i.auth["@ditto.authenticationExpiring"](e):d=e:Logger.warning("Internal inconsistency, LoginProvider callback fired after the corresponding Ditto instance has been deallocated.")})))}else"onlinePlayground"===(null===(o=a.identity)||void 0===o?void 0:o.type)?(l=null===(s=a.identity.enableDittoCloudSync)||void 0===s||s,this.auth=new OnlineAuthenticator(this.keepAlive,this,{authenticationRequired:function(t){},authenticationExpiringSoon:function(t,e){}})):this.auth=new NotAvailableAuthenticator(this.keepAlive);dittoSetCloudSyncEnabled(c,l),transportsInit(),this.appID=dittoAuthClientGetAppID(c),this.siteID=dittoAuthClientGetSiteID(c),this.sync=new Sync(this),this.store=new Store(this),this.smallPeerInfo=new SmallPeerInfo(this),this.presence=new Presence(this),this.presenceManager=new PresenceManager(this),this.liveQueryManager=new LiveQueryManager(this,this.keepAlive),this.attachmentFetcherManager=new AttachmentFetcherManager(this),this.transportConditionsManager=new TransportConditionsManager(this),this.subscriptionManager=new SubscriptionManager(this),a.isParameters&&null!=d&&this.auth["@ditto.authenticationExpiring"](d)}static disableDeadlockDetection(){}static hasDeadlockDetection(){return!1}static isEnvironmentSupported(){let t,e=!1;"undefined"!=typeof window&&window.navigator&&window.navigator.userAgent&&window.navigator.appVersion&&(e=-1!==window.navigator.userAgent.indexOf("MSIE")||window.navigator.appVersion.indexOf("Trident/")>-1);try{t=checkAPIs()}catch(t){throw new Error(`Error checking environment support: ${t}`)}return!e&&t}setOfflineOnlyLicenseToken(t){if("string"!=typeof t)throw new TypeError(`Expected parameter licenseToken to have type string, but got '${typeof t}'`);if(IdentityTypesRequiringOfflineLicenseToken.includes(this.configOrParameters.identity.type))this.deferClose((e=>{mapFFIErrors((()=>{tryVerifyLicense(e.deref(),t)}))}));else{const t=this.configOrParameters.isConfig?`The connect mode '${this.config.connect.mode}' does not require an offline license token.`:`The identity type '${this.identity.type}' does not require an offline license token.`;Logger.error(t)}}get transportConfig(){return this.deferClose((t=>{const e=dittoTransportConfig(t.deref());return transportConfigFromDeserializable(CBOR.decode(e)).freeze()}))}setTransportConfig(t){const e=transportConfigToSerializable(t.copy().freeze()),i=CBOR.encode(e);this.deferClose((t=>{dittoSetTransportConfig(t.deref(),i)}))}updateTransportConfig(t){const e=this.transportConfig.copy();return t(e),this.setTransportConfig(e),this}startSync(){this.deferClose((t=>{if(IdentityTypesRequiringOfflineLicenseToken.includes(this.configOrParameters.identity.type)&&!this.isActivated)throw new Error("Sync could not be started because Ditto has not yet been activated. This can be achieved with a successful call to `setOfflineOnlyLicenseToken`. If you need to obtain a license token then please visit https://portal.ditto.live.");this.isSyncActive||this.keepAlive.retain("sync"),this._deviceName=dittoSetDeviceName(t.deref(),this.deviceName);try{mapFFIErrors((()=>dittoTryStartSync(t.deref())))}catch(t){throw this.isSyncActive||this.keepAlive.release("sync"),t}}))}stopSync(){this.deferClose((t=>{this.isSyncActive&&this.keepAlive.release("sync"),dittoStopSync(t.deref())}))}observePeers(t){Logger.warning("`ditto.observePeers()` is deprecated, please use `ditto.presence.observe()` instead.");const e=this.presenceManager.addObserver(t);return new Observer(this.presenceManager,e,{stopsWhenFinalized:!0})}observeTransportConditions(t){const e=this.transportConditionsManager.addObserver(t);return new Observer(this.transportConditionsManager,e,{stopsWhenFinalized:!0})}async runGarbageCollection(){return this.deferCloseAsync((async t=>dittoRunGarbageCollection(t.deref())))}async disableSyncWithV3(){throw new Error("This API is not available in React Native environments.")}async close(){if(!this.isClosed){if(this._isClosed=!0,this.stopSync(),this.store.close(),this.presence.close(),this.auth.close(),this.sync.close(),await this.presenceManager.close(),this.liveQueryManager.close(),this.attachmentFetcherManager.close(),this.transportConditionsManager.close(),this.subscriptionManager.close(),this.keepAlive.isActive)throw new Error("Internal inconsistency, still kept alive after the Ditto object has been close()-ed. Active IDs: "+this.keepAlive.currentIDs().join(", "));do{await Promise.allSettled(this.pendingOperations)}while(this.pendingOperations.size>0);this.deferCloseAllowed=!1,await Bridge.ditto.close(this)}}get numPendingOperations(){return this.pendingOperations.size}deferClose(t){if(!this.deferCloseAllowed)throw new Error("Can't perform operation using a Ditto instance that has been closed.");return t(Bridge.ditto.handleFor(this))}async deferCloseAsync(t){if(!this.deferCloseAllowed)throw new Error("Can't perform operation using a Ditto instance that has been closed.");const e=t(Bridge.ditto.handleFor(this));let i;this.pendingOperations.add(e);try{i=await e}finally{this.pendingOperations.delete(e)}return i}}const checkAPIs=t=>{const e=t||globalThis||global||window;return["BigInt","WeakRef","FinalizationRegistry"].every((t=>!!e[t]))},disableDeadlockTimeoutWhenDebugging=()=>{},CUSTOM_INSPECT_SYMBOL=Symbol.for("nodejs.util.inspect.custom");class QueryResultItem{get value(){if(this.materialize(),void 0===this.materializedValue)throw new Error("Internal Error: Materialized value is undefined");return this.materializedValue}get isMaterialized(){return void 0!==this.materializedValue}materialize(){if(!this.isMaterialized){const t=this.cborData();let e;try{e=CBOR.decode(t)}catch(t){throw new Error(`Internal inconsistency: CBOR decoding error while materializing result item: ${t.message}`)}if(void 0===e)throw new Error("Internal inconsistency: Materialized value is undefined");this.materializedValue=e}}dematerialize(){this.materializedValue=void 0}cborData(){return queryResultItemCBOR(this.deref())}jsonString(){return queryResultItemJSON(this.deref())}[CUSTOM_INSPECT_SYMBOL](t,e,i){return customInspectRepresentation(this,i)}constructor(){}static fromJSON(t){const e=(new TextEncoder).encode(t);return Bridge.queryResultItem.bridge(queryResultItemNew(e))}deref(){return Bridge.queryResultItem.handleFor(this).deref()}}class ConnectionRequest{get peerKeyString(){return connectionRequestPeerKeyString(this.deref())}get peerMetadata(){return JSON.parse(this.peerMetadataJSONString)}get peerMetadataJSONString(){return connectionRequestPeerMetadataJSON(this.deref())}get identityServiceMetadata(){return JSON.parse(this.identityServiceMetadataJSONString)}get identityServiceMetadataJSONString(){return connectionRequestIdentityServiceMetadataJSON(this.deref())}get connectionType(){return connectionRequestConnectionType(this.deref())}toString(){return`ConnectionRequest(${this.peerKeyString} via ${this.connectionType})`}[Symbol.for("nodejs.util.inspect.custom")](t,e,i){return this.toString()}deref(){return Bridge.connectionRequest.handleFor(this).deref()}}Bridge.attachment.registerType(Attachment),Bridge.connectionRequest.registerType(ConnectionRequest),Bridge.document.registerType(Document),Bridge.queryResultItem.registerType(QueryResultItem),Bridge.differ.registerType(Differ),Bridge.transaction.registerType(Transaction),Bridge.queryResult.registerType(QueryResult),Bridge.mutableDocument.registerType(MutableDocument),Bridge.ditto.registerType(Ditto);export{Attachment,AttachmentFetcher,AttachmentToken,Authenticator,ConfigOrParameters,ConnectionRequest,DEFAULT_IDENTITY,Diff,Differ,Ditto,DittoConfig,DittoError,DocumentID,ERROR_CODES,IdentityTypesRequiringOfflineLicenseToken,Logger,NotAvailableAuthenticator,Observer,OnlineAuthenticator,OnlineAuthenticatorV2,Presence,QueryResult,QueryResultItem,SmallPeerInfo,Store,StoreObserver,Sync,SyncSubscription,Transaction,TransactionInfo,TransportConfig,addressToString,checkAPIs,disableDeadlockTimeoutWhenDebugging,getMissingAndroidPermissions,init,makeIdentityConfig,mapFFIErrors,mapFFIErrorsAsync,transportConfigFromDeserializable,transportConfigToSerializable,validateAttachmentMetadata,validateDocumentIDCBOR,validateDocumentIDValue};
1
+ import{NativeModules,Platform}from"react-native";const REGISTRY_SWEEP_INTERVAL=1e4;class WeakRefBasedFinalizationRegistry{[Symbol.toStringTag]="FinalizationRegistry";counter=0;registrations=new Map;constructor(t){this.finalize=t}register(t,e,i){this.registrations.set(this.counter,{targetRef:new WeakRef(t),tokenRef:i?new WeakRef(i):void 0,value:e}),this.counter++,this.scheduleSweep()}unregister(t){if(!t)return!1;let e=!1;return this.registrations.forEach(((i,n)=>{i.tokenRef?.deref()===t&&(this.registrations.delete(n),e=!0)})),e}sweep=()=>{clearTimeout(this.sweepTimeout),this.sweepTimeout=void 0,this.registrations.forEach(((t,e)=>{if(void 0!==t.targetRef.deref())return;const i=t.value;this.registrations.delete(e),this.finalize(i)})),this.registrations.size>0&&this.scheduleSweep()};scheduleSweep(){this.sweepTimeout||(this.sweepTimeout=setTimeout(this.sweep,1e4))}}class WeakRefMock{[Symbol.toStringTag]="WeakRef";constructor(t){this.target=t}deref(){return this.target}static get[Symbol.toStringTag](){return"WeakRef"}}!function(t){function x(){}function y(){}var e=String.fromCharCode,i={}.toString,n=i.call(t.SharedArrayBuffer),r=i(),o=t.Uint8Array,s=o||Array,a=o?ArrayBuffer:s,c=a.isView||function(t){return t&&"length"in t},d=i.call(a.prototype);a=y.prototype;var l=t.TextEncoder,u=t.TextDecoder,f=new(o?Uint16Array:s)(32);x.prototype.decode=function(t){if(!c(t)){var a=i.call(t);if(a!==d&&a!==n&&a!==r)throw TypeError("Failed to execute 'decode' on 'TextDecoder': The provided value is not of type '(ArrayBuffer or ArrayBufferView)'");t=o?new s(t):t||[]}for(var l,u,h,_=a="",g=0,p=0|t.length,m=p-32|0,b=0,w=0,v=0,I=-1;g<p;){for(l=g<=m?32:p-g|0;v<l;g=g+1|0,v=v+1|0){switch((u=255&t[g])>>4){case 15:if(2!=(h=255&t[g=g+1|0])>>6||247<u){g=g-1|0;break}b=(7&u)<<6|63&h,w=5,u=256;case 14:b<<=6,b|=(15&u)<<6|63&(h=255&t[g=g+1|0]),w=2==h>>6?w+4|0:24,u=u+256&768;case 13:case 12:b<<=6,b|=(31&u)<<6|63&(h=255&t[g=g+1|0]),w=w+7|0,g<p&&2==h>>6&&b>>w&&1114112>b?(u=b,0<=(b=b-65536|0)&&(I=55296+(b>>10)|0,u=56320+(1023&b)|0,31>v?(f[v]=I,v=v+1|0,I=-1):(h=I,I=u,u=h))):(g=g-(u>>=8)-1|0,u=65533),b=w=0,l=g<=m?32:p-g|0;default:f[v]=u;continue;case 11:case 10:case 9:case 8:}f[v]=65533}if(_+=e(f[0],f[1],f[2],f[3],f[4],f[5],f[6],f[7],f[8],f[9],f[10],f[11],f[12],f[13],f[14],f[15],f[16],f[17],f[18],f[19],f[20],f[21],f[22],f[23],f[24],f[25],f[26],f[27],f[28],f[29],f[30],f[31]),32>v&&(_=_.slice(0,v-32|0)),g<p){if(f[0]=I,v=~I>>>31,I=-1,_.length<a.length)continue}else-1!==I&&(_+=e(I));a+=_,_=""}return a},a.encode=function(t){var e,i=0|(t=void 0===t?"":""+t).length,n=new s(8+(i<<1)|0),r=0,a=!o;for(e=0;e<i;e=e+1|0,r=r+1|0){var c=0|t.charCodeAt(e);if(127>=c)n[r]=c;else{if(2047>=c)n[r]=192|c>>6;else{t:{if(55296<=c)if(56319>=c){var d=0|t.charCodeAt(e=e+1|0);if(56320<=d&&57343>=d){if(65535<(c=(c<<10)+d-56613888|0)){n[r]=240|c>>18,n[r=r+1|0]=128|c>>12&63,n[r=r+1|0]=128|c>>6&63,n[r=r+1|0]=128|63&c;continue}break t}c=65533}else 57343>=c&&(c=65533);!a&&e<<1<r&&e<<1<(r-7|0)&&(a=!0,(d=new s(3*i)).set(n),n=d)}n[r]=224|c>>12,n[r=r+1|0]=128|c>>6&63}n[r=r+1|0]=128|63&c}}return o?n.subarray(0,r):n.slice(0,r)},l||(t.TextEncoder=y),u||(t.TextDecoder=x)}(""+void 0==typeof global?""+void 0==typeof self?void 0:self:global);const dittoCore=global,isLoaded="function"==typeof dittoCore.ditto_sdk_transports_init;if(!isLoaded){const t=NativeModules.DittoRNSDK?.install();if(!t)throw new Error("JSI bindings were not installed for: DittoRNSDK Module");if("android"===Platform.OS){if(!dittoCore.ditto_sdk_transports_set_android_context())throw new Error("Couldn't set Android context early. This is required for proper initialization.")}Platform.constants.reactNativeVersion.minor<=75&&setInterval((()=>{dittoCore.ditto_tick()}),50),"undefined"==typeof WeakRef&&(global.WeakRef=WeakRefMock),void 0===global.FinalizationRegistry&&(global.FinalizationRegistry=WeakRefBasedFinalizationRegistry);const e=Platform.select({ios:"iOS",android:"Android",macos:"macOS",default:"Unknown"});dittoCore.ditto_init_sdk_version(e,"JavaScript","4.13.1")}function ditto_sdk_transports_init(t){return dittoCore.ditto_sdk_transports_init(t)}function getMissingAndroidPermissions(){return"android"!==Platform.OS?[]:dittoCore.ditto_sdk_transports_android_missing_permissions()}function getPlatform(){return Platform.OS}function boxCBytesIntoBuffer(t){const e=dittoCore.sliceBoxedToUInt8Array(t);return e?new Uint8Array(e):null}function refCBytesIntoBuffer(t){const e=dittoCore.sliceRefToUInt8Array(t);return e?new Uint8Array(e):null}function dittoffi_differ_diff(...t){return boxCBytesIntoBuffer(dittoCore.dittoffi_differ_diff(...t))}function ditto_identity_config_make_online_playground(...t){return dittoCore.ditto_identity_config_make_online_playground(...t)}function ditto_identity_config_make_offline_playground(...t){return dittoCore.ditto_identity_config_make_offline_playground(...t)}function ditto_identity_config_make_shared_key(...t){return dittoCore.ditto_identity_config_make_shared_key(...t)}function ditto_identity_config_make_online_with_authentication(...t){return dittoCore.ditto_identity_config_make_online_with_authentication(...t)}function dittoffi_ditto_try_new_blocking(...t){return dittoCore.dittoffi_ditto_try_new_blocking(...t)}function dittoffi_DEFAULT_DATABASE_ID(...t){return dittoCore.dittoffi_DEFAULT_DATABASE_ID(...t)}function dittoffi_DITTO_DEVELOPMENT_PROVIDER(...t){return dittoCore.dittoffi_DITTO_DEVELOPMENT_PROVIDER(...t)}function dittoffi_ditto_config_default(...t){return dittoCore.dittoffi_ditto_config_default(...t)}function dittoffi_ditto_open_throws(...t){return dittoCore.dittoffi_ditto_open_throws(...t)}function ditto_shutdown(...t){return dittoCore.ditto_shutdown(...t)}function ditto_free(...t){return dittoCore.ditto_free(...t)}function dittoffi_ditto_is_activated(...t){return dittoCore.dittoffi_ditto_is_activated(...t)}function dittoffi_ditto_is_sync_active(...t){return dittoCore.dittoffi_ditto_is_sync_active(...t)}function dittoffi_ditto_try_start_sync(...t){return dittoCore.dittoffi_ditto_try_start_sync(...t)}function dittoffi_ditto_stop_sync(...t){return dittoCore.dittoffi_ditto_stop_sync(...t)}function dittoffi_ditto_try_set_transport_config(...t){return dittoCore.dittoffi_ditto_try_set_transport_config(...t)}function dittoffi_ditto_transport_config(...t){return dittoCore.dittoffi_ditto_transport_config(...t)}function dittoffi_ditto_set_cloud_sync_enabled(...t){return dittoCore.dittoffi_ditto_set_cloud_sync_enabled(...t)}function refCStringToString(...t){return dittoCore.refCStringToString(...t)}function boxCStringIntoString(...t){return dittoCore.boxCStringIntoString(...t)}function withOutBoxCBytes(...t){return dittoCore.withOutBoxCBytes(...t)}function ditto_auth_client_get_app_id(...t){return dittoCore.ditto_auth_client_get_app_id(...t)}function ditto_auth_client_is_web_valid(...t){return dittoCore.ditto_auth_client_is_web_valid(...t)}function ditto_auth_client_get_site_id(...t){return dittoCore.ditto_auth_client_get_site_id(...t)}function ditto_auth_client_make_login_provider(...t){return dittoCore.ditto_auth_client_make_login_provider(...t)}function ditto_auth_set_login_provider(...t){return dittoCore.ditto_auth_set_login_provider(...t)}function ditto_auth_client_login_with_token(...t){return dittoCore.ditto_auth_client_login_with_token(...t)}function ditto_auth_client_login_with_token_and_feedback(...t){return dittoCore.ditto_auth_client_login_with_token_and_feedback(...t)}function ditto_auth_client_login_with_credentials(...t){return dittoCore.ditto_auth_client_login_with_credentials(...t)}function ditto_auth_client_logout(...t){return dittoCore.ditto_auth_client_logout(...t)}function ditto_auth_client_user_id(...t){return dittoCore.ditto_auth_client_user_id(...t)}function dittoffi_ditto_set_authentication_status_handler(...t){return dittoCore.dittoffi_ditto_set_authentication_status_handler(...t)}function dittoffi_authentication_status_is_authenticated(...t){return dittoCore.dittoffi_authentication_status_is_authenticated(...t)}function dittoffi_authentication_status_user_id(...t){return dittoCore.dittoffi_authentication_status_user_id(...t)}function dittoffi_authentication_status_free(...t){return dittoCore.dittoffi_authentication_status_free(...t)}function dittoffi_try_experimental_register_change_observer_str_detached(...t){return dittoCore.dittoffi_try_experimental_register_change_observer_str_detached(...t)}function dittoffi_try_add_sync_subscription(...t){return dittoCore.dittoffi_try_add_sync_subscription(...t)}function dittoffi_try_remove_sync_subscription(...t){return dittoCore.dittoffi_try_remove_sync_subscription(...t)}function dittoffi_try_exec_statement(...t){return dittoCore.dittoffi_try_exec_statement(...t)}function dittoffi_query_result_item_count(...t){return dittoCore.dittoffi_query_result_item_count(...t)}function dittoffi_query_result_item_at(...t){return dittoCore.dittoffi_query_result_item_at(...t)}function dittoffi_query_result_item_new(...t){return dittoCore.dittoffi_query_result_item_new(...t)}function dittoffi_query_result_has_commit_id(...t){return dittoCore.dittoffi_query_result_has_commit_id(...t)}function dittoffi_query_result_commit_id(...t){return dittoCore.dittoffi_query_result_commit_id(...t)}function dittoffi_query_result_mutated_document_id_count(...t){return dittoCore.dittoffi_query_result_mutated_document_id_count(...t)}function dittoffi_query_result_mutated_document_id_at(...t){return dittoCore.dittoffi_query_result_mutated_document_id_at(...t)}function dittoffi_query_result_item_cbor(...t){return dittoCore.dittoffi_query_result_item_cbor(...t)}function dittoffi_query_result_item_json(...t){return dittoCore.dittoffi_query_result_item_json(...t)}function ditto_document_id_query_compatible(...t){return dittoCore.ditto_document_id_query_compatible(...t)}function ditto_document_id(...t){return dittoCore.ditto_document_id(...t)}function ditto_document_free(...t){return dittoCore.ditto_document_free(...t)}function ditto_validate_document_id(...t){return dittoCore.ditto_validate_document_id(...t)}function ditto_presence_v3(...t){return dittoCore.ditto_presence_v3(...t)}function ditto_register_presence_v3_callback(...t){return dittoCore.ditto_register_presence_v3_callback(...t)}function ditto_clear_presence_v3_callback(...t){return dittoCore.ditto_clear_presence_v3_callback(...t)}function dittoffi_presence_peer_metadata_json(...t){return dittoCore.dittoffi_presence_peer_metadata_json(...t)}function dittoffi_presence_try_set_peer_metadata_json(...t){return dittoCore.dittoffi_presence_try_set_peer_metadata_json(...t)}function dittoffi_presence_set_connection_request_handler(...t){return dittoCore.dittoffi_presence_set_connection_request_handler(...t)}function ditto_new_attachment_from_file(...t){return dittoCore.ditto_new_attachment_from_file(...t)}function ditto_new_attachment_from_bytes(...t){return dittoCore.ditto_new_attachment_from_bytes(...t)}function ditto_resolve_attachment(...t){return dittoCore.ditto_resolve_attachment(...t)}function ditto_cancel_resolve_attachment(...t){return dittoCore.ditto_cancel_resolve_attachment(...t)}function ditto_free_attachment_handle(...t){return dittoCore.ditto_free_attachment_handle(...t)}function ditto_get_complete_attachment_path(...t){return dittoCore.ditto_get_complete_attachment_path(...t)}function ditto_live_query_start(...t){return dittoCore.ditto_live_query_start(...t)}function ditto_live_query_stop(...t){return dittoCore.ditto_live_query_stop(...t)}function ditto_live_query_signal_available_next(...t){return dittoCore.ditto_live_query_signal_available_next(...t)}function ditto_log(...t){return dittoCore.ditto_log(...t)}function ditto_logger_init(...t){return dittoCore.ditto_logger_init(...t)}function ditto_logger_set_log_file(...t){return dittoCore.ditto_logger_set_log_file(...t)}function ditto_logger_minimum_log_level_get(...t){return dittoCore.ditto_logger_minimum_log_level_get(...t)}function ditto_logger_minimum_log_level(...t){return dittoCore.ditto_logger_minimum_log_level(...t)}function ditto_logger_emoji_headings_enabled_get(...t){return dittoCore.ditto_logger_emoji_headings_enabled_get(...t)}function ditto_logger_emoji_headings_enabled(...t){return dittoCore.ditto_logger_emoji_headings_enabled(...t)}function ditto_logger_enabled_get(...t){return dittoCore.ditto_logger_enabled_get(...t)}function ditto_logger_enabled(...t){return dittoCore.ditto_logger_enabled(...t)}function ditto_small_peer_info_get_is_enabled(...t){return dittoCore.ditto_small_peer_info_get_is_enabled(...t)}function ditto_small_peer_info_set_enabled(...t){return dittoCore.ditto_small_peer_info_set_enabled(...t)}function ditto_small_peer_info_get_sync_scope(...t){return dittoCore.ditto_small_peer_info_get_sync_scope(...t)}function ditto_small_peer_info_set_sync_scope(...t){return dittoCore.ditto_small_peer_info_set_sync_scope(...t)}function ditto_small_peer_info_get_metadata(...t){return dittoCore.ditto_small_peer_info_get_metadata(...t)}function ditto_small_peer_info_set_metadata(...t){return dittoCore.ditto_small_peer_info_set_metadata(...t)}function ditto_sdk_transports_error_new(...t){return dittoCore.ditto_sdk_transports_error_new(...t)}function ditto_sdk_transports_error_value(...t){return dittoCore.ditto_sdk_transports_error_value(...t)}function ditto_sdk_transports_error_free(...t){return dittoCore.ditto_sdk_transports_error_free(...t)}function dittoffi_connection_request_peer_key_string(...t){return dittoCore.dittoffi_connection_request_peer_key_string(...t)}function dittoffi_connection_request_peer_metadata_json(...t){return dittoCore.dittoffi_connection_request_peer_metadata_json(...t)}function dittoffi_connection_request_authorize(...t){return dittoCore.dittoffi_connection_request_authorize(...t)}function dittoffi_connection_request_free(...t){return dittoCore.dittoffi_connection_request_free(...t)}function dittoffi_connection_request_connection_type(...t){return dittoCore.dittoffi_connection_request_connection_type(...t)}function ditto_set_device_name(...t){return dittoCore.ditto_set_device_name(...t)}function ditto_get_sdk_version(...t){return dittoCore.ditto_get_sdk_version(...t)}function dittoffi_get_sdk_semver(...t){return dittoCore.dittoffi_get_sdk_semver(...t)}function ditto_error_message(...t){return dittoCore.ditto_error_message(...t)}function dittoffi_error_code(...t){return dittoCore.dittoffi_error_code(...t)}function dittoffi_error_description(...t){return dittoCore.dittoffi_error_description(...t)}function dittoffi_error_free(...t){return dittoCore.dittoffi_error_free(...t)}function dittoffi_try_verify_license(...t){return dittoCore.dittoffi_try_verify_license(...t)}function ditto_run_garbage_collection(...t){return dittoCore.ditto_run_garbage_collection(...t)}function ditto_disable_sync_with_v3(...t){return dittoCore.ditto_disable_sync_with_v3(...t)}function dittoffi_base64_encode(...t){return dittoCore.dittoffi_base64_encode(...t)}function dittoffi_try_base64_decode(...t){return dittoCore.dittoffi_try_base64_decode(...t)}function dittoffi_crypto_generate_secure_random_token(...t){return dittoCore.dittoffi_crypto_generate_secure_random_token(...t)}function readFile(...t){return dittoCore.readFile(...t)}function copyFile(...t){return dittoCore.copyFile(...t)}function getDefaultDirectory(){return dittoCore.defaultDirectory}function defaultDeviceName$1(...t){return dittoCore.defaultDeviceName(...t)}function dittoffi_ditto_absolute_persistence_directory(...t){return dittoCore.dittoffi_ditto_absolute_persistence_directory(...t)}function dittoffi_logger_try_export_to_file_async(...t){return dittoCore.dittoffi_logger_try_export_to_file_async(...t)}function ditto_logger_set_custom_log_cb(...t){return dittoCore.ditto_logger_set_custom_log_cb(...t)}function dittoffi_query_result_free(...t){return dittoCore.dittoffi_query_result_free(...t)}function dittoffi_query_result_item_free(...t){return dittoCore.dittoffi_query_result_item_free(...t)}function ditto_register_presence_v1_callback(...t){return dittoCore.ditto_register_presence_v1_callback(...t)}function ditto_clear_presence_callback(...t){return dittoCore.ditto_clear_presence_callback(...t)}function ditto_presence_v1(...t){return dittoCore.ditto_presence_v1(...t)}function dittoffi_differ_new(...t){return dittoCore.dittoffi_differ_new(...t)}function dittoffi_differ_free(...t){return dittoCore.dittoffi_differ_free(...t)}function dittoffi_store_transactions(...t){return dittoCore.dittoffi_store_transactions(...t)}function dittoffi_store_begin_transaction_async_throws(...t){return dittoCore.dittoffi_store_begin_transaction_async_throws(...t)}function dittoffi_transaction_complete_async_throws(...t){return dittoCore.dittoffi_transaction_complete_async_throws(...t)}function dittoffi_transaction_execute_async_throws(...t){return dittoCore.dittoffi_transaction_execute_async_throws(...t)}function dittoffi_transaction_info(...t){return dittoCore.dittoffi_transaction_info(...t)}function dittoffi_transaction_free(...t){return dittoCore.dittoffi_transaction_free(...t)}function ditto_register_transport_condition_changed_callback(...t){return dittoCore.ditto_register_transport_condition_changed_callback(...t)}function ditto_add_subscription(){throw new Error("ditto_add_subscription is not implemented in React Native.")}function ditto_remove_subscription(){throw new Error("ditto_remove_subscription is not implemented in React Native.")}function dittoffi_connection_request_identity_service_metadata_json(){throw new Error("Not implemented in React Native.")}const PREFIX_REGEX=new RegExp(/^<.*?>\s*/);class DittoFFIError extends Error{constructor(t,e,i){const n=ffiErrorMessage();super(e||n||i),this.code=t}}function throwOnErrorResult(t,e){if(null!==t){let i,n;try{i=dittoffi_error_code(t),n=boxCStringIntoString(dittoffi_error_description(t)),dittoffi_error_free(t)}catch(t){throw new DittoFFIError(-1,`Failed to retrieve Ditto core error message: ${t.message}`)}throw n=null==n?`${e}() failed with error code: ${i}`:n.replace(PREFIX_REGEX,""),new DittoFFIError(i,n)}}function ffiErrorMessage(){return boxCStringIntoString(ditto_error_message())}const DittoCRDTTypeKey="_ditto_internal_type_jkb12973t4b",DittoCRDTValueKey="_value";var DittoCRDTType;function DITTO_DEVELOPMENT_PROVIDER(){ensureInitialized();return refCStringToString(dittoffi_DITTO_DEVELOPMENT_PROVIDER())}function DEFAULT_DATABASE_ID(){ensureInitialized();return refCStringToString(dittoffi_DEFAULT_DATABASE_ID())}function differNew(){return ensureInitialized(),dittoffi_differ_new()}function differDiff(t,e){return ensureInitialized(),dittoffi_differ_diff(t,e)}function differFree(t){ensureInitialized(),dittoffi_differ_free(t)}function dittoPointerToStorePointer(t){return{addr:t.addr,type:"dittoffi_store_t const *"}}function documentID(t){ensureInitialized();return boxCBytesIntoBuffer(ditto_document_id(t))}function documentFree(t){ensureInitialized(),ditto_document_free(t)}function documentIDQueryCompatible(t,e){ensureInitialized();return boxCStringIntoString(ditto_document_id_query_compatible(t,e))}function validateDocumentID(t){ensureInitialized();return boxCBytesIntoBuffer(withOutBoxCBytes((e=>{const i=ditto_validate_document_id(t,e);if(0!==i)throw new Error(errorMessage()||`ditto_validate_document_id() failed with error code: ${i}`);return e})))}async function tryExecStatement(t,e,i){ensureInitialized();const n=bytesFromString(e),r=await dittoffi_try_exec_statement(t,n,i);return throwOnErrorResult(r.error,"dittoffi_try_exec_statement"),r.success}function addSubscription(t,e,i,n,r,o,s){ensureInitialized(),bytesFromString(e),bytesFromString(i);const a=ditto_add_subscription();if(0!==a)throw new Error(errorMessage()||`ditto_add_subscription() failed with error code: ${a}`)}function removeSubscription(t,e,i,n,r,o,s){ensureInitialized(),bytesFromString(e),bytesFromString(i);const a=ditto_remove_subscription();if(0!==a)throw new Error(errorMessage()||`ditto_remove_subscription() failed with error code: ${a}`)}function tryAddSyncSubscription(t,e,i){ensureInitialized();throwOnErrorResult(dittoffi_try_add_sync_subscription(t,bytesFromString(e),i).error,"dittoffi_try_add_sync_subscription")}function tryRemoveSyncSubscription(t,e,i){ensureInitialized();throwOnErrorResult(dittoffi_try_remove_sync_subscription(t,bytesFromString(e),i).error,"dittoffi_try_remove_sync_subscription")}function queryResultFree(t){ensureInitialized(),dittoffi_query_result_free(t)}function queryResultItemFree(t){ensureInitialized(),dittoffi_query_result_item_free(t)}function queryResultItems(t){ensureInitialized();const e=[],i=dittoffi_query_result_item_count(t);for(let n=0;n<i;n++)e.push(dittoffi_query_result_item_at(t,n));return e}function queryResultMutatedDocumentIDs(t){ensureInitialized();const e=[],i=dittoffi_query_result_mutated_document_id_count(t);for(let n=0;n<i;n++){const i=dittoffi_query_result_mutated_document_id_at(t,n);e.push(boxCBytesIntoBuffer(i))}return e}function queryResultHasCommitID(t){return ensureInitialized(),dittoffi_query_result_has_commit_id(t)}function queryResultCommitID(t){ensureInitialized();const e=dittoffi_query_result_commit_id(t);return BigInt(e)}function queryResultItemCBOR(t){ensureInitialized();return boxCBytesIntoBuffer(dittoffi_query_result_item_cbor(t))}function queryResultItemJSON(t){ensureInitialized();return boxCStringIntoString(dittoffi_query_result_item_json(t))}function queryResultItemNew(t){ensureInitialized();const e=dittoffi_query_result_item_new(t);return throwOnErrorResult(e.error,"dittoffi_query_result_item_new"),e.success}function tryExperimentalRegisterChangeObserver(t,e,i,n){ensureInitialized();const r=wrapBackgroundCbForFFI((t=>log("Error",`The registered store observer callback failed with ${t}`)),n),o=dittoffi_try_experimental_register_change_observer_str_detached(t,bytesFromString(e),i,r);return throwOnErrorResult(o.error,"dittoffi_try_experimental_register_change_observer_str_detached"),o.success}async function liveQueryStart(t,e){ensureInitialized();const i=await ditto_live_query_start(t,e);if(0!==i)throw new Error(errorMessage()||`\`ditto_live_query_start()\` failed with error code: ${i}`)}function liveQueryStop(t,e){ensureInitialized(),ditto_live_query_stop(t,e)}async function liveQuerySignalAvailableNext(t,e){ensureInitialized(),await ditto_live_query_signal_available_next(t,e)}function loggerInit(){ensureInitialized(),ditto_logger_init()}async function loggerSetCustomLogCb(t){if(ensureInitialized(),null===t)await ditto_logger_set_custom_log_cb(null);else{const e=wrapBackgroundCbForFFI(null,((e,i)=>{try{const n=boxCStringIntoString(i);t(e,n)}catch(t){log("Error",`The registered cb in \`ditto_logger_set_custom_log_cb()\` failed with: ${t}`)}}));await ditto_logger_set_custom_log_cb(e)}}function loggerEnabled(t){ensureInitialized(),ditto_logger_enabled(!!t)}function loggerEnabledGet(){return ensureInitialized(),!!ditto_logger_enabled_get()}function loggerEmojiHeadingsEnabled(t){ensureInitialized(),ditto_logger_emoji_headings_enabled(t)}function loggerEmojiHeadingsEnabledGet(){return ensureInitialized(),ditto_logger_emoji_headings_enabled_get()}function loggerMinimumLogLevel(t){ensureInitialized(),ditto_logger_minimum_log_level(t)}function loggerMinimumLogLevelGet(){return ensureInitialized(),ditto_logger_minimum_log_level_get()}function loggerSetLogFile(t){ensureInitialized();if(0!==ditto_logger_set_log_file(t?bytesFromString(t):null)){const t=errorMessage();throw new Error(`Can't set log file, due to error: ${t}`)}}async function loggerTryExportToFile(t){ensureInitialized();const e=bytesFromString(t),i=await new Promise(((t,i)=>{const n=wrapBackgroundCbForFFI(i,t);dittoffi_logger_try_export_to_file_async(e,n)}));return throwOnErrorResult(i.error,"dittoffi_logger_try_export_to_file_async"),i.success}function log(t,e){ensureInitialized();ditto_log(t,bytesFromString(e))}function dittoIdentityConfigMakeOnlinePlayground(t,e,i){ensureInitialized();const n=bytesFromString(t),r=bytesFromString(e),o=bytesFromString(i),{status_code:s,identity_config:a}=ditto_identity_config_make_online_playground(n,r,o);if(0!==s)throw new Error(errorMessage()||`ditto_identity_config_make_online_playground() failed with error code: ${s}`);return a}function dittoIdentityConfigMakeOnlineWithAuthentication(t,e){ensureInitialized();const i=bytesFromString(t),n=bytesFromString(e),{status_code:r,identity_config:o}=ditto_identity_config_make_online_with_authentication(i,n);if(0!==r)throw new Error(errorMessage()||`ditto_identity_config_make_online_with_authentication() failed with error code: ${r}`);return o}function dittoIdentityConfigMakeOfflinePlayground(t,e){ensureInitialized();const i=bytesFromString(t),n=Number(e),{status_code:r,identity_config:o}=ditto_identity_config_make_offline_playground(i,n);if(0!==r)throw new Error(errorMessage()||`ditto_identity_config_make_offline_playground() failed with error code: ${r}`);return o}function dittoIdentityConfigMakeSharedKey(t,e,i){ensureInitialized();const n=bytesFromString(t),r=bytesFromString(e),o=Number(i),{status_code:s,identity_config:a}=ditto_identity_config_make_shared_key(n,r,o);if(0!==s)throw new Error(errorMessage()||`ditto_identity_config_make_shared_key() failed with error code: ${s}`);return a}function dittoAuthClientGetSiteID(t){return ensureInitialized(),ditto_auth_client_get_site_id(t)}function dittoAuthClientGetAppID(t){ensureInitialized();return boxCStringIntoString(ditto_auth_client_get_app_id(t))}function dittoAuthClientUserID(t){ensureInitialized();return boxCStringIntoString(ditto_auth_client_user_id(t))}function dittoAuthClientIsWebValid(t){return ensureInitialized(),0!==ditto_auth_client_is_web_valid(t)}async function dittoAuthClientLoginWithTokenAndFeedback(t,e,i){ensureInitialized();const n=bytesFromString(e),r=bytesFromString(i),o=await ditto_auth_client_login_with_token_and_feedback(t,n,r);return{error:0===o.status_code?null:new DittoFFIError(o.status_code,void 0,"Ditto failed to authenticate."),clientInfo:o.c_string?boxCStringIntoString(o.c_string):null}}async function dittoAuthClientLoginWithToken(t,e,i){ensureInitialized();const n=bytesFromString(e),r=bytesFromString(i),o=await ditto_auth_client_login_with_token(t,n,r);if(0!==o)throw new Error(errorMessage()||`Ditto failed to authenticate (error code: ${o}).`)}async function dittoAuthClientLoginWithUsernameAndPassword(t,e,i,n){ensureInitialized();const r=bytesFromString(e),o=bytesFromString(i),s=bytesFromString(n),a=await ditto_auth_client_login_with_credentials(t,r,o,s);if(0!==a)throw new Error(errorMessage()||`Ditto failed to authenticate (error code: ${a}).`)}async function dittoAuthClientLogout(t){ensureInitialized();const e=await ditto_auth_client_logout(t);if(0!==e)throw new Error(errorMessage()||`Ditto failed to logout (error code: ${e}).`)}function dittoSetAuthenticationStatusHandler(t,e,i){ensureInitialized(),dittoffi_ditto_set_authentication_status_handler(t,wrapBackgroundCbForFFI(i,e))}function authenticationStatusUserID(t){return ensureInitialized(),boxCStringIntoString(dittoffi_authentication_status_user_id(t))}function authenticationStatusIsAuthenticated(t){return ensureInitialized(),dittoffi_authentication_status_is_authenticated(t)}function authenticationStatusFree(t){ensureInitialized(),dittoffi_authentication_status_free(t)}function storeTransactions(t){ensureInitialized();return boxCBytesIntoBuffer(dittoffi_store_transactions(t))}async function storeBeginTransaction(t,e){ensureInitialized();const i={is_read_only:e.isReadOnly,hint:bytesFromString(e.hint)};return new Promise(((e,n)=>{const r=wrapBackgroundCbForFFI(n,(t=>{throwOnErrorResult(t.error,"dittoffi_store_begin_transaction_async_throws"),e(t.success)}));dittoffi_store_begin_transaction_async_throws(t,i,r)}))}async function transactionCompleteAsync(t,e){return ensureInitialized(),new Promise(((i,n)=>{const r=wrapBackgroundCbForFFI(n,(t=>{throwOnErrorResult(t.error,"dittoffi_transaction_complete_async_throws");const e=t.success;i(e)}));dittoffi_transaction_complete_async_throws(t,e,r)}))}async function transactionExecuteAsync(t,e,i){return ensureInitialized(),new Promise(((n,r)=>{const o=wrapBackgroundCbForFFI(r,(t=>{throwOnErrorResult(t.error,"dittoffi_transaction_execute_async_throws"),n(t.success)})),s=bytesFromString(e);dittoffi_transaction_execute_async_throws(t,s,i,o)}))}function transactionInfo(t){ensureInitialized();return boxCBytesIntoBuffer(dittoffi_transaction_info(t))}function transactionFree(t){ensureInitialized(),dittoffi_transaction_free(t)}function dittoConfigDefault(){ensureInitialized();return boxCBytesIntoBuffer(dittoffi_ditto_config_default())}function dittoAbsolutePersistenceDirectory(t){ensureInitialized();return boxCStringIntoString(dittoffi_ditto_absolute_persistence_directory(t))}function dittoOpenThrows(t,e,i){ensureInitialized();const n=dittoffi_ditto_open_throws(t,e,bytesFromString(i));return throwOnErrorResult(n.error,"dittoffi_ditto_open_throws"),n.success}function dittoTryNewBlocking(t,e,i,n){ensureInitialized();const r=dittoffi_ditto_try_new_blocking(bytesFromString(t),e,i,bytesFromString(null),n);return throwOnErrorResult(r.error,"dittoffi_ditto_try_new_blocking"),r.success}function dittoFree(t){return ensureInitialized(),ditto_free(t)}function cryptoGenerateSecureRandomToken(){ensureInitialized();return boxCStringIntoString(dittoffi_crypto_generate_secure_random_token())}function dittoRegisterPresenceV1Callback(t,e){ensureInitialized(),ditto_register_presence_v1_callback(t,wrapBackgroundCbForFFI((t=>log("Error",`The registered presence callback v1 errored with ${t}`)),(t=>{const i=refCStringToString(t);e(i)})))}async function dittoClearPresenceCallback(t){return ensureInitialized(),ditto_clear_presence_callback(t)}function dittoRegisterPresenceV3Callback(t,e){ensureInitialized(),ditto_register_presence_v3_callback(t,wrapBackgroundCbForFFI((t=>log("Error",`The registered presence callback v3 errored with ${t}`)),(t=>{const i=refCStringToString(t);e(i)})))}async function dittoClearPresenceV3Callback(t){return ensureInitialized(),ditto_clear_presence_v3_callback(t)}function presencePeerMetadataJSON(t){ensureInitialized();const e=boxCBytesIntoBuffer(dittoffi_presence_peer_metadata_json(t));return(new TextDecoder).decode(e)}async function presenceTrySetPeerMetadataJSON(t,e){ensureInitialized();const i=bytesFromString(e);throwOnErrorResult((await dittoffi_presence_try_set_peer_metadata_json(t,i)).error,"dittoffi_presence_try_set_peer_metadata_json")}function connectionRequestPeerKeyString(t){ensureInitialized();return boxCStringIntoString(dittoffi_connection_request_peer_key_string(t))}function connectionRequestPeerMetadataJSON(t){ensureInitialized();const e=refCBytesIntoBuffer(dittoffi_connection_request_peer_metadata_json(t));return(new TextDecoder).decode(e)}function connectionRequestIdentityServiceMetadataJSON(t){ensureInitialized();const e=refCBytesIntoBuffer(dittoffi_connection_request_identity_service_metadata_json());return(new TextDecoder).decode(e)}function connectionRequestConnectionType(t){return ensureInitialized(),dittoffi_connection_request_connection_type(t)}function connectionRequestAuthorize(t,e){ensureInitialized(),dittoffi_connection_request_authorize(t,e)}function connectionRequestFree(t){ensureInitialized(),dittoffi_connection_request_free(t)}function presenceSetConnectionRequestHandler(t,e,i){if(ensureInitialized(),null==e)dittoffi_presence_set_connection_request_handler(t,null);else{dittoffi_presence_set_connection_request_handler(t,wrapAsyncBackgroundCbForFFI(i,e))}}function dittoIsActivated(t){return ensureInitialized(),dittoffi_ditto_is_activated(t)}function dittoIsSyncActive(t){return ensureInitialized(),dittoffi_ditto_is_sync_active(t)}function dittoTryStartSync(t){ensureInitialized();throwOnErrorResult(dittoffi_ditto_try_start_sync(t).error,"dittoffi_ditto_try_start_sync")}function dittoStopSync(t){return ensureInitialized(),dittoffi_ditto_stop_sync(t)}function dittoSetTransportConfig(t,e){ensureInitialized();throwOnErrorResult(dittoffi_ditto_try_set_transport_config(t,e,!0).error,"dittoffi_ditto_try_set_transport_config")}function dittoTransportConfig(t){ensureInitialized();return boxCBytesIntoBuffer(dittoffi_ditto_transport_config(t))}function dittoSetCloudSyncEnabled(t,e){ensureInitialized(),dittoffi_ditto_set_cloud_sync_enabled(t,e)}function dittoSmallPeerInfoGetIsEnabled(t){return ensureInitialized(),ditto_small_peer_info_get_is_enabled(t)}function dittoSmallPeerInfoSetEnabled(t,e){return ensureInitialized(),ditto_small_peer_info_set_enabled(t,e)}function dittoSmallPeerInfoGetSyncScope(t){return ensureInitialized(),ditto_small_peer_info_get_sync_scope(t)}function dittoSmallPeerInfoSetSyncScope(t,e){return ensureInitialized(),ditto_small_peer_info_set_sync_scope(t,e)}function dittoSmallPeerInfoGetMetadata(t){ensureInitialized();return boxCStringIntoString(ditto_small_peer_info_get_metadata(t))}function dittoSmallPeerInfoSetMetadata(t,e){ensureInitialized();const i=ditto_small_peer_info_set_metadata(t,bytesFromString(e));switch(i){case 0:return;case-1:throw new Error("Internal inconsistency, the observability subsystem is unavailable.");case 1:throw new Error(`Validation error, size limit exceeded: ${errorMessage()||"metadata is too big"}`);case 2:throw new Error(`Validation error, ${errorMessage()||"depth limit for metadata object exceeded"}`);case 3:throw new Error(`Validation error, ${errorMessage()||`'${e}' is not a valid JSON object`}`);default:throw new Error(errorMessage()||`Internal inconsistency, ditto_small_peer_info_set_metadata() returned an unknown error code: ${i}`)}}function dittoRegisterTransportConditionChangedCallback(t,e){ensureInitialized(),ditto_register_transport_condition_changed_callback(t,e?wrapBackgroundCbForFFI((t=>log("Error",`The registered "transport condition changed" callback errored with ${t}`)),e):null)}function dittoSetDeviceName(t,e){ensureInitialized();return boxCStringIntoString(ditto_set_device_name(t,bytesFromString(e)))}function dittoNewAttachmentFromFile(t,e,i){ensureInitialized();const n={},r=ditto_new_attachment_from_file(t,bytesFromString(e),i,n);if(0!==r)throw new DittoFFIError(r,null,`ditto_new_attachment_from_file() failed with error code: ${r}`);return n}async function dittoNewAttachmentFromBytes(t,e){ensureInitialized();const i={},n=await ditto_new_attachment_from_bytes(t,e,i);if(0!==n)throw new DittoFFIError(n,null,`ditto_new_attachment_from_bytes() failed with error code: ${n}`);return i}async function dittoResolveAttachment(t,e,i,n){ensureInitialized();const{onComplete:r,onProgress:o,onDelete:s}=i,a=wrapBackgroundCbForFFI(n,r),c=wrapBackgroundCbForFFI(n,o),d=wrapBackgroundCbForFFI(n,s),{status_code:l,cancel_token:u}=await ditto_resolve_attachment(t,e,a,c,d);if(0!==l)throw new DittoFFIError(l,null,`ditto_resolve_attachment() failed with error code: ${l}`);return u}function dittoCancelResolveAttachment(t,e,i){ensureInitialized();const n=ditto_cancel_resolve_attachment(t,e,i);if(0!==n)throw new Error(errorMessage()||`ditto_cancel_resolve_attachment() failed with error code: ${n}`)}function freeAttachmentHandle(t){ensureInitialized(),ditto_free_attachment_handle(t)}function dittoGetCompleteAttachmentPath(t,e){ensureInitialized();return refCStringToString(ditto_get_complete_attachment_path(t,e))}function dittoGetSDKVersion(t){ensureInitialized();return boxCStringIntoString(ditto_get_sdk_version(t))}function dittoGetSDKSemver(){ensureInitialized();return boxCStringIntoString(dittoffi_get_sdk_semver())}function dittoPresenceV1(t){ensureInitialized();return boxCStringIntoString(ditto_presence_v1(t))}function dittoPresenceV3(t){ensureInitialized();return boxCStringIntoString(ditto_presence_v3(t))}async function dittoShutdown(t){return ensureInitialized(),await ditto_shutdown(t)}async function dittoRunGarbageCollection(t){ensureInitialized();const e=await ditto_run_garbage_collection(t);if(0!==e)throw new Error(errorMessage()||`ditto_run_garbage_collection() failed with error code: ${e}`)}async function dittoDisableSyncWithV3(t){ensureInitialized();const e=await ditto_disable_sync_with_v3(t);if(0!==e)throw new Error(errorMessage()||`ditto_disable_sync_with_v3() failed with error code: ${e}`)}function base64encode(t,e){return boxCStringIntoString(dittoffi_base64_encode(t,e))}function tryBase64Decode(t,e){const i=dittoffi_try_base64_decode(bytesFromString(t),e);return throwOnErrorResult(i.error,"dittoffi_try_base64_decode"),boxCBytesIntoBuffer(i.success)}async function dittoAuthSetLoginProvider(t,e){return ensureInitialized(),await ditto_auth_set_login_provider(t,e)}function dittoAuthClientMakeLoginProvider(t,e){return ensureInitialized(),ditto_auth_client_make_login_provider(wrapBackgroundCbForFFI(e,t))}function transportsInit(){ensureInitialized();const{output:t,errorType:e}=withTransportsError(ditto_sdk_transports_init);if(!1===t)throw new Error(`Failed to initialize transports (${e} error)`)}function withTransportsError(t,...e){const i=ditto_sdk_transports_error_new(),n=t(...e,i),r=ditto_sdk_transports_error_value(i);return ditto_sdk_transports_error_free(i),{output:n,errorType:r}}!function(t){t[t.counter=0]="counter",t[t.register=1]="register",t[t.attachment=2]="attachment",t[t.rga=3]="rga",t[t.rwMap=4]="rwMap"}(DittoCRDTType||(DittoCRDTType={}));let isInitialized$1=!1;function tryVerifyLicense(t,e){ensureInitialized();throwOnErrorResult(dittoffi_try_verify_license(t,bytesFromString(e)).error,"dittoffi_try_verify_license")}function defaultDeviceName(){return rnOnlyDefaultDeviceName()}function rnOnlyGetPlatform(){return getPlatform()}function rnOnlyDefaultDeviceName(){return defaultDeviceName$1()}function rnOnlyGetDefaultDirectory(){return getDefaultDirectory()}function rnOnlyReadFile(t){return readFile(t)}function rnOnlyCopyFile(t,e,i){return copyFile(t,e,i)}function wrapBackgroundCbForFFI(t,e){return e}function wrapAsyncBackgroundCbForFFI(t,e){return e}function bytesFromString(t){if(void 0===t)return;if(null===t)return null;if("string"!=typeof t)throw new Error(`Can't convert string to Uint8Array, not a string: ${t}`);return(new TextEncoder).encode(`${t}\0`)}function errorMessage(){ensureInitialized();return boxCStringIntoString(ditto_error_message())}function ensureInitialized(){if(!isInitialized$1)throw new Error("Ditto needs to be initialized before using any of its API, please make sure to call `await init()` first.")}isInitialized$1=!0;const ERROR_CODES={internal:"An unexpected internal error occurred. Please get in touch with Ditto customer service to report this incident.","internal/unknown-error":"An unexpected internal error occurred. Please get in touch with Ditto customer service to report this incident.","sdk/unsupported":"The feature is not supported by the current environment.","authentication/failed-to-authenticate":"Ditto failed to authenticate.","authentication/expiration-handler-missing":"The expiration handler must be set before starting sync.","io/already-exists":"A file or directory already exists.","io/not-found":"A file or directory could not be found.","io/permission-denied":"The operation failed due to insufficient permissions.","io/operation-failed":"The operation failed.","query/arguments-invalid":"The query arguments were invalid.","query/evaluation":"The query could not be evaluated.","query/execution":"The query could not be executed.","query/invalid":"The query was invalid.","query/unsupported":"The query contains unsupported features.","query/parameter":"The query to update system parameters failed.","store/backend":"An error occurred with the storage backend.","store/crdt":"An error occurred processing a CRDT.","store/document-not-found":"The document with the provided ID could not be found.","store/transaction-read-only":"A mutating DQL query was attempted using a read-only transaction.","store/document-id":"The document ID is invalid.","store/persistence-directory-locked":"The chosen persistence directory is already in use by another Ditto instance.","store/attachment-file-permission-denied":"Permission has been denied for a file operation when working with attachments.","store/attachment-file-not-found":"The source file for the attachment does not exist.","store/attachment-not-found":"The attachment could not be found.","store/attachment-token-invalid":"The attachment token is invalid.","store/failed-to-create-attachment":"The attachment could not be created.","store/failed-to-fetch-attachment":"The attachment could not be fetched.","activation/license-token-verification-failed":"Please provide a valid license token.","activation/license-token-expired":"The license token expired. Please renew it.","activation/license-token-unsupported-future-version":"The provided license token is in an unsupported future format.","activation/not-activated":"The operation failed because the Ditto instance has not yet been activated.","activation/unnecessary":"Activation is unnecessary for this Ditto instance, because of its identity.","validation/depth-limit-exceeded":"The maximum depth limit has been exceeded.","validation/invalid-cbor":"The value provided is not valid CBOR.","validation/invalid-json":"The value provided is not valid JSON.","validation/invalid-transport-config":"The TransportConfig is invalid for the active platform.","validation/invalid-ditto-config":"The DittoConfig provided is invalid.","validation/not-an-object":"The value provided is not of type object.","validation/not-json-compatible":"Value is not serializable as JSON.","validation/size-limit-exceeded":"The size limit has been exceeded.","encryption/extraneous-passphrase-given":"Unexpected passphrase provided for the currently unencrypted store.","differ/identity-key-path-invalid":"A provided identity key path is invalid."},DEFAULT_STATUS_CODE_MAPPING={ActivationLicenseTokenExpired:["activation/license-token-expired"],ActivationLicenseTokenInvalid:["activation/license-token-verification-failed"],ActivationLicenseUnsupportedFutureVersion:["activation/license-token-unsupported-future-version"],ActivationNotActivated:["activation/not-activated"],ActivationUnnecessary:["activation/unnecessary"],AuthenticationExpirationHandlerMissing:["authentication/expiration-handler-missing"],IoAlreadyExists:["io/already-exists"],IoNotFound:["io/not-found"],IoPermissionDenied:["io/permission-denied"],IoOperationFailed:["io/operation-failed"],JsFloatingStoreOperation:["internal","Internal inconsistency, an outstanding store operation was not awaited."],DqlEvaluationError:["query/evaluation"],DqlQueryCompilation:["query/invalid"],DqlInvalidQueryArgs:["query/arguments-invalid"],DqlUnsupported:["query/unsupported"],StoreQuery:["query/execution"],ParameterQuery:["query/parameter"],EncryptionExtraneousPassphraseGiven:["encryption/extraneous-passphrase-given"],StoreDatabase:["store/backend"],StoreDocumentId:["store/document-id"],StoreDocumentNotFound:["store/document-not-found"],StoreTransactionReadOnly:["store/transaction-read-only"],Crdt:["store/crdt"],LockedDittoWorkingDirectory:["store/persistence-directory-locked"],Base64Invalid:["internal","Invalid base64 encoding."],CborInvalid:["internal","Invalid CBOR encoding."],CborUnsupported:["internal","Unsupported CBOR encoding."],ValidationDepthLimitExceeded:["validation/depth-limit-exceeded"],ValidationInvalidCbor:["validation/invalid-cbor"],ValidationInvalidDittoConfig:["validation/invalid-ditto-config"],ValidationInvalidJson:["validation/invalid-json"],ValidationInvalidTransportConfig:["validation/invalid-transport-config"],ValidationNotAMap:["validation/not-an-object"],ValidationSizeLimitExceeded:["validation/size-limit-exceeded"],DifferIdentityKeyPathInvalid:["differ/identity-key-path-invalid"],Transport:["internal","Transport error."],Unsupported:["sdk/unsupported"],Unknown:["internal/unknown-error"],default:["internal/unknown-error"]};class DittoError extends Error{constructor(t,e,i={}){if(null==ERROR_CODES[t])throw new DittoError("internal",`Invalid error code: ${t}`);super(e||ERROR_CODES[t]),this.code="internal",this.code=t,this.context=Object.freeze({...i})}static fromFFIError(t,e,i,n){const r=i||t.message,o={coreError:t.code,coreErrorMessage:t.message,...n},s=new DittoError(e,r,o);return null!=t.stack&&(s.stack=t.stack),s}}function mapFFIErrors(t,e,i){try{return t()}catch(t){if(t instanceof DittoFFIError)throw translateFFIError(t,e,i);throw t}}async function mapFFIErrorsAsync(t,e,i){try{return await t()}catch(t){if(t instanceof DittoFFIError)throw translateFFIError(t,e,i);throw t}}const translateFFIError=(t,e,i)=>{var n;const r=t.code.toString();let o,s;return null!=e&&null!=e[r]?[o,s]=e[r]:[o,s]=null!==(n=DEFAULT_STATUS_CODE_MAPPING[r])&&void 0!==n?n:DEFAULT_STATUS_CODE_MAPPING.default,DittoError.fromFFIError(t,o,s,i)};class AttachmentToken{constructor(t){let e,i,n;null!=t[DittoCRDTTypeKey]?({id:e,len:i,meta:n}=AttachmentToken.validateTypedInput(t)):({id:e,len:i,meta:n}=AttachmentToken.validateUntypedInput(t)),this.id=mapFFIErrors((()=>base64encode(e,"Unpadded"))),this.idBytes=e,this.len=i,this.metadata=n}static validateTypedInput(t){if(t[DittoCRDTTypeKey]!==DittoCRDTType.attachment)throw new Error("Invalid attachment token");const e=t._id;if(!(e instanceof Uint8Array))throw new Error("Invalid attachment token id");const i=t._len;if("number"!=typeof i&&"bigint"!=typeof i||i<0)throw new Error("Invalid attachment token length, must be a non-negative number or bigint");const n=t._meta;if("object"!=typeof n)throw new Error("Invalid attachment token meta");return{id:e,len:i,meta:n}}static validateUntypedInput(t){const e=t.id;if("string"!=typeof e)throw new Error("Invalid attachment token id");const i=mapFFIErrors((()=>tryBase64Decode(e,"Unpadded")),{Base64Invalid:["store/attachment-token-invalid","Failed to decode attachment token id from base64 input"]},{attachmentTokenID:e}),n=t.len;if("number"!=typeof n&&"bigint"!=typeof n||n<0)throw new Error("Invalid attachment token length, must be a non-negative number or bigint");const r=t.metadata;if("object"!=typeof r)throw new Error("Invalid attachment token meta");return{id:i,len:n,meta:r}}}class Logger{static get logFile(){return this._logFile}static setLogFile(t){t?(loggerSetLogFile(t),this._logFile=t):(loggerSetLogFile(void 0),delete this._logFile)}static setLogFileURL(t){var e;this.setLogFile(null!==(e=null==t?void 0:t.pathname)&&void 0!==e?e:null)}static get enabled(){return loggerEnabledGet()}static set enabled(t){loggerEnabled(t)}static get emojiLogLevelHeadingsEnabled(){return loggerEmojiHeadingsEnabledGet()}static set emojiLogLevelHeadingsEnabled(t){loggerEmojiHeadingsEnabled(t)}static get minimumLogLevel(){return loggerMinimumLogLevelGet()}static set minimumLogLevel(t){loggerMinimumLogLevel(t)}static get customLogCallback(){return this._customLogCallback}static async setCustomLogCallback(t){if(null!=t&&"function"!=typeof t)throw new TypeError(`Expected parameter 'callback' to be a function or undefined, but got ${typeof t}.`);null!=t?(await loggerSetCustomLogCb(t),this._customLogCallback=t):(await loggerSetCustomLogCb(null),delete this._customLogCallback)}static async exportToFile(t){if("string"!=typeof t)throw new TypeError(`Expected parameter 'path' to be a string, but got ${typeof t}.`);let e=t;return mapFFIErrorsAsync((()=>loggerTryExportToFile(e)))}static log(t,e){log(t,e)}static error(t){this.log("Error",t)}static warning(t){this.log("Warning",t)}static info(t){this.log("Info",t)}static debug(t){this.log("Debug",t)}static verbose(t){this.log("Verbose",t)}constructor(){throw new Error("Logger can't be instantiated, use its static properties & methods directly instead.")}}var _a;const DEBUG_TYPE_NAMES=[],DEBUG_ALL_TYPES=!1;class Handle{constructor(t,e,i){this.isClosed=!1,this.isFinalized=!1,this.isUnregistered=!1,this.bridge=t,this.objectWeakRef=new WeakRef(e),this.pointer=i}get type(){return this.bridge.type}deref(){if(this.isClosed)throw new Error("Bridging error: can't get pointer for an object that has been closed.");if(this.isFinalized)throw new Error("Bridging error: can't get pointer for an object that has been finalized.");if(this.isUnregistered)throw new Error("Bridging error: can't get pointer for an object that has been unregistered.");return this.pointer}derefOrNull(){var t;return this.isClosed||this.isFinalized||this.isUnregistered?null:null!==(t=this.pointer)&&void 0!==t?t:null}object(){const t=this.objectWeakRef.deref();if(null==t)throw new Error(`Bridging error: ${this.bridge.type.name} object has been garbage collected.`);if(this.isClosed)throw new Error(`Bridging error: ${this.bridge.type.name} object has been closed.`);if(this.isUnregistered)throw new Error(`Bridging error: ${this.bridge.type.name} object has been unregistered.`);return t}objectOrNull(){var t;return null!==(t=this.objectWeakRef.deref())&&void 0!==t?t:null}toString(){const t=this.derefOrNull();return`{ Handle | type: ${this.bridge.type}, object: ${this.objectWeakRef.deref()}, FFI address: ${null==t?void 0:t.addr}, FFI type: ${null==t?void 0:t.type} }`}bridgeWillClose(){this.isClosed=!0}bridgeDidClose(){this.pointer=null}bridgeWillFinalize(){this.isFinalized=!0}bridgeDidFinalize(){this.pointer=null}bridgeWillUnregister(){this.isUnregistered=!0}bridgeDidUnregister(){this.pointer=null}}class Handles{constructor(t,e){this.handles=e.map((e=>t.handleFor(e)))}deref(){return this.handles.map((t=>t.deref()))}}class Bridge{constructor(t){this.internalType=null,this.release=t,this.handlesByAddress={},this.handlesByObject=new WeakMap,this.finalizationRegistry=new FinalizationRegistry(this.finalize.bind(this)),_a.all.push(new WeakRef(this))}get type(){if(null==this.internalType)throw new Error("Bridge type has not been registered yet.");return this.internalType}registerType(t){if(this.internalType!==t){if(this.internalType)throw new Error(`Can't register bridged type '${t.name}', another type was already registered: ${this.internalType}`);this.internalType=t}}handleFor(t){const e=this.handlesByObject.get(t);if(null==e)throw new Error(`Bridging error: ${this.type.name} object is not currently registered in this bridge.`);return e}handlesFor(t){return new Handles(this,t)}objectFor(t){const e=this.handlesByAddress[t.addr];if(e){if(e.type!==this.type)throw new Error(`Can't return object for pointer, pointer is associated with an object of type ${e.type} but this bridge is configured for ${this.type}`);return e.object()}}bridge(t,e){const i=this.objectFor(t);if(i)return i;let n;if(e||(e=()=>Reflect.construct(this.type,[])),"function"==typeof e){if(n=e(),!(n instanceof this.type))throw new Error(`Can't bridge, expected passed in create function to return a ${this.type.name} object but got: ${n}`)}else n=e;return this.register(n,t),n}register(t,e){const i=t.constructor;if(i!==this.type)throw new Error(`Can't register, bridge is configured for type ${this.type.name} but passed in object is of type ${i.name}`);const n=this.handlesByObject.get(t),r=n?n.pointer:null;if(null!=r&&null!=n)throw new Error(`Can't register, an object for the passed in pointer has previously been registered: ${n.object()}`);if(null!=r&&null==n)throw new Error(`Internal inconsistency, trying to register an object which has an associated pointer but no handle entry: ${i.name} at ${r.type} ${r.addr}`);if(null==r&&null!=n)throw new Error(`Internal inconsistency, trying to register an object which has a handle entry but no associated pointer: ${i.name} ${t}`);const o=new Handle(this,t,e);this.handlesByAddress[e.addr]=o,this.handlesByObject.set(t,o),this.finalizationRegistry.register(t,o,t),DEBUG_TYPE_NAMES.includes(this.type.name)&&Logger.debug(`[VERBOSE] Bridge REGISTERED a new instance of ${this.type.name}, current count: ${Object.keys(this.handlesByAddress).length}`)}unregister(t){const e=t.constructor,i=this.type;if(e!==i)throw new Error(`Can't unregister, bridge is configured for type ${i.name} but passed in object is of type ${e.name}`);const n=this.handlesByObject.get(t);if(null==n)throw new Error(`Can't unregister, object has not been registered before: ${t}`);if(n.type!==i)throw new Error(`Internal inconsistency, trying to unregister an object that has a handle with a different type than that of the bridge: ${n}`);if(n.objectOrNull()!==t)throw new Error(`Internal inconsistency, trying to unregister an object whose associated handle holds a different object: ${n}`);if(n.isClosed)throw new Error(`Can't unregister, object has been closed before: ${t}`);if(n.isFinalized)throw new Error(`Can't unregister, object has been finalized before: ${t}`);if(n.isUnregistered)throw new Error(`Can't unregister, object has been unregistered already: ${t}`);n.bridgeWillUnregister(),this.finalizationRegistry.unregister(t),delete this.handlesByAddress[n.pointer.addr],this.handlesByObject.delete(t),n.bridgeDidUnregister(),DEBUG_TYPE_NAMES.includes(this.type.name)&&Logger.debug(`[VERBOSE] Bridge UNREGISTERED an instance of ${this.type.name}, current count: ${Object.keys(this.handlesByAddress).length}`)}unregisterAll(){DEBUG_TYPE_NAMES.includes(this.type.name)&&Logger.debug(`[VERBOSE] Unregistering ALL bridged instances of type ${this.type.name}.`);for(const t of Object.values(this.handlesByAddress)){const e=t.object();e&&this.unregister(e)}}async close(t){const e=t.constructor,i=this.type;if(e!==i)throw new Error(`Can't close, bridge is configured for type ${i.name} but passed in object is of type ${e.name}`);const n=this.handlesByObject.get(t);if(null==n)throw new Error(`Can't close an object that has not been registered before: ${t}`);if(n.type!==i)throw new Error(`Internal inconsistency, trying to close an object that has a handle with a different type than that of the bridge: ${n}`);if(n.isUnregistered)throw new Error("Can't close object, object has been unregistered.");if(n.isFinalized)throw new Error("Internal inconsistency, trying to close an object that has already been finalized.");if(n.isClosed)return;const r=n.pointer;if(!r)throw new Error("Internal inconsistency, trying to close an object whose pointer is null.");n.bridgeWillClose(),delete this.handlesByAddress[r.addr],await this.release(r),n.bridgeDidClose(),DEBUG_TYPE_NAMES.includes(this.type.name)&&Logger.debug(`[VERBOSE] Bridge CLOSED an instance of ${this.type.name}, current count: ${Object.keys(this.handlesByAddress).length}`)}get count(){return Object.keys(this.handlesByAddress).length}async finalize(t){if(t.isFinalized)throw new Error("Internal inconsistency, trying to finalize an object that has already been finalized.");if(t.isUnregistered)throw new Error("Internal inconsistency, trying to finalize an object that has been unregistered before.");if(t.bridgeWillFinalize(),!t.isClosed){const e=t.pointer;if(!e)throw new Error("Internal inconsistency, trying to finalize an object whose pointer is null.");delete this.handlesByAddress[e.addr],await this.release(e)}t.bridgeDidFinalize(),DEBUG_TYPE_NAMES.includes(this.type.name)&&Logger.debug(`[VERBOSE] Bridge FINALIZED an instance of ${this.type.name}, current count: ${Object.keys(this.handlesByAddress).length}`)}}_a=Bridge,Bridge.all=[],Bridge.attachment=new _a(freeAttachmentHandle),Bridge.connectionRequest=new _a(connectionRequestFree),Bridge.document=new _a(documentFree),Bridge.mutableDocument=new _a(documentFree),Bridge.queryResult=new _a(queryResultFree),Bridge.queryResultItem=new _a(queryResultItemFree),Bridge.transaction=new _a(transactionFree),Bridge.differ=new _a(differFree),Bridge.ditto=new _a((async t=>{await dittoClearPresenceCallback(t),await dittoShutdown(t),dittoFree(t)}));class Attachment{get id(){return this.token.id}get len(){return this.token.len}get metadata(){return this.token.metadata}data(){return this.ditto.deferCloseAsync((async t=>{{const e=Bridge.attachment.handleFor(this),i=dittoGetCompleteAttachmentPath(t.deref(),e.deref());return await rnOnlyReadFile(i)}}))}getData(){return this.data()}copyToPath(t){return this.ditto.deferCloseAsync((async e=>{{const i=Bridge.attachment.handleFor(this);rnOnlyCopyFile(dittoGetCompleteAttachmentPath(e.deref(),i.deref()),t,this.ditto.absolutePersistenceDirectory)}}))}constructor(t,e){this.ditto=t,this.token=e}}function validateAttachmentMetadata(t){if("object"!=typeof t)throw new DittoError("store/failed-to-create-attachment",`Invalid attachment metadata: expected a value of type object but got ${typeof t}.`);for(const e in t)if("string"!=typeof t[e])throw new DittoError("store/failed-to-create-attachment",`Invalid attachment metadata: metadata values must be strings but key '${e}' has a value of type ${typeof t[e]}.`)}const defaultDittoCloudDomain="cloud.ditto.live";function defaultAuthURL(t){return`https://${t}.cloud.ditto.live`}function customInspectRepresentation(t,e){return void 0===e?`${t.constructor.name} ${JSON.stringify({value:t.value},null,2)}`:`${t.constructor.name} ${e({value:t.value})}`}function sleep(t){return new Promise(((e,i)=>{setTimeout(e,t)}))}async function step(t){return await sleep(0),t()}const performAsyncToWorkaroundNonAsyncFFIAPI=step;function capitalize(t){return t.charAt(0).toUpperCase()+t.slice(1)}class AttachmentFetcher{stop(){if(null==this.manager){this.isStopped||(this.rejectPendingFetch(),this.rejectPendingFetch=null),this.ditto.store.removeAttachmentFetcher(this);const t=Bridge.ditto.handleFor(this.ditto);this.ditto.deferCloseAsync((async()=>{const e=await this.cancelTokenPromise;e&&dittoCancelResolveAttachment(t.deref(),this.token.idBytes,e)}))}else step((async()=>{await this.manager.stopAttachmentFetcher(this),null!=this.rejectPendingFetch&&(this.rejectPendingFetch(),this.rejectPendingFetch=null)}))}then(t,e){return this.attachment.then(t,e)}constructor(t,e,i,n){this.cancelTokenPromise=null,this.rejectPendingFetch=null,this.ditto=t,this.token=e,this.manager=i,this.id=cryptoGenerateSecureRandomToken();const r=n||function(){},o=Bridge.ditto.handleFor(t);this.attachment=new Promise(((t,i)=>{const onComplete=e=>{const i=new Attachment(this.ditto,this.token);Bridge.attachment.bridge(e,(()=>i)),r({type:"Completed",attachment:i}),this.rejectPendingFetch=null,t(i)},onProgress=(t,e)=>{r({type:"Progress",totalBytes:e,downloadedBytes:t})},onDelete=()=>{r({type:"Deleted"}),null!=this.manager?(this.rejectPendingFetch=null,t(null)):(this.rejectPendingFetch=null,i(new DittoError("store/attachment-not-found","The attachment was deleted while being fetched.")))},onError=()=>{};this.rejectPendingFetch=()=>{const t=null!=this.manager?new Error("Attachment fetch was canceled"):new DittoError("store/failed-to-fetch-attachment","Attachment fetch was canceled");i(t)};const n=new WeakRef(this);this.cancelTokenPromise=(async()=>{try{return await mapFFIErrorsAsync((async()=>dittoResolveAttachment(o.deref(),e.idBytes,{onComplete:onComplete,onProgress:onProgress,onDelete:onDelete},onError)),{1:["store/failed-to-fetch-attachment","Failed to fetch the attachment."],2:["store/attachment-token-invalid","The attachment token was invalid."],3:["store/attachment-not-found","The attachment was not found."]})}catch(e){let o=!1;e instanceof DittoError&&"store/attachment-not-found"===e.code&&(o=!0,r({type:"Deleted"})),Logger.error(e.message);const s=n.deref();return null==s||(null!=s.manager&&e instanceof DittoError&&(e=new Error(e.message)),s.rejectPendingFetch=null,null!=s.manager&&o?t(null):i(e)),null}})()})),null==i&&this.attachment.then((()=>{this.rejectPendingFetch=null,this.ditto.store.removeAttachmentFetcher(this)})).catch((()=>{this.rejectPendingFetch=null,this.ditto.store.removeAttachmentFetcher(this)}))}get isStopped(){return null==this.rejectPendingFetch}}let isInitialized=!1,initPromise=null;function init(t={}){return isInitialized?initPromise:initPromise||(initPromise=(async()=>{isInitialized=!0})(),initPromise)}const CBOR_OPTIONS=Object.freeze({dictionary:"object",mode:"strict"}),EMPTY_KEY=Symbol("EMPTY_KEY"),OMIT_VALUE=Symbol("OMIT_VALUE"),POW_2_24=5.960464477539063e-8,POW_2_32=4294967296,POW_2_53=9007199254740992,MAX_SAFE_INTEGER=18446744073709551616n,DECODE_CHUNK_SIZE=8192,kCborTag=6,kCborTagUint8=64,kCborTagUint16=69,kCborTagUint32=70,kCborTagInt8=72,kCborTagInt16=77,kCborTagInt32=78,kCborTagFloat32=85,kCborTagFloat64=86;function objectIs(t,e){return"function"==typeof Object.is?Object.is(t,e):t===e?0!==t||1/t==1/e:t!=t&&e!=e}function options(t){const e={...CBOR_OPTIONS};return"object"==typeof t&&(e.dictionary=function isDictionary(t){return"string"==typeof t&&["object","map"].includes(t)}(t.dictionary)?t.dictionary:CBOR_OPTIONS.dictionary,e.mode=function isMode(t){return"string"==typeof t&&["loose","strict","sequence"].includes(t)}(t.mode)?t.mode:CBOR_OPTIONS.mode),Object.freeze(e)}function lexicographicalCompare(t,e){const i=Math.min(t.byteLength,e.byteLength);for(let n=0;n<i;n++){const i=t[n]-e[n];if(0!==i)return i}return t.byteLength-e.byteLength}var _Sequence_instances,_Sequence_toInspectString,__classPrivateFieldGet=function(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)};class Sequence{static from(t){return new Sequence(Array.from(t))}constructor(t){_Sequence_instances.add(this),Object.defineProperty(this,"_data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._data=t||[]}add(t){return this._data.push(t)-1}remove(t){return this._data.splice(t,1)[0]}get(t){return this._data[t]}clone(){return new Sequence(this.data)}get data(){return Array.from(this._data)}get size(){return this._data.length}[(_Sequence_instances=new WeakSet,Symbol.toStringTag)](){return"Sequence"}[(_Sequence_toInspectString=function _Sequence_toInspectString(t){return`${this[Symbol.toStringTag]()}(${this.size}) ${t(this._data)}`},Symbol.for("Deno.customInspect"))](t){return __classPrivateFieldGet(this,_Sequence_instances,"m",_Sequence_toInspectString).call(this,t)}[Symbol.for("nodejs.util.inspect.custom")](t,e,i){return __classPrivateFieldGet(this,_Sequence_instances,"m",_Sequence_toInspectString).call(this,i)}}class SimpleValue{static create(t){if(void 0===t)return new SimpleValue(23);if(null===t)return new SimpleValue(22);if(!0===t)return new SimpleValue(21);if(!1===t)return new SimpleValue(20);if("number"==typeof t&&t>=0&&t<=255)return new SimpleValue(t);throw new Error("CBORError: Value out of range or not a simple value.")}constructor(t){switch(Object.defineProperty(this,"semantic",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),!0){case 20===t:this.semantic="false";break;case 21===t:this.semantic="true";break;case 22===t:this.semantic="null";break;case 23===t:this.semantic="undefined";break;case t>23&&t<32:this.semantic="reserved";break;default:this.semantic="unassigned"}this.value=t}toPrimitive(){switch(this.semantic){case"false":return!1;case"true":return!0;case"null":return null;default:return}}}class TaggedValue{constructor(t,e){Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tag",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.value=t,this.tag=e}}function decode(t,e,i={}){const{dictionary:n,mode:r}=options(i),o="sequence"===r||"strict"===r,s=new DataView(t),a=new Uint8Array(t);let c=0,reviverFunction=function(t,e){return e};function commitRead(t,e){return c+=t,e}function readArrayBuffer(e){return commitRead(e,new Uint8Array(t,c,e))}function readUint8(){return commitRead(1,a[c])}function readUint16(){return commitRead(2,s.getUint16(c))}function readBreak(){return 255===a[c]&&(c+=1,!0)}function readLength(t){if(t<24)return t;if(24===t)return readUint8();if(25===t)return readUint16();if(26===t)return function readUint32(){return commitRead(4,s.getUint32(c))}();if(27===t){const t=function readUint64(){return commitRead(8,s.getBigUint64(c))}();return t<POW_2_53?Number(t):t}if(31===t)return-1;throw new Error("CBORError: Invalid length encoding")}function readIndefiniteStringLength(t){const e=readUint8();if(255===e)return-1;const i=readLength(31&e);if(i<0||e>>5!==t)throw new Error("CBORError: Invalid indefinite length element");return Number(i)}function appendUtf16Data(t,e){for(let i=0;i<e;++i){let i=readUint8();128&i&&(i<224?(i=(31&i)<<6|63&readUint8(),e-=1):i<240?(i=(15&i)<<12|(63&readUint8())<<6|63&readUint8(),e-=2):(i=(15&i)<<18|(63&readUint8())<<12|(63&readUint8())<<6|63&readUint8(),e-=3)),i<65536?t.push(i):(i-=65536,t.push(55296|i>>10),t.push(56320|1023&i))}}function decodeItem(){const t=readUint8(),e=t>>5,i=31&t;let r,a;if(7===e)switch(i){case 25:return function readFloat16(){const t=new ArrayBuffer(4),e=new DataView(t),i=readUint16(),n=32768&i;let r=31744&i;const o=1023&i;if(31744===r)r=261120;else if(0!==r)r+=114688;else if(0!==o)return(n?-1:1)*o*POW_2_24;return e.setUint32(0,n<<16|r<<13|o<<13),e.getFloat32(0)}();case 26:return function readFloat32(){return commitRead(4,s.getFloat32(c))}();case 27:return function readFloat64(){return commitRead(8,s.getFloat64(c))}()}if(a=readLength(i),a<0&&(e<2||6<e))throw new Error("CBORError: Invalid length");switch(e){case 0:return reviverFunction(EMPTY_KEY,a);case 1:return reviverFunction(EMPTY_KEY,"number"==typeof a?-1-a:-1n-a);case 2:if(a<0){const t=[];let i=0;for(;(a=readIndefiniteStringLength(e))>=0;)i+=a,t.push(readArrayBuffer(a));const n=new Uint8Array(i);let o=0;for(r=0;r<t.length;++r)n.set(t[r],o),o+=t[r].length;return reviverFunction(EMPTY_KEY,n)}return reviverFunction(EMPTY_KEY,readArrayBuffer(a));case 3:{const t=[];if(a<0)for(;(a=readIndefiniteStringLength(e))>=0;)appendUtf16Data(t,a);else appendUtf16Data(t,a);let i="";for(r=0;r<t.length;r+=8192)i+=String.fromCharCode.apply(null,t.slice(r,r+8192));return reviverFunction(EMPTY_KEY,i)}case 4:{let t;if(a<0){t=[];let e=0;for(;!readBreak();)t.push(reviverFunction(e++,decodeItem()))}else for(t=new Array(a),r=0;r<a;++r)t[r]=reviverFunction(r,decodeItem());return reviverFunction(EMPTY_KEY,t)}case 5:{if("map"===n){const t=new Map;for(r=0;r<a||a<0&&!readBreak();++r){const e=decodeItem();if(o&&t.has(e))throw new Error("CBORError: Duplicate key encountered");t.set(e,reviverFunction(e,decodeItem()))}return reviverFunction(EMPTY_KEY,t)}const t={};for(r=0;r<a||a<0&&!readBreak();++r){const e=decodeItem();if(o&&Object.prototype.hasOwnProperty.call(t,e))throw new Error("CBORError: Duplicate key encountered");t[e]=reviverFunction(e,decodeItem())}return reviverFunction(EMPTY_KEY,t)}case 6:{const t=decodeItem(),e=a;if(t instanceof Uint8Array){const i=t.buffer.slice(t.byteOffset,t.byteLength+t.byteOffset);switch(e){case 64:return reviverFunction(EMPTY_KEY,new Uint8Array(i));case 72:return reviverFunction(EMPTY_KEY,new Int8Array(i));case 69:return reviverFunction(EMPTY_KEY,new Uint16Array(i));case 77:return reviverFunction(EMPTY_KEY,new Int16Array(i));case 70:return reviverFunction(EMPTY_KEY,new Uint32Array(i));case 78:return reviverFunction(EMPTY_KEY,new Int32Array(i));case 85:return reviverFunction(EMPTY_KEY,new Float32Array(i));case 86:return reviverFunction(EMPTY_KEY,new Float64Array(i))}}return reviverFunction(EMPTY_KEY,new TaggedValue(t,e))}case 7:switch(a){case 20:return reviverFunction(EMPTY_KEY,!1);case 21:return reviverFunction(EMPTY_KEY,!0);case 22:return reviverFunction(EMPTY_KEY,null);case 23:return reviverFunction(EMPTY_KEY,void 0);default:return reviverFunction(EMPTY_KEY,new SimpleValue(a))}}}"function"==typeof e&&(reviverFunction=e);const d=decodeItem();if(c!==t.byteLength){if("sequence"!==r)throw new Error("CBORError: Remaining bytes");const e=new Sequence([d]);for(;c<t.byteLength;)e.add(reviverFunction(EMPTY_KEY,decodeItem()));return e}return"sequence"===r?new Sequence([d]):d}function parse(t,e,i){return decode(t,e,i)}function encode(t,e){let i,n=new ArrayBuffer(256),r=new DataView(n),o=new Uint8Array(n),s=0,replacerFunction=(t,e)=>e;if("function"==typeof e&&(replacerFunction=e),Array.isArray(e)){const t=e.slice();replacerFunction=(e,i)=>e===EMPTY_KEY||t.includes(e)?i:OMIT_VALUE}function prepareWrite(t){let e=n.byteLength;const a=s+t;for(;e<a;)e<<=1;if(e!==n.byteLength){const t=r;n=new ArrayBuffer(e),r=new DataView(n),o=new Uint8Array(n);const i=s+3>>2;for(let e=0;e<i;++e)r.setUint32(e<<2,t.getUint32(e<<2))}return i=t,r}function commitWrite(...t){s+=i}function writeUint8(t){commitWrite(prepareWrite(1).setUint8(s,t))}function writeUint8Array(t){prepareWrite(t.length),o.set(t,s),commitWrite()}function writeUint16(t){commitWrite(prepareWrite(2).setUint16(s,t))}function writeUint32(t){commitWrite(prepareWrite(4).setUint32(s,t))}function writeUint64(t){const e=t%POW_2_32,i=(t-e)/POW_2_32,n=prepareWrite(8);n.setUint32(s,i),n.setUint32(s+4,e),commitWrite()}function writeBigUint64(t){commitWrite(prepareWrite(8).setBigUint64(s,t))}function writeVarUint(t,e){t<=255?t<24?writeUint8(Number(t)|e):(writeUint8(24|e),writeUint8(Number(t))):t<=65535?(writeUint8(25|e),writeUint16(Number(t))):t<=4294967295?(writeUint8(26|e),writeUint32(Number(t))):(writeUint8(27|e),"number"==typeof t?writeUint64(t):writeBigUint64(t))}function writeTypeAndLength(t,e){e<24?writeUint8(t<<5|e):e<256?(writeUint8(t<<5|24),writeUint8(e)):e<65536?(writeUint8(t<<5|25),writeUint16(e)):e<4294967296?(writeUint8(t<<5|26),writeUint32(e)):(writeUint8(t<<5|27),writeUint64(e))}function encodeItem(t){if(t!==OMIT_VALUE){if(!1===t)return writeUint8(244);if(!0===t)return writeUint8(245);if(null===t)return writeUint8(246);if(void 0===t)return writeUint8(247);if(objectIs(t,-0))return writeUint8Array([249,128,0]);switch(typeof t){case"bigint":return function writeBigInteger(t){let e=0;if(0<=t&&t<=MAX_SAFE_INTEGER)e=0;else{if(!(-MAX_SAFE_INTEGER<=t&&t<0))throw new Error("CBORError: Encountered unsafe integer outside of valid CBOR range.");e=1,t=-(t+1n)}if(t<0x100000000n)return writeTypeAndLength(e,Number(t));writeUint8(e<<5|27),writeBigUint64(t)}(t);case"number":if(Math.floor(t)===t){if(0<=t&&t<=POW_2_53)return writeTypeAndLength(0,t);if(-POW_2_53<=t&&t<0)return writeTypeAndLength(1,-(t+1))}return writeUint8(251),function writeFloat64(t){commitWrite(prepareWrite(8).setFloat64(s,t))}(t);case"string":{const e=[],i=t.length;for(let n=0;n<i;++n){let i=t.charCodeAt(n);i<128?e.push(i):i<2048?(e.push(192|i>>6),e.push(128|63&i)):i<55296||i>=57344?(e.push(224|i>>12),e.push(128|i>>6&63),e.push(128|63&i)):(i=(1023&i)<<10,i|=1023&t.charCodeAt(++n),i+=65536,e.push(240|i>>18),e.push(128|i>>12&63),e.push(128|i>>6&63),e.push(128|63&i))}return writeTypeAndLength(3,e.length),writeUint8Array(e)}default:{let e;if(Array.isArray(t))!function writeArray(t){const e=s,i=t.length;let n=0;writeTypeAndLength(4,i);const r=s;for(let e=0;e<i;e+=1){const i=replacerFunction(e,t[e]);i!==OMIT_VALUE&&(encodeItem(i),n+=1)}if(i>n){const t=o.slice(r,s);s=e,writeTypeAndLength(4,n),writeUint8Array(t)}}(t);else if(t instanceof Uint8Array)writeVarUint(64,192),writeTypeAndLength(2,t.length),writeUint8Array(t);else if(t instanceof Int8Array)writeVarUint(72,192),writeTypeAndLength(2,t.byteLength),writeUint8Array(new Uint8Array(t.buffer));else if(t instanceof Uint16Array)writeVarUint(69,192),writeTypeAndLength(2,t.byteLength),writeUint8Array(new Uint8Array(t.buffer));else if(t instanceof Int16Array)writeVarUint(77,192),writeTypeAndLength(2,t.byteLength),writeUint8Array(new Uint8Array(t.buffer));else if(t instanceof Uint32Array)writeVarUint(70,192),writeTypeAndLength(2,t.byteLength),writeUint8Array(new Uint8Array(t.buffer));else if(t instanceof Int32Array)writeVarUint(78,192),writeTypeAndLength(2,t.byteLength),writeUint8Array(new Uint8Array(t.buffer));else if(t instanceof Float32Array)writeVarUint(85,192),writeTypeAndLength(2,t.byteLength),writeUint8Array(new Uint8Array(t.buffer));else if(t instanceof Float64Array)writeVarUint(86,192),writeTypeAndLength(2,t.byteLength),writeUint8Array(new Uint8Array(t.buffer));else if(ArrayBuffer.isView(t))e=new Uint8Array(t.buffer),writeTypeAndLength(2,e.length),writeUint8Array(e);else if(t instanceof ArrayBuffer||"function"==typeof SharedArrayBuffer&&t instanceof SharedArrayBuffer)e=new Uint8Array(t),writeTypeAndLength(2,e.length),writeUint8Array(e);else if(t instanceof TaggedValue)writeVarUint(t.tag,192),encodeItem(t.value);else if(t instanceof SimpleValue)writeTypeAndLength(7,t.value);else if(t instanceof Sequence){if(0!==s)throw new Error("CBORError: A CBOR Sequence may not be nested.");const e=t.size;for(let i=0;i<e;i+=1)encodeItem(t.get(i))}else!function writeDictionary(t){const e=[],i=s;let n=s,r=0,a=0;if(t instanceof Map){r=t.size,writeTypeAndLength(5,r),n=s;for(const[i,n]of t.entries()){const t=replacerFunction(i,n);if(t===OMIT_VALUE)continue;let r=s;encodeItem(i);const c=o.slice(r,s);r=s,encodeItem(t);const d=o.slice(r,s);a+=1,e.push([c,d])}}else{const i=Object.keys(t);r=i.length,writeTypeAndLength(5,r),n=s;for(let n=0;n<r;n+=1){const r=i[n],c=replacerFunction(r,t[r]);if(c===OMIT_VALUE)continue;let d=s;encodeItem(r);const l=o.slice(d,s);d=s,encodeItem(c);const u=o.slice(d,s);a+=1,e.push([l,u])}}function sortEncodedKeys(t){s=i,writeTypeAndLength(5,a),e.sort((([t],[e])=>lexicographicalCompare(t,e)));for(let i=0;i<t;i+=1){const[t,n]=e[i];writeUint8Array(t),writeUint8Array(n)}}if(r>a){const t=e.length;if(t>1)sortEncodedKeys(t);else{const t=o.slice(n,s);s=i,writeTypeAndLength(5,a),writeUint8Array(t)}}else{const t=e.length;t>1&&sortEncodedKeys(t)}}(t)}}}}if(encodeItem(replacerFunction(EMPTY_KEY,t)),"slice"in n)return n.slice(0,s);const a=new ArrayBuffer(s),c=new DataView(a);for(let t=0;t<s;++t)c.setUint8(t,r.getUint8(t));return a}function binarify(t,e){return encode(t,e)}const CBOR$1={binarify:binarify,decode:decode,encode:encode,parse:parse};class CBOR{static encode(t){const e=CBOR$1.encode(t);return new Uint8Array(e)}static decode(t,e){const i=t.buffer;return CBOR$1.decode(i,e)}}class DocumentID{get value(){let t=this["@ditto.value"];return void 0===t&&(t=CBOR.decode(this["@ditto.cbor"]),this["@ditto.value"]=t),t}constructor(t,e=!1,i=!1){const n=e?t:CBOR.encode(t),r=i?n:validateDocumentIDCBOR(n);if(!r)throw new Error(`Can't create DocumentID, passed in value is not valid: ${t}`);this.isValidated=!i,this["@ditto.cbor"]=r}equals(t){const e=this["@ditto.cbor"],i=t["@ditto.cbor"];if(e===i)return!0;if(!(e instanceof Uint8Array))return!1;if(!(i instanceof Uint8Array))return!1;if(e.length!==i.length)return!1;for(let t=0;t<e.length;t+=1)if(e[t]!==i[t])return!1;return!0}toString(){return documentIDQueryCompatible(this["@ditto.cbor"],"WithoutQuotes")}toBase64String(){return mapFFIErrors((()=>base64encode(this["@ditto.cbor"],"Padded")))}toQueryCompatibleString(){return documentIDQueryCompatible(this["@ditto.cbor"],"WithQuotes")}toCBOR(){return this["@ditto.cbor"]}}function validateDocumentIDValue(t){if(void 0===t)throw new Error(`Invalid document ID: ${t}`);return t}function validateDocumentIDCBOR(t){const e=validateDocumentID(t);return null!=e?e:t}class Observer{get token(){return this._token}constructor(t,e,i={}){this.observerManager=t,this._token=e,this.options=i,i.stopsWhenFinalized&&Observer.finalizationRegistry.register(this,{observerManager:t,token:e},this)}get isStopped(){return void 0!==this.token&&this.observerManager.hasObserver(this.token)}stop(){const t=this.token;t&&(delete this._token,Observer.finalizationRegistry.unregister(this),this.observerManager.removeObserver(t))}static finalize(t){const{observerManager:e,token:i}=t;e.removeObserver(i)}}Observer.finalizationRegistry=new FinalizationRegistry(Observer.finalize);class Diff{constructor(t){const e=CBOR.decode(t);this.insertions=e.insertions,this.deletions=e.deletions,this.updates=e.updates,this.moves=e.moves.map((([t,e])=>({from:t,to:e})))}}class Differ{constructor(){const t=differNew();return Bridge.differ.bridge(t,this)}diff(t){const e=t.map((t=>t.deref())),i=differDiff(this.deref(),e);return new Diff(i)}deref(){return Bridge.differ.handleFor(this).deref()}}class ObserverManager{constructor(t,e={}){var i,n,r,o;const s=null!==(i=e.keepAlive)&&void 0!==i?i:null,a=null!==(n=e.register)&&void 0!==n?n:null,c=null!==(r=e.unregister)&&void 0!==r?r:null,d=null!==(o=e.process)&&void 0!==o?o:null;this.id=t,this.keepAlive=s,this.isClosed=!1,this.isRegistered=!1,this.callbacksByToken={},null!==a&&(this.register=a),null!==c&&(this.unregister=c),null!==d&&(this.process=d)}addObserver(t){var e;if(this.isClosed)throw new Error(`Internal inconsistency, can't add '${this.id}' observer, observer mananger close()-ed.`);this.registerIfNeeded();const i=cryptoGenerateSecureRandomToken();return this.callbacksByToken[i]=t,null===(e=this.keepAlive)||void 0===e||e.retain(`${this.id}.${i}`),i}removeObserver(t){var e;const i=this.callbacksByToken[t];if(void 0===i)throw new Error(`Can't remove '${this.id}' observer, token '${t}' has never been registered before.`);null!==i&&(this.callbacksByToken[t]=null,null===(e=this.keepAlive)||void 0===e||e.release(`${this.id}.${t}`),this.unregisterIfNeeded())}hasObserver(t){return void 0!==this.callbacksByToken[t]}notify(...t){if(this.isClosed)return;const e=this.process(...t);for(const t in this.callbacksByToken){const i=this.callbacksByToken[t];if(i)try{i(...e)}catch(t){Logger.error(`Uncaught error in ${this.id} observer callback: ${t}`)}}}close(){this.isClosed=!0;for(const t in this.callbacksByToken)this.removeObserver(t)}register(t){}unregister(){}process(...t){return t}hasObservers(){return Object.keys(this.callbacksByToken).length>0}registerIfNeeded(){if(!this.isRegistered){const t=new WeakRef(this);this.isRegistered=!0,this.register((function(...e){const i=t.deref();i&&i.notify(...e)}))}}unregisterIfNeeded(){!this.hasObservers()&&this.isRegistered&&(this.isRegistered=!1,this.unregister())}}function authenticationStatusFromFFI(t){const e=authenticationStatusIsAuthenticated(t),i=authenticationStatusUserID(t);return authenticationStatusFree(t),{isAuthenticated:e,userID:i}}class Authenticator{static get DEVELOPMENT_PROVIDER(){return DITTO_DEVELOPMENT_PROVIDER()}get expirationHandler(){throw new Error("Authenticator.expirationHandler is only available when using a DittoConfig with a ConfigConnectServer.")}async setExpirationHandler(t){throw new Error("Authenticator.expirationHandler is only available when using a DittoConfig with a ConfigConnectServer.")}get status(){return this._status}async login(t,e){if("string"!=typeof t)throw new TypeError(`Expected parameter token to have type string, but got '${typeof t}'`);if("string"!=typeof e)throw new TypeError(`Expected parameter provider to have type string, but got '${typeof e}'`);throw new Error("Authenticator.login() is abstract and must be implemented by subclasses.")}loginWithToken(t,e){if("string"!=typeof t)throw new TypeError(`Expected parameter token to have type string, but got '${typeof t}'`);if("string"!=typeof e)throw new TypeError(`Expected parameter provider to have type string, but got '${typeof e}'`);throw new Error("Authenticator.loginWithToken() is abstract and must be implemented by subclasses.")}loginWithUsernameAndPassword(t,e,i){if("string"!=typeof t)throw new TypeError(`Expected parameter username to have type string, but got '${typeof t}'`);if("string"!=typeof e)throw new TypeError(`Expected parameter password to have type string, but got '${typeof e}'`);if("string"!=typeof i)throw new TypeError(`Expected parameter provider to have type string, but got '${typeof i}'`);throw new Error("Authenticator.loginWithUsernameAndPassword() is abstract and must be implemented by subclasses.")}logout(t){if(void 0!==t&&"function"!=typeof t)throw new TypeError(`Expected parameter cleanupFn to have type function, but got '${typeof t}'`);throw new Error("Authenticator.logout() is abstract and must be implemented by subclasses.")}observeStatus(t){if("function"!=typeof t)throw new TypeError(`Expected parameter callback to have type function, but got '${typeof t}'`);const e=this.observerManager.addObserver(t);return new Observer(this.observerManager,e,{stopsWhenFinalized:!0})}constructor(t){this.keepAlive=t,this._status={isAuthenticated:!1,userID:null},this.loginSupported=!1,this.observerManager=new ObserverManager("AuthenticationStatusObservation",{keepAlive:t})}"@ditto.authenticationExpiring"(t){throw new Error("Authenticator['@ditto.authenticationExpiring']() is abstract and must be implemented by subclasses.")}close(){this.observerManager.close()}}class OnlineAuthenticator extends Authenticator{async login(t,e){if("string"!=typeof t)throw new TypeError(`Expected parameter token to have type string, but got '${typeof t}'`);if("string"!=typeof e)throw new TypeError(`Expected parameter provider to have type string, but got '${typeof e}'`);const i=this.ditto.deref();if(!i||i.isClosed)throw new DittoError("authentication/failed-to-authenticate","Ditto instance is closed");return i.deferCloseAsync((async i=>{const{clientInfo:n,error:r}=await dittoAuthClientLoginWithTokenAndFeedback(i.deref(),t,e);return{clientInfo:n,error:null!=r?DittoError.fromFFIError(r,"authentication/failed-to-authenticate"):null}}))}async loginWithToken(t,e){if("string"!=typeof t)throw new TypeError(`Expected parameter token to have type string, but got '${typeof t}'`);if("string"!=typeof e)throw new TypeError(`Expected parameter provider to have type string, but got '${typeof e}'`);const i=this.ditto.deref();if(i&&!i.isClosed)return i.deferCloseAsync((async i=>{await dittoAuthClientLoginWithToken(i.deref(),t,e)}))}async loginWithUsernameAndPassword(t,e,i){if("string"!=typeof t)throw new TypeError(`Expected parameter username to have type string, but got '${typeof t}'`);if("string"!=typeof e)throw new TypeError(`Expected parameter password to have type string, but got '${typeof e}'`);if("string"!=typeof i)throw new TypeError(`Expected parameter provider to have type string, but got '${typeof i}'`);const n=this.ditto.deref();if(n&&!n.isClosed)return n.deferCloseAsync((async n=>{await dittoAuthClientLoginWithUsernameAndPassword(n.deref(),t,e,i)}))}async logout(t){if(void 0!==t&&"function"!=typeof t)throw new TypeError(`Expected parameter cleanupFn to have type function, but got '${typeof t}'`);const e=this.ditto.deref();if(e&&!e.isClosed)return e.deferCloseAsync((async i=>{await dittoAuthClientLogout(i.deref()),e.stopSync(),null==t||t(e)}))}constructor(t,e,i){super(t),this.loginSupported=!0,this._status={isAuthenticated:!1,userID:null},this.ditto=new WeakRef(e),this.authenticationHandler=i;const n=new WeakRef(this);e.deferClose((t=>{dittoSetAuthenticationStatusHandler(t.deref(),(function(t){const e=n.deref();if(null==e)return void Logger.info("Authenticator is null, ignoring authentication status change");const i=authenticationStatusFromFFI(t);e.authenticationStatusUpdated(i)}))})),this.updateAndNotify(!1)}"@ditto.authenticationExpiring"(t){const e=this.ditto.deref();if(!(null!==e&&e.configOrParameters.isParameters))return void e.deferCloseAsync((async()=>{try{await this.expirationHandler(e,t)}catch(t){Logger.error(`Authentication expiration handler failed: ${t.message}`)}}));const i=this.authenticationHandler;t>0?i.authenticationExpiringSoon(this,t):i.authenticationRequired(this)}authenticationStatusUpdated(t){var e;const i=this.status;this._status=t;!!i.isAuthenticated==!!t.isAuthenticated&&i.userID===t.userID||(null===(e=this.authenticationHandler.authenticationStatusDidChange)||void 0===e||e.call(this.authenticationHandler,this),this.observerManager.notify(t))}updateAndNotify(t){const e=this.ditto.deref();if(!e)return void Logger.debug("Unable to update auth status and notify, related Ditto object does not exist anymore.");const i=Bridge.ditto.handleFor(e).derefOrNull();if(!i)return void Logger.debug("Unable to update auth status and notify, related Ditto object does not exist anymore.");const n={isAuthenticated:dittoAuthClientIsWebValid(i),userID:dittoAuthClientUserID(i)};t?this.authenticationStatusUpdated(n):this._status=n}}class OnlineAuthenticatorV2 extends Authenticator{get expirationHandler(){const t=this.ditto.deref();return!t||t.isClosed?(Logger.error("Ditto instance is closed, cannot get authentication expiration handler."),null):this._expirationHandler}async setExpirationHandler(t){if(null!==t&&"function"!=typeof t)throw new TypeError(`Expected parameter handler to have type function or null, but got '${typeof t}'`);const e=this.ditto.deref();return e&&!e.isClosed||Logger.error("Ditto instance is closed, cannot set authentication expiration handler."),this._expirationHandler=t,e.deferCloseAsync((async t=>{try{const e=dittoAuthClientMakeLoginProvider(this.makeFFFIAuthenticationExpirationHandler());await dittoAuthSetLoginProvider(t.deref(),e)}catch(t){Logger.error(`Failed to set authentication expiration handler: ${t.message}`)}}))}constructor(t,e){if(super(t),this._expirationHandler=null,e.configOrParameters.isParameters)throw new Error("OnlineAuthenticatorV2 can only be used with the new DittoConfig-based API.");this.loginSupported="server"===e.config.connect.mode,this.ditto=new WeakRef(e);const i=new WeakRef(this);e.deferClose((t=>{dittoSetAuthenticationStatusHandler(t.deref(),(function(t){const e=i.deref();if(null==e)return void Logger.info("Authenticator is null, ignoring authentication status change");const n=authenticationStatusFromFFI(t);e.authenticationStatusUpdated(n)}))})),this.updateAndNotify(!1)}async login(t,e){if("string"!=typeof t)throw new TypeError(`Expected parameter token to have type string, but got '${typeof t}'`);if("string"!=typeof e)throw new TypeError(`Expected parameter provider to have type string, but got '${typeof e}'`);const i=this.ditto.deref();if(!i||i.isClosed)throw new DittoError("authentication/failed-to-authenticate","Ditto instance is closed");return i.deferCloseAsync((async i=>{const{clientInfo:n,error:r}=await dittoAuthClientLoginWithTokenAndFeedback(i.deref(),t,e);return{clientInfo:n,error:null!=r?DittoError.fromFFIError(r,"authentication/failed-to-authenticate"):null}}))}async loginWithToken(t,e){if("string"!=typeof t)throw new TypeError(`Expected parameter token to have type string, but got '${typeof t}'`);if("string"!=typeof e)throw new TypeError(`Expected parameter provider to have type string, but got '${typeof e}'`);const i=this.ditto.deref();if(i&&!i.isClosed)return i.deferCloseAsync((async i=>{await dittoAuthClientLoginWithToken(i.deref(),t,e)}))}async loginWithUsernameAndPassword(t,e,i){if("string"!=typeof t)throw new TypeError(`Expected parameter username to have type string, but got '${typeof t}'`);if("string"!=typeof e)throw new TypeError(`Expected parameter password to have type string, but got '${typeof e}'`);if("string"!=typeof i)throw new TypeError(`Expected parameter provider to have type string, but got '${typeof i}'`);const n=this.ditto.deref();if(n&&!n.isClosed)return n.deferCloseAsync((async n=>{await dittoAuthClientLoginWithUsernameAndPassword(n.deref(),t,e,i)}))}async logout(t){if(void 0!==t&&"function"!=typeof t)throw new TypeError(`Expected parameter cleanupFn to have type function, but got '${typeof t}'`);const e=this.ditto.deref();if(e&&!e.isClosed)return e.deferCloseAsync((async i=>{await dittoAuthClientLogout(i.deref()),e.stopSync(),null==t||t(e)}))}authenticationStatusUpdated(t){const e=this.status;this._status=t;!!e.isAuthenticated==!!t.isAuthenticated&&e.userID===t.userID||this.observerManager.notify(t)}updateAndNotify(t){const e=this.ditto.deref();if(!e)return void Logger.debug("Unable to update auth status and notify, related Ditto object does not exist anymore.");const i=Bridge.ditto.handleFor(e).derefOrNull();if(!i)return void Logger.debug("Unable to update auth status and notify, related Ditto object does not exist anymore.");const n={isAuthenticated:dittoAuthClientIsWebValid(i),userID:dittoAuthClientUserID(i)};t?this.authenticationStatusUpdated(n):this._status=n}makeFFFIAuthenticationExpirationHandler(){const t=new WeakRef(this);return e=>{const i=t.deref();if(!i)return;const n=i.ditto.deref();n&&(null!=i.expirationHandler?n.deferCloseAsync((async()=>{try{await i.expirationHandler(n,e)}catch(t){Logger.error(`The authentication handler set via \`ditto.auth.setExpirationHandler()\` failed: ${t.message}`)}})):Logger.error("Authentication required but no expiration handler is set. Please set an expiration handler using `ditto.auth.setExpirationHandler()`."))}}}class NotAvailableAuthenticator extends Authenticator{async login(t,e){throw new Error("Can't login, authentication is not supported for the identity in use, please use an onlineWithAuthentication identity.")}async loginWithToken(t,e){throw new Error("Can't login, authentication is not supported for the identity in use, please use an onlineWithAuthentication identity.")}async loginWithUsernameAndPassword(t,e,i){throw new Error("Can't login, authentication is not supported for the identity in use, please use an onlineWithAuthentication identity.")}logout(t){throw new Error("Can't logout, authentication is not supported for the identity in use, please use an onlineWithAuthentication identity.")}"@ditto.authenticationExpiring"(t){throw new Error(`Internal inconsistency, authentication is not available, yet the @ditto.authenticationExpiring() was called on authenticator: ${this}`)}}const IdentityTypesRequiringOfflineLicenseToken=["manual","sharedKey","offlinePlayground"];function makeIdentityConfig(t){var e,i,n;if("offlinePlayground"===t.type)return dittoIdentityConfigMakeOfflinePlayground(t.appID,null!==(e=t.siteID)&&void 0!==e?e:0);if("manual"===t.type)throw new Error("Manual Identify is currently not implemented for React Native.");if("sharedKey"===t.type)return dittoIdentityConfigMakeSharedKey(t.appID,t.sharedKey,t.siteID);if("onlinePlayground"===t.type){const e=null!==(i=t.customAuthURL)&&void 0!==i?i:defaultAuthURL(t.appID);return dittoIdentityConfigMakeOnlinePlayground(t.appID,t.token,e)}if("onlineWithAuthentication"===t.type){const e=null!==(n=t.customAuthURL)&&void 0!==n?n:defaultAuthURL(t.appID);return dittoIdentityConfigMakeOnlineWithAuthentication(t.appID,e)}}const DEFAULT_IDENTITY={type:"offlinePlayground",appID:""};class DittoConfig{static get DEFAULT_DATABASE_ID(){return DEFAULT_DATABASE_ID()}static get default(){const t=dittoConfigDefault();return fromFFICBORData(CBOR.decode(t))}constructor(t,e,i){if(this._isFrozen=!1,loggerInit(),"string"!=typeof t)throw new TypeError("Expected id to be a string, but got: "+typeof t);if("object"!=typeof e)throw new TypeError("Expected connect to be an object, but got: "+typeof e);if(null!=i&&"string"!=typeof i)throw new TypeError("Expected persistenceDirectory to be undefined or a string, but got: "+typeof i);this.databaseID=t,this.connect=e,this.persistenceDirectory=i,this.validate()}get isFrozen(){return this._isFrozen}freeze(){return this.isFrozen||(this._isFrozen=!0,Object.freeze(this.connect),Object.freeze(this)),this}copy(){return new DittoConfig(this.databaseID,{...this.connect},this.persistenceDirectory)}toCBOR(){try{const t=toFFICBORData(this);return CBOR.encode(t)}catch(t){throw new DittoError("validation/invalid-ditto-config",`Failed to convert DittoConfig to CBOR: ${t.message}`)}}validate(){if(!this.databaseID)throw new DittoError("validation/invalid-ditto-config","`id` must be provided for DittoConfig.");if("string"!=typeof this.databaseID)throw new DittoError("validation/invalid-ditto-config",`\`id\` must be of type string, but is of type '${typeof this.databaseID}': ${this.databaseID}`);if(!this.connect)throw new DittoError("validation/invalid-ditto-config","`connect` must be provided for DittoConfig.");if("object"!=typeof this.connect)throw new DittoError("validation/invalid-ditto-config",`\`connect\` must be an object, but is of type '${typeof this.connect}'.`)}}function toFFICBORData(t){var e;let i;if("server"===t.connect.mode)i={type:"server",url:t.connect.url};else{if("smallPeersOnly"!==t.connect.mode)throw new DittoError("validation/invalid-ditto-config",`Unsupported connect mode: ${t.connect.mode}`);i={type:"small_peers_only"},t.connect.privateKey&&(i.private_key=t.connect.privateKey)}return{database_id:t.databaseID,connect:i,persistence_directory:null!==(e=t.persistenceDirectory)&&void 0!==e?e:null,experimental:{}}}function fromFFICBORData(t){let e;return"server"===t.connect.type?e={mode:"server",url:t.connect.url}:(e={mode:"smallPeersOnly"},t.connect.private_key&&(e.privateKey=t.connect.private_key)),new DittoConfig(t.database_id,e,t.persistence_directory)}const AUTH_HANDLER_NOOP={authenticationRequired(t){},authenticationExpiringSoon(t,e){},authenticationStatusDidChange(t){}},DEFAULT_PERSISTENCE_DIRECTORY="ditto";class ConfigOrParameters{get isConfig(){return void 0!==this._config}get isParameters(){return void 0!==this._parameters}get kind(){if(this.isConfig&&!this.isParameters)return"config";if(this.isParameters&&!this.isConfig)return"parameters";throw new DittoError("internal","ConfigOrParameters is neither a config nor parameters")}get config(){switch(this.kind){case"config":return this._config;case"parameters":const t=this._parameters.identity;switch(t.type){case"onlineWithAuthentication":case"onlinePlayground":return new DittoConfig(t.appID,{mode:"server",url:this.urlFrom(t.customAuthURL,t.appID)},this._parameters.persistenceDirectory);case"sharedKey":return new DittoConfig(t.appID,{mode:"smallPeersOnly",privateKey:t.sharedKey},this._parameters.persistenceDirectory);case"offlinePlayground":return new DittoConfig(t.appID,{mode:"smallPeersOnly"},this._parameters.persistenceDirectory);case"manual":return Logger.warning("Can't create a `DittoConfig` from a `manual` identity, manual identities are being phased out and not supported with the `DittoConfig`-based APIs anymore. Mapping onto `{ mode: 'smallPeersOnly' }`."),new DittoConfig(DittoConfig.DEFAULT_DATABASE_ID,{mode:"smallPeersOnly"},this._parameters.persistenceDirectory)}}}get identity(){switch(this.kind){case"parameters":return this._parameters.identity;case"config":const{databaseID:t,connect:e}=this._config;switch(e.mode){case"server":return{type:"onlineWithAuthentication",appID:t,authHandler:AUTH_HANDLER_NOOP,enableDittoCloudSync:!1,customAuthURL:e.url};case"smallPeersOnly":return e.privateKey?{type:"sharedKey",appID:t,sharedKey:e.privateKey}:{type:"offlinePlayground",appID:t}}}}get persistenceDirectory(){switch(this.kind){case"parameters":return this._parameters.persistenceDirectory;case"config":return this._config.persistenceDirectory}}constructor(t,e){if(this.passphrase=null,this.historyTrackingEnabled=!1,t instanceof DittoConfig)this._config=t,this._parameters=void 0;else{const i=this.validatePersistenceDirectory(e);this.validateIdentity(t),this._parameters={identity:t,persistenceDirectory:i},this._config=void 0}}redactingSensitiveData(){switch(this.kind){case"config":const t=this._config.copy();return"smallPeersOnly"===t.connect.mode&&null!=t.connect.privateKey&&(t.connect.privateKey="[REDACTED]"),new ConfigOrParameters(t);case"parameters":const e={...this._parameters.identity};return"sharedKey"===e.type&&(e.sharedKey="[REDACTED]"),new ConfigOrParameters(e,this._parameters.persistenceDirectory)}}validateIdentity(t){var e,i;if(!t||"object"!=typeof t)throw new TypeError("Expected `identity` to be an object, but got: "+typeof t);const n={...t},r=t.appID;if(!["offlinePlayground","sharedKey","manual","onlinePlayground","onlineWithAuthentication"].includes(t.type))throw new Error(`Unknown identity type: ${t.type}`);if(("offlinePlayground"===t.type||"sharedKey"===t.type||"onlinePlayground"===t.type||"onlineWithAuthentication"===t.type)&&void 0===r)throw new Error("Property .appID must be given for identity, but isn't.");if(void 0!==r&&"string"!=typeof r)throw new Error(`Property .appID must be be of type string, but is of type '${typeof r}': ${r}`);if(("offlinePlayground"===t.type||"sharedKey"===t.type)&&void 0!==t.siteID){const e=t.siteID;if(!("number"==typeof e||"bigint"==typeof e))throw new Error("siteID must be a number or BigInt");if(e<0)throw new Error("siteID must be >= 0");if(e>BigInt("0xffffffffffffffff"))throw new Error("siteID must be < 2^64")}if("offlinePlayground"===t.type&&void 0!==t.siteID&&Logger.warning("Property .siteID is deprecated and should no longer be specified in an offline playground identity."),"sharedKey"===t.type&&void 0!==t.siteID&&Logger.warning("Property .siteID is deprecated and should no longer be specified in a shared key identity."),t.type,"onlinePlayground"===t.type){const e=t.token;if(void 0===e)throw new Error("Property .token must be given for identity but isn't. You can find the corresponding token on the Ditto Portal.");if(void 0!==e&&"string"!=typeof e)throw new Error(`Property .token of identity must be be of type string, but is of type '${typeof e}': ${e}`)}if("onlineWithAuthentication"===t.type){const n=typeof t.authHandler;if("object"!==n)throw new TypeError(`Property .authHandler on identity of type onlineWithAuthentication must be an object, but is of type '${n}'.`);const r=typeof(null===(e=t.authHandler)||void 0===e?void 0:e.authenticationExpiringSoon),o=typeof(null===(i=t.authHandler)||void 0===i?void 0:i.authenticationRequired);if("function"!==r)throw new TypeError(`Property .authHandler.authenticationExpiringSoon on identity of type onlineWithAuthentication must be a function, but is of type '${r}'.`);if("function"!==o)throw new TypeError(`Property .authHandler.authenticationRequired on identity of type onlineWithAuthentication must be a function, but is of type '${o}'.`)}return n}validatePersistenceDirectory(t){if(null==t)return"ditto";if(0===t.trim().length)throw new Error(`Invalid persistenceDirectory: '${t}'`);return t}urlFrom(t,e){return null!=t?t:`https://${e}.cloud.ditto.live`}}function transportConfigFromDeserializable(t){const e=t.peer_to_peer,i=e.bluetooth_le.enabled,n=e.awdl.enabled,r=e.lan,o=r.enabled,s=r.mdns_enabled,a=r.multicast_enabled,c=e.wifi_aware.enabled,d=t.connect,l=d.tcp_servers,u=d.websocket_urls,f=d.retry_interval,h=t.listen,_=h.tcp,g=_.enabled,p=_.interface_ip,m=_.port,b=h.http,w=b.enabled,v=b.interface_ip,I=b.port,E=b.static_content_path,C=b.websocket_sync,D=b.tls_key_path,A=b.tls_certificate_path,S=t.global,T=S.sync_group,k=S.routing_hint,F=new TransportConfig;return F.peerToPeer.bluetoothLE.isEnabled=i,F.peerToPeer.awdl.isEnabled=n,F.peerToPeer.lan.isEnabled=o,F.peerToPeer.lan.isMdnsEnabled=s,F.peerToPeer.lan.isMulticastEnabled=a,F.peerToPeer.wifiAware.isEnabled=c,F.connect.tcpServers=l,F.connect.websocketURLs=u,F.connect.retryInterval=f,F.listen.tcp.isEnabled=g,F.listen.tcp.interfaceIP=p,F.listen.tcp.port=m,F.listen.http.isEnabled=w,F.listen.http.interfaceIP=v,F.listen.http.port=I,F.listen.http.staticContentPath=E,F.listen.http.websocketSync=C,F.listen.http.tlsKeyPath=D,F.listen.http.tlsCertificatePath=A,F.global.syncGroup=T,F.global.routingHint=k,F}function transportConfigToSerializable(t){const e=t.peerToPeer,i=t.connect,n=t.listen,r=t.global,o={peer_to_peer:{bluetooth_le:{enabled:e.bluetoothLE.isEnabled},awdl:{enabled:e.awdl.isEnabled},wifi_aware:{enabled:e.wifiAware.isEnabled},lan:{enabled:e.lan.isEnabled,mdns_enabled:e.lan.isMdnsEnabled,multicast_enabled:e.lan.isMulticastEnabled}},connect:{tcp_servers:i.tcpServers,websocket_urls:i.websocketURLs,retry_interval:i.retryInterval},listen:{tcp:{enabled:n.tcp.isEnabled,interface_ip:n.tcp.interfaceIP,port:n.tcp.port},http:{enabled:n.http.isEnabled,interface_ip:n.http.interfaceIP,port:n.http.port,websocket_sync:n.http.websocketSync}},global:{sync_group:r.syncGroup,routing_hint:r.routingHint}};return n.http.staticContentPath&&(o.listen.http.static_content_path=n.http.staticContentPath),n.http.tlsKeyPath&&(o.listen.http.tls_key_path=n.http.tlsKeyPath),n.http.tlsCertificatePath&&(o.listen.http.tls_certificate_path=n.http.tlsCertificatePath),o}const NO_PREFERRED_ROUTE_HINT=0;class TransportConfig{constructor(){this._isFrozen=!1,this.peerToPeer={bluetoothLE:{isEnabled:!1},awdl:{isEnabled:!1},lan:{isEnabled:!1,isMdnsEnabled:!0,isMulticastEnabled:!0},wifiAware:{isEnabled:!1}},this.connect={tcpServers:[],websocketURLs:[],retryInterval:5e3},this.listen={tcp:{isEnabled:!1,interfaceIP:"[::]",port:4040},http:{isEnabled:!1,interfaceIP:"[::]",port:80,websocketSync:!0}},this.global={syncGroup:0,routingHint:0}}setAllPeerToPeerEnabled(t){this.peerToPeer.bluetoothLE.isEnabled=t,this.peerToPeer.lan.isEnabled=t,this.peerToPeer.awdl.isEnabled=t,this.peerToPeer.wifiAware.isEnabled=t}setAvailablePeerToPeerEnabled(t){const e="android"===rnOnlyGetPlatform(),i="ios"===rnOnlyGetPlatform(),n="macos"===rnOnlyGetPlatform();this.peerToPeer.bluetoothLE.isEnabled=t,this.peerToPeer.lan.isEnabled=t,this.peerToPeer.wifiAware.isEnabled=!!e&&t,this.peerToPeer.awdl.isEnabled=!(!i&&!n)&&t}get isFrozen(){return this._isFrozen}freeze(){return this.isFrozen||(this._isFrozen=!0,Object.freeze(this.peerToPeer.bluetoothLE),Object.freeze(this.peerToPeer.awdl),Object.freeze(this.peerToPeer.lan),Object.freeze(this.peerToPeer.wifiAware),Object.freeze(this.peerToPeer),Object.freeze(this.connect.tcpServers),Object.freeze(this.connect.websocketURLs),Object.freeze(this.connect),Object.freeze(this.listen.tcp),Object.freeze(this.listen.http),Object.freeze(this.listen),Object.freeze(this.global),Object.freeze(this)),this}copy(){const t=new TransportConfig;return t.peerToPeer.bluetoothLE.isEnabled=this.peerToPeer.bluetoothLE.isEnabled,t.peerToPeer.awdl.isEnabled=this.peerToPeer.awdl.isEnabled,t.peerToPeer.lan.isEnabled=this.peerToPeer.lan.isEnabled,t.peerToPeer.lan.isMdnsEnabled=this.peerToPeer.lan.isMdnsEnabled,t.peerToPeer.lan.isMulticastEnabled=this.peerToPeer.lan.isMulticastEnabled,t.peerToPeer.wifiAware.isEnabled=this.peerToPeer.wifiAware.isEnabled,t.connect.tcpServers=this.connect.tcpServers.slice(),t.connect.websocketURLs=this.connect.websocketURLs.slice(),t.connect.retryInterval=this.connect.retryInterval,t.listen.tcp={...this.listen.tcp},t.listen.http={...this.listen.http},t.global.syncGroup=this.global.syncGroup,t.global.routingHint=this.global.routingHint,t}static areListenTCPsEqual(t,e){return t.isEnabled===e.isEnabled&&t.interfaceIP===e.interfaceIP&&t.port===e.port}static areListenHTTPsEqual(t,e){return t.isEnabled===e.isEnabled&&t.interfaceIP===e.interfaceIP&&t.port===e.port&&t.staticContentPath===e.staticContentPath&&t.websocketSync===e.websocketSync&&t.tlsKeyPath===e.tlsKeyPath&&t.tlsCertificatePath===e.tlsCertificatePath}}const privateToken$1=Symbol("privateConstructorToken");class Counter{get value(){return this._value}constructor(){this._value=0}static"@ditto.create"(t,e,i){const n=t?new MutableCounter(privateToken$1):new Counter;return n.mutDoc=t,n.path=e,n._value=i,n}}class MutableCounter extends Counter{increment(t){throw new Error("This API is not available in React Native environments. Please use 'ditto.store.registerObserver(…)' instead. For more details and guidance, visit: https://ditto.com/link/dql.")}constructor(){if(arguments[0]!==privateToken$1)throw new Error("MutableCounter constructor is for internal use only.");super()}}const privateToken="@ditto.ff82dae89821c5ab822a8b539056bce4";class Register{get value(){return this["@ditto.value"]}constructor(t){this["@ditto.value"]=t}static"@ditto.create"(t,e,i){const n=t?new MutableRegister(i,privateToken):new Register(i);return n["@ditto.mutableDocument"]=t,n["@ditto.path"]=e,n["@ditto.value"]=i,n}}class MutableRegister extends Register{get value(){return super.value}set value(t){this.set(t)}set(t){const e=this["@ditto.mutableDocument"],i=this["@ditto.path"];e.at(i)["@ditto.set"](t),this["@ditto.value"]=t}constructor(t){if(arguments[1]!==privateToken)throw new Error("MutableRegister constructor is for internal use only.");super(t)}}function desugarJSObject(t){if(t&&"object"==typeof t){if(Array.isArray(t))return t.map(((t,e)=>desugarJSObject(t)));if(t instanceof DocumentID)return t.value;if(t instanceof Counter){const e={};return e[DittoCRDTTypeKey]=DittoCRDTType.counter,e._value=t.value,e}if(t instanceof Register){const e={};return e[DittoCRDTTypeKey]=DittoCRDTType.register,e._value=t.value,e}if(t instanceof Attachment){const e={_id:t.token.idBytes,_len:t.token.len,_meta:t.token.metadata};return e[DittoCRDTTypeKey]=DittoCRDTType.attachment,e}{const e={};for(const[i,n]of Object.entries(t))e[i]=desugarJSObject(n);return e}}return checkForUnsupportedValues(t),t}function checkForUnsupportedValues(t){if(Number.isNaN(t)||t===1/0||t===-1/0)throw new Error("Non-finite float values are not supported")}const CUSTOM_INSPECT_SYMBOL$1=Symbol.for("nodejs.util.inspect.custom");class Document{static hash(t){throw new Error("This API is not available in React Native environments. Please use 'ditto.store.registerObserver(…)' instead. For more information see: https://ditto.com/link/dql-legacy-to-dql-adoption")}static hashMnemonic(t){throw new Error("This API is not available in React Native environments. Please use 'ditto.store.registerObserver(…)' instead. For more information see: https://ditto.com/link/dql-legacy-to-dql-adoption")}get id(){throw new Error("This API is not available in React Native environments. Please use 'ditto.store.registerObserver(…)' instead. For more information see: https://ditto.com/link/dql-legacy-to-dql-adoption")}get path(){throw new Error("This API is not available in React Native environments. Please use 'ditto.store.registerObserver(…)' instead. For more information see: https://ditto.com/link/dql-legacy-to-dql-adoption")}get value(){throw new Error("This API is not available in React Native environments. Please use 'ditto.store.registerObserver(…)' instead. For more information see: https://ditto.com/link/dql-legacy-to-dql-adoption")}at(t){throw new Error("This API is not available in React Native environments. Please use 'ditto.store.registerObserver(…)' instead. For more information see: https://ditto.com/link/dql-legacy-to-dql-adoption")}constructor(){}static idCBOR(t){return documentID(Bridge.document.handleFor(t).deref())}static canonicalizedIDCBOR(t){return validateDocumentIDCBOR(t)}static isIDCBORCanonical(t){return t===this.canonicalizedIDCBOR(t)}toString(){return`${this.constructor.name}(${this.id})`}[CUSTOM_INSPECT_SYMBOL$1](t,e,i){return customInspectRepresentation(this,i)}}class MutableDocument{get id(){throw new Error("This API is not available in React Native environments. Please use 'ditto.store.registerObserver(…)' instead. For more information see: https://ditto.com/link/dql-legacy-to-dql-adoption")}get path(){throw new Error("This API is not available in React Native environments. Please use 'ditto.store.registerObserver(…)' instead. For more information see: https://ditto.com/link/dql-legacy-to-dql-adoption")}get value(){throw new Error("This API is not available in React Native environments. Please use 'ditto.store.registerObserver(…)' instead. For more information see: https://ditto.com/link/dql-legacy-to-dql-adoption")}at(t){throw new Error("This API is not available in React Native environments. Please use 'ditto.store.registerObserver(…)' instead. For more information see: https://ditto.com/link/dql-legacy-to-dql-adoption")}constructor(){this["@ditto.updateResults"]=[]}static idCBOR(t){return documentID(Bridge.mutableDocument.handleFor(t).deref())}toString(){return`${this.constructor.name}(${this.id})`}[CUSTOM_INSPECT_SYMBOL$1](t,e,i){return customInspectRepresentation(this,i)}}MutableDocument.canonicalizedIDCBOR=Document.canonicalizedIDCBOR,MutableDocument.isIDCBORCanonical=Document.isIDCBORCanonical;class QueryResult{mutatedDocumentIDs(){return queryResultMutatedDocumentIDs(Bridge.queryResult.handleFor(this).deref()).map((t=>new DocumentID(t,!0)))}mutatedDocumentIDsV2(){return queryResultMutatedDocumentIDs(Bridge.queryResult.handleFor(this).deref()).map((t=>CBOR.decode(t)))}get commitID(){const t=Bridge.queryResult.handleFor(this);return queryResultHasCommitID(t.deref())?queryResultCommitID(t.deref()):null}constructor(t){if(null==t)throw new Error("Internal inconsistency, failed to initialize query result without a response pointer");const e=queryResultItems(t);this.items=e.map((t=>Bridge.queryResultItem.bridge(t)))}}class StoreObserver{get isCancelled(){return this._isCancelled}cancel(){this._isCancelled||(this._isCancelled=!0,this.ditto.store.unregisterObserver(this))}constructor(t,e,i,n){this._isCancelled=!1,this.queryString=e,this.queryArguments=i?Object.freeze({...i}):void 0,this.ditto=t;let r,o=null;if(null!=i)try{const t=desugarJSObject(i);o=CBOR.encode(t)}catch(t){throw new DittoError("query/arguments-invalid")}if(this.ditto.deferClose((t=>{const i=new WeakRef(this);function wrappedObservationHandler(t){const e=i.deref();if(null==e)return void Logger.debug(`Ignoring change event received by store observer ${r} after it was cancelled`);const o=Bridge.queryResult.bridge(t.query_result,(()=>new QueryResult(t.query_result)));Logger.debug(`Invoking user event handler with new event for store observer ${r}`),n(o,(()=>e.signalNext()))}mapFFIErrors((()=>{r=tryExperimentalRegisterChangeObserver(t.deref(),e,o,wrappedObservationHandler)}))})),null==r)throw new DittoError("internal","Internal inconsistency, store observer ID is undefined after registering");this.liveQueryID=r}async signalNext(){const t=this.ditto;if(t&&!t.isClosed){if(null==this.liveQueryID)throw new Error("live query ID is null while signaling ready for next event");return t.deferCloseAsync((async t=>{Logger.debug(`Signaling availability for live query ${this.liveQueryID}`),await liveQuerySignalAvailableNext(t.deref(),this.liveQueryID)}))}}}class TransactionInfo{constructor(t,e,i){this.id=t,this.hint=i,this.isReadOnly=e}}class Transaction{constructor(t){this.store=t}get info(){const t=transactionInfo(Bridge.transaction.handleFor(this).deref()),e=CBOR.decode(t);return new TransactionInfo(e.id,e.is_read_only,e.hint)}async execute(t,e){if("string"!=typeof t)throw new DittoError("query/invalid","Expected parameter 'query' to be of type 'string', found: "+typeof t);return this.store.ditto.deferCloseAsync((async()=>{let i=null;if(e)try{const t=desugarJSObject(e);i=CBOR.encode(t)}catch(t){throw new DittoError("query/arguments-invalid",`Unable to encode query arguments: ${t.message}`)}const n=Bridge.transaction.handleFor(this),r=await mapFFIErrorsAsync((async()=>transactionExecuteAsync(n.deref(),t,i)));return Bridge.queryResult.bridge(r,(()=>new QueryResult(r)))}))}async complete(t){const e=Bridge.transaction.handleFor(this);return(await mapFFIErrorsAsync((async()=>await transactionCompleteAsync(e.deref(),capitalize(t))))).toLowerCase()}}class Store{get transactions(){return this.ditto.deferClose((t=>{const e=storeTransactions(dittoPointerToStorePointer(t.deref()));return CBOR.decode(e).map((t=>new TransactionInfo(t.id,t.is_read_only,t.hint)))}))}registerObserver(t,e,i){return this.registerObserverWithSignalNext(t,((t,i)=>{try{e(t)}finally{i()}}),i)}registerObserverWithSignalNext(t,e,i){if("string"!=typeof t)throw new DittoError("query/invalid","Expected parameter 'query' to be of type 'string', found: "+typeof t);const n=new StoreObserver(this.ditto,t,null!=i?i:null,e);return this.observers=Object.freeze([...this.observers,n]),this.ditto.deferCloseAsync((async t=>new Promise((e=>{step((async()=>{try{await mapFFIErrorsAsync((async()=>await liveQueryStart(t.deref(),n.liveQueryID)))}catch(t){Logger.error(`Failed to start live query: ${t.message}`)}e()}))})))),n}collection(t){throw new Error("This API is not available in React Native environments. Please use 'ditto.store.registerObserver(…)' instead. For more information see: https://ditto.com/link/dql-legacy-to-dql-adoption")}collections(){throw new Error("This API is not available in React Native environments. Please use 'ditto.store.registerObserver(…)' instead. For more information see: https://ditto.com/link/dql-legacy-to-dql-adoption")}collectionNames(){throw new Error("This API is not available in React Native environments. Please use 'ditto.store.registerObserver(…)' instead. For more information see: https://ditto.com/link/dql-legacy-to-dql-adoption")}async execute(t,e){if("string"!=typeof t)throw new DittoError("query/invalid","Expected parameter 'query' to be of type 'string', found: "+typeof t);return this.ditto.deferCloseAsync((async i=>{let n=null;if(null!=e)try{const t=desugarJSObject(e);n=CBOR.encode(t)}catch(t){throw new DittoError("query/arguments-invalid",`Unable to encode query arguments: ${t.message}`)}const r=await mapFFIErrorsAsync((async()=>await performAsyncToWorkaroundNonAsyncFFIAPI((()=>tryExecStatement(i.deref(),t,n)))));return Bridge.queryResult.bridge(r,(()=>new QueryResult(r)))}))}async write(t){throw new Error("This API is not available in React Native environments. Please use 'ditto.store.registerObserver(…)' instead. For more information see: https://ditto.com/link/dql-legacy-to-dql-adoption")}async newAttachment(t,e){return null!=e&&validateAttachmentMetadata(e),this.ditto.deferCloseAsync((async i=>{const{id:n,len:r,handle:o}=await(async()=>{if("string"==typeof t)return mapFFIErrors((()=>dittoNewAttachmentFromFile(i.deref(),t,"Copy")),{1:["store/failed-to-create-attachment"],2:["store/attachment-file-not-found"],3:["store/attachment-file-permission-denied"]});if(t instanceof Uint8Array)return mapFFIErrorsAsync((async()=>await dittoNewAttachmentFromBytes(i.deref(),t)),{1:["store/failed-to-create-attachment"]});throw new Error(`Can't create new attachment, only file path as string or raw data as Uint8Array are supported, but got: ${typeof t}, ${t}`)})(),s={_id:n,_len:r,_meta:{...e},[DittoCRDTTypeKey]:DittoCRDTType.attachment},a=new AttachmentToken(s),c=new Attachment(this.ditto,a);return Bridge.attachment.bridge(o,(()=>c))}))}fetchAttachment(t,e){if(null==t)throw new Error("Missing required parameter 'token'");let i;return i=t instanceof AttachmentToken?t:new AttachmentToken(t),this.ditto.deferClose((()=>{const t=new AttachmentFetcher(this.ditto,i,null,e);return this.attachmentFetchers=Object.freeze([...this.attachmentFetchers,t]),t}))}constructor(t){this.observers=Object.freeze([]),this.attachmentFetchers=Object.freeze([]),this.ditto=t}unregisterObserver(t){if(t.ditto!==this.ditto)throw new DittoError("internal","Internal inconsistency, can't remove store observer that does not belong to this store");if(!t.isCancelled)throw new DittoError("internal","Internal inconsistency, can't remove store observer that has not been cancelled");const e=this.observers.findIndex((e=>e===t));if(-1===e)return!1;const i=[...this.observers];i.splice(e,1),this.observers=Object.freeze(i);const n=Bridge.ditto.handleFor(this.ditto);return this.ditto.deferClose((()=>{mapFFIErrors((()=>liveQueryStop(n.deref(),t.liveQueryID)))})),!0}removeAttachmentFetcher(t){if(t.ditto!==this.ditto)throw new DittoError("internal","Internal inconsistency, can't finalize attachment fetcher that does not belong to this store");if(null!=t.manager)throw new DittoError("internal","Internal inconsistency, store can't remove attachment fetcher that is owned by the attachment fetcher manager");if(!t.isStopped)throw new DittoError("internal","Internal inconsistency, can't remove attachment fetcher that has not stopped");const e=this.attachmentFetchers.findIndex((e=>e===t));if(-1===e)return!1;const i=[...this.attachmentFetchers];return i.splice(e,1),this.attachmentFetchers=Object.freeze(i),!0}async transaction(t,e={}){return this.ditto.deferCloseAsync((async()=>{if((null==e?void 0:e.isReadOnly)&&"boolean"!=typeof e.isReadOnly)throw new TypeError("Expected 'options.isReadOnly' to be a boolean");if((null==e?void 0:e.hint)&&"string"!=typeof e.hint)throw new TypeError("Expected 'options.hint' to be a string");const i=await this.beginTransaction(e);let n;try{n=await t(i)}catch(t){throw await i.complete("rollback"),t}return"rollback"===n||"commit"===n?await i.complete(n):(await i.complete("commit"),n)}))}async beginTransaction(t={}){return this.ditto.deferCloseAsync((async e=>{var i,n;const r=null!==(i=t.isReadOnly)&&void 0!==i&&i,o=null!==(n=t.hint)&&void 0!==n?n:null,s=dittoPointerToStorePointer(e.deref()),a=await storeBeginTransaction(s,{isReadOnly:r,hint:o});return Bridge.transaction.bridge(a,(()=>new Transaction(this)))}))}close(){for(const t of this.observers)t.cancel();for(const t of this.attachmentFetchers)t.stop()}}class KeepAlive{get isActive(){return null!==this.intervalID}constructor(){this.countsByID={},this.intervalID=null}retain(t){if(void 0===this.countsByID[t]&&(this.countsByID[t]=0),this.countsByID[t]+=1,null===this.intervalID){const t=2147483647;this.intervalID=setInterval((()=>{}),t),KeepAlive.finalizationRegistry.register(this,this.intervalID,this)}}release(t){if(void 0===this.countsByID[t])throw new Error(`Internal inconsistency, trying to release a keep-alive ID that hasn't been retained before or isn't tracked anymore: ${t}`);this.countsByID[t]-=1,0===this.countsByID[t]&&delete this.countsByID[t],0===Object.keys(this.countsByID).length&&(KeepAlive.finalizationRegistry.unregister(this),clearInterval(this.intervalID),this.intervalID=null)}currentIDs(){return Object.keys(this.countsByID)}countForID(t){var e;return null!==(e=this.countsByID[t])&&void 0!==e?e:null}}function addressToString(t){return`${t.siteId}-${t.pubkey}`}KeepAlive.finalizationRegistry=new FinalizationRegistry(clearInterval);class Presence{get connectionRequestHandler(){return this._connectionRequestHandler}set connectionRequestHandler(t){let e=null;if(null!=t){if("function"!=typeof t)throw new TypeError(`Expected parameter 'handler' to be a function but got ${typeof t} instead`);e=async e=>{const i=Bridge.connectionRequest.bridge(e),n=await t(i);if("allow"!==n&&"deny"!==n)return Logger.error(`The connection request handler must return "allow" or "deny" but returned "${n}" instead. The connection request will be denied.`),"Deny";connectionRequestAuthorize(e,"allow"===n?"Allow":"Deny")}}this._connectionRequestHandler=t;const handleError=t=>{Logger.error(`The connection request handler threw an error while handling a connection request, the connection request will be denied. ${t}`)},i=Bridge.ditto.handleFor(this.ditto);this.ditto.deferClose((()=>{presenceSetConnectionRequestHandler(i.deref(),e,handleError)}))}get graph(){return this.ditto.deferClose((t=>{const e=dittoPresenceV3(t.deref());return JSON.parse(e)}))}get peerMetadataJSONString(){return this.ditto.deferClose((t=>mapFFIErrors((()=>presencePeerMetadataJSON(t.deref())))))}async setPeerMetadataJSONString(t){await this.ditto.deferCloseAsync((async e=>mapFFIErrorsAsync((async()=>presenceTrySetPeerMetadataJSON(e.deref(),t)))))}get peerMetadata(){return JSON.parse(this.peerMetadataJSONString)}async setPeerMetadata(t){let e;try{e=JSON.stringify(t)}catch(t){throw new DittoError("validation/not-json-compatible",`Failed encoding peer metadata to JSON. ${t}`)}await this.setPeerMetadataJSONString(e)}observe(t){if("function"!=typeof t)throw new TypeError(`Expected parameter didChangeHandler to have type function, but got '${typeof t}'`);const e=this.observerManager.addObserver(t),i=new Observer(this.observerManager,e,{stopsWhenFinalized:!0});return t(this.graph),i}constructor(t){this._connectionRequestHandler=null,this.ditto=t,this.observerManager=new ObserverManager("PresenceObservation",{keepAlive:t.keepAlive,register:t=>{this.ditto.deferClose((e=>{dittoRegisterPresenceV3Callback(e.deref(),t)}))},unregister:()=>{t.deferCloseAsync((async t=>dittoClearPresenceV3Callback(t.deref())))},process:t=>[JSON.parse(t)]})}close(){this.observerManager.close()}}class LiveQueryManager{constructor(t,e){this.finalizationRegistry=new FinalizationRegistry(this.finalize),this.ditto=t,this.keepAlive=e,this.liveQueriesByID={}}startLiveQuery(t){this.ditto.deferCloseAsync((async e=>{const i=t.liveQueryID;if(!i)throw new Error("Internal inconsistency, tried to add a live query that doesn't have a live query ID (probably stopped).");if(this.liveQueriesByID[i])throw new Error("Internal inconsistency, tried to add a live query with an ID that has already been added.");const n=new WeakRef(t);return this.liveQueriesByID[i]=n,this.finalizationRegistry.register(t,i,this.finalize),t.liveQueryManager=this,this.ditto.keepAlive.retain(`LiveQuery.${i}`),new Promise(((t,n)=>{step((async()=>{await liveQueryStart(e.deref(),i),t()}))}))}))}stopLiveQuery(t){this.finalizationRegistry.unregister(t);const e=t.liveQueryID;if(!e)throw new Error("Internal inconsistency, tried to remove a live query that doesn't have a live query ID (probably stopped).");t.liveQueryManager=null,this.stopLiveQueryWithID(e)}close(){for(const t in this.liveQueriesByID){const e=this.liveQueriesByID[t].deref();e&&this.stopLiveQuery(e)}}stopLiveQueryWithID(t){this.ditto.deferClose((e=>{liveQueryStop(e.deref(),t),this.keepAlive.release(`LiveQuery.${t}`),delete this.liveQueriesByID[t]}))}finalize(t){this.stopLiveQueryWithID(t)}}class PresenceManager{constructor(t){this.ditto=t,this.isClosed=!1,this.isRegistered=!1,this.currentRemotePeers=[],this.callbacksByPresenceToken={}}addObserver(t){if(this.isClosed)throw new Error("Internal inconsistency, can't add presence observer, observer mananger close()-ed.");this.registerIfNeeded();const e=cryptoGenerateSecureRandomToken();return this.callbacksByPresenceToken[e]=t,this.ditto.keepAlive.retain(`PresenceObservation.${e}`),t(this.currentRemotePeers),e}async removeObserver(t){const e=this.callbacksByPresenceToken[t];if(void 0===e)throw new Error(`Can't remove presence observer, token '${t}' has never been registered before.`);if(null!==e)return void 0!==this.callbacksByPresenceToken[t]?(this.ditto.keepAlive.release(`PresenceObservation.${t}`),this.callbacksByPresenceToken[t]=null,this.unregisterIfNeeded()):void 0}hasObserver(t){return void 0!==this.callbacksByPresenceToken[t]}async close(){this.isClosed=!0;const t=Object.keys(this.callbacksByPresenceToken);return Promise.all(t.map((t=>this.removeObserver(t))))}hasObservers(){return Object.keys(this.callbacksByPresenceToken).length>0}registerIfNeeded(){this.ditto.deferClose((t=>{if(!this.isRegistered){this.isRegistered=!0;const e=dittoPresenceV1(t.deref());this.currentRemotePeers=this.decode(e).sort(this.compareRemotePeers),dittoRegisterPresenceV1Callback(t.deref(),this.handlePresenceV1Callback.bind(this))}}))}unregisterIfNeeded(){return this.ditto.deferCloseAsync((async t=>{!this.hasObservers()&&this.isRegistered&&(this.isRegistered=!1,await dittoClearPresenceCallback(t.deref()),this.currentRemotePeers=[])}))}handlePresenceV1Callback(t){const e=this.decode(t).sort(this.compareRemotePeers);this.currentRemotePeers=e,this.notify()}notify(){if(!this.isClosed)for(const t in this.callbacksByPresenceToken){const e=this.callbacksByPresenceToken[t];e&&e(this.currentRemotePeers)}}decode(t){return JSON.parse(t).map((t=>{var e,i;return{networkID:t.network_id,deviceName:t.device_name,rssi:null!==(e=t.rssi)&&void 0!==e?e:void 0,approximateDistanceInMeters:null!==(i=t.approximate_distance_in_meters)&&void 0!==i?i:void 0,connections:t.connections}}))}compareRemotePeers(t,e){return 0===t.connections.length&&e.connections.length>0?1:t.connections.length>0&&0===e.connections.length||t.deviceName<e.deviceName?-1:t.deviceName>e.deviceName?1:0}}class TransportConditionsManager extends ObserverManager{constructor(t){super("TransportConditionsObservation",{keepAlive:t.keepAlive}),this.ditto=t}register(t){return this.ditto.deferClose((e=>dittoRegisterTransportConditionChangedCallback(e.deref(),t)))}unregister(){return this.ditto.deferClose((t=>dittoRegisterTransportConditionChangedCallback(t.deref(),null)))}process(t,e){let i,n;switch(t){case"Bluetooth":i="BLE";break;case"Tcp":i="TCP";break;case"Awdl":i="AWDL";break;case"Mdns":i="MDNS";break;case"WiFiAware":i="WiFiAware"}switch(e){case"Unknown":n="Unknown";break;case"Ok":n="OK";break;case"GenericFailure":n="GenericFailure";break;case"AppInBackground":n="AppInBackground";break;case"MdnsFailure":n="MDNSFailure";break;case"TcpListenFailure":n="TCPListenFailure";break;case"NoBleCentralPermission":n="NoBLECentralPermission";break;case"NoBlePeripheralPermission":n="NoBLEPeripheralPermission";break;case"CannotEstablishConnection":n="CannotEstablishConnection";break;case"BleDisabled":n="BLEDisabled";break;case"NoBleHardware":n="NoBLEHardware";break;case"WifiDisabled":n="WiFiDisabled";break;case"TemporarilyUnavailable":n="TemporarilyUnavailable"}return[n,i]}}class SyncSubscription{get isCancelled(){return this._isCancelled}cancel(){this._isCancelled||(this._isCancelled=!0,this.ditto.sync.unregisterSubscription(this))}constructor(t,e,i,n){if(this._isCancelled=!1,null==i!=(null==n))throw new DittoError("internal","Internal inconsistency, query arguments and query arguments CBOR must be both null or both non-null",{queryArguments:i,queryArgumentsCBOR:n});this.ditto=t,this.queryString=e,this.queryArguments=i?Object.freeze({...i}):void 0,this.queryArgumentsCBOR=n}}class Sync{get isActive(){return this.ditto.isSyncActive}start(){this.ditto.startSync()}stop(){this.ditto.stopSync()}registerSubscription(t,e){if("string"!=typeof t)throw new DittoError("query/invalid","Expected parameter 'query' to be of type 'string', found: "+typeof t);let i=null;if(null!=e)try{const t=desugarJSObject(e);i=CBOR.encode(t)}catch(t){throw new DittoError("query/arguments-invalid",`Unable to encode query arguments: ${t.message}`)}this.ditto.deferClose((e=>{mapFFIErrors((()=>tryAddSyncSubscription(e.deref(),t,i)))}));const n=new SyncSubscription(this.ditto,t,e||null,i);return this.subscriptions=Object.freeze([...this.subscriptions,n]),n}constructor(t){this.subscriptions=Object.freeze([]),this.ditto=t}unregisterSubscription(t){if(t.ditto!==this.ditto)throw new DittoError("internal","Can't remove replication subscription that does not belong to this store");if(!t.isCancelled)throw new DittoError("internal","Internal inconsistency, can't remove replication subscription that has not been cancelled");const e=this.subscriptions.findIndex((e=>e===t));if(-1===e)return!1;const i=[...this.subscriptions];return i.splice(e,1),this.subscriptions=Object.freeze(i),this.ditto.deferClose((e=>{mapFFIErrors((()=>tryRemoveSyncSubscription(e.deref(),t.queryString,t.queryArgumentsCBOR)))})),!0}close(){for(const t of this.subscriptions)t.cancel()}}class SubscriptionManager{constructor(t){this.ditto=t,this.subscriptions={},this.finalizationRegistry=new FinalizationRegistry(this.removeWithContextInfo.bind(this))}add(t){const e=t.contextInfo;this.ditto.deferClose((i=>{this.subscriptions[e.id]=new WeakRef(t),this.finalizationRegistry.register(t,t.contextInfo,t),addSubscription(i.deref(),e.collectionName,e.query,e.queryArgsCBOR,e.orderBys,e.limit,e.offset)}))}remove(t){if(null==this.subscriptions[t.contextInfo.id])throw new Error(`Internal inconsistency, tried to remove a subscription that is not tracked: ${t.contextInfo.id}`);this.finalizationRegistry.unregister(t),this.removeWithContextInfo(t.contextInfo)}close(){this.ditto.deferClose((()=>{for(const t in this.subscriptions){const e=this.subscriptions[t].deref();null==e||e.cancel()}}))}removeWithContextInfo(t){this.ditto.deferClose((e=>{delete this.subscriptions[t.id],removeSubscription(e.deref(),t.collectionName,t.query,t.queryArgsCBOR,t.orderBys,t.limit,t.offset)}))}}class AttachmentFetcherManager{constructor(t){this.contextInfoByID={},this.finalizationRegistry=new FinalizationRegistry(this.stopWithContextInfo.bind(this)),this.ditto=t}startAttachmentFetcher(t,e){return this.ditto.deferClose((()=>{const i=new AttachmentFetcher(this.ditto,t,this,e),n={id:i.id,attachmentTokenID:t.idBytes,cancelTokenPromise:i.cancelTokenPromise,attachmentFetcher:new WeakRef(i)};this.finalizationRegistry.register(i,n,i),this.contextInfoByID[i.id]=n;const resetCancelToken=()=>{null!=this.contextInfoByID[i.id]&&(this.contextInfoByID[i.id].cancelTokenPromise=null)};return i.attachment.then((t=>(resetCancelToken(),t)),(t=>(resetCancelToken(),t))),this.ditto.keepAlive.retain(`AttachmentFetcher.${i.id})`),i}))}async stopAttachmentFetcher(t){this.finalizationRegistry.unregister(t);const e=this.contextInfoByID[t.id];if(null==e)throw new Error(`Internal inconsistency: cannot stop attachment fetcher ${t.id}, which is not registered.`);await this.stopWithContextInfo(e)}close(){this.ditto.deferCloseAsync((async()=>{const t=Object.values(this.contextInfoByID).map((async t=>{const e=t.attachmentFetcher.deref();null!=e&&await this.stopAttachmentFetcher(e)}));await Promise.all(t)}))}stopWithContextInfo(t){return this.ditto.deferCloseAsync((async e=>{if(null==this.contextInfoByID[t.id])throw new Error(`Internal inconsistency: attachment fetcher ${t.id} not found in active attachment fetchers.`);delete this.contextInfoByID[t.id],this.ditto.keepAlive.release(`AttachmentFetcher.${t.id})`);const i=await t.cancelTokenPromise;i&&dittoCancelResolveAttachment(e.deref(),t.attachmentTokenID,i)}))}}class SmallPeerInfo{get isEnabled(){return this.ditto.deferClose((t=>dittoSmallPeerInfoGetIsEnabled(t.deref())))}set isEnabled(t){if("boolean"!=typeof t)throw new TypeError("Expected boolean, got "+typeof t);this.ditto.deferClose((e=>{dittoSmallPeerInfoSetEnabled(e.deref(),t)}))}get metadata(){return JSON.parse(this.metadataJSONString)}set metadata(t){this.metadataJSONString=JSON.stringify(t)}get metadataJSONString(){return this.ditto.deferClose((t=>dittoSmallPeerInfoGetMetadata(t.deref())))}set metadataJSONString(t){if("string"!=typeof t)throw new TypeError("Expected string, got "+typeof t);this.ditto.deferClose((e=>{dittoSmallPeerInfoSetMetadata(e.deref(),t)}))}get syncScope(){return this.ditto.deferClose((t=>dittoSmallPeerInfoGetSyncScope(t.deref())))}set syncScope(t){this.ditto.deferClose((e=>dittoSmallPeerInfoSetSyncScope(e.deref(),t)))}async getSyncScope(){return this.ditto.deferClose((t=>dittoSmallPeerInfoGetSyncScope(t.deref())))}async setSyncScope(t){return this.ditto.deferClose((e=>dittoSmallPeerInfoSetSyncScope(e.deref(),t)))}constructor(t){this.ditto=t}}class Ditto{static get VERSION(){return dittoGetSDKSemver()}static get DEFAULT_ROOT_DIRECTORY(){return rnOnlyGetDefaultDirectory()}static async open(t=DittoConfig.default){if(!(t instanceof DittoConfig))throw new TypeError("Ditto.open() expects a DittoConfig, but got "+typeof t);if("object"!=typeof t.connect)throw new TypeError("Ditto.open() expects a DittoConfig with a `connect` property, but got "+typeof t.connect);if(!Ditto.isEnvironmentSupported())throw new Error("Ditto does not support this JavaScript environment. Please consult the Ditto JavaScript documentation for a list of supported environments and browsers. You can use `Ditto.isEnvironmentSupported()` to run this check anytime.");const e=mapFFIErrors((()=>dittoOpenThrows(t.toCBOR(),"PlatformDependent",Ditto.DEFAULT_ROOT_DIRECTORY)));return new Ditto(null,null,t,e)}static openSync(t=DittoConfig.default){if(!(t instanceof DittoConfig))throw new TypeError("Ditto.openSync() expects a DittoConfig, but got "+typeof t);if("object"!=typeof t.connect)throw new TypeError("Ditto.open() expects a DittoConfig with a `connect` property, but got "+typeof t.connect);if(!Ditto.isEnvironmentSupported())throw new Error("Ditto does not support this JavaScript environment. Please consult the Ditto JavaScript documentation for a list of supported environments and browsers. You can use `Ditto.isEnvironmentSupported()` to run this check anytime.");const e=mapFFIErrors((()=>dittoOpenThrows(t.toCBOR(),"PlatformDependent",Ditto.DEFAULT_ROOT_DIRECTORY)));return new Ditto(null,null,t,e)}get deviceName(){return this._deviceName}set deviceName(t){this.isSyncActive&&Logger.warning("Changes to the device name take effect when sync is restarted."),this._deviceName=t}get sdkVersion(){return this.deferClose((t=>dittoGetSDKVersion(t.deref())))}get identity(){return this.configOrParameters.isConfig&&Logger.warning("Accessing legacy `identity` property on a Ditto instance initialized with the new DittoConfig API. The mapping may not be exact."),this.configOrParameters.identity}get path(){return Logger.warning("'Ditto.path' is deprecated. Use 'Ditto.persistenceDirectory' instead."),this.persistenceDirectory}get config(){return this.configOrParameters.isParameters&&Logger.warning("Attempted to access property 'config' of a 'Ditto' instance initialized using the deprecated parameter-based APIs. Since there is no exact 1:1 mapping between the old parameters and the new 'DittoConfig', the returned configuration will be an incomplete approximation."),this.configOrParameters.config}get absolutePersistenceDirectory(){return this.deferClose((t=>dittoAbsolutePersistenceDirectory(t.deref())))}get persistenceDirectory(){return this.configOrParameters.persistenceDirectory}get isActivated(){return this.deferClose((t=>dittoIsActivated(t.deref())))}get isClosed(){var t;return null!==(t=this._isClosed)&&void 0!==t&&t}get isSyncActive(){return this.deferClose((t=>dittoIsSyncActive(t.deref())))}constructor(t,e){var i,n,r,o,s;if(this.deferCloseAllowed=!0,this._isClosed=!1,this.pendingOperations=new Set,!Ditto.isEnvironmentSupported())throw new Error("Ditto does not support this JavaScript environment. Please consult the Ditto JavaScript documentation for a list of supported environments and browsers. You can use `Ditto.isEnvironmentSupported()` to run this check anytime.");let a,c=null;if(4===arguments.length&&arguments[2]instanceof DittoConfig){if(null!=t||null!=e)throw new DittoError("internal","identity and persistenceDirectory params must be null when constructing Ditto with DittoConfig");a=new ConfigOrParameters(arguments[2]),c=arguments[3]}else{a=new ConfigOrParameters(null!=t?t:DEFAULT_IDENTITY,e)}if(this.configOrParameters=a.redactingSensitiveData(),null==c){const t=makeIdentityConfig(a.identity),e="Disabled",i="PlatformDependent";c=mapFFIErrors((()=>dittoTryNewBlocking(a.persistenceDirectory,t,e,i)))}Bridge.ditto.bridge(c,this),this._deviceName=defaultDeviceName(),dittoDisableSyncWithV3(c).catch((t=>{Logger.error(`Failed to disable sync with V3: ${null==t?void 0:t.message}`)}));let d=null,l=!1;if(this.keepAlive=new KeepAlive,a.isConfig)this.auth=new OnlineAuthenticatorV2(this.keepAlive,this);else if("onlineWithAuthentication"===(null===(i=a.identity)||void 0===i?void 0:i.type)){l=null===(r=null===(n=a.identity)||void 0===n?void 0:n.enableDittoCloudSync)||void 0===r||r,this.auth=new OnlineAuthenticator(this.keepAlive,this,a.identity.authHandler);const t=new WeakRef(this);dittoAuthSetLoginProvider(c,dittoAuthClientMakeLoginProvider((function(e){const i=t.deref();i?i.auth?i.auth["@ditto.authenticationExpiring"](e):d=e:Logger.warning("Internal inconsistency, LoginProvider callback fired after the corresponding Ditto instance has been deallocated.")})))}else"onlinePlayground"===(null===(o=a.identity)||void 0===o?void 0:o.type)?(l=null===(s=a.identity.enableDittoCloudSync)||void 0===s||s,this.auth=new OnlineAuthenticator(this.keepAlive,this,{authenticationRequired:function(t){},authenticationExpiringSoon:function(t,e){}})):this.auth=new NotAvailableAuthenticator(this.keepAlive);dittoSetCloudSyncEnabled(c,l),transportsInit(),this.appID=dittoAuthClientGetAppID(c),this.siteID=dittoAuthClientGetSiteID(c),this.sync=new Sync(this),this.store=new Store(this),this.smallPeerInfo=new SmallPeerInfo(this),this.presence=new Presence(this),this.presenceManager=new PresenceManager(this),this.liveQueryManager=new LiveQueryManager(this,this.keepAlive),this.attachmentFetcherManager=new AttachmentFetcherManager(this),this.transportConditionsManager=new TransportConditionsManager(this),this.subscriptionManager=new SubscriptionManager(this),a.isParameters&&null!=d&&this.auth["@ditto.authenticationExpiring"](d)}static disableDeadlockDetection(){}static hasDeadlockDetection(){return!1}static isEnvironmentSupported(){let t,e=!1;"undefined"!=typeof window&&window.navigator&&window.navigator.userAgent&&window.navigator.appVersion&&(e=-1!==window.navigator.userAgent.indexOf("MSIE")||window.navigator.appVersion.indexOf("Trident/")>-1);try{t=checkAPIs()}catch(t){throw new Error(`Error checking environment support: ${t}`)}return!e&&t}setOfflineOnlyLicenseToken(t){if("string"!=typeof t)throw new TypeError(`Expected parameter licenseToken to have type string, but got '${typeof t}'`);if(IdentityTypesRequiringOfflineLicenseToken.includes(this.configOrParameters.identity.type))this.deferClose((e=>{mapFFIErrors((()=>{tryVerifyLicense(e.deref(),t)}))}));else{const t=this.configOrParameters.isConfig?`The connect mode '${this.config.connect.mode}' does not require an offline license token.`:`The identity type '${this.identity.type}' does not require an offline license token.`;Logger.error(t)}}get transportConfig(){return this.deferClose((t=>{const e=dittoTransportConfig(t.deref());return transportConfigFromDeserializable(CBOR.decode(e)).freeze()}))}setTransportConfig(t){const e=transportConfigToSerializable(t.copy().freeze()),i=CBOR.encode(e);this.deferClose((t=>{dittoSetTransportConfig(t.deref(),i)}))}updateTransportConfig(t){const e=this.transportConfig.copy();return t(e),this.setTransportConfig(e),this}startSync(){this.deferClose((t=>{if(IdentityTypesRequiringOfflineLicenseToken.includes(this.configOrParameters.identity.type)&&!this.isActivated)throw new Error("Sync could not be started because Ditto has not yet been activated. This can be achieved with a successful call to `setOfflineOnlyLicenseToken`. If you need to obtain a license token then please visit https://portal.ditto.live.");this.isSyncActive||this.keepAlive.retain("sync"),this._deviceName=dittoSetDeviceName(t.deref(),this.deviceName);try{mapFFIErrors((()=>dittoTryStartSync(t.deref())))}catch(t){throw this.isSyncActive||this.keepAlive.release("sync"),t}}))}stopSync(){this.deferClose((t=>{this.isSyncActive&&this.keepAlive.release("sync"),dittoStopSync(t.deref())}))}observePeers(t){if(Logger.warning("`ditto.observePeers()` is deprecated, please use `ditto.presence.observe()` instead."),"function"!=typeof t)throw new TypeError(`Expected parameter callback to have type function, but got '${typeof t}'`);const e=this.presenceManager.addObserver(t);return new Observer(this.presenceManager,e,{stopsWhenFinalized:!0})}observeTransportConditions(t){if("function"!=typeof t)throw new TypeError(`Expected parameter callback to have type function, but got '${typeof t}'`);const e=this.transportConditionsManager.addObserver(t);return new Observer(this.transportConditionsManager,e,{stopsWhenFinalized:!0})}async runGarbageCollection(){return this.deferCloseAsync((async t=>dittoRunGarbageCollection(t.deref())))}async disableSyncWithV3(){throw new Error("This API is not available in React Native environments.")}async close(){if(!this.isClosed){if(this._isClosed=!0,this.stopSync(),this.store.close(),this.presence.close(),this.auth.close(),this.sync.close(),await this.presenceManager.close(),this.liveQueryManager.close(),this.attachmentFetcherManager.close(),this.transportConditionsManager.close(),this.subscriptionManager.close(),this.keepAlive.isActive)throw new Error("Internal inconsistency, still kept alive after the Ditto object has been close()-ed. Active IDs: "+this.keepAlive.currentIDs().join(", "));do{await Promise.allSettled(this.pendingOperations)}while(this.pendingOperations.size>0);this.deferCloseAllowed=!1,await Bridge.ditto.close(this)}}get numPendingOperations(){return this.pendingOperations.size}deferClose(t){if(!this.deferCloseAllowed)throw new Error("Can't perform operation using a Ditto instance that has been closed.");return t(Bridge.ditto.handleFor(this))}async deferCloseAsync(t){if(!this.deferCloseAllowed)throw new Error("Can't perform operation using a Ditto instance that has been closed.");const e=t(Bridge.ditto.handleFor(this));let i;this.pendingOperations.add(e);try{i=await e}finally{this.pendingOperations.delete(e)}return i}}const checkAPIs=t=>{const e=t||globalThis||global||window;return["BigInt","WeakRef","FinalizationRegistry"].every((t=>!!e[t]))},disableDeadlockTimeoutWhenDebugging=()=>{},CUSTOM_INSPECT_SYMBOL=Symbol.for("nodejs.util.inspect.custom");class QueryResultItem{get value(){if(this.materialize(),void 0===this.materializedValue)throw new Error("Internal Error: Materialized value is undefined");return this.materializedValue}get isMaterialized(){return void 0!==this.materializedValue}materialize(){if(!this.isMaterialized){const t=this.cborData();let e;try{e=CBOR.decode(t)}catch(t){throw new Error(`Internal inconsistency: CBOR decoding error while materializing result item: ${t.message}`)}if(void 0===e)throw new Error("Internal inconsistency: Materialized value is undefined");this.materializedValue=e}}dematerialize(){this.materializedValue=void 0}cborData(){return queryResultItemCBOR(this.deref())}jsonString(){return queryResultItemJSON(this.deref())}[CUSTOM_INSPECT_SYMBOL](t,e,i){return customInspectRepresentation(this,i)}constructor(){}static fromJSON(t){const e=(new TextEncoder).encode(t);return Bridge.queryResultItem.bridge(queryResultItemNew(e))}deref(){return Bridge.queryResultItem.handleFor(this).deref()}}class ConnectionRequest{get peerKeyString(){return connectionRequestPeerKeyString(this.deref())}get peerMetadata(){return JSON.parse(this.peerMetadataJSONString)}get peerMetadataJSONString(){return connectionRequestPeerMetadataJSON(this.deref())}get identityServiceMetadata(){return JSON.parse(this.identityServiceMetadataJSONString)}get identityServiceMetadataJSONString(){return connectionRequestIdentityServiceMetadataJSON(this.deref())}get connectionType(){return connectionRequestConnectionType(this.deref())}toString(){return`ConnectionRequest(${this.peerKeyString} via ${this.connectionType})`}[Symbol.for("nodejs.util.inspect.custom")](t,e,i){return this.toString()}deref(){return Bridge.connectionRequest.handleFor(this).deref()}}Bridge.attachment.registerType(Attachment),Bridge.connectionRequest.registerType(ConnectionRequest),Bridge.document.registerType(Document),Bridge.queryResultItem.registerType(QueryResultItem),Bridge.differ.registerType(Differ),Bridge.transaction.registerType(Transaction),Bridge.queryResult.registerType(QueryResult),Bridge.mutableDocument.registerType(MutableDocument),Bridge.ditto.registerType(Ditto);export{Attachment,AttachmentFetcher,AttachmentToken,Authenticator,ConfigOrParameters,ConnectionRequest,DEFAULT_IDENTITY,Diff,Differ,Ditto,DittoConfig,DittoError,DocumentID,ERROR_CODES,IdentityTypesRequiringOfflineLicenseToken,Logger,NotAvailableAuthenticator,Observer,OnlineAuthenticator,OnlineAuthenticatorV2,Presence,QueryResult,QueryResultItem,SmallPeerInfo,Store,StoreObserver,Sync,SyncSubscription,Transaction,TransactionInfo,TransportConfig,addressToString,checkAPIs,disableDeadlockTimeoutWhenDebugging,getMissingAndroidPermissions,init,makeIdentityConfig,mapFFIErrors,mapFFIErrorsAsync,transportConfigFromDeserializable,transportConfigToSerializable,validateAttachmentMetadata,validateDocumentIDCBOR,validateDocumentIDValue};
2
2
  //# sourceMappingURL=ditto.es6.js.map