@dittolive/ditto 2.1.0 → 3.0.0-alpha1
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.darwin-arm64.node +0 -0
- package/node/ditto.darwin-x64.node +0 -0
- package/node/ditto.linux-arm.node +0 -0
- package/node/ditto.linux-x64.node +0 -0
- package/node/transports.darwin-arm64.node +0 -0
- package/node/transports.darwin-x64.node +0 -0
- package/package.json +1 -1
- package/types/ditto.d.ts +216 -303
- package/web/ditto.es6.js +1 -1
- package/web/ditto.umd.js +1 -1
- package/web/ditto.wasm +0 -0
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: **
|
|
6
|
+
Version: **3.0.0-alpha1**
|
|
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/
|
|
9
|
+
[API Reference](https://software.ditto.live/js/Ditto/3.0.0-alpha1/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=[],debugAllTypes=!1;class Meta{constructor(t,e,i){this.type=t,this.object=e,this.pointer=i}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,i={}){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 i=e.object.deref();if(!i)throw new Error(`Internal inconsistency, found a meta entry for an object whose object is undefined (garbage collected): ${t}`);return i}bridge(t,e,i={}){const n=i.throwIfAlreadyBridged,r=this.objectFor(t);if(r&&n)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 i=t.constructor,n=this.type;if(i!==n)throw new Error(`Can't register, bridge is configured for type ${n.name} but passed in object is of type ${i.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(i,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,i=this.type;if(e!==i)throw new Error(`Can't unregister, bridge is configured for type ${i.name} but passed in object is of type ${e.name}`);const n=this.pointerFor(t);if(!n)throw new Error(`Can't unregister, object that has not been registered before: ${t}`);const r=this.metaByAddrMap[n.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!==i)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[n.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 i;const n=null!==(i=e.errorMessagePrefix)&&void 0!==i?i:"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(`${n} '${t}' is not a number.`);if(r&&Math.floor(t)!==t)throw new Error(`${n} '${t}' is not an integer.`);if(void 0!==o&&t<o)throw new Error(`${n} '${t}' must be >= ${o}.`);if(void 0!==s&&t>s)throw new Error(`${n} '${t}' must be <= ${s}.`);if(void 0!==a&&t<=a)throw new Error(`${n} '${t}' must be > ${a}.`);if(void 0!==c&&t>=c)throw new Error(`${n} '${t}' must be < ${c}.`);return t}function validateQuery(t,e={}){var i;const n=null!==(i=e.errorMessagePrefix)&&void 0!==i?i:"Query validation failed,";if("string"!=typeof t)throw new Error(`${n} query is not a string: ${t}`);if(""===t)throw new Error(`${n} query is an empty string.`);const r=t.trim();if(""===r)throw new Error(`${n} 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,i)=>{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")}catch(e){throw new Error("Couldn't load native module 'ditto."+t+".node' due to error.",e)}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_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_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_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_insert_cbor(...t){return ditto.ditto_document_insert_cbor(...t)}function ditto_document_pop_cbor(...t){return ditto.ditto_document_pop_cbor(...t)}function ditto_document_push_cbor(...t){return ditto.ditto_document_push_cbor(...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_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_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 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 documentSetCBORWithTimestamp(t,e,i,n,r){ensureInitialized();const o=ditto_document_set_cbor_with_timestamp(t,bytesFromString(e),i,n,r);if(0!==o)throw new Error(errorMessage()||`ditto_document_set_cbor_with_timestamp() failed with error code: ${o}`)}function documentSetCBOR(t,e,i,n){ensureInitialized();const r=ditto_document_set_cbor(t,bytesFromString(e),i,n);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,i){ensureInitialized();const n=ditto_document_get_cbor_with_path_type(t,bytesFromString(e),i);return{statusCode:n.status_code,cbor:boxCBytesIntoBuffer(n.cbor)}}function documentRemove(t,e){ensureInitialized();const i=ditto_document_remove(t,bytesFromString(e));if(0!==i)throw new Error(errorMessage()||`ditto_document_remove() failed with error code: ${i}`)}function documentIncrementCounter(t,e,i){ensureInitialized();const n=ditto_document_increment_counter(t,bytesFromString(e),i);if(0!==n)throw new Error(errorMessage()||`ditto_document_increment_counter() failed with error code: ${n}`)}function documentPushCBOR(t,e,i){ensureInitialized();const n=ditto_document_push_cbor(t,bytesFromString(e),i);if(0!==n)throw new Error(errorMessage()||`ditto_document_push_cbor() failed with error code: ${n}`)}function documentPopCBOR(t,e){ensureInitialized();const i=bytesFromString(e);return boxCBytesIntoBuffer(withOutBoxCBytes((e=>{const n=ditto_document_pop_cbor(t,i,e);if(0!==n)throw new Error(errorMessage()||`ditto_document_pop_cbor() failed with error code: ${n}`);return e})))}function documentInsertCBOR(t,e,i){ensureInitialized();const n=ditto_document_insert_cbor(t,bytesFromString(e),i);if(0!==n)throw new Error(errorMessage()||`ditto_document_insert_cbor() failed with error code: ${n}`)}function documentFree(t){ensureInitialized(),ditto_document_free(t)}function documentIDQueryCompatible(t,e){ensureInitialized();return boxCStringIntoString(ditto_document_id_query_compatible(t,e))}function validateDocumentID(t){ensureInitialized();return boxCBytesIntoBuffer(withOutBoxCBytes((e=>{const i=ditto_validate_document_id(t,e);if(0!==i)throw new Error(errorMessage()||`ditto_validate_document_id() failed with error code: ${i}`);return e})))}async function collectionGet(t,e,i,n){ensureInitialized();const r=bytesFromString(e),{status_code:o,document:s}=await ditto_collection_get(t,r,i,n);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,i,n,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,i,n,s,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,i,n){ensureInitialized();const r=bytesFromString(e),{status_code:o,bool_value:s}=await ditto_collection_remove(t,r,i,n);if(0!==o)throw new Error(errorMessage()||`ditto_collection_remove() failed with error code: ${o}`);return s}async function collectionEvict(t,e,i,n){ensureInitialized();const r=bytesFromString(e),{status_code:o,bool_value:s}=await ditto_collection_evict(t,r,i,n);if(0!==o)throw new Error(errorMessage()||`ditto_collection_evict() failed with error code: ${o}`);return s}async function collectionUpdate(t,e,i,n){ensureInitialized();const r=bytesFromString(e),o=await ditto_collection_update(t,r,i,n);if(0!==o)throw new Error(errorMessage()||`ditto_collection_update() failed with error code: ${o}`)}async function collectionUpdateMultiple(t,e,i,n){ensureInitialized();const r=bytesFromString(e),o=jsDocsToCDocs(n),s=await ditto_collection_update_multiple(t,r,i,o);if(0!==s)throw new Error(errorMessage()||`ditto_collection_update_multiple() failed with error code: ${s}`)}async function collectionExecQueryStr(t,e,i,n,r,o,s,a){ensureInitialized();const c=bytesFromString(e),u=bytesFromString(n);return await ditto_collection_exec_query_str(t,c,i,u,r,o,s,a)}async function collectionRemoveQueryStr(t,e,i,n,r,o,s,a){ensureInitialized();const c=bytesFromString(e),u=bytesFromString(n);return await ditto_collection_remove_query_str(t,c,i,u,r,o,s,a)}async function collectionEvictQueryStr(t,e,i,n,r,o,s,a){ensureInitialized();const c=bytesFromString(e),u=bytesFromString(n);return await ditto_collection_evict_query_str(t,c,i,u,r,o,s,a)}function addSubscription(t,e,i,n,r,o,s){ensureInitialized();return ditto_add_subscription(t,bytesFromString(e),bytesFromString(i),n,r,o,s)}function removeSubscription(t,e,i,n,r,o,s){ensureInitialized();return ditto_remove_subscription(t,bytesFromString(e),bytesFromString(i),n,r,o,s)}function liveQueryRegister(t,e,i,n,r,o,s,a,c){ensureInitialized();const u=bytesFromString(e),l=bytesFromString(i),{status_code:d,i64:h}=ditto_live_query_register_str_detached(t,u,l,n,r,o,s,wrapBackgroundCbForFFI(c,a));if(0!==d)throw new Error(errorMessage()||`\`ditto_live_query_register_str()\` failed with error code: ${d}`);return h}async function liveQueryStart(t,e){ensureInitialized();const i=await ditto_live_query_start(t,e);if(0!==i)throw new Error(errorMessage()||`\`ditto_live_query_start()\` failed with error code: ${i}`)}function liveQueryStop(t,e){ensureInitialized(),ditto_live_query_stop(t,e)}async function liveQuerySignalAvailableNext(t,e){ensureInitialized(),await ditto_live_query_signal_available_next(t,e)}async function liveQueryWebhookRegister(t,e,i,n,r,o,s){ensureInitialized();const a=bytesFromString(e),c=bytesFromString(i),u=bytesFromString(s),{status_code:l,id:d}=await ditto_live_query_webhook_register_str(t,a,c,n,r,o,u);if(0!==l)throw new Error(errorMessage()||`\`ditto_live_query_webhook_register_str()\` failed with error code: ${l}`);return boxCBytesIntoBuffer(d)}async function readTransaction(t){ensureInitialized();const{status_code:e,txn:i}=await ditto_read_transaction(t);if(0!==e)throw new Error(errorMessage()||`\`ditto_read_transaction()\` failed with error code: ${e}`);return i}function readTransactionFree(t){return ensureInitialized(),ditto_read_transaction_free(t)}async function writeTransaction(t){ensureInitialized();const{status_code:e,txn:i}=await ditto_write_transaction(t);if(0!==e)throw new Error(errorMessage()||`ditto_write_transaction() failed with error code: ${e}`);return i}async function writeTransactionCommit(t,e){ensureInitialized();const i=await ditto_write_transaction_commit(t,e);if(0!==i)throw new Error(errorMessage()||`ditto_write_transaction_commit() failed with error code: ${i}`)}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){ensureInitialized();return ditto_add_websocket_client(t,bytesFromString(e))}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,i)=>{try{const n=boxCStringIntoString(i);t(e,n)}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,i,n){ensureInitialized();const r=bytesFromString(t),o=bytesFromString(e),s=bytesFromString(i),a=bytesFromString(n),{status_code:c,auth_client:u}=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 u}function dittoAuthClientMakeWithWeb(t,e,i,n){ensureInitialized();const r=bytesFromString(t),o=bytesFromString(e),s=bytesFromString(i),{status_code:a,auth_client:c}=ditto_auth_client_make_with_web(r,o,s,n);if(0!==a)throw new Error(errorMessage()||`ditto_auth_client_make_with_web() failed with error code: ${a}`);return c}function dittoAuthClientMakeForDevelopment(t,e,i){ensureInitialized();const n=bytesFromString(t),r=bytesFromString(e),o=Number(i),{status_code:s,auth_client:a}=ditto_auth_client_make_for_development(n,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,i,n){ensureInitialized();const r=bytesFromString(t),o=bytesFromString(e),s=bytesFromString(i),a=Number(n),{status_code:c,auth_client:u}=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 u}function dittoAuthClientMakeWithStaticX509(t){ensureInitialized();const e=bytesFromString(t),{status_code:i,auth_client:n}=ditto_auth_client_make_with_static_x509(e);if(0!==i)throw new Error(errorMessage()||`ditto_auth_client_make_with_static_x509() failed with error code: ${i}`);return n}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,i){ensureInitialized();const n=bytesFromString(e),r=bytesFromString(i),o=await ditto_auth_client_login_with_token(t,n,r);if(0!==o)throw new Error(errorMessage()||`Ditto failed to authenticate (error code: ${o}).`)}async function dittoAuthClientLoginWithUsernameAndPassword(t,e,i,n){ensureInitialized();const r=bytesFromString(e),o=bytesFromString(i),s=bytesFromString(n),a=await ditto_auth_client_login_with_credentials(t,r,o,s);if(0!==a)throw new Error(errorMessage()||`Ditto failed to authenticate (error code: ${a}).`)}async function dittoAuthClientLogout(t){ensureInitialized();const e=await ditto_auth_client_logout(t);if(0!==e)throw new Error(errorMessage()||`Ditto failed to logout (error code: ${e}).`)}function 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),i=e.status_code,n=e.names;if(0!==i)throw new Error(errorMessage()||`ditto_get_collection_names() failed with error code: ${i}`);return cStringVecToStringArray(n)}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 i=refCStringToString(t);e(i)}))):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,i){ensureInitialized();const n={},r=ditto_new_attachment_from_file(t,bytesFromString(e),i,n);if(0!==r)throw new Error(errorMessage()||`ditto_new_attachment_from_file() failed with error code: ${r}`);return n}async function dittoNewAttachmentFromBytes(t,e){ensureInitialized();const i={},n=await ditto_new_attachment_from_bytes(t,e,i);if(0!==n)throw new Error(errorMessage()||`ditto_new_attachment_from_bytes() failed with error code: ${n}`);return i}async function dittoResolveAttachment(t,e,i,n){ensureInitialized();const{onComplete:r,onProgress:o,onDelete:s}=i,{status_code:a,cancel_token:c}=await ditto_resolve_attachment(t,e,wrapBackgroundCbForFFI(n,r),wrapBackgroundCbForFFI(n,o),wrapBackgroundCbForFFI(n,s));if(0!==a)throw new Error(errorMessage()||`ditto_resolve_attachment() failed with error code: ${a}`);return c}function dittoCancelResolveAttachment(t,e,i){ensureInitialized();const n=ditto_cancel_resolve_attachment(t,e,i);if(0!==n)throw new Error(errorMessage()||`ditto_cancel_resolve_attachment() failed with error code: ${n}`)}function freeAttachmentHandle(t){ensureInitialized(),ditto_free_attachment_handle(t)}function dittoGetCompleteAttachmentPath(t,e){ensureInitialized();return refCStringToString(ditto_get_complete_attachment_path(t,e))}function dittoGetSDKVersion(t){ensureInitialized();return boxCStringIntoString(ditto_get_sdk_version(t))}function dittoPresenceV1(t){ensureInitialized();return boxCStringIntoString(ditto_presence_v1(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,i,n,r,o){ensureInitialized();return ditto_start_http_server(t,bytesFromString(e),bytesFromString(i),n,bytesFromString(r),bytesFromString(o))}function dittoStopHTTPServer(t){return ensureInitialized(),ditto_stop_http_server(t)}function dittoRunGarbageCollection(t){return ensureInitialized(),ditto_run_garbage_collection(t)}function documentsHash(t){ensureInitialized();const{status_code:e,u64:i}=ditto_documents_hash(t);if(0!==e)throw new Error(errorMessage()||`\`ditto_documents_hash()\` failed with error code: ${e}`);return BigInt(i)}function documentsHashMnemonic(t){ensureInitialized();const{status_code:e,c_string:i}=ditto_documents_hash_mnemonic(t);if(0!==e)throw new Error(errorMessage()||`\`ditto_documents_hash_mnemonic()\` failed with error code: ${e}`);return boxCStringIntoString(i)}function dittoAuthClientMakeLoginProvider(t,e){return ensureInitialized(),ditto_auth_client_make_login_provider(wrapBackgroundCbForFFI(e,t))}function dittoAuthClientSetValidityListener(t,e,i){ensureInitialized();return ditto_auth_client_set_validity_listener(t,wrapBackgroundCbForFFI(i,(function(t,i){return e(1===t,1===i)})))}!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,i){ensureInitialized(),bytesFromString(t),bytesFromString(e);const n=ditto_init_sdk_version(t,e,bytesFromString(i));if(void 0!==n&&0!==n)throw new Error(errorMessage()||`ditto_init_sdk_version() failed with error code: ${n}`)}function verifyLicense(t){ensureInitialized();const e=bytesFromString(t);let i;const n=boxCStringIntoString(withOutPtr("char *",(t=>(i=verify_license(e,t),t))));return{result:i,errorMessage:n}}isInitialized=!0,withOutPtr=wrapFFIOutFunction(withOutPtr$1);const NOT_FOUND_ERROR_CODE=-30798;function wrapBackgroundCbForFFI(t,e){return void 0===t&&(t=console.error),(i,...n)=>{let r;try{r=e(...n)}catch(e){try{t(e)}catch(t){console.error(`Internal error: \`onError()\` handler oughtn't throw, but it did throw ${t}`)}}return i(r)}}function wrapFFIOutFunction(t){return function(...e){let i,n,r=!1;const o=e[e.length-1],s=e.splice(0,e.length-1),a=t(...s,(t=>{try{n=o(t),r=n===t}catch(t){i=t}}));if(i)throw i;return r?a:n}}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||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 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="2.1.0";async function init(t={}){}switch(process.platform){case"android":initSDKVersion("Android","JavaScript","2.1.0");break;case"darwin":initSDKVersion("Mac","JavaScript","2.1.0");break;case"linux":initSDKVersion("Linux","JavaScript","2.1.0");break;case"win32":initSDKVersion("Windows","JavaScript","2.1.0");break;default:initSDKVersion("Unknown","JavaScript","2.1.0")}loggerInit();class KeepAlive{constructor(){this.countsByID={},this.intervalID=null}get isActive(){return null!==this.intervalID}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{constructor(){throw new Error("Logger can't be instantiated, use it's static properties & methods directly instead.")}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)}}class ObserverManager{constructor(t,e=null){this.id=t,this.keepAlive=e,this.isRegistered=!1,this.callbacksByToken={}}addObserver(t){var e;this.registerIfNeeded();const i=generateEphemeralToken();return this.callbacksByToken[i]=t,null===(e=this.keepAlive)||void 0===e||e.retain(`${this.id}.${i}`),i}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.processCallback(...t);for(const t in this.callbacksByToken){(0,this.callbacksByToken[t])(...e)}}register(t){}unregister(){}processCallback(...t){return t}hasObservers(){return Object.keys(this.callbacksByToken).length>0}registerIfNeeded(){if(!this.isRegistered){const t=new WeakRef(this);this.isRegistered=!0,this.register((function(...e){const i=t.deref();i&&i.notify(...e)}))}}unregisterIfNeeded(){!this.hasObservers()&&this.isRegistered&&(this.isRegistered=!1,this.unregister())}async finalize(t){await this.removeObserver(t)}}class Observer{constructor(t,e,i={}){this.observerManager=t,this.token=e,this.options=i,i.stopsWhenFinalized&&Observer.finalizationRegistry.register(this,{observerManager:t,token:e},this)}get isStopped(){return void 0===this.token}stop(){const t=this.token;t&&(delete this.token,Observer.finalizationRegistry.unregister(this),this.observerManager.removeObserver(t))}static finalize(t){const{observerManager:e,token:i}=t;e.removeObserver(i)}}Observer.finalizationRegistry=new FinalizationRegistry(Observer.finalize);class Authenticator{constructor(t){this.keepAlive=t,this.status={isAuthenticated:!1,userID:null},this.loginSupported=!1,this.observerManager=new ObserverManager("AuthenticationStatusObservation",t)}loginWithToken(t,e){throw new Error("Authenticator.loginWithToken() is abstract and must be implemented by subclasses.")}loginWithUsernameAndPassword(t,e,i){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})}"@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{constructor(t,e,i,n){super(t),this.loginSupported=!0,this.status={isAuthenticated:!1,userID:null},this.authClientPointer=e,this.ditto=new WeakRef(i),this.authenticationHandler=n,this.updateAndNotify(!1),OnlineAuthenticator.finalizationRegistry.register(this,e)}async loginWithToken(t,e){await dittoAuthClientLoginWithToken(this.authClientPointer,t,e)}async loginWithUsernameAndPassword(t,e,i){await dittoAuthClientLoginWithUsernameAndPassword(this.authClientPointer,t,e,i)}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.")}"@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 i=this.status.isAuthenticated,n=this.status.userID,r=dittoAuthClientIsWebValid(this.authClientPointer),o=dittoAuthClientUserID(this.authClientPointer),s={isAuthenticated:r,userID:o};if(this.status=s,t){!!i==!!r&&n===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,i){throw new Error("Can't login, authentication is not supported for the identity in use, please use an onlineWithAuthentication identity.")}logout(t){throw new Error("Can't logout, authentication is not supported for the identity in use, please use an onlineWithAuthentication identity.")}"@ditto.authenticationExpiring"(t){throw new Error(`Internal inconsistency, authentication is not available, yet the @ditto.authenticationExpiring() was called on authenticator: ${this}`)}"@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"];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:"[::]",port:4040},http:{isEnabled:!1,interfaceIP:"[::]",port:80,websocketSync:!0}},this.global={syncGroup: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}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,i){let n=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,n.getUint16(o))}function readUint32(){return commitRead(4,n.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 i=readLength(31&e);if(i<0||e>>5!==t)throw new Error("Invalid indefinite length element");return i}function appendUtf16Data(t,e){for(let i=0;i<e;++i){let i=readUint8();128&i&&(i<224?(i=(31&i)<<6|63&readUint8(),e-=1):i<240?(i=(15&i)<<12|(63&readUint8())<<6|63&readUint8(),e-=2):(i=(15&i)<<18|(63&readUint8())<<12|(63&readUint8())<<6|63&readUint8(),e-=3)),i<65536?t.push(i):(i-=65536,t.push(55296|i>>10),t.push(56320|1023&i))}}"function"==typeof e&&(tagValueFunction=e),"function"==typeof i&&(simpleValFunction=i);let s=function decodeItem(){let t,e,i=readUint8(),r=i>>5,s=31&i;if(7===r)switch(s){case 25:return function readFloat16(){let t=new ArrayBuffer(4),e=new DataView(t),i=readUint16(),n=32768&i,r=31744&i,o=1023&i;if(31744===r)r=261120;else if(0!==r)r+=114688;else if(0!==o)return(n?-1:1)*o*POW_2_24;return e.setUint32(0,n<<16|r<<13|o<<13),e.getFloat32(0)}();case 26:return function readFloat32(){return commitRead(4,n.getFloat32(o))}();case 27:return function readFloat64(){return commitRead(8,n.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 i=[],n=0;for(;(e=readIndefiniteStringLength(r))>=0;)n+=e,i.push(readArrayBuffer(e));let o=new Uint8Array(n),s=0;for(t=0;t<i.length;++t)o.set(i[t],s),s+=i[t].length;return o}return readArrayBuffer(e);case 3:let i=[];if(e<0)for(;(e=readIndefiniteStringLength(r))>=0;)appendUtf16Data(i,e);else appendUtf16Data(i,e);let n="";for(t=0;t<i.length;t+=8192)n+=String.fromCharCode.apply(null,i.slice(t,t+8192));return n;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,i=new ArrayBuffer(256),n=new DataView(i),r=new Uint8Array(i),o=0;function prepareWrite(t){let s=i.byteLength,a=o+t;for(;s<a;)s<<=1;if(s!==i.byteLength){let t=n;i=new ArrayBuffer(s),n=new DataView(i),r=new Uint8Array(i);let e=o+3>>2;for(let i=0;i<e;++i)n.setUint32(i<<2,t.getUint32(i<<2))}return e=t,n}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,i=(t-e)/POW_2_32,n=prepareWrite(8);n.setUint32(o,i),n.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 i=[];for(e=0;e<t.length;++e){let n=t.charCodeAt(e);n<128?i.push(n):n<2048?(i.push(192|n>>6),i.push(128|63&n)):n<55296||n>=57344?(i.push(224|n>>12),i.push(128|n>>6&63),i.push(128|63&n)):(n=(1023&n)<<10,n|=1023&t.charCodeAt(++e),n+=65536,i.push(240|n>>18),i.push(128|n>>12&63),i.push(128|n>>6&63),i.push(128|63&n))}return writeTypeAndLength(3,i.length),writeUint8Array(i);default:let n,r;if(Array.isArray(t))for(n=t.length,writeTypeAndLength(4,n),e=0;e<n;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 i=Object.keys(t);for(n=i.length,writeTypeAndLength(5,n),e=0;e<n;e+=1){let n=i[e];encodeItem(n),encodeItem(t[n])}}}}(t),"slice"in i)return i.slice(0,o);let s=new ArrayBuffer(o),a=new DataView(s);for(let t=0;t<o;++t)a.setUint8(t,n.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{constructor(t,e=!1,i=!1){const n=e?t:CBOR.encode(t),r=i?n:validateDocumentIDCBOR(n);if(!r)throw new Error(`Can't create DocumentID, passed in value is not valid: ${t}`);this.isValidated=!i,this["@ditto.cbor"]=r}get value(){let t=this["@ditto.value"];return void 0===t&&(t=CBOR.decode(this["@ditto.cbor"]),this["@ditto.value"]=t),t}equals(t){const e=this["@ditto.cbor"],i=t["@ditto.cbor"];if(e===i)return!0;if(!(e instanceof Uint8Array))return!1;if(!(i instanceof Uint8Array))return!1;if(e.length!==i.length)return!1;for(let t=0;t<e.length;t+=1)if(e[t]!==i[t])return!1;return!0}toString(){return documentIDQueryCompatible(this["@ditto.cbor"],"WithoutQuotes")}toBase64String(){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{constructor(t,e){this.ditto=t,this.token=e}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)),i=require("fs/promises");return i.copyFile(e,t,i.COPYFILE_EXCL)}}}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 i=t._len;if("number"!=typeof i||i<0)throw new Error("Invalid attachment token length");const n=t._meta;if("object"!=typeof n)throw new Error("Invalid attachment token meta");this.id=e,this.len=i,this.metadata=n}}class AttachmentFetcher{constructor(t,e,i){this.ditto=t,this.token=e,this.eventHandler=i||null,this.cancelTokenPromise=null;const n=i||function(){};this.attachment=new Promise(((i,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}),n({type:"Completed",attachment:e}),i(e)},onProgress:(t,e)=>{n({type:"Progress",totalBytes:e,downloadedBytes:t})},onDelete:()=>{this.eventHandler=null,this.cancelTokenPromise=null,n({type:"Deleted"}),i(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)}stop(){AttachmentFetcher.stopWithContextInfo({ditto:this.ditto,attachmentTokenID:this.token.id,cancelTokenPromise:this.cancelTokenPromise})}then(t,e){return this.attachment.then(t,e)}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{constructor(t,e,i,n,r,o){this.isCancelled=!1,this.query=e,this.queryArgsCBOR=i,this.collection=t,this.contextInfo={ditto:t.store.ditto,collectionName:t.name,query:e,queryArgsCBOR:i,orderBys:n,limit:r,offset:o},Subscription.add(this,this.contextInfo)}get collectionName(){return this.collection.name}cancel(){this.isCancelled||(this.isCancelled=!0,Subscription.remove(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$2="@ditto.64d129224a5377b63e9727479ec987d9";class Counter{constructor(){this.value=0}static"@ditto.create"(t,e,i){const n=t?new MutableCounter(privateToken$2):new Counter;return n.mutDoc=t,n.path=e,n.value=i,n}}class MutableCounter extends Counter{increment(t){const e=this.mutDoc,i=this.path;if(!e)throw new Error("Can't increment counter, only possible within the closure of a collection's update() method.");e.at(i)["@ditto.increment"](t),this.value+=t}constructor(){if(arguments[0]!==privateToken$2)throw new Error("MutableCounter constructor is for internal use only.");super()}}const privateToken$1="@ditto.ff82dae89821c5ab822a8b539056bce4";class Register{constructor(t){this["@ditto.value"]=t}get value(){return this["@ditto.value"]}static"@ditto.create"(t,e,i){const n=t?new MutableRegister(i,privateToken$1):new Register(i);return n["@ditto.mutableDocument"]=t,n["@ditto.path"]=e,n["@ditto.value"]=i,n}}class MutableRegister extends Register{get value(){return super.value}set value(t){this.set(t)}set(t){const e=this["@ditto.mutableDocument"],i=this["@ditto.path"];e.at(i)["@ditto.set"](t),this["@ditto.value"]=t}constructor(t){if(arguments[1]!==privateToken$1)throw new Error("MutableRegister constructor is for internal use only.");super(t)}}const privateToken="@ditto.65bd197aba2caca16d64149d4ea81c67";class RGA{constructor(t=[]){this["@ditto.value"]=t}get value(){return this["@ditto.value"]}static"@ditto.create"(t,e,i){const n=t?new MutableRGA(i,privateToken):new RGA(i);return n["@ditto.mutableDocument"]=t,n["@ditto.path"]=e,n["@ditto.value"]=i,n}}class MutableRGA extends RGA{get value(){const t=this["@ditto.mutableDocument"],e=this["@ditto.path"];return t.at(e).value}setAt(t,e){const i=this["@ditto.mutableDocument"],n=this["@ditto.path"];i.at(n).at(e)["@ditto.set"](t)}removeAt(t){const e=this["@ditto.mutableDocument"],i=this["@ditto.path"];e.at(i).at(t)["@ditto.remove"]()}push(t){const e=this["@ditto.mutableDocument"],i=this["@ditto.path"];e.at(i)["@ditto.push"](t)}pop(){const t=this["@ditto.mutableDocument"],e=this["@ditto.path"];return t.at(e)["@ditto.pop"]()}insertAt(t,e){const i=this["@ditto.mutableDocument"],n=this["@ditto.path"];i.at(n).at(e)["@ditto.insert"](t)}constructor(t){if(arguments[1]!==privateToken)throw new Error("MutableRGA constructor is for internal use only.");super(t)}}class UpdateResult{constructor(t,e,i,n,r){this.type=t,this.docID=e,this.path=i,void 0!==n&&(this.value=n),void 0!==r&&(this.amount=r)}static set(t,e,i){return new UpdateResult("set",t,e,i,void 0)}static replacedWithCounter(t,e){return new UpdateResult("replacedWithCounter",t,e,void 0,void 0)}static incremented(t,e,i){return new UpdateResult("incremented",t,e,void 0,i)}static inserted(t,e,i){return new UpdateResult("inserted",t,e,i,void 0)}static removed(t,e){return new UpdateResult("removed",t,e,void 0,void 0)}static pushed(t,e,i){return new UpdateResult("pushed",t,e,i,void 0)}static popped(t,e,i){return new UpdateResult("popped",t,e,i,void 0)}}function augmentJSONValue(t,e,i){if(t&&"object"==typeof t){if(Array.isArray(t))return t.map(((t,n)=>augmentJSONValue(t,e,`${i}[${n}]`)));if(t[DittoCRDTTypeKey]===DittoCRDTType.counter)return Counter["@ditto.create"](e,i,t._value);if(t[DittoCRDTTypeKey]===DittoCRDTType.register)return Register["@ditto.create"](e,i,t._value);if(t[DittoCRDTTypeKey]===DittoCRDTType.rga){const n=augmentJSONValue(t._value,e,i);return RGA["@ditto.create"](e,i,n)}if(t[DittoCRDTTypeKey]===DittoCRDTType.attachment)return new AttachmentToken(t);for(const[n,r]of Object.entries(t))t[n]=augmentJSONValue(r,e,`${i}['${n}']`);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,i]of Object.entries(t))t[e]=desugarJSObject(i,!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 i;const n=null!==(i=e.isInitial)&&void 0!==i&&i;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 n?t:r}static evaluate(t,e,i={}){var n;const r=null!==(n=i.stopAtLastContainer)&&void 0!==n&&n,o={keyPath:t,object:e,options:{...i},coveredPath:null,nextPathComponent:null,remainingPath:t,value:e};return function recurse(t,e){if(""===e)return o.value=t,o;const{nextPathComponentRaw:i,nextPathComponent:n,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 i=e[0],n=e[1];return{nextPathComponentRaw:i,nextPathComponent:n,remainingPath:t.slice(n.length+1)}}const i=t.match(subscriptIndexRegExp);if(null!==i){const e=i[0],n=i[1];return{nextPathComponentRaw:e,nextPathComponent:parseInt(n),remainingPath:t.slice(n.length+2)}}const n=t.match(subscriptSingleQuoteKeyRegExp);if(null!==n){const e=n[0],i=n[1];return{nextPathComponentRaw:e,nextPathComponent:i,remainingPath:t.slice(i.length+4)}}const r=t.match(subscriptDoubleQuoteKeyRegExp);if(null!==r){const e=r[0],i=r[1];return{nextPathComponentRaw:e,nextPathComponent:i,remainingPath:t.slice(i.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=n,o.remainingPath=s,null===o.coveredPath||"number"==typeof i?o.coveredPath=i:o.coveredPath+=i,""===s&&r?(o.value=t,o):recurse(t[n],s)}(e,this.withLeadingDot(t))}constructor(){}}class DocumentPath{constructor(t,e,i){this.document=t,this.path=i?KeyPath.validate(e,{isInitial:!0}):e}at(t){if("string"==typeof t){const e=t,i=KeyPath.validate(e),n=KeyPath.withoutLeadingDot(`${this.path}${i}`);return new DocumentPath(this.document,n,!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"](null,this.path,t):null}get attachmentToken(){const t=this.underlyingValueForPathType("Attachment");return void 0!==t?new AttachmentToken(t):null}underlyingValueForPathType(t){const e=this.path,i=this.document,n=documentGetCBORWithPathType(documentBridge.pointerFor(i),e,t);return null!==n.cbor?CBOR.decode(n.cbor):void 0}}class MutableDocumentPath{constructor(t,e,i){this.mutableDocument=t,this.path=i?KeyPath.validate(e,{isInitial:!0}):e}at(t){if("string"==typeof t){const e=t,i=KeyPath.validate(e),n=KeyPath.withoutLeadingDot(`${this.path}${i}`);return new MutableDocumentPath(this.mutableDocument,n,!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.mutableDocument,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"]()}underlyingValueForPathType(t){const e=this.path,i=this.mutableDocument,n=documentGetCBORWithPathType(mutableDocumentBridge.pointerFor(i),e,t);return null!==n.cbor?CBOR.decode(n.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 i=mutableDocumentBridge.pointerFor(this.mutableDocument),n=desugarJSObject(t,!1),r=CBOR.encode(n);e?documentSetCBORWithTimestamp(i,this.path,r,!0,0):documentSetCBOR(i,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.pop"(){const t=documentPopCBOR(mutableDocumentBridge.pointerFor(this.mutableDocument),this.path);let e=augmentJSONValue(CBOR.decode(t),this.mutableDocument,this.path);e instanceof Register&&(e=e.value),e instanceof Counter&&(e=e.value),this.updateInMemory(((t,e)=>{const i=t[e];if(!Array.isArray(i))throw new Error(`Can't pop, object at key-path ${this.path} is not an array.`);i.pop()}));const i=UpdateResult.popped(this.mutableDocument.id,this.path,e);return this.recordUpdateResult(i),e}"@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)}"@ditto.push"(t){const e=mutableDocumentBridge.pointerFor(this.mutableDocument),i=desugarJSObject(t,!1),n=CBOR.encode(i);documentPushCBOR(e,this.path,n),this.updateInMemory(((e,i)=>{const n=e[i];if(!Array.isArray(n))throw new Error(`Can't push value, object at key-path ${this.path} is not an array.`);n.push(t)}));const r=augmentJSONValue(CBOR.decode(n),this.mutableDocument,this.path),o=UpdateResult.pushed(this.mutableDocument.id,this.path,r);this.recordUpdateResult(o)}"@ditto.insert"(t){const e=mutableDocumentBridge.pointerFor(this.mutableDocument),i=desugarJSObject(t),n=CBOR.encode(i);documentInsertCBOR(e,this.path,n),this.updateInMemory(((e,i)=>{const n=i;if(!Array.isArray(e))throw new Error(`Can't insert value, object trying to be indexed at key-path ${this.path} is not an array.`);if("number"!=typeof n)throw new Error(`Can't insert value, last path component in key-path ${this.path} is not a number.`);e.splice(n,0,t)}));const r=augmentJSONValue(CBOR.decode(n),this.mutableDocument,this.path),o=UpdateResult.inserted(this.mutableDocument.id,this.path,r);this.recordUpdateResult(o)}updateInMemory(t){const e=this.mutableDocument.value,i=KeyPath.evaluate(this.path,e,{stopAtLastContainer:!0});t(i.value,i.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{constructor(){this["@ditto.updateResults"]=[]}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)}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{constructor(t,e){const i=t.map((t=>t.toString())).sort().join(", ");if(i!==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}}get(t){const e=(t instanceof DocumentID?t:new DocumentID(t)).toString();return this.updateResultsByDocumentIDString[e]}keys(){return this.documentIDs.slice()}}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{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}hash(t){return documentsHash(t.map((t=>documentBridge.pointerFor(t))))}hashMnemonic(t){return documentsHashMnemonic(t.map((t=>documentBridge.pointerFor(t))))}}class SingleDocumentLiveQueryEvent{constructor(t,e){this.isInitial=t,this.oldDocument=e}hash(t){return documentsHash(null===t?[]:[documentBridge.pointerFor(t)])}hashMnemonic(t){return documentsHashMnemonic(null===t?[]:[documentBridge.pointerFor(t)])}}class LiveQuery{constructor(t,e,i,n,r,o,s,a,c){this.query=t,this.queryArgs=e?Object.freeze({...e}):null,this.queryArgsCBOR=i,this.orderBys=n,this.limit=r,this.offset=o,this.collection=s,this.handler=c,a&&(this.subscription=a);const u=dittoBridge.pointerFor(s.store.ditto),l=s.name;let d;const signalNext=async()=>{await liveQuerySignalAvailableNext(u,d)};if(d=liveQueryRegister(u,l,t,i,this.orderBys,r,o,(t=>{const e=t.documents.map((t=>documentBridge.bridge(t)));let i;i=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,i,signalNext)})),!d)throw new Error("Internal inconsistency, couldn't create a valid live query ID.");this.liveQueryID=d,step((async()=>await liveQueryStart(u,d))),s.store.ditto.keepAlive.retain(`LiveQuery.${d}`)}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 i=dittoBridge.pointerFor(this.collection.store.ditto);null===(t=this.subscription)||void 0===t||t.cancel(),liveQueryStop(i,e)}}async signalNext(){const t=dittoBridge.pointerFor(this.collection.store.ditto);await liveQuerySignalAvailableNext(t,this.liveQueryID)}}class PendingCursorOperation{constructor(t,e,i){this.currentLimit=-1,this.currentOffset=0,this.orderBys=[],this.query=validateQuery(t),this.queryArgs=e?Object.freeze({...e}):null,this.collection=i,this.queryArgsCBOR=e?CBOR.encode(e):null}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)}observe(t){return Logger.warning("Method `observe()` is deprecated and will be removed in the near future. Please use `observeLocal()` and `subscribe()` individually instead."),this._observe(t,!0,!1)}observeWithNextSignal(t){return Logger.warning("Method `observeWithNextSignal()` is deprecated and will be removed in the near future. Please use `observeLocalWithNextSignal()` and `subscribe()` individually instead."),this._observe(t,!0,!0)}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 i=await writeTransaction(e),n=await collectionRemoveQueryStr(e,this.collection.name,i,t,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);return await writeTransactionCommit(e,i),n}))).map((t=>new DocumentID(t,!0)))}async evict(){const t=this.query,e=dittoBridge.pointerFor(this.collection.store.ditto);return(await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const i=await writeTransaction(e),n=await collectionEvictQueryStr(e,this.collection.name,i,t,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);return await writeTransactionCommit(e,i),n}))).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,i=dittoBridge.pointerFor(this.collection.store.ditto),n=await writeTransaction(i),r=await collectionExecQueryStr(i,this.collection.name,n,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,i=e.toString(),n=t["@ditto.updateResults"];if(a[i])throw new Error(`Internal inconsistency, update results for document ID as string already exist: ${i}`);s.push(e),a[i]=n,mutableDocumentBridge.pointerFor(t),mutableDocumentBridge.unregister(t)}return await collectionUpdateMultiple(i,this.collection.name,n,r),await writeTransactionCommit(i,n),new UpdateResultsMap(s,a)}))}_observe(t,e,i){const n=e?this.subscribe():null;const r=i?t:function wrappedHandler(e,i,n){try{return t.call(this,e,i)}finally{n()}};return new LiveQuery(this.query,this.queryArgs,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset,this.collection,n,r)}then(t,e){return this.exec().then(t,e)}}class PendingIDSpecificOperation{constructor(t,e){this.documentID=t,this.collection=e,this.documentIDCBOR=t.toCBOR()}subscribe(){return new Subscription(this.collection,this.query,null,[],-1,0)}observe(t){return Logger.warning("Method `observe()` is deprecated and will be removed in the near future. Please use `observeLocal()` and `subscribe()` individually instead."),this._observe(t,!0,!1)}observeWithNextSignal(t){return Logger.warning("Method `observeWithNextSignal()` is deprecated and will be removed in the near future. Please use `observeLocalWithNextSignal()` and `subscribe()` individually instead."),this._observe(t,!0,!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),i=await collectionRemove(t,this.collection.name,e,this.documentIDCBOR);return await writeTransactionCommit(t,e),i}))}async evict(){const t=dittoBridge.pointerFor(this.collection.store.ditto);return await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const e=await writeTransaction(t),i=await collectionEvict(t,this.collection.name,e,this.documentIDCBOR);return await writeTransactionCommit(t,e),i}))}async exec(){const t=dittoBridge.pointerFor(this.collection.store.ditto);return await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const e=await readTransaction(t),i=await collectionGet(t,this.collection.name,this.documentIDCBOR,e);let n;return i&&(n=documentBridge.bridge(i)),readTransactionFree(e),n}))}async update(t){const e=dittoBridge.pointerFor(this.collection.store.ditto),i=await readTransaction(e),n=await collectionGet(e,this.collection.name,this.documentIDCBOR,i);if(readTransactionFree(i),!n)throw new Error(`Can't update, document with ID '${this.documentID.toString()}' not found in collection named '${this.collection.name}'`);const r=mutableDocumentBridge.bridge(n,(()=>new MutableDocument));t(r),mutableDocumentBridge.unregister(r);const o=await writeTransaction(e);return await collectionUpdate(e,this.collection.name,o,n),await writeTransactionCommit(e,o),r["@ditto.updateResults"].slice()}_observe(t,e,i){const n=e?this.subscribe():null;return new LiveQuery(this.query,null,null,[],-1,0,this.collection,n,((e,n,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===n.isInitial&&n.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===n.isInitial&&n.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===n.isInitial&&n.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===n.isInitial&&n.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===n.isInitial&&n.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===n.isInitial?0:n.insertions.length+n.deletions.length+n.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===n.isInitial?void 0:n.oldDocuments[0],a=new SingleDocumentLiveQueryEvent(n.isInitial,s);if(i)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{constructor(t,e){this.name=t,this.store=e}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 i;const n=null!==(i=e.writeStrategy)&&void 0!==i?i:"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(),u=desugarJSObject(t,!0),l=CBOR.encode(u),d=await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>await collectionInsertValue(o,this.name,l,c,n)));return new DocumentID(d,!0)}async newAttachment(t,e={}){const i=this.store.ditto,n=dittoBridge.pointerFor(i),{id:r,len:o,handle:s}=await(async()=>{if("string"==typeof t)return dittoNewAttachmentFromFile(n,t,"Copy");if(t instanceof Uint8Array)return await dittoNewAttachmentFromBytes(n,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),u=new Attachment(i,c);return attachmentBridge.bridge(s,(()=>u),{throwIfAlreadyBridged:!0})}fetchAttachment(t,e){const i=this.store.ditto;return new AttachmentFetcher(i,t,e)}findByIDCBOR(t){const e=new DocumentID(t,!0,!0);return new PendingIDSpecificOperation(e,this)}}class CollectionsEvent{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}static initial(t){return new CollectionsEvent({isInitial:!0,collections:t,oldCollections:[],insertions:[],deletions:[],updates:[],moves:[]})}}class PendingCollectionsOperation{constructor(t){this.store=t,this.pendingCursorOperation=new PendingCursorOperation("true",null,new Collection("__collections",t))}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()}observe(t){return Logger.warning("Method `observe()` is deprecated and will be removed in the near future. Please use `observeLocal()` and `subscribe()` individually instead."),this._observe(t,!0,!1)}observeWithNextSignal(t){return Logger.warning("Method `observeWithNextSignal()` is deprecated and will be removed in the near future. Please use `observeLocalWithNextSignal()` and `subscribe()` individually instead."),this._observe(t,!0,!0)}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)}then(t,e){return this.exec().then(t,e)}_observe(t,e,i){const n=new WeakRef(this);return this.pendingCursorOperation._observe((function(e,r,o){const s=n.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})}i?t(c,o):t(c)}),e,i)}}function collectionsFromDocuments(t,e){const i=[];for(const n of t){const t=n.at("name").value;void 0!==t&&"string"==typeof t&&i.push(new Collection(t,e))}return i}class Store{constructor(t){this.ditto=t}collection(t){return new Collection(t,this)}collections(){return new PendingCollectionsOperation(this.ditto.store)}collectionNames(){return dittoGetCollectionNames(dittoBridge.pointerFor(this.ditto))}async registerLiveQueryWebhook(t,e,i){const n=validateQuery(e),r=await liveQueryWebhookRegister(dittoBridge.pointerFor(this.ditto),t,n,[],0,0,i);return new DocumentID(r,!0)}}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,i;return{networkID:t.network_id,deviceName:t.device_name,rssi:null!==(e=t.rssi)&&void 0!==e?e:void 0,approximateDistanceInMeters:null!==(i=t.approximate_distance_in_meters)&&void 0!==i?i:void 0,connections:t.connections}}))}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",t.keepAlive),this.ditto=t}register(t){return dittoRegisterTransportConditionChangedCallback(dittoBridge.pointerFor(this.ditto),t)}unregister(){return dittoRegisterTransportConditionChangedCallback(dittoBridge.pointerFor(this.ditto),null)}processCallback(t,e){let i,n;switch(t){case"Bluetooth":i="BLE";break;case"Tcp":i="TCP";break;case"Awdl":i="AWDL";break;case"Mdns":i="MDNS"}switch(e){case"Unknown":n="Unknown";break;case"Ok":n="OK";break;case"GenericFailure":n="GenericFailure";break;case"AppInBackground":n="AppInBackground";break;case"MdnsFailure":n="MDNSFailure";break;case"TcpListenFailure":n="TCPListenFailure";break;case"NoBleCentralPermission":n="NoBLECentralPermission";break;case"NoBlePeripheralPermission":n="NoBLEPeripheralPermission";break;case"CannotEstablishConnection":n="CannotEstablishConnection";break;case"BleDisabled":n="BLEDisabled";break;case"NoBleHardware":n="NoBLEHardware";break;case"WifiDisabled":n="WiFiDisabled";break;case"TemporarilyUnavailable":n="TemporarilyUnavailable"}return[n,i]}}class Sync{constructor(t){this.bluetoothLETransportPointer=null,this.awdlTransportPointer=null,this.lanTransportPointer=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,i=stateFrom(this.parameters);this.updatePeerToPeerBluetoothLE(e,i),this.updatePeerToPeerAWDL(e,i),this.updatePeerToPeerLAN(e,i),this.updateListenTCP(e,i),this.updateListenHTTP(e,i),this.updateConnectTCPServers(e,i),this.updateConnectWebsocketURLs(e,i),this.updateGlobal(e,i),this.state=i}updatePeerToPeerBluetoothLE(t,e){const i=dittoBridge.pointerFor(this.ditto),n=t.effectiveTransportConfig.peerToPeer.bluetoothLE,r=e.effectiveTransportConfig.peerToPeer.bluetoothLE,o=!n.isEnabled&&r.isEnabled,s=n.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){if(o){if(!bleIsAvailable(i))throw new Error("Can't start P2P BluetoothLE transport because not available.");this.bluetoothLETransportPointer=bleCreate(i)}s&&(bleDestroy(this.bluetoothLETransportPointer),delete this.bluetoothLETransportPointer)}else{if(o){const t={clientTransport:dittoAddInternalBLEClientTransport(i),serverTransport:dittoAddInternalBLEServerTransport(i)};this.bluetoothLETransportPointer=t}if(s){const t=this.bluetoothLETransportPointer,{clientTransport:e,serverTransport:i}=t;BLEServerFreeHandle(i),BLEClientFreeHandle(e),this.bluetoothLETransportPointer=null}}}updatePeerToPeerAWDL(t,e){const i=dittoBridge.pointerFor(this.ditto),n=t.effectiveTransportConfig.peerToPeer.awdl,r=e.effectiveTransportConfig.peerToPeer.awdl,o=!n.isEnabled&&r.isEnabled,s=n.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(i))throw new Error("Can't start P2P AWDL transport because not available.");this.awdlTransportPointer=awdlCreate(i)}s&&(awdlDestroy(this.awdlTransportPointer),this.awdlTransportPointer=null)}updatePeerToPeerLAN(t,e){const i=dittoBridge.pointerFor(this.ditto),n=t.effectiveTransportConfig.peerToPeer.lan,r=e.effectiveTransportConfig.peerToPeer.lan;if(n.isEnabled&&(n.isMdnsEnabled&&(lanDestroy(this.lanTransportPointer),delete this.lanTransportPointer),n.isMulticastEnabled&&dittoRemoveMulticastTransport(i)),r.isEnabled){if(r.isMdnsEnabled){if(!lanIsAvailable(i))throw new Error("Can't start P2P LAN transport because not available.");this.lanTransportPointer=lanCreate(i)}r.isMulticastEnabled&&dittoAddMulticastTransport(i)}}updateListenTCP(t,e){const i=t.effectiveTransportConfig.listen.tcp,n=e.effectiveTransportConfig.listen.tcp;if(TransportConfig.areListenTCPsEqual(n,i))return;const r=dittoBridge.pointerFor(this.ditto);i.isEnabled&&dittoStopTCPServer(r),n.isEnabled&&dittoStartTCPServer(r,`${n.interfaceIP}:${n.port}`)}updateListenHTTP(t,e){const i=t.effectiveTransportConfig.listen.http,n=e.effectiveTransportConfig.listen.http;if(TransportConfig.areListenHTTPsEqual(i,n))return;const r=dittoBridge.pointerFor(this.ditto);i.isEnabled&&dittoStopHTTPServer(r),n.isEnabled&&dittoStartHTTPServer(r,`${n.interfaceIP}:${n.port}`,n.staticContentPath||null,n.websocketSync?"Enabled":"Disabled",n.tlsCertificatePath||null,n.tlsKeyPath||null)}updateConnectTCPServers(t,e){const i=Object.getOwnPropertyNames(this.staticTCPClientsByAddress),n=e.effectiveTransportConfig.connect.tcpServers,r=new Set(n);for(const t of i)r.delete(t);const o=new Set(i);for(const t of n)o.delete(t);const s=r.values(),a=o.values();for(const t of s){const e=addStaticTCPClient(dittoBridge.pointerFor(this.ditto),t),i=staticTCPClientBridge.bridge(e);this.staticTCPClientsByAddress[t]=i}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 i=staticTCPClientBridge.pointerFor(e);staticTCPClientBridge.unregister(e),staticTCPClientFreeHandle(i),delete this.staticTCPClientsByAddress[t]}}updateConnectWebsocketURLs(t,e){const i=Object.getOwnPropertyNames(this.websocketClientsByURL),n=e.effectiveTransportConfig.connect.websocketURLs.slice(),r=new Set(n);for(const t of i)r.delete(t);const o=new Set(i);for(const t of n)o.delete(t);const s=r.values(),a=o.values();for(const t of s){const e=addWebsocketClient(dittoBridge.pointerFor(this.ditto),t),i=websocketClientBridge.bridge(e);this.websocketClientsByURL[t]=i}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 i=websocketClientBridge.pointerFor(e);websocketClientBridge.unregister(e),websocketClientFreeHandle(i),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 i=t.transportConfig.copy(),n=t.identity,r=t.isSyncActive,o=t.isX509Valid,s=t.isWebValid;let a,c;i.connect.tcpServers,i.connect.websocketURLs;let u=!1;if("onlinePlayground"!==n.type&&"onlineWithAuthentication"!==n.type||(a=n.appID,c=null!==(e=n.customDittoCloudURL)&&void 0!==e?e:null,u=!n.hasOwnProperty("enableDittoCloudSync")||n.enableDittoCloudSync),r&&o||(i.peerToPeer.bluetoothLE.isEnabled=!1,i.peerToPeer.awdl.isEnabled=!1,i.peerToPeer.lan.isEnabled=!1,i.listen.tcp.isEnabled=!1,i.connect.tcpServers=[]),r&&s||(i.connect.websocketURLs=[]),r||(i.listen.http.isEnabled=!1),r&&s&&u){const t=null!=c?c:defaultDittoCloudURL(a);i.connect.websocketURLs.push(t)}return i.peerToPeer.lan.isEnabled&&!i.listen.tcp.isEnabled&&(i.listen.tcp.isEnabled=!0,i.listen.tcp.interfaceIP="[::]",i.listen.tcp.port=0),{underlyingSyncParameters:t,effectiveTransportConfig:i.freeze()}}class Ditto{constructor(t,e){this.isWebValid=!1,this.isX509Valid=!1;const i=null!=t?t:{type:"offlinePlayground",appID:""},n=e&&e.trim().length>0?e:"ditto",r=Object.freeze(this.validateIdentity(i));this.identity=Object.freeze(r),this.path=n;require("fs").mkdirSync(n,{recursive:!0});{const t=require("os");this.deviceName=t.hostname()}this.keepAlive=new KeepAlive;const o=uninitializedDittoMake(n);let s=null;const a=new WeakRef(this),c=(()=>{var t,e,i;if("offlinePlayground"===r.type)return dittoAuthClientMakeForDevelopment(n,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(n,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(n,r.appID,r.token,t)}if("onlineWithAuthentication"===r.type){const t=null!==(i=r.customAuthURL)&&void 0!==i?i: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(n,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 u=dittoAuthClientIsWebValid(c),l=dittoAuthClientIsX509Valid(c),d=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=d,this.transportConfig=p.copy().freeze(),this.isX509Valid=l,this.isWebValid=u,this.sync=new Sync(this),this.sync.update({isSyncActive:!1,isX509Valid:l,isWebValid:u,identity:r,transportConfig:p}),this.isActivated=!IdentityTypesRequiringOfflineLicenseToken.includes(r.type),this.store=new Store(this),this.presenceManager=new PresenceManager(this),this.transportConditionsManager=new TransportConditionsManager(this),null!==s&&this.auth["@ditto.authenticationExpiring"](s)}get sdkVersion(){return dittoGetSDKVersion(dittoBridge.pointerFor(this))}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:i}=verifyLicense(t);if("LicenseOk"!==e)throw this.isActivated=!1,new Error(i);this.isActivated=!0}}setTransportConfig(t){this.transportConfig,this.transportConfig=t.copy().freeze();const e=this.transportConfig,i=this.identity,n=this.isWebValid,r=this.isX509Valid;this.sync.update({transportConfig:e,identity:i,isWebValid:n,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){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))}authClientValidityChanged(t,e){const i=this.transportConfig,n=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:i,identity:n,isWebValid:t,isX509Valid:e,isSyncActive:r})}validateIdentity(t){const e={...t};t.appName;const i=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===i)throw new Error("Property .appID must be given for identity, but isn't.");if(void 0!==i&&"string"!=typeof i)throw new Error(`Property .appID must be be of type string, but is of type '${typeof i}': ${i}`);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 i=this.isWebValid,n=this.isX509Valid,r=this.identity,o=this.transportConfig;dittoSetDeviceName(e,this.deviceName),this.sync.update({identity:r,transportConfig:o,isWebValid:i,isX509Valid:n,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,dittoFree);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.MutableRGA=MutableRGA,exports.MutableRegister=MutableRegister,exports.NotAvailableAuthenticator=NotAvailableAuthenticator,exports.Observer=Observer,exports.OnlineAuthenticator=OnlineAuthenticator,exports.PendingCollectionsOperation=PendingCollectionsOperation,exports.PendingCursorOperation=PendingCursorOperation,exports.PendingIDSpecificOperation=PendingIDSpecificOperation,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.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,i){this.type=t,this.object=e,this.pointer=i}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,i={}){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 i=e.object.deref();if(!i)throw new Error(`Internal inconsistency, found a meta entry for an object whose object is undefined (garbage collected): ${t}`);return i}bridge(t,e,i={}){const n=i.throwIfAlreadyBridged,r=this.objectFor(t);if(r&&n)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 i=t.constructor,n=this.type;if(i!==n)throw new Error(`Can't register, bridge is configured for type ${n.name} but passed in object is of type ${i.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(i,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,i=this.type;if(e!==i)throw new Error(`Can't unregister, bridge is configured for type ${i.name} but passed in object is of type ${e.name}`);const n=this.pointerFor(t);if(!n)throw new Error(`Can't unregister, object that has not been registered before: ${t}`);const r=this.metaByAddrMap[n.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!==i)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[n.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 i;const n=null!==(i=e.errorMessagePrefix)&&void 0!==i?i:"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(`${n} '${t}' is not a number.`);if(r&&Math.floor(t)!==t)throw new Error(`${n} '${t}' is not an integer.`);if(void 0!==o&&t<o)throw new Error(`${n} '${t}' must be >= ${o}.`);if(void 0!==s&&t>s)throw new Error(`${n} '${t}' must be <= ${s}.`);if(void 0!==a&&t<=a)throw new Error(`${n} '${t}' must be > ${a}.`);if(void 0!==c&&t>=c)throw new Error(`${n} '${t}' must be < ${c}.`);return t}function validateQuery(t,e={}){var i;const n=null!==(i=e.errorMessagePrefix)&&void 0!==i?i:"Query validation failed,";if("string"!=typeof t)throw new Error(`${n} query is not a string: ${t}`);if(""===t)throw new Error(`${n} query is an empty string.`);const r=t.trim();if(""===r)throw new Error(`${n} 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,i)=>{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")}catch(e){throw new Error("Couldn't load native module 'ditto."+t+".node' due to error.",e)}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_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 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 documentSetCBORWithTimestamp(t,e,i,n,r){ensureInitialized();const o=ditto_document_set_cbor_with_timestamp(t,bytesFromString(e),i,n,r);if(0!==o)throw new Error(errorMessage()||`ditto_document_set_cbor_with_timestamp() failed with error code: ${o}`)}function documentSetCBOR(t,e,i,n){ensureInitialized();const r=ditto_document_set_cbor(t,bytesFromString(e),i,n);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,i){ensureInitialized();const n=ditto_document_get_cbor_with_path_type(t,bytesFromString(e),i);return{statusCode:n.status_code,cbor:boxCBytesIntoBuffer(n.cbor)}}function documentRemove(t,e){ensureInitialized();const i=ditto_document_remove(t,bytesFromString(e));if(0!==i)throw new Error(errorMessage()||`ditto_document_remove() failed with error code: ${i}`)}function documentIncrementCounter(t,e,i){ensureInitialized();const n=ditto_document_increment_counter(t,bytesFromString(e),i);if(0!==n)throw new Error(errorMessage()||`ditto_document_increment_counter() failed with error code: ${n}`)}function documentFree(t){ensureInitialized(),ditto_document_free(t)}function documentIDQueryCompatible(t,e){ensureInitialized();return boxCStringIntoString(ditto_document_id_query_compatible(t,e))}function validateDocumentID(t){ensureInitialized();return boxCBytesIntoBuffer(withOutBoxCBytes((e=>{const i=ditto_validate_document_id(t,e);if(0!==i)throw new Error(errorMessage()||`ditto_validate_document_id() failed with error code: ${i}`);return e})))}async function collectionGet(t,e,i,n){ensureInitialized();const r=bytesFromString(e),{status_code:o,document:s}=await ditto_collection_get(t,r,i,n);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,i,n,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,i,n,s,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,i,n){ensureInitialized();const r=bytesFromString(e),{status_code:o,bool_value:s}=await ditto_collection_remove(t,r,i,n);if(0!==o)throw new Error(errorMessage()||`ditto_collection_remove() failed with error code: ${o}`);return s}async function collectionEvict(t,e,i,n){ensureInitialized();const r=bytesFromString(e),{status_code:o,bool_value:s}=await ditto_collection_evict(t,r,i,n);if(0!==o)throw new Error(errorMessage()||`ditto_collection_evict() failed with error code: ${o}`);return s}async function collectionUpdate(t,e,i,n){ensureInitialized();const r=bytesFromString(e),o=await ditto_collection_update(t,r,i,n);if(0!==o)throw new Error(errorMessage()||`ditto_collection_update() failed with error code: ${o}`)}async function collectionUpdateMultiple(t,e,i,n){ensureInitialized();const r=bytesFromString(e),o=jsDocsToCDocs(n),s=await ditto_collection_update_multiple(t,r,i,o);if(0!==s)throw new Error(errorMessage()||`ditto_collection_update_multiple() failed with error code: ${s}`)}async function collectionExecQueryStr(t,e,i,n,r,o,s,a){ensureInitialized();const c=bytesFromString(e),l=bytesFromString(n);return await ditto_collection_exec_query_str(t,c,i,l,r,o,s,a)}async function collectionRemoveQueryStr(t,e,i,n,r,o,s,a){ensureInitialized();const c=bytesFromString(e),l=bytesFromString(n);return await ditto_collection_remove_query_str(t,c,i,l,r,o,s,a)}async function collectionEvictQueryStr(t,e,i,n,r,o,s,a){ensureInitialized();const c=bytesFromString(e),l=bytesFromString(n);return await ditto_collection_evict_query_str(t,c,i,l,r,o,s,a)}function addSubscription(t,e,i,n,r,o,s){ensureInitialized();return ditto_add_subscription(t,bytesFromString(e),bytesFromString(i),n,r,o,s)}function removeSubscription(t,e,i,n,r,o,s){ensureInitialized();return ditto_remove_subscription(t,bytesFromString(e),bytesFromString(i),n,r,o,s)}function liveQueryRegister(t,e,i,n,r,o,s,a,c){ensureInitialized();const l=bytesFromString(e),u=bytesFromString(i),{status_code:d,i64:h}=ditto_live_query_register_str_detached(t,l,u,n,r,o,s,wrapBackgroundCbForFFI(c,a));if(0!==d)throw new Error(errorMessage()||`\`ditto_live_query_register_str()\` failed with error code: ${d}`);return h}async function liveQueryStart(t,e){ensureInitialized();const i=await ditto_live_query_start(t,e);if(0!==i)throw new Error(errorMessage()||`\`ditto_live_query_start()\` failed with error code: ${i}`)}function liveQueryStop(t,e){ensureInitialized(),ditto_live_query_stop(t,e)}async function liveQuerySignalAvailableNext(t,e){ensureInitialized(),await ditto_live_query_signal_available_next(t,e)}async function liveQueryWebhookRegister(t,e,i,n,r,o,s){ensureInitialized();const a=bytesFromString(e),c=bytesFromString(i),l=bytesFromString(s),{status_code:u,id:d}=await ditto_live_query_webhook_register_str(t,a,c,n,r,o,l);if(0!==u)throw new Error(errorMessage()||`\`ditto_live_query_webhook_register_str()\` failed with error code: ${u}`);return boxCBytesIntoBuffer(d)}async function readTransaction(t){ensureInitialized();const{status_code:e,txn:i}=await ditto_read_transaction(t);if(0!==e)throw new Error(errorMessage()||`\`ditto_read_transaction()\` failed with error code: ${e}`);return i}function readTransactionFree(t){return ensureInitialized(),ditto_read_transaction_free(t)}async function writeTransaction(t){ensureInitialized();const{status_code:e,txn:i}=await ditto_write_transaction(t);if(0!==e)throw new Error(errorMessage()||`ditto_write_transaction() failed with error code: ${e}`);return i}async function writeTransactionCommit(t,e){ensureInitialized();const i=await ditto_write_transaction_commit(t,e);if(0!==i)throw new Error(errorMessage()||`ditto_write_transaction_commit() failed with error code: ${i}`)}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){ensureInitialized();return ditto_add_websocket_client(t,bytesFromString(e))}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,i)=>{try{const n=boxCStringIntoString(i);t(e,n)}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,i,n){ensureInitialized();const r=bytesFromString(t),o=bytesFromString(e),s=bytesFromString(i),a=bytesFromString(n),{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,i,n){ensureInitialized();const r=bytesFromString(t),o=bytesFromString(e),s=bytesFromString(i),{status_code:a,auth_client:c}=ditto_auth_client_make_with_web(r,o,s,n);if(0!==a)throw new Error(errorMessage()||`ditto_auth_client_make_with_web() failed with error code: ${a}`);return c}function dittoAuthClientMakeForDevelopment(t,e,i){ensureInitialized();const n=bytesFromString(t),r=bytesFromString(e),o=Number(i),{status_code:s,auth_client:a}=ditto_auth_client_make_for_development(n,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,i,n){ensureInitialized();const r=bytesFromString(t),o=bytesFromString(e),s=bytesFromString(i),a=Number(n),{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:i,auth_client:n}=ditto_auth_client_make_with_static_x509(e);if(0!==i)throw new Error(errorMessage()||`ditto_auth_client_make_with_static_x509() failed with error code: ${i}`);return n}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,i){ensureInitialized();const n=bytesFromString(e),r=bytesFromString(i),o=await ditto_auth_client_login_with_token(t,n,r);if(0!==o)throw new Error(errorMessage()||`Ditto failed to authenticate (error code: ${o}).`)}async function dittoAuthClientLoginWithUsernameAndPassword(t,e,i,n){ensureInitialized();const r=bytesFromString(e),o=bytesFromString(i),s=bytesFromString(n),a=await ditto_auth_client_login_with_credentials(t,r,o,s);if(0!==a)throw new Error(errorMessage()||`Ditto failed to authenticate (error code: ${a}).`)}async function dittoAuthClientLogout(t){ensureInitialized();const e=await ditto_auth_client_logout(t);if(0!==e)throw new Error(errorMessage()||`Ditto failed to logout (error code: ${e}).`)}function 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),i=e.status_code,n=e.names;if(0!==i)throw new Error(errorMessage()||`ditto_get_collection_names() failed with error code: ${i}`);return cStringVecToStringArray(n)}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 i=refCStringToString(t);e(i)}))):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 i=refCStringToString(t);e(i)})))}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,i){ensureInitialized();const n={},r=ditto_new_attachment_from_file(t,bytesFromString(e),i,n);if(0!==r)throw new Error(errorMessage()||`ditto_new_attachment_from_file() failed with error code: ${r}`);return n}async function dittoNewAttachmentFromBytes(t,e){ensureInitialized();const i={},n=await ditto_new_attachment_from_bytes(t,e,i);if(0!==n)throw new Error(errorMessage()||`ditto_new_attachment_from_bytes() failed with error code: ${n}`);return i}async function dittoResolveAttachment(t,e,i,n){ensureInitialized();const{onComplete:r,onProgress:o,onDelete:s}=i,{status_code:a,cancel_token:c}=await ditto_resolve_attachment(t,e,wrapBackgroundCbForFFI(n,r),wrapBackgroundCbForFFI(n,o),wrapBackgroundCbForFFI(n,s));if(0!==a)throw new Error(errorMessage()||`ditto_resolve_attachment() failed with error code: ${a}`);return c}function dittoCancelResolveAttachment(t,e,i){ensureInitialized();const n=ditto_cancel_resolve_attachment(t,e,i);if(0!==n)throw new Error(errorMessage()||`ditto_cancel_resolve_attachment() failed with error code: ${n}`)}function freeAttachmentHandle(t){ensureInitialized(),ditto_free_attachment_handle(t)}function dittoGetCompleteAttachmentPath(t,e){ensureInitialized();return refCStringToString(ditto_get_complete_attachment_path(t,e))}function dittoGetSDKVersion(t){ensureInitialized();return boxCStringIntoString(ditto_get_sdk_version(t))}function 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,i,n,r,o){ensureInitialized();return ditto_start_http_server(t,bytesFromString(e),bytesFromString(i),n,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:i}=ditto_documents_hash(t);if(0!==e)throw new Error(errorMessage()||`\`ditto_documents_hash()\` failed with error code: ${e}`);return BigInt(i)}function documentsHashMnemonic(t){ensureInitialized();const{status_code:e,c_string:i}=ditto_documents_hash_mnemonic(t);if(0!==e)throw new Error(errorMessage()||`\`ditto_documents_hash_mnemonic()\` failed with error code: ${e}`);return boxCStringIntoString(i)}function dittoAuthClientMakeLoginProvider(t,e){return ensureInitialized(),ditto_auth_client_make_login_provider(wrapBackgroundCbForFFI(e,t))}function dittoAuthClientSetValidityListener(t,e,i){ensureInitialized();return ditto_auth_client_set_validity_listener(t,wrapBackgroundCbForFFI(i,(function(t,i){return e(1===t,1===i)})))}!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,i){ensureInitialized(),bytesFromString(t),bytesFromString(e);const n=ditto_init_sdk_version(t,e,bytesFromString(i));if(void 0!==n&&0!==n)throw new Error(errorMessage()||`ditto_init_sdk_version() failed with error code: ${n}`)}function verifyLicense(t){ensureInitialized();const e=bytesFromString(t);let i;const n=boxCStringIntoString(withOutPtr("char *",(t=>(i=verify_license(e,t),t))));return{result:i,errorMessage:n}}isInitialized=!0,withOutPtr=wrapFFIOutFunction(withOutPtr$1);const NOT_FOUND_ERROR_CODE=-30798;function wrapBackgroundCbForFFI(t,e){return void 0===t&&(t=console.error),(i,...n)=>{let r;try{r=e(...n)}catch(e){try{t(e)}catch(t){console.error(`Internal error: \`onError()\` handler oughtn't throw, but it did throw ${t}`)}}return i(r)}}function wrapFFIOutFunction(t){return function(...e){let i,n,r=!1;const o=e[e.length-1],s=e.splice(0,e.length-1),a=t(...s,(t=>{try{n=o(t),r=n===t}catch(t){i=t}}));if(i)throw i;return r?a:n}}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||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 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.0-alpha1";async function init(t={}){}switch(process.platform){case"android":initSDKVersion("Android","JavaScript","3.0.0-alpha1");break;case"darwin":initSDKVersion("Mac","JavaScript","3.0.0-alpha1");break;case"linux":initSDKVersion("Linux","JavaScript","3.0.0-alpha1");break;case"win32":initSDKVersion("Windows","JavaScript","3.0.0-alpha1");break;default:initSDKVersion("Unknown","JavaScript","3.0.0-alpha1")}loggerInit();class KeepAlive{constructor(){this.countsByID={},this.intervalID=null}get isActive(){return null!==this.intervalID}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{constructor(){throw new Error("Logger can't be instantiated, use it's static properties & methods directly instead.")}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)}}class ObserverManager{constructor(t,e={}){var i,n,r,o;const s=null!==(i=e.keepAlive)&&void 0!==i?i:null,a=null!==(n=e.register)&&void 0!==n?n:null,c=null!==(r=e.unregister)&&void 0!==r?r:null,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 i=generateEphemeralToken();return this.callbacksByToken[i]=t,null===(e=this.keepAlive)||void 0===e||e.retain(`${this.id}.${i}`),i}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 i=t.deref();i&&i.notify(...e)}))}}unregisterIfNeeded(){!this.hasObservers()&&this.isRegistered&&(this.isRegistered=!1,this.unregister())}async finalize(t){await this.removeObserver(t)}}class Observer{constructor(t,e,i={}){this.observerManager=t,this.token=e,this.options=i,i.stopsWhenFinalized&&Observer.finalizationRegistry.register(this,{observerManager:t,token:e},this)}get isStopped(){return void 0===this.token}stop(){const t=this.token;t&&(delete this.token,Observer.finalizationRegistry.unregister(this),this.observerManager.removeObserver(t))}static finalize(t){const{observerManager:e,token:i}=t;e.removeObserver(i)}}Observer.finalizationRegistry=new FinalizationRegistry(Observer.finalize);class Authenticator{constructor(t){this.keepAlive=t,this.status={isAuthenticated:!1,userID:null},this.loginSupported=!1,this.observerManager=new ObserverManager("AuthenticationStatusObservation",{keepAlive:t})}loginWithToken(t,e){throw new Error("Authenticator.loginWithToken() is abstract and must be implemented by subclasses.")}loginWithUsernameAndPassword(t,e,i){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})}"@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{constructor(t,e,i,n){super(t),this.loginSupported=!0,this.status={isAuthenticated:!1,userID:null},this.authClientPointer=e,this.ditto=new WeakRef(i),this.authenticationHandler=n,this.updateAndNotify(!1),OnlineAuthenticator.finalizationRegistry.register(this,e)}async loginWithToken(t,e){await dittoAuthClientLoginWithToken(this.authClientPointer,t,e)}async loginWithUsernameAndPassword(t,e,i){await dittoAuthClientLoginWithUsernameAndPassword(this.authClientPointer,t,e,i)}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.")}"@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 i=this.status.isAuthenticated,n=this.status.userID,r=dittoAuthClientIsWebValid(this.authClientPointer),o=dittoAuthClientUserID(this.authClientPointer),s={isAuthenticated:r,userID:o};if(this.status=s,t){!!i==!!r&&n===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,i){throw new Error("Can't login, authentication is not supported for the identity in use, please use an onlineWithAuthentication identity.")}logout(t){throw new Error("Can't logout, authentication is not supported for the identity in use, please use an onlineWithAuthentication identity.")}"@ditto.authenticationExpiring"(t){throw new Error(`Internal inconsistency, authentication is not available, yet the @ditto.authenticationExpiring() was called on authenticator: ${this}`)}"@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"];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:"[::]",port:4040},http:{isEnabled:!1,interfaceIP:"[::]",port:80,websocketSync:!0}},this.global={syncGroup: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}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,i){let n=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,n.getUint16(o))}function readUint32(){return commitRead(4,n.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 i=readLength(31&e);if(i<0||e>>5!==t)throw new Error("Invalid indefinite length element");return i}function appendUtf16Data(t,e){for(let i=0;i<e;++i){let i=readUint8();128&i&&(i<224?(i=(31&i)<<6|63&readUint8(),e-=1):i<240?(i=(15&i)<<12|(63&readUint8())<<6|63&readUint8(),e-=2):(i=(15&i)<<18|(63&readUint8())<<12|(63&readUint8())<<6|63&readUint8(),e-=3)),i<65536?t.push(i):(i-=65536,t.push(55296|i>>10),t.push(56320|1023&i))}}"function"==typeof e&&(tagValueFunction=e),"function"==typeof i&&(simpleValFunction=i);let s=function decodeItem(){let t,e,i=readUint8(),r=i>>5,s=31&i;if(7===r)switch(s){case 25:return function readFloat16(){let t=new ArrayBuffer(4),e=new DataView(t),i=readUint16(),n=32768&i,r=31744&i,o=1023&i;if(31744===r)r=261120;else if(0!==r)r+=114688;else if(0!==o)return(n?-1:1)*o*POW_2_24;return e.setUint32(0,n<<16|r<<13|o<<13),e.getFloat32(0)}();case 26:return function readFloat32(){return commitRead(4,n.getFloat32(o))}();case 27:return function readFloat64(){return commitRead(8,n.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 i=[],n=0;for(;(e=readIndefiniteStringLength(r))>=0;)n+=e,i.push(readArrayBuffer(e));let o=new Uint8Array(n),s=0;for(t=0;t<i.length;++t)o.set(i[t],s),s+=i[t].length;return o}return readArrayBuffer(e);case 3:let i=[];if(e<0)for(;(e=readIndefiniteStringLength(r))>=0;)appendUtf16Data(i,e);else appendUtf16Data(i,e);let n="";for(t=0;t<i.length;t+=8192)n+=String.fromCharCode.apply(null,i.slice(t,t+8192));return n;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,i=new ArrayBuffer(256),n=new DataView(i),r=new Uint8Array(i),o=0;function prepareWrite(t){let s=i.byteLength,a=o+t;for(;s<a;)s<<=1;if(s!==i.byteLength){let t=n;i=new ArrayBuffer(s),n=new DataView(i),r=new Uint8Array(i);let e=o+3>>2;for(let i=0;i<e;++i)n.setUint32(i<<2,t.getUint32(i<<2))}return e=t,n}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,i=(t-e)/POW_2_32,n=prepareWrite(8);n.setUint32(o,i),n.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 i=[];for(e=0;e<t.length;++e){let n=t.charCodeAt(e);n<128?i.push(n):n<2048?(i.push(192|n>>6),i.push(128|63&n)):n<55296||n>=57344?(i.push(224|n>>12),i.push(128|n>>6&63),i.push(128|63&n)):(n=(1023&n)<<10,n|=1023&t.charCodeAt(++e),n+=65536,i.push(240|n>>18),i.push(128|n>>12&63),i.push(128|n>>6&63),i.push(128|63&n))}return writeTypeAndLength(3,i.length),writeUint8Array(i);default:let n,r;if(Array.isArray(t))for(n=t.length,writeTypeAndLength(4,n),e=0;e<n;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 i=Object.keys(t);for(n=i.length,writeTypeAndLength(5,n),e=0;e<n;e+=1){let n=i[e];encodeItem(n),encodeItem(t[n])}}}}(t),"slice"in i)return i.slice(0,o);let s=new ArrayBuffer(o),a=new DataView(s);for(let t=0;t<o;++t)a.setUint8(t,n.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{constructor(t,e=!1,i=!1){const n=e?t:CBOR.encode(t),r=i?n:validateDocumentIDCBOR(n);if(!r)throw new Error(`Can't create DocumentID, passed in value is not valid: ${t}`);this.isValidated=!i,this["@ditto.cbor"]=r}get value(){let t=this["@ditto.value"];return void 0===t&&(t=CBOR.decode(this["@ditto.cbor"]),this["@ditto.value"]=t),t}equals(t){const e=this["@ditto.cbor"],i=t["@ditto.cbor"];if(e===i)return!0;if(!(e instanceof Uint8Array))return!1;if(!(i instanceof Uint8Array))return!1;if(e.length!==i.length)return!1;for(let t=0;t<e.length;t+=1)if(e[t]!==i[t])return!1;return!0}toString(){return documentIDQueryCompatible(this["@ditto.cbor"],"WithoutQuotes")}toBase64String(){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{constructor(t,e){this.ditto=t,this.token=e}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)),i=require("fs/promises");return i.copyFile(e,t,i.COPYFILE_EXCL)}}}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 i=t._len;if("number"!=typeof i||i<0)throw new Error("Invalid attachment token length");const n=t._meta;if("object"!=typeof n)throw new Error("Invalid attachment token meta");this.id=e,this.len=i,this.metadata=n}}class AttachmentFetcher{constructor(t,e,i){this.ditto=t,this.token=e,this.eventHandler=i||null,this.cancelTokenPromise=null;const n=i||function(){};this.attachment=new Promise(((i,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}),n({type:"Completed",attachment:e}),i(e)},onProgress:(t,e)=>{n({type:"Progress",totalBytes:e,downloadedBytes:t})},onDelete:()=>{this.eventHandler=null,this.cancelTokenPromise=null,n({type:"Deleted"}),i(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)}stop(){AttachmentFetcher.stopWithContextInfo({ditto:this.ditto,attachmentTokenID:this.token.id,cancelTokenPromise:this.cancelTokenPromise})}then(t,e){return this.attachment.then(t,e)}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{constructor(t,e,i,n,r,o){this.isCancelled=!1,this.query=e,this.queryArgsCBOR=i,this.collection=t,this.contextInfo={ditto:t.store.ditto,collectionName:t.name,query:e,queryArgsCBOR:i,orderBys:n,limit:r,offset:o},Subscription.add(this,this.contextInfo)}get collectionName(){return this.collection.name}cancel(){this.isCancelled||(this.isCancelled=!0,Subscription.remove(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,i){const n=t?new MutableCounter(privateToken$1):new Counter;return n.mutDoc=t,n.path=e,n.value=i,n}}class MutableCounter extends Counter{increment(t){const e=this.mutDoc,i=this.path;if(!e)throw new Error("Can't increment counter, only possible within the closure of a collection's update() method.");e.at(i)["@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{constructor(t){this["@ditto.value"]=t}get value(){return this["@ditto.value"]}static"@ditto.create"(t,e,i){const n=t?new MutableRegister(i,privateToken):new Register(i);return n["@ditto.mutableDocument"]=t,n["@ditto.path"]=e,n["@ditto.value"]=i,n}}class MutableRegister extends Register{get value(){return super.value}set value(t){this.set(t)}set(t){const e=this["@ditto.mutableDocument"],i=this["@ditto.path"];e.at(i)["@ditto.set"](t),this["@ditto.value"]=t}constructor(t){if(arguments[1]!==privateToken)throw new Error("MutableRegister constructor is for internal use only.");super(t)}}class RGA{constructor(t=[]){this["@ditto.value"]=t}get value(){return this["@ditto.value"]}static"@ditto.create"(t,e){const i=new RGA(e);return i["@ditto.path"]=t,i["@ditto.value"]=e,i}}class UpdateResult{constructor(t,e,i,n,r){this.type=t,this.docID=e,this.path=i,void 0!==n&&(this.value=n),void 0!==r&&(this.amount=r)}static set(t,e,i){return new UpdateResult("set",t,e,i,void 0)}static incremented(t,e,i){return new UpdateResult("incremented",t,e,void 0,i)}static removed(t,e){return new UpdateResult("removed",t,e,void 0,void 0)}}function augmentJSONValue(t,e,i){if(t&&"object"==typeof t){if(Array.isArray(t))return t.map(((t,n)=>augmentJSONValue(t,e,`${i}[${n}]`)));if(t[DittoCRDTTypeKey]===DittoCRDTType.counter)return Counter["@ditto.create"](e,i,t._value);if(t[DittoCRDTTypeKey]===DittoCRDTType.register)return Register["@ditto.create"](e,i,t._value);if(t[DittoCRDTTypeKey]===DittoCRDTType.rga){const n=augmentJSONValue(t._value,e,i);return RGA["@ditto.create"](i,n)}if(t[DittoCRDTTypeKey]===DittoCRDTType.attachment)return new AttachmentToken(t);for(const[n,r]of Object.entries(t))t[n]=augmentJSONValue(r,e,`${i}['${n}']`);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,i]of Object.entries(t))t[e]=desugarJSObject(i,!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 i;const n=null!==(i=e.isInitial)&&void 0!==i&&i;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 n?t:r}static evaluate(t,e,i={}){var n;const r=null!==(n=i.stopAtLastContainer)&&void 0!==n&&n,o={keyPath:t,object:e,options:{...i},coveredPath:null,nextPathComponent:null,remainingPath:t,value:e};return function recurse(t,e){if(""===e)return o.value=t,o;const{nextPathComponentRaw:i,nextPathComponent:n,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 i=e[0],n=e[1];return{nextPathComponentRaw:i,nextPathComponent:n,remainingPath:t.slice(n.length+1)}}const i=t.match(subscriptIndexRegExp);if(null!==i){const e=i[0],n=i[1];return{nextPathComponentRaw:e,nextPathComponent:parseInt(n),remainingPath:t.slice(n.length+2)}}const n=t.match(subscriptSingleQuoteKeyRegExp);if(null!==n){const e=n[0],i=n[1];return{nextPathComponentRaw:e,nextPathComponent:i,remainingPath:t.slice(i.length+4)}}const r=t.match(subscriptDoubleQuoteKeyRegExp);if(null!==r){const e=r[0],i=r[1];return{nextPathComponentRaw:e,nextPathComponent:i,remainingPath:t.slice(i.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=n,o.remainingPath=s,null===o.coveredPath||"number"==typeof i?o.coveredPath=i:o.coveredPath+=i,""===s&&r?(o.value=t,o):recurse(t[n],s)}(e,this.withLeadingDot(t))}constructor(){}}class DocumentPath{constructor(t,e,i){this.document=t,this.path=i?KeyPath.validate(e,{isInitial:!0}):e}at(t){if("string"==typeof t){const e=t,i=KeyPath.validate(e),n=KeyPath.withoutLeadingDot(`${this.path}${i}`);return new DocumentPath(this.document,n,!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}underlyingValueForPathType(t){const e=this.path,i=this.document,n=documentGetCBORWithPathType(documentBridge.pointerFor(i),e,t);return null!==n.cbor?CBOR.decode(n.cbor):void 0}}class MutableDocumentPath{constructor(t,e,i){this.mutableDocument=t,this.path=i?KeyPath.validate(e,{isInitial:!0}):e}at(t){if("string"==typeof t){const e=t,i=KeyPath.validate(e),n=KeyPath.withoutLeadingDot(`${this.path}${i}`);return new MutableDocumentPath(this.mutableDocument,n,!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"]()}underlyingValueForPathType(t){const e=this.path,i=this.mutableDocument,n=documentGetCBORWithPathType(mutableDocumentBridge.pointerFor(i),e,t);return null!==n.cbor?CBOR.decode(n.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 i=mutableDocumentBridge.pointerFor(this.mutableDocument),n=desugarJSObject(t,!1),r=CBOR.encode(n);e?documentSetCBORWithTimestamp(i,this.path,r,!0,0):documentSetCBOR(i,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,i=KeyPath.evaluate(this.path,e,{stopAtLastContainer:!0});t(i.value,i.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{constructor(){this["@ditto.updateResults"]=[]}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)}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{constructor(t,e){const i=t.map((t=>t.toString())).sort().join(", ");if(i!==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}}get(t){const e=(t instanceof DocumentID?t:new DocumentID(t)).toString();return this.updateResultsByDocumentIDString[e]}keys(){return this.documentIDs.slice()}}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{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}hash(t){return documentsHash(t.map((t=>documentBridge.pointerFor(t))))}hashMnemonic(t){return documentsHashMnemonic(t.map((t=>documentBridge.pointerFor(t))))}}class SingleDocumentLiveQueryEvent{constructor(t,e){this.isInitial=t,this.oldDocument=e}hash(t){return documentsHash(null===t?[]:[documentBridge.pointerFor(t)])}hashMnemonic(t){return documentsHashMnemonic(null===t?[]:[documentBridge.pointerFor(t)])}}class LiveQuery{constructor(t,e,i,n,r,o,s,a,c){this.query=t,this.queryArgs=e?Object.freeze({...e}):null,this.queryArgsCBOR=i,this.orderBys=n,this.limit=r,this.offset=o,this.collection=s,this.handler=c,a&&(this.subscription=a);const l=s.name,u=new WeakRef(s.store.ditto);let d;const signalNext=async()=>{const t=u.deref();if(t){const e=dittoBridge.pointerFor(t);await liveQuerySignalAvailableNext(e,d)}},h=dittoBridge.pointerFor(s.store.ditto);if(d=liveQueryRegister(h,l,t,i,this.orderBys,r,o,(t=>{const e=t.documents.map((t=>documentBridge.bridge(t)));let i;i=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,i,signalNext)})),!d)throw new Error("Internal inconsistency, couldn't create a valid live query ID.");this.liveQueryID=d,step((async()=>await liveQueryStart(h,d))),s.store.ditto.keepAlive.retain(`LiveQuery.${d}`)}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 i=dittoBridge.pointerFor(this.collection.store.ditto);null===(t=this.subscription)||void 0===t||t.cancel(),liveQueryStop(i,e)}}async signalNext(){const t=dittoBridge.pointerFor(this.collection.store.ditto);await liveQuerySignalAvailableNext(t,this.liveQueryID)}}class PendingCursorOperation{constructor(t,e,i){this.currentLimit=-1,this.currentOffset=0,this.orderBys=[],this.query=validateQuery(t),this.queryArgs=e?Object.freeze({...e}):null,this.collection=i,this.queryArgsCBOR=e?CBOR.encode(e):null}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 i=await writeTransaction(e),n=await collectionRemoveQueryStr(e,this.collection.name,i,t,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);return await writeTransactionCommit(e,i),n}))).map((t=>new DocumentID(t,!0)))}async evict(){const t=this.query,e=dittoBridge.pointerFor(this.collection.store.ditto);return(await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const i=await writeTransaction(e),n=await collectionEvictQueryStr(e,this.collection.name,i,t,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);return await writeTransactionCommit(e,i),n}))).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,i=dittoBridge.pointerFor(this.collection.store.ditto),n=await writeTransaction(i),r=await collectionExecQueryStr(i,this.collection.name,n,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,i=e.toString(),n=t["@ditto.updateResults"];if(a[i])throw new Error(`Internal inconsistency, update results for document ID as string already exist: ${i}`);s.push(e),a[i]=n,mutableDocumentBridge.pointerFor(t),mutableDocumentBridge.unregister(t)}return await collectionUpdateMultiple(i,this.collection.name,n,r),await writeTransactionCommit(i,n),new UpdateResultsMap(s,a)}))}_observe(t,e,i){const n=e?this.subscribe():null;const r=i?t:function wrappedHandler(e,i,n){try{return t.call(this,e,i)}finally{n()}};return new LiveQuery(this.query,this.queryArgs,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset,this.collection,n,r)}then(t,e){return this.exec().then(t,e)}}class PendingIDSpecificOperation{constructor(t,e){this.documentID=t,this.collection=e,this.documentIDCBOR=t.toCBOR()}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),i=await collectionRemove(t,this.collection.name,e,this.documentIDCBOR);return await writeTransactionCommit(t,e),i}))}async evict(){const t=dittoBridge.pointerFor(this.collection.store.ditto);return await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const e=await writeTransaction(t),i=await collectionEvict(t,this.collection.name,e,this.documentIDCBOR);return await writeTransactionCommit(t,e),i}))}async exec(){const t=dittoBridge.pointerFor(this.collection.store.ditto);return await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const e=await readTransaction(t),i=await collectionGet(t,this.collection.name,this.documentIDCBOR,e);let n;return i&&(n=documentBridge.bridge(i)),readTransactionFree(e),n}))}async update(t){const e=dittoBridge.pointerFor(this.collection.store.ditto),i=await readTransaction(e),n=await collectionGet(e,this.collection.name,this.documentIDCBOR,i);if(readTransactionFree(i),!n)throw new Error(`Can't update, document with ID '${this.documentID.toString()}' not found in collection named '${this.collection.name}'`);const r=mutableDocumentBridge.bridge(n,(()=>new MutableDocument));t(r),mutableDocumentBridge.unregister(r);const o=await writeTransaction(e);return await collectionUpdate(e,this.collection.name,o,n),await writeTransactionCommit(e,o),r["@ditto.updateResults"].slice()}_observe(t,e,i){const n=e?this.subscribe():null;return new LiveQuery(this.query,null,null,[],-1,0,this.collection,n,((e,n,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===n.isInitial&&n.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===n.isInitial&&n.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===n.isInitial&&n.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===n.isInitial&&n.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===n.isInitial&&n.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===n.isInitial?0:n.insertions.length+n.deletions.length+n.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===n.isInitial?void 0:n.oldDocuments[0],a=new SingleDocumentLiveQueryEvent(n.isInitial,s);if(i)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{constructor(t,e){this.name=t,this.store=e}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 i;const n=null!==(i=e.writeStrategy)&&void 0!==i?i:"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),u=CBOR.encode(l),d=await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>await collectionInsertValue(o,this.name,u,c,n)));return new DocumentID(d,!0)}async newAttachment(t,e={}){const i=this.store.ditto,n=dittoBridge.pointerFor(i),{id:r,len:o,handle:s}=await(async()=>{if("string"==typeof t)return dittoNewAttachmentFromFile(n,t,"Copy");if(t instanceof Uint8Array)return await dittoNewAttachmentFromBytes(n,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(i,c);return attachmentBridge.bridge(s,(()=>l),{throwIfAlreadyBridged:!0})}fetchAttachment(t,e){const i=this.store.ditto;return new AttachmentFetcher(i,t,e)}findByIDCBOR(t){const e=new DocumentID(t,!0,!0);return new PendingIDSpecificOperation(e,this)}}class CollectionsEvent{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}static initial(t){return new CollectionsEvent({isInitial:!0,collections:t,oldCollections:[],insertions:[],deletions:[],updates:[],moves:[]})}}class PendingCollectionsOperation{constructor(t){this.store=t,this.pendingCursorOperation=new PendingCursorOperation("true",null,new Collection("__collections",t))}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)}then(t,e){return this.exec().then(t,e)}_observe(t,e,i){const n=new WeakRef(this);return this.pendingCursorOperation._observe((function(e,r,o){const s=n.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})}i?t(c,o):t(c)}),e,i)}}function collectionsFromDocuments(t,e){const i=[];for(const n of t){const t=n.at("name").value;void 0!==t&&"string"==typeof t&&i.push(new Collection(t,e))}return i}class Store{constructor(t){this.ditto=t}collection(t){return new Collection(t,this)}collections(){return new PendingCollectionsOperation(this.ditto.store)}collectionNames(){return dittoGetCollectionNames(dittoBridge.pointerFor(this.ditto))}async registerLiveQueryWebhook(t,e,i){const n=validateQuery(e),r=await liveQueryWebhookRegister(dittoBridge.pointerFor(this.ditto),t,n,[],0,0,i);return new DocumentID(r,!0)}}function addressToString(t){return`${t.siteId}-${t.pubkey}`}class Presence{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)]})}get graph(){const t=dittoPresenceV3(dittoBridge.pointerFor(this.ditto));return JSON.parse(t)}observe(t){const e=this.observerManager.addObserver(t),i=new Observer(this.observerManager,e,{stopsWhenFinalized:!0});return t(this.graph),i}}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,i;return{networkID:t.network_id,deviceName:t.device_name,rssi:null!==(e=t.rssi)&&void 0!==e?e:void 0,approximateDistanceInMeters:null!==(i=t.approximate_distance_in_meters)&&void 0!==i?i:void 0,connections:t.connections}}))}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 i,n;switch(t){case"Bluetooth":i="BLE";break;case"Tcp":i="TCP";break;case"Awdl":i="AWDL";break;case"Mdns":i="MDNS"}switch(e){case"Unknown":n="Unknown";break;case"Ok":n="OK";break;case"GenericFailure":n="GenericFailure";break;case"AppInBackground":n="AppInBackground";break;case"MdnsFailure":n="MDNSFailure";break;case"TcpListenFailure":n="TCPListenFailure";break;case"NoBleCentralPermission":n="NoBLECentralPermission";break;case"NoBlePeripheralPermission":n="NoBLEPeripheralPermission";break;case"CannotEstablishConnection":n="CannotEstablishConnection";break;case"BleDisabled":n="BLEDisabled";break;case"NoBleHardware":n="NoBLEHardware";break;case"WifiDisabled":n="WiFiDisabled";break;case"TemporarilyUnavailable":n="TemporarilyUnavailable"}return[n,i]}}class Sync{constructor(t){this.bluetoothLETransportPointer=null,this.awdlTransportPointer=null,this.lanTransportPointer=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,i=stateFrom(this.parameters);this.updatePeerToPeerBluetoothLE(e,i),this.updatePeerToPeerAWDL(e,i),this.updatePeerToPeerLAN(e,i),this.updateListenTCP(e,i),this.updateListenHTTP(e,i),this.updateConnectTCPServers(e,i),this.updateConnectWebsocketURLs(e,i),this.updateGlobal(e,i),this.state=i}updatePeerToPeerBluetoothLE(t,e){const i=dittoBridge.pointerFor(this.ditto),n=t.effectiveTransportConfig.peerToPeer.bluetoothLE,r=e.effectiveTransportConfig.peerToPeer.bluetoothLE,o=!n.isEnabled&&r.isEnabled,s=n.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){if(o){if(!bleIsAvailable(i))throw new Error("Can't start P2P BluetoothLE transport because not available.");this.bluetoothLETransportPointer=bleCreate(i)}s&&(bleDestroy(this.bluetoothLETransportPointer),delete this.bluetoothLETransportPointer)}else{if(o){const t={clientTransport:dittoAddInternalBLEClientTransport(i),serverTransport:dittoAddInternalBLEServerTransport(i)};this.bluetoothLETransportPointer=t}if(s){const t=this.bluetoothLETransportPointer,{clientTransport:e,serverTransport:i}=t;BLEServerFreeHandle(i),BLEClientFreeHandle(e),this.bluetoothLETransportPointer=null}}}updatePeerToPeerAWDL(t,e){const i=dittoBridge.pointerFor(this.ditto),n=t.effectiveTransportConfig.peerToPeer.awdl,r=e.effectiveTransportConfig.peerToPeer.awdl,o=!n.isEnabled&&r.isEnabled,s=n.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(i))throw new Error("Can't start P2P AWDL transport because not available.");this.awdlTransportPointer=awdlCreate(i)}s&&(awdlDestroy(this.awdlTransportPointer),this.awdlTransportPointer=null)}updatePeerToPeerLAN(t,e){const i=dittoBridge.pointerFor(this.ditto),n=t.effectiveTransportConfig.peerToPeer.lan,r=e.effectiveTransportConfig.peerToPeer.lan;if(n.isEnabled&&(n.isMdnsEnabled&&(lanDestroy(this.lanTransportPointer),delete this.lanTransportPointer),n.isMulticastEnabled&&dittoRemoveMulticastTransport(i)),r.isEnabled){if(r.isMdnsEnabled){if(!lanIsAvailable(i))throw new Error("Can't start P2P LAN transport because not available.");this.lanTransportPointer=lanCreate(i)}r.isMulticastEnabled&&dittoAddMulticastTransport(i)}}updateListenTCP(t,e){const i=t.effectiveTransportConfig.listen.tcp,n=e.effectiveTransportConfig.listen.tcp;if(TransportConfig.areListenTCPsEqual(n,i))return;const r=dittoBridge.pointerFor(this.ditto);i.isEnabled&&dittoStopTCPServer(r),n.isEnabled&&dittoStartTCPServer(r,`${n.interfaceIP}:${n.port}`)}updateListenHTTP(t,e){const i=t.effectiveTransportConfig.listen.http,n=e.effectiveTransportConfig.listen.http;if(TransportConfig.areListenHTTPsEqual(i,n))return;const r=dittoBridge.pointerFor(this.ditto);i.isEnabled&&dittoStopHTTPServer(r),n.isEnabled&&dittoStartHTTPServer(r,`${n.interfaceIP}:${n.port}`,n.staticContentPath||null,n.websocketSync?"Enabled":"Disabled",n.tlsCertificatePath||null,n.tlsKeyPath||null)}updateConnectTCPServers(t,e){const i=Object.getOwnPropertyNames(this.staticTCPClientsByAddress),n=e.effectiveTransportConfig.connect.tcpServers,r=new Set(n);for(const t of i)r.delete(t);const o=new Set(i);for(const t of n)o.delete(t);const s=r.values(),a=o.values();for(const t of s){const e=addStaticTCPClient(dittoBridge.pointerFor(this.ditto),t),i=staticTCPClientBridge.bridge(e);this.staticTCPClientsByAddress[t]=i}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 i=staticTCPClientBridge.pointerFor(e);staticTCPClientBridge.unregister(e),staticTCPClientFreeHandle(i),delete this.staticTCPClientsByAddress[t]}}updateConnectWebsocketURLs(t,e){const i=Object.getOwnPropertyNames(this.websocketClientsByURL),n=e.effectiveTransportConfig.connect.websocketURLs.slice(),r=new Set(n);for(const t of i)r.delete(t);const o=new Set(i);for(const t of n)o.delete(t);const s=r.values(),a=o.values();for(const t of s){const e=addWebsocketClient(dittoBridge.pointerFor(this.ditto),t),i=websocketClientBridge.bridge(e);this.websocketClientsByURL[t]=i}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 i=websocketClientBridge.pointerFor(e);websocketClientBridge.unregister(e),websocketClientFreeHandle(i),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 i=t.transportConfig.copy(),n=t.identity,r=t.isSyncActive,o=t.isX509Valid,s=t.isWebValid;let a,c;i.connect.tcpServers,i.connect.websocketURLs;let l=!1;if("onlinePlayground"!==n.type&&"onlineWithAuthentication"!==n.type||(a=n.appID,c=null!==(e=n.customDittoCloudURL)&&void 0!==e?e:null,l=!n.hasOwnProperty("enableDittoCloudSync")||n.enableDittoCloudSync),r&&o||(i.peerToPeer.bluetoothLE.isEnabled=!1,i.peerToPeer.awdl.isEnabled=!1,i.peerToPeer.lan.isEnabled=!1,i.listen.tcp.isEnabled=!1,i.connect.tcpServers=[]),r&&s||(i.connect.websocketURLs=[]),r||(i.listen.http.isEnabled=!1),r&&s&&l){const t=null!=c?c:defaultDittoCloudURL(a);i.connect.websocketURLs.push(t)}return i.peerToPeer.lan.isEnabled&&!i.listen.tcp.isEnabled&&(i.listen.tcp.isEnabled=!0,i.listen.tcp.interfaceIP="[::]",i.listen.tcp.port=0),{underlyingSyncParameters:t,effectiveTransportConfig:i.freeze()}}class Ditto{constructor(t,e){this.isWebValid=!1,this.isX509Valid=!1;const i=null!=t?t:{type:"offlinePlayground",appID:""},n=e&&e.trim().length>0?e:"ditto",r=Object.freeze(this.validateIdentity(i));this.identity=Object.freeze(r),this.path=n;require("fs").mkdirSync(n,{recursive:!0});{const t=require("os");this.deviceName=t.hostname()}this.keepAlive=new KeepAlive;const o=uninitializedDittoMake(n);let s=null;const a=new WeakRef(this),c=(()=>{var t,e,i;if("offlinePlayground"===r.type)return dittoAuthClientMakeForDevelopment(n,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(n,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(n,r.appID,r.token,t)}if("onlineWithAuthentication"===r.type){const t=null!==(i=r.customAuthURL)&&void 0!==i?i: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(n,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),u=dittoAuthClientIsX509Valid(c),d=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=d,this.transportConfig=p.copy().freeze(),this.isX509Valid=u,this.isWebValid=l,this.sync=new Sync(this),this.sync.update({isSyncActive:!1,isX509Valid:u,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)}get sdkVersion(){return dittoGetSDKVersion(dittoBridge.pointerFor(this))}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:i}=verifyLicense(t);if("LicenseOk"!==e)throw this.isActivated=!1,new Error(i);this.isActivated=!0}}setTransportConfig(t){this.transportConfig,this.transportConfig=t.copy().freeze();const e=this.transportConfig,i=this.identity,n=this.isWebValid,r=this.isX509Valid;this.sync.update({transportConfig:e,identity:i,isWebValid:n,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 i=this.transportConfig,n=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:i,identity:n,isWebValid:t,isX509Valid:e,isSyncActive:r})}validateIdentity(t){const e={...t};t.appName;const i=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===i)throw new Error("Property .appID must be given for identity, but isn't.");if(void 0!==i&&"string"!=typeof i)throw new Error(`Property .appID must be be of type string, but is of type '${typeof i}': ${i}`);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 i=this.isWebValid,n=this.isX509Valid,r=this.identity,o=this.transportConfig;dittoSetDeviceName(e,this.deviceName),this.sync.update({identity:r,transportConfig:o,isWebValid:i,isX509Valid:n,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
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dittolive/ditto",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "3.0.0-alpha1",
|
|
4
4
|
"description": "Ditto is a cross-platform embeddable NoSQL database that can sync with or without an internet connection.",
|
|
5
5
|
"homepage": "https://ditto.live",
|
|
6
6
|
"license": "SEE LICENSE IN LICENSE.md",
|