@dittolive/ditto 3.0.6-experimental.node-loading-issues.linux-x64.1 → 3.0.6-experimental.node-loading-issues.3.linux-x64
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/node/ditto.cjs.js +1 -1
- package/node/ditto.linux-x64.node +0 -0
- package/package.json +1 -1
- package/web/ditto.es6.js +1 -1
- package/web/ditto.umd.js +1 -1
- package/web/ditto.wasm +0 -0
- package/node/ditto.cjs.js.map +0 -1
- package/node/ditto.cjs.pretty.js +0 -6068
- package/node/ditto.cjs.pretty.js.map +0 -1
- package/types/ditto.d.ts.map +0 -1
- package/web/ditto.es6.js.map +0 -1
- package/web/ditto.es6.pretty.js +0 -8552
- package/web/ditto.es6.pretty.js.map +0 -1
- package/web/ditto.umd.js.map +0 -1
- package/web/ditto.umd.pretty.js +0 -8605
- package/web/ditto.umd.pretty.js.map +0 -1
package/README.md
CHANGED
|
@@ -3,10 +3,10 @@
|
|
|
3
3
|
*Ditto is a cross platform SDK that allows mobile, web, and IoT apps to sync
|
|
4
4
|
with and even without connectivity.*
|
|
5
5
|
|
|
6
|
-
Version: **3.0.6-experimental.node-loading-issues.linux-x64
|
|
6
|
+
Version: **3.0.6-experimental.node-loading-issues.3.linux-x64**
|
|
7
7
|
|
|
8
8
|
Please visit [ditto.live](https://ditto.live) for more info as well as the
|
|
9
|
-
[API Reference](https://software.ditto.live/js/Ditto/3.0.6-experimental.node-loading-issues.linux-x64
|
|
9
|
+
[API Reference](https://software.ditto.live/js/Ditto/3.0.6-experimental.node-loading-issues.3.linux-x64/api-reference/) for this particular version.
|
|
10
10
|
|
|
11
11
|
--------------------------------------------------------------------------------
|
|
12
12
|
|
package/node/ditto.cjs.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";const debugTypeNames=[];const debugAllTypes=false;class Meta{constructor(type,object,pointer){this.type=type;this.object=object;this.pointer=pointer}toString(){return`{ Meta | type: ${this.type.name}, object: ${this.object.deref()}, FFI address: ${this.pointer.addr}, FFI type: ${this.pointer.type} }`}}class Bridge{constructor(type,release,options={}){this.type=type;this.release=release;this.metaByAddrMap={};this.finalizationRegistry=new FinalizationRegistry(this.finalize.bind(this));Bridge.all.push(new WeakRef(this))}pointerFor(object){return object["@ditto.ptr"]}objectFor(pointer){const meta=this.metaByAddrMap[pointer.addr];if(!meta)return undefined;if(meta.type!==this.type)throw new Error(`Can't return object for pointer, pointer is associated with an object of type ${meta.type} but this bridge is configured for ${this.type}`);const object=meta.object.deref();if(!object)throw new Error(`Internal inconsistency, found a meta entry for an object whose object is undefined (garbage collected): ${pointer}`);return object}bridge(pointer,objectOrCreate,options={}){const throwIfAlreadyBridged=options["throwIfAlreadyBridged"];const existingObject=this.objectFor(pointer);if(existingObject&&throwIfAlreadyBridged){throw new Error(`Can't bridge, pointer has already been bridged: ${JSON.stringify(pointer)}`)}if(existingObject){return existingObject}if(!objectOrCreate){objectOrCreate=()=>Reflect.construct(this.type,[])}let object;if(typeof objectOrCreate==="function"){object=objectOrCreate();if(!object){throw new Error(`Can't bridge, expected passed in create function to return an object but got: ${object}`)}}else{object=objectOrCreate}this.register(object,pointer);return object}register(object,pointer){const objectType=object.constructor;const bridgeType=this.type;if(objectType!==bridgeType)throw new Error(`Can't register, bridge is configured for type ${bridgeType.name} but passed in object is of type ${objectType.name}`);const existingPointer=this.pointerFor(object);const existingMeta=this.metaByAddrMap[pointer.addr];if(existingPointer&&existingMeta)throw new Error(`Can't register, an object for the passed in pointer has previously been registered: ${existingMeta.pointer}`);if(existingPointer&&!existingMeta)throw new Error(`Internal inconsistency, trying to register an object which has an associated pointer but no meta entry: ${object}`);if(!existingPointer&&existingMeta)throw new Error(`Internal inconsistency, trying to register an object which has a meta entry but no associated pointer: ${object}`);const meta=new Meta(objectType,new WeakRef(object),pointer);object["@ditto.ptr"]=pointer;this.metaByAddrMap[meta.pointer.addr]=meta;this.finalizationRegistry.register(object,pointer,object);if(debugTypeNames.includes(this.type.name)||debugAllTypes){console.log(`[VERBOSE] Bridge REGISTERED a new instance of ${this.type.name}, current count: ${Object.keys(this.metaByAddrMap).length}`)}}unregister(object){const objectType=object.constructor;const bridgeType=this.type;if(objectType!==bridgeType)throw new Error(`Can't unregister, bridge is configured for type ${bridgeType.name} but passed in object is of type ${objectType.name}`);const pointer=this.pointerFor(object);if(!pointer)throw new Error(`Can't unregister, object that has not been registered before: ${object}`);const meta=this.metaByAddrMap[pointer.addr];if(!meta)throw new Error(`Internal inconsistency, trying to unregister an object which has an associated pointer but no meta entry: ${object}`);if(meta.type!==bridgeType)throw new Error(`Internal inconsistency, trying to unregister an object that has a meta entry with a different type than that of the bridge: ${meta}`);if(!meta.object.deref())throw new Error(`Internal inconsistency, trying to unregister an object that has a meta entry whose object is undfined (garbage collected): ${meta}`);if(meta.object.deref()!==object)throw new Error(`Internal inconsistency, trying to unregister an object that has a meta entry holding a different object: ${meta}`);this.finalizationRegistry.unregister(object);delete this.metaByAddrMap[pointer.addr];delete object["@ditto.ptr"];if(debugTypeNames.includes(this.type.name)||debugAllTypes){console.log(`[VERBOSE] Bridge UNREGISTERED an instance of ${this.type.name}, current count: ${Object.keys(this.metaByAddrMap).length}`)}}unregisterAll(){if(debugTypeNames.includes(this.type.name)||debugAllTypes){console.log(`[VERBOSE] Unregistering ALL bridged instances of type ${this.type.name}.`)}for(const meta of Object.values(this.metaByAddrMap)){const object=meta.object.deref();if(object){this.unregister(object)}}}get count(){return Object.keys(this.metaByAddrMap).length}finalize(pointer){const meta=this.metaByAddrMap[pointer.addr];if(!meta)throw new Error(`Internal inconsistency, tried to finalize an instance for a pointer, that has no meta entry: ${pointer}`);delete this.metaByAddrMap[pointer.addr];this.release(pointer);if(debugTypeNames.includes(this.type.name)||debugAllTypes){console.log(`[VERBOSE] Bridge FINALIZED an instance of ${this.type.name}, current count: ${Object.keys(this.metaByAddrMap).length}`)}}}Bridge.all=[];const defaultDittoCloudDomain=`cloud.ditto.live`;function defaultAuthURL(appID){return`https://${appID}.${defaultDittoCloudDomain}`}function defaultDittoCloudURL(appID){return`wss://${appID}.${defaultDittoCloudDomain}`}function validateNumber(value,options={}){var _a;const errorMessagePrefix=(_a=options["errorMessagePrefix"])!==null&&_a!==void 0?_a:"Number validation failed:";const integer=!!options["integer"];const min=options["min"];const max=options["max"];const minX=options["minX"];const maxX=options["maxX"];if(typeof value!=="number")throw new Error(`${errorMessagePrefix} '${value}' is not a number.`);if(integer&&Math.floor(value)!==value)throw new Error(`${errorMessagePrefix} '${value}' is not an integer.`);if(typeof min!=="undefined"&&value<min)throw new Error(`${errorMessagePrefix} '${value}' must be >= ${min}.`);if(typeof max!=="undefined"&&value>max)throw new Error(`${errorMessagePrefix} '${value}' must be <= ${max}.`);if(typeof minX!=="undefined"&&value<=minX)throw new Error(`${errorMessagePrefix} '${value}' must be > ${minX}.`);if(typeof maxX!=="undefined"&&value>=maxX)throw new Error(`${errorMessagePrefix} '${value}' must be < ${maxX}.`);return value}function validateQuery(query,options={}){var _a;const errorMessagePrefix=(_a=options["errorMessagePrefix"])!==null&&_a!==void 0?_a:"Query validation failed,";if(typeof query!=="string")throw new Error(`${errorMessagePrefix} query is not a string: ${query}`);if(query==="")throw new Error(`${errorMessagePrefix} query is an empty string.`);const validatedQuery=query.trim();if(validatedQuery==="")throw new Error(`${errorMessagePrefix} query contains only whitespace characters.`);return validatedQuery}class StaticTCPClient{}class WebsocketClient{}const staticTCPClientBridge=new Bridge(StaticTCPClient,staticTCPClientFreeHandle);const websocketClientBridge=new Bridge(WebsocketClient,websocketClientFreeHandle);function generateEphemeralToken(){let webcrypto=undefined;{webcrypto=require("crypto").webcrypto}const data=new Uint16Array(16);webcrypto.getRandomValues(data);const doublets=Array.from(data);return doublets.map((doublet=>doublet.toString(16))).join("")}function sleep(milliseconds){return new Promise(((resolve,reject)=>{setTimeout(resolve,milliseconds)}))}async function step(block){await sleep(0);return block()}const performAsyncToWorkaroundNonAsyncFFIAPI=step;const ditto=function(){const target=process.platform+"-"+process.arch;try{if(target==="darwin-x64")return require("./ditto.darwin-x64.node");if(target==="darwin-arm64")return require("./ditto.darwin-arm64.node");if(target==="linux-x64")return require("./ditto.linux-x64.node");if(target==="linux-arm")return require("./ditto.linux-arm.node");if(target==="win32-x64")return require("./ditto.win32-x64.node")}catch(error){throw new Error("Couldn't load native module 'ditto."+target+".node' due to error.",error)}throw new Error("No native module 'ditto."+target+".node' found.")}();function ble_client_free_handle(...args){return ditto.ble_client_free_handle(...args)}function ble_server_free_handle(...args){return ditto.ble_server_free_handle(...args)}function boxCBytesIntoBuffer(...args){return ditto.boxCBytesIntoBuffer(...args)}function boxCStringIntoString(...args){return ditto.boxCStringIntoString(...args)}function cStringVecToStringArray(...args){return ditto.cStringVecToStringArray(...args)}function ditto_add_internal_ble_client_transport(...args){return ditto.ditto_add_internal_ble_client_transport(...args)}function ditto_add_internal_ble_server_transport(...args){return ditto.ditto_add_internal_ble_server_transport(...args)}function ditto_add_internal_mdns_advertiser(...args){return ditto.ditto_add_internal_mdns_advertiser(...args)}function ditto_add_internal_mdns_transport(...args){return ditto.ditto_add_internal_mdns_transport(...args)}function ditto_add_multicast_transport(...args){return ditto.ditto_add_multicast_transport(...args)}function ditto_add_static_tcp_client(...args){return ditto.ditto_add_static_tcp_client(...args)}function ditto_add_subscription(...args){return ditto.ditto_add_subscription(...args)}function ditto_add_websocket_client(...args){return ditto.ditto_add_websocket_client(...args)}function ditto_auth_client_free(...args){return ditto.ditto_auth_client_free(...args)}function ditto_auth_client_get_site_id(...args){return ditto.ditto_auth_client_get_site_id(...args)}function ditto_auth_client_is_web_valid(...args){return ditto.ditto_auth_client_is_web_valid(...args)}function ditto_auth_client_is_x509_valid(...args){return ditto.ditto_auth_client_is_x509_valid(...args)}function ditto_auth_client_login_with_credentials(...args){return ditto.ditto_auth_client_login_with_credentials(...args)}function ditto_auth_client_login_with_token(...args){return ditto.ditto_auth_client_login_with_token(...args)}function ditto_auth_client_logout(...args){return ditto.ditto_auth_client_logout(...args)}function ditto_auth_client_make_anonymous_client(...args){return ditto.ditto_auth_client_make_anonymous_client(...args)}function ditto_auth_client_make_for_development(...args){return ditto.ditto_auth_client_make_for_development(...args)}function ditto_auth_client_make_login_provider(...args){return ditto.ditto_auth_client_make_login_provider(...args)}function ditto_auth_client_make_with_shared_key(...args){return ditto.ditto_auth_client_make_with_shared_key(...args)}function ditto_auth_client_make_with_static_x509(...args){return ditto.ditto_auth_client_make_with_static_x509(...args)}function ditto_auth_client_make_with_web(...args){return ditto.ditto_auth_client_make_with_web(...args)}function ditto_auth_client_set_validity_listener(...args){return ditto.ditto_auth_client_set_validity_listener(...args)}function ditto_auth_client_user_id(...args){return ditto.ditto_auth_client_user_id(...args)}function ditto_cancel_resolve_attachment(...args){return ditto.ditto_cancel_resolve_attachment(...args)}function ditto_clear_presence_callback(...args){return ditto.ditto_clear_presence_callback(...args)}function ditto_clear_presence_v3_callback(...args){return ditto.ditto_clear_presence_v3_callback(...args)}function ditto_collection_evict(...args){return ditto.ditto_collection_evict(...args)}function ditto_collection_evict_query_str(...args){return ditto.ditto_collection_evict_query_str(...args)}function ditto_collection_exec_query_str(...args){return ditto.ditto_collection_exec_query_str(...args)}function ditto_collection_get(...args){return ditto.ditto_collection_get(...args)}function ditto_collection_insert_value(...args){return ditto.ditto_collection_insert_value(...args)}function ditto_collection_remove(...args){return ditto.ditto_collection_remove(...args)}function ditto_collection_remove_query_str(...args){return ditto.ditto_collection_remove_query_str(...args)}function ditto_collection_update(...args){return ditto.ditto_collection_update(...args)}function ditto_collection_update_multiple(...args){return ditto.ditto_collection_update_multiple(...args)}function ditto_disable_sync_with_v2(...args){return ditto.ditto_disable_sync_with_v2(...args)}function ditto_document_free(...args){return ditto.ditto_document_free(...args)}function ditto_document_get_cbor_with_path_type(...args){return ditto.ditto_document_get_cbor_with_path_type(...args)}function ditto_document_id(...args){return ditto.ditto_document_id(...args)}function ditto_document_id_query_compatible(...args){return ditto.ditto_document_id_query_compatible(...args)}function ditto_document_increment_counter(...args){return ditto.ditto_document_increment_counter(...args)}function ditto_document_remove(...args){return ditto.ditto_document_remove(...args)}function ditto_document_set_cbor(...args){return ditto.ditto_document_set_cbor(...args)}function ditto_document_set_cbor_with_timestamp(...args){return ditto.ditto_document_set_cbor_with_timestamp(...args)}function ditto_documents_hash(...args){return ditto.ditto_documents_hash(...args)}function ditto_documents_hash_mnemonic(...args){return ditto.ditto_documents_hash_mnemonic(...args)}function ditto_error_message(...args){return ditto.ditto_error_message(...args)}function ditto_free(...args){return ditto.ditto_free(...args)}function ditto_free_attachment_handle(...args){return ditto.ditto_free_attachment_handle(...args)}function ditto_get_collection_names(...args){return ditto.ditto_get_collection_names(...args)}function ditto_get_complete_attachment_path(...args){return ditto.ditto_get_complete_attachment_path(...args)}function ditto_get_sdk_version(...args){return ditto.ditto_get_sdk_version(...args)}function ditto_init_sdk_version(...args){return ditto.ditto_init_sdk_version(...args)}function ditto_live_query_register_str_detached(...args){return ditto.ditto_live_query_register_str_detached(...args)}function ditto_live_query_signal_available_next(...args){return ditto.ditto_live_query_signal_available_next(...args)}function ditto_live_query_start(...args){return ditto.ditto_live_query_start(...args)}function ditto_live_query_stop(...args){return ditto.ditto_live_query_stop(...args)}function ditto_live_query_webhook_register_str(...args){return ditto.ditto_live_query_webhook_register_str(...args)}function ditto_log(...args){return ditto.ditto_log(...args)}function ditto_logger_emoji_headings_enabled(...args){return ditto.ditto_logger_emoji_headings_enabled(...args)}function ditto_logger_emoji_headings_enabled_get(...args){return ditto.ditto_logger_emoji_headings_enabled_get(...args)}function ditto_logger_enabled(...args){return ditto.ditto_logger_enabled(...args)}function ditto_logger_enabled_get(...args){return ditto.ditto_logger_enabled_get(...args)}function ditto_logger_init(...args){return ditto.ditto_logger_init(...args)}function ditto_logger_minimum_log_level(...args){return ditto.ditto_logger_minimum_log_level(...args)}function ditto_logger_minimum_log_level_get(...args){return ditto.ditto_logger_minimum_log_level_get(...args)}function ditto_logger_set_custom_log_cb(...args){return ditto.ditto_logger_set_custom_log_cb(...args)}function ditto_logger_set_log_file(...args){return ditto.ditto_logger_set_log_file(...args)}function ditto_make(...args){return ditto.ditto_make(...args)}function ditto_new_attachment_from_bytes(...args){return ditto.ditto_new_attachment_from_bytes(...args)}function ditto_new_attachment_from_file(...args){return ditto.ditto_new_attachment_from_file(...args)}function ditto_presence_v1(...args){return ditto.ditto_presence_v1(...args)}function ditto_presence_v3(...args){return ditto.ditto_presence_v3(...args)}function ditto_read_transaction(...args){return ditto.ditto_read_transaction(...args)}function ditto_read_transaction_free(...args){return ditto.ditto_read_transaction_free(...args)}function ditto_register_presence_v1_callback(...args){return ditto.ditto_register_presence_v1_callback(...args)}function ditto_register_presence_v3_callback(...args){return ditto.ditto_register_presence_v3_callback(...args)}function ditto_register_transport_condition_changed_callback(...args){return ditto.ditto_register_transport_condition_changed_callback(...args)}function ditto_remove_multicast_transport(...args){return ditto.ditto_remove_multicast_transport(...args)}function ditto_remove_subscription(...args){return ditto.ditto_remove_subscription(...args)}function ditto_resolve_attachment(...args){return ditto.ditto_resolve_attachment(...args)}function ditto_run_garbage_collection(...args){return ditto.ditto_run_garbage_collection(...args)}function ditto_set_device_name(...args){return ditto.ditto_set_device_name(...args)}function ditto_set_sync_group(...args){return ditto.ditto_set_sync_group(...args)}function ditto_start_http_server(...args){return ditto.ditto_start_http_server(...args)}function ditto_start_tcp_server(...args){return ditto.ditto_start_tcp_server(...args)}function ditto_stop_http_server(...args){return ditto.ditto_stop_http_server(...args)}function ditto_stop_tcp_server(...args){return ditto.ditto_stop_tcp_server(...args)}function ditto_validate_document_id(...args){return ditto.ditto_validate_document_id(...args)}function ditto_write_transaction(...args){return ditto.ditto_write_transaction(...args)}function ditto_write_transaction_commit(...args){return ditto.ditto_write_transaction_commit(...args)}function jsDocsToCDocs(...args){return ditto.jsDocsToCDocs(...args)}function mdns_client_free_handle(...args){return ditto.mdns_client_free_handle(...args)}function mdns_server_free_handle(...args){return ditto.mdns_server_free_handle(...args)}function refCStringToString(...args){return ditto.refCStringToString(...args)}function static_tcp_client_free_handle(...args){return ditto.static_tcp_client_free_handle(...args)}function uninitialized_ditto_make(...args){return ditto.uninitialized_ditto_make(...args)}function verify_license(...args){return ditto.verify_license(...args)}function websocket_client_free_handle(...args){return ditto.websocket_client_free_handle(...args)}function withOutBoxCBytes(...args){return ditto.withOutBoxCBytes(...args)}function withOutPtr$1(...args){return ditto.withOutPtr(...args)}const DittoCRDTTypeKey="_ditto_internal_type_jkb12973t4b";const DittoCRDTValueKey="_value";var DittoCRDTType;(function(DittoCRDTType){DittoCRDTType[DittoCRDTType["counter"]=0]="counter";DittoCRDTType[DittoCRDTType["register"]=1]="register";DittoCRDTType[DittoCRDTType["attachment"]=2]="attachment";DittoCRDTType[DittoCRDTType["rga"]=3]="rga";DittoCRDTType[DittoCRDTType["rwMap"]=4]="rwMap"})(DittoCRDTType||(DittoCRDTType={}));function dittoAddInternalBLEClientTransport(ditto){{return ditto_add_internal_ble_client_transport(ditto)}}function dittoAddInternalBLEServerTransport(ditto){{return ditto_add_internal_ble_server_transport(ditto)}}function bleClientFreeHandle(handle){{return ble_client_free_handle(handle)}}function bleServerFreeHandle(handle){{return ble_server_free_handle(handle)}}function dittoAddInternalMdnsTransport(ditto){{return ditto_add_internal_mdns_transport(ditto)}}function mdnsClientFreeHandle(handle){{return mdns_client_free_handle(handle)}}function dittoAddInternalMdnsAdvertiser(ditto){{return ditto_add_internal_mdns_advertiser(ditto)}}function mdnsServerFreeHandle(handle){{return mdns_server_free_handle(handle)}}function documentSetCBORWithTimestamp(document,path,cbor,createPath,timestamp){ensureInitialized();const pathX=bytesFromString(path);const errorCode=ditto_document_set_cbor_with_timestamp(document,pathX,cbor,createPath,timestamp);if(errorCode!==0)throw new Error(errorMessage()||`ditto_document_set_cbor_with_timestamp() failed with error code: ${errorCode}`)}function documentSetCBOR(document,path,cbor,createPath){ensureInitialized();const pathX=bytesFromString(path);const errorCode=ditto_document_set_cbor(document,pathX,cbor,createPath);if(errorCode!==0)throw new Error(errorMessage()||`ditto_document_set_cbor() failed with error code: ${errorCode}`)}function documentID(self){ensureInitialized();const documentIDX=ditto_document_id(self);return boxCBytesIntoBuffer(documentIDX)}function documentGetCBORWithPathType(document,path,pathType){ensureInitialized();const pathBytes=bytesFromString(path);const cborPathResultRaw=ditto_document_get_cbor_with_path_type(document,pathBytes,pathType);const cborPathResult={statusCode:cborPathResultRaw.status_code,cbor:boxCBytesIntoBuffer(cborPathResultRaw.cbor)};return cborPathResult}function documentRemove(document,path){ensureInitialized();const pathBytes=bytesFromString(path);const errorCode=ditto_document_remove(document,pathBytes);if(errorCode!==0)throw new Error(errorMessage()||`ditto_document_remove() failed with error code: ${errorCode}`)}function documentIncrementCounter(document,path,amount){ensureInitialized();const pathBytes=bytesFromString(path);const errorCode=ditto_document_increment_counter(document,pathBytes,amount);if(errorCode!==0)throw new Error(errorMessage()||`ditto_document_increment_counter() failed with error code: ${errorCode}`)}function documentFree(self){ensureInitialized();ditto_document_free(self)}function documentIDQueryCompatible(docID,stringPrimitiveFormat){ensureInitialized();const docIDString=ditto_document_id_query_compatible(docID,stringPrimitiveFormat);return boxCStringIntoString(docIDString)}function validateDocumentID(docID){ensureInitialized();const cborCBytes=withOutBoxCBytes((outCBOR=>{const errorCode=ditto_validate_document_id(docID,outCBOR);if(errorCode!==0)throw new Error(errorMessage()||`ditto_validate_document_id() failed with error code: ${errorCode}`);return outCBOR}));return boxCBytesIntoBuffer(cborCBytes)}async function collectionGet(ditto,collectionName,documentID,readTransaction){ensureInitialized();const collectionNameX=bytesFromString(collectionName);const{status_code:errorCode,document:document}=await ditto_collection_get(ditto,collectionNameX,documentID,readTransaction);if(errorCode===NOT_FOUND_ERROR_CODE)return null;if(errorCode!==0)throw new Error(errorMessage()||`ditto_collection_get() failed with error code: ${errorCode}`);return document}async function collectionInsertValue(ditto,collectionName,doc_cbor,doc_id,writeStrategy){ensureInitialized();const collectionNameX=bytesFromString(collectionName);let strategy;switch(writeStrategy){case"merge":strategy="Merge";break;case"insertIfAbsent":strategy="InsertIfAbsent";break;case"insertDefaultIfAbsent":strategy="InsertDefaultIfAbsent";break;default:throw new Error("Invalid write strategy provided")}const{status_code:errorCode,id:id}=await ditto_collection_insert_value(ditto,collectionNameX,doc_cbor,doc_id,strategy,null,null);if(errorCode!==0)throw new Error(errorMessage()||`ditto_collection_insert_value() failed with error code: ${errorCode}`);return boxCBytesIntoBuffer(id)}async function collectionRemove(ditto,collectionName,writeTransaction,documentID){ensureInitialized();const collectionNameX=bytesFromString(collectionName);const{status_code:errorCode,bool_value:didRemove}=await ditto_collection_remove(ditto,collectionNameX,writeTransaction,documentID);if(errorCode!==0)throw new Error(errorMessage()||`ditto_collection_remove() failed with error code: ${errorCode}`);return didRemove}async function collectionEvict(ditto,collectionName,writeTransaction,documentID){ensureInitialized();const collectionNameX=bytesFromString(collectionName);const{status_code:errorCode,bool_value:didEvict}=await ditto_collection_evict(ditto,collectionNameX,writeTransaction,documentID);if(errorCode!==0)throw new Error(errorMessage()||`ditto_collection_evict() failed with error code: ${errorCode}`);return didEvict}async function collectionUpdate(ditto,collectionName,writeTransaction,document){ensureInitialized();const collectionNameX=bytesFromString(collectionName);const errorCode=await ditto_collection_update(ditto,collectionNameX,writeTransaction,document);if(errorCode!==0)throw new Error(errorMessage()||`ditto_collection_update() failed with error code: ${errorCode}`)}async function collectionUpdateMultiple(ditto,collectionName,writeTransaction,documents){ensureInitialized();const collectionNameX=bytesFromString(collectionName);const cDocuments=jsDocsToCDocs(documents);const errorCode=await ditto_collection_update_multiple(ditto,collectionNameX,writeTransaction,cDocuments);if(errorCode!==0)throw new Error(errorMessage()||`ditto_collection_update_multiple() failed with error code: ${errorCode}`)}async function collectionExecQueryStr(ditto,collectionName,writeTransaction,query,queryArgsCBOR,orderBy,limit,offset){ensureInitialized();const collectionNameX=bytesFromString(collectionName);const queryX=bytesFromString(query);return await ditto_collection_exec_query_str(ditto,collectionNameX,writeTransaction,queryX,queryArgsCBOR,orderBy,limit,offset)}async function collectionRemoveQueryStr(ditto,collectionName,writeTransaction,query,queryArgsCBOR,orderBy,limit,offset){ensureInitialized();const collectionNameX=bytesFromString(collectionName);const queryX=bytesFromString(query);return await ditto_collection_remove_query_str(ditto,collectionNameX,writeTransaction,queryX,queryArgsCBOR,orderBy,limit,offset)}async function collectionEvictQueryStr(ditto,collectionName,writeTransaction,query,queryArgsCBOR,orderBy,limit,offset){ensureInitialized();const collectionNameX=bytesFromString(collectionName);const queryX=bytesFromString(query);return await ditto_collection_evict_query_str(ditto,collectionNameX,writeTransaction,queryX,queryArgsCBOR,orderBy,limit,offset)}function addSubscription(ditto,collectionName,query,queryArgsCBOR,orderBy,limit,offset){ensureInitialized();const collectionNameX=bytesFromString(collectionName);const queryX=bytesFromString(query);return ditto_add_subscription(ditto,collectionNameX,queryX,queryArgsCBOR,orderBy,limit,offset)}function removeSubscription(ditto,collectionName,query,queryArgsCBOR,orderBy,limit,offset){ensureInitialized();const collectionNameX=bytesFromString(collectionName);const queryX=bytesFromString(query);return ditto_remove_subscription(ditto,collectionNameX,queryX,queryArgsCBOR,orderBy,limit,offset)}function liveQueryRegister(ditto,collectionName,query,queryArgsCBOR,orderBy,limit,offset,eventHandler,onError){ensureInitialized();const collectionNameBuffer=bytesFromString(collectionName);const queryBuffer=bytesFromString(query);const{status_code:errorCode,i64:id}=ditto_live_query_register_str_detached(ditto,collectionNameBuffer,queryBuffer,queryArgsCBOR,orderBy,limit,offset,wrapBackgroundCbForFFI(onError,eventHandler));if(errorCode!==0)throw new Error(errorMessage()||`\`ditto_live_query_register_str()\` failed with error code: ${errorCode}`);return id}async function liveQueryStart(ditto,liveQueryID){ensureInitialized();const errorCode=await ditto_live_query_start(ditto,liveQueryID);if(errorCode!==0)throw new Error(errorMessage()||`\`ditto_live_query_start()\` failed with error code: ${errorCode}`)}function liveQueryStop(ditto,liveQueryID){ensureInitialized();ditto_live_query_stop(ditto,liveQueryID)}async function liveQuerySignalAvailableNext(ditto,liveQueryID){ensureInitialized();await ditto_live_query_signal_available_next(ditto,liveQueryID)}async function liveQueryWebhookRegister(ditto,collectionName,query,orderBy,limit,offset,url){ensureInitialized();const collectionNameBuffer=bytesFromString(collectionName);const queryBuffer=bytesFromString(query);const urlBuffer=bytesFromString(url);const{status_code:errorCode,id:id}=await ditto_live_query_webhook_register_str(ditto,collectionNameBuffer,queryBuffer,orderBy,limit,offset,urlBuffer);if(errorCode!==0)throw new Error(errorMessage()||`\`ditto_live_query_webhook_register_str()\` failed with error code: ${errorCode}`);return boxCBytesIntoBuffer(id)}async function readTransaction(ditto){ensureInitialized();const{status_code:errorCode,txn:readTransaction}=await ditto_read_transaction(ditto);if(errorCode!==0)throw new Error(errorMessage()||`\`ditto_read_transaction()\` failed with error code: ${errorCode}`);return readTransaction}function readTransactionFree(self){ensureInitialized();return ditto_read_transaction_free(self)}async function writeTransaction(ditto){ensureInitialized();const{status_code:errorCode,txn:writeTransaction}=await ditto_write_transaction(ditto,null);if(errorCode!==0)throw new Error(errorMessage()||`ditto_write_transaction() failed with error code: ${errorCode}`);return writeTransaction}async function writeTransactionCommit(ditto,self){ensureInitialized();const errorCode=await ditto_write_transaction_commit(ditto,self);if(errorCode!==0)throw new Error(errorMessage()||`ditto_write_transaction_commit() failed with error code: ${errorCode}`)}function addStaticTCPClient(ditto,address){ensureInitialized();const addressBuffer=bytesFromString(address);return ditto_add_static_tcp_client(ditto,addressBuffer)}function staticTCPClientFreeHandle(self){static_tcp_client_free_handle(self)}function addWebsocketClient(ditto,address,routingHint){ensureInitialized();const addressBuffer=bytesFromString(address);return ditto_add_websocket_client(ditto,addressBuffer,routingHint)}function websocketClientFreeHandle(self){ensureInitialized();websocket_client_free_handle(self)}function loggerInit(){ensureInitialized();ditto_logger_init()}async function loggerSetCustomLogCb(cb){ensureInitialized();if(null===cb){await ditto_logger_set_custom_log_cb(null)}else{const wrappedCallback=wrapBackgroundCbForFFI(null,((loglevel,cMsg)=>{try{const msg=boxCStringIntoString(cMsg);cb(loglevel,msg)}catch(e){console.error(`The registered cb in \`ditto_logger_set_custom_log_cb()\` failed with: ${e}`)}}));await ditto_logger_set_custom_log_cb(wrappedCallback)}}function loggerEnabled(enabled){ensureInitialized();ditto_logger_enabled(!!enabled)}function loggerEnabledGet(){ensureInitialized();return!!ditto_logger_enabled_get()}function loggerEmojiHeadingsEnabled(loggerEmojiHeadingsEnabled){ensureInitialized();ditto_logger_emoji_headings_enabled(loggerEmojiHeadingsEnabled)}function loggerEmojiHeadingsEnabledGet(){ensureInitialized();return ditto_logger_emoji_headings_enabled_get()}function loggerMinimumLogLevel(logLevel){ensureInitialized();ditto_logger_minimum_log_level(logLevel)}function loggerMinimumLogLevelGet(){ensureInitialized();return ditto_logger_minimum_log_level_get()}function loggerSetLogFile(path){ensureInitialized();const pathBytesOrNull=path?bytesFromString(path):null;const errorCode=ditto_logger_set_log_file(pathBytesOrNull);if(errorCode!==0){errorMessage();throw new Error(`Can't set log file, due to error: ${errorMessage}`)}}function log(level,message){ensureInitialized();bytesFromString(level);const messageBuffer=bytesFromString(message);ditto_log(level,messageBuffer)}function dittoAuthClientMakeAnonymousClient(path,appID,sharedToken,baseURL){ensureInitialized();const pathX=bytesFromString(path);const appIDX=bytesFromString(appID);const sharedTokenX=bytesFromString(sharedToken);const baseURLX=bytesFromString(baseURL);const{status_code:errorCode,auth_client:authClient}=ditto_auth_client_make_anonymous_client(pathX,appIDX,sharedTokenX,baseURLX);if(errorCode!==0)throw new Error(errorMessage()||`ditto_auth_client_make_anonymous_client() failed with error code: ${errorCode}`);return authClient}function dittoAuthClientMakeWithWeb(path,appID,baseURL,loginProvider){ensureInitialized();const pathX=bytesFromString(path);const appIDX=bytesFromString(appID);const baseURLX=bytesFromString(baseURL);const{status_code:errorCode,auth_client:authClient}=ditto_auth_client_make_with_web(pathX,appIDX,baseURLX,loginProvider);if(errorCode!==0)throw new Error(errorMessage()||`ditto_auth_client_make_with_web() failed with error code: ${errorCode}`);return authClient}function dittoAuthClientMakeForDevelopment(path,appId,siteID){ensureInitialized();const pathX=bytesFromString(path);const appIdX=bytesFromString(appId);const siteIDX=Number(siteID);const{status_code:errorCode,auth_client:authClient}=ditto_auth_client_make_for_development(pathX,appIdX,siteIDX);if(errorCode!==0)throw new Error(errorMessage()||`ditto_auth_client_make_for_development() failed with error code: ${errorCode}`);return authClient}function dittoAuthClientMakeWithSharedKey(path,appId,sharedKey,siteID){ensureInitialized();const pathX=bytesFromString(path);const appIdX=bytesFromString(appId);const sharedKeyX=bytesFromString(sharedKey);const siteIDX=Number(siteID);const{status_code:errorCode,auth_client:authClient}=ditto_auth_client_make_with_shared_key(pathX,appIdX,sharedKeyX,siteIDX);if(errorCode!==0)throw new Error(errorMessage()||`ditto_auth_client_make_with_shared_key() failed with error code: ${errorCode}`);return authClient}function dittoAuthClientMakeWithStaticX509(configCBORBase64){ensureInitialized();const configCBORBase64X=bytesFromString(configCBORBase64);const{status_code:errorCode,auth_client:authClient}=ditto_auth_client_make_with_static_x509(configCBORBase64X);if(errorCode!==0)throw new Error(errorMessage()||`ditto_auth_client_make_with_static_x509() failed with error code: ${errorCode}`);return authClient}function dittoAuthClientGetSiteID(authClient){ensureInitialized();return ditto_auth_client_get_site_id(authClient)}function dittoAuthClientFree(authClient){ensureInitialized();return ditto_auth_client_free(authClient)}function dittoAuthClientIsWebValid(authClient){ensureInitialized();return ditto_auth_client_is_web_valid(authClient)!==0}function dittoAuthClientUserID(authClient){ensureInitialized();const cStr=ditto_auth_client_user_id(authClient);return boxCStringIntoString(cStr)}function dittoAuthClientIsX509Valid(authClient){ensureInitialized();return ditto_auth_client_is_x509_valid(authClient)!==0}async function dittoAuthClientLoginWithToken(authClient,token,provider){ensureInitialized();const tokenBytes=bytesFromString(token);const providerBytes=bytesFromString(provider);const errorCode=await ditto_auth_client_login_with_token(authClient,tokenBytes,providerBytes);if(errorCode!==0)throw new Error(errorMessage()||`Ditto failed to authenticate (error code: ${errorCode}).`)}async function dittoAuthClientLoginWithUsernameAndPassword(authClient,username,password,provider){ensureInitialized();const usernameBytes=bytesFromString(username);const passwordBytes=bytesFromString(password);const providerBytes=bytesFromString(provider);const errorCode=await ditto_auth_client_login_with_credentials(authClient,usernameBytes,passwordBytes,providerBytes);if(errorCode!==0)throw new Error(errorMessage()||`Ditto failed to authenticate (error code: ${errorCode}).`)}async function dittoAuthClientLogout(authClient){ensureInitialized();const errorCode=await ditto_auth_client_logout(authClient);if(errorCode!==0)throw new Error(errorMessage()||`Ditto failed to logout (error code: ${errorCode}).`)}function uninitializedDittoMake(path){ensureInitialized();const pathX=bytesFromString(path);return uninitialized_ditto_make(pathX)}function dittoMake(uninitializedDitto,authClient){ensureInitialized();return ditto_make(uninitializedDitto,authClient,"Disabled")}async function dittoGetCollectionNames(self){ensureInitialized();const result=await ditto_get_collection_names(self);const errorCode=result.status_code;const cStringVec=result.names;if(errorCode!==0)throw new Error(errorMessage()||`ditto_get_collection_names() failed with error code: ${errorCode}`);const strings=cStringVecToStringArray(cStringVec);return strings}function dittoFree(self){ensureInitialized();return ditto_free(self)}async function dittoRegisterPresenceV1Callback(self,cb){ensureInitialized();if(cb){ditto_register_presence_v1_callback(self,wrapBackgroundCbForFFI((err=>console.error(`The registered presence callback errored with ${err}`)),(cJsonStr=>{const jsonStr=refCStringToString(cJsonStr);cb(jsonStr)})))}else{await ditto_clear_presence_callback(self)}}async function dittoRegisterPresenceV3Callback(self,cb){ensureInitialized();ditto_register_presence_v3_callback(self,wrapBackgroundCbForFFI((err=>console.error(`The registered presence callback v3 errored with ${err}`)),(cJsonStr=>{const jsonStr=refCStringToString(cJsonStr);cb(jsonStr)})))}async function dittoClearPresenceV3Callback(self){ensureInitialized();ditto_clear_presence_v3_callback(self)}async function dittoClearPresenceCallback(self){ensureInitialized();await ditto_clear_presence_callback(self)}function dittoRegisterTransportConditionChangedCallback(self,cb){ensureInitialized();if(!cb){ditto_register_transport_condition_changed_callback(self,null)}else{ditto_register_transport_condition_changed_callback(self,wrapBackgroundCbForFFI((err=>console.error(`The registered "transport condition changed" callback errored with ${err}`)),cb))}}function dittoSetDeviceName(dittoPointer,deviceName){ensureInitialized();let deviceNameCString=bytesFromString(deviceName);return ditto_set_device_name(dittoPointer,deviceNameCString)}function dittoSetSyncGroup(dittoPointer,syncGroup){ensureInitialized();return ditto_set_sync_group(dittoPointer,syncGroup)}function dittoNewAttachmentFromFile(ditto,sourcePath,fileOperation){ensureInitialized();const sourcePathCString=bytesFromString(sourcePath);const outAttachment={};const errorCode=ditto_new_attachment_from_file(ditto,sourcePathCString,fileOperation,outAttachment);if(errorCode!==0){throw new Error(errorMessage()||`ditto_new_attachment_from_file() failed with error code: ${errorCode}`)}return outAttachment}async function dittoNewAttachmentFromBytes(ditto,bytes){ensureInitialized();const outAttachment={};const errorCode=await ditto_new_attachment_from_bytes(ditto,bytes,outAttachment);if(errorCode!==0){throw new Error(errorMessage()||`ditto_new_attachment_from_bytes() failed with error code: ${errorCode}`)}return outAttachment}async function dittoResolveAttachment(ditto,id,namedCallbacks,onError){ensureInitialized();const{onComplete:onComplete,onProgress:onProgress,onDelete:onDelete}=namedCallbacks;const{status_code:errorCode,cancel_token:cancelToken}=await ditto_resolve_attachment(ditto,id,wrapBackgroundCbForFFI(onError,onComplete),wrapBackgroundCbForFFI(onError,onProgress),wrapBackgroundCbForFFI(onError,onDelete));if(errorCode!==0){throw new Error(errorMessage()||`ditto_resolve_attachment() failed with error code: ${errorCode}`)}return cancelToken}function dittoCancelResolveAttachment(dittoPointer,id,cancelToken){ensureInitialized();const errorCode=ditto_cancel_resolve_attachment(dittoPointer,id,cancelToken);if(errorCode!==0)throw new Error(errorMessage()||`ditto_cancel_resolve_attachment() failed with error code: ${errorCode}`)}function freeAttachmentHandle(attachmentHandlePointer){ensureInitialized();ditto_free_attachment_handle(attachmentHandlePointer)}function dittoGetCompleteAttachmentPath(dittoPointer,attachmentHandlePointer){ensureInitialized();const pathCString=ditto_get_complete_attachment_path(dittoPointer,attachmentHandlePointer);return refCStringToString(pathCString)}function dittoGetSDKVersion(ditto){ensureInitialized();const cString=ditto_get_sdk_version(ditto);return boxCStringIntoString(cString)}function dittoPresenceV1(self){ensureInitialized();const cString=ditto_presence_v1(self);return boxCStringIntoString(cString)}function dittoPresenceV3(self){ensureInitialized();const cString=ditto_presence_v3(self);return boxCStringIntoString(cString)}function dittoStartTCPServer(dittoPointer,bind){ensureInitialized();const bindBuffer=bytesFromString(bind);return ditto_start_tcp_server(dittoPointer,bindBuffer)}function dittoStopTCPServer(dittoPointer){ensureInitialized();return ditto_stop_tcp_server(dittoPointer)}function dittoAddMulticastTransport(dittoPointer){ensureInitialized();return ditto_add_multicast_transport(dittoPointer)}function dittoRemoveMulticastTransport(dittoPointer){ensureInitialized();return ditto_remove_multicast_transport(dittoPointer)}function dittoStartHTTPServer(dittoPointer,bind,staticPath,websocketMode,tlsCertPath,tlsKeyPath){ensureInitialized();const bindBuffer=bytesFromString(bind);const staticPathBuffer=bytesFromString(staticPath);const tlsCertPathBuffer=bytesFromString(tlsCertPath);const tlsKeyPathBuffer=bytesFromString(tlsKeyPath);return ditto_start_http_server(dittoPointer,bindBuffer,staticPathBuffer,websocketMode,tlsCertPathBuffer,tlsKeyPathBuffer)}function dittoStopHTTPServer(dittoPointer){ensureInitialized();return ditto_stop_http_server(dittoPointer)}function dittoRunGarbageCollection(dittoPointer){ensureInitialized();return ditto_run_garbage_collection(dittoPointer)}async function dittoDisableSyncWithV2(dittoPointer){ensureInitialized();const errorCode=await ditto_disable_sync_with_v2(dittoPointer);if(errorCode!==0)throw new Error(errorMessage()||`ditto_disable_sync_with_v2() failed with error code: ${errorCode}`)}function documentsHash(documents){ensureInitialized();const{status_code:errorCode,u64:hash}=ditto_documents_hash(documents);if(errorCode!==0)throw new Error(errorMessage()||`\`ditto_documents_hash()\` failed with error code: ${errorCode}`);return BigInt(hash)}function documentsHashMnemonic(documents){ensureInitialized();const{status_code:errorCode,c_string:c_string}=ditto_documents_hash_mnemonic(documents);if(errorCode!==0)throw new Error(errorMessage()||`\`ditto_documents_hash_mnemonic()\` failed with error code: ${errorCode}`);return boxCStringIntoString(c_string)}function dittoAuthClientMakeLoginProvider(expiringCb,onError){ensureInitialized();return ditto_auth_client_make_login_provider(wrapBackgroundCbForFFI(onError,expiringCb))}function dittoAuthClientSetValidityListener(authClient,validityUpdateCb,onError){ensureInitialized();const validityUpdateRawCb=wrapBackgroundCbForFFI(onError,(function(isWebValidInt,isX509ValidInt){return validityUpdateCb(isWebValidInt===1,isX509ValidInt===1)}));return ditto_auth_client_set_validity_listener(authClient,validityUpdateRawCb)}let isInitialized=false;let withOutPtr;{isInitialized=true;withOutPtr=wrapFFIOutFunction(withOutPtr$1)}function initSDKVersion(platform,language,semVer){ensureInitialized();bytesFromString(platform);bytesFromString(language);const semVerCString=bytesFromString(semVer);const errorCode=ditto_init_sdk_version(platform,language,semVerCString);if(typeof errorCode!=="undefined"&&errorCode!==0)throw new Error(errorMessage()||`ditto_init_sdk_version() failed with error code: ${errorCode}`)}function verifyLicense(license){ensureInitialized();const licenseBuffer=bytesFromString(license);let result;const errorMessageCString=withOutPtr("char *",(outErrorMessage=>{result=verify_license(licenseBuffer,outErrorMessage);return outErrorMessage}));const errorMessage=boxCStringIntoString(errorMessageCString);return{result:result,errorMessage:errorMessage}}const NOT_FOUND_ERROR_CODE=-30798;function wrapBackgroundCbForFFI(onError,cb){if(onError===undefined){onError=console.error}return(ret_sender,...args)=>{let ret;try{ret=cb(...args)}catch(err){try{onError(err)}catch(nested_error){console.error(`Internal error: \`onError()\` handler oughtn't throw, but it did throw ${nested_error}`)}}return ret_sender(ret)}}function wrapFFIOutFunction(ffiOutFunction){return function(...args){let occurredError=undefined;let callbackResult=undefined;let isCallbackResultOutParameter=false;const callback=args[args.length-1];const previous_args=args.splice(0,args.length-1);const dittoCoreResult=ffiOutFunction(...previous_args,(outParameter=>{try{callbackResult=callback(outParameter);isCallbackResultOutParameter=callbackResult===outParameter}catch(error){occurredError=error}}));if(occurredError){throw occurredError}return isCallbackResultOutParameter?dittoCoreResult:callbackResult}}function bytesFromString(jsString){if(typeof jsString==="undefined")return undefined;if(jsString===null)return null;if(typeof jsString!=="string")throw new Error(`Can't convert string to Uint8Array, not a string: ${jsString}`);const textEncoder=new TextEncoder;return textEncoder.encode(`${jsString}\0`)}function errorMessage(){ensureInitialized();const errorMessageCString=ditto_error_message();return boxCStringIntoString(errorMessageCString)}function ensureInitialized(){if(!isInitialized){throw new Error("Ditto needs to be initialized before using any of its API, please make sure to call `await init()` first.")}}const transports=function(){{if(typeof process!=="undefined"&&typeof require!=="undefined"){const target=process.platform+"-"+process.arch;try{if(target==="darwin-x64")return require(`./transports.darwin-x64.node`);if(target==="darwin-arm64")return require(`./transports.darwin-arm64.node`)}catch(error){return null}}}return null}();function bleIsAvailable(ditto){{if(process.platform==="linux"||process.platform==="win32"){return true}}if(transports!==null){return transports.bleIsAvailable(ditto)}else{return false}}function bleCreate(ditto){if(transports!==null){return transports.bleCreate(ditto)}else{throw new Error("Can't create BluetoothLE handle, P2P BluetoothLE is not supported on this platform.")}}function bleDestroy(ble){if(transports!==null){return transports.bleDestroy(ble)}else{throw new Error("Can't destroy BluetoothLE handle, P2P BluetoothLE is not supported on this platform.")}}function lanIsAvailable(ditto){{if(process.platform==="win32"){return true}}if(transports!==null){return transports.lanIsAvailable(ditto)}else{return false}}function lanCreate(ditto){if(transports!==null){return transports.lanCreate(ditto)}else{throw new Error("Can't create LAN handle, P2P LAN transport is not supported on this platform.")}}function lanDestroy(lan){if(transports!==null){return transports.lanDestroy(lan)}else{throw new Error("Can't destroy LAN handle, P2P LAN transport is not supported on this platform.")}}function awdlIsAvailable(ditto){if(transports!==null){return transports.awdlIsAvailable(ditto)}else{return false}}function awdlCreate(ditto){if(transports!==null){return transports.awdlCreate(ditto)}else{throw new Error("Can't create AWDL handle, P2P AWDL transport is not supported on this platform.")}}function awdlDestroy(awdl){if(transports!==null){return transports.awdlDestroy(awdl)}else{throw new Error("Can't destroy AWDL handle, P2P AWDL transport is not supported on this platform.")}}const fullBuildVersionString="3.0.6-experimental.node-loading-issues.linux-x64.1";async function init(options={}){}{switch(process.platform){case"android":initSDKVersion("Android","JavaScript",fullBuildVersionString);break;case"darwin":initSDKVersion("Mac","JavaScript",fullBuildVersionString);break;case"linux":initSDKVersion("Linux","JavaScript",fullBuildVersionString);break;case"win32":initSDKVersion("Windows","JavaScript",fullBuildVersionString);break;default:initSDKVersion("Unknown","JavaScript",fullBuildVersionString);break}loggerInit()}class KeepAlive{get isActive(){return this.intervalID!==null}constructor(){this.countsByID={};this.intervalID=null}retain(id){if(typeof this.countsByID[id]==="undefined"){this.countsByID[id]=0}this.countsByID[id]+=1;if(this.intervalID===null){const maxDelay=2147483647;this.intervalID=setInterval((()=>{}),maxDelay);KeepAlive.finalizationRegistry.register(this,this.intervalID,this)}}release(id){if(typeof this.countsByID[id]==="undefined"){throw new Error(`Internal inconsistency, trying to release a keep-alive ID that hasn't been retained before or isn't tracked anymore: ${id}`)}this.countsByID[id]-=1;if(this.countsByID[id]===0){delete this.countsByID[id]}if(Object.keys(this.countsByID).length===0){KeepAlive.finalizationRegistry.unregister(this);clearInterval(this.intervalID);this.intervalID=null}}currentIDs(){return Object.keys(this.countsByID)}countForID(id){var _a;return(_a=this.countsByID[id])!==null&&_a!==void 0?_a:null}}KeepAlive.finalizationRegistry=new FinalizationRegistry(clearInterval);class Logger{static setLogFile(path){if(path){loggerSetLogFile(path);this["logFile"]=path}else{loggerSetLogFile(null);delete this["logFile"]}}static setLogFileURL(url){this.setLogFile(url===null||url===void 0?void 0:url.pathname)}static get enabled(){return loggerEnabledGet()}static set enabled(enabled){loggerEnabled(enabled)}static get emojiLogLevelHeadingsEnabled(){return loggerEmojiHeadingsEnabledGet()}static set emojiLogLevelHeadingsEnabled(emojiLogLevelHeadingsEnabled){loggerEmojiHeadingsEnabled(emojiLogLevelHeadingsEnabled)}static get minimumLogLevel(){return loggerMinimumLogLevelGet()}static set minimumLogLevel(minimumLogLevel){loggerMinimumLogLevel(minimumLogLevel)}static async setCustomLogCallback(callback){if(callback){await loggerSetCustomLogCb(callback);this["customLogCallback"]=callback}else{await loggerSetCustomLogCb(null);delete this["customLogCallback"]}}static log(level,message){log(level,message)}static error(message){this.log("Error",message)}static warning(message){this.log("Warning",message)}static info(message){this.log("Info",message)}static debug(message){this.log("Debug",message)}static verbose(message){this.log("Verbose",message)}constructor(){throw new Error("Logger can't be instantiated, use it's static properties & methods directly instead.")}}class ObserverManager{constructor(id,options={}){var _a,_b,_c,_d;const keepAlive=(_a=options.keepAlive)!==null&&_a!==void 0?_a:null;const register=(_b=options.register)!==null&&_b!==void 0?_b:null;const unregister=(_c=options.unregister)!==null&&_c!==void 0?_c:null;const process=(_d=options.process)!==null&&_d!==void 0?_d:null;this.id=id;this.keepAlive=keepAlive;this.isRegistered=false;this.callbacksByToken={};if(register!==null){this.register=register}if(unregister!==null){this.unregister=unregister}if(process!==null){this.process=process}}addObserver(callback){var _a;this.registerIfNeeded();const token=generateEphemeralToken();this.callbacksByToken[token]=callback;(_a=this.keepAlive)===null||_a===void 0?void 0:_a.retain(`${this.id}.${token}`);return token}removeObserver(token){var _a;delete this.callbacksByToken[token];(_a=this.keepAlive)===null||_a===void 0?void 0:_a.release(`${this.id}.${token}`);this.unregisterIfNeeded()}notify(...args){const processedArgs=this.process(...args);for(const token in this.callbacksByToken){const callback=this.callbacksByToken[token];callback(...processedArgs)}}register(callback){}unregister(){}process(...args){return args}hasObservers(){return Object.keys(this.callbacksByToken).length>0}registerIfNeeded(){const needsToRegister=!this.isRegistered;if(needsToRegister){const weakThis=new WeakRef(this);this.isRegistered=true;this.register((function(...args){const strongThis=weakThis.deref();if(!strongThis){return}strongThis.notify(...args)}))}}unregisterIfNeeded(){const needsToUnregister=!this.hasObservers()&&this.isRegistered;if(needsToUnregister){this.isRegistered=false;this.unregister()}}async finalize(token){await this.removeObserver(token)}}class Observer{constructor(observerManager,token,options={}){this.observerManager=observerManager;this.token=token;this.options=options;if(options.stopsWhenFinalized){Observer.finalizationRegistry.register(this,{observerManager:observerManager,token:token},this)}}get isStopped(){return typeof this.token==="undefined"}stop(){const token=this.token;if(token){delete this["token"];Observer.finalizationRegistry.unregister(this);this.observerManager.removeObserver(token)}}static finalize(observerManagerAndToken){const{observerManager:observerManager,token:token}=observerManagerAndToken;observerManager.removeObserver(token)}}Observer.finalizationRegistry=new FinalizationRegistry(Observer.finalize);class Authenticator{loginWithToken(token,provider){throw new Error(`Authenticator.loginWithToken() is abstract and must be implemented by subclasses.`)}loginWithUsernameAndPassword(username,password,provider){throw new Error(`Authenticator.loginWithUsernameAndPassword() is abstract and must be implemented by subclasses.`)}logout(cleanupFn){throw new Error(`Authenticator.logout() is abstract and must be implemented by subclasses.`)}observeStatus(callback){const token=this.observerManager.addObserver(callback);return new Observer(this.observerManager,token,{stopsWhenFinalized:true})}constructor(keepAlive){this.keepAlive=keepAlive;this.status={isAuthenticated:false,userID:null};this.loginSupported=false;this.observerManager=new ObserverManager("AuthenticationStatusObservation",{keepAlive:keepAlive})}"@ditto.authenticationExpiring"(number){throw new Error(`Authenticator['@ditto.authenticationExpiring']() is abstract and must be implemented by subclasses.`)}"@ditto.authClientValidityChanged"(isWebValid,isX509Valid){throw new Error(`Authenticator['@ditto.authClientValidityChanged']() is abstract and must be implemented by subclasses.`)}}class OnlineAuthenticator extends Authenticator{async loginWithToken(token,provider){await dittoAuthClientLoginWithToken(this.authClientPointer,token,provider)}async loginWithUsernameAndPassword(username,password,provider){await dittoAuthClientLoginWithUsernameAndPassword(this.authClientPointer,username,password,provider)}async logout(cleanupFn){const ditto=this.ditto.deref();if(ditto){await dittoAuthClientLogout(this.authClientPointer);ditto.stopSync();cleanupFn===null||cleanupFn===void 0?void 0:cleanupFn(this.ditto)}else{Logger.warning("Unable to logout, related Ditto object does not exist anymore.")}}constructor(keepAlive,authClientPointer,ditto,authenticationHandler){super(keepAlive);this["loginSupported"]=true;this["status"]={isAuthenticated:false,userID:null};this.authClientPointer=authClientPointer;this.ditto=new WeakRef(ditto);this.authenticationHandler=authenticationHandler;this.updateAndNotify(false);OnlineAuthenticator.finalizationRegistry.register(this,authClientPointer)}"@ditto.authenticationExpiring"(secondsRemaining){const authenticationHandler=this.authenticationHandler;if(secondsRemaining>0){authenticationHandler.authenticationExpiringSoon(this,secondsRemaining)}else{authenticationHandler.authenticationRequired(this)}}"@ditto.authClientValidityChanged"(isWebValid,isX509Valid){this.updateAndNotify(true)}updateAndNotify(shouldNotify){var _a;const wasAuthenticated=this.status.isAuthenticated;const previousUserID=this.status.userID;const isAuthenticated=dittoAuthClientIsWebValid(this.authClientPointer);const userID=dittoAuthClientUserID(this.authClientPointer);const status={isAuthenticated:isAuthenticated,userID:userID};this["status"]=status;if(shouldNotify){const sameStatus=!!wasAuthenticated===!!isAuthenticated&&previousUserID===userID;if(!sameStatus){(_a=this.authenticationHandler.authenticationStatusDidChange)===null||_a===void 0?void 0:_a.call(this.authenticationHandler,this);this.observerManager.notify(status)}}}static finalize(authClientPointer){dittoAuthClientFree(authClientPointer)}}OnlineAuthenticator.finalizationRegistry=new FinalizationRegistry(OnlineAuthenticator.finalize);class NotAvailableAuthenticator extends Authenticator{async loginWithToken(token,provider){throw new Error(`Can't login, authentication is not supported for the identity in use, please use an onlineWithAuthentication identity.`)}async loginWithUsernameAndPassword(username,password,provider){throw new Error(`Can't login, authentication is not supported for the identity in use, please use an onlineWithAuthentication identity.`)}logout(cleanupFn){throw new Error(`Can't logout, authentication is not supported for the identity in use, please use an onlineWithAuthentication identity.`)}"@ditto.authenticationExpiring"(secondsRemaining){throw new Error(`Internal inconsistency, authentication is not available, yet the @ditto.authenticationExpiring() was called on authenticator: ${this}`)}"@ditto.authClientValidityChanged"(isWebValid,isX509Valid){throw new Error(`Internal inconsistency, authentication is not available, yet the @ditto.authClientValidityChanged() was called on authenticator: ${this}`)}}const IdentityTypesRequiringOfflineLicenseToken=["manual","sharedKey","offlinePlayground"];const NO_PREFERRED_ROUTE_HINT=0;class TransportConfig{constructor(){this.peerToPeer={bluetoothLE:{isEnabled:false},awdl:{isEnabled:false},lan:{isEnabled:false,isMdnsEnabled:true,isMulticastEnabled:true}};this.connect={tcpServers:[],websocketURLs:[]};this.listen={tcp:{isEnabled:false,interfaceIP:"0.0.0.0",port:4040},http:{isEnabled:false,interfaceIP:"0.0.0.0",port:80,websocketSync:true}};this.global={syncGroup:0,routingHint:NO_PREFERRED_ROUTE_HINT}}setAllPeerToPeerEnabled(enabled){this.peerToPeer.bluetoothLE.isEnabled=enabled;this.peerToPeer.lan.isEnabled=enabled;this.peerToPeer.awdl.isEnabled=enabled}freeze(){if(this.isFrozen)return this;this["isFrozen"]=true;Object.freeze(this.peerToPeer.bluetoothLE);Object.freeze(this.peerToPeer.awdl);Object.freeze(this.peerToPeer.lan);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);return this}copy(){const copy=new TransportConfig;copy.peerToPeer.bluetoothLE.isEnabled=this.peerToPeer.bluetoothLE.isEnabled;copy.peerToPeer.awdl.isEnabled=this.peerToPeer.awdl.isEnabled;copy.peerToPeer.lan.isEnabled=this.peerToPeer.lan.isEnabled;copy.peerToPeer.lan.isMdnsEnabled=this.peerToPeer.lan.isMdnsEnabled;copy.peerToPeer.lan.isMulticastEnabled=this.peerToPeer.lan.isMulticastEnabled;copy.connect.tcpServers=this.connect.tcpServers.slice();copy.connect.websocketURLs=this.connect.websocketURLs.slice();copy.listen["tcp"]={...this.listen.tcp};copy.listen["http"]={...this.listen.http};copy.global.syncGroup=this.global.syncGroup;copy.global.routingHint=this.global.routingHint;return copy}static areListenTCPsEqual(left,right){return left.isEnabled===right.isEnabled&&left.interfaceIP===right.interfaceIP&&left.port===right.port}static areListenHTTPsEqual(left,right){return left.isEnabled===right.isEnabled&&left.interfaceIP===right.interfaceIP&&left.port===right.port&&left.staticContentPath===right.staticContentPath&&left.websocketSync===right.websocketSync&&left.tlsKeyPath===right.tlsKeyPath&&left.tlsCertificatePath===right.tlsCertificatePath}}const POW_2_24=5.960464477539063e-8;const POW_2_32=4294967296;const POW_2_53=9007199254740992;const DECODE_CHUNK_SIZE=8192;function objectIs(x,y){if(typeof Object.is==="function")return Object.is(x,y);if(x===y){return x!==0||1/x===1/y}return x!==x&&y!==y}class TaggedValue{constructor(value,tag){this.value=value;this.tag=tag}}function decode(data,tagger,simpleValue){let dataView=new DataView(data);let ta=new Uint8Array(data);let offset=0;let tagValueFunction=function(value,tag){return new TaggedValue(value,tag)};let simpleValFunction=function(value){return undefined};if(typeof tagger==="function")tagValueFunction=tagger;if(typeof simpleValue==="function")simpleValFunction=simpleValue;function commitRead(length,value){offset+=length;return value}function readArrayBuffer(length){return commitRead(length,new Uint8Array(data,offset,length))}function readFloat16(){let tempArrayBuffer=new ArrayBuffer(4);let tempDataView=new DataView(tempArrayBuffer);let value=readUint16();let sign=value&32768;let exponent=value&31744;let fraction=value&1023;if(exponent===31744)exponent=255<<10;else if(exponent!==0)exponent+=127-15<<10;else if(fraction!==0)return(sign?-1:1)*fraction*POW_2_24;tempDataView.setUint32(0,sign<<16|exponent<<13|fraction<<13);return tempDataView.getFloat32(0)}function readFloat32(){return commitRead(4,dataView.getFloat32(offset))}function readFloat64(){return commitRead(8,dataView.getFloat64(offset))}function readUint8(){return commitRead(1,ta[offset])}function readUint16(){return commitRead(2,dataView.getUint16(offset))}function readUint32(){return commitRead(4,dataView.getUint32(offset))}function readUint64(){return readUint32()*POW_2_32+readUint32()}function readBreak(){if(ta[offset]!==255)return false;offset+=1;return true}function readLength(additionalInformation){if(additionalInformation<24)return additionalInformation;if(additionalInformation===24)return readUint8();if(additionalInformation===25)return readUint16();if(additionalInformation===26)return readUint32();if(additionalInformation===27)return readUint64();if(additionalInformation===31)return-1;throw new Error("Invalid length encoding")}function readIndefiniteStringLength(majorType){let initialByte=readUint8();if(initialByte===255)return-1;let length=readLength(initialByte&31);if(length<0||initialByte>>5!==majorType)throw new Error("Invalid indefinite length element");return length}function appendUtf16Data(utf16data,length){for(let i=0;i<length;++i){let value=readUint8();if(value&128){if(value<224){value=(value&31)<<6|readUint8()&63;length-=1}else if(value<240){value=(value&15)<<12|(readUint8()&63)<<6|readUint8()&63;length-=2}else{value=(value&15)<<18|(readUint8()&63)<<12|(readUint8()&63)<<6|readUint8()&63;length-=3}}if(value<65536){utf16data.push(value)}else{value-=65536;utf16data.push(55296|value>>10);utf16data.push(56320|value&1023)}}}function decodeItem(){let initialByte=readUint8();let majorType=initialByte>>5;let additionalInformation=initialByte&31;let i;let length;if(majorType===7){switch(additionalInformation){case 25:return readFloat16();case 26:return readFloat32();case 27:return readFloat64()}}length=readLength(additionalInformation);if(length<0&&(majorType<2||6<majorType))throw new Error("Invalid length");switch(majorType){case 0:return length;case 1:return-1-length;case 2:if(length<0){let elements=[];let fullArrayLength=0;while((length=readIndefiniteStringLength(majorType))>=0){fullArrayLength+=length;elements.push(readArrayBuffer(length))}let fullArray=new Uint8Array(fullArrayLength);let fullArrayOffset=0;for(i=0;i<elements.length;++i){fullArray.set(elements[i],fullArrayOffset);fullArrayOffset+=elements[i].length}return fullArray}return readArrayBuffer(length);case 3:let utf16data=[];if(length<0){while((length=readIndefiniteStringLength(majorType))>=0)appendUtf16Data(utf16data,length)}else{appendUtf16Data(utf16data,length)}let string="";for(i=0;i<utf16data.length;i+=DECODE_CHUNK_SIZE){string+=String.fromCharCode.apply(null,utf16data.slice(i,i+DECODE_CHUNK_SIZE))}return string;case 4:let retArray;if(length<0){retArray=[];while(!readBreak())retArray.push(decodeItem())}else{retArray=new Array(length);for(i=0;i<length;++i)retArray[i]=decodeItem()}return retArray;case 5:let retObject={};for(i=0;i<length||length<0&&!readBreak();++i){let key=decodeItem();retObject[key]=decodeItem()}return retObject;case 6:return tagValueFunction(decodeItem(),length);case 7:switch(length){case 20:return false;case 21:return true;case 22:return null;case 23:return undefined;default:return simpleValFunction(length)}}}let ret=decodeItem();if(offset!==data.byteLength)throw new Error("Remaining bytes");return ret}function encode(value){let data=new ArrayBuffer(256);let dataView=new DataView(data);let byteView=new Uint8Array(data);let lastLength;let offset=0;function prepareWrite(length){let newByteLength=data.byteLength;let requiredLength=offset+length;while(newByteLength<requiredLength)newByteLength<<=1;if(newByteLength!==data.byteLength){let oldDataView=dataView;data=new ArrayBuffer(newByteLength);dataView=new DataView(data);byteView=new Uint8Array(data);let uint32count=offset+3>>2;for(let i=0;i<uint32count;++i)dataView.setUint32(i<<2,oldDataView.getUint32(i<<2))}lastLength=length;return dataView}function commitWrite(...args){offset+=lastLength}function writeFloat64(val){commitWrite(prepareWrite(8).setFloat64(offset,val))}function writeUint8(val){commitWrite(prepareWrite(1).setUint8(offset,val))}function writeUint8Array(val){prepareWrite(val.length);byteView.set(val,offset);commitWrite()}function writeUint16(val){commitWrite(prepareWrite(2).setUint16(offset,val))}function writeUint32(val){commitWrite(prepareWrite(4).setUint32(offset,val))}function writeUint64(val){let low=val%POW_2_32;let high=(val-low)/POW_2_32;let view=prepareWrite(8);view.setUint32(offset,high);view.setUint32(offset+4,low);commitWrite()}function writeVarUint(val,mod){if(val<=255){if(val<24){writeUint8(val|mod)}else{writeUint8(24|mod);writeUint8(val)}}else if(val<=65535){writeUint8(25|mod);writeUint16(val)}else if(val<=4294967295){writeUint8(26|mod);writeUint32(val)}else{writeUint8(27|mod);writeUint64(val)}}function writeTypeAndLength(type,length){if(length<24){writeUint8(type<<5|length)}else if(length<256){writeUint8(type<<5|24);writeUint8(length)}else if(length<65536){writeUint8(type<<5|25);writeUint16(length)}else if(length<4294967296){writeUint8(type<<5|26);writeUint32(length)}else{writeUint8(type<<5|27);writeUint64(length)}}function encodeItem(val){let i;if(val===false)return writeUint8(244);if(val===true)return writeUint8(245);if(val===null)return writeUint8(246);if(val===undefined)return writeUint8(247);if(objectIs(val,-0))return writeUint8Array([249,128,0]);switch(typeof val){case"number":if(Math.floor(val)===val){if(0<=val&&val<=POW_2_53)return writeTypeAndLength(0,val);if(-POW_2_53<=val&&val<0)return writeTypeAndLength(1,-(val+1))}writeUint8(251);return writeFloat64(val);case"string":let utf8data=[];for(i=0;i<val.length;++i){let charCode=val.charCodeAt(i);if(charCode<128){utf8data.push(charCode)}else if(charCode<2048){utf8data.push(192|charCode>>6);utf8data.push(128|charCode&63)}else if(charCode<55296||charCode>=57344){utf8data.push(224|charCode>>12);utf8data.push(128|charCode>>6&63);utf8data.push(128|charCode&63)}else{charCode=(charCode&1023)<<10;charCode|=val.charCodeAt(++i)&1023;charCode+=65536;utf8data.push(240|charCode>>18);utf8data.push(128|charCode>>12&63);utf8data.push(128|charCode>>6&63);utf8data.push(128|charCode&63)}}writeTypeAndLength(3,utf8data.length);return writeUint8Array(utf8data);default:let length;let converted;if(Array.isArray(val)){length=val.length;writeTypeAndLength(4,length);for(i=0;i<length;i+=1)encodeItem(val[i])}else if(val instanceof Uint8Array){writeTypeAndLength(2,val.length);writeUint8Array(val)}else if(ArrayBuffer.isView(val)){converted=new Uint8Array(val.buffer);writeTypeAndLength(2,converted.length);writeUint8Array(converted)}else if(val instanceof ArrayBuffer||typeof SharedArrayBuffer==="function"&&val instanceof SharedArrayBuffer){converted=new Uint8Array(val);writeTypeAndLength(2,converted.length);writeUint8Array(converted)}else if(val instanceof TaggedValue){writeVarUint(val.tag,192);encodeItem(val.value)}else{let keys=Object.keys(val);length=keys.length;writeTypeAndLength(5,length);for(i=0;i<length;i+=1){let key=keys[i];encodeItem(key);encodeItem(val[key])}}}}encodeItem(value);if("slice"in data)return data.slice(0,offset);let ret=new ArrayBuffer(offset);let retView=new DataView(ret);for(let i=0;i<offset;++i)retView.setUint8(i,dataView.getUint8(i));return ret}const CBOR$1={decode:decode,encode:encode};class CBOR{static encode(data){const arrayBuffer=CBOR$1.encode(data);return new Uint8Array(arrayBuffer)}static decode(data){const arrayBuffer=data.buffer;return CBOR$1.decode(arrayBuffer)}}class DocumentID{get value(){let value=this["@ditto.value"];if(typeof value==="undefined"){value=CBOR.decode(this["@ditto.cbor"]);this["@ditto.value"]=value}return value}constructor(value,skipCBOREncoding=false,skipValidation=false){const cbor=skipCBOREncoding?value:CBOR.encode(value);const validatedCBOR=skipValidation?cbor:validateDocumentIDCBOR(cbor);if(!validatedCBOR){throw new Error(`Can't create DocumentID, passed in value is not valid: ${value}`)}this.isValidated=!skipValidation;this["@ditto.cbor"]=validatedCBOR}equals(documentID){const left=this["@ditto.cbor"];const right=documentID["@ditto.cbor"];if(left===right){return true}if(!(left instanceof Uint8Array)){return false}if(!(right instanceof Uint8Array)){return false}if(left.length!==right.length){return false}for(let i=0;i<left.length;i+=1){if(left[i]!==right[i])return false}return true}toString(){return documentIDQueryCompatible(this["@ditto.cbor"],"WithoutQuotes")}toBase64String(){const bytes=this["@ditto.cbor"];return btoa(String.fromCharCode.apply(null,bytes))}toQueryCompatibleString(){return documentIDQueryCompatible(this["@ditto.cbor"],"WithQuotes")}toCBOR(){return this["@ditto.cbor"]}}function validateDocumentIDValue(id){if(typeof id==="undefined"){throw new Error(`Invalid document ID: ${id}`)}return id}function validateDocumentIDCBOR(idCBOR){const validatedIDCBOROrNull=validateDocumentID(idCBOR);return validatedIDCBOROrNull!==null&&validatedIDCBOROrNull!==void 0?validatedIDCBOROrNull:idCBOR}class Attachment{get metadata(){return this.token.metadata}getData(){{const dittoPointer=dittoBridge.pointerFor(this.ditto);const attachmentHandlePointer=attachmentBridge.pointerFor(this);const attachmentPath=dittoGetCompleteAttachmentPath(dittoPointer,attachmentHandlePointer);const fs=require("fs/promises");return fs.readFile(attachmentPath)}}copyToPath(path){{const dittoPointer=dittoBridge.pointerFor(this.ditto);const attachmentHandlePointer=attachmentBridge.pointerFor(this);const attachmentPath=dittoGetCompleteAttachmentPath(dittoPointer,attachmentHandlePointer);const fs=require("fs/promises");return fs.copyFile(attachmentPath,path,fs.COPYFILE_EXCL)}}constructor(ditto,token){this.ditto=ditto;this.token=token}}const attachmentBridge=new Bridge(Attachment,freeAttachmentHandle);class AttachmentToken{constructor(jsObj){const type=jsObj[DittoCRDTTypeKey];if(type!==DittoCRDTType.attachment){throw new Error("Invalid attachment token")}const id=jsObj["_id"];if(!(id instanceof Uint8Array)){throw new Error("Invalid attachment token id")}const len=jsObj["_len"];if(typeof len!=="number"||len<0){throw new Error("Invalid attachment token length")}const meta=jsObj["_meta"];if(typeof meta!=="object"){throw new Error("Invalid attachment token meta")}this.id=id;this.len=len;this.metadata=meta}}class AttachmentFetcher{stop(){AttachmentFetcher.stopWithContextInfo({ditto:this.ditto,attachmentTokenID:this.token.id,cancelTokenPromise:this.cancelTokenPromise})}then(onfulfilled,onrejected){return this.attachment.then(onfulfilled,onrejected)}constructor(ditto,token,eventHandler){this.ditto=ditto;this.token=token;this.eventHandler=eventHandler||null;this.cancelTokenPromise=null;const eventHandlerOrNoOp=eventHandler||function(){};this.attachment=new Promise(((resolve,reject)=>{const dittoPointer=dittoBridge.pointerFor(ditto);this.cancelTokenPromise=dittoResolveAttachment(dittoPointer,token.id,{onComplete:attachmentHandlePointer=>{this["eventHandler"]=null;this["cancelTokenPromise"]=null;const attachment=new Attachment(this.ditto,this.token);attachmentBridge.bridge(attachmentHandlePointer,(()=>attachment),{throwIfAlreadyBridged:true});eventHandlerOrNoOp({type:"Completed",attachment:attachment});resolve(attachment)},onProgress:(downloaded,toDownload)=>{eventHandlerOrNoOp({type:"Progress",totalBytes:toDownload,downloadedBytes:downloaded})},onDelete:()=>{this["eventHandler"]=null;this["cancelTokenPromise"]=null;eventHandlerOrNoOp({type:"Deleted"});resolve(null)}},(err=>{this["eventHandler"]=null;this["cancelTokenPromise"]=null;reject(err)}))}));const contextInfo={ditto:ditto,attachmentTokenID:token.id,cancelTokenPromise:this.cancelTokenPromise};AttachmentFetcher.finalizationRegistry.register(this,contextInfo,contextInfo)}static stopWithContextInfo(contextInfo){step((async()=>{const cancelToken=await contextInfo.cancelTokenPromise;if(cancelToken){const dittoPointer=dittoBridge.pointerFor(contextInfo.ditto);dittoCancelResolveAttachment(dittoPointer,contextInfo.attachmentTokenID,cancelToken)}}))}}AttachmentFetcher.finalizationRegistry=new FinalizationRegistry(AttachmentFetcher.stopWithContextInfo);class Subscription{get collectionName(){return this.collection.name}cancel(){if(!this.isCancelled){this["isCancelled"]=true;Subscription.remove(this,this.contextInfo)}}constructor(collection,query,queryArgsCBOR,orderBys,limit,offset){this.isCancelled=false;this.query=query;this.queryArgsCBOR=queryArgsCBOR;this.collection=collection;this.contextInfo={ditto:collection.store.ditto,collectionName:collection.name,query:query,queryArgsCBOR:queryArgsCBOR,orderBys:orderBys,limit:limit,offset:offset};Subscription.add(this,this.contextInfo)}static add(subscription,contextInfo){const dittoX=dittoBridge.pointerFor(contextInfo.ditto);addSubscription(dittoX,contextInfo.collectionName,contextInfo.query,contextInfo.queryArgsCBOR,contextInfo.orderBys,contextInfo.limit,contextInfo.offset);this.finalizationRegistry.register(subscription,contextInfo,contextInfo)}static remove(subscription,contextInfo){const dittoX=dittoBridge.pointerFor(contextInfo.ditto);removeSubscription(dittoX,contextInfo.collectionName,contextInfo.query,contextInfo.queryArgsCBOR,contextInfo.orderBys,contextInfo.limit,contextInfo.offset);if(subscription)this.finalizationRegistry.unregister(contextInfo)}}Subscription.finalizationRegistry=new FinalizationRegistry((contextInfo=>{Subscription.remove(null,contextInfo)}));const privateToken$1="@ditto.64d129224a5377b63e9727479ec987d9";class Counter{constructor(){this.value=0}static"@ditto.create"(mutDoc,path,value){const counter=mutDoc?new MutableCounter(privateToken$1):new Counter;counter.mutDoc=mutDoc;counter.path=path;counter["value"]=value;return counter}}class MutableCounter extends Counter{increment(amount){const mutDoc=this["mutDoc"];const path=this["path"];if(!mutDoc){throw new Error(`Can't increment counter, only possible within the closure of a collection's update() method.`)}mutDoc.at(path)["@ditto.increment"](amount);this["value"]+=amount}constructor(){if(arguments[0]===privateToken$1){super()}else{throw new Error(`MutableCounter constructor is for internal use only.`)}}}const privateToken="@ditto.ff82dae89821c5ab822a8b539056bce4";class Register{get value(){return this["@ditto.value"]}constructor(value){this["@ditto.value"]=value}static"@ditto.create"(mutableDocument,path,value){const register=mutableDocument?new MutableRegister(value,privateToken):new Register(value);register["@ditto.mutableDocument"]=mutableDocument;register["@ditto.path"]=path;register["@ditto.value"]=value;return register}}class MutableRegister extends Register{get value(){return super.value}set value(value){this.set(value)}set(value){const mutableDocument=this["@ditto.mutableDocument"];const path=this["@ditto.path"];mutableDocument.at(path)["@ditto.set"](value);this["@ditto.value"]=value}constructor(value){if(arguments[1]===privateToken){super(value)}else{throw new Error(`MutableRegister constructor is for internal use only.`)}}}class RGA{get value(){return this["@ditto.value"]}constructor(array=[]){this["@ditto.value"]=array}static"@ditto.create"(path,value){const rga=new RGA(value);rga["@ditto.path"]=path;rga["@ditto.value"]=value;return rga}}class UpdateResult{static set(docID,path,value){return new UpdateResult("set",docID,path,value,undefined)}static incremented(docID,path,amount){return new UpdateResult("incremented",docID,path,undefined,amount)}static removed(docID,path){return new UpdateResult("removed",docID,path,undefined,undefined)}constructor(type,docID,path,value,amount){this.type=type;this.docID=docID;this.path=path;if(value!==undefined)this.value=value;if(amount!==undefined)this.amount=amount}}function augmentJSONValue(json,mutDoc,workingPath){if(json&&typeof json==="object"){if(Array.isArray(json)){return json.map(((v,idx)=>augmentJSONValue(v,mutDoc,`${workingPath}[${idx}]`)))}else if(json[DittoCRDTTypeKey]===DittoCRDTType.counter){return Counter["@ditto.create"](mutDoc,workingPath,json[DittoCRDTValueKey])}else if(json[DittoCRDTTypeKey]===DittoCRDTType.register){return Register["@ditto.create"](mutDoc,workingPath,json[DittoCRDTValueKey])}else if(json[DittoCRDTTypeKey]===DittoCRDTType.rga){const augmentedValue=augmentJSONValue(json[DittoCRDTValueKey],mutDoc,workingPath);return RGA["@ditto.create"](workingPath,augmentedValue)}else if(json[DittoCRDTTypeKey]===DittoCRDTType.attachment){return new AttachmentToken(json)}else{for(const[key,value]of Object.entries(json)){json[key]=augmentJSONValue(value,mutDoc,`${workingPath}['${key}']`)}return json}}else{return json}}function desugarJSObject(jsObj,atRoot=false){if(jsObj&&typeof jsObj==="object"){if(Array.isArray(jsObj)){return jsObj.map(((v,idx)=>desugarJSObject(v,false)))}else if(jsObj instanceof DocumentID){return jsObj.value}else if(jsObj instanceof Counter){const counterJSON={};counterJSON[DittoCRDTTypeKey]=DittoCRDTType.counter;counterJSON[DittoCRDTValueKey]=jsObj.value;return counterJSON}else if(jsObj instanceof Register){const registerJSON={};registerJSON[DittoCRDTTypeKey]=DittoCRDTType.register;registerJSON[DittoCRDTValueKey]=jsObj.value;return registerJSON}else if(jsObj instanceof RGA){const rgaJSON={};rgaJSON[DittoCRDTTypeKey]=DittoCRDTType.rga;rgaJSON[DittoCRDTValueKey]=desugarJSObject(jsObj.value);return rgaJSON}else if(jsObj instanceof Attachment){const attachmentJSON={_id:jsObj.token.id,_len:jsObj.token.len,_meta:jsObj.token.metadata};attachmentJSON[DittoCRDTTypeKey]=DittoCRDTType.attachment;return attachmentJSON}else{for(const[key,value]of Object.entries(jsObj)){jsObj[key]=desugarJSObject(value,false)}return jsObj}}else{return jsObj}}const regularKeyPattern=/\.([A-Za-z_]\w*)/.source;const subscriptIndexPattern=/\[(\d+)\]/.source;const subscriptSingleQuoteKeyPattern=/\[\'(.+?)\'\]/.source;const subscriptDoubleQuoteKeyPattern=/\[\"(.+?)\"\]/.source;const validKeyPathPattern=`((${regularKeyPattern})|(${subscriptIndexPattern})|(${subscriptSingleQuoteKeyPattern})|(${subscriptDoubleQuoteKeyPattern}))*`;const regularKeyRegExp=new RegExp(`^${regularKeyPattern}`);const subscriptIndexRegExp=new RegExp(`^${subscriptIndexPattern}`);const subscriptSingleQuoteKeyRegExp=new RegExp(`^${subscriptSingleQuoteKeyPattern}`);const subscriptDoubleQuoteKeyRegExp=new RegExp(`^${subscriptDoubleQuoteKeyPattern}`);const validKeyPathRegExp=new RegExp(`^${validKeyPathPattern}$`);class KeyPath{static withLeadingDot(keyPath){if(typeof keyPath==="number"){return keyPath}if(typeof keyPath!=="string"){throw new Error(`Key-path must be a string or a number but is ${typeof keyPath}: ${keyPath}`)}const needsLeadingDot=typeof keyPath==="string"&&!!keyPath.match(/^[A-Za-z_]/);return needsLeadingDot?`.${keyPath}`:keyPath}static withoutLeadingDot(keyPath){if(typeof keyPath==="number"){return keyPath}if(typeof keyPath!=="string"){throw new Error(`Key-path must be a string or a number but is ${typeof keyPath}: ${keyPath}`)}const hasLeadingDot=typeof keyPath==="string"&&!!keyPath.match(/^\./);return hasLeadingDot?keyPath.slice(1):keyPath}static validate(keyPath,options={}){var _a;const isInitial=(_a=options.isInitial)!==null&&_a!==void 0?_a:false;if(typeof keyPath==="number"){return Math.floor(Math.abs(keyPath))}if(typeof keyPath!=="string"){throw new Error(`Key-path must be a string or a number but is ${typeof keyPath}: ${keyPath}`)}const keyPathWithLeadingDot=this.withLeadingDot(keyPath);if(!validKeyPathRegExp.test(keyPathWithLeadingDot)){throw new Error(`Key-path is not valid: ${keyPath}`)}return isInitial?keyPath:keyPathWithLeadingDot}static evaluate(keyPath,object,options={}){var _a;const stopAtLastContainer=(_a=options.stopAtLastContainer)!==null&&_a!==void 0?_a:false;const evaluationResult={keyPath:keyPath,object:object,options:{...options},coveredPath:null,nextPathComponent:null,remainingPath:keyPath,value:object};function advance(keyPath){if(typeof keyPath==="number"){return{nextPathComponentRaw:keyPath,nextPathComponent:keyPath,remainingPath:""}}if(typeof keyPath!=="string"){throw new Error(`Can't return value at given keyPath, expected keyPath to be a string or a number but got ${typeof keyPath}: ${keyPath}`)}const regularKeyMatch=keyPath.match(regularKeyRegExp);if(regularKeyMatch!==null){const nextPathComponentRaw=regularKeyMatch[0];const nextPathComponent=regularKeyMatch[1];const remainingPath=keyPath.slice(nextPathComponent.length+1);return{nextPathComponentRaw:nextPathComponentRaw,nextPathComponent:nextPathComponent,remainingPath:remainingPath}}const subscriptIndexMatch=keyPath.match(subscriptIndexRegExp);if(subscriptIndexMatch!==null){const nextPathComponentRaw=subscriptIndexMatch[0];const nextPathComponentString=subscriptIndexMatch[1];const nextPathComponent=parseInt(nextPathComponentString);const remainingPath=keyPath.slice(nextPathComponentString.length+2);return{nextPathComponentRaw:nextPathComponentRaw,nextPathComponent:nextPathComponent,remainingPath:remainingPath}}const subscriptSingleQuoteMatch=keyPath.match(subscriptSingleQuoteKeyRegExp);if(subscriptSingleQuoteMatch!==null){const nextPathComponentRaw=subscriptSingleQuoteMatch[0];const nextPathComponent=subscriptSingleQuoteMatch[1];const remainingPath=keyPath.slice(nextPathComponent.length+4);return{nextPathComponentRaw:nextPathComponentRaw,nextPathComponent:nextPathComponent,remainingPath:remainingPath}}const subscriptDoubleQuoteMatch=keyPath.match(subscriptDoubleQuoteKeyRegExp);if(subscriptDoubleQuoteMatch!==null){const nextPathComponentRaw=subscriptDoubleQuoteMatch[0];const nextPathComponent=subscriptDoubleQuoteMatch[1];const remainingPath=keyPath.slice(nextPathComponent.length+4);return{nextPathComponentRaw:nextPathComponentRaw,nextPathComponent:nextPathComponent,remainingPath:remainingPath}}throw new Error(`Can't return value at keyPath because the following part of the keyPath is invalid: ${keyPath}`)}function recurse(object,keyPath){if(keyPath===""){evaluationResult.value=object;return evaluationResult}const{nextPathComponentRaw:nextPathComponentRaw,nextPathComponent:nextPathComponent,remainingPath:remainingPath}=advance(keyPath);evaluationResult.nextPathComponent=nextPathComponent;evaluationResult.remainingPath=remainingPath;if(evaluationResult.coveredPath===null||typeof nextPathComponentRaw==="number"){evaluationResult.coveredPath=nextPathComponentRaw}else{evaluationResult.coveredPath+=nextPathComponentRaw}if(remainingPath===""&&stopAtLastContainer){evaluationResult.value=object;return evaluationResult}const nextObject=object[nextPathComponent];return recurse(nextObject,remainingPath)}const keyPathWithLeadingDot=this.withLeadingDot(keyPath);return recurse(object,keyPathWithLeadingDot)}constructor(){}}class DocumentPath{at(keyPathOrIndex){if(typeof keyPathOrIndex==="string"){const keyPath=keyPathOrIndex;const validatedKeyPath=KeyPath.validate(keyPath);const absoluteKeyPath=KeyPath.withoutLeadingDot(`${this.path}${validatedKeyPath}`);return new DocumentPath(this.document,absoluteKeyPath,false)}if(typeof keyPathOrIndex==="number"){const index=keyPathOrIndex;const validatedIndex=validateNumber(index,{integer:true,min:0,errorMessagePrefix:"DocumentPath.at() validation failed index:"});return new DocumentPath(this.document,`${this.path}[${validatedIndex.toString()}]`,false)}throw new Error(`Can't return document path at key-path or index, string or number expected but got ${typeof keyPathOrIndex}: ${keyPathOrIndex}`)}get value(){return this.underlyingValueForPathType("Any")}get counter(){const underlyingValue=this.underlyingValueForPathType("Counter");return typeof underlyingValue!=="undefined"?Counter["@ditto.create"](null,this.path,underlyingValue):null}get register(){const underlyingValue=this.underlyingValueForPathType("Register");return typeof underlyingValue!=="undefined"?Register["@ditto.create"](null,this.path,underlyingValue):null}get rga(){const underlyingValue=this.underlyingValueForPathType("Rga");return typeof underlyingValue!=="undefined"?RGA["@ditto.create"](this.path,underlyingValue):null}get attachmentToken(){const underlyingValue=this.underlyingValueForPathType("Attachment");return typeof underlyingValue!=="undefined"?new AttachmentToken(underlyingValue):null}constructor(document,path,validate){this.document=document;this.path=validate?KeyPath.validate(path,{isInitial:true}):path}underlyingValueForPathType(pathType){const path=this.path;const document=this.document;const documentX=documentBridge.pointerFor(document);const cborPathResult=documentGetCBORWithPathType(documentX,path,pathType);return cborPathResult.cbor!==null?CBOR.decode(cborPathResult.cbor):undefined}}class MutableDocumentPath{at(keyPathOrIndex){if(typeof keyPathOrIndex==="string"){const keyPath=keyPathOrIndex;const validatedKeyPath=KeyPath.validate(keyPath);const absoluteKeyPath=KeyPath.withoutLeadingDot(`${this.path}${validatedKeyPath}`);return new MutableDocumentPath(this.mutableDocument,absoluteKeyPath,false)}if(typeof keyPathOrIndex==="number"){const index=keyPathOrIndex;const validatedIndex=validateNumber(index,{integer:true,min:0,errorMessagePrefix:"MutableDocumentPath.at() validation failed index:"});return new MutableDocumentPath(this.mutableDocument,`${this.path}[${validatedIndex.toString()}]`,false)}throw new Error(`Can't return mutable document path at key-path or index, string or number expected but got ${typeof keyPathOrIndex}: ${keyPathOrIndex}`)}get value(){return this.underlyingValueForPathType("Any")}get counter(){const underlyingValue=this.underlyingValueForPathType("Counter");return typeof underlyingValue!=="undefined"?Counter["@ditto.create"](this.mutableDocument,this.path,underlyingValue):null}get register(){const underlyingValue=this.underlyingValueForPathType("Register");return typeof underlyingValue!=="undefined"?Register["@ditto.create"](this.mutableDocument,this.path,underlyingValue):null}get rga(){const underlyingValue=this.underlyingValueForPathType("Rga");return typeof underlyingValue!=="undefined"?RGA["@ditto.create"](this.path,underlyingValue):null}get attachmentToken(){const underlyingValue=this.underlyingValueForPathType("Attachment");return typeof underlyingValue!=="undefined"?new AttachmentToken(underlyingValue):null}set(value,isDefault){return this["@ditto.set"](value,isDefault)}remove(){return this["@ditto.remove"]()}constructor(mutableDocument,path,validate){this.mutableDocument=mutableDocument;this.path=validate?KeyPath.validate(path,{isInitial:true}):path}underlyingValueForPathType(pathType){const path=this.path;const document=this.mutableDocument;const documentX=mutableDocumentBridge.pointerFor(document);const cborPathResult=documentGetCBORWithPathType(documentX,path,pathType);return cborPathResult.cbor!==null?CBOR.decode(cborPathResult.cbor):undefined}"@ditto.increment"(amount){const documentPointer=mutableDocumentBridge.pointerFor(this.mutableDocument);documentIncrementCounter(documentPointer,this.path,amount);const updateResult=UpdateResult.incremented(this.mutableDocument.id,this.path,amount);this.recordUpdateResult(updateResult)}"@ditto.set"(value,isDefault){const documentX=mutableDocumentBridge.pointerFor(this.mutableDocument);const valueJSON=desugarJSObject(value,false);const valueCBOR=CBOR.encode(valueJSON);if(isDefault){documentSetCBORWithTimestamp(documentX,this.path,valueCBOR,true,0)}else{documentSetCBOR(documentX,this.path,valueCBOR,true)}const valueJSONCopy=CBOR.decode(valueCBOR);const valueCopy=augmentJSONValue(valueJSONCopy,this.mutableDocument,this.path);const updateResult=UpdateResult.set(this.mutableDocument.id,this.path,valueCopy);this.recordUpdateResult(updateResult)}"@ditto.remove"(){const documentPointer=mutableDocumentBridge.pointerFor(this.mutableDocument);documentRemove(documentPointer,this.path);this.updateInMemory(((container,lastPathComponent)=>{if(Array.isArray(container)&&typeof lastPathComponent==="number"){container.splice(lastPathComponent,1)}else{delete container[lastPathComponent]}}));const updateResult=UpdateResult.removed(this.mutableDocument.id,this.path);this.recordUpdateResult(updateResult)}updateInMemory(block){const mutableDocumentValue=this.mutableDocument.value;const evaluationResult=KeyPath.evaluate(this.path,mutableDocumentValue,{stopAtLastContainer:true});block(evaluationResult.value,evaluationResult.nextPathComponent)}recordUpdateResult(updateResult){const updateResults=this.mutableDocument["@ditto.updateResults"].slice();updateResults.push(updateResult);Object.freeze(updateResults);this.mutableDocument["@ditto.updateResults"]=updateResults}}class Document{static hash(documentOrMany){const documents=documentsFrom(documentOrMany);const documentPointers=documents.map((doc=>documentBridge.pointerFor(doc)));return documentsHash(documentPointers)}static hashMnemonic(documentOrMany){const documents=documentsFrom(documentOrMany);const documentPointers=documents.map((doc=>documentBridge.pointerFor(doc)));return documentsHashMnemonic(documentPointers)}get id(){let id=this["@ditto.id"];if(typeof id==="undefined"){const documentX=documentBridge.pointerFor(this);const documentIDCBOR=documentID(documentX);id=new DocumentID(documentIDCBOR,true);this["@ditto.id"]=id}return id}get path(){return new DocumentPath(this,"",false)}get value(){let value=this["@ditto.value"];if(typeof value==="undefined"){value=this.path.value;this["@ditto.value"]=value}return value}at(keyPathOrIndex){return this.path.at(keyPathOrIndex)}constructor(){}static idCBOR(document){const documentX=documentBridge.pointerFor(document);return documentID(documentX)}static canonicalizedIDCBOR(idCBOR){return validateDocumentIDCBOR(idCBOR)}static isIDCBORCanonical(idCBOR){const canonicalIDCBOR=this.canonicalizedIDCBOR(idCBOR);return idCBOR===canonicalIDCBOR}}class MutableDocument{get id(){let id=this["@ditto.id"];if(typeof id==="undefined"){const documentX=mutableDocumentBridge.pointerFor(this);const documentIDCBOR=documentID(documentX);id=new DocumentID(documentIDCBOR,true);this["@ditto.id"]=id}return id}get path(){return new MutableDocumentPath(this,"",false)}get value(){return this.path.value}at(keyPathOrIndex){return this.path.at(keyPathOrIndex)}constructor(){this["@ditto.updateResults"]=[]}static idCBOR(mutableDocument){const documentX=mutableDocumentBridge.pointerFor(mutableDocument);return documentID(documentX)}}MutableDocument.canonicalizedIDCBOR=Document.canonicalizedIDCBOR;MutableDocument.isIDCBORCanonical=Document.isIDCBORCanonical;const documentBridge=new Bridge(Document,documentFree);const mutableDocumentBridge=new Bridge(MutableDocument,documentFree);function documentsFrom(documentOrMany){if(!documentOrMany){return[]}if(documentOrMany instanceof Document){return[documentOrMany]}if(documentOrMany instanceof Array){return documentOrMany}throw new Error(`Expected null, a single document, or an array of documents but got value of type ${typeof documentOrMany}: ${documentOrMany}`)}class UpdateResultsMap{get(documentIDOrValue){const documentID=documentIDOrValue instanceof DocumentID?documentIDOrValue:new DocumentID(documentIDOrValue);const documentIDString=documentID.toString();return this.updateResultsByDocumentIDString[documentIDString]}keys(){return this.documentIDs.slice()}constructor(documentIDs,updateResultsByDocumentIDString){const documentIDStrings=documentIDs.map((documentID=>documentID.toString())).sort().join(", ");const updateResultsKeys=Object.keys(updateResultsByDocumentIDString).sort().join(", ");if(documentIDStrings!==updateResultsKeys){throw new Error("Internal inconsistency, can't construct update results map, documentIDs must all be keys in update results (by document ID string)")}this.documentIDs=documentIDs.slice();this.updateResultsByDocumentIDString={...updateResultsByDocumentIDString}}}class LiveQueryEventInitial{constructor(){this.isInitial=true}hash(documents){return documentsHash(documents.map((doc=>documentBridge.pointerFor(doc))))}hashMnemonic(documents){return documentsHashMnemonic(documents.map((doc=>documentBridge.pointerFor(doc))))}}class LiveQueryEventUpdate{hash(documents){return documentsHash(documents.map((doc=>documentBridge.pointerFor(doc))))}hashMnemonic(documents){return documentsHashMnemonic(documents.map((doc=>documentBridge.pointerFor(doc))))}constructor(params){this.isInitial=false;this.oldDocuments=params.oldDocuments;this.insertions=params.insertions;this.deletions=params.deletions;this.updates=params.updates;this.moves=params.moves}}class SingleDocumentLiveQueryEvent{hash(document){return documentsHash(document===null?[]:[documentBridge.pointerFor(document)])}hashMnemonic(document){return documentsHashMnemonic(document===null?[]:[documentBridge.pointerFor(document)])}constructor(isInitial,oldDocument){this.isInitial=isInitial;this.oldDocument=oldDocument}}class LiveQuery{get collectionName(){return this.collection.name}get isStopped(){return this.liveQueryID===null}stop(){var _a;const liveQueryID=this.liveQueryID;if(liveQueryID!==null){this.collection.store.ditto.keepAlive.release(`LiveQuery.${liveQueryID}`);this.liveQueryID=null;const dittoPointer=dittoBridge.pointerFor(this.collection.store.ditto);(_a=this.subscription)===null||_a===void 0?void 0:_a.cancel();liveQueryStop(dittoPointer,liveQueryID)}}constructor(query,queryArgs,queryArgsCBOR,orderBys,limit,offset,collection,subscription,handler){this.query=query;this.queryArgs=queryArgs?Object.freeze({...queryArgs}):null;this.queryArgsCBOR=queryArgsCBOR;this.orderBys=orderBys;this.limit=limit;this.offset=offset;this.collection=collection;this.handler=handler;if(subscription){this.subscription=subscription}const collectionName=collection.name;const weakDitto=new WeakRef(collection.store.ditto);let liveQueryID=undefined;const signalNext=async()=>{const ditto=weakDitto.deref();if(ditto){const dittoPointer=dittoBridge.pointerFor(ditto);await liveQuerySignalAvailableNext(dittoPointer,liveQueryID)}};const dittoPointer=dittoBridge.pointerFor(collection.store.ditto);liveQueryID=liveQueryRegister(dittoPointer,collectionName,query,queryArgsCBOR,this.orderBys,limit,offset,(cCBParams=>{const documents=cCBParams.documents.map((ptr=>documentBridge.bridge(ptr)));let event;if(cCBParams.is_initial){event=new LiveQueryEventInitial}else{event=new LiveQueryEventUpdate({oldDocuments:cCBParams.old_documents.map((ptr=>documentBridge.bridge(ptr))),insertions:cCBParams.insertions,deletions:cCBParams.deletions,updates:cCBParams.updates,moves:cCBParams.moves.map((move=>({from:move[0],to:move[1]})))})}handler(documents,event,signalNext)}));if(!liveQueryID){throw new Error("Internal inconsistency, couldn't create a valid live query ID.")}this.liveQueryID=liveQueryID;step((async()=>await liveQueryStart(dittoPointer,liveQueryID)));collection.store.ditto.keepAlive.retain(`LiveQuery.${liveQueryID}`)}async signalNext(){const dittoPointer=dittoBridge.pointerFor(this.collection.store.ditto);await liveQuerySignalAvailableNext(dittoPointer,this.liveQueryID)}}class PendingCursorOperation{sort(propertyPath,direction="ascending"){this.orderBys.push({query:propertyPath,direction:direction==="ascending"?"Ascending":"Descending"});return this}offset(offset){if(offset<0)throw new Error(`Can't offset by '${offset}', offset must be >= 0`);if(!Number.isFinite(offset))throw new Error(`Can't offset by '${offset}', offset must be a finite number`);if(Number.isNaN(offset))throw new Error(`Can't offset by '${offset}', offset must be a valid number`);const integerOffset=Math.round(offset);if(offset!==integerOffset)throw new Error(`Can't offset by '${offset}', offset must be an integer number`);this.currentOffset=offset;return this}limit(limit){if(limit<-1)throw new Error(`Can't limit to '${limit}', limit must be >= -1 (where -1 means unlimited)`);if(!Number.isFinite(limit))throw new Error(`Can't limit to '${limit}', limit must be a finite number`);if(Number.isNaN(limit))throw new Error(`Can't limit to '${limit}', limit must be a valid number`);const integerLimit=Math.round(limit);if(limit!==integerLimit)throw new Error(`Can't limit to '${limit}', limit must be an integer number`);this.currentLimit=limit;return this}subscribe(){return new Subscription(this.collection,this.query,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset)}observeLocal(handler){return this._observe(handler,false,false)}observeLocalWithNextSignal(handler){return this._observe(handler,false,true)}async remove(){const query=this.query;const dittoX=dittoBridge.pointerFor(this.collection.store.ditto);const documentsX=await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const writeTransactionX=await writeTransaction(dittoX);const documentsX=await collectionRemoveQueryStr(dittoX,this.collection.name,writeTransactionX,query,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);await writeTransactionCommit(dittoX,writeTransactionX);return documentsX}));return documentsX.map((idCBOR=>new DocumentID(idCBOR,true)))}async evict(){const query=this.query;const dittoX=dittoBridge.pointerFor(this.collection.store.ditto);const documentsX=await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const writeTransactionX=await writeTransaction(dittoX);const documentsX=await collectionEvictQueryStr(dittoX,this.collection.name,writeTransactionX,query,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);await writeTransactionCommit(dittoX,writeTransactionX);return documentsX}));return documentsX.map((idCBOR=>new DocumentID(idCBOR,true)))}async exec(){const query=this.query;const dittoX=dittoBridge.pointerFor(this.collection.store.ditto);const documentsX=await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>await collectionExecQueryStr(dittoX,this.collection.name,null,query,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset)));return documentsX.map((documentX=>documentBridge.bridge(documentX)))}async update(closure){return await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const query=this.query;const dittoX=dittoBridge.pointerFor(this.collection.store.ditto);const writeTransactionX=await writeTransaction(dittoX);const documentsX=await collectionExecQueryStr(dittoX,this.collection.name,writeTransactionX,query,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);const mutableDocuments=documentsX.map((documentX=>mutableDocumentBridge.bridge(documentX,(()=>new MutableDocument))));closure(mutableDocuments);const updateResultsDocumentIDs=[];const updateResultsByDocumentIDString={};for(const mutableDocument of mutableDocuments){const documentID=mutableDocument.id;const documentIDString=documentID.toString();const updateResults=mutableDocument["@ditto.updateResults"];if(updateResultsByDocumentIDString[documentIDString]){throw new Error(`Internal inconsistency, update results for document ID as string already exist: ${documentIDString}`)}updateResultsDocumentIDs.push(documentID);updateResultsByDocumentIDString[documentIDString]=updateResults;mutableDocumentBridge.pointerFor(mutableDocument);mutableDocumentBridge.unregister(mutableDocument)}await collectionUpdateMultiple(dittoX,this.collection.name,writeTransactionX,documentsX);await writeTransactionCommit(dittoX,writeTransactionX);return new UpdateResultsMap(updateResultsDocumentIDs,updateResultsByDocumentIDString)}))}constructor(query,queryArgs,collection){this.currentLimit=-1;this.currentOffset=0;this.orderBys=[];this.query=validateQuery(query);this.queryArgs=queryArgs?Object.freeze({...queryArgs}):null;this.collection=collection;this.queryArgsCBOR=queryArgs?CBOR.encode(queryArgs):null}_observe(handler,createSubscription,waitForNextSignal){const subscription=createSubscription?this.subscribe():null;function wrappedHandler(documents,event,nextSignal){try{return handler.call(this,documents,event)}finally{nextSignal()}}const handlerOrWrapped=waitForNextSignal?handler:wrappedHandler;return new LiveQuery(this.query,this.queryArgs,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset,this.collection,subscription,handlerOrWrapped)}then(onfulfilled,onrejected){return this.exec().then(onfulfilled,onrejected)}}class PendingIDSpecificOperation{subscribe(){return new Subscription(this.collection,this.query,null,[],-1,0)}observeLocal(handler){return this._observe(handler,false,false)}observeLocalWithNextSignal(handler){return this._observe(handler,false,true)}async remove(){const dittoX=dittoBridge.pointerFor(this.collection.store.ditto);return await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const writeTransactionX=await writeTransaction(dittoX);const didRemove=await collectionRemove(dittoX,this.collection.name,writeTransactionX,this.documentIDCBOR);await writeTransactionCommit(dittoX,writeTransactionX);return didRemove}))}async evict(){const dittoX=dittoBridge.pointerFor(this.collection.store.ditto);return await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const writeTransactionX=await writeTransaction(dittoX);const didEvict=await collectionEvict(dittoX,this.collection.name,writeTransactionX,this.documentIDCBOR);await writeTransactionCommit(dittoX,writeTransactionX);return didEvict}))}async exec(){const dittoX=dittoBridge.pointerFor(this.collection.store.ditto);return await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const readTransactionX=await readTransaction(dittoX);const documentX=await collectionGet(dittoX,this.collection.name,this.documentIDCBOR,readTransactionX);let document=undefined;if(documentX)document=documentBridge.bridge(documentX);readTransactionFree(readTransactionX);return document}))}async update(closure){const dittoX=dittoBridge.pointerFor(this.collection.store.ditto);const readTransactionX=await readTransaction(dittoX);const documentX=await collectionGet(dittoX,this.collection.name,this.documentIDCBOR,readTransactionX);readTransactionFree(readTransactionX);if(!documentX)throw new Error(`Can't update, document with ID '${this.documentID.toString()}' not found in collection named '${this.collection.name}'`);const mutableDocument=mutableDocumentBridge.bridge(documentX,(()=>new MutableDocument));closure(mutableDocument);mutableDocumentBridge.unregister(mutableDocument);const writeTransactionX=await writeTransaction(dittoX);await collectionUpdate(dittoX,this.collection.name,writeTransactionX,documentX);await writeTransactionCommit(dittoX,writeTransactionX);return mutableDocument["@ditto.updateResults"].slice()}constructor(documentID,collection){this.documentID=documentID;this.collection=collection;this.documentIDCBOR=documentID.toCBOR()}_observe(handler,createSubscription,waitForNextSignal){const subscription=createSubscription?this.subscribe():null;return new LiveQuery(this.query,null,null,[],-1,0,this.collection,subscription,((documents,event,signalNext)=>{if(documents.length>1){const documentIDsAsBase64Strings=documents.map((document=>document.id.toBase64String()));throw new Error(`Internal inconsistency, single document live query returned more than one document. Query: ${this.query}, documentIDs: ${documentIDsAsBase64Strings.join(", ")}.`)}if(event.isInitial===false&&event.oldDocuments.length>1)throw new Error(`Internal inconsistency, single document live query returned an update event with more than one old documents. Query ${this.query}.`);if(event.isInitial===false&&event.insertions.length>1)throw new Error(`Internal inconsistency, single document live query returned an update event with more than one insertion, which doesn't make sense for single document observations. Query ${this.query}.`);if(event.isInitial===false&&event.deletions.length>1)throw new Error(`Internal inconsistency, single document live query returned an update event with more than one deletion, which doesn't make sense for single document observations. Query ${this.query}.`);if(event.isInitial===false&&event.updates.length>1)throw new Error(`Internal inconsistency, single document live query returned an update event with more than one update, which doesn't make sense for single document observations. Query ${this.query}.`);if(event.isInitial===false&&event.moves.length>0)throw new Error(`Internal inconsistency, single document live query returned an update event with moves, which doesn't make sense for single document observations. Query ${this.query}.`);const totalNumberOfManipulations=event.isInitial===true?0:event.insertions.length+event.deletions.length+event.updates.length;if(totalNumberOfManipulations>1)throw new Error(`Internal inconsistency, single document live query returned a combination of inserts, updates, and/or deletes, which doesn't make sense for single document observation. Query ${this.query}.`);const document=documents[0]||null;const oldDocument=event.isInitial===true?undefined:event.oldDocuments[0];const singleDocumentEvent=new SingleDocumentLiveQueryEvent(event.isInitial,oldDocument);if(waitForNextSignal){handler(document,singleDocumentEvent,signalNext)}else{try{handler(document,singleDocumentEvent)}finally{signalNext()}}}))}then(onfulfilled,onrejected){return this.exec().then(onfulfilled,onrejected)}get query(){return`_id == ${this.documentID.toQueryCompatibleString()}`}}class Collection{find(query,queryArgs){return new PendingCursorOperation(query,queryArgs!==null&&queryArgs!==void 0?queryArgs:null,this)}findAll(){return this.find("true")}findByID(id){const documentID=id instanceof DocumentID?id:new DocumentID(id);return new PendingIDSpecificOperation(documentID,this)}async upsert(value,options={}){var _a;const writeStrategy=(_a=options.writeStrategy)!==null&&_a!==void 0?_a:"merge";const ditto=this.store.ditto;const dittoPointer=dittoBridge.pointerFor(ditto);const id=value._id;let documentID;if(typeof id==="undefined"){documentID=undefined}else if(id instanceof DocumentID){documentID=id}else{documentID=new DocumentID(id)}const documentIDCBOR=typeof documentID==="undefined"?null:documentID.toCBOR();const documentValueJSON=desugarJSObject(value,true);const documentValueCBOR=CBOR.encode(documentValueJSON);const idCBOR=await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>await collectionInsertValue(dittoPointer,this.name,documentValueCBOR,documentIDCBOR,writeStrategy)));return new DocumentID(idCBOR,true)}async newAttachment(pathOrData,metadata={}){const ditto=this.store.ditto;const dittoPointer=dittoBridge.pointerFor(ditto);const{id:id,len:len,handle:handle}=await(async()=>{if(typeof pathOrData==="string"){{return dittoNewAttachmentFromFile(dittoPointer,pathOrData,"Copy")}}if(pathOrData instanceof Uint8Array){return await dittoNewAttachmentFromBytes(dittoPointer,pathOrData)}throw new Error(`Can't create new attachment, only file path as string or raw data as Uint8Array are supported, but got: ${typeof pathOrData}, ${pathOrData}`)})();const attachmentTokenJSON={_id:id,_len:len,_meta:{...metadata}};attachmentTokenJSON[DittoCRDTTypeKey]=DittoCRDTType.attachment;const attachmentToken=new AttachmentToken(attachmentTokenJSON);const attachment=new Attachment(ditto,attachmentToken);return attachmentBridge.bridge(handle,(()=>attachment),{throwIfAlreadyBridged:true})}fetchAttachment(token,eventHandler){const ditto=this.store.ditto;return new AttachmentFetcher(ditto,token,eventHandler)}constructor(name,store){this.name=name;this.store=store}findByIDCBOR(idCBOR){const documentID=new DocumentID(idCBOR,true,true);return new PendingIDSpecificOperation(documentID,this)}}class CollectionsEvent{static initial(collections){return new CollectionsEvent({isInitial:true,collections:collections,oldCollections:[],insertions:[],deletions:[],updates:[],moves:[]})}constructor(params){this.isInitial=params.isInitial;this.collections=params.collections;this.oldCollections=params.oldCollections;this.insertions=params.insertions;this.deletions=params.deletions;this.updates=params.updates;this.moves=params.moves}}class PendingCollectionsOperation{sort(propertyPath,direction="ascending"){this.pendingCursorOperation.sort(propertyPath,direction);return this}offset(offset){this.pendingCursorOperation.offset(offset);return this}limit(limit){this.pendingCursorOperation.limit(limit);return this}subscribe(){return this.pendingCursorOperation.subscribe()}observeLocal(handler){return this._observe(handler,false,false)}observeLocalWithNextSignal(handler){return this._observe(handler,false,true)}async exec(){const documents=await this.pendingCursorOperation.exec();return collectionsFromDocuments(documents,this.store)}constructor(store){this.store=store;this.pendingCursorOperation=new PendingCursorOperation("true",null,new Collection("__collections",store))}then(onfulfilled,onrejected){return this.exec().then(onfulfilled,onrejected)}_observe(handler,createSubscription,waitForNextSignal){const weakThis=new WeakRef(this);const collectionsObservationHandler=function(documents,event,nextSignal){const strongThis=weakThis.deref();if(strongThis===null)return;const collections=collectionsFromDocuments(documents,strongThis.store);let collEvent;if(event.isInitial===true){collEvent=CollectionsEvent.initial(collections)}else{const oldCollections=collectionsFromDocuments(event.oldDocuments,strongThis.store);collEvent=new CollectionsEvent({isInitial:false,collections:collections,oldCollections:oldCollections,insertions:event.insertions,deletions:event.deletions,updates:event.updates,moves:event.moves})}if(waitForNextSignal){handler(collEvent,nextSignal)}else{handler(collEvent)}};return this.pendingCursorOperation._observe(collectionsObservationHandler,createSubscription,waitForNextSignal)}}function collectionsFromDocuments(documents,store){const collections=[];for(const document of documents){const collectionName=document.at("name").value;if(collectionName!==undefined&&typeof collectionName==="string"){collections.push(new Collection(collectionName,store))}}return collections}class Store{collection(name){return new Collection(name,this)}collections(){return new PendingCollectionsOperation(this.ditto.store)}collectionNames(){return dittoGetCollectionNames(dittoBridge.pointerFor(this.ditto))}constructor(ditto){this.ditto=ditto}async registerLiveQueryWebhook(collectionName,query,url){const validatedQuery=validateQuery(query);const idCBOR=await liveQueryWebhookRegister(dittoBridge.pointerFor(this.ditto),collectionName,validatedQuery,[],0,0,url);return new DocumentID(idCBOR,true)}}function addressToString(address){return`${address.siteId}-${address.pubkey}`}class Presence{get graph(){const dittoPointer=dittoBridge.pointerFor(this.ditto);const graphJSONString=dittoPresenceV3(dittoPointer);return JSON.parse(graphJSONString)}observe(didChangeHandler){const observerToken=this.observerManager.addObserver(didChangeHandler);const observer=new Observer(this.observerManager,observerToken,{stopsWhenFinalized:true});didChangeHandler(this.graph);return observer}constructor(ditto){this.ditto=ditto;this.observerManager=new ObserverManager("PresenceObservation",{keepAlive:ditto.keepAlive,register:callback=>{const dittoPointer=dittoBridge.pointerFor(this.ditto);dittoRegisterPresenceV3Callback(dittoPointer,callback)},unregister:()=>{const dittoPointer=dittoBridge.pointerFor(this.ditto);dittoClearPresenceV3Callback(dittoPointer)},process:presenceGraphJSONString=>{const presenceGraph=JSON.parse(presenceGraphJSONString);return[presenceGraph]}})}}class PresenceManager{constructor(ditto){this.ditto=ditto;this.isRegistered=false;this.currentRemotePeers=[];this.callbacksByPresenceToken={}}addObserver(callback){this.registerIfNeeded();const token=generateEphemeralToken();this.callbacksByPresenceToken[token]=callback;this.ditto.keepAlive.retain(`PresenceObservation.${token}`);callback(this.currentRemotePeers);return token}removeObserver(token){this.ditto.keepAlive.release(`PresenceObservation.${token}`);delete this.callbacksByPresenceToken[token];this.unregisterIfNeeded()}hasObservers(){return Object.keys(this.callbacksByPresenceToken).length>0}registerIfNeeded(){const needsToRegister=!this.isRegistered;if(needsToRegister){this.isRegistered=true;const dittoPointer=dittoBridge.pointerFor(this.ditto);const remotePeersJSONString=dittoPresenceV1(dittoPointer);this.currentRemotePeers=this.decode(remotePeersJSONString).sort(this.compareRemotePeers);dittoRegisterPresenceV1Callback(dittoPointer,this.handlePresenceV1Callback.bind(this))}}unregisterIfNeeded(){const needsToUnregister=!this.hasObservers()&&this.isRegistered;if(needsToUnregister){this.isRegistered=false;const dittoPointer=dittoBridge.pointerFor(this.ditto);dittoRegisterPresenceV1Callback(dittoPointer,null);this.currentRemotePeers=[]}}handlePresenceV1Callback(remotePeersJSONString){const remotePeers=this.decode(remotePeersJSONString).sort(this.compareRemotePeers);this.currentRemotePeers=remotePeers;this.notify()}notify(){for(const token in this.callbacksByPresenceToken){const callback=this.callbacksByPresenceToken[token];callback(this.currentRemotePeers)}}decode(remotePeersJSONString){const remotePeersJSON=JSON.parse(remotePeersJSONString);return remotePeersJSON.map((remotePeerJSON=>{var _a,_b;return{networkID:remotePeerJSON["network_id"],deviceName:remotePeerJSON["device_name"],rssi:(_a=remotePeerJSON["rssi"])!==null&&_a!==void 0?_a:undefined,approximateDistanceInMeters:(_b=remotePeerJSON["approximate_distance_in_meters"])!==null&&_b!==void 0?_b:undefined,connections:remotePeerJSON["connections"]}}))}finalize(token){this.removeObserver(token)}compareRemotePeers(left,right){if(left.connections.length===0&&right.connections.length>0)return+1;if(left.connections.length>0&&right.connections.length===0)return-1;if(left.deviceName<right.deviceName)return-1;if(left.deviceName>right.deviceName)return+1;return 0}}class TransportConditionsManager extends ObserverManager{constructor(ditto){const keepAlive=ditto.keepAlive;super("TransportConditionsObservation",{keepAlive:keepAlive});this.ditto=ditto}register(callback){const dittoPointer=dittoBridge.pointerFor(this.ditto);return dittoRegisterTransportConditionChangedCallback(dittoPointer,callback)}unregister(){const dittoPointer=dittoBridge.pointerFor(this.ditto);return dittoRegisterTransportConditionChangedCallback(dittoPointer,null)}process(conditionSource,transportCondition){let apiConditionSource;switch(conditionSource){case"Bluetooth":apiConditionSource="BLE";break;case"Tcp":apiConditionSource="TCP";break;case"Awdl":apiConditionSource="AWDL";break;case"Mdns":apiConditionSource="MDNS";break}let apiTransportCondition;switch(transportCondition){case"Unknown":apiTransportCondition="Unknown";break;case"Ok":apiTransportCondition="OK";break;case"GenericFailure":apiTransportCondition="GenericFailure";break;case"AppInBackground":apiTransportCondition="AppInBackground";break;case"MdnsFailure":apiTransportCondition="MDNSFailure";break;case"TcpListenFailure":apiTransportCondition="TCPListenFailure";break;case"NoBleCentralPermission":apiTransportCondition="NoBLECentralPermission";break;case"NoBlePeripheralPermission":apiTransportCondition="NoBLEPeripheralPermission";break;case"CannotEstablishConnection":apiTransportCondition="CannotEstablishConnection";break;case"BleDisabled":apiTransportCondition="BLEDisabled";break;case"NoBleHardware":apiTransportCondition="NoBLEHardware";break;case"WifiDisabled":apiTransportCondition="WiFiDisabled";break;case"TemporarilyUnavailable":apiTransportCondition="TemporarilyUnavailable";break}return[apiTransportCondition,apiConditionSource]}}class Sync{constructor(ditto){this.bluetoothLETransportPointer=null;this.awdlTransportPointer=null;this.lanTransportPointer=null;this.mdnsClientTransportPointer=null;this.mdnsServerAdvertiserPointer=null;const identity=ditto.identity;const transportConfig=new TransportConfig;const parameters={identity:identity,transportConfig:transportConfig,isWebValid:false,isX509Valid:false,isSyncActive:false};this.ditto=ditto;this.parameters=parameters;this.state=stateFrom(parameters);this.staticTCPClientsByAddress={};this.websocketClientsByURL={}}update(parameters){this["parameters"]={...parameters};const stateOld=this.state;const stateNew=stateFrom(this.parameters);this.updatePeerToPeerBluetoothLE(stateOld,stateNew);this.updatePeerToPeerAWDL(stateOld,stateNew);this.updatePeerToPeerLAN(stateOld,stateNew);this.updateListenTCP(stateOld,stateNew);this.updateListenHTTP(stateOld,stateNew);this.updateConnectTCPServers(stateOld,stateNew);this.updateConnectWebsocketURLs(stateOld,stateNew);this.updateGlobal(stateOld,stateNew);this.state=stateNew}updatePeerToPeerBluetoothLE(stateOld,stateNew){const dittoPointer=dittoBridge.pointerFor(this.ditto);const bluetoothLEOld=stateOld.effectiveTransportConfig.peerToPeer.bluetoothLE;const bluetoothLENew=stateNew.effectiveTransportConfig.peerToPeer.bluetoothLE;const shouldStart=!bluetoothLEOld.isEnabled&&bluetoothLENew.isEnabled;const shouldStop=bluetoothLEOld.isEnabled&&!bluetoothLENew.isEnabled;if(shouldStart&&this.bluetoothLETransportPointer)throw new Error(`Internal inconsistency, when starting BLE transport, no BLE transport pointer should exist.`);if(shouldStop&&!this.bluetoothLETransportPointer)throw new Error(`Internal inconsistency, when stopping BLE transport, a BLE transport pointer should exist.`);{if(process.platform==="linux"||process.platform==="win32"){if(shouldStart){const clientTransport=dittoAddInternalBLEClientTransport(dittoPointer);const serverTransport=dittoAddInternalBLEServerTransport(dittoPointer);const blePlatform={clientTransport:clientTransport,serverTransport:serverTransport};this.bluetoothLETransportPointer=blePlatform}if(shouldStop){const blePlatform=this.bluetoothLETransportPointer;const{clientTransport:clientTransport,serverTransport:serverTransport}=blePlatform;bleServerFreeHandle(serverTransport);bleClientFreeHandle(clientTransport);this.bluetoothLETransportPointer=null}return}}if(shouldStart){if(!bleIsAvailable(dittoPointer))throw new Error("Can't start P2P BluetoothLE transport because not available.");this.bluetoothLETransportPointer=bleCreate(dittoPointer)}if(shouldStop){bleDestroy(this.bluetoothLETransportPointer);delete this.bluetoothLETransportPointer}}updatePeerToPeerAWDL(stateOld,stateNew){const dittoPointer=dittoBridge.pointerFor(this.ditto);const awdlOld=stateOld.effectiveTransportConfig.peerToPeer.awdl;const awdlNew=stateNew.effectiveTransportConfig.peerToPeer.awdl;const shouldStart=!awdlOld.isEnabled&&awdlNew.isEnabled;const shouldStop=awdlOld.isEnabled&&!awdlNew.isEnabled;if(shouldStart&&this.awdlTransportPointer)throw new Error(`Internal inconsistency, when starting AWDL transport, no AWDL transport pointer should exist.`);if(shouldStop&&!this.awdlTransportPointer)throw new Error(`Internal inconsistency, when stopping AWDL transport, an AWDL transport pointer should exist.`);if(shouldStart){if(!awdlIsAvailable(dittoPointer))throw new Error("Can't start P2P AWDL transport because not available.");this.awdlTransportPointer=awdlCreate(dittoPointer)}if(shouldStop){awdlDestroy(this.awdlTransportPointer);this.awdlTransportPointer=null}}updatePeerToPeerLAN(stateOld,stateNew){const dittoPointer=dittoBridge.pointerFor(this.ditto);const lanOld=stateOld.effectiveTransportConfig.peerToPeer.lan;const lanNew=stateNew.effectiveTransportConfig.peerToPeer.lan;{if(process.platform==="win32"){if(lanOld.isEnabled){if(lanOld.isMdnsEnabled){mdnsClientFreeHandle(this.mdnsClientTransportPointer);this.mdnsClientTransportPointer=null;mdnsServerFreeHandle(this.mdnsServerAdvertiserPointer);this.mdnsServerAdvertiserPointer=null}if(lanOld.isMulticastEnabled){dittoRemoveMulticastTransport(dittoPointer)}}if(lanNew.isEnabled){if(lanNew.isMdnsEnabled){this.mdnsClientTransportPointer=dittoAddInternalMdnsTransport(dittoPointer);this.mdnsServerAdvertiserPointer=dittoAddInternalMdnsAdvertiser(dittoPointer)}if(lanNew.isMulticastEnabled){dittoAddMulticastTransport(dittoPointer)}}return}}if(lanOld.isEnabled){if(lanOld.isMdnsEnabled){lanDestroy(this.lanTransportPointer);delete this.lanTransportPointer}if(lanOld.isMulticastEnabled){dittoRemoveMulticastTransport(dittoPointer)}}if(lanNew.isEnabled){if(lanNew.isMdnsEnabled){if(!lanIsAvailable(dittoPointer))throw new Error("Can't start P2P LAN transport because not available.");this.lanTransportPointer=lanCreate(dittoPointer)}if(lanNew.isMulticastEnabled){dittoAddMulticastTransport(dittoPointer)}}}updateListenTCP(stateOld,stateNew){const tcpOld=stateOld.effectiveTransportConfig.listen.tcp;const tcpNew=stateNew.effectiveTransportConfig.listen.tcp;if(TransportConfig.areListenTCPsEqual(tcpNew,tcpOld))return;const dittoPointer=dittoBridge.pointerFor(this.ditto);if(tcpOld.isEnabled)dittoStopTCPServer(dittoPointer);if(tcpNew.isEnabled)dittoStartTCPServer(dittoPointer,`${tcpNew.interfaceIP}:${tcpNew.port}`)}updateListenHTTP(stateOld,stateNew){const httpOld=stateOld.effectiveTransportConfig.listen.http;const httpNew=stateNew.effectiveTransportConfig.listen.http;if(TransportConfig.areListenHTTPsEqual(httpOld,httpNew))return;const dittoPointer=dittoBridge.pointerFor(this.ditto);if(httpOld.isEnabled)dittoStopHTTPServer(dittoPointer);if(httpNew.isEnabled){dittoStartHTTPServer(dittoPointer,`${httpNew.interfaceIP}:${httpNew.port}`,httpNew.staticContentPath||null,httpNew.websocketSync?"Enabled":"Disabled",httpNew.tlsCertificatePath||null,httpNew.tlsKeyPath||null)}}updateConnectTCPServers(stateOld,stateNew){const currentTCPServers=Object.getOwnPropertyNames(this.staticTCPClientsByAddress);const desiredTCPServers=stateNew.effectiveTransportConfig.connect.tcpServers;const tcpServersToConnectToSet=new Set(desiredTCPServers);for(const tcpServer of currentTCPServers)tcpServersToConnectToSet.delete(tcpServer);const tcpServersToDisconnectFromSet=new Set(currentTCPServers);for(const tcpServer of desiredTCPServers)tcpServersToDisconnectFromSet.delete(tcpServer);const tcpServersToConnectTo=tcpServersToConnectToSet.values();const tcpServersToDisconnectFrom=tcpServersToDisconnectFromSet.values();for(const tcpServer of tcpServersToConnectTo){const staticTCPClientPointer=addStaticTCPClient(dittoBridge.pointerFor(this.ditto),tcpServer);const staticTCPClient=staticTCPClientBridge.bridge(staticTCPClientPointer);this.staticTCPClientsByAddress[tcpServer]=staticTCPClient}for(const tcpServer of tcpServersToDisconnectFrom){const staticTCPClient=this.staticTCPClientsByAddress[tcpServer];if(!staticTCPClient)throw new Error(`Internal inconsistency, can't disconnect from TCP address '${tcpServer}', no staticTCPClient found.`);const staticTCPClientPointer=staticTCPClientBridge.pointerFor(staticTCPClient);staticTCPClientBridge.unregister(staticTCPClient);staticTCPClientFreeHandle(staticTCPClientPointer);delete this.staticTCPClientsByAddress[tcpServer]}}updateConnectWebsocketURLs(stateOld,stateNew){const currentWebsocketURLs=Object.getOwnPropertyNames(this.websocketClientsByURL);const desiredWebsocketURLs=stateNew.effectiveTransportConfig.connect.websocketURLs.slice();const websocketURLsToConnectToSet=new Set(desiredWebsocketURLs);for(const websocketURL of currentWebsocketURLs)websocketURLsToConnectToSet.delete(websocketURL);const websocketURLsToDisconnectFromSet=new Set(currentWebsocketURLs);for(const websocketURL of desiredWebsocketURLs)websocketURLsToDisconnectFromSet.delete(websocketURL);const websocketURLsToConnectTo=websocketURLsToConnectToSet.values();const websocketURLsToDisconnectFrom=websocketURLsToDisconnectFromSet.values();const routingHint=stateNew.effectiveTransportConfig.global.routingHint;for(const websocketURL of websocketURLsToConnectTo){const websocketClientPointer=addWebsocketClient(dittoBridge.pointerFor(this.ditto),websocketURL,routingHint);const websocketClient=websocketClientBridge.bridge(websocketClientPointer);this.websocketClientsByURL[websocketURL]=websocketClient}for(const websocketURL of websocketURLsToDisconnectFrom){const websocketClient=this.websocketClientsByURL[websocketURL];if(!websocketClient)throw new Error(`Internal inconsistency, can't disconnect from websocket URL '${websocketURL}', no websocketClient found.`);const websocketClientPointer=websocketClientBridge.pointerFor(websocketClient);websocketClientBridge.unregister(websocketClient);websocketClientFreeHandle(websocketClientPointer);delete this.websocketClientsByURL[websocketURL]}}updateGlobal(stateOld,stateNew){if(stateOld.effectiveTransportConfig.global.syncGroup!==stateNew.effectiveTransportConfig.global.syncGroup){dittoSetSyncGroup(dittoBridge.pointerFor(this.ditto),stateNew.effectiveTransportConfig.global.syncGroup)}}}function stateFrom(parameters){var _a;const transportConfig=parameters.transportConfig.copy();const identity=parameters.identity;const isSyncActive=parameters.isSyncActive;const isX509Valid=parameters.isX509Valid;const isWebValid=parameters.isWebValid;transportConfig.connect.tcpServers;transportConfig.connect.websocketURLs;let appID;let customDittoCloudURL;let isDittoCloudSyncEnabled=false;if(identity.type==="onlinePlayground"||identity.type==="onlineWithAuthentication"){appID=identity.appID;customDittoCloudURL=(_a=identity.customDittoCloudURL)!==null&&_a!==void 0?_a:null;isDittoCloudSyncEnabled=identity.hasOwnProperty("enableDittoCloudSync")?identity.enableDittoCloudSync:true}if(!isSyncActive||!isX509Valid){transportConfig.peerToPeer.bluetoothLE.isEnabled=false;transportConfig.peerToPeer.awdl.isEnabled=false;transportConfig.peerToPeer.lan.isEnabled=false;transportConfig.listen.tcp.isEnabled=false;transportConfig.connect.tcpServers=[]}if(!isSyncActive||!isWebValid){transportConfig.connect.websocketURLs=[]}if(!isSyncActive){transportConfig.listen.http.isEnabled=false}if(isSyncActive&&isWebValid&&isDittoCloudSyncEnabled){const dittoCloudURL=customDittoCloudURL!==null&&customDittoCloudURL!==void 0?customDittoCloudURL:defaultDittoCloudURL(appID);transportConfig.connect.websocketURLs.push(dittoCloudURL)}if(transportConfig.peerToPeer.lan.isEnabled&&!transportConfig.listen.tcp.isEnabled){transportConfig.listen.tcp.isEnabled=true;transportConfig.listen.tcp.interfaceIP="0.0.0.0";transportConfig.listen.tcp.port=0}return{underlyingSyncParameters:parameters,effectiveTransportConfig:transportConfig.freeze()}}class Ditto{get sdkVersion(){const dittoPointer=dittoBridge.pointerFor(this);return dittoGetSDKVersion(dittoPointer)}constructor(identity,path){this.isWebValid=false;this.isX509Valid=false;const isPathGiven=path&&path.trim().length>0;const identityOrDefault=identity!==null&&identity!==void 0?identity:{type:"offlinePlayground",appID:""};const pathOrDefault=isPathGiven?path:"ditto";const validIdentity=Object.freeze(this.validateIdentity(identityOrDefault));this.identity=Object.freeze(validIdentity);this.path=pathOrDefault;{const fs=require("fs");fs.mkdirSync(pathOrDefault,{recursive:true})}{const os=require("os");this.deviceName=os.hostname()}this.keepAlive=new KeepAlive;const uninitializedDittoX=uninitializedDittoMake(pathOrDefault);let secondsRemainingUntilAuthenticationExpires=null;const weakThis=new WeakRef(this);const authClientX=(()=>{var _a,_b,_c;if(validIdentity.type==="offlinePlayground"){return dittoAuthClientMakeForDevelopment(pathOrDefault,validIdentity.appID,(_a=validIdentity.siteID)!==null&&_a!==void 0?_a:0)}if(validIdentity.type==="manual"){return dittoAuthClientMakeWithStaticX509(validIdentity.certificate)}if(validIdentity.type==="sharedKey"){return dittoAuthClientMakeWithSharedKey(pathOrDefault,validIdentity.appID,validIdentity.sharedKey,validIdentity.siteID)}if(validIdentity.type==="onlinePlayground"){const authURL=(_b=validIdentity.customAuthURL)!==null&&_b!==void 0?_b:defaultAuthURL(validIdentity.appID);return dittoAuthClientMakeAnonymousClient(pathOrDefault,validIdentity.appID,validIdentity.token,authURL)}if(validIdentity.type==="onlineWithAuthentication"){const authURL=(_c=validIdentity.customAuthURL)!==null&&_c!==void 0?_c:defaultAuthURL(validIdentity.appID);const loginProviderX=dittoAuthClientMakeLoginProvider((function(secondsRemaining){const strongThis=weakThis.deref();if(!strongThis){Logger.warning(`Internal inconsistency, LoginProvider callback fired after the corresponding Ditto instance has been deallocated.`);return}if(strongThis.auth){strongThis.auth["@ditto.authenticationExpiring"](secondsRemaining)}else{secondsRemainingUntilAuthenticationExpires=secondsRemaining}}));return dittoAuthClientMakeWithWeb(pathOrDefault,validIdentity.appID,authURL,loginProviderX)}throw new Error(`Can't create Ditto, unsupported identity type: ${validIdentity}`)})();dittoAuthClientSetValidityListener(authClientX,(function(...args){var _a;(_a=weakThis.deref())===null||_a===void 0?void 0:_a.authClientValidityChanged(...args)}));const isWebValid=dittoAuthClientIsWebValid(authClientX);const isX509Valid=dittoAuthClientIsX509Valid(authClientX);const siteID=dittoAuthClientGetSiteID(authClientX);const dittoX=dittoMake(uninitializedDittoX,authClientX);dittoBridge.bridge(dittoX,this);if(validIdentity.type==="onlineWithAuthentication"){this.auth=new OnlineAuthenticator(this.keepAlive,authClientX,this,validIdentity.authHandler)}else if(validIdentity.type==="onlinePlayground"){this.auth=new OnlineAuthenticator(this.keepAlive,authClientX,this,{authenticationRequired:function(authenticator){},authenticationExpiringSoon:function(authenticator,secondsRemaining){}})}else{dittoAuthClientFree(authClientX);this.auth=new NotAvailableAuthenticator(this.keepAlive)}const transportConfig=this.makeDefaultTransportConfig();this.siteID=siteID;this.transportConfig=transportConfig.copy().freeze();this.isX509Valid=isX509Valid;this.isWebValid=isWebValid;this.sync=new Sync(this);this.sync.update({isSyncActive:false,isX509Valid:isX509Valid,isWebValid:isWebValid,identity:validIdentity,transportConfig:transportConfig});this.isActivated=!IdentityTypesRequiringOfflineLicenseToken.includes(validIdentity.type);this.store=new Store(this);this.presence=new Presence(this);this.presenceManager=new PresenceManager(this);this.transportConditionsManager=new TransportConditionsManager(this);if(secondsRemainingUntilAuthenticationExpires!==null){this.auth["@ditto.authenticationExpiring"](secondsRemainingUntilAuthenticationExpires)}}setOfflineOnlyLicenseToken(licenseToken){{if(IdentityTypesRequiringOfflineLicenseToken.includes(this.identity.type)){const{result:result,errorMessage:errorMessage}=verifyLicense(licenseToken);if(result!=="LicenseOk"){this["isActivated"]=false;throw new Error(errorMessage)}else{this["isActivated"]=true}}else{throw new Error("Offline license tokens should only be used for manual, sharedKey or offlinePlayground identities")}}}setTransportConfig(transportConfig){this.transportConfig;this["transportConfig"]=transportConfig.copy().freeze();const transportConfigNew=this.transportConfig;const identity=this.identity;const isWebValid=this.isWebValid;const isX509Valid=this.isX509Valid;this.sync.update({transportConfig:transportConfigNew,identity:identity,isWebValid:isWebValid,isX509Valid:isX509Valid,isSyncActive:this.isSyncActive})}updateTransportConfig(update){const transportConfig=this.transportConfig.copy();update(transportConfig);this.setTransportConfig(transportConfig);return this}startSync(){this.setSyncActive(true)}stopSync(){this.setSyncActive(false)}observePeers(callback){Logger.warning("`ditto.observePeers()` is deprecated, please use `ditto.presence.observe()` instead.");const token=this.presenceManager.addObserver(callback);return new Observer(this.presenceManager,token,{stopsWhenFinalized:true})}observeTransportConditions(callback){const token=this.transportConditionsManager.addObserver(callback);return new Observer(this.transportConditionsManager,token,{stopsWhenFinalized:true})}runGarbageCollection(){const dittoPointer=dittoBridge.pointerFor(this);dittoRunGarbageCollection(dittoPointer)}disableSyncWithV2(){const dittoPointer=dittoBridge.pointerFor(this);dittoDisableSyncWithV2(dittoPointer)}authClientValidityChanged(isWebValid,isX509Valid){const transportConfig=this.transportConfig;const identity=this.identity;const isSyncActive=this.isSyncActive;this.isX509Valid;this.isWebValid;this.isX509Valid=isX509Valid;this.isWebValid=isWebValid;this.auth["@ditto.authClientValidityChanged"](isWebValid,isX509Valid);this.sync.update({transportConfig:transportConfig,identity:identity,isWebValid:isWebValid,isX509Valid:isX509Valid,isSyncActive:isSyncActive})}validateIdentity(identity){const validIdentity={...identity};identity["appName"];const appID=identity["appID"];if(!["offlinePlayground","sharedKey","manual","onlinePlayground","onlineWithAuthentication"].includes(identity.type)){throw new Error(`Can't create Ditto instance, unknown identity type: ${identity.type}`)}if((identity.type==="offlinePlayground"||identity.type==="sharedKey"||identity.type==="onlinePlayground"||identity.type==="onlineWithAuthentication")&&typeof appID==="undefined"){throw new Error(`Property .appID must be given for identity, but isn't.`)}if(typeof appID!=="undefined"&&typeof appID!=="string"){throw new Error(`Property .appID must be be of type string, but is of type '${typeof appID}': ${appID}`)}if((identity.type==="offlinePlayground"||identity.type==="sharedKey")&&typeof identity.siteID!=="undefined"){const siteID=identity.siteID;const isSiteIDNumberOrBigInt=typeof siteID==="number"||typeof siteID==="bigint";if(!isSiteIDNumberOrBigInt)throw new Error("Can't create Ditto instance, siteID must be a number or BigInt");if(siteID<0)throw new Error("Can't create Ditto instance, siteID must be >= 0");if(siteID>BigInt("0xffffffffffffffff"))throw new Error("Can't create Ditto instance, siteID must be < 2^64")}if(identity.type==="sharedKey");if(identity.type==="manual");if(identity.type==="onlinePlayground"){const token=identity.token;if(typeof token==="undefined"){throw new Error(`Property .token must be given for identity but isn't. You can find the corresponding token on the Ditto Portal.`)}if(typeof token!=="undefined"&&typeof token!=="string"){throw new Error(`Property .token of identity must be be of type string, but is of type '${typeof token}': ${token}`)}}if(identity.type==="onlineWithAuthentication");return validIdentity}setSyncActive(flag){if(flag&&IdentityTypesRequiringOfflineLicenseToken.includes(this.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.")}if(!this.isSyncActive&&flag){this.keepAlive.retain("sync")}if(this.isSyncActive&&!flag){this.keepAlive.release("sync")}const dittoPointer=dittoBridge.pointerFor(this);this["isSyncActive"]=flag;const isWebValid=this.isWebValid;const isX509Valid=this.isX509Valid;const identity=this.identity;const transportConfig=this.transportConfig;dittoSetDeviceName(dittoPointer,this.deviceName);this.sync.update({identity:identity,transportConfig:transportConfig,isWebValid:isWebValid,isX509Valid:isX509Valid,isSyncActive:!!flag})}makeDefaultTransportConfig(){const dittoPointer=dittoBridge.pointerFor(this);const transportConfig=new TransportConfig;if(bleIsAvailable(dittoPointer)){transportConfig.peerToPeer.bluetoothLE.isEnabled=true}if(awdlIsAvailable(dittoPointer)){transportConfig.peerToPeer.awdl.isEnabled=true}if(lanIsAvailable(dittoPointer)){transportConfig.peerToPeer.lan.isEnabled=true}{if(process.platform==="linux"){transportConfig.peerToPeer.bluetoothLE.isEnabled=false}}return transportConfig.freeze()}}const dittoBridge=new Bridge(Ditto,(dittoPointer=>{dittoClearPresenceCallback(dittoPointer);dittoFree(dittoPointer)}));class Value{constructor(value,options={}){this.value=value;this.isDefault=!!options["isDefault"]}}exports.Attachment=Attachment;exports.AttachmentFetcher=AttachmentFetcher;exports.AttachmentToken=AttachmentToken;exports.Authenticator=Authenticator;exports.CBOR=CBOR;exports.Collection=Collection;exports.CollectionsEvent=CollectionsEvent;exports.Counter=Counter;exports.Ditto=Ditto;exports.Document=Document;exports.DocumentID=DocumentID;exports.DocumentPath=DocumentPath;exports.IdentityTypesRequiringOfflineLicenseToken=IdentityTypesRequiringOfflineLicenseToken;exports.KeepAlive=KeepAlive;exports.LiveQuery=LiveQuery;exports.LiveQueryEventInitial=LiveQueryEventInitial;exports.LiveQueryEventUpdate=LiveQueryEventUpdate;exports.Logger=Logger;exports.MutableCounter=MutableCounter;exports.MutableDocument=MutableDocument;exports.MutableDocumentPath=MutableDocumentPath;exports.MutableRegister=MutableRegister;exports.NotAvailableAuthenticator=NotAvailableAuthenticator;exports.Observer=Observer;exports.OnlineAuthenticator=OnlineAuthenticator;exports.PendingCollectionsOperation=PendingCollectionsOperation;exports.PendingCursorOperation=PendingCursorOperation;exports.PendingIDSpecificOperation=PendingIDSpecificOperation;exports.Presence=Presence;exports.RGA=RGA;exports.Register=Register;exports.SingleDocumentLiveQueryEvent=SingleDocumentLiveQueryEvent;exports.Store=Store;exports.Subscription=Subscription;exports.TransportConfig=TransportConfig;exports.UpdateResult=UpdateResult;exports.UpdateResultsMap=UpdateResultsMap;exports.Value=Value;exports.addressToString=addressToString;exports.attachmentBridge=attachmentBridge;exports.dittoBridge=dittoBridge;exports.documentBridge=documentBridge;exports.init=init;exports.mutableDocumentBridge=mutableDocumentBridge;exports.validateDocumentIDCBOR=validateDocumentIDCBOR;exports.validateDocumentIDValue=validateDocumentIDValue;
|
|
1
|
+
"use strict";const debugTypeNames=[],debugAllTypes=!1;class Meta{constructor(t,e,n){this.type=t,this.object=e,this.pointer=n}toString(){return`{ Meta | type: ${this.type.name}, object: ${this.object.deref()}, FFI address: ${this.pointer.addr}, FFI type: ${this.pointer.type} }`}}class Bridge{constructor(t,e,n={}){this.type=t,this.release=e,this.metaByAddrMap={},this.finalizationRegistry=new FinalizationRegistry(this.finalize.bind(this)),Bridge.all.push(new WeakRef(this))}pointerFor(t){return t["@ditto.ptr"]}objectFor(t){const e=this.metaByAddrMap[t.addr];if(!e)return;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}`);const n=e.object.deref();if(!n)throw new Error(`Internal inconsistency, found a meta entry for an object whose object is undefined (garbage collected): ${t}`);return n}bridge(t,e,n={}){const i=n.throwIfAlreadyBridged,r=this.objectFor(t);if(r&&i)throw new Error(`Can't bridge, pointer has already been bridged: ${JSON.stringify(t)}`);if(r)return r;let o;if(e||(e=()=>Reflect.construct(this.type,[])),"function"==typeof e){if(o=e(),!o)throw new Error(`Can't bridge, expected passed in create function to return an object but got: ${o}`)}else o=e;return this.register(o,t),o}register(t,e){const n=t.constructor,i=this.type;if(n!==i)throw new Error(`Can't register, bridge is configured for type ${i.name} but passed in object is of type ${n.name}`);const r=this.pointerFor(t),o=this.metaByAddrMap[e.addr];if(r&&o)throw new Error(`Can't register, an object for the passed in pointer has previously been registered: ${o.pointer}`);if(r&&!o)throw new Error(`Internal inconsistency, trying to register an object which has an associated pointer but no meta entry: ${t}`);if(!r&&o)throw new Error(`Internal inconsistency, trying to register an object which has a meta entry but no associated pointer: ${t}`);const s=new Meta(n,new WeakRef(t),e);t["@ditto.ptr"]=e,this.metaByAddrMap[s.pointer.addr]=s,this.finalizationRegistry.register(t,e,t),debugTypeNames.includes(this.type.name)&&console.log(`[VERBOSE] Bridge REGISTERED a new instance of ${this.type.name}, current count: ${Object.keys(this.metaByAddrMap).length}`)}unregister(t){const e=t.constructor,n=this.type;if(e!==n)throw new Error(`Can't unregister, bridge is configured for type ${n.name} but passed in object is of type ${e.name}`);const i=this.pointerFor(t);if(!i)throw new Error(`Can't unregister, object that has not been registered before: ${t}`);const r=this.metaByAddrMap[i.addr];if(!r)throw new Error(`Internal inconsistency, trying to unregister an object which has an associated pointer but no meta entry: ${t}`);if(r.type!==n)throw new Error(`Internal inconsistency, trying to unregister an object that has a meta entry with a different type than that of the bridge: ${r}`);if(!r.object.deref())throw new Error(`Internal inconsistency, trying to unregister an object that has a meta entry whose object is undfined (garbage collected): ${r}`);if(r.object.deref()!==t)throw new Error(`Internal inconsistency, trying to unregister an object that has a meta entry holding a different object: ${r}`);this.finalizationRegistry.unregister(t),delete this.metaByAddrMap[i.addr],delete t["@ditto.ptr"],debugTypeNames.includes(this.type.name)&&console.log(`[VERBOSE] Bridge UNREGISTERED an instance of ${this.type.name}, current count: ${Object.keys(this.metaByAddrMap).length}`)}unregisterAll(){debugTypeNames.includes(this.type.name)&&console.log(`[VERBOSE] Unregistering ALL bridged instances of type ${this.type.name}.`);for(const t of Object.values(this.metaByAddrMap)){const e=t.object.deref();e&&this.unregister(e)}}get count(){return Object.keys(this.metaByAddrMap).length}finalize(t){if(!this.metaByAddrMap[t.addr])throw new Error(`Internal inconsistency, tried to finalize an instance for a pointer, that has no meta entry: ${t}`);delete this.metaByAddrMap[t.addr],this.release(t),debugTypeNames.includes(this.type.name)&&console.log(`[VERBOSE] Bridge FINALIZED an instance of ${this.type.name}, current count: ${Object.keys(this.metaByAddrMap).length}`)}}Bridge.all=[];const defaultDittoCloudDomain="cloud.ditto.live";function defaultAuthURL(t){return`https://${t}.cloud.ditto.live`}function defaultDittoCloudURL(t){return`wss://${t}.cloud.ditto.live`}function validateNumber(t,e={}){var n;const i=null!==(n=e.errorMessagePrefix)&&void 0!==n?n:"Number validation failed:",r=!!e.integer,o=e.min,s=e.max,a=e.minX,c=e.maxX;if("number"!=typeof t)throw new Error(`${i} '${t}' is not a number.`);if(r&&Math.floor(t)!==t)throw new Error(`${i} '${t}' is not an integer.`);if(void 0!==o&&t<o)throw new Error(`${i} '${t}' must be >= ${o}.`);if(void 0!==s&&t>s)throw new Error(`${i} '${t}' must be <= ${s}.`);if(void 0!==a&&t<=a)throw new Error(`${i} '${t}' must be > ${a}.`);if(void 0!==c&&t>=c)throw new Error(`${i} '${t}' must be < ${c}.`);return t}function validateQuery(t,e={}){var n;const i=null!==(n=e.errorMessagePrefix)&&void 0!==n?n:"Query validation failed,";if("string"!=typeof t)throw new Error(`${i} query is not a string: ${t}`);if(""===t)throw new Error(`${i} query is an empty string.`);const r=t.trim();if(""===r)throw new Error(`${i} query contains only whitespace characters.`);return r}class StaticTCPClient{}class WebsocketClient{}const staticTCPClientBridge=new Bridge(StaticTCPClient,staticTCPClientFreeHandle),websocketClientBridge=new Bridge(WebsocketClient,websocketClientFreeHandle);function generateEphemeralToken(){let t;t=require("crypto").webcrypto;const e=new Uint16Array(16);t.getRandomValues(e);return Array.from(e).map((t=>t.toString(16))).join("")}function sleep(t){return new Promise(((e,n)=>{setTimeout(e,t)}))}async function step(t){return await sleep(0),t()}const performAsyncToWorkaroundNonAsyncFFIAPI=step,ditto=function(){const t=process.platform+"-"+process.arch;try{if("darwin-x64"===t)return require("./ditto.darwin-x64.node");if("darwin-arm64"===t)return require("./ditto.darwin-arm64.node");if("linux-x64"===t)return require("./ditto.linux-x64.node");if("linux-arm"===t)return require("./ditto.linux-arm.node");if("win32-x64"===t)return require("./ditto.win32-x64.node")}catch(e){throw new Error("Couldn't load native module 'ditto."+t+".node' due to error:"+e.toString())}throw new Error("No native module 'ditto."+t+".node' found.")}();function ble_client_free_handle(...t){return ditto.ble_client_free_handle(...t)}function ble_server_free_handle(...t){return ditto.ble_server_free_handle(...t)}function boxCBytesIntoBuffer(...t){return ditto.boxCBytesIntoBuffer(...t)}function boxCStringIntoString(...t){return ditto.boxCStringIntoString(...t)}function cStringVecToStringArray(...t){return ditto.cStringVecToStringArray(...t)}function ditto_add_internal_ble_client_transport(...t){return ditto.ditto_add_internal_ble_client_transport(...t)}function ditto_add_internal_ble_server_transport(...t){return ditto.ditto_add_internal_ble_server_transport(...t)}function ditto_add_internal_mdns_advertiser(...t){return ditto.ditto_add_internal_mdns_advertiser(...t)}function ditto_add_internal_mdns_transport(...t){return ditto.ditto_add_internal_mdns_transport(...t)}function ditto_add_multicast_transport(...t){return ditto.ditto_add_multicast_transport(...t)}function ditto_add_static_tcp_client(...t){return ditto.ditto_add_static_tcp_client(...t)}function ditto_add_subscription(...t){return ditto.ditto_add_subscription(...t)}function ditto_add_websocket_client(...t){return ditto.ditto_add_websocket_client(...t)}function ditto_auth_client_free(...t){return ditto.ditto_auth_client_free(...t)}function ditto_auth_client_get_site_id(...t){return ditto.ditto_auth_client_get_site_id(...t)}function ditto_auth_client_is_web_valid(...t){return ditto.ditto_auth_client_is_web_valid(...t)}function ditto_auth_client_is_x509_valid(...t){return ditto.ditto_auth_client_is_x509_valid(...t)}function ditto_auth_client_login_with_credentials(...t){return ditto.ditto_auth_client_login_with_credentials(...t)}function ditto_auth_client_login_with_token(...t){return ditto.ditto_auth_client_login_with_token(...t)}function ditto_auth_client_logout(...t){return ditto.ditto_auth_client_logout(...t)}function ditto_auth_client_make_anonymous_client(...t){return ditto.ditto_auth_client_make_anonymous_client(...t)}function ditto_auth_client_make_for_development(...t){return ditto.ditto_auth_client_make_for_development(...t)}function ditto_auth_client_make_login_provider(...t){return ditto.ditto_auth_client_make_login_provider(...t)}function ditto_auth_client_make_with_shared_key(...t){return ditto.ditto_auth_client_make_with_shared_key(...t)}function ditto_auth_client_make_with_static_x509(...t){return ditto.ditto_auth_client_make_with_static_x509(...t)}function ditto_auth_client_make_with_web(...t){return ditto.ditto_auth_client_make_with_web(...t)}function ditto_auth_client_set_validity_listener(...t){return ditto.ditto_auth_client_set_validity_listener(...t)}function ditto_auth_client_user_id(...t){return ditto.ditto_auth_client_user_id(...t)}function ditto_cancel_resolve_attachment(...t){return ditto.ditto_cancel_resolve_attachment(...t)}function ditto_clear_presence_callback(...t){return ditto.ditto_clear_presence_callback(...t)}function ditto_clear_presence_v3_callback(...t){return ditto.ditto_clear_presence_v3_callback(...t)}function ditto_collection_evict(...t){return ditto.ditto_collection_evict(...t)}function ditto_collection_evict_query_str(...t){return ditto.ditto_collection_evict_query_str(...t)}function ditto_collection_exec_query_str(...t){return ditto.ditto_collection_exec_query_str(...t)}function ditto_collection_get(...t){return ditto.ditto_collection_get(...t)}function ditto_collection_insert_value(...t){return ditto.ditto_collection_insert_value(...t)}function ditto_collection_remove(...t){return ditto.ditto_collection_remove(...t)}function ditto_collection_remove_query_str(...t){return ditto.ditto_collection_remove_query_str(...t)}function ditto_collection_update(...t){return ditto.ditto_collection_update(...t)}function ditto_collection_update_multiple(...t){return ditto.ditto_collection_update_multiple(...t)}function ditto_disable_sync_with_v2(...t){return ditto.ditto_disable_sync_with_v2(...t)}function ditto_document_free(...t){return ditto.ditto_document_free(...t)}function ditto_document_get_cbor_with_path_type(...t){return ditto.ditto_document_get_cbor_with_path_type(...t)}function ditto_document_id(...t){return ditto.ditto_document_id(...t)}function ditto_document_id_query_compatible(...t){return ditto.ditto_document_id_query_compatible(...t)}function ditto_document_increment_counter(...t){return ditto.ditto_document_increment_counter(...t)}function ditto_document_remove(...t){return ditto.ditto_document_remove(...t)}function ditto_document_set_cbor(...t){return ditto.ditto_document_set_cbor(...t)}function ditto_document_set_cbor_with_timestamp(...t){return ditto.ditto_document_set_cbor_with_timestamp(...t)}function ditto_documents_hash(...t){return ditto.ditto_documents_hash(...t)}function ditto_documents_hash_mnemonic(...t){return ditto.ditto_documents_hash_mnemonic(...t)}function ditto_error_message(...t){return ditto.ditto_error_message(...t)}function ditto_free(...t){return ditto.ditto_free(...t)}function ditto_free_attachment_handle(...t){return ditto.ditto_free_attachment_handle(...t)}function ditto_get_collection_names(...t){return ditto.ditto_get_collection_names(...t)}function ditto_get_complete_attachment_path(...t){return ditto.ditto_get_complete_attachment_path(...t)}function ditto_get_sdk_version(...t){return ditto.ditto_get_sdk_version(...t)}function ditto_init_sdk_version(...t){return ditto.ditto_init_sdk_version(...t)}function ditto_live_query_register_str_detached(...t){return ditto.ditto_live_query_register_str_detached(...t)}function ditto_live_query_signal_available_next(...t){return ditto.ditto_live_query_signal_available_next(...t)}function ditto_live_query_start(...t){return ditto.ditto_live_query_start(...t)}function ditto_live_query_stop(...t){return ditto.ditto_live_query_stop(...t)}function ditto_live_query_webhook_register_str(...t){return ditto.ditto_live_query_webhook_register_str(...t)}function ditto_log(...t){return ditto.ditto_log(...t)}function ditto_logger_emoji_headings_enabled(...t){return ditto.ditto_logger_emoji_headings_enabled(...t)}function ditto_logger_emoji_headings_enabled_get(...t){return ditto.ditto_logger_emoji_headings_enabled_get(...t)}function ditto_logger_enabled(...t){return ditto.ditto_logger_enabled(...t)}function ditto_logger_enabled_get(...t){return ditto.ditto_logger_enabled_get(...t)}function ditto_logger_init(...t){return ditto.ditto_logger_init(...t)}function ditto_logger_minimum_log_level(...t){return ditto.ditto_logger_minimum_log_level(...t)}function ditto_logger_minimum_log_level_get(...t){return ditto.ditto_logger_minimum_log_level_get(...t)}function ditto_logger_set_custom_log_cb(...t){return ditto.ditto_logger_set_custom_log_cb(...t)}function ditto_logger_set_log_file(...t){return ditto.ditto_logger_set_log_file(...t)}function ditto_make(...t){return ditto.ditto_make(...t)}function ditto_new_attachment_from_bytes(...t){return ditto.ditto_new_attachment_from_bytes(...t)}function ditto_new_attachment_from_file(...t){return ditto.ditto_new_attachment_from_file(...t)}function ditto_presence_v1(...t){return ditto.ditto_presence_v1(...t)}function ditto_presence_v3(...t){return ditto.ditto_presence_v3(...t)}function ditto_read_transaction(...t){return ditto.ditto_read_transaction(...t)}function ditto_read_transaction_free(...t){return ditto.ditto_read_transaction_free(...t)}function ditto_register_presence_v1_callback(...t){return ditto.ditto_register_presence_v1_callback(...t)}function ditto_register_presence_v3_callback(...t){return ditto.ditto_register_presence_v3_callback(...t)}function ditto_register_transport_condition_changed_callback(...t){return ditto.ditto_register_transport_condition_changed_callback(...t)}function ditto_remove_multicast_transport(...t){return ditto.ditto_remove_multicast_transport(...t)}function ditto_remove_subscription(...t){return ditto.ditto_remove_subscription(...t)}function ditto_resolve_attachment(...t){return ditto.ditto_resolve_attachment(...t)}function ditto_run_garbage_collection(...t){return ditto.ditto_run_garbage_collection(...t)}function ditto_set_device_name(...t){return ditto.ditto_set_device_name(...t)}function ditto_set_sync_group(...t){return ditto.ditto_set_sync_group(...t)}function ditto_start_http_server(...t){return ditto.ditto_start_http_server(...t)}function ditto_start_tcp_server(...t){return ditto.ditto_start_tcp_server(...t)}function ditto_stop_http_server(...t){return ditto.ditto_stop_http_server(...t)}function ditto_stop_tcp_server(...t){return ditto.ditto_stop_tcp_server(...t)}function ditto_validate_document_id(...t){return ditto.ditto_validate_document_id(...t)}function ditto_write_transaction(...t){return ditto.ditto_write_transaction(...t)}function ditto_write_transaction_commit(...t){return ditto.ditto_write_transaction_commit(...t)}function jsDocsToCDocs(...t){return ditto.jsDocsToCDocs(...t)}function mdns_client_free_handle(...t){return ditto.mdns_client_free_handle(...t)}function mdns_server_free_handle(...t){return ditto.mdns_server_free_handle(...t)}function refCStringToString(...t){return ditto.refCStringToString(...t)}function static_tcp_client_free_handle(...t){return ditto.static_tcp_client_free_handle(...t)}function uninitialized_ditto_make(...t){return ditto.uninitialized_ditto_make(...t)}function verify_license(...t){return ditto.verify_license(...t)}function websocket_client_free_handle(...t){return ditto.websocket_client_free_handle(...t)}function withOutBoxCBytes(...t){return ditto.withOutBoxCBytes(...t)}function withOutPtr$1(...t){return ditto.withOutPtr(...t)}const DittoCRDTTypeKey="_ditto_internal_type_jkb12973t4b",DittoCRDTValueKey="_value";var DittoCRDTType;function dittoAddInternalBLEClientTransport(t){return ditto_add_internal_ble_client_transport(t)}function dittoAddInternalBLEServerTransport(t){return ditto_add_internal_ble_server_transport(t)}function bleClientFreeHandle(t){return ble_client_free_handle(t)}function bleServerFreeHandle(t){return ble_server_free_handle(t)}function dittoAddInternalMdnsTransport(t){return ditto_add_internal_mdns_transport(t)}function mdnsClientFreeHandle(t){return mdns_client_free_handle(t)}function dittoAddInternalMdnsAdvertiser(t){return ditto_add_internal_mdns_advertiser(t)}function mdnsServerFreeHandle(t){return mdns_server_free_handle(t)}function documentSetCBORWithTimestamp(t,e,n,i,r){ensureInitialized();const o=ditto_document_set_cbor_with_timestamp(t,bytesFromString(e),n,i,r);if(0!==o)throw new Error(errorMessage()||`ditto_document_set_cbor_with_timestamp() failed with error code: ${o}`)}function documentSetCBOR(t,e,n,i){ensureInitialized();const r=ditto_document_set_cbor(t,bytesFromString(e),n,i);if(0!==r)throw new Error(errorMessage()||`ditto_document_set_cbor() failed with error code: ${r}`)}function documentID(t){ensureInitialized();return boxCBytesIntoBuffer(ditto_document_id(t))}function documentGetCBORWithPathType(t,e,n){ensureInitialized();const i=ditto_document_get_cbor_with_path_type(t,bytesFromString(e),n);return{statusCode:i.status_code,cbor:boxCBytesIntoBuffer(i.cbor)}}function documentRemove(t,e){ensureInitialized();const n=ditto_document_remove(t,bytesFromString(e));if(0!==n)throw new Error(errorMessage()||`ditto_document_remove() failed with error code: ${n}`)}function documentIncrementCounter(t,e,n){ensureInitialized();const i=ditto_document_increment_counter(t,bytesFromString(e),n);if(0!==i)throw new Error(errorMessage()||`ditto_document_increment_counter() failed with error code: ${i}`)}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 n=ditto_validate_document_id(t,e);if(0!==n)throw new Error(errorMessage()||`ditto_validate_document_id() failed with error code: ${n}`);return e})))}async function collectionGet(t,e,n,i){ensureInitialized();const r=bytesFromString(e),{status_code:o,document:s}=await ditto_collection_get(t,r,n,i);if(o===NOT_FOUND_ERROR_CODE)return null;if(0!==o)throw new Error(errorMessage()||`ditto_collection_get() failed with error code: ${o}`);return s}async function collectionInsertValue(t,e,n,i,r){ensureInitialized();const o=bytesFromString(e);let s;switch(r){case"merge":s="Merge";break;case"insertIfAbsent":s="InsertIfAbsent";break;case"insertDefaultIfAbsent":s="InsertDefaultIfAbsent";break;default:throw new Error("Invalid write strategy provided")}const{status_code:a,id:c}=await ditto_collection_insert_value(t,o,n,i,s,null,null);if(0!==a)throw new Error(errorMessage()||`ditto_collection_insert_value() failed with error code: ${a}`);return boxCBytesIntoBuffer(c)}async function collectionRemove(t,e,n,i){ensureInitialized();const r=bytesFromString(e),{status_code:o,bool_value:s}=await ditto_collection_remove(t,r,n,i);if(0!==o)throw new Error(errorMessage()||`ditto_collection_remove() failed with error code: ${o}`);return s}async function collectionEvict(t,e,n,i){ensureInitialized();const r=bytesFromString(e),{status_code:o,bool_value:s}=await ditto_collection_evict(t,r,n,i);if(0!==o)throw new Error(errorMessage()||`ditto_collection_evict() failed with error code: ${o}`);return s}async function collectionUpdate(t,e,n,i){ensureInitialized();const r=bytesFromString(e),o=await ditto_collection_update(t,r,n,i);if(0!==o)throw new Error(errorMessage()||`ditto_collection_update() failed with error code: ${o}`)}async function collectionUpdateMultiple(t,e,n,i){ensureInitialized();const r=bytesFromString(e),o=jsDocsToCDocs(i),s=await ditto_collection_update_multiple(t,r,n,o);if(0!==s)throw new Error(errorMessage()||`ditto_collection_update_multiple() failed with error code: ${s}`)}async function collectionExecQueryStr(t,e,n,i,r,o,s,a){ensureInitialized();const c=bytesFromString(e),l=bytesFromString(i);return await ditto_collection_exec_query_str(t,c,n,l,r,o,s,a)}async function collectionRemoveQueryStr(t,e,n,i,r,o,s,a){ensureInitialized();const c=bytesFromString(e),l=bytesFromString(i);return await ditto_collection_remove_query_str(t,c,n,l,r,o,s,a)}async function collectionEvictQueryStr(t,e,n,i,r,o,s,a){ensureInitialized();const c=bytesFromString(e),l=bytesFromString(i);return await ditto_collection_evict_query_str(t,c,n,l,r,o,s,a)}function addSubscription(t,e,n,i,r,o,s){ensureInitialized();return ditto_add_subscription(t,bytesFromString(e),bytesFromString(n),i,r,o,s)}function removeSubscription(t,e,n,i,r,o,s){ensureInitialized();return ditto_remove_subscription(t,bytesFromString(e),bytesFromString(n),i,r,o,s)}function liveQueryRegister(t,e,n,i,r,o,s,a,c){ensureInitialized();const l=bytesFromString(e),d=bytesFromString(n),{status_code:u,i64:h}=ditto_live_query_register_str_detached(t,l,d,i,r,o,s,wrapBackgroundCbForFFI(c,a));if(0!==u)throw new Error(errorMessage()||`\`ditto_live_query_register_str()\` failed with error code: ${u}`);return h}async function liveQueryStart(t,e){ensureInitialized();const n=await ditto_live_query_start(t,e);if(0!==n)throw new Error(errorMessage()||`\`ditto_live_query_start()\` failed with error code: ${n}`)}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)}async function liveQueryWebhookRegister(t,e,n,i,r,o,s){ensureInitialized();const a=bytesFromString(e),c=bytesFromString(n),l=bytesFromString(s),{status_code:d,id:u}=await ditto_live_query_webhook_register_str(t,a,c,i,r,o,l);if(0!==d)throw new Error(errorMessage()||`\`ditto_live_query_webhook_register_str()\` failed with error code: ${d}`);return boxCBytesIntoBuffer(u)}async function readTransaction(t){ensureInitialized();const{status_code:e,txn:n}=await ditto_read_transaction(t);if(0!==e)throw new Error(errorMessage()||`\`ditto_read_transaction()\` failed with error code: ${e}`);return n}function readTransactionFree(t){return ensureInitialized(),ditto_read_transaction_free(t)}async function writeTransaction(t){ensureInitialized();const{status_code:e,txn:n}=await ditto_write_transaction(t,null);if(0!==e)throw new Error(errorMessage()||`ditto_write_transaction() failed with error code: ${e}`);return n}async function writeTransactionCommit(t,e){ensureInitialized();const n=await ditto_write_transaction_commit(t,e);if(0!==n)throw new Error(errorMessage()||`ditto_write_transaction_commit() failed with error code: ${n}`)}function addStaticTCPClient(t,e){ensureInitialized();return ditto_add_static_tcp_client(t,bytesFromString(e))}function staticTCPClientFreeHandle(t){static_tcp_client_free_handle(t)}function addWebsocketClient(t,e,n){ensureInitialized();return ditto_add_websocket_client(t,bytesFromString(e),n)}function websocketClientFreeHandle(t){ensureInitialized(),websocket_client_free_handle(t)}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,n)=>{try{const i=boxCStringIntoString(n);t(e,i)}catch(t){console.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))throw errorMessage(),new Error(`Can't set log file, due to error: ${errorMessage}`)}function log(t,e){ensureInitialized(),bytesFromString(t);ditto_log(t,bytesFromString(e))}function dittoAuthClientMakeAnonymousClient(t,e,n,i){ensureInitialized();const r=bytesFromString(t),o=bytesFromString(e),s=bytesFromString(n),a=bytesFromString(i),{status_code:c,auth_client:l}=ditto_auth_client_make_anonymous_client(r,o,s,a);if(0!==c)throw new Error(errorMessage()||`ditto_auth_client_make_anonymous_client() failed with error code: ${c}`);return l}function dittoAuthClientMakeWithWeb(t,e,n,i){ensureInitialized();const r=bytesFromString(t),o=bytesFromString(e),s=bytesFromString(n),{status_code:a,auth_client:c}=ditto_auth_client_make_with_web(r,o,s,i);if(0!==a)throw new Error(errorMessage()||`ditto_auth_client_make_with_web() failed with error code: ${a}`);return c}function dittoAuthClientMakeForDevelopment(t,e,n){ensureInitialized();const i=bytesFromString(t),r=bytesFromString(e),o=Number(n),{status_code:s,auth_client:a}=ditto_auth_client_make_for_development(i,r,o);if(0!==s)throw new Error(errorMessage()||`ditto_auth_client_make_for_development() failed with error code: ${s}`);return a}function dittoAuthClientMakeWithSharedKey(t,e,n,i){ensureInitialized();const r=bytesFromString(t),o=bytesFromString(e),s=bytesFromString(n),a=Number(i),{status_code:c,auth_client:l}=ditto_auth_client_make_with_shared_key(r,o,s,a);if(0!==c)throw new Error(errorMessage()||`ditto_auth_client_make_with_shared_key() failed with error code: ${c}`);return l}function dittoAuthClientMakeWithStaticX509(t){ensureInitialized();const e=bytesFromString(t),{status_code:n,auth_client:i}=ditto_auth_client_make_with_static_x509(e);if(0!==n)throw new Error(errorMessage()||`ditto_auth_client_make_with_static_x509() failed with error code: ${n}`);return i}function dittoAuthClientGetSiteID(t){return ensureInitialized(),ditto_auth_client_get_site_id(t)}function dittoAuthClientFree(t){return ensureInitialized(),ditto_auth_client_free(t)}function dittoAuthClientIsWebValid(t){return ensureInitialized(),0!==ditto_auth_client_is_web_valid(t)}function dittoAuthClientUserID(t){ensureInitialized();return boxCStringIntoString(ditto_auth_client_user_id(t))}function dittoAuthClientIsX509Valid(t){return ensureInitialized(),0!==ditto_auth_client_is_x509_valid(t)}async function dittoAuthClientLoginWithToken(t,e,n){ensureInitialized();const i=bytesFromString(e),r=bytesFromString(n),o=await ditto_auth_client_login_with_token(t,i,r);if(0!==o)throw new Error(errorMessage()||`Ditto failed to authenticate (error code: ${o}).`)}async function dittoAuthClientLoginWithUsernameAndPassword(t,e,n,i){ensureInitialized();const r=bytesFromString(e),o=bytesFromString(n),s=bytesFromString(i),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 uninitializedDittoMake(t){ensureInitialized();return uninitialized_ditto_make(bytesFromString(t))}function dittoMake(t,e){return ensureInitialized(),ditto_make(t,e,"Disabled")}async function dittoGetCollectionNames(t){ensureInitialized();const e=await ditto_get_collection_names(t),n=e.status_code,i=e.names;if(0!==n)throw new Error(errorMessage()||`ditto_get_collection_names() failed with error code: ${n}`);return cStringVecToStringArray(i)}function dittoFree(t){return ensureInitialized(),ditto_free(t)}async function dittoRegisterPresenceV1Callback(t,e){ensureInitialized(),e?ditto_register_presence_v1_callback(t,wrapBackgroundCbForFFI((t=>console.error(`The registered presence callback errored with ${t}`)),(t=>{const n=refCStringToString(t);e(n)}))):await ditto_clear_presence_callback(t)}async function dittoRegisterPresenceV3Callback(t,e){ensureInitialized(),ditto_register_presence_v3_callback(t,wrapBackgroundCbForFFI((t=>console.error(`The registered presence callback v3 errored with ${t}`)),(t=>{const n=refCStringToString(t);e(n)})))}async function dittoClearPresenceV3Callback(t){ensureInitialized(),ditto_clear_presence_v3_callback(t)}async function dittoClearPresenceCallback(t){ensureInitialized(),await ditto_clear_presence_callback(t)}function dittoRegisterTransportConditionChangedCallback(t,e){ensureInitialized(),ditto_register_transport_condition_changed_callback(t,e?wrapBackgroundCbForFFI((t=>console.error(`The registered "transport condition changed" callback errored with ${t}`)),e):null)}function dittoSetDeviceName(t,e){return ensureInitialized(),ditto_set_device_name(t,bytesFromString(e))}function dittoSetSyncGroup(t,e){return ensureInitialized(),ditto_set_sync_group(t,e)}function dittoNewAttachmentFromFile(t,e,n){ensureInitialized();const i={},r=ditto_new_attachment_from_file(t,bytesFromString(e),n,i);if(0!==r)throw new Error(errorMessage()||`ditto_new_attachment_from_file() failed with error code: ${r}`);return i}async function dittoNewAttachmentFromBytes(t,e){ensureInitialized();const n={},i=await ditto_new_attachment_from_bytes(t,e,n);if(0!==i)throw new Error(errorMessage()||`ditto_new_attachment_from_bytes() failed with error code: ${i}`);return n}async function dittoResolveAttachment(t,e,n,i){ensureInitialized();const{onComplete:r,onProgress:o,onDelete:s}=n,{status_code:a,cancel_token:c}=await ditto_resolve_attachment(t,e,wrapBackgroundCbForFFI(i,r),wrapBackgroundCbForFFI(i,o),wrapBackgroundCbForFFI(i,s));if(0!==a)throw new Error(errorMessage()||`ditto_resolve_attachment() failed with error code: ${a}`);return c}function dittoCancelResolveAttachment(t,e,n){ensureInitialized();const i=ditto_cancel_resolve_attachment(t,e,n);if(0!==i)throw new Error(errorMessage()||`ditto_cancel_resolve_attachment() failed with error code: ${i}`)}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 dittoPresenceV1(t){ensureInitialized();return boxCStringIntoString(ditto_presence_v1(t))}function dittoPresenceV3(t){ensureInitialized();return boxCStringIntoString(ditto_presence_v3(t))}function dittoStartTCPServer(t,e){ensureInitialized();return ditto_start_tcp_server(t,bytesFromString(e))}function dittoStopTCPServer(t){return ensureInitialized(),ditto_stop_tcp_server(t)}function dittoAddMulticastTransport(t){return ensureInitialized(),ditto_add_multicast_transport(t)}function dittoRemoveMulticastTransport(t){return ensureInitialized(),ditto_remove_multicast_transport(t)}function dittoStartHTTPServer(t,e,n,i,r,o){ensureInitialized();return ditto_start_http_server(t,bytesFromString(e),bytesFromString(n),i,bytesFromString(r),bytesFromString(o))}function dittoStopHTTPServer(t){return ensureInitialized(),ditto_stop_http_server(t)}function dittoRunGarbageCollection(t){return ensureInitialized(),ditto_run_garbage_collection(t)}async function dittoDisableSyncWithV2(t){ensureInitialized();const e=await ditto_disable_sync_with_v2(t);if(0!==e)throw new Error(errorMessage()||`ditto_disable_sync_with_v2() failed with error code: ${e}`)}function documentsHash(t){ensureInitialized();const{status_code:e,u64:n}=ditto_documents_hash(t);if(0!==e)throw new Error(errorMessage()||`\`ditto_documents_hash()\` failed with error code: ${e}`);return BigInt(n)}function documentsHashMnemonic(t){ensureInitialized();const{status_code:e,c_string:n}=ditto_documents_hash_mnemonic(t);if(0!==e)throw new Error(errorMessage()||`\`ditto_documents_hash_mnemonic()\` failed with error code: ${e}`);return boxCStringIntoString(n)}function dittoAuthClientMakeLoginProvider(t,e){return ensureInitialized(),ditto_auth_client_make_login_provider(wrapBackgroundCbForFFI(e,t))}function dittoAuthClientSetValidityListener(t,e,n){ensureInitialized();return ditto_auth_client_set_validity_listener(t,wrapBackgroundCbForFFI(n,(function(t,n){return e(1===t,1===n)})))}!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 withOutPtr,isInitialized=!1;function initSDKVersion(t,e,n){ensureInitialized(),bytesFromString(t),bytesFromString(e);const i=ditto_init_sdk_version(t,e,bytesFromString(n));if(void 0!==i&&0!==i)throw new Error(errorMessage()||`ditto_init_sdk_version() failed with error code: ${i}`)}function verifyLicense(t){ensureInitialized();const e=bytesFromString(t);let n;const i=boxCStringIntoString(withOutPtr("char *",(t=>(n=verify_license(e,t),t))));return{result:n,errorMessage:i}}isInitialized=!0,withOutPtr=wrapFFIOutFunction(withOutPtr$1);const NOT_FOUND_ERROR_CODE=-30798;function wrapBackgroundCbForFFI(t,e){return void 0===t&&(t=console.error),(n,...i)=>{let r;try{r=e(...i)}catch(e){try{t(e)}catch(t){console.error(`Internal error: \`onError()\` handler oughtn't throw, but it did throw ${t}`)}}return n(r)}}function wrapFFIOutFunction(t){return function(...e){let n,i,r=!1;const o=e[e.length-1],s=e.splice(0,e.length-1),a=t(...s,(t=>{try{i=o(t),r=i===t}catch(t){n=t}}));if(n)throw n;return r?a:i}}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)throw new Error("Ditto needs to be initialized before using any of its API, please make sure to call `await init()` first.")}const transports=function(){if("undefined"!=typeof process&&"undefined"!=typeof require){const t=process.platform+"-"+process.arch;try{if("darwin-x64"===t)return require("./transports.darwin-x64.node");if("darwin-arm64"===t)return require("./transports.darwin-arm64.node")}catch(t){return null}}return null}();function bleIsAvailable(t){return"linux"===process.platform||"win32"===process.platform||null!==transports&&transports.bleIsAvailable(t)}function bleCreate(t){if(null!==transports)return transports.bleCreate(t);throw new Error("Can't create BluetoothLE handle, P2P BluetoothLE is not supported on this platform.")}function bleDestroy(t){if(null!==transports)return transports.bleDestroy(t);throw new Error("Can't destroy BluetoothLE handle, P2P BluetoothLE is not supported on this platform.")}function lanIsAvailable(t){return"win32"===process.platform||null!==transports&&transports.lanIsAvailable(t)}function lanCreate(t){if(null!==transports)return transports.lanCreate(t);throw new Error("Can't create LAN handle, P2P LAN transport is not supported on this platform.")}function lanDestroy(t){if(null!==transports)return transports.lanDestroy(t);throw new Error("Can't destroy LAN handle, P2P LAN transport is not supported on this platform.")}function awdlIsAvailable(t){return null!==transports&&transports.awdlIsAvailable(t)}function awdlCreate(t){if(null!==transports)return transports.awdlCreate(t);throw new Error("Can't create AWDL handle, P2P AWDL transport is not supported on this platform.")}function awdlDestroy(t){if(null!==transports)return transports.awdlDestroy(t);throw new Error("Can't destroy AWDL handle, P2P AWDL transport is not supported on this platform.")}const fullBuildVersionString="3.0.6-experimental.node-loading-issues.3.linux-x64";async function init(t={}){}switch(process.platform){case"android":initSDKVersion("Android","JavaScript",fullBuildVersionString);break;case"darwin":initSDKVersion("Mac","JavaScript",fullBuildVersionString);break;case"linux":initSDKVersion("Linux","JavaScript",fullBuildVersionString);break;case"win32":initSDKVersion("Windows","JavaScript",fullBuildVersionString);break;default:initSDKVersion("Unknown","JavaScript",fullBuildVersionString)}loggerInit();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}}KeepAlive.finalizationRegistry=new FinalizationRegistry(clearInterval);class Logger{static setLogFile(t){t?(loggerSetLogFile(t),this.logFile=t):(loggerSetLogFile(null),delete this.logFile)}static setLogFileURL(t){this.setLogFile(null==t?void 0:t.pathname)}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 async setCustomLogCallback(t){t?(await loggerSetCustomLogCb(t),this.customLogCallback=t):(await loggerSetCustomLogCb(null),delete this.customLogCallback)}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 it's static properties & methods directly instead.")}}class ObserverManager{constructor(t,e={}){var n,i,r,o;const s=null!==(n=e.keepAlive)&&void 0!==n?n:null,a=null!==(i=e.register)&&void 0!==i?i:null,c=null!==(r=e.unregister)&&void 0!==r?r:null,l=null!==(o=e.process)&&void 0!==o?o:null;this.id=t,this.keepAlive=s,this.isRegistered=!1,this.callbacksByToken={},null!==a&&(this.register=a),null!==c&&(this.unregister=c),null!==l&&(this.process=l)}addObserver(t){var e;this.registerIfNeeded();const n=generateEphemeralToken();return this.callbacksByToken[n]=t,null===(e=this.keepAlive)||void 0===e||e.retain(`${this.id}.${n}`),n}removeObserver(t){var e;delete this.callbacksByToken[t],null===(e=this.keepAlive)||void 0===e||e.release(`${this.id}.${t}`),this.unregisterIfNeeded()}notify(...t){const e=this.process(...t);for(const t in this.callbacksByToken){(0,this.callbacksByToken[t])(...e)}}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 n=t.deref();n&&n.notify(...e)}))}}unregisterIfNeeded(){!this.hasObservers()&&this.isRegistered&&(this.isRegistered=!1,this.unregister())}async finalize(t){await this.removeObserver(t)}}class Observer{constructor(t,e,n={}){this.observerManager=t,this.token=e,this.options=n,n.stopsWhenFinalized&&Observer.finalizationRegistry.register(this,{observerManager:t,token:e},this)}get isStopped(){return void 0===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:n}=t;e.removeObserver(n)}}Observer.finalizationRegistry=new FinalizationRegistry(Observer.finalize);class Authenticator{loginWithToken(t,e){throw new Error("Authenticator.loginWithToken() is abstract and must be implemented by subclasses.")}loginWithUsernameAndPassword(t,e,n){throw new Error("Authenticator.loginWithUsernameAndPassword() is abstract and must be implemented by subclasses.")}logout(t){throw new Error("Authenticator.logout() is abstract and must be implemented by subclasses.")}observeStatus(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.")}"@ditto.authClientValidityChanged"(t,e){throw new Error("Authenticator['@ditto.authClientValidityChanged']() is abstract and must be implemented by subclasses.")}}class OnlineAuthenticator extends Authenticator{async loginWithToken(t,e){await dittoAuthClientLoginWithToken(this.authClientPointer,t,e)}async loginWithUsernameAndPassword(t,e,n){await dittoAuthClientLoginWithUsernameAndPassword(this.authClientPointer,t,e,n)}async logout(t){const e=this.ditto.deref();e?(await dittoAuthClientLogout(this.authClientPointer),e.stopSync(),null==t||t(this.ditto)):Logger.warning("Unable to logout, related Ditto object does not exist anymore.")}constructor(t,e,n,i){super(t),this.loginSupported=!0,this.status={isAuthenticated:!1,userID:null},this.authClientPointer=e,this.ditto=new WeakRef(n),this.authenticationHandler=i,this.updateAndNotify(!1),OnlineAuthenticator.finalizationRegistry.register(this,e)}"@ditto.authenticationExpiring"(t){const e=this.authenticationHandler;t>0?e.authenticationExpiringSoon(this,t):e.authenticationRequired(this)}"@ditto.authClientValidityChanged"(t,e){this.updateAndNotify(!0)}updateAndNotify(t){var e;const n=this.status.isAuthenticated,i=this.status.userID,r=dittoAuthClientIsWebValid(this.authClientPointer),o=dittoAuthClientUserID(this.authClientPointer),s={isAuthenticated:r,userID:o};if(this.status=s,t){!!n==!!r&&i===o||(null===(e=this.authenticationHandler.authenticationStatusDidChange)||void 0===e||e.call(this.authenticationHandler,this),this.observerManager.notify(s))}}static finalize(t){dittoAuthClientFree(t)}}OnlineAuthenticator.finalizationRegistry=new FinalizationRegistry(OnlineAuthenticator.finalize);class NotAvailableAuthenticator extends Authenticator{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,n){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}`)}"@ditto.authClientValidityChanged"(t,e){throw new Error(`Internal inconsistency, authentication is not available, yet the @ditto.authClientValidityChanged() was called on authenticator: ${this}`)}}const IdentityTypesRequiringOfflineLicenseToken=["manual","sharedKey","offlinePlayground"],NO_PREFERRED_ROUTE_HINT=0;class TransportConfig{constructor(){this.peerToPeer={bluetoothLE:{isEnabled:!1},awdl:{isEnabled:!1},lan:{isEnabled:!1,isMdnsEnabled:!0,isMulticastEnabled:!0}},this.connect={tcpServers:[],websocketURLs:[]},this.listen={tcp:{isEnabled:!1,interfaceIP:"0.0.0.0",port:4040},http:{isEnabled:!1,interfaceIP:"0.0.0.0",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}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),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)),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.connect.tcpServers=this.connect.tcpServers.slice(),t.connect.websocketURLs=this.connect.websocketURLs.slice(),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 POW_2_24=5.960464477539063e-8,POW_2_32=4294967296,POW_2_53=9007199254740992,DECODE_CHUNK_SIZE=8192;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}class TaggedValue{constructor(t,e){this.value=t,this.tag=e}}function decode(t,e,n){let i=new DataView(t),r=new Uint8Array(t),o=0,tagValueFunction=function(t,e){return new TaggedValue(t,e)},simpleValFunction=function(t){};function commitRead(t,e){return o+=t,e}function readArrayBuffer(e){return commitRead(e,new Uint8Array(t,o,e))}function readUint8(){return commitRead(1,r[o])}function readUint16(){return commitRead(2,i.getUint16(o))}function readUint32(){return commitRead(4,i.getUint32(o))}function readBreak(){return 255===r[o]&&(o+=1,!0)}function readLength(t){if(t<24)return t;if(24===t)return readUint8();if(25===t)return readUint16();if(26===t)return readUint32();if(27===t)return function readUint64(){return readUint32()*POW_2_32+readUint32()}();if(31===t)return-1;throw new Error("Invalid length encoding")}function readIndefiniteStringLength(t){let e=readUint8();if(255===e)return-1;let n=readLength(31&e);if(n<0||e>>5!==t)throw new Error("Invalid indefinite length element");return n}function appendUtf16Data(t,e){for(let n=0;n<e;++n){let n=readUint8();128&n&&(n<224?(n=(31&n)<<6|63&readUint8(),e-=1):n<240?(n=(15&n)<<12|(63&readUint8())<<6|63&readUint8(),e-=2):(n=(15&n)<<18|(63&readUint8())<<12|(63&readUint8())<<6|63&readUint8(),e-=3)),n<65536?t.push(n):(n-=65536,t.push(55296|n>>10),t.push(56320|1023&n))}}"function"==typeof e&&(tagValueFunction=e),"function"==typeof n&&(simpleValFunction=n);let s=function decodeItem(){let t,e,n=readUint8(),r=n>>5,s=31&n;if(7===r)switch(s){case 25:return function readFloat16(){let t=new ArrayBuffer(4),e=new DataView(t),n=readUint16(),i=32768&n,r=31744&n,o=1023&n;if(31744===r)r=261120;else if(0!==r)r+=114688;else if(0!==o)return(i?-1:1)*o*POW_2_24;return e.setUint32(0,i<<16|r<<13|o<<13),e.getFloat32(0)}();case 26:return function readFloat32(){return commitRead(4,i.getFloat32(o))}();case 27:return function readFloat64(){return commitRead(8,i.getFloat64(o))}()}if(e=readLength(s),e<0&&(r<2||6<r))throw new Error("Invalid length");switch(r){case 0:return e;case 1:return-1-e;case 2:if(e<0){let n=[],i=0;for(;(e=readIndefiniteStringLength(r))>=0;)i+=e,n.push(readArrayBuffer(e));let o=new Uint8Array(i),s=0;for(t=0;t<n.length;++t)o.set(n[t],s),s+=n[t].length;return o}return readArrayBuffer(e);case 3:let n=[];if(e<0)for(;(e=readIndefiniteStringLength(r))>=0;)appendUtf16Data(n,e);else appendUtf16Data(n,e);let i="";for(t=0;t<n.length;t+=8192)i+=String.fromCharCode.apply(null,n.slice(t,t+8192));return i;case 4:let o;if(e<0)for(o=[];!readBreak();)o.push(decodeItem());else for(o=new Array(e),t=0;t<e;++t)o[t]=decodeItem();return o;case 5:let s={};for(t=0;t<e||e<0&&!readBreak();++t){s[decodeItem()]=decodeItem()}return s;case 6:return tagValueFunction(decodeItem(),e);case 7:switch(e){case 20:return!1;case 21:return!0;case 22:return null;case 23:return;default:return simpleValFunction(e)}}}();if(o!==t.byteLength)throw new Error("Remaining bytes");return s}function encode(t){let e,n=new ArrayBuffer(256),i=new DataView(n),r=new Uint8Array(n),o=0;function prepareWrite(t){let s=n.byteLength,a=o+t;for(;s<a;)s<<=1;if(s!==n.byteLength){let t=i;n=new ArrayBuffer(s),i=new DataView(n),r=new Uint8Array(n);let e=o+3>>2;for(let n=0;n<e;++n)i.setUint32(n<<2,t.getUint32(n<<2))}return e=t,i}function commitWrite(...t){o+=e}function writeUint8(t){commitWrite(prepareWrite(1).setUint8(o,t))}function writeUint8Array(t){prepareWrite(t.length),r.set(t,o),commitWrite()}function writeUint16(t){commitWrite(prepareWrite(2).setUint16(o,t))}function writeUint32(t){commitWrite(prepareWrite(4).setUint32(o,t))}function writeUint64(t){let e=t%POW_2_32,n=(t-e)/POW_2_32,i=prepareWrite(8);i.setUint32(o,n),i.setUint32(o+4,e),commitWrite()}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))}if(function encodeItem(t){let e;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"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(o,t))}(t);case"string":let n=[];for(e=0;e<t.length;++e){let i=t.charCodeAt(e);i<128?n.push(i):i<2048?(n.push(192|i>>6),n.push(128|63&i)):i<55296||i>=57344?(n.push(224|i>>12),n.push(128|i>>6&63),n.push(128|63&i)):(i=(1023&i)<<10,i|=1023&t.charCodeAt(++e),i+=65536,n.push(240|i>>18),n.push(128|i>>12&63),n.push(128|i>>6&63),n.push(128|63&i))}return writeTypeAndLength(3,n.length),writeUint8Array(n);default:let i,r;if(Array.isArray(t))for(i=t.length,writeTypeAndLength(4,i),e=0;e<i;e+=1)encodeItem(t[e]);else if(t instanceof Uint8Array)writeTypeAndLength(2,t.length),writeUint8Array(t);else if(ArrayBuffer.isView(t))r=new Uint8Array(t.buffer),writeTypeAndLength(2,r.length),writeUint8Array(r);else if(t instanceof ArrayBuffer||"function"==typeof SharedArrayBuffer&&t instanceof SharedArrayBuffer)r=new Uint8Array(t),writeTypeAndLength(2,r.length),writeUint8Array(r);else if(t instanceof TaggedValue)!function writeVarUint(t,e){t<=255?t<24?writeUint8(t|e):(writeUint8(24|e),writeUint8(t)):t<=65535?(writeUint8(25|e),writeUint16(t)):t<=4294967295?(writeUint8(26|e),writeUint32(t)):(writeUint8(27|e),writeUint64(t))}(t.tag,192),encodeItem(t.value);else{let n=Object.keys(t);for(i=n.length,writeTypeAndLength(5,i),e=0;e<i;e+=1){let i=n[e];encodeItem(i),encodeItem(t[i])}}}}(t),"slice"in n)return n.slice(0,o);let s=new ArrayBuffer(o),a=new DataView(s);for(let t=0;t<o;++t)a.setUint8(t,i.getUint8(t));return s}const CBOR$1={decode:decode,encode:encode};class CBOR{static encode(t){const e=CBOR$1.encode(t);return new Uint8Array(e)}static decode(t){const e=t.buffer;return CBOR$1.decode(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,n=!1){const i=e?t:CBOR.encode(t),r=n?i:validateDocumentIDCBOR(i);if(!r)throw new Error(`Can't create DocumentID, passed in value is not valid: ${t}`);this.isValidated=!n,this["@ditto.cbor"]=r}equals(t){const e=this["@ditto.cbor"],n=t["@ditto.cbor"];if(e===n)return!0;if(!(e instanceof Uint8Array))return!1;if(!(n instanceof Uint8Array))return!1;if(e.length!==n.length)return!1;for(let t=0;t<e.length;t+=1)if(e[t]!==n[t])return!1;return!0}toString(){return documentIDQueryCompatible(this["@ditto.cbor"],"WithoutQuotes")}toBase64String(){const t=this["@ditto.cbor"];return btoa(String.fromCharCode.apply(null,t))}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 Attachment{get metadata(){return this.token.metadata}getData(){{const t=dittoGetCompleteAttachmentPath(dittoBridge.pointerFor(this.ditto),attachmentBridge.pointerFor(this));return require("fs/promises").readFile(t)}}copyToPath(t){{const e=dittoGetCompleteAttachmentPath(dittoBridge.pointerFor(this.ditto),attachmentBridge.pointerFor(this)),n=require("fs/promises");return n.copyFile(e,t,n.COPYFILE_EXCL)}}constructor(t,e){this.ditto=t,this.token=e}}const attachmentBridge=new Bridge(Attachment,freeAttachmentHandle);class AttachmentToken{constructor(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 n=t._len;if("number"!=typeof n||n<0)throw new Error("Invalid attachment token length");const i=t._meta;if("object"!=typeof i)throw new Error("Invalid attachment token meta");this.id=e,this.len=n,this.metadata=i}}class AttachmentFetcher{stop(){AttachmentFetcher.stopWithContextInfo({ditto:this.ditto,attachmentTokenID:this.token.id,cancelTokenPromise:this.cancelTokenPromise})}then(t,e){return this.attachment.then(t,e)}constructor(t,e,n){this.ditto=t,this.token=e,this.eventHandler=n||null,this.cancelTokenPromise=null;const i=n||function(){};this.attachment=new Promise(((n,r)=>{const o=dittoBridge.pointerFor(t);this.cancelTokenPromise=dittoResolveAttachment(o,e.id,{onComplete:t=>{this.eventHandler=null,this.cancelTokenPromise=null;const e=new Attachment(this.ditto,this.token);attachmentBridge.bridge(t,(()=>e),{throwIfAlreadyBridged:!0}),i({type:"Completed",attachment:e}),n(e)},onProgress:(t,e)=>{i({type:"Progress",totalBytes:e,downloadedBytes:t})},onDelete:()=>{this.eventHandler=null,this.cancelTokenPromise=null,i({type:"Deleted"}),n(null)}},(t=>{this.eventHandler=null,this.cancelTokenPromise=null,r(t)}))}));const r={ditto:t,attachmentTokenID:e.id,cancelTokenPromise:this.cancelTokenPromise};AttachmentFetcher.finalizationRegistry.register(this,r,r)}static stopWithContextInfo(t){step((async()=>{const e=await t.cancelTokenPromise;if(e){dittoCancelResolveAttachment(dittoBridge.pointerFor(t.ditto),t.attachmentTokenID,e)}}))}}AttachmentFetcher.finalizationRegistry=new FinalizationRegistry(AttachmentFetcher.stopWithContextInfo);class Subscription{get collectionName(){return this.collection.name}cancel(){this.isCancelled||(this.isCancelled=!0,Subscription.remove(this,this.contextInfo))}constructor(t,e,n,i,r,o){this.isCancelled=!1,this.query=e,this.queryArgsCBOR=n,this.collection=t,this.contextInfo={ditto:t.store.ditto,collectionName:t.name,query:e,queryArgsCBOR:n,orderBys:i,limit:r,offset:o},Subscription.add(this,this.contextInfo)}static add(t,e){addSubscription(dittoBridge.pointerFor(e.ditto),e.collectionName,e.query,e.queryArgsCBOR,e.orderBys,e.limit,e.offset),this.finalizationRegistry.register(t,e,e)}static remove(t,e){removeSubscription(dittoBridge.pointerFor(e.ditto),e.collectionName,e.query,e.queryArgsCBOR,e.orderBys,e.limit,e.offset),t&&this.finalizationRegistry.unregister(e)}}Subscription.finalizationRegistry=new FinalizationRegistry((t=>{Subscription.remove(null,t)}));const privateToken$1="@ditto.64d129224a5377b63e9727479ec987d9";class Counter{constructor(){this.value=0}static"@ditto.create"(t,e,n){const i=t?new MutableCounter(privateToken$1):new Counter;return i.mutDoc=t,i.path=e,i.value=n,i}}class MutableCounter extends Counter{increment(t){const e=this.mutDoc,n=this.path;if(!e)throw new Error("Can't increment counter, only possible within the closure of a collection's update() method.");e.at(n)["@ditto.increment"](t),this.value+=t}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,n){const i=t?new MutableRegister(n,privateToken):new Register(n);return i["@ditto.mutableDocument"]=t,i["@ditto.path"]=e,i["@ditto.value"]=n,i}}class MutableRegister extends Register{get value(){return super.value}set value(t){this.set(t)}set(t){const e=this["@ditto.mutableDocument"],n=this["@ditto.path"];e.at(n)["@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)}}class RGA{get value(){return this["@ditto.value"]}constructor(t=[]){this["@ditto.value"]=t}static"@ditto.create"(t,e){const n=new RGA(e);return n["@ditto.path"]=t,n["@ditto.value"]=e,n}}class UpdateResult{static set(t,e,n){return new UpdateResult("set",t,e,n,void 0)}static incremented(t,e,n){return new UpdateResult("incremented",t,e,void 0,n)}static removed(t,e){return new UpdateResult("removed",t,e,void 0,void 0)}constructor(t,e,n,i,r){this.type=t,this.docID=e,this.path=n,void 0!==i&&(this.value=i),void 0!==r&&(this.amount=r)}}function augmentJSONValue(t,e,n){if(t&&"object"==typeof t){if(Array.isArray(t))return t.map(((t,i)=>augmentJSONValue(t,e,`${n}[${i}]`)));if(t[DittoCRDTTypeKey]===DittoCRDTType.counter)return Counter["@ditto.create"](e,n,t._value);if(t[DittoCRDTTypeKey]===DittoCRDTType.register)return Register["@ditto.create"](e,n,t._value);if(t[DittoCRDTTypeKey]===DittoCRDTType.rga){const i=augmentJSONValue(t._value,e,n);return RGA["@ditto.create"](n,i)}if(t[DittoCRDTTypeKey]===DittoCRDTType.attachment)return new AttachmentToken(t);for(const[i,r]of Object.entries(t))t[i]=augmentJSONValue(r,e,`${n}['${i}']`);return t}return t}function desugarJSObject(t,e=!1){if(t&&"object"==typeof t){if(Array.isArray(t))return t.map(((t,e)=>desugarJSObject(t,!1)));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 RGA){const e={};return e[DittoCRDTTypeKey]=DittoCRDTType.rga,e._value=desugarJSObject(t.value),e}if(t instanceof Attachment){const e={_id:t.token.id,_len:t.token.len,_meta:t.token.metadata};return e[DittoCRDTTypeKey]=DittoCRDTType.attachment,e}for(const[e,n]of Object.entries(t))t[e]=desugarJSObject(n,!1);return t}return t}const regularKeyPattern=/\.([A-Za-z_]\w*)/.source,subscriptIndexPattern=/\[(\d+)\]/.source,subscriptSingleQuoteKeyPattern=/\[\'(.+?)\'\]/.source,subscriptDoubleQuoteKeyPattern=/\[\"(.+?)\"\]/.source,validKeyPathPattern=`((${regularKeyPattern})|(${subscriptIndexPattern})|(${subscriptSingleQuoteKeyPattern})|(${subscriptDoubleQuoteKeyPattern}))*`,regularKeyRegExp=new RegExp(`^${regularKeyPattern}`),subscriptIndexRegExp=new RegExp(`^${subscriptIndexPattern}`),subscriptSingleQuoteKeyRegExp=new RegExp(`^${subscriptSingleQuoteKeyPattern}`),subscriptDoubleQuoteKeyRegExp=new RegExp(`^${subscriptDoubleQuoteKeyPattern}`),validKeyPathRegExp=new RegExp(`^${validKeyPathPattern}$`);class KeyPath{static withLeadingDot(t){if("number"==typeof t)return t;if("string"!=typeof t)throw new Error(`Key-path must be a string or a number but is ${typeof t}: ${t}`);return"string"==typeof t&&!!t.match(/^[A-Za-z_]/)?`.${t}`:t}static withoutLeadingDot(t){if("number"==typeof t)return t;if("string"!=typeof t)throw new Error(`Key-path must be a string or a number but is ${typeof t}: ${t}`);return"string"==typeof t&&!!t.match(/^\./)?t.slice(1):t}static validate(t,e={}){var n;const i=null!==(n=e.isInitial)&&void 0!==n&&n;if("number"==typeof t)return Math.floor(Math.abs(t));if("string"!=typeof t)throw new Error(`Key-path must be a string or a number but is ${typeof t}: ${t}`);const r=this.withLeadingDot(t);if(!validKeyPathRegExp.test(r))throw new Error(`Key-path is not valid: ${t}`);return i?t:r}static evaluate(t,e,n={}){var i;const r=null!==(i=n.stopAtLastContainer)&&void 0!==i&&i,o={keyPath:t,object:e,options:{...n},coveredPath:null,nextPathComponent:null,remainingPath:t,value:e};return function recurse(t,e){if(""===e)return o.value=t,o;const{nextPathComponentRaw:n,nextPathComponent:i,remainingPath:s}=function advance(t){if("number"==typeof t)return{nextPathComponentRaw:t,nextPathComponent:t,remainingPath:""};if("string"!=typeof t)throw new Error(`Can't return value at given keyPath, expected keyPath to be a string or a number but got ${typeof t}: ${t}`);const e=t.match(regularKeyRegExp);if(null!==e){const n=e[0],i=e[1];return{nextPathComponentRaw:n,nextPathComponent:i,remainingPath:t.slice(i.length+1)}}const n=t.match(subscriptIndexRegExp);if(null!==n){const e=n[0],i=n[1];return{nextPathComponentRaw:e,nextPathComponent:parseInt(i),remainingPath:t.slice(i.length+2)}}const i=t.match(subscriptSingleQuoteKeyRegExp);if(null!==i){const e=i[0],n=i[1];return{nextPathComponentRaw:e,nextPathComponent:n,remainingPath:t.slice(n.length+4)}}const r=t.match(subscriptDoubleQuoteKeyRegExp);if(null!==r){const e=r[0],n=r[1];return{nextPathComponentRaw:e,nextPathComponent:n,remainingPath:t.slice(n.length+4)}}throw new Error(`Can't return value at keyPath because the following part of the keyPath is invalid: ${t}`)}(e);return o.nextPathComponent=i,o.remainingPath=s,null===o.coveredPath||"number"==typeof n?o.coveredPath=n:o.coveredPath+=n,""===s&&r?(o.value=t,o):recurse(t[i],s)}(e,this.withLeadingDot(t))}constructor(){}}class DocumentPath{at(t){if("string"==typeof t){const e=t,n=KeyPath.validate(e),i=KeyPath.withoutLeadingDot(`${this.path}${n}`);return new DocumentPath(this.document,i,!1)}if("number"==typeof t){const e=validateNumber(t,{integer:!0,min:0,errorMessagePrefix:"DocumentPath.at() validation failed index:"});return new DocumentPath(this.document,`${this.path}[${e.toString()}]`,!1)}throw new Error(`Can't return document path at key-path or index, string or number expected but got ${typeof t}: ${t}`)}get value(){return this.underlyingValueForPathType("Any")}get counter(){const t=this.underlyingValueForPathType("Counter");return void 0!==t?Counter["@ditto.create"](null,this.path,t):null}get register(){const t=this.underlyingValueForPathType("Register");return void 0!==t?Register["@ditto.create"](null,this.path,t):null}get rga(){const t=this.underlyingValueForPathType("Rga");return void 0!==t?RGA["@ditto.create"](this.path,t):null}get attachmentToken(){const t=this.underlyingValueForPathType("Attachment");return void 0!==t?new AttachmentToken(t):null}constructor(t,e,n){this.document=t,this.path=n?KeyPath.validate(e,{isInitial:!0}):e}underlyingValueForPathType(t){const e=this.path,n=this.document,i=documentGetCBORWithPathType(documentBridge.pointerFor(n),e,t);return null!==i.cbor?CBOR.decode(i.cbor):void 0}}class MutableDocumentPath{at(t){if("string"==typeof t){const e=t,n=KeyPath.validate(e),i=KeyPath.withoutLeadingDot(`${this.path}${n}`);return new MutableDocumentPath(this.mutableDocument,i,!1)}if("number"==typeof t){const e=validateNumber(t,{integer:!0,min:0,errorMessagePrefix:"MutableDocumentPath.at() validation failed index:"});return new MutableDocumentPath(this.mutableDocument,`${this.path}[${e.toString()}]`,!1)}throw new Error(`Can't return mutable document path at key-path or index, string or number expected but got ${typeof t}: ${t}`)}get value(){return this.underlyingValueForPathType("Any")}get counter(){const t=this.underlyingValueForPathType("Counter");return void 0!==t?Counter["@ditto.create"](this.mutableDocument,this.path,t):null}get register(){const t=this.underlyingValueForPathType("Register");return void 0!==t?Register["@ditto.create"](this.mutableDocument,this.path,t):null}get rga(){const t=this.underlyingValueForPathType("Rga");return void 0!==t?RGA["@ditto.create"](this.path,t):null}get attachmentToken(){const t=this.underlyingValueForPathType("Attachment");return void 0!==t?new AttachmentToken(t):null}set(t,e){return this["@ditto.set"](t,e)}remove(){return this["@ditto.remove"]()}constructor(t,e,n){this.mutableDocument=t,this.path=n?KeyPath.validate(e,{isInitial:!0}):e}underlyingValueForPathType(t){const e=this.path,n=this.mutableDocument,i=documentGetCBORWithPathType(mutableDocumentBridge.pointerFor(n),e,t);return null!==i.cbor?CBOR.decode(i.cbor):void 0}"@ditto.increment"(t){documentIncrementCounter(mutableDocumentBridge.pointerFor(this.mutableDocument),this.path,t);const e=UpdateResult.incremented(this.mutableDocument.id,this.path,t);this.recordUpdateResult(e)}"@ditto.set"(t,e){const n=mutableDocumentBridge.pointerFor(this.mutableDocument),i=desugarJSObject(t,!1),r=CBOR.encode(i);e?documentSetCBORWithTimestamp(n,this.path,r,!0,0):documentSetCBOR(n,this.path,r,!0);const o=augmentJSONValue(CBOR.decode(r),this.mutableDocument,this.path),s=UpdateResult.set(this.mutableDocument.id,this.path,o);this.recordUpdateResult(s)}"@ditto.remove"(){documentRemove(mutableDocumentBridge.pointerFor(this.mutableDocument),this.path),this.updateInMemory(((t,e)=>{Array.isArray(t)&&"number"==typeof e?t.splice(e,1):delete t[e]}));const t=UpdateResult.removed(this.mutableDocument.id,this.path);this.recordUpdateResult(t)}updateInMemory(t){const e=this.mutableDocument.value,n=KeyPath.evaluate(this.path,e,{stopAtLastContainer:!0});t(n.value,n.nextPathComponent)}recordUpdateResult(t){const e=this.mutableDocument["@ditto.updateResults"].slice();e.push(t),Object.freeze(e),this.mutableDocument["@ditto.updateResults"]=e}}class Document{static hash(t){return documentsHash(documentsFrom(t).map((t=>documentBridge.pointerFor(t))))}static hashMnemonic(t){return documentsHashMnemonic(documentsFrom(t).map((t=>documentBridge.pointerFor(t))))}get id(){let t=this["@ditto.id"];if(void 0===t){const e=documentID(documentBridge.pointerFor(this));t=new DocumentID(e,!0),this["@ditto.id"]=t}return t}get path(){return new DocumentPath(this,"",!1)}get value(){let t=this["@ditto.value"];return void 0===t&&(t=this.path.value,this["@ditto.value"]=t),t}at(t){return this.path.at(t)}constructor(){}static idCBOR(t){return documentID(documentBridge.pointerFor(t))}static canonicalizedIDCBOR(t){return validateDocumentIDCBOR(t)}static isIDCBORCanonical(t){return t===this.canonicalizedIDCBOR(t)}}class MutableDocument{get id(){let t=this["@ditto.id"];if(void 0===t){const e=documentID(mutableDocumentBridge.pointerFor(this));t=new DocumentID(e,!0),this["@ditto.id"]=t}return t}get path(){return new MutableDocumentPath(this,"",!1)}get value(){return this.path.value}at(t){return this.path.at(t)}constructor(){this["@ditto.updateResults"]=[]}static idCBOR(t){return documentID(mutableDocumentBridge.pointerFor(t))}}MutableDocument.canonicalizedIDCBOR=Document.canonicalizedIDCBOR,MutableDocument.isIDCBORCanonical=Document.isIDCBORCanonical;const documentBridge=new Bridge(Document,documentFree),mutableDocumentBridge=new Bridge(MutableDocument,documentFree);function documentsFrom(t){if(!t)return[];if(t instanceof Document)return[t];if(t instanceof Array)return t;throw new Error(`Expected null, a single document, or an array of documents but got value of type ${typeof t}: ${t}`)}class UpdateResultsMap{get(t){const e=(t instanceof DocumentID?t:new DocumentID(t)).toString();return this.updateResultsByDocumentIDString[e]}keys(){return this.documentIDs.slice()}constructor(t,e){const n=t.map((t=>t.toString())).sort().join(", ");if(n!==Object.keys(e).sort().join(", "))throw new Error("Internal inconsistency, can't construct update results map, documentIDs must all be keys in update results (by document ID string)");this.documentIDs=t.slice(),this.updateResultsByDocumentIDString={...e}}}class LiveQueryEventInitial{constructor(){this.isInitial=!0}hash(t){return documentsHash(t.map((t=>documentBridge.pointerFor(t))))}hashMnemonic(t){return documentsHashMnemonic(t.map((t=>documentBridge.pointerFor(t))))}}class LiveQueryEventUpdate{hash(t){return documentsHash(t.map((t=>documentBridge.pointerFor(t))))}hashMnemonic(t){return documentsHashMnemonic(t.map((t=>documentBridge.pointerFor(t))))}constructor(t){this.isInitial=!1,this.oldDocuments=t.oldDocuments,this.insertions=t.insertions,this.deletions=t.deletions,this.updates=t.updates,this.moves=t.moves}}class SingleDocumentLiveQueryEvent{hash(t){return documentsHash(null===t?[]:[documentBridge.pointerFor(t)])}hashMnemonic(t){return documentsHashMnemonic(null===t?[]:[documentBridge.pointerFor(t)])}constructor(t,e){this.isInitial=t,this.oldDocument=e}}class LiveQuery{get collectionName(){return this.collection.name}get isStopped(){return null===this.liveQueryID}stop(){var t;const e=this.liveQueryID;if(null!==e){this.collection.store.ditto.keepAlive.release(`LiveQuery.${e}`),this.liveQueryID=null;const n=dittoBridge.pointerFor(this.collection.store.ditto);null===(t=this.subscription)||void 0===t||t.cancel(),liveQueryStop(n,e)}}constructor(t,e,n,i,r,o,s,a,c){this.query=t,this.queryArgs=e?Object.freeze({...e}):null,this.queryArgsCBOR=n,this.orderBys=i,this.limit=r,this.offset=o,this.collection=s,this.handler=c,a&&(this.subscription=a);const l=s.name,d=new WeakRef(s.store.ditto);let u;const signalNext=async()=>{const t=d.deref();if(t){const e=dittoBridge.pointerFor(t);await liveQuerySignalAvailableNext(e,u)}},h=dittoBridge.pointerFor(s.store.ditto);if(u=liveQueryRegister(h,l,t,n,this.orderBys,r,o,(t=>{const e=t.documents.map((t=>documentBridge.bridge(t)));let n;n=t.is_initial?new LiveQueryEventInitial:new LiveQueryEventUpdate({oldDocuments:t.old_documents.map((t=>documentBridge.bridge(t))),insertions:t.insertions,deletions:t.deletions,updates:t.updates,moves:t.moves.map((t=>({from:t[0],to:t[1]})))}),c(e,n,signalNext)})),!u)throw new Error("Internal inconsistency, couldn't create a valid live query ID.");this.liveQueryID=u,step((async()=>await liveQueryStart(h,u))),s.store.ditto.keepAlive.retain(`LiveQuery.${u}`)}async signalNext(){const t=dittoBridge.pointerFor(this.collection.store.ditto);await liveQuerySignalAvailableNext(t,this.liveQueryID)}}class PendingCursorOperation{sort(t,e="ascending"){return this.orderBys.push({query:t,direction:"ascending"===e?"Ascending":"Descending"}),this}offset(t){if(t<0)throw new Error(`Can't offset by '${t}', offset must be >= 0`);if(!Number.isFinite(t))throw new Error(`Can't offset by '${t}', offset must be a finite number`);if(Number.isNaN(t))throw new Error(`Can't offset by '${t}', offset must be a valid number`);if(t!==Math.round(t))throw new Error(`Can't offset by '${t}', offset must be an integer number`);return this.currentOffset=t,this}limit(t){if(t<-1)throw new Error(`Can't limit to '${t}', limit must be >= -1 (where -1 means unlimited)`);if(!Number.isFinite(t))throw new Error(`Can't limit to '${t}', limit must be a finite number`);if(Number.isNaN(t))throw new Error(`Can't limit to '${t}', limit must be a valid number`);if(t!==Math.round(t))throw new Error(`Can't limit to '${t}', limit must be an integer number`);return this.currentLimit=t,this}subscribe(){return new Subscription(this.collection,this.query,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset)}observeLocal(t){return this._observe(t,!1,!1)}observeLocalWithNextSignal(t){return this._observe(t,!1,!0)}async remove(){const t=this.query,e=dittoBridge.pointerFor(this.collection.store.ditto);return(await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const n=await writeTransaction(e),i=await collectionRemoveQueryStr(e,this.collection.name,n,t,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);return await writeTransactionCommit(e,n),i}))).map((t=>new DocumentID(t,!0)))}async evict(){const t=this.query,e=dittoBridge.pointerFor(this.collection.store.ditto);return(await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const n=await writeTransaction(e),i=await collectionEvictQueryStr(e,this.collection.name,n,t,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);return await writeTransactionCommit(e,n),i}))).map((t=>new DocumentID(t,!0)))}async exec(){const t=this.query,e=dittoBridge.pointerFor(this.collection.store.ditto);return(await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>await collectionExecQueryStr(e,this.collection.name,null,t,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset)))).map((t=>documentBridge.bridge(t)))}async update(t){return await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const e=this.query,n=dittoBridge.pointerFor(this.collection.store.ditto),i=await writeTransaction(n),r=await collectionExecQueryStr(n,this.collection.name,i,e,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset),o=r.map((t=>mutableDocumentBridge.bridge(t,(()=>new MutableDocument))));t(o);const s=[],a={};for(const t of o){const e=t.id,n=e.toString(),i=t["@ditto.updateResults"];if(a[n])throw new Error(`Internal inconsistency, update results for document ID as string already exist: ${n}`);s.push(e),a[n]=i,mutableDocumentBridge.pointerFor(t),mutableDocumentBridge.unregister(t)}return await collectionUpdateMultiple(n,this.collection.name,i,r),await writeTransactionCommit(n,i),new UpdateResultsMap(s,a)}))}constructor(t,e,n){this.currentLimit=-1,this.currentOffset=0,this.orderBys=[],this.query=validateQuery(t),this.queryArgs=e?Object.freeze({...e}):null,this.collection=n,this.queryArgsCBOR=e?CBOR.encode(e):null}_observe(t,e,n){const i=e?this.subscribe():null;const r=n?t:function wrappedHandler(e,n,i){try{return t.call(this,e,n)}finally{i()}};return new LiveQuery(this.query,this.queryArgs,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset,this.collection,i,r)}then(t,e){return this.exec().then(t,e)}}class PendingIDSpecificOperation{subscribe(){return new Subscription(this.collection,this.query,null,[],-1,0)}observeLocal(t){return this._observe(t,!1,!1)}observeLocalWithNextSignal(t){return this._observe(t,!1,!0)}async remove(){const t=dittoBridge.pointerFor(this.collection.store.ditto);return await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const e=await writeTransaction(t),n=await collectionRemove(t,this.collection.name,e,this.documentIDCBOR);return await writeTransactionCommit(t,e),n}))}async evict(){const t=dittoBridge.pointerFor(this.collection.store.ditto);return await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const e=await writeTransaction(t),n=await collectionEvict(t,this.collection.name,e,this.documentIDCBOR);return await writeTransactionCommit(t,e),n}))}async exec(){const t=dittoBridge.pointerFor(this.collection.store.ditto);return await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const e=await readTransaction(t),n=await collectionGet(t,this.collection.name,this.documentIDCBOR,e);let i;return n&&(i=documentBridge.bridge(n)),readTransactionFree(e),i}))}async update(t){const e=dittoBridge.pointerFor(this.collection.store.ditto),n=await readTransaction(e),i=await collectionGet(e,this.collection.name,this.documentIDCBOR,n);if(readTransactionFree(n),!i)throw new Error(`Can't update, document with ID '${this.documentID.toString()}' not found in collection named '${this.collection.name}'`);const r=mutableDocumentBridge.bridge(i,(()=>new MutableDocument));t(r),mutableDocumentBridge.unregister(r);const o=await writeTransaction(e);return await collectionUpdate(e,this.collection.name,o,i),await writeTransactionCommit(e,o),r["@ditto.updateResults"].slice()}constructor(t,e){this.documentID=t,this.collection=e,this.documentIDCBOR=t.toCBOR()}_observe(t,e,n){const i=e?this.subscribe():null;return new LiveQuery(this.query,null,null,[],-1,0,this.collection,i,((e,i,r)=>{if(e.length>1){const t=e.map((t=>t.id.toBase64String()));throw new Error(`Internal inconsistency, single document live query returned more than one document. Query: ${this.query}, documentIDs: ${t.join(", ")}.`)}if(!1===i.isInitial&&i.oldDocuments.length>1)throw new Error(`Internal inconsistency, single document live query returned an update event with more than one old documents. Query ${this.query}.`);if(!1===i.isInitial&&i.insertions.length>1)throw new Error(`Internal inconsistency, single document live query returned an update event with more than one insertion, which doesn't make sense for single document observations. Query ${this.query}.`);if(!1===i.isInitial&&i.deletions.length>1)throw new Error(`Internal inconsistency, single document live query returned an update event with more than one deletion, which doesn't make sense for single document observations. Query ${this.query}.`);if(!1===i.isInitial&&i.updates.length>1)throw new Error(`Internal inconsistency, single document live query returned an update event with more than one update, which doesn't make sense for single document observations. Query ${this.query}.`);if(!1===i.isInitial&&i.moves.length>0)throw new Error(`Internal inconsistency, single document live query returned an update event with moves, which doesn't make sense for single document observations. Query ${this.query}.`);if((!0===i.isInitial?0:i.insertions.length+i.deletions.length+i.updates.length)>1)throw new Error(`Internal inconsistency, single document live query returned a combination of inserts, updates, and/or deletes, which doesn't make sense for single document observation. Query ${this.query}.`);const o=e[0]||null,s=!0===i.isInitial?void 0:i.oldDocuments[0],a=new SingleDocumentLiveQueryEvent(i.isInitial,s);if(n)t(o,a,r);else try{t(o,a)}finally{r()}}))}then(t,e){return this.exec().then(t,e)}get query(){return`_id == ${this.documentID.toQueryCompatibleString()}`}}class Collection{find(t,e){return new PendingCursorOperation(t,null!=e?e:null,this)}findAll(){return this.find("true")}findByID(t){const e=t instanceof DocumentID?t:new DocumentID(t);return new PendingIDSpecificOperation(e,this)}async upsert(t,e={}){var n;const i=null!==(n=e.writeStrategy)&&void 0!==n?n:"merge",r=this.store.ditto,o=dittoBridge.pointerFor(r),s=t._id;let a;a=void 0===s?void 0:s instanceof DocumentID?s:new DocumentID(s);const c=void 0===a?null:a.toCBOR(),l=desugarJSObject(t,!0),d=CBOR.encode(l),u=await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>await collectionInsertValue(o,this.name,d,c,i)));return new DocumentID(u,!0)}async newAttachment(t,e={}){const n=this.store.ditto,i=dittoBridge.pointerFor(n),{id:r,len:o,handle:s}=await(async()=>{if("string"==typeof t)return dittoNewAttachmentFromFile(i,t,"Copy");if(t instanceof Uint8Array)return await dittoNewAttachmentFromBytes(i,t);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}`)})(),a={_id:r,_len:o,_meta:{...e}};a[DittoCRDTTypeKey]=DittoCRDTType.attachment;const c=new AttachmentToken(a),l=new Attachment(n,c);return attachmentBridge.bridge(s,(()=>l),{throwIfAlreadyBridged:!0})}fetchAttachment(t,e){const n=this.store.ditto;return new AttachmentFetcher(n,t,e)}constructor(t,e){this.name=t,this.store=e}findByIDCBOR(t){const e=new DocumentID(t,!0,!0);return new PendingIDSpecificOperation(e,this)}}class CollectionsEvent{static initial(t){return new CollectionsEvent({isInitial:!0,collections:t,oldCollections:[],insertions:[],deletions:[],updates:[],moves:[]})}constructor(t){this.isInitial=t.isInitial,this.collections=t.collections,this.oldCollections=t.oldCollections,this.insertions=t.insertions,this.deletions=t.deletions,this.updates=t.updates,this.moves=t.moves}}class PendingCollectionsOperation{sort(t,e="ascending"){return this.pendingCursorOperation.sort(t,e),this}offset(t){return this.pendingCursorOperation.offset(t),this}limit(t){return this.pendingCursorOperation.limit(t),this}subscribe(){return this.pendingCursorOperation.subscribe()}observeLocal(t){return this._observe(t,!1,!1)}observeLocalWithNextSignal(t){return this._observe(t,!1,!0)}async exec(){return collectionsFromDocuments(await this.pendingCursorOperation.exec(),this.store)}constructor(t){this.store=t,this.pendingCursorOperation=new PendingCursorOperation("true",null,new Collection("__collections",t))}then(t,e){return this.exec().then(t,e)}_observe(t,e,n){const i=new WeakRef(this);return this.pendingCursorOperation._observe((function(e,r,o){const s=i.deref();if(null===s)return;const a=collectionsFromDocuments(e,s.store);let c;if(!0===r.isInitial)c=CollectionsEvent.initial(a);else{const t=collectionsFromDocuments(r.oldDocuments,s.store);c=new CollectionsEvent({isInitial:!1,collections:a,oldCollections:t,insertions:r.insertions,deletions:r.deletions,updates:r.updates,moves:r.moves})}n?t(c,o):t(c)}),e,n)}}function collectionsFromDocuments(t,e){const n=[];for(const i of t){const t=i.at("name").value;void 0!==t&&"string"==typeof t&&n.push(new Collection(t,e))}return n}class Store{collection(t){return new Collection(t,this)}collections(){return new PendingCollectionsOperation(this.ditto.store)}collectionNames(){return dittoGetCollectionNames(dittoBridge.pointerFor(this.ditto))}constructor(t){this.ditto=t}async registerLiveQueryWebhook(t,e,n){const i=validateQuery(e),r=await liveQueryWebhookRegister(dittoBridge.pointerFor(this.ditto),t,i,[],0,0,n);return new DocumentID(r,!0)}}function addressToString(t){return`${t.siteId}-${t.pubkey}`}class Presence{get graph(){const t=dittoPresenceV3(dittoBridge.pointerFor(this.ditto));return JSON.parse(t)}observe(t){const e=this.observerManager.addObserver(t),n=new Observer(this.observerManager,e,{stopsWhenFinalized:!0});return t(this.graph),n}constructor(t){this.ditto=t,this.observerManager=new ObserverManager("PresenceObservation",{keepAlive:t.keepAlive,register:t=>{dittoRegisterPresenceV3Callback(dittoBridge.pointerFor(this.ditto),t)},unregister:()=>{dittoClearPresenceV3Callback(dittoBridge.pointerFor(this.ditto))},process:t=>[JSON.parse(t)]})}}class PresenceManager{constructor(t){this.ditto=t,this.isRegistered=!1,this.currentRemotePeers=[],this.callbacksByPresenceToken={}}addObserver(t){this.registerIfNeeded();const e=generateEphemeralToken();return this.callbacksByPresenceToken[e]=t,this.ditto.keepAlive.retain(`PresenceObservation.${e}`),t(this.currentRemotePeers),e}removeObserver(t){this.ditto.keepAlive.release(`PresenceObservation.${t}`),delete this.callbacksByPresenceToken[t],this.unregisterIfNeeded()}hasObservers(){return Object.keys(this.callbacksByPresenceToken).length>0}registerIfNeeded(){if(!this.isRegistered){this.isRegistered=!0;const t=dittoBridge.pointerFor(this.ditto),e=dittoPresenceV1(t);this.currentRemotePeers=this.decode(e).sort(this.compareRemotePeers),dittoRegisterPresenceV1Callback(t,this.handlePresenceV1Callback.bind(this))}}unregisterIfNeeded(){if(!this.hasObservers()&&this.isRegistered){this.isRegistered=!1;dittoRegisterPresenceV1Callback(dittoBridge.pointerFor(this.ditto),null),this.currentRemotePeers=[]}}handlePresenceV1Callback(t){const e=this.decode(t).sort(this.compareRemotePeers);this.currentRemotePeers=e,this.notify()}notify(){for(const t in this.callbacksByPresenceToken){(0,this.callbacksByPresenceToken[t])(this.currentRemotePeers)}}decode(t){return JSON.parse(t).map((t=>{var e,n;return{networkID:t.network_id,deviceName:t.device_name,rssi:null!==(e=t.rssi)&&void 0!==e?e:void 0,approximateDistanceInMeters:null!==(n=t.approximate_distance_in_meters)&&void 0!==n?n:void 0,connections:t.connections}}))}finalize(t){this.removeObserver(t)}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 dittoRegisterTransportConditionChangedCallback(dittoBridge.pointerFor(this.ditto),t)}unregister(){return dittoRegisterTransportConditionChangedCallback(dittoBridge.pointerFor(this.ditto),null)}process(t,e){let n,i;switch(t){case"Bluetooth":n="BLE";break;case"Tcp":n="TCP";break;case"Awdl":n="AWDL";break;case"Mdns":n="MDNS"}switch(e){case"Unknown":i="Unknown";break;case"Ok":i="OK";break;case"GenericFailure":i="GenericFailure";break;case"AppInBackground":i="AppInBackground";break;case"MdnsFailure":i="MDNSFailure";break;case"TcpListenFailure":i="TCPListenFailure";break;case"NoBleCentralPermission":i="NoBLECentralPermission";break;case"NoBlePeripheralPermission":i="NoBLEPeripheralPermission";break;case"CannotEstablishConnection":i="CannotEstablishConnection";break;case"BleDisabled":i="BLEDisabled";break;case"NoBleHardware":i="NoBLEHardware";break;case"WifiDisabled":i="WiFiDisabled";break;case"TemporarilyUnavailable":i="TemporarilyUnavailable"}return[i,n]}}class Sync{constructor(t){this.bluetoothLETransportPointer=null,this.awdlTransportPointer=null,this.lanTransportPointer=null,this.mdnsClientTransportPointer=null,this.mdnsServerAdvertiserPointer=null;const e={identity:t.identity,transportConfig:new TransportConfig,isWebValid:!1,isX509Valid:!1,isSyncActive:!1};this.ditto=t,this.parameters=e,this.state=stateFrom(e),this.staticTCPClientsByAddress={},this.websocketClientsByURL={}}update(t){this.parameters={...t};const e=this.state,n=stateFrom(this.parameters);this.updatePeerToPeerBluetoothLE(e,n),this.updatePeerToPeerAWDL(e,n),this.updatePeerToPeerLAN(e,n),this.updateListenTCP(e,n),this.updateListenHTTP(e,n),this.updateConnectTCPServers(e,n),this.updateConnectWebsocketURLs(e,n),this.updateGlobal(e,n),this.state=n}updatePeerToPeerBluetoothLE(t,e){const n=dittoBridge.pointerFor(this.ditto),i=t.effectiveTransportConfig.peerToPeer.bluetoothLE,r=e.effectiveTransportConfig.peerToPeer.bluetoothLE,o=!i.isEnabled&&r.isEnabled,s=i.isEnabled&&!r.isEnabled;if(o&&this.bluetoothLETransportPointer)throw new Error("Internal inconsistency, when starting BLE transport, no BLE transport pointer should exist.");if(s&&!this.bluetoothLETransportPointer)throw new Error("Internal inconsistency, when stopping BLE transport, a BLE transport pointer should exist.");if("linux"!==process.platform&&"win32"!==process.platform){if(o){if(!bleIsAvailable(n))throw new Error("Can't start P2P BluetoothLE transport because not available.");this.bluetoothLETransportPointer=bleCreate(n)}s&&(bleDestroy(this.bluetoothLETransportPointer),delete this.bluetoothLETransportPointer)}else{if(o){const t={clientTransport:dittoAddInternalBLEClientTransport(n),serverTransport:dittoAddInternalBLEServerTransport(n)};this.bluetoothLETransportPointer=t}if(s){const t=this.bluetoothLETransportPointer,{clientTransport:e,serverTransport:n}=t;bleServerFreeHandle(n),bleClientFreeHandle(e),this.bluetoothLETransportPointer=null}}}updatePeerToPeerAWDL(t,e){const n=dittoBridge.pointerFor(this.ditto),i=t.effectiveTransportConfig.peerToPeer.awdl,r=e.effectiveTransportConfig.peerToPeer.awdl,o=!i.isEnabled&&r.isEnabled,s=i.isEnabled&&!r.isEnabled;if(o&&this.awdlTransportPointer)throw new Error("Internal inconsistency, when starting AWDL transport, no AWDL transport pointer should exist.");if(s&&!this.awdlTransportPointer)throw new Error("Internal inconsistency, when stopping AWDL transport, an AWDL transport pointer should exist.");if(o){if(!awdlIsAvailable(n))throw new Error("Can't start P2P AWDL transport because not available.");this.awdlTransportPointer=awdlCreate(n)}s&&(awdlDestroy(this.awdlTransportPointer),this.awdlTransportPointer=null)}updatePeerToPeerLAN(t,e){const n=dittoBridge.pointerFor(this.ditto),i=t.effectiveTransportConfig.peerToPeer.lan,r=e.effectiveTransportConfig.peerToPeer.lan;if("win32"===process.platform)return i.isEnabled&&(i.isMdnsEnabled&&(mdnsClientFreeHandle(this.mdnsClientTransportPointer),this.mdnsClientTransportPointer=null,mdnsServerFreeHandle(this.mdnsServerAdvertiserPointer),this.mdnsServerAdvertiserPointer=null),i.isMulticastEnabled&&dittoRemoveMulticastTransport(n)),void(r.isEnabled&&(r.isMdnsEnabled&&(this.mdnsClientTransportPointer=dittoAddInternalMdnsTransport(n),this.mdnsServerAdvertiserPointer=dittoAddInternalMdnsAdvertiser(n)),r.isMulticastEnabled&&dittoAddMulticastTransport(n)));if(i.isEnabled&&(i.isMdnsEnabled&&(lanDestroy(this.lanTransportPointer),delete this.lanTransportPointer),i.isMulticastEnabled&&dittoRemoveMulticastTransport(n)),r.isEnabled){if(r.isMdnsEnabled){if(!lanIsAvailable(n))throw new Error("Can't start P2P LAN transport because not available.");this.lanTransportPointer=lanCreate(n)}r.isMulticastEnabled&&dittoAddMulticastTransport(n)}}updateListenTCP(t,e){const n=t.effectiveTransportConfig.listen.tcp,i=e.effectiveTransportConfig.listen.tcp;if(TransportConfig.areListenTCPsEqual(i,n))return;const r=dittoBridge.pointerFor(this.ditto);n.isEnabled&&dittoStopTCPServer(r),i.isEnabled&&dittoStartTCPServer(r,`${i.interfaceIP}:${i.port}`)}updateListenHTTP(t,e){const n=t.effectiveTransportConfig.listen.http,i=e.effectiveTransportConfig.listen.http;if(TransportConfig.areListenHTTPsEqual(n,i))return;const r=dittoBridge.pointerFor(this.ditto);n.isEnabled&&dittoStopHTTPServer(r),i.isEnabled&&dittoStartHTTPServer(r,`${i.interfaceIP}:${i.port}`,i.staticContentPath||null,i.websocketSync?"Enabled":"Disabled",i.tlsCertificatePath||null,i.tlsKeyPath||null)}updateConnectTCPServers(t,e){const n=Object.getOwnPropertyNames(this.staticTCPClientsByAddress),i=e.effectiveTransportConfig.connect.tcpServers,r=new Set(i);for(const t of n)r.delete(t);const o=new Set(n);for(const t of i)o.delete(t);const s=r.values(),a=o.values();for(const t of s){const e=addStaticTCPClient(dittoBridge.pointerFor(this.ditto),t),n=staticTCPClientBridge.bridge(e);this.staticTCPClientsByAddress[t]=n}for(const t of a){const e=this.staticTCPClientsByAddress[t];if(!e)throw new Error(`Internal inconsistency, can't disconnect from TCP address '${t}', no staticTCPClient found.`);const n=staticTCPClientBridge.pointerFor(e);staticTCPClientBridge.unregister(e),staticTCPClientFreeHandle(n),delete this.staticTCPClientsByAddress[t]}}updateConnectWebsocketURLs(t,e){const n=Object.getOwnPropertyNames(this.websocketClientsByURL),i=e.effectiveTransportConfig.connect.websocketURLs.slice(),r=new Set(i);for(const t of n)r.delete(t);const o=new Set(n);for(const t of i)o.delete(t);const s=r.values(),a=o.values(),c=e.effectiveTransportConfig.global.routingHint;for(const t of s){const e=addWebsocketClient(dittoBridge.pointerFor(this.ditto),t,c),n=websocketClientBridge.bridge(e);this.websocketClientsByURL[t]=n}for(const t of a){const e=this.websocketClientsByURL[t];if(!e)throw new Error(`Internal inconsistency, can't disconnect from websocket URL '${t}', no websocketClient found.`);const n=websocketClientBridge.pointerFor(e);websocketClientBridge.unregister(e),websocketClientFreeHandle(n),delete this.websocketClientsByURL[t]}}updateGlobal(t,e){t.effectiveTransportConfig.global.syncGroup!==e.effectiveTransportConfig.global.syncGroup&&dittoSetSyncGroup(dittoBridge.pointerFor(this.ditto),e.effectiveTransportConfig.global.syncGroup)}}function stateFrom(t){var e;const n=t.transportConfig.copy(),i=t.identity,r=t.isSyncActive,o=t.isX509Valid,s=t.isWebValid;let a,c;n.connect.tcpServers,n.connect.websocketURLs;let l=!1;if("onlinePlayground"!==i.type&&"onlineWithAuthentication"!==i.type||(a=i.appID,c=null!==(e=i.customDittoCloudURL)&&void 0!==e?e:null,l=!i.hasOwnProperty("enableDittoCloudSync")||i.enableDittoCloudSync),r&&o||(n.peerToPeer.bluetoothLE.isEnabled=!1,n.peerToPeer.awdl.isEnabled=!1,n.peerToPeer.lan.isEnabled=!1,n.listen.tcp.isEnabled=!1,n.connect.tcpServers=[]),r&&s||(n.connect.websocketURLs=[]),r||(n.listen.http.isEnabled=!1),r&&s&&l){const t=null!=c?c:defaultDittoCloudURL(a);n.connect.websocketURLs.push(t)}return n.peerToPeer.lan.isEnabled&&!n.listen.tcp.isEnabled&&(n.listen.tcp.isEnabled=!0,n.listen.tcp.interfaceIP="0.0.0.0",n.listen.tcp.port=0),{underlyingSyncParameters:t,effectiveTransportConfig:n.freeze()}}class Ditto{get sdkVersion(){return dittoGetSDKVersion(dittoBridge.pointerFor(this))}constructor(t,e){this.isWebValid=!1,this.isX509Valid=!1;const n=null!=t?t:{type:"offlinePlayground",appID:""},i=e&&e.trim().length>0?e:"ditto",r=Object.freeze(this.validateIdentity(n));this.identity=Object.freeze(r),this.path=i;require("fs").mkdirSync(i,{recursive:!0});{const t=require("os");this.deviceName=t.hostname()}this.keepAlive=new KeepAlive;const o=uninitializedDittoMake(i);let s=null;const a=new WeakRef(this),c=(()=>{var t,e,n;if("offlinePlayground"===r.type)return dittoAuthClientMakeForDevelopment(i,r.appID,null!==(t=r.siteID)&&void 0!==t?t:0);if("manual"===r.type)return dittoAuthClientMakeWithStaticX509(r.certificate);if("sharedKey"===r.type)return dittoAuthClientMakeWithSharedKey(i,r.appID,r.sharedKey,r.siteID);if("onlinePlayground"===r.type){const t=null!==(e=r.customAuthURL)&&void 0!==e?e:defaultAuthURL(r.appID);return dittoAuthClientMakeAnonymousClient(i,r.appID,r.token,t)}if("onlineWithAuthentication"===r.type){const t=null!==(n=r.customAuthURL)&&void 0!==n?n:defaultAuthURL(r.appID),e=dittoAuthClientMakeLoginProvider((function(t){const e=a.deref();e?e.auth?e.auth["@ditto.authenticationExpiring"](t):s=t:Logger.warning("Internal inconsistency, LoginProvider callback fired after the corresponding Ditto instance has been deallocated.")}));return dittoAuthClientMakeWithWeb(i,r.appID,t,e)}throw new Error(`Can't create Ditto, unsupported identity type: ${r}`)})();dittoAuthClientSetValidityListener(c,(function(...t){var e;null===(e=a.deref())||void 0===e||e.authClientValidityChanged(...t)}));const l=dittoAuthClientIsWebValid(c),d=dittoAuthClientIsX509Valid(c),u=dittoAuthClientGetSiteID(c),h=dittoMake(o,c);dittoBridge.bridge(h,this),"onlineWithAuthentication"===r.type?this.auth=new OnlineAuthenticator(this.keepAlive,c,this,r.authHandler):"onlinePlayground"===r.type?this.auth=new OnlineAuthenticator(this.keepAlive,c,this,{authenticationRequired:function(t){},authenticationExpiringSoon:function(t,e){}}):(dittoAuthClientFree(c),this.auth=new NotAvailableAuthenticator(this.keepAlive));const p=this.makeDefaultTransportConfig();this.siteID=u,this.transportConfig=p.copy().freeze(),this.isX509Valid=d,this.isWebValid=l,this.sync=new Sync(this),this.sync.update({isSyncActive:!1,isX509Valid:d,isWebValid:l,identity:r,transportConfig:p}),this.isActivated=!IdentityTypesRequiringOfflineLicenseToken.includes(r.type),this.store=new Store(this),this.presence=new Presence(this),this.presenceManager=new PresenceManager(this),this.transportConditionsManager=new TransportConditionsManager(this),null!==s&&this.auth["@ditto.authenticationExpiring"](s)}setOfflineOnlyLicenseToken(t){if(!IdentityTypesRequiringOfflineLicenseToken.includes(this.identity.type))throw new Error("Offline license tokens should only be used for manual, sharedKey or offlinePlayground identities");{const{result:e,errorMessage:n}=verifyLicense(t);if("LicenseOk"!==e)throw this.isActivated=!1,new Error(n);this.isActivated=!0}}setTransportConfig(t){this.transportConfig,this.transportConfig=t.copy().freeze();const e=this.transportConfig,n=this.identity,i=this.isWebValid,r=this.isX509Valid;this.sync.update({transportConfig:e,identity:n,isWebValid:i,isX509Valid:r,isSyncActive:this.isSyncActive})}updateTransportConfig(t){const e=this.transportConfig.copy();return t(e),this.setTransportConfig(e),this}startSync(){this.setSyncActive(!0)}stopSync(){this.setSyncActive(!1)}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})}runGarbageCollection(){dittoRunGarbageCollection(dittoBridge.pointerFor(this))}disableSyncWithV2(){dittoDisableSyncWithV2(dittoBridge.pointerFor(this))}authClientValidityChanged(t,e){const n=this.transportConfig,i=this.identity,r=this.isSyncActive;this.isX509Valid,this.isWebValid,this.isX509Valid=e,this.isWebValid=t,this.auth["@ditto.authClientValidityChanged"](t,e),this.sync.update({transportConfig:n,identity:i,isWebValid:t,isX509Valid:e,isSyncActive:r})}validateIdentity(t){const e={...t};t.appName;const n=t.appID;if(!["offlinePlayground","sharedKey","manual","onlinePlayground","onlineWithAuthentication"].includes(t.type))throw new Error(`Can't create Ditto instance, unknown identity type: ${t.type}`);if(("offlinePlayground"===t.type||"sharedKey"===t.type||"onlinePlayground"===t.type||"onlineWithAuthentication"===t.type)&&void 0===n)throw new Error("Property .appID must be given for identity, but isn't.");if(void 0!==n&&"string"!=typeof n)throw new Error(`Property .appID must be be of type string, but is of type '${typeof n}': ${n}`);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("Can't create Ditto instance, siteID must be a number or BigInt");if(e<0)throw new Error("Can't create Ditto instance, siteID must be >= 0");if(e>BigInt("0xffffffffffffffff"))throw new Error("Can't create Ditto instance, siteID must be < 2^64")}if(t.type,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}`)}return t.type,e}setSyncActive(t){if(t&&IdentityTypesRequiringOfflineLicenseToken.includes(this.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&&t&&this.keepAlive.retain("sync"),this.isSyncActive&&!t&&this.keepAlive.release("sync");const e=dittoBridge.pointerFor(this);this.isSyncActive=t;const n=this.isWebValid,i=this.isX509Valid,r=this.identity,o=this.transportConfig;dittoSetDeviceName(e,this.deviceName),this.sync.update({identity:r,transportConfig:o,isWebValid:n,isX509Valid:i,isSyncActive:!!t})}makeDefaultTransportConfig(){const t=dittoBridge.pointerFor(this),e=new TransportConfig;return bleIsAvailable(t)&&(e.peerToPeer.bluetoothLE.isEnabled=!0),awdlIsAvailable(t)&&(e.peerToPeer.awdl.isEnabled=!0),lanIsAvailable(t)&&(e.peerToPeer.lan.isEnabled=!0),"linux"===process.platform&&(e.peerToPeer.bluetoothLE.isEnabled=!1),e.freeze()}}const dittoBridge=new Bridge(Ditto,(t=>{dittoClearPresenceCallback(t),dittoFree(t)}));class Value{constructor(t,e={}){this.value=t,this.isDefault=!!e.isDefault}}exports.Attachment=Attachment,exports.AttachmentFetcher=AttachmentFetcher,exports.AttachmentToken=AttachmentToken,exports.Authenticator=Authenticator,exports.CBOR=CBOR,exports.Collection=Collection,exports.CollectionsEvent=CollectionsEvent,exports.Counter=Counter,exports.Ditto=Ditto,exports.Document=Document,exports.DocumentID=DocumentID,exports.DocumentPath=DocumentPath,exports.IdentityTypesRequiringOfflineLicenseToken=IdentityTypesRequiringOfflineLicenseToken,exports.KeepAlive=KeepAlive,exports.LiveQuery=LiveQuery,exports.LiveQueryEventInitial=LiveQueryEventInitial,exports.LiveQueryEventUpdate=LiveQueryEventUpdate,exports.Logger=Logger,exports.MutableCounter=MutableCounter,exports.MutableDocument=MutableDocument,exports.MutableDocumentPath=MutableDocumentPath,exports.MutableRegister=MutableRegister,exports.NotAvailableAuthenticator=NotAvailableAuthenticator,exports.Observer=Observer,exports.OnlineAuthenticator=OnlineAuthenticator,exports.PendingCollectionsOperation=PendingCollectionsOperation,exports.PendingCursorOperation=PendingCursorOperation,exports.PendingIDSpecificOperation=PendingIDSpecificOperation,exports.Presence=Presence,exports.RGA=RGA,exports.Register=Register,exports.SingleDocumentLiveQueryEvent=SingleDocumentLiveQueryEvent,exports.Store=Store,exports.Subscription=Subscription,exports.TransportConfig=TransportConfig,exports.UpdateResult=UpdateResult,exports.UpdateResultsMap=UpdateResultsMap,exports.Value=Value,exports.addressToString=addressToString,exports.attachmentBridge=attachmentBridge,exports.dittoBridge=dittoBridge,exports.documentBridge=documentBridge,exports.init=init,exports.mutableDocumentBridge=mutableDocumentBridge,exports.validateDocumentIDCBOR=validateDocumentIDCBOR,exports.validateDocumentIDValue=validateDocumentIDValue;
|
|
2
2
|
//# sourceMappingURL=ditto.cjs.js.map
|
|
Binary file
|