UNPKG

@dittolive/ditto

Version:

Ditto is a cross-platform SDK that allows apps to sync with and even without internet connectivity.

1 lines • 105 kB
import{NativeModules,Platform}from"react-native";const REGISTRY_SWEEP_INTERVAL=1e4;class WeakRefBasedFinalizationRegistry{[Symbol.toStringTag]="FinalizationRegistry";counter=0;registrations=new Map;constructor(e){this.finalize=e}register(e,t,r){this.registrations.set(this.counter,{targetRef:new WeakRef(e),tokenRef:r?new WeakRef(r):void 0,value:t}),this.counter++,this.scheduleSweep()}unregister(e){if(!e)return!1;let t=!1;return this.registrations.forEach((r,n)=>{r.tokenRef?.deref()===e&&(this.registrations.delete(n),t=!0)}),t}sweep=()=>{clearTimeout(this.sweepTimeout),this.sweepTimeout=void 0,this.registrations.forEach((e,t)=>{if(void 0!==e.targetRef.deref())return;const r=e.value;this.registrations.delete(t),this.finalize(r)}),this.registrations.size>0&&this.scheduleSweep()};scheduleSweep(){this.sweepTimeout||(this.sweepTimeout=setTimeout(this.sweep,1e4))}}class WeakRefMock{[Symbol.toStringTag]="WeakRef";constructor(e){this.target=e}deref(){return this.target}static get[Symbol.toStringTag](){return"WeakRef"}}let DittoModule;!function(e){function x(){}function y(){}var t=String.fromCharCode,r={}.toString,n=r.call(e.SharedArrayBuffer),i=r(),o=e.Uint8Array,s=o||Array,a=o?ArrayBuffer:s,c=a.isView||function(e){return e&&"length"in e},d=r.call(a.prototype);a=y.prototype;var u=e.TextEncoder,l=e.TextDecoder,f=new(o?Uint16Array:s)(32);x.prototype.decode=function(e){if(!c(e)){var a=r.call(e);if(a!==d&&a!==n&&a!==i)throw TypeError("Failed to execute 'decode' on 'TextDecoder': The provided value is not of type '(ArrayBuffer or ArrayBufferView)'");e=o?new s(e):e||[]}for(var u,l,h,_=a="",p=0,g=0|e.length,b=g-32|0,m=0,w=0,v=0,E=-1;p<g;){for(u=p<=b?32:g-p|0;v<u;p=p+1|0,v=v+1|0){switch((l=255&e[p])>>4){case 15:if(2!=(h=255&e[p=p+1|0])>>6||247<l){p=p-1|0;break}m=(7&l)<<6|63&h,w=5,l=256;case 14:m<<=6,m|=(15&l)<<6|63&(h=255&e[p=p+1|0]),w=2==h>>6?w+4|0:24,l=l+256&768;case 13:case 12:m<<=6,m|=(31&l)<<6|63&(h=255&e[p=p+1|0]),w=w+7|0,p<g&&2==h>>6&&m>>w&&1114112>m?(l=m,0<=(m=m-65536|0)&&(E=55296+(m>>10)|0,l=56320+(1023&m)|0,31>v?(f[v]=E,v=v+1|0,E=-1):(h=E,E=l,l=h))):(p=p-(l>>=8)-1|0,l=65533),m=w=0,u=p<=b?32:g-p|0;default:f[v]=l;continue;case 11:case 10:case 9:case 8:}f[v]=65533}if(_+=t(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)),p<g){if(f[0]=E,v=~E>>>31,E=-1,_.length<a.length)continue}else-1!==E&&(_+=t(E));a+=_,_=""}return a},a.encode=function(e){var t,r=0|(e=void 0===e?"":""+e).length,n=new s(8+(r<<1)|0),i=0,a=!o;for(t=0;t<r;t=t+1|0,i=i+1|0){var c=0|e.charCodeAt(t);if(127>=c)n[i]=c;else{if(2047>=c)n[i]=192|c>>6;else{e:{if(55296<=c)if(56319>=c){var d=0|e.charCodeAt(t=t+1|0);if(56320<=d&&57343>=d){if(65535<(c=(c<<10)+d-56613888|0)){n[i]=240|c>>18,n[i=i+1|0]=128|c>>12&63,n[i=i+1|0]=128|c>>6&63,n[i=i+1|0]=128|63&c;continue}break e}c=65533}else 57343>=c&&(c=65533);!a&&t<<1<i&&t<<1<(i-7|0)&&(a=!0,(d=new s(3*r)).set(n),n=d)}n[i]=224|c>>12,n[i=i+1|0]=128|c>>6&63}n[i=i+1|0]=128|63&c}}return o?n.subarray(0,i):n.slice(0,i)},u||(e.TextEncoder=y),l||(e.TextDecoder=x)}(""+void 0==typeof global?""+void 0==typeof self?void 0:self:global);try{DittoModule=require("../specs/NativeDittoRNSDK").default}catch(e){DittoModule=NativeModules.DittoRNSDK}const dittoCore=global,isLoaded="function"==typeof dittoCore.ditto_sdk_transports_init;if(!isLoaded){const e=DittoModule?.install();if(!e)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 t=Platform.select({ios:"iOS",android:"Android",macos:"macOS",default:"Unknown"});dittoCore.ditto_init_sdk_version(t,"JavaScript","5.0.0")}function ditto_sdk_transports_init(e){return dittoCore.ditto_sdk_transports_init(e)}function getMissingAndroidPermissions(){return"android"!==Platform.OS?[]:dittoCore.ditto_sdk_transports_android_missing_permissions()}function getPlatform(){return Platform.OS}function boxCBytesIntoBuffer(e){const t=dittoCore.sliceBoxedToUInt8Array(e);return t?new Uint8Array(t):null}function refCBytesIntoBuffer(e){const t=dittoCore.sliceRefToUInt8Array(e);return t?new Uint8Array(t):null}function dittoffi_differ_diff(...e){return boxCBytesIntoBuffer(dittoCore.dittoffi_differ_diff(...e))}function dittoffi_DEFAULT_DATABASE_ID(...e){return dittoCore.dittoffi_DEFAULT_DATABASE_ID(...e)}function dittoffi_DITTO_DEVELOPMENT_PROVIDER(...e){return dittoCore.dittoffi_DITTO_DEVELOPMENT_PROVIDER(...e)}function dittoffi_ditto_config_default(...e){return dittoCore.dittoffi_ditto_config_default(...e)}function dittoffi_ditto_config(...e){return dittoCore.dittoffi_ditto_config(...e)}function dittoffi_ditto_open_throws(...e){return dittoCore.dittoffi_ditto_open_throws(...e)}function ditto_shutdown(...e){return dittoCore.ditto_shutdown(...e)}function ditto_free(...e){return dittoCore.ditto_free(...e)}function dittoffi_ditto_is_activated(...e){return dittoCore.dittoffi_ditto_is_activated(...e)}function dittoffi_ditto_is_sync_active(...e){return dittoCore.dittoffi_ditto_is_sync_active(...e)}function dittoffi_ditto_try_start_sync(...e){return dittoCore.dittoffi_ditto_try_start_sync(...e)}function dittoffi_ditto_stop_sync(...e){return dittoCore.dittoffi_ditto_stop_sync(...e)}function dittoffi_ditto_try_set_transport_config(...e){return dittoCore.dittoffi_ditto_try_set_transport_config(...e)}function dittoffi_ditto_transport_config(...e){return dittoCore.dittoffi_ditto_transport_config(...e)}function refCStringToString(...e){return dittoCore.refCStringToString(...e)}function boxCStringIntoString(...e){return dittoCore.boxCStringIntoString(...e)}function ditto_auth_client_is_web_valid(...e){return dittoCore.ditto_auth_client_is_web_valid(...e)}function ditto_auth_client_make_login_provider(...e){return dittoCore.ditto_auth_client_make_login_provider(...e)}function ditto_auth_set_login_provider(...e){return dittoCore.ditto_auth_set_login_provider(...e)}function ditto_auth_client_login_with_token_and_feedback(...e){return dittoCore.ditto_auth_client_login_with_token_and_feedback(...e)}function ditto_auth_client_logout(...e){return dittoCore.ditto_auth_client_logout(...e)}function ditto_auth_client_user_id(...e){return dittoCore.ditto_auth_client_user_id(...e)}function dittoffi_ditto_set_authentication_status_handler(...e){return dittoCore.dittoffi_ditto_set_authentication_status_handler(...e)}function dittoffi_authentication_status_is_authenticated(...e){return dittoCore.dittoffi_authentication_status_is_authenticated(...e)}function dittoffi_authentication_status_user_id(...e){return dittoCore.dittoffi_authentication_status_user_id(...e)}function dittoffi_authentication_status_free(...e){return dittoCore.dittoffi_authentication_status_free(...e)}function dittoffi_store_register_observer_throws(...e){return dittoCore.dittoffi_store_register_observer_throws(...e)}function dittoffi_store_observers(...e){return dittoCore.dittoffi_store_observers(...e)}function dittoffi_store_observer_query_string(...e){return dittoCore.dittoffi_store_observer_query_string(...e)}function dittoffi_store_observer_query_arguments_cbor(...e){return dittoCore.dittoffi_store_observer_query_arguments_cbor(...e)}function dittoffi_store_observer_query_arguments_json(...e){return dittoCore.dittoffi_store_observer_query_arguments_json(...e)}function dittoffi_store_observer_cancel(...e){return dittoCore.dittoffi_store_observer_cancel(...e)}function dittoffi_store_observer_is_cancelled(...e){return dittoCore.dittoffi_store_observer_is_cancelled(...e)}function dittoffi_store_observer_free(...e){return dittoCore.dittoffi_store_observer_free(...e)}function dittoffi_sync_register_subscription_throws(...e){return dittoCore.dittoffi_sync_register_subscription_throws(...e)}function dittoffi_sync_subscriptions(...e){return dittoCore.dittoffi_sync_subscriptions(...e)}function dittoffi_sync_subscription_query_string(...e){return dittoCore.dittoffi_sync_subscription_query_string(...e)}function dittoffi_sync_subscription_query_arguments_cbor(...e){return dittoCore.dittoffi_sync_subscription_query_arguments_cbor(...e)}function dittoffi_sync_subscription_query_arguments_json(...e){return dittoCore.dittoffi_sync_subscription_query_arguments_json(...e)}function dittoffi_sync_subscription_cancel(...e){return dittoCore.dittoffi_sync_subscription_cancel(...e)}function dittoffi_sync_subscription_is_cancelled(...e){return dittoCore.dittoffi_sync_subscription_is_cancelled(...e)}function dittoffi_sync_subscription_free(...e){return dittoCore.dittoffi_sync_subscription_free(...e)}function dittoffi_try_exec_statement(...e){return dittoCore.dittoffi_try_exec_statement(...e)}function dittoffi_query_result_item_count(...e){return dittoCore.dittoffi_query_result_item_count(...e)}function dittoffi_query_result_item_at(...e){return dittoCore.dittoffi_query_result_item_at(...e)}function dittoffi_query_result_item_new(...e){return dittoCore.dittoffi_query_result_item_new(...e)}function dittoffi_query_result_has_commit_id(...e){return dittoCore.dittoffi_query_result_has_commit_id(...e)}function dittoffi_query_result_commit_id(...e){return dittoCore.dittoffi_query_result_commit_id(...e)}function dittoffi_query_result_mutated_document_id_count(...e){return dittoCore.dittoffi_query_result_mutated_document_id_count(...e)}function dittoffi_query_result_mutated_document_id_at(...e){return dittoCore.dittoffi_query_result_mutated_document_id_at(...e)}function dittoffi_query_result_item_cbor(...e){return dittoCore.dittoffi_query_result_item_cbor(...e)}function dittoffi_query_result_item_json(...e){return dittoCore.dittoffi_query_result_item_json(...e)}function ditto_presence_v3(...e){return dittoCore.ditto_presence_v3(...e)}function ditto_register_presence_v3_callback(...e){return dittoCore.ditto_register_presence_v3_callback(...e)}function ditto_clear_presence_v3_callback(...e){return dittoCore.ditto_clear_presence_v3_callback(...e)}function dittoffi_presence_peer_metadata_json(...e){return dittoCore.dittoffi_presence_peer_metadata_json(...e)}function dittoffi_presence_try_set_peer_metadata_json(...e){return dittoCore.dittoffi_presence_try_set_peer_metadata_json(...e)}function dittoffi_presence_set_connection_request_handler(...e){return dittoCore.dittoffi_presence_set_connection_request_handler(...e)}function ditto_new_attachment_from_file(...e){return dittoCore.ditto_new_attachment_from_file(...e)}function ditto_new_attachment_from_bytes(...e){return dittoCore.ditto_new_attachment_from_bytes(...e)}function ditto_resolve_attachment(...e){return dittoCore.ditto_resolve_attachment(...e)}function ditto_cancel_resolve_attachment(...e){return dittoCore.ditto_cancel_resolve_attachment(...e)}function ditto_free_attachment_handle(...e){return dittoCore.ditto_free_attachment_handle(...e)}function ditto_get_complete_attachment_path(...e){return dittoCore.ditto_get_complete_attachment_path(...e)}function ditto_log(...e){return dittoCore.ditto_log(...e)}function ditto_logger_init(...e){return dittoCore.ditto_logger_init(...e)}function ditto_logger_minimum_log_level_get(...e){return dittoCore.ditto_logger_minimum_log_level_get(...e)}function ditto_logger_minimum_log_level(...e){return dittoCore.ditto_logger_minimum_log_level(...e)}function ditto_logger_enabled_get(...e){return dittoCore.ditto_logger_enabled_get(...e)}function ditto_logger_enabled(...e){return dittoCore.ditto_logger_enabled(...e)}function ditto_small_peer_info_get_is_enabled(...e){return dittoCore.ditto_small_peer_info_get_is_enabled(...e)}function ditto_small_peer_info_set_enabled(...e){return dittoCore.ditto_small_peer_info_set_enabled(...e)}function ditto_small_peer_info_get_metadata(...e){return dittoCore.ditto_small_peer_info_get_metadata(...e)}function ditto_small_peer_info_set_metadata(...e){return dittoCore.ditto_small_peer_info_set_metadata(...e)}function ditto_sdk_transports_error_new(...e){return dittoCore.ditto_sdk_transports_error_new(...e)}function ditto_sdk_transports_error_value(...e){return dittoCore.ditto_sdk_transports_error_value(...e)}function ditto_sdk_transports_error_free(...e){return dittoCore.ditto_sdk_transports_error_free(...e)}function dittoffi_connection_request_peer_key_string(...e){return dittoCore.dittoffi_connection_request_peer_key_string(...e)}function dittoffi_connection_request_peer_metadata_json(...e){return dittoCore.dittoffi_connection_request_peer_metadata_json(...e)}function dittoffi_connection_request_authorize(...e){return dittoCore.dittoffi_connection_request_authorize(...e)}function dittoffi_connection_request_free(...e){return dittoCore.dittoffi_connection_request_free(...e)}function dittoffi_connection_request_connection_type(...e){return dittoCore.dittoffi_connection_request_connection_type(...e)}function ditto_set_device_name(...e){return dittoCore.ditto_set_device_name(...e)}function dittoffi_get_sdk_semver(...e){return dittoCore.dittoffi_get_sdk_semver(...e)}function ditto_error_message(...e){return dittoCore.ditto_error_message(...e)}function dittoffi_error_code(...e){return dittoCore.dittoffi_error_code(...e)}function dittoffi_error_description(...e){return dittoCore.dittoffi_error_description(...e)}function dittoffi_error_free(...e){return dittoCore.dittoffi_error_free(...e)}function dittoffi_try_verify_license(...e){return dittoCore.dittoffi_try_verify_license(...e)}function dittoffi_base64_encode(...e){return dittoCore.dittoffi_base64_encode(...e)}function dittoffi_try_base64_decode(...e){return dittoCore.dittoffi_try_base64_decode(...e)}function dittoffi_crypto_generate_secure_random_token(...e){return dittoCore.dittoffi_crypto_generate_secure_random_token(...e)}function readFile(...e){return dittoCore.readFile(...e)}function copyFile(...e){return dittoCore.copyFile(...e)}function getDefaultDirectory(){return dittoCore.defaultDirectory}function defaultDeviceName$1(...e){return dittoCore.defaultDeviceName(...e)}function dittoffi_ditto_absolute_persistence_directory(...e){return dittoCore.dittoffi_ditto_absolute_persistence_directory(...e)}function dittoffi_logger_try_export_to_file_async(...e){return dittoCore.dittoffi_logger_try_export_to_file_async(...e)}function ditto_logger_set_custom_log_cb(...e){return dittoCore.ditto_logger_set_custom_log_cb(...e)}function dittoffi_query_result_free(...e){return dittoCore.dittoffi_query_result_free(...e)}function dittoffi_query_result_item_free(...e){return dittoCore.dittoffi_query_result_item_free(...e)}function ditto_clear_presence_callback(...e){return dittoCore.ditto_clear_presence_callback(...e)}function dittoffi_differ_new(...e){return dittoCore.dittoffi_differ_new(...e)}function dittoffi_differ_free(...e){return dittoCore.dittoffi_differ_free(...e)}function dittoffi_store_transactions(...e){return dittoCore.dittoffi_store_transactions(...e)}function dittoffi_store_begin_transaction_async_throws(...e){return dittoCore.dittoffi_store_begin_transaction_async_throws(...e)}function dittoffi_transaction_complete_async_throws(...e){return dittoCore.dittoffi_transaction_complete_async_throws(...e)}function dittoffi_transaction_execute_async_throws(...e){return dittoCore.dittoffi_transaction_execute_async_throws(...e)}function dittoffi_transaction_info(...e){return dittoCore.dittoffi_transaction_info(...e)}function dittoffi_transaction_free(...e){return dittoCore.dittoffi_transaction_free(...e)}function ditto_register_transport_condition_changed_callback(...e){return dittoCore.ditto_register_transport_condition_changed_callback(...e)}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(e,t,r){const n=ffiErrorMessage();super(t||n||r),this.code=e}}function throwOnErrorResult(e,t){if(null!==e){let r,n;try{r=dittoffi_error_code(e),n=boxCStringIntoString(dittoffi_error_description(e)),dittoffi_error_free(e)}catch(e){throw new DittoFFIError(-1,`Failed to retrieve Ditto core error message: ${e.message}`)}throw n=null==n?`${t}() failed with error code: ${r}`:n.replace(PREFIX_REGEX,""),new DittoFFIError(r,n)}}function ffiErrorMessage(){return boxCStringIntoString(ditto_error_message())}const DittoCRDTTypeKey="_ditto_internal_type_jkb12973t4b";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(e,t){return ensureInitialized(),dittoffi_differ_diff(e,t)}function differFree(e){ensureInitialized(),dittoffi_differ_free(e)}function dittoPointerToStorePointer(e){return{addr:e.addr,type:"dittoffi_store_t const *"}}async function tryExecStatement(e,t,r){ensureInitialized();const n=bytesFromString(t),i=await dittoffi_try_exec_statement(e,n,r);return throwOnErrorResult(i.error,"dittoffi_try_exec_statement"),i.success}function syncRegisterSubscriptionThrows(e,t,r){ensureInitialized();const n=dittoffi_sync_register_subscription_throws(e,bytesFromString(t),r);return throwOnErrorResult(n.error,"dittoffi_sync_register_subscription_throws"),n.success}function syncSubscriptions(e){return ensureInitialized(),dittoffi_sync_subscriptions(e)}function syncSubscriptionQueryString(e){ensureInitialized();return boxCStringIntoString(dittoffi_sync_subscription_query_string(e))}function syncSubscriptionQueryArgumentsCBOR(e){ensureInitialized();const t=dittoffi_sync_subscription_query_arguments_cbor(e);return null===t?null:boxCBytesIntoBuffer(t)}function syncSubscriptionQueryArgumentsJSON(e){ensureInitialized();const t=dittoffi_sync_subscription_query_arguments_json(e);if(null===t)return null;const r=boxCBytesIntoBuffer(t);return(new TextDecoder).decode(r)}function syncSubscriptionCancel(e){ensureInitialized(),dittoffi_sync_subscription_cancel(e)}function syncSubscriptionIsCancelled(e){return ensureInitialized(),dittoffi_sync_subscription_is_cancelled(e)}function syncSubscriptionFree(e){ensureInitialized(),dittoffi_sync_subscription_free(e)}function queryResultFree(e){ensureInitialized(),dittoffi_query_result_free(e)}function queryResultItemFree(e){ensureInitialized(),dittoffi_query_result_item_free(e)}function queryResultItems(e){ensureInitialized();const t=[],r=dittoffi_query_result_item_count(e);for(let n=0;n<r;n++)t.push(dittoffi_query_result_item_at(e,n));return t}function queryResultMutatedDocumentIDs(e){ensureInitialized();const t=[],r=dittoffi_query_result_mutated_document_id_count(e);for(let n=0;n<r;n++){const r=dittoffi_query_result_mutated_document_id_at(e,n);t.push(boxCBytesIntoBuffer(r))}return t}function queryResultHasCommitID(e){return ensureInitialized(),dittoffi_query_result_has_commit_id(e)}function queryResultCommitID(e){ensureInitialized();const t=dittoffi_query_result_commit_id(e);return BigInt(t)}function queryResultItemCBOR(e){ensureInitialized();return boxCBytesIntoBuffer(dittoffi_query_result_item_cbor(e))}function queryResultItemJSON(e){ensureInitialized();return boxCStringIntoString(dittoffi_query_result_item_json(e))}function queryResultItemNew(e){ensureInitialized();const t=dittoffi_query_result_item_new(e);return throwOnErrorResult(t.error,"dittoffi_query_result_item_new"),t.success}function storeRegisterObserverThrows(e,t,r,n){ensureInitialized();const i=dittoffi_store_register_observer_throws(e,bytesFromString(t),r,wrapBackgroundCbForFFI(e=>log("Error",`The registered store observer callback failed with ${e}`),n));return throwOnErrorResult(i.error,"dittoffi_store_register_observer_throws"),i.success}function storeObservers(e){return ensureInitialized(),dittoffi_store_observers(e)}function storeObserverQueryString(e){ensureInitialized();return boxCStringIntoString(dittoffi_store_observer_query_string(e))}function storeObserverQueryArgumentsCBOR(e){ensureInitialized();const t=dittoffi_store_observer_query_arguments_cbor(e);return null===t?null:boxCBytesIntoBuffer(t)}function storeObserverQueryArgumentsJSON(e){ensureInitialized();const t=dittoffi_store_observer_query_arguments_json(e);if(null===t)return null;const r=boxCBytesIntoBuffer(t);return(new TextDecoder).decode(r)}function storeObserverCancel(e){ensureInitialized(),dittoffi_store_observer_cancel(e)}function storeObserverIsCancelled(e){return ensureInitialized(),dittoffi_store_observer_is_cancelled(e)}function storeObserverFree(e){ensureInitialized(),dittoffi_store_observer_free(e)}function loggerInit(){ensureInitialized(),ditto_logger_init()}async function loggerSetCustomLogCb(e){if(ensureInitialized(),null===e)await ditto_logger_set_custom_log_cb(null);else{const t=wrapBackgroundCbForFFI(null,(t,r)=>{try{const n=boxCStringIntoString(r);e(t,n)}catch(e){log("Error",`The registered cb in \`ditto_logger_set_custom_log_cb()\` failed with: ${e}`)}});await ditto_logger_set_custom_log_cb(t)}}function loggerEnabled(e){ensureInitialized(),ditto_logger_enabled(!!e)}function loggerEnabledGet(){return ensureInitialized(),!!ditto_logger_enabled_get()}function loggerMinimumLogLevel(e){ensureInitialized(),ditto_logger_minimum_log_level(e)}function loggerMinimumLogLevelGet(){return ensureInitialized(),ditto_logger_minimum_log_level_get()}async function loggerTryExportToFile(e){ensureInitialized();const t=bytesFromString(e),r=await new Promise((e,r)=>{const n=wrapBackgroundCbForFFI(r,e);dittoffi_logger_try_export_to_file_async(t,n)});return throwOnErrorResult(r.error,"dittoffi_logger_try_export_to_file_async"),r.success}function log(e,t){ensureInitialized();ditto_log(e,bytesFromString(t))}function dittoAuthClientUserID(e){ensureInitialized();return boxCStringIntoString(ditto_auth_client_user_id(e))}function dittoAuthClientIsWebValid(e){return ensureInitialized(),0!==ditto_auth_client_is_web_valid(e)}async function dittoAuthClientLoginWithTokenAndFeedback(e,t,r){ensureInitialized();const n=bytesFromString(t),i=bytesFromString(r),o=await ditto_auth_client_login_with_token_and_feedback(e,n,i);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 dittoAuthClientLogout(e){ensureInitialized();const t=await ditto_auth_client_logout(e);if(0!==t)throw new Error(errorMessage()||`Ditto failed to logout (error code: ${t}).`)}function dittoSetAuthenticationStatusHandler(e,t,r){ensureInitialized(),dittoffi_ditto_set_authentication_status_handler(e,wrapBackgroundCbForFFI(r,t))}function authenticationStatusUserID(e){return ensureInitialized(),boxCStringIntoString(dittoffi_authentication_status_user_id(e))}function authenticationStatusIsAuthenticated(e){return ensureInitialized(),dittoffi_authentication_status_is_authenticated(e)}function authenticationStatusFree(e){ensureInitialized(),dittoffi_authentication_status_free(e)}function storeTransactions(e){ensureInitialized();return boxCBytesIntoBuffer(dittoffi_store_transactions(e))}async function storeBeginTransaction(e,t){ensureInitialized();const r={is_read_only:t.isReadOnly,hint:bytesFromString(t.hint)};return new Promise((t,n)=>{const i=wrapBackgroundCbForFFI(n,e=>{throwOnErrorResult(e.error,"dittoffi_store_begin_transaction_async_throws"),t(e.success)});dittoffi_store_begin_transaction_async_throws(e,r,i)})}async function transactionCompleteAsync(e,t){return ensureInitialized(),new Promise((r,n)=>{const i=wrapBackgroundCbForFFI(n,e=>{throwOnErrorResult(e.error,"dittoffi_transaction_complete_async_throws");const t=e.success;r(t)});dittoffi_transaction_complete_async_throws(e,t,i)})}async function transactionExecuteAsync(e,t,r){return ensureInitialized(),new Promise((n,i)=>{const o=wrapBackgroundCbForFFI(i,e=>{throwOnErrorResult(e.error,"dittoffi_transaction_execute_async_throws"),n(e.success)}),s=bytesFromString(t);dittoffi_transaction_execute_async_throws(e,s,r,o)})}function transactionInfo(e){ensureInitialized();return boxCBytesIntoBuffer(dittoffi_transaction_info(e))}function transactionFree(e){ensureInitialized(),dittoffi_transaction_free(e)}function dittoConfigDefault(){ensureInitialized();return boxCBytesIntoBuffer(dittoffi_ditto_config_default())}function dittoConfig(e){ensureInitialized();return boxCBytesIntoBuffer(dittoffi_ditto_config(e))}function dittoAbsolutePersistenceDirectory(e){ensureInitialized();return boxCStringIntoString(dittoffi_ditto_absolute_persistence_directory(e))}function dittoOpenThrows(e,t,r){ensureInitialized();const n=dittoffi_ditto_open_throws(e,t,bytesFromString(r));return throwOnErrorResult(n.error,"dittoffi_ditto_open_throws"),n.success}function dittoFree(e){return ensureInitialized(),ditto_free(e)}function cryptoGenerateSecureRandomToken(){ensureInitialized();return boxCStringIntoString(dittoffi_crypto_generate_secure_random_token())}async function dittoClearPresenceCallback(e){return ensureInitialized(),ditto_clear_presence_callback(e)}function dittoRegisterPresenceV3Callback(e,t){ensureInitialized(),ditto_register_presence_v3_callback(e,wrapBackgroundCbForFFI(e=>log("Error",`The registered presence callback v3 errored with ${e}`),e=>{const r=refCStringToString(e);t(r)}))}async function dittoClearPresenceV3Callback(e){return ensureInitialized(),ditto_clear_presence_v3_callback(e)}function presencePeerMetadataJSON(e){ensureInitialized();const t=boxCBytesIntoBuffer(dittoffi_presence_peer_metadata_json(e));return(new TextDecoder).decode(t)}async function presenceTrySetPeerMetadataJSON(e,t){ensureInitialized();const r=bytesFromString(t);throwOnErrorResult((await dittoffi_presence_try_set_peer_metadata_json(e,r)).error,"dittoffi_presence_try_set_peer_metadata_json")}function connectionRequestPeerKeyString(e){ensureInitialized();return boxCStringIntoString(dittoffi_connection_request_peer_key_string(e))}function connectionRequestPeerMetadataJSON(e){ensureInitialized();const t=refCBytesIntoBuffer(dittoffi_connection_request_peer_metadata_json(e));return(new TextDecoder).decode(t)}function connectionRequestIdentityServiceMetadataJSON(e){ensureInitialized();const t=refCBytesIntoBuffer(dittoffi_connection_request_identity_service_metadata_json());return(new TextDecoder).decode(t)}function connectionRequestConnectionType(e){return ensureInitialized(),dittoffi_connection_request_connection_type(e)}function connectionRequestAuthorize(e,t){ensureInitialized(),dittoffi_connection_request_authorize(e,t)}function connectionRequestFree(e){ensureInitialized(),dittoffi_connection_request_free(e)}function presenceSetConnectionRequestHandler(e,t,r){if(ensureInitialized(),null==t)dittoffi_presence_set_connection_request_handler(e,null);else{dittoffi_presence_set_connection_request_handler(e,wrapAsyncBackgroundCbForFFI(r,t))}}function dittoIsActivated(e){return ensureInitialized(),dittoffi_ditto_is_activated(e)}function dittoIsSyncActive(e){return ensureInitialized(),dittoffi_ditto_is_sync_active(e)}function dittoTryStartSync(e){ensureInitialized();throwOnErrorResult(dittoffi_ditto_try_start_sync(e).error,"dittoffi_ditto_try_start_sync")}function dittoStopSync(e){return ensureInitialized(),dittoffi_ditto_stop_sync(e)}function dittoSetTransportConfig(e,t){ensureInitialized();throwOnErrorResult(dittoffi_ditto_try_set_transport_config(e,t,!0).error,"dittoffi_ditto_try_set_transport_config")}function dittoTransportConfig(e){ensureInitialized();return boxCBytesIntoBuffer(dittoffi_ditto_transport_config(e))}function dittoSmallPeerInfoGetIsEnabled(e){return ensureInitialized(),ditto_small_peer_info_get_is_enabled(e)}function dittoSmallPeerInfoSetEnabled(e,t){return ensureInitialized(),ditto_small_peer_info_set_enabled(e,t)}function dittoSmallPeerInfoGetMetadata(e){ensureInitialized();return boxCStringIntoString(ditto_small_peer_info_get_metadata(e))}function dittoSmallPeerInfoSetMetadata(e,t){ensureInitialized();const r=ditto_small_peer_info_set_metadata(e,bytesFromString(t));switch(r){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()||`'${t}' is not a valid JSON object`}`);default:throw new Error(errorMessage()||`Internal inconsistency, ditto_small_peer_info_set_metadata() returned an unknown error code: ${r}`)}}function dittoRegisterTransportConditionChangedCallback(e,t){ensureInitialized(),ditto_register_transport_condition_changed_callback(e,t?wrapBackgroundCbForFFI(e=>log("Error",`The registered "transport condition changed" callback errored with ${e}`),t):null)}function dittoSetDeviceName(e,t){ensureInitialized();return boxCStringIntoString(ditto_set_device_name(e,bytesFromString(t)))}function dittoNewAttachmentFromFile(e,t,r){ensureInitialized();const n={},i=ditto_new_attachment_from_file(e,bytesFromString(t),r,n);if(0!==i)throw new DittoFFIError(i,void 0,`ditto_new_attachment_from_file() failed with error code: ${i}`);return n}async function dittoNewAttachmentFromBytes(e,t){ensureInitialized();const r={},n=await ditto_new_attachment_from_bytes(e,t,r);if(0!==n)throw new DittoFFIError(n,void 0,`ditto_new_attachment_from_bytes() failed with error code: ${n}`);return r}async function dittoResolveAttachment(e,t,r,n){ensureInitialized();const{onComplete:i,onProgress:o,onDelete:s}=r,a=wrapBackgroundCbForFFI(n,i),c=wrapBackgroundCbForFFI(n,o),d=wrapBackgroundCbForFFI(n,s),{status_code:u,cancel_token:l}=await ditto_resolve_attachment(e,t,a,c,d);if(0!==u)throw new DittoFFIError(u,void 0,`ditto_resolve_attachment() failed with error code: ${u}`);return l}function dittoCancelResolveAttachment(e,t,r){ensureInitialized();const n=ditto_cancel_resolve_attachment(e,t,r);if(0!==n)throw new Error(errorMessage()||`ditto_cancel_resolve_attachment() failed with error code: ${n}`)}function freeAttachmentHandle(e){ensureInitialized(),ditto_free_attachment_handle(e)}function dittoGetCompleteAttachmentPath(e,t){ensureInitialized();return refCStringToString(ditto_get_complete_attachment_path(e,t))}function dittoGetSDKSemver(){ensureInitialized();return boxCStringIntoString(dittoffi_get_sdk_semver())}function dittoPresenceV3(e){ensureInitialized();return boxCStringIntoString(ditto_presence_v3(e))}async function dittoShutdown(e){return ensureInitialized(),await ditto_shutdown(e)}function base64encode(e,t){return boxCStringIntoString(dittoffi_base64_encode(e,t))}function tryBase64Decode(e,t){const r=dittoffi_try_base64_decode(bytesFromString(e),t);return throwOnErrorResult(r.error,"dittoffi_try_base64_decode"),boxCBytesIntoBuffer(r.success)}async function dittoAuthSetLoginProvider(e,t){return ensureInitialized(),await ditto_auth_set_login_provider(e,t)}function dittoAuthClientMakeLoginProvider(e,t){return ensureInitialized(),ditto_auth_client_make_login_provider(wrapBackgroundCbForFFI(t,e))}function transportsInit(){ensureInitialized();const{output:e,errorType:t}=withTransportsError(ditto_sdk_transports_init);if(!1===e)throw new Error(`Failed to initialize transports (${t} error)`)}function withTransportsError(e,...t){const r=ditto_sdk_transports_error_new(),n=e(...t,r),i=ditto_sdk_transports_error_value(r);return ditto_sdk_transports_error_free(r),{output:n,errorType:i}}!function(e){e[e.counter=0]="counter",e[e.register=1]="register",e[e.attachment=2]="attachment",e[e.rga=3]="rga",e[e.rwMap=4]="rwMap"}(DittoCRDTType||(DittoCRDTType={}));let isInitialized$1=!1;function tryVerifyLicense(e,t){ensureInitialized();throwOnErrorResult(dittoffi_try_verify_license(e,bytesFromString(t)).error,"dittoffi_try_verify_license")}function defaultDeviceName(){return rnOnlyDefaultDeviceName()}function rnOnlyGetPlatform(){return getPlatform()}function rnOnlyDefaultDeviceName(){return defaultDeviceName$1()}function rnOnlyGetDefaultDirectory(){return getDefaultDirectory()}function rnOnlyReadFile(e){return readFile(e)}function rnOnlyCopyFile(e,t,r){return copyFile(e,t,r)}function wrapBackgroundCbForFFI(e,t){return t}function wrapAsyncBackgroundCbForFFI(e,t){return t}function bytesFromString(e){if(void 0===e)return;if(null===e)return null;if("string"!=typeof e)throw new Error(`Can't convert string to Uint8Array, not a string: ${e}`);return(new TextEncoder).encode(`${e}\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.",unknown:"An unexpected internal error occurred. Please get in touch with Ditto customer service to report this incident.",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:["unsupported"],Unknown:["unknown"],default:["unknown"]};class DittoError extends Error{constructor(e,t){if(null==ERROR_CODES[e])throw new DittoError("internal",`Invalid error code: ${e}`);super(t||ERROR_CODES[e]),this.code="internal",this.code=e}static fromFFIError(e,t,r){const n=r||e.message,i=new DittoError(t,n);return null!=e.stack&&(i.stack=e.stack),i}}function mapFFIErrors(e,t){try{return e()}catch(e){if(e instanceof DittoFFIError)throw translateFFIError(e,t);throw e}}async function mapFFIErrorsAsync(e,t){try{return await e()}catch(e){if(e instanceof DittoFFIError)throw translateFFIError(e,t);throw e}}const translateFFIError=(e,t)=>{const r=e.code.toString();let n,i;return null!=t&&null!=t[r]?[n,i]=t[r]:[n,i]=DEFAULT_STATUS_CODE_MAPPING[r]??DEFAULT_STATUS_CODE_MAPPING.default,DittoError.fromFFIError(e,n,i)};class AttachmentToken{constructor(e){let t,r,n;null!=e[DittoCRDTTypeKey]?({id:t,len:r,meta:n}=AttachmentToken.validateTypedInput(e)):({id:t,len:r,meta:n}=AttachmentToken.validateUntypedInput(e)),this.id=mapFFIErrors(()=>base64encode(t,"Unpadded")),this.idBytes=t,this.len=r,this.metadata=n}static validateTypedInput(e){if(e[DittoCRDTTypeKey]!==DittoCRDTType.attachment)throw new Error("Invalid attachment token");const t=e._id;if(!(t instanceof Uint8Array))throw new Error("Invalid attachment token id");const r=t.constructor===Uint8Array?t:new Uint8Array(t),n=e._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 i=e._meta;if("object"!=typeof i)throw new Error("Invalid attachment token meta");return{id:r,len:n,meta:i}}static validateUntypedInput(e){const t=e.id;if("string"!=typeof t)throw new Error("Invalid attachment token id");const r=mapFFIErrors(()=>tryBase64Decode(t,"Unpadded"),{Base64Invalid:["store/attachment-token-invalid","Failed to decode attachment token id from base64 input"]}),n=e.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 i=e.metadata;if("object"!=typeof i)throw new Error("Invalid attachment token meta");return{id:r,len:n,meta:i}}}class Logger{static get logFile(){return this._logFile}static get enabled(){return loggerEnabledGet()}static set enabled(e){loggerEnabled(e)}static get minimumLogLevel(){return loggerMinimumLogLevelGet()}static set minimumLogLevel(e){loggerMinimumLogLevel(e)}static get customLogCallback(){return this._customLogCallback}static async setCustomLogCallback(e){if(null!=e&&"function"!=typeof e)throw new TypeError(`Expected parameter 'callback' to be a function or undefined, but got ${typeof e}.`);null!=e?(await loggerSetCustomLogCb(e),this._customLogCallback=e):(await loggerSetCustomLogCb(null),delete this._customLogCallback)}static async exportToFile(e){if("string"!=typeof e)throw new TypeError(`Expected parameter 'path' to be a string, but got ${typeof e}.`);let t=e;return mapFFIErrorsAsync(()=>loggerTryExportToFile(t))}static log(e,t){log(e,t)}static error(e){this.log("Error",e)}static warning(e){this.log("Warning",e)}static info(e){this.log("Info",e)}static debug(e){this.log("Debug",e)}static verbose(e){this.log("Verbose",e)}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(e,t,r){this.isClosed=!1,this.isFinalized=!1,this.isUnregistered=!1,this.bridge=e,this.objectWeakRef=new WeakRef(t),this.pointer=r}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(){return this.isClosed||this.isFinalized||this.isUnregistered?null:this.pointer??null}object(){const e=this.objectWeakRef.deref();if(null==e)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 e}objectOrNull(){return this.objectWeakRef.deref()??null}toString(){const e=this.derefOrNull();return`{ Handle | type: ${this.bridge.type}, object: ${this.objectWeakRef.deref()}, FFI address: ${e?.addr}, FFI type: ${e?.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(e,t){this.handles=t.map(t=>e.handleFor(t))}deref(){return this.handles.map(e=>e.deref())}}class Bridge{constructor(e){this.internalType=null,this.release=e,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(e){if(this.internalType!==e){if(this.internalType)throw new Error(`Can't register bridged type '${e.name}', another type was already registered: ${this.internalType}`);this.internalType=e}}handleFor(e){const t=this.handlesByObject.get(e);if(null==t)throw new Error(`Bridging error: ${this.type.name} object is not currently registered in this bridge.`);return t}handlesFor(e){return new Handles(this,e)}objectFor(e){const t=this.handlesByAddress[e.addr];if(t){if(t.type!==this.type)throw new Error(`Can't return object for pointer, pointer is associated with an object of type ${t.type} but this bridge is configured for ${this.type}`);return t.object()}}bridge(e,t){const r=this.objectFor(e);if(r)return r;let n;if(t||(t=()=>Reflect.construct(this.type,[])),"function"==typeof t){if(n=t(),!(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=t;return this.register(n,e),n}register(e,t){const r=e.constructor;if(r!==this.type)throw new Error(`Can't register, bridge is configured for type ${this.type.name} but passed in object is of type ${r.name}`);const n=this.handlesByObject.get(e),i=n?n.pointer:null;if(null!=i&&null!=n)throw new Error(`Can't register, an object for the passed in pointer has previously been registered: ${n.object()}`);if(null!=i&&null==n)throw new Error(`Internal inconsistency, trying to register an object which has an associated pointer but no handle entry: ${r.name} at ${i.type} ${i.addr}`);if(null==i&&null!=n)throw new Error(`Internal inconsistency, trying to register an object which has a handle entry but no associated pointer: ${r.name} ${e}`);const o=new Handle(this,e,t);this.handlesByAddress[t.addr]=o,this.handlesByObject.set(e,o),this.finalizationRegistry.register(e,o,e),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(e){const t=e.constructor,r=this.type;if(t!==r)throw new Error(`Can't unregister, bridge is configured for type ${r.name} but passed in object is of type ${t.name}`);const n=this.handlesByObject.get(e);if(null==n)throw new Error(`Can't unregister, object has not been registered before: ${e}`);if(n.type!==r)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()!==e)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: ${e}`);if(n.isFinalized)throw new Error(`Can't unregister, object has been finalized before: ${e}`);if(n.isUnregistered)throw new Error(`Can't unregister, object has been unregistered already: ${e}`);n.bridgeWillUnregister(),this.finalizationRegistry.unregister(e),delete this.handlesByAddress[n.pointer.addr],this.handlesByObject.delete(e),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 e of Object.values(this.handlesByAddress)){const t=e.object();t&&this.unregister(t)}}async close(e){const t=e.constructor,r=this.type;if(t!==r)throw new Error(`Can't close, bridge is configured for type ${r.name} but passed in object is of type ${t.name}`);const n=this.handlesByObject.get(e);if(null==n)throw new Error(`Can't close an object that has not been registered before: ${e}`);if(n.type!==r)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 i=n.pointer;if(!i)throw new Error("Internal inconsistency, trying to close an object whose pointer is null.");n.bridgeWillClose(),delete this.handlesByAddress[i.addr],await this.release(i),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(e){if(e.isFinalized)throw new Error("Internal inconsistency, trying to finalize an object that has already been finalized.");if(e.isUnregistered)throw new Error("Internal inconsistency, trying to finalize an object that has been unregistered before.");if(e.bridgeWillFinalize(),!e.isClosed){const t=e.pointer;if(!t)throw new Error("Internal inconsistency, trying to finalize an object whose pointer is null.");delete this.handlesByAddress[t.addr],await this.release(t)}e.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.queryResult=new _a(queryResultFree),Bridge.queryResultItem=new _a(queryResultItemFree),Bridge.transaction=new _a(transactionFree),Bridge.differ=new _a(differFree),Bridge.storeObserver=new _a(storeObserverFree),Bridge.syncSubscription=new _a(syncSubscriptionFree),Bridge.ditto=new _a(async e=>{await dittoClearPresenceCallback(e),await dittoShutdown(e),dittoFree(e)});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 e=>{{const t=Bridge.attachment.handleFor(this),r=dittoGetCompleteAttachmentPath(e.deref(),t.deref());return await rnOnlyReadFile(r)}})}copyToPath(e){return this.ditto.deferCloseAsync(async t=>{{const r=Bridge.attachment.handleFor(this);rnOnlyCopyFile(dittoGetComplete