@dittolive/ditto 1.1.1 → 1.1.2

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/web/ditto.umd.js CHANGED
@@ -1,2 +1,2 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).Ditto={})}(this,(function(t){"use strict";class Meta{constructor(t,e,n){this.type=t,this.object=e,this.pointer=n}toString(){return`{ Meta | type: ${this.type.name}, object: ${this.object.deref()}, FFI address: ${this.pointer.addr}, FFI type: ${this.pointer.type} }`}}class Bridge{constructor(t,n,r={}){this.type=t,this.release=n,this.metaByAddrMap=e,this.finalizationRegistry=new FinalizationRegistry(this.finalize.bind(this))}pointerFor(t){return t["@ditto.ptr"]}objectFor(t){const e=this.metaByAddrMap[t.addr];if(!e)return;if(e.type!==this.type)throw new Error(`Can't return object for pointer, pointer is associated with an object of type ${e.type} but this bridge is configured for ${this.type}`);const n=e.object.deref();if(!n)throw new Error(`Internal inconsistency, found a meta entry for an object whose object is undefined (garbage collected): ${t}`);return n}bridge(t,e,n={}){const r=n.throwIfAlreadyBridged,i=this.objectFor(t);if(i&&r)throw new Error(`Can't bridge, pointer has already been bridged: ${JSON.stringify(t)}`);if(i)return i;e||(e=()=>Reflect.construct(this.type,[]));const o=e();if(!o)throw new Error(`Can't bridge, expected create() to return an object but got: ${o}`);return this.register(o,t),o}register(t,e){const n=t.constructor,r=this.type;if(n!==r)throw new Error(`Can't register, bridge is configured for type ${r.name} but passed in object is of type ${n.name}`);const i=this.pointerFor(t),o=this.metaByAddrMap[e.addr];if(i&&o)throw new Error(`Can't register, an object for the passed in pointer has previously been registered: ${o.pointer}`);if(i&&!o)throw new Error(`Internal inconsistency, trying to register an object which has an associated pointer but no meta entry: ${t}`);if(!i&&o)throw new Error(`Internal inconsistency, trying to register an object which has a meta entry but no associated pointer: ${t}`);const a=new Meta(n,new WeakRef(t),e);t["@ditto.ptr"]=e,this.metaByAddrMap[a.pointer.addr]=a,this.finalizationRegistry.register(t,e,t)}unregister(t){const e=t.constructor,n=this.type;if(e!==n)throw new Error(`Can't unregister, bridge is configured for type ${n.name} but passed in object is of type ${e.name}`);const r=this.pointerFor(t);if(!r)throw new Error(`Can't unregister, object that has not been registered before: ${t}`);const i=this.metaByAddrMap[r.addr];if(!i)throw new Error(`Internal inconsistency, trying to unregister an object which has an associated pointer but no meta entry: ${t}`);if(i.type!==n)throw new Error(`Internal inconsistency, trying to unregister an object that has a meta entry with a different type than that of the bridge: ${i}`);if(!i.object.deref())throw new Error(`Internal inconsistency, trying to unregister an object that has a meta entry whose object is undfined (garbage collected): ${i}`);if(i.object.deref()!==t)throw new Error(`Internal inconsistency, trying to unregister an object that has a meta entry holding a different object: ${i}`);this.finalizationRegistry.unregister(t),delete this.metaByAddrMap[r.addr],delete t["@ditto.ptr"]}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)}}const e={},n=!0;function validateNumber(t,e={}){var n;const r=null!==(n=e.errorMessagePrefix)&&void 0!==n?n:"Number validation failed:",i=!!e.integer,o=e.min,a=e.max,s=e.minX,c=e.maxX;if("number"!=typeof t)throw new Error(`${r} '${t}' is not a number.`);if(i&&Math.floor(t)!==t)throw new Error(`${r} '${t}' is not an integer.`);if(void 0!==o&&t<o)throw new Error(`${r} '${t}' must be >= ${o}.`);if(void 0!==a&&t>a)throw new Error(`${r} '${t}' must be <= ${a}.`);if(void 0!==s&&t<=s)throw new Error(`${r} '${t}' must be > ${s}.`);if(void 0!==c&&t>=c)throw new Error(`${r} '${t}' must be < ${c}.`);return t}function validateQuery(t,e={}){var n;const r=null!==(n=e.errorMessagePrefix)&&void 0!==n?n:"Query validation failed,";if("string"!=typeof t)throw new Error(`${r} query is not a string: ${t}`);if(""===t)throw new Error(`${r} query is an empty string.`);const i=t.trim();if(""===i)throw new Error(`${r} query contains only whitespace characters.`);return i}const r=new Bridge(class StaticTCPClient{},staticTCPClientFreeHandle),i=new Bridge(class WebsocketClient{},websocketClientFreeHandle);const o=async function step(t){return await function sleep(t){return new Promise(((e,n)=>{setTimeout(e,t)}))}(0),t()};let a;const s=new Array(32).fill(void 0);function getObject(t){return s[t]}s.push(void 0,null,!0,!1);let c=s.length;function takeObject(t){const e=getObject(t);return function dropObject(t){t<36||(s[t]=c,c=t)}(t),e}let u=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});u.decode();let d=null;function getUint8Memory0(){return null!==d&&d.buffer===a.memory.buffer||(d=new Uint8Array(a.memory.buffer)),d}function getStringFromWasm0(t,e){return u.decode(getUint8Memory0().subarray(t,t+e))}function addHeapObject(t){c===s.length&&s.push(s.length+1);const e=c;return c=s[e],s[e]=t,e}let l=0,h=new TextEncoder("utf-8");const b="function"==typeof h.encodeInto?function(t,e){return h.encodeInto(t,e)}:function(t,e){const n=h.encode(t);return e.set(n),{read:t.length,written:n.length}};function passStringToWasm0(t,e,n){if(void 0===n){const n=h.encode(t),r=e(n.length);return getUint8Memory0().subarray(r,r+n.length).set(n),l=n.length,r}let r=t.length,i=e(r);const o=getUint8Memory0();let a=0;for(;a<r;a++){const e=t.charCodeAt(a);if(e>127)break;o[i+a]=e}if(a!==r){0!==a&&(t=t.slice(a)),i=n(i,r,r=a+3*t.length);const e=getUint8Memory0().subarray(i+a,i+r);a+=b(t,e).written}return l=a,i}let _=null;function getInt32Memory0(){return null!==_&&_.buffer===a.memory.buffer||(_=new Int32Array(a.memory.buffer)),_}function debugString(t){const e=typeof t;if("number"==e||"boolean"==e||null==t)return`${t}`;if("string"==e)return`"${t}"`;if("symbol"==e){const e=t.description;return null==e?"Symbol":`Symbol(${e})`}if("function"==e){const e=t.name;return"string"==typeof e&&e.length>0?`Function(${e})`:"Function"}if(Array.isArray(t)){const e=t.length;let n="[";e>0&&(n+=debugString(t[0]));for(let r=1;r<e;r++)n+=", "+debugString(t[r]);return n+="]",n}const n=/\[object ([^\]]+)\]/.exec(toString.call(t));let r;if(!(n.length>1))return toString.call(t);if(r=n[1],"Object"==r)try{return"Object("+JSON.stringify(t)+")"}catch(t){return"Object"}return t instanceof Error?`${t.name}: ${t.message}\n${t.stack}`:r}const f=new FinalizationRegistry((t=>{a.__wbindgen_export_2.get(t.dtor)(t.a,t.b)}));function makeMutClosure(t,e,n,r){const i={a:t,b:e,cnt:1,dtor:n},real=(...t)=>{i.cnt++;const e=i.a;i.a=0;try{return r(e,i.b,...t)}finally{0==--i.cnt?(a.__wbindgen_export_2.get(i.dtor)(e,i.b),f.unregister(i)):i.a=e}};return real.original=i,f.register(real,i,i),real}function __wbg_adapter_36(t,e,n){a._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__hcb8d91858ad73b23(t,e,addHeapObject(n))}function __wbg_adapter_39(t,e){a._dyn_core__ops__function__FnMut_____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__h96b039d0794c6fba(t,e)}function __wbg_adapter_42(t,e,n){a._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__hba532b687780d9b0(t,e,addHeapObject(n))}function __wbg_adapter_45(t,e){a._dyn_core__ops__function__FnMut_____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__ha31b6b51054a23b1(t,e)}function __wbg_adapter_48(t,e,n){a._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__h12036a797c03dada(t,e,addHeapObject(n))}function ditto_register_transport_condition_changed_callback(t,e){return takeObject(a.ditto_register_transport_condition_changed_callback(addHeapObject(t),addHeapObject(e)))}function ditto_logger_set_custom_log_cb(t){return takeObject(a.ditto_logger_set_custom_log_cb(addHeapObject(t)))}function handleError(t,e){try{return t.apply(this,e)}catch(t){a.__wbindgen_exn_store(addHeapObject(t))}}function getArrayU8FromWasm0(t,e){return getUint8Memory0().subarray(t/1,t/1+e)}function boxCStringIntoString(t){return takeObject(a.boxCStringIntoString(addHeapObject(t)))}function boxCBytesIntoBuffer(t){return takeObject(a.boxCBytesIntoBuffer(addHeapObject(t)))}function withOutPtr$1(t,e){return takeObject(a.withOutPtr(addHeapObject(t),addHeapObject(e)))}function withOutBoxCBytes(t){return takeObject(a.withOutBoxCBytes(addHeapObject(t)))}async function init$3(t){if(void 0===t)throw new Error("Can't load ditto.wasm, expected module to be provided at initialization time but got nothing.");const e={wbg:{}};e.wbg.__wbindgen_object_drop_ref=function(t){takeObject(t)},e.wbg.__wbindgen_string_new=function(t,e){return addHeapObject(getStringFromWasm0(t,e))},e.wbg.__wbindgen_cb_drop=function(t){const e=takeObject(t).original;if(1==e.cnt--)return e.a=0,!0;return!1},e.wbg.__wbg_log_fbcf63c42b370e42=function(t,e){try{console.log(getStringFromWasm0(t,e))}finally{a.__wbindgen_free(t,e)}},e.wbg.__wbindgen_json_serialize=function(t,e){const n=getObject(e);var r=passStringToWasm0(JSON.stringify(void 0===n?null:n),a.__wbindgen_malloc,a.__wbindgen_realloc),i=l;getInt32Memory0()[t/4+1]=i,getInt32Memory0()[t/4+0]=r},e.wbg.__wbg_new_693216e109162396=function(){return addHeapObject(new Error)},e.wbg.__wbg_stack_0ddaca5d1abfb52f=function(t,e){var n=passStringToWasm0(getObject(e).stack,a.__wbindgen_malloc,a.__wbindgen_realloc),r=l;getInt32Memory0()[t/4+1]=r,getInt32Memory0()[t/4+0]=n},e.wbg.__wbg_error_09919627ac0992f5=function(t,e){try{console.error(getStringFromWasm0(t,e))}finally{a.__wbindgen_free(t,e)}},e.wbg.__wbindgen_is_string=function(t){return"string"==typeof getObject(t)},e.wbg.__wbindgen_string_get=function(t,e){const n=getObject(e);var r="string"==typeof n?n:void 0,i=function isLikeNone(t){return null==t}(r)?0:passStringToWasm0(r,a.__wbindgen_malloc,a.__wbindgen_realloc),o=l;getInt32Memory0()[t/4+1]=o,getInt32Memory0()[t/4+0]=i},e.wbg.__wbindgen_object_clone_ref=function(t){return addHeapObject(getObject(t))},e.wbg.__wbg_fetch_d6391b3bc62838b4=function(t){return addHeapObject(fetch(getObject(t)))},e.wbg.__wbg_Window_2b37b61fe0cb894b=function(t){return addHeapObject(getObject(t).Window)},e.wbg.__wbindgen_is_undefined=function(t){return void 0===getObject(t)},e.wbg.__wbg_WorkerGlobalScope_da7fa0bf3cb27800=function(t){return addHeapObject(getObject(t).WorkerGlobalScope)},e.wbg.__wbg_randomFillSync_64cc7d048f228ca8=function(){return handleError((function(t,e,n){getObject(t).randomFillSync(getArrayU8FromWasm0(e,n))}),arguments)},e.wbg.__wbg_getRandomValues_98117e9a7e993920=function(){return handleError((function(t,e){getObject(t).getRandomValues(getObject(e))}),arguments)},e.wbg.__wbg_process_2f24d6544ea7b200=function(t){return addHeapObject(getObject(t).process)},e.wbg.__wbindgen_is_object=function(t){const e=getObject(t);return"object"==typeof e&&null!==e},e.wbg.__wbg_versions_6164651e75405d4a=function(t){return addHeapObject(getObject(t).versions)},e.wbg.__wbg_node_4b517d861cbcb3bc=function(t){return addHeapObject(getObject(t).node)},e.wbg.__wbg_modulerequire_3440a4bcf44437db=function(){return handleError((function(t,e){return addHeapObject(r.require(getStringFromWasm0(t,e)))}),arguments)},e.wbg.__wbg_crypto_98fc271021c7d2ad=function(t){return addHeapObject(getObject(t).crypto)},e.wbg.__wbg_msCrypto_a2cdb043d2bfe57f=function(t){return addHeapObject(getObject(t).msCrypto)},e.wbg.__wbg_clearInterval_f94c74cd3759378b=function(t,e){getObject(t).clearInterval(e)},e.wbg.__wbg_clearTimeout_2c1ba0016d8bca41=function(t,e){getObject(t).clearTimeout(e)},e.wbg.__wbg_setInterval_ec2d9dc4a54a6566=function(){return handleError((function(t,e,n){return getObject(t).setInterval(getObject(e),n)}),arguments)},e.wbg.__wbg_setTimeout_df66d951b1726b78=function(){return handleError((function(t,e,n){return getObject(t).setTimeout(getObject(e),n)}),arguments)},e.wbg.__wbg_readyState_d14de08ffb5783f5=function(t){return getObject(t).readyState},e.wbg.__wbg_setonopen_33b75427f7db7ce1=function(t,e){getObject(t).onopen=getObject(e)},e.wbg.__wbg_setonerror_cb55f0521ac0da3a=function(t,e){getObject(t).onerror=getObject(e)},e.wbg.__wbg_setonclose_7094f96283d130e0=function(t,e){getObject(t).onclose=getObject(e)},e.wbg.__wbg_setonmessage_ca5f75e4a84134ef=function(t,e){getObject(t).onmessage=getObject(e)},e.wbg.__wbg_setbinaryType_c9a67ad8bb4125af=function(t,e){getObject(t).binaryType=takeObject(e)},e.wbg.__wbg_new_982fe22cd93d67f7=function(){return handleError((function(t,e){return addHeapObject(new WebSocket(getStringFromWasm0(t,e)))}),arguments)},e.wbg.__wbg_newwithstrsequence_15aec70da899280b=function(){return handleError((function(t,e,n){return addHeapObject(new WebSocket(getStringFromWasm0(t,e),getObject(n)))}),arguments)},e.wbg.__wbg_close_f2a10c1de90df5f0=function(){return handleError((function(t){getObject(t).close()}),arguments)},e.wbg.__wbg_send_503c2e7652e95bf5=function(){return handleError((function(t,e,n){getObject(t).send(getStringFromWasm0(e,n))}),arguments)},e.wbg.__wbg_send_73ab09dbae2da3c3=function(){return handleError((function(t,e,n){getObject(t).send(getArrayU8FromWasm0(e,n))}),arguments)},e.wbg.__wbg_new_9c35e8e8b09fb4a3=function(){return handleError((function(){return addHeapObject(new Headers)}),arguments)},e.wbg.__wbg_append_fb85316567f7a798=function(){return handleError((function(t,e,n,r,i){getObject(t).append(getStringFromWasm0(e,n),getStringFromWasm0(r,i))}),arguments)},e.wbg.__wbg_instanceof_Response_e1b11afbefa5b563=function(t){return getObject(t)instanceof Response},e.wbg.__wbg_url_50e0bdb6051741be=function(t,e){var n=passStringToWasm0(getObject(e).url,a.__wbindgen_malloc,a.__wbindgen_realloc),r=l;getInt32Memory0()[t/4+1]=r,getInt32Memory0()[t/4+0]=n},e.wbg.__wbg_status_6d8bb444ddc5a7b2=function(t){return getObject(t).status},e.wbg.__wbg_headers_5ffa990806e04cfc=function(t){return addHeapObject(getObject(t).headers)},e.wbg.__wbg_arrayBuffer_b8937ed04beb0d36=function(){return handleError((function(t){return addHeapObject(getObject(t).arrayBuffer())}),arguments)},e.wbg.__wbg_code_18a1e10cf380ddc6=function(t){return getObject(t).code},e.wbg.__wbg_clearInterval_708ee6c3f45bf733=function(t,e){getObject(t).clearInterval(e)},e.wbg.__wbg_clearTimeout_c1f246d6874c0679=function(t,e){getObject(t).clearTimeout(e)},e.wbg.__wbg_fetch_b4e81012e07ff95a=function(t,e){return addHeapObject(getObject(t).fetch(getObject(e)))},e.wbg.__wbg_setInterval_a02797f5ab1c7eb1=function(){return handleError((function(t,e,n){return getObject(t).setInterval(getObject(e),n)}),arguments)},e.wbg.__wbg_setTimeout_5314850184d61a44=function(){return handleError((function(t,e,n){return getObject(t).setTimeout(getObject(e),n)}),arguments)},e.wbg.__wbg_wasClean_f06e0966f0a58bfa=function(t){return getObject(t).wasClean},e.wbg.__wbg_code_c8c420857439c0b4=function(t){return getObject(t).code},e.wbg.__wbg_reason_a10c58463722f72e=function(t,e){var n=passStringToWasm0(getObject(e).reason,a.__wbindgen_malloc,a.__wbindgen_realloc),r=l;getInt32Memory0()[t/4+1]=r,getInt32Memory0()[t/4+0]=n},e.wbg.__wbg_now_559193109055ebad=function(t){return getObject(t).now()},e.wbg.__wbg_data_9e55e7d79ab13ef1=function(t){return addHeapObject(getObject(t).data)},e.wbg.__wbg_newwithstrandinit_9b0fa00478c37287=function(){return handleError((function(t,e,n){return addHeapObject(new Request(getStringFromWasm0(t,e),getObject(n)))}),arguments)},e.wbg.__wbg_instanceof_Blob_da9f4ebaadaae9ed=function(t){return getObject(t)instanceof Blob},e.wbg.__wbg_mksendret_2ddb0c3d74066b91=function(){return addHeapObject((function send_ret(t){return t}))},e.wbg.__wbg_trydownsize_6469cbea84321086=function(t){return addHeapObject(function try_downsize(t){switch(typeof t){case"bigint":if(-Number.MAX_SAFE_INTEGER<=t&&t<=Number.MAX_SAFE_INTEGER)return Number(t);case"number":return t;default:throw new Error(`number or bigint expected, got \`${t}\``)}}(takeObject(t)))},e.wbg.__wbg_isnumber_9dd7158c4e98db56=function(t){return function is_number(t){return"number"==typeof t}(getObject(t))},e.wbg.__wbg_tostring_e3961886d1042b76=function(t,e){var n=passStringToWasm0(function to_string(t){return t.toString()}(getObject(e)),a.__wbindgen_malloc,a.__wbindgen_realloc),r=l;getInt32Memory0()[t/4+1]=r,getInt32Memory0()[t/4+0]=n},e.wbg.__wbg_fromstring_02bfb2e556c6cc4c=function(t,e){return addHeapObject(function from_string(t){return BigInt(t)}(getStringFromWasm0(t,e)))},e.wbg.__wbg_getelement_8de75a26955a9ca9=function(t,e){return addHeapObject(function get_element(t,e){return t[e]}(getObject(t),e>>>0))},e.wbg.__wbg_typeof_005a8c22f80d0545=function(t,e){var n=passStringToWasm0(function typeof_(t){return typeof t}(getObject(e)),a.__wbindgen_malloc,a.__wbindgen_realloc),r=l;getInt32Memory0()[t/4+1]=r,getInt32Memory0()[t/4+0]=n},e.wbg.__wbindgen_json_parse=function(t,e){return addHeapObject(JSON.parse(getStringFromWasm0(t,e)))},e.wbg.__wbindgen_number_new=function(t){return addHeapObject(t)},e.wbg.__wbindgen_is_null=function(t){return null===getObject(t)},e.wbg.__wbg_new_949bbc1147195c4e=function(){return addHeapObject(new Array)},e.wbg.__wbg_valueOf_9578284a568a094f=function(t){return getObject(t).valueOf()},e.wbg.__wbindgen_is_function=function(t){return"function"==typeof getObject(t)},e.wbg.__wbg_newnoargs_be86524d73f67598=function(t,e){return addHeapObject(new Function(getStringFromWasm0(t,e)))},e.wbg.__wbg_next_c4151d46d5fa7097=function(t){return addHeapObject(getObject(t).next)},e.wbg.__wbg_next_7720502039b96d00=function(){return handleError((function(t){return addHeapObject(getObject(t).next())}),arguments)},e.wbg.__wbg_done_b06cf0578e89ff68=function(t){return getObject(t).done},e.wbg.__wbg_value_e74a542443d92451=function(t){return addHeapObject(getObject(t).value)},e.wbg.__wbg_iterator_4fc4ce93e6b92958=function(){return addHeapObject(Symbol.iterator)},e.wbg.__wbg_get_4d0f21c2f823742e=function(){return handleError((function(t,e){return addHeapObject(Reflect.get(getObject(t),getObject(e)))}),arguments)},e.wbg.__wbg_call_888d259a5fefc347=function(){return handleError((function(t,e){return addHeapObject(getObject(t).call(getObject(e)))}),arguments)},e.wbg.__wbg_new_0b83d3df67ecb33e=function(){return addHeapObject(new Object)},e.wbg.__wbg_push_284486ca27c6aa8b=function(t,e){return getObject(t).push(getObject(e))},e.wbg.__wbg_instanceof_ArrayBuffer_764b6d4119231cb3=function(t){return getObject(t)instanceof ArrayBuffer},e.wbg.__wbg_apply_7cfa6ebf144990a5=function(){return handleError((function(t,e,n){return addHeapObject(getObject(t).apply(getObject(e),getObject(n)))}),arguments)},e.wbg.__wbg_call_346669c262382ad7=function(){return handleError((function(t,e,n){return addHeapObject(getObject(t).call(getObject(e),getObject(n)))}),arguments)},e.wbg.__wbg_valueOf_99d85ac83228d11b=function(t){return getObject(t).valueOf()},e.wbg.__wbg_getTime_10d33f4f2959e5dd=function(t){return getObject(t).getTime()},e.wbg.__wbg_new0_fd3a3a290b25cdac=function(){return addHeapObject(new Date)},e.wbg.__wbg_now_af172eabe2e041ad=function(){return Date.now()},e.wbg.__wbg_instanceof_Object_66786225e0dbc8ba=function(t){return getObject(t)instanceof Object},e.wbg.__wbg_new_b1d61b5687f5e73a=function(t,e){try{var n={a:t,b:e},r=new Promise(((t,e)=>{const r=n.a;n.a=0;try{return function __wbg_adapter_327(t,e,n,r){a.wasm_bindgen__convert__closures__invoke2_mut__h1ddbd6d42d64ac99(t,e,addHeapObject(n),addHeapObject(r))}(r,n.b,t,e)}finally{n.a=r}}));return addHeapObject(r)}finally{n.a=n.b=0}},e.wbg.__wbg_resolve_d23068002f584f22=function(t){return addHeapObject(Promise.resolve(getObject(t)))},e.wbg.__wbg_then_2fcac196782070cc=function(t,e){return addHeapObject(getObject(t).then(getObject(e)))},e.wbg.__wbg_then_8c2d62e8ae5978f7=function(t,e,n){return addHeapObject(getObject(t).then(getObject(e),getObject(n)))},e.wbg.__wbg_self_c6fbdfc2918d5e58=function(){return handleError((function(){return addHeapObject(self.self)}),arguments)},e.wbg.__wbg_window_baec038b5ab35c54=function(){return handleError((function(){return addHeapObject(window.window)}),arguments)},e.wbg.__wbg_globalThis_3f735a5746d41fbd=function(){return handleError((function(){return addHeapObject(globalThis.globalThis)}),arguments)},e.wbg.__wbg_global_1bc0b39582740e95=function(){return handleError((function(){return addHeapObject(global.global)}),arguments)},e.wbg.__wbg_buffer_397eaa4d72ee94dd=function(t){return addHeapObject(getObject(t).buffer)},e.wbg.__wbg_newwithbyteoffsetandlength_4b9b8c4e3f5adbff=function(t,e,n){return addHeapObject(new Uint8Array(getObject(t),e>>>0,n>>>0))},e.wbg.__wbg_new_a7ce447f15ff496f=function(t){return addHeapObject(new Uint8Array(getObject(t)))},e.wbg.__wbg_set_969ad0a60e51d320=function(t,e,n){getObject(t).set(getObject(e),n>>>0)},e.wbg.__wbg_length_1eb8fc608a0d4cdb=function(t){return getObject(t).length},e.wbg.__wbg_instanceof_Uint8Array_08a1f3a179095e76=function(t){return getObject(t)instanceof Uint8Array},e.wbg.__wbg_newwithlength_929232475839a482=function(t){return addHeapObject(new Uint8Array(t>>>0))},e.wbg.__wbg_subarray_8b658422a224f479=function(t,e,n){return addHeapObject(getObject(t).subarray(e>>>0,n>>>0))},e.wbg.__wbg_has_1275b5eec3dc7a7a=function(){return handleError((function(t,e){return Reflect.has(getObject(t),getObject(e))}),arguments)},e.wbg.__wbg_set_82a4e8a85e31ac42=function(){return handleError((function(t,e,n){return Reflect.set(getObject(t),getObject(e),getObject(n))}),arguments)},e.wbg.__wbindgen_debug_string=function(t,e){var n=passStringToWasm0(debugString(getObject(e)),a.__wbindgen_malloc,a.__wbindgen_realloc),r=l;getInt32Memory0()[t/4+1]=r,getInt32Memory0()[t/4+0]=n},e.wbg.__wbindgen_throw=function(t,e){throw new Error(getStringFromWasm0(t,e))},e.wbg.__wbindgen_rethrow=function(t){throw takeObject(t)},e.wbg.__wbindgen_memory=function(){return addHeapObject(a.memory)},e.wbg.__wbindgen_closure_wrapper1714=function(t,e,n){return addHeapObject(makeMutClosure(t,e,254,__wbg_adapter_36))},e.wbg.__wbindgen_closure_wrapper1716=function(t,e,n){return addHeapObject(makeMutClosure(t,e,254,__wbg_adapter_39))},e.wbg.__wbindgen_closure_wrapper7560=function(t,e,n){return addHeapObject(makeMutClosure(t,e,2460,__wbg_adapter_42))},e.wbg.__wbindgen_closure_wrapper11566=function(t,e,n){return addHeapObject(makeMutClosure(t,e,3623,__wbg_adapter_45))},e.wbg.__wbindgen_closure_wrapper13364=function(t,e,n){return addHeapObject(makeMutClosure(t,e,4088,__wbg_adapter_48))},("string"==typeof t||"function"==typeof Request&&t instanceof Request||"function"==typeof URL&&t instanceof URL)&&(t=fetch(t));const{instance:n,module:r}=await async function load(t,e){if("function"==typeof Response&&t instanceof Response){if("function"==typeof WebAssembly.instantiateStreaming)try{return await WebAssembly.instantiateStreaming(t,e)}catch(e){if("application/wasm"==t.headers.get("Content-Type"))throw e;console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",e)}const n=await t.arrayBuffer();return await WebAssembly.instantiate(n,e)}{const n=await WebAssembly.instantiate(t,e);return n instanceof WebAssembly.Instance?{instance:n,module:t}:n}}(await t,e);return a=n.exports,init$3.__wbindgen_wasm_module=r,a}function documentSetCBORWithTimestamp(t,e,n,r,i){ensureInitialized();const o=function ditto_document_set_cbor_with_timestamp(t,e,n,r,i){return takeObject(a.ditto_document_set_cbor_with_timestamp(addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r),addHeapObject(i)))}(t,bytesFromString(e),n,r,i);if(0!==o)throw new Error(errorMessage()||`ditto_document_set_cbor_with_timestamp() failed with error code: ${o}`)}function documentSetCBOR(t,e,n,r){ensureInitialized();const i=function ditto_document_set_cbor(t,e,n,r){return takeObject(a.ditto_document_set_cbor(addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r)))}(t,bytesFromString(e),n,r);if(0!==i)throw new Error(errorMessage()||`ditto_document_set_cbor() failed with error code: ${i}`)}function documentID(t){ensureInitialized();return boxCBytesIntoBuffer(function ditto_document_id(t){return takeObject(a.ditto_document_id(addHeapObject(t)))}(t))}function documentCBOR(t){ensureInitialized();return boxCBytesIntoBuffer(function ditto_document_cbor(t){return takeObject(a.ditto_document_cbor(addHeapObject(t)))}(t))}function documentGetCBOR(t,e){ensureInitialized();const n=function ditto_document_get_cbor(t,e){return takeObject(a.ditto_document_get_cbor(addHeapObject(t),addHeapObject(e)))}(t,bytesFromString(e));return boxCBytesIntoBuffer(n)}function documentRemove(t,e){ensureInitialized();const n=function ditto_document_remove(t,e){return takeObject(a.ditto_document_remove(addHeapObject(t),addHeapObject(e)))}(t,bytesFromString(e));if(0!==n)throw new Error(errorMessage()||`ditto_document_remove() failed with error code: ${n}`)}function documentReplaceWithCounter(t,e){ensureInitialized();const n=function ditto_document_replace_with_counter(t,e){return takeObject(a.ditto_document_replace_with_counter(addHeapObject(t),addHeapObject(e)))}(t,bytesFromString(e)),r=errorMessage();if("InvalidPointer"===r)throw new Error(`Can't replace with counter, property does not exist at path or path is not valid: ${e}`);if(0!==n)throw new Error(r||`ditto_document_replace_with_counter() failed with error code: ${n}`)}function documentReplaceWithCounterWithTimestamp(t,e,n){ensureInitialized();const r=function ditto_document_replace_with_counter_with_timestamp(t,e,n){return takeObject(a.ditto_document_replace_with_counter_with_timestamp(addHeapObject(t),addHeapObject(e),addHeapObject(n)))}(t,bytesFromString(e),n),i=errorMessage();if("InvalidPointer"===i)throw new Error(`Can't replace with counter, property does not exist at path or path is not valid: ${e}`);if(0!==r)throw new Error(i||`ditto_document_replace_with_counter_with_timestamp() failed with error code: ${r}`)}function documentIncrementCounter(t,e,n){ensureInitialized();const r=function ditto_document_increment_counter(t,e,n){return takeObject(a.ditto_document_increment_counter(addHeapObject(t),addHeapObject(e),addHeapObject(n)))}(t,bytesFromString(e),n);if(0!==r)throw new Error(errorMessage()||`ditto_document_increment_counter() failed with error code: ${r}`)}function documentPushCBOR(t,e,n){ensureInitialized();const r=function ditto_document_push_cbor(t,e,n){return takeObject(a.ditto_document_push_cbor(addHeapObject(t),addHeapObject(e),addHeapObject(n)))}(t,bytesFromString(e),n);if(0!==r)throw new Error(errorMessage()||`ditto_document_push_cbor() failed with error code: ${r}`)}function documentPopCBOR(t,e){ensureInitialized();const n=bytesFromString(e),r=withOutBoxCBytes((e=>{const r=function ditto_document_pop_cbor(t,e,n){return takeObject(a.ditto_document_pop_cbor(addHeapObject(t),addHeapObject(e),addHeapObject(n)))}(t,n,e);if(0!==r)throw new Error(errorMessage()||`ditto_document_pop_cbor() failed with error code: ${r}`);return e}));return boxCBytesIntoBuffer(r)}function documentInsertCBOR(t,e,n){ensureInitialized();const r=function ditto_document_insert_cbor(t,e,n){return takeObject(a.ditto_document_insert_cbor(addHeapObject(t),addHeapObject(e),addHeapObject(n)))}(t,bytesFromString(e),n);if(0!==r)throw new Error(errorMessage()||`ditto_document_insert_cbor() failed with error code: ${r}`)}function documentFree(t){ensureInitialized(),function ditto_document_free(t){return takeObject(a.ditto_document_free(addHeapObject(t)))}(t)}function documentIDQueryCompatible(t,e){ensureInitialized();return boxCStringIntoString(function ditto_document_id_query_compatible(t,e){return takeObject(a.ditto_document_id_query_compatible(addHeapObject(t),addHeapObject(e)))}(t,e))}function validateDocumentID(t){ensureInitialized();return boxCBytesIntoBuffer(withOutBoxCBytes((e=>{const n=function ditto_validate_document_id(t,e){return takeObject(a.ditto_validate_document_id(addHeapObject(t),addHeapObject(e)))}(t,e);if(0!==n)throw new Error(errorMessage()||`ditto_validate_document_id() failed with error code: ${n}`);return e})))}function collectionGet(t,e,n,r){ensureInitialized();const i=bytesFromString(e),{status_code:o,document:s}=function ditto_collection_get(t,e,n,r){return takeObject(a.ditto_collection_get(addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r)))}(t,i,n,r);if(o===m)return null;if(0!==o)throw new Error(errorMessage()||`ditto_collection_get() failed with error code: ${o}`);return s}async function collectionInsertValue(t,e,n,r,i){ensureInitialized();const o=bytesFromString(e);let s;switch(i){case"merge":s="Merge";break;case"overwrite":s="Overwrite";break;case"insertIfAbsent":s="InsertIfAbsent";break;case"insertDefaultIfAbsent":s="InsertDefaultIfAbsent";break;default:throw new Error("Invalid write strategy provided")}const{status_code:c,id:u}=await function ditto_collection_insert_value(t,e,n,r,i,o){return takeObject(a.ditto_collection_insert_value(addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r),addHeapObject(i),addHeapObject(o)))}(t,o,n,r,s,null);if(0!==c)throw new Error(errorMessage()||`ditto_collection_insert_value() failed with error code: ${c}`);return boxCBytesIntoBuffer(u)}function collectionRemove(t,e,n,r){ensureInitialized();const i=bytesFromString(e),{status_code:o,bool_value:s}=function ditto_collection_remove(t,e,n,r){return takeObject(a.ditto_collection_remove(addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r)))}(t,i,n,r);if(0!==o)throw new Error(errorMessage()||`ditto_collection_remove() failed with error code: ${o}`);return s}function collectionEvict(t,e,n,r){ensureInitialized();const i=bytesFromString(e),{status_code:o,bool_value:s}=function ditto_collection_evict(t,e,n,r){return takeObject(a.ditto_collection_evict(addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r)))}(t,i,n,r);if(0!==o)throw new Error(errorMessage()||`ditto_collection_evict() failed with error code: ${o}`);return s}function collectionUpdate(t,e,n,r){ensureInitialized();const i=function ditto_collection_update(t,e,n,r){return takeObject(a.ditto_collection_update(addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r)))}(t,bytesFromString(e),n,r);if(0!==i)throw new Error(errorMessage()||`ditto_collection_update() failed with error code: ${i}`)}function collectionUpdateMultiple(t,e,n,r){ensureInitialized();const i=function ditto_collection_update_multiple(t,e,n,r){return takeObject(a.ditto_collection_update_multiple(addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r)))}(t,bytesFromString(e),n,function jsDocsToCDocs(t){return takeObject(a.jsDocsToCDocs(addHeapObject(t)))}(r));if(0!==i)throw new Error(errorMessage()||`ditto_collection_update_multiple() failed with error code: ${i}`)}function collectionExecQueryStr(t,e,n,r,i,o,s,c){ensureInitialized();return function ditto_collection_exec_query_str(t,e,n,r,i,o,s,c){return takeObject(a.ditto_collection_exec_query_str(addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r),addHeapObject(i),addHeapObject(o),addHeapObject(s),addHeapObject(c)))}(t,bytesFromString(e),n,bytesFromString(r),i,o,s,c)}function collectionRemoveQueryStr(t,e,n,r,i,o,s,c){ensureInitialized();return function ditto_collection_remove_query_str(t,e,n,r,i,o,s,c){return takeObject(a.ditto_collection_remove_query_str(addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r),addHeapObject(i),addHeapObject(o),addHeapObject(s),addHeapObject(c)))}(t,bytesFromString(e),n,bytesFromString(r),i,o,s,c)}function collectionEvictQueryStr(t,e,n,r,i,o,s,c){ensureInitialized();return function ditto_collection_evict_query_str(t,e,n,r,i,o,s,c){return takeObject(a.ditto_collection_evict_query_str(addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r),addHeapObject(i),addHeapObject(o),addHeapObject(s),addHeapObject(c)))}(t,bytesFromString(e),n,bytesFromString(r),i,o,s,c)}function addSubscription(t,e,n,r){ensureInitialized();return function ditto_add_subscription(t,e,n,r){return takeObject(a.ditto_add_subscription(addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r)))}(t,bytesFromString(e),bytesFromString(n),r)}function removeSubscription(t,e,n,r){ensureInitialized();return function ditto_remove_subscription(t,e,n,r){return takeObject(a.ditto_remove_subscription(addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r)))}(t,bytesFromString(e),bytesFromString(n),r)}function liveQueryRegister(t,e,n,r,i,o,s,c,u){ensureInitialized();const d=bytesFromString(e),l=bytesFromString(n),{status_code:h,i64:b}=function ditto_live_query_register_str_detached(t,e,n,r,i,o,s,c){return takeObject(a.ditto_live_query_register_str_detached(addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r),addHeapObject(i),addHeapObject(o),addHeapObject(s),addHeapObject(c)))}(t,d,l,r,i,o,s,wrapBackgroundCbForFFI(u,c));if(0!==h)throw new Error(errorMessage()||`\`ditto_live_query_register_str()\` failed with error code: ${h}`);return b}function liveQueryStart(t,e){ensureInitialized();const n=function ditto_live_query_start(t,e){return takeObject(a.ditto_live_query_start(addHeapObject(t),addHeapObject(e)))}(t,e);if(0!==n)throw new Error(errorMessage()||`\`ditto_live_query_start()\` failed with error code: ${n}`)}function liveQueryStop(t,e){ensureInitialized(),function ditto_live_query_stop(t,e){return takeObject(a.ditto_live_query_stop(addHeapObject(t),addHeapObject(e)))}(t,e)}async function liveQuerySignalAvailableNext(t,e){ensureInitialized(),await function ditto_live_query_signal_available_next(t,e){return takeObject(a.ditto_live_query_signal_available_next(addHeapObject(t),addHeapObject(e)))}(t,e)}function liveQueryWebhookRegister(t,e,n,r,i,o,s){ensureInitialized();const c=bytesFromString(e),u=bytesFromString(n),d=bytesFromString(s),{status_code:l,id:h}=function ditto_live_query_webhook_register_str(t,e,n,r,i,o,s){return takeObject(a.ditto_live_query_webhook_register_str(addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r),addHeapObject(i),addHeapObject(o),addHeapObject(s)))}(t,c,u,r,i,o,d);if(0!==l)throw new Error(errorMessage()||`\`ditto_live_query_webhook_register_str()\` failed with error code: ${l}`);return boxCBytesIntoBuffer(h)}async function readTransaction(t){ensureInitialized();const{status_code:e,txn:n}=await function ditto_read_transaction(t){return takeObject(a.ditto_read_transaction(addHeapObject(t)))}(t);if(0!==e)throw new Error(errorMessage()||`\`ditto_read_transaction()\` failed with error code: ${e}`);return n}function readTransactionFree(t){return ensureInitialized(),function ditto_read_transaction_free(t){return takeObject(a.ditto_read_transaction_free(addHeapObject(t)))}(t)}async function writeTransaction(t){ensureInitialized();const{status_code:e,txn:n}=await function ditto_write_transaction(t){return takeObject(a.ditto_write_transaction(addHeapObject(t)))}(t);if(0!==e)throw new Error(errorMessage()||`ditto_write_transaction() failed with error code: ${e}`);return n}async function writeTransactionCommit(t,e){ensureInitialized();const n=await function ditto_write_transaction_commit(t,e){return takeObject(a.ditto_write_transaction_commit(addHeapObject(t),addHeapObject(e)))}(t,e);if(0!==n)throw new Error(errorMessage()||`ditto_write_transaction_commit() failed with error code: ${n}`)}function addStaticTCPClient(t,e){ensureInitialized();return(void 0)(t,bytesFromString(e))}function staticTCPClientFreeHandle(t){(void 0)(t)}function addWebsocketClient(t,e){ensureInitialized();return function ditto_add_websocket_client(t,e){return takeObject(a.ditto_add_websocket_client(addHeapObject(t),addHeapObject(e)))}(t,bytesFromString(e))}function websocketClientFreeHandle(t){ensureInitialized(),function websocket_client_free_handle(t){return takeObject(a.websocket_client_free_handle(addHeapObject(t)))}(t)}function loggerInit(){ensureInitialized(),function ditto_logger_init(){return takeObject(a.ditto_logger_init())}()}async function loggerSetCustomLogCb(t){if(ensureInitialized(),null===t)await ditto_logger_set_custom_log_cb(null);else{const e=wrapBackgroundCbForFFI(null,((e,n)=>{try{const r=boxCStringIntoString(n);t(e,r)}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(),function ditto_logger_enabled(t){return takeObject(a.ditto_logger_enabled(addHeapObject(t)))}(!!t)}function loggerEnabledGet(){return ensureInitialized(),!!function ditto_logger_enabled_get(){return takeObject(a.ditto_logger_enabled_get())}()}function loggerEmojiHeadingsEnabled(t){ensureInitialized(),function ditto_logger_emoji_headings_enabled(t){return takeObject(a.ditto_logger_emoji_headings_enabled(addHeapObject(t)))}(t)}function loggerEmojiHeadingsEnabledGet(){return ensureInitialized(),function ditto_logger_emoji_headings_enabled_get(){return takeObject(a.ditto_logger_emoji_headings_enabled_get())}()}function loggerMinimumLogLevel(t){ensureInitialized(),function ditto_logger_minimum_log_level(t){return takeObject(a.ditto_logger_minimum_log_level(addHeapObject(t)))}(t)}function loggerMinimumLogLevelGet(){return ensureInitialized(),function ditto_logger_minimum_log_level_get(){return takeObject(a.ditto_logger_minimum_log_level_get())}()}function loggerSetLogFile(t){ensureInitialized();if(0!==function ditto_logger_set_log_file(t){return takeObject(a.ditto_logger_set_log_file(addHeapObject(t)))}(t?bytesFromString(t):null))throw errorMessage(),new Error(`Can't set log file, due to error: ${errorMessage}`)}function log(t,e){ensureInitialized(),bytesFromString(t);!function ditto_log(t,e){return takeObject(a.ditto_log(addHeapObject(t),addHeapObject(e)))}(t,bytesFromString(e))}function dittoAuthClientMakeWithWeb(t,e,n,r){ensureInitialized();const i=bytesFromString(t),o=bytesFromString(e),s=bytesFromString(n),{status_code:c,auth_client:u}=function ditto_auth_client_make_with_web(t,e,n,r){return takeObject(a.ditto_auth_client_make_with_web(addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r)))}(i,o,s,r);if(0!==c)throw new Error(errorMessage()||`ditto_auth_client_make_with_web() failed with error code: ${c}`);return u}function dittoAuthClientMakeForDevelopment(t,e,n){ensureInitialized();const r=bytesFromString(t),i=bytesFromString(e),o=Number(n),{status_code:s,auth_client:c}=function ditto_auth_client_make_for_development(t,e,n){return takeObject(a.ditto_auth_client_make_for_development(addHeapObject(t),addHeapObject(e),addHeapObject(n)))}(r,i,o);if(0!==s)throw new Error(errorMessage()||`ditto_auth_client_make_for_development() failed with error code: ${s}`);return c}function dittoAuthClientMakeWithSharedKey(t,e,n,r){ensureInitialized();const i=bytesFromString(t),o=bytesFromString(e),s=bytesFromString(n),c=Number(r),{status_code:u,auth_client:d}=function ditto_auth_client_make_with_shared_key(t,e,n,r){return takeObject(a.ditto_auth_client_make_with_shared_key(addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r)))}(i,o,s,c);if(0!==u)throw new Error(errorMessage()||`ditto_auth_client_make_with_shared_key() failed with error code: ${u}`);return d}function dittoAuthClientMakeWithStaticX509(t){ensureInitialized();const e=bytesFromString(t),{status_code:n,auth_client:r}=function ditto_auth_client_make_with_static_x509(t){return takeObject(a.ditto_auth_client_make_with_static_x509(addHeapObject(t)))}(e);if(0!==n)throw new Error(errorMessage()||`ditto_auth_client_make_with_static_x509() failed with error code: ${n}`);return r}function dittoAuthClientGetSiteID(t){return ensureInitialized(),function ditto_auth_client_get_site_id(t){return takeObject(a.ditto_auth_client_get_site_id(addHeapObject(t)))}(t)}function dittoAuthClientFree(t){return ensureInitialized(),function ditto_auth_client_free(t){return takeObject(a.ditto_auth_client_free(addHeapObject(t)))}(t)}function dittoAuthClientIsWebValid(t){return ensureInitialized(),0!==function ditto_auth_client_is_web_valid(t){return takeObject(a.ditto_auth_client_is_web_valid(addHeapObject(t)))}(t)}function dittoAuthClientUserID(t){ensureInitialized();return boxCStringIntoString(function ditto_auth_client_user_id(t){return takeObject(a.ditto_auth_client_user_id(addHeapObject(t)))}(t))}function dittoAuthClientIsX509Valid(t){return ensureInitialized(),0!==function ditto_auth_client_is_x509_valid(t){return takeObject(a.ditto_auth_client_is_x509_valid(addHeapObject(t)))}(t)}async function dittoAuthClientLoginWithToken(t,e,n){ensureInitialized();const r=bytesFromString(e),i=bytesFromString(n),o=await function ditto_auth_client_login_with_token(t,e,n){return takeObject(a.ditto_auth_client_login_with_token(addHeapObject(t),addHeapObject(e),addHeapObject(n)))}(t,r,i);if(0!==o)throw new Error(errorMessage()||`Ditto failed to authenticate (error code: ${o}).`)}async function dittoAuthClientLoginWithUsernameAndPassword(t,e,n,r){ensureInitialized();const i=bytesFromString(e),o=bytesFromString(n),s=bytesFromString(r),c=await function ditto_auth_client_login_with_credentials(t,e,n,r){return takeObject(a.ditto_auth_client_login_with_credentials(addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r)))}(t,i,o,s);if(0!==c)throw new Error(errorMessage()||`Ditto failed to authenticate (error code: ${c}).`)}async function dittoAuthClientLogout(t){ensureInitialized();const e=await function ditto_auth_client_logout(t){return takeObject(a.ditto_auth_client_logout(addHeapObject(t)))}(t);if(0!==e)throw new Error(errorMessage()||`Ditto failed to logout (error code: ${e}).`)}function uninitializedDittoMake(t){ensureInitialized();return function uninitialized_ditto_make(t){return takeObject(a.uninitialized_ditto_make(addHeapObject(t)))}(bytesFromString(t))}function dittoMake(t,e){return ensureInitialized(),function ditto_make(t,e){return takeObject(a.ditto_make(addHeapObject(t),addHeapObject(e)))}(t,e)}function dittoGetCollectionNames(t){ensureInitialized();const e=function ditto_get_collection_names(t){return takeObject(a.ditto_get_collection_names(addHeapObject(t)))}(t),n=e.status_code,r=e.names;if(0!==n)throw new Error(errorMessage()||`ditto_get_collection_names() failed with error code: ${n}`);return function cStringVecToStringArray(t){return takeObject(a.cStringVecToStringArray(addHeapObject(t)))}(r)}async function dittoRegisterPresenceV1Callback(t,e){ensureInitialized(),e?function ditto_register_presence_v1_callback(t,e){return takeObject(a.ditto_register_presence_v1_callback(addHeapObject(t),addHeapObject(e)))}(t,wrapBackgroundCbForFFI((t=>console.error(`The registered presence callback errored with ${t}`)),(t=>{const n=function refCStringToString(t){return takeObject(a.refCStringToString(addHeapObject(t)))}(t);e(n)}))):await function ditto_clear_presence_callback(t){return takeObject(a.ditto_clear_presence_callback(addHeapObject(t)))}(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){ensureInitialized();let n=bytesFromString(e);if(n.length>64){n=bytesFromString(e.replace(/[^ -~]+/g,"").substr(0,63))}return function ditto_set_device_name(t,e){return takeObject(a.ditto_set_device_name(addHeapObject(t),addHeapObject(e)))}(t,n)}function dittoSetSyncGroup(t,e){return ensureInitialized(),function ditto_set_sync_group(t,e){return takeObject(a.ditto_set_sync_group(addHeapObject(t),addHeapObject(e)))}(t,e)}function dittoNewAttachmentFromBytes(t,e){ensureInitialized();const n={},r=function ditto_new_attachment_from_bytes(t,e,n){return takeObject(a.ditto_new_attachment_from_bytes(addHeapObject(t),addHeapObject(e),addHeapObject(n)))}(t,e,n);if(0!==r)throw new Error(errorMessage()||`ditto_new_attachment_from_bytes() failed with error code: ${r}`);return n}function dittoResolveAttachment(t,e,n,r){ensureInitialized();const{onComplete:i,onProgress:o,onDelete:s}=n,{status_code:c,cancel_token:u}=function ditto_resolve_attachment(t,e,n,r,i){return takeObject(a.ditto_resolve_attachment(addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r),addHeapObject(i)))}(t,e,wrapBackgroundCbForFFI(r,i),wrapBackgroundCbForFFI(r,o),wrapBackgroundCbForFFI(r,s));if(0!==c)throw new Error(errorMessage()||`ditto_resolve_attachment() failed with error code: ${c}`);return u}function dittoCancelResolveAttachment(t,e,n){ensureInitialized();const r=function ditto_cancel_resolve_attachment(t,e,n){return takeObject(a.ditto_cancel_resolve_attachment(addHeapObject(t),addHeapObject(e),addHeapObject(n)))}(t,e,n);if(0!==r)throw new Error(errorMessage()||`ditto_cancel_resolve_attachment() failed with error code: ${r}`)}async function dittoGetCompleteAttachmentData(t,e){ensureInitialized();const{status:n,data:r}=await function ditto_get_complete_attachment_data(t,e){return takeObject(a.ditto_get_complete_attachment_data(addHeapObject(t),addHeapObject(e)))}(t,e);if(0!==n)throw new Error(errorMessage()||`\`ditto_get_complete_attachment_data()\` failed with error code: ${n}`);return boxCBytesIntoBuffer(r)}function dittoGetSDKVersion(t){ensureInitialized();return boxCStringIntoString(function ditto_get_sdk_version(){return takeObject(a.ditto_get_sdk_version())}())}function dittoPresenceV1(t){ensureInitialized();return boxCStringIntoString(function ditto_presence_v1(t){return takeObject(a.ditto_presence_v1(addHeapObject(t)))}(t))}function dittoRunGarbageCollection(t){return ensureInitialized(),function ditto_run_garbage_collection(t){return takeObject(a.ditto_run_garbage_collection(addHeapObject(t)))}(t)}function documentsHash(t){ensureInitialized();const{status_code:e,u64:n}=function ditto_documents_hash(t){return takeObject(a.ditto_documents_hash(addHeapObject(t)))}(t);if(0!==e)throw new Error(errorMessage()||`\`ditto_documents_hash()\` failed with error code: ${e}`);return BigInt(n)}function documentsHashMnemonic(t){ensureInitialized();const{status_code:e,c_string:n}=function ditto_documents_hash_mnemonic(t){return takeObject(a.ditto_documents_hash_mnemonic(addHeapObject(t)))}(t);if(0!==e)throw new Error(errorMessage()||`\`ditto_documents_hash_mnemonic()\` failed with error code: ${e}`);return boxCStringIntoString(n)}function dittoAuthClientMakeLoginProvider(t,e){return ensureInitialized(),function ditto_auth_client_make_login_provider(t){return takeObject(a.ditto_auth_client_make_login_provider(addHeapObject(t)))}(wrapBackgroundCbForFFI(e,t))}function dittoAuthClientSetValidityListener(t,e,n){ensureInitialized();return function ditto_auth_client_set_validity_listener(t,e){return takeObject(a.ditto_auth_client_set_validity_listener(addHeapObject(t),addHeapObject(e)))}(t,wrapBackgroundCbForFFI(n,((t,n)=>e(1===t,1===n))))}let p,g=!1;async function init$2(t){t?await init$3(t):await init$3(),g=!0,p=function wrapFFIOutFunction(t){return function(...e){let n,r,i=!1;const o=e[e.length-1],a=e.splice(0,e.length-1),s=t(...a,(t=>{try{r=o(t),i=r===t}catch(t){n=t}}));if(n)throw n;return i?s:r}}(withOutPtr$1)}function initSDKVersion(t,e,n){ensureInitialized(),bytesFromString(t),bytesFromString(e);const r=function ditto_init_sdk_version(t,e,n){return takeObject(a.ditto_init_sdk_version(addHeapObject(t),addHeapObject(e),addHeapObject(n)))}(t,e,bytesFromString(n));if(void 0!==r&&0!==r)throw new Error(errorMessage()||`ditto_init_sdk_version() failed with error code: ${r}`)}function verifyLicense(t){ensureInitialized();const e=bytesFromString(t);let n;const r=p("char *",(t=>(n=function verify_license(t,e){return takeObject(a.verify_license(addHeapObject(t),addHeapObject(e)))}(e,t),t))),i=boxCStringIntoString(r);return{result:n,errorMessage:i}}const m=-30798;function wrapBackgroundCbForFFI(t,e){return void 0===t&&(t=console.error),(n,...r)=>{let i;try{i=e(...r)}catch(e){try{t(e)}catch(t){console.error(`Internal error: \`onError()\` handler oughtn't throw, but it did throw ${t}`)}}return n(i)}}function bytesFromString(t){if(void 0===t)return;if(null===t)return null;if("string"!=typeof t)throw new Error(`Can't convert string to Uint8Array, not a string: ${t}`);return(new TextEncoder).encode(`${t}\0`)}function errorMessage(){ensureInitialized();return boxCStringIntoString(function ditto_error_message(){return takeObject(a.ditto_error_message())}())}function ensureInitialized(){if(!g)throw new Error("Ditto needs to be initialized before using any of its API, please make sure to call `await init()` first.")}let w=null;if("undefined"!=typeof process&&"undefined"!=typeof require){const t=process.arch,e=process.platform;try{w=require(`./transports.${e}-${t}.node`)}catch(t){}}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}}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)}setLogFile(t){throw new Error("Deprecated, use Logger's static properties and methods directly instead.")}setLogFileURL(t){throw new Error("Deprecated, use Logger's static properties and methods directly instead.")}async setCustomLogCallback(t){throw new Error("Deprecated, use Logger's static properties and methods directly instead.")}static shared(){return Logger.warning("Logger.shared() is deprecated, use Logger's static properties & methods directly instead."),this}}class ObserverManager{constructor(t,e=null){this.id=t,this.keepAlive=e,this.isRegistered=!1,this.callbacksByToken={}}addObserver(t){var e;this.registerIfNeeded();const n=this.generateToken();return this.callbacksByToken[n]=t,null===(e=this.keepAlive)||void 0===e||e.retain(`${this.id}.${n}`),n}removeObserver(t){var e;delete this.callbacksByToken[t],null===(e=this.keepAlive)||void 0===e||e.release(`${this.id}.${t}`),this.unregisterIfNeeded()}notify(...t){const e=this.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(){!this.isRegistered&&(this.isRegistered=!0,this.register(this.notify.bind(this)))}unregisterIfNeeded(){!this.hasObservers()&&this.isRegistered&&(this.isRegistered=!1,this.unregister())}generateToken(){let t;do{t=Math.ceil(Math.random()*Number.MAX_SAFE_INTEGER)}while(this.callbacksByToken.hasOwnProperty(t));return t}async finalize(t){await this.removeObserver(t)}}class Observer{constructor(t,e,n={}){this.observerManager=t,this.token=e,this.options=n,n.stopsWhenFinalized&&Observer.finalizationRegistry.register(this,{observerManager:t,token:e},this)}get isStopped(){return void 0===this.token}stop(){const t=this.token;t&&(delete this.token,Observer.finalizationRegistry.unregister(this),this.observerManager.removeObserver(t))}static finalize(t){const{observerManager:e,token:n}=t;e.removeObserver(n)}}Observer.finalizationRegistry=new FinalizationRegistry(Observer.finalize);class Authenticator{constructor(t){this["@ditto.authenticationExpiring"]=function(t){throw new Error("Authenticator['@ditto.authenticationExpiring']() is abstract and must be implemented by subclasses.")},this["@ditto.authClientValidityChanged"]=function(t,e){throw new Error("Authenticator['@ditto.authClientValidityChanged']() is abstract and must be implemented by subclasses.")},this.keepAlive=t,this.status={isAuthenticated:!1,userID:null},this.loginSupported=!1,this.observerManager=new ObserverManager("AuthenticationStatusObservation",t)}get isAuthenticated(){return this.status.isAuthenticated}get userID(){return this.status.userID}loginWithToken(t,e){throw new Error("Authenticator.loginWithToken() is abstract and must be implemented by subclasses.")}loginWithUsernameAndPassword(t,e,n){throw new Error("Authenticator.loginWithUsernameAndPassword() is abstract and must be implemented by subclasses.")}logout(t){throw new Error("Authenticator.logout() is abstract and must be implemented by subclasses.")}observeStatus(t){const e=this.observerManager.addObserver(t);return new Observer(this.observerManager,e)}}class OnlineAuthenticator extends Authenticator{constructor(t,e,n,r){super(t),this["@ditto.authenticationExpiring"]=function(t){const e=this.authenticationHandler;t>0?e.authenticationExpiringSoon(this,t):e.authenticationRequired(this)},this["@ditto.authClientValidityChanged"]=function(t,e){this.updateAndNotify(!0)},this.loginSupported=!0,this.status={isAuthenticated:!1,userID:null},this.authClientPointer=e,this.ditto=new WeakRef(n),this.authenticationHandler=r,this.updateAndNotify(!1),OnlineAuthenticator.finalizationRegistry.register(this,e)}async loginWithToken(t,e){await dittoAuthClientLoginWithToken(this.authClientPointer,t,e)}async loginWithUsernameAndPassword(t,e,n){await dittoAuthClientLoginWithUsernameAndPassword(this.authClientPointer,t,e,n)}async logout(t){const e=this.ditto.deref();e?(await dittoAuthClientLogout(this.authClientPointer),e.stopSync(),null==t||t(this.ditto)):Logger.warning("Unable to logout, related Ditto object does not exist anymore.")}updateAndNotify(t){var e;const n=this.isAuthenticated,r=this.userID,i=dittoAuthClientIsWebValid(this.authClientPointer),o=dittoAuthClientUserID(this.authClientPointer),a={isAuthenticated:i,userID:o};if(this.status=a,t){!!n==!!i&&r===o||(null===(e=this.authenticationHandler.authenticationStatusDidChange)||void 0===e||e.call(this.authenticationHandler,this),this.observerManager.notify(a))}}static finalize(t){dittoAuthClientFree(t)}}OnlineAuthenticator.finalizationRegistry=new FinalizationRegistry(OnlineAuthenticator.finalize);class NotAvailableAuthenticator extends Authenticator{constructor(){super(...arguments),this["@ditto.authenticationExpiring"]=t=>{throw new Error(`Internal inconsistency, authentication is not available, yet the @ditto.authenticationExpiring() was called on authenticator: ${self}`)},this["@ditto.authClientValidityChanged"]=function(t,e){throw new Error(`Internal inconsistency, authentication is not available, yet the @ditto.authClientValidityChanged() was called on authenticator: ${self}`)}}async loginWithToken(t,e){throw new Error("Can't login, authentication is not supported for the identity in use, please use an onlineWithAuthentication identity.")}async loginWithUsernameAndPassword(t,e,n){throw new Error("Can't login, authentication is not supported for the identity in use, please use an onlineWithAuthentication identity.")}logout(t){throw new Error("Can't logout, authentication is not supported for the identity in use, please use an onlineWithAuthentication identity.")}}const y=4294967296,O=9007199254740992;const v={decode:function decode(t,e,n){let r=new DataView(t),i=new Uint8Array(t),o=0,tagValueFunction=function(t,e){return t},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,i[o])}function readUint16(){return commitRead(2,r.getUint16(o))}function readUint32(){return commitRead(4,r.getUint32(o))}function readBreak(){return 255===i[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()*y+readUint32()}();if(31===t)return-1;throw new Error("Invalid length encoding")}function readIndefiniteStringLength(t){let e=readUint8();if(255===e)return-1;let n=readLength(31&e);if(n<0||e>>5!==t)throw new Error("Invalid indefinite length element");return n}function appendUtf16Data(t,e){for(let n=0;n<e;++n){let n=readUint8();128&n&&(n<224?(n=(31&n)<<6|63&readUint8(),e-=1):n<240?(n=(15&n)<<12|(63&readUint8())<<6|63&readUint8(),e-=2):(n=(15&n)<<18|(63&readUint8())<<12|(63&readUint8())<<6|63&readUint8(),e-=3)),n<65536?t.push(n):(n-=65536,t.push(55296|n>>10),t.push(56320|1023&n))}}"function"==typeof e&&(tagValueFunction=e),"function"==typeof n&&(simpleValFunction=n);let a=function decodeItem(){let t,e,n=readUint8(),i=n>>5,a=31&n;if(7===i)switch(a){case 25:return function readFloat16(){let t=new ArrayBuffer(4),e=new DataView(t),n=readUint16(),r=32768&n,i=31744&n,o=1023&n;if(31744===i)i=261120;else if(0!==i)i+=114688;else if(0!==o)return(r?-1:1)*o*5.960464477539063e-8;return e.setUint32(0,r<<16|i<<13|o<<13),e.getFloat32(0)}();case 26:return function readFloat32(){return commitRead(4,r.getFloat32(o))}();case 27:return function readFloat64(){return commitRead(8,r.getFloat64(o))}()}if(e=readLength(a),e<0&&(i<2||6<i))throw new Error("Invalid length");switch(i){case 0:return e;case 1:return-1-e;case 2:if(e<0){let n=[],r=0;for(;(e=readIndefiniteStringLength(i))>=0;)r+=e,n.push(readArrayBuffer(e));let o=new Uint8Array(r),a=0;for(t=0;t<n.length;++t)o.set(n[t],a),a+=n[t].length;return o}return readArrayBuffer(e);case 3:let n=[];if(e<0)for(;(e=readIndefiniteStringLength(i))>=0;)appendUtf16Data(n,e);else appendUtf16Data(n,e);let r="";for(t=0;t<n.length;t+=8192)r+=String.fromCharCode.apply(null,n.slice(t,t+8192));return r;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 a={};for(t=0;t<e||e<0&&!readBreak();++t){a[decodeItem()]=decodeItem()}return a;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 a},encode:function encode(t){let e,n=new ArrayBuffer(256),r=new DataView(n),i=new Uint8Array(n),o=0;function prepareWrite(t){let a=n.byteLength,s=o+t;for(;a<s;)a<<=1;if(a!==n.byteLength){let t=r;n=new ArrayBuffer(a),r=new DataView(n),i=new Uint8Array(n);let e=o+3>>2;for(let n=0;n<e;++n)r.setUint32(n<<2,t.getUint32(n<<2))}return e=t,r}function commitWrite(...t){o+=e}function writeUint8(t){commitWrite(prepareWrite(1).setUint8(o,t))}function writeUint8Array(t){prepareWrite(t.length),i.set(t,o),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),function writeUint16(t){commitWrite(prepareWrite(2).setUint16(o,t))}(e)):e<4294967296?(writeUint8(t<<5|26),function writeUint32(t){commitWrite(prepareWrite(4).setUint32(o,t))}(e)):(writeUint8(t<<5|27),function writeUint64(t){let e=t%y,n=(t-e)/y,r=prepareWrite(8);r.setUint32(o,n),r.setUint32(o+4,e),commitWrite()}(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(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}(t,-0))return writeUint8Array([249,128,0]);switch(typeof t){case"number":if(Math.floor(t)===t){if(0<=t&&t<=O)return writeTypeAndLength(0,t);if(-O<=t&&t<0)return writeTypeAndLength(1,-(t+1))}return writeUint8(251),function writeFloat64(t){commitWrite(prepareWrite(8).setFloat64(o,t))}(t);case"string":let n=[];for(e=0;e<t.length;++e){let r=t.charCodeAt(e);r<128?n.push(r):r<2048?(n.push(192|r>>6),n.push(128|63&r)):r<55296||r>=57344?(n.push(224|r>>12),n.push(128|r>>6&63),n.push(128|63&r)):(r=(1023&r)<<10,r|=1023&t.charCodeAt(++e),r+=65536,n.push(240|r>>18),n.push(128|r>>12&63),n.push(128|r>>6&63),n.push(128|63&r))}return writeTypeAndLength(3,n.length),writeUint8Array(n);default:let r,i;if(Array.isArray(t))for(r=t.length,writeTypeAndLength(4,r),e=0;e<r;e+=1)encodeItem(t[e]);else if(t instanceof Uint8Array)writeTypeAndLength(2,t.length),writeUint8Array(t);else if(ArrayBuffer.isView(t))i=new Uint8Array(t.buffer),writeTypeAndLength(2,i.length),writeUint8Array(i);else if(t instanceof ArrayBuffer||"function"==typeof SharedArrayBuffer&&t instanceof SharedArrayBuffer)i=new Uint8Array(t),writeTypeAndLength(2,i.length),writeUint8Array(i);else{let n=Object.keys(t);for(r=n.length,writeTypeAndLength(5,r),e=0;e<r;e+=1){let r=n[e];encodeItem(r),encodeItem(t[r])}}}}(t),"slice"in n)return n.slice(0,o);let a=new ArrayBuffer(o),s=new DataView(a);for(let t=0;t<o;++t)s.setUint8(t,r.getUint8(t));return a}};class CBOR{static encode(t){const e=v.encode(t);return new Uint8Array(e)}static decode(t){const e=t.buffer;return v.decode(e)}}class UpdateResult{constructor(t,e,n,r,i){this.type=t,this.docID=e,this.path=n,void 0!==r&&(this.value=r),void 0!==i&&(this.amount=i)}static set(t,e,n){return new UpdateResult("set",t,e,n,void 0)}static replacedWithCounter(t,e){return new UpdateResult("replacedWithCounter",t,e,void 0,void 0)}static incremented(t,e,n){return new UpdateResult("incremented",t,e,void 0,n)}static inserted(t,e,n){return new UpdateResult("inserted",t,e,n,void 0)}static removed(t,e){return new UpdateResult("removed",t,e,void 0,void 0)}static pushed(t,e,n){return new UpdateResult("pushed",t,e,n,void 0)}static popped(t,e,n){return new UpdateResult("popped",t,e,n,void 0)}}class AttachmentToken{constructor(t){if("ditto_attachment"!==t._type)throw new Error("Invalid attachment token");const e=t._id;if(!(e instanceof Uint8Array))throw new Error("Invalid attachment token id");const n=t._len;if("number"!=typeof n||n<0)throw new Error("Invalid attachment token length");const r=t._meta;if("object"!=typeof r)throw new Error("Invalid attachment token meta");this.id=e,this.len=n,this.metadata=r}}class Attachment{constructor(t,e){this.ditto=t,this.token=e}get metadata(){return this.token.metadata}getData(){return dittoGetCompleteAttachmentData(L.pointerFor(this.ditto),j.pointerFor(this))}copyToPath(t){throw new Error("Can't copy attachment to path, not available when running in the browser.")}}const j=new Bridge(Attachment,(function freeAttachmentHandle(t){ensureInitialized(),function ditto_free_attachment_handle(t){return takeObject(a.ditto_free_attachment_handle(addHeapObject(t)))}(t)}));class Counter{constructor(t,e){this.value=t,this.isDefault=!!e}increment(t){if(!this.mutDoc)throw new Error("Can't increment counter, only possible within the closure of a collection's update() method.");this.mutDoc.at(this.path,!0).increment(t),this.value+=t}static __newInternal(t,e,n){const r=new Counter(n);return r.mutDoc=t,r.path=e,r}}class Value{constructor(t,e={}){this.value=t,this.isDefault=!!e.isDefault}}const C=/^[A-Za-z0-9_]+$/,I=/^[A-Za-z_]/;function validateKeyPathComponent(t,e=!1){if(Number.isFinite(+t))return`[${t}]`;if("string"==typeof t)return I.test(t)&&C.test(t)?e?t:`.${t}`:`['${t}']`;throw new Error(`Invalid path component: ${t}.`)}const k=["push","pop","splice","unshift","shift"];function set(t,e,n){let r=n,i=!1;const o=n instanceof Counter,a=n instanceof Value;(o||a)&&(r=n.value,i=!!n.isDefault);const s=r instanceof Counter,c=r instanceof Value;if(o&&s)throw`Can't set counter at path '${e}', nesting of Counter within Counter is forbidden.`;if(o&&c)throw`Can't set counter at path '${e}', nesting of Value within Counter is forbidden.`;if(a&&s)throw`Can't set value at path '${e}', nesting of Counter within Value is forbidden.`;if(a&&c)throw`Can't set value at path '${e}', nesting of Value within Value is forbidden.`;MutableDocument.pathAt(t,e,!0).set(r,i),o&&MutableDocument.pathAt(t,e,!0).replaceWithCounter(i)}function proxyFactory(t,e,n){return new Proxy(t,{get(t,r,i){if("symbol"==typeof r)return t[r];if("object"==typeof t&&""===n){if("_value"===r)return MutableDocument.value(i);if("_valueAt"===r)return t=>MutableDocument.valueAt(i,t);if("_pathAt"===r)return t=>MutableDocument.pathAt(i,t);if("toJSON"===r)return MutableDocument.prototype.toJSON;if("string"==typeof r&&r.startsWith("@ditto."))return e[r]}if("_replaceWithCounterAt"===r)return t=>{const r=validateKeyPathComponent(t);return MutableDocument.replaceWithCounterAt(e,`${n}${r}`)};if("_incrementCounterAt"===r)return(t,r)=>{const i=validateKeyPathComponent(t);return MutableDocument.incrementCounterAt(e,`${n}${i}`,r)};if(t instanceof Counter)return t[r];const o=t[r],a=typeof o;if("undefined"!==a){if("function"===a&&k.includes(r)&&(t.__arrayOp=r),"object"!==a)return o;const i=validateKeyPathComponent(r,""===n);return proxyFactory(o,e,`${n}${i}`)}return o},set(t,r,i){const o=validateKeyPathComponent(r,""===n),a=`${n}${o}`;if("object"==typeof t&&""===n&&"string"==typeof r&&r.startsWith("@ditto."))return e[r]=i,!0;if("object"==typeof t&&Array.isArray(t)){if("length"===r){if(i===t.length-1){const r=t.__arrayOp;r&&"pop"===r&&(MutableDocument.pathAt(e,n,!0).pop(),t.pop())}return t[r]=i,delete t.__arrayOp,!0}const o=+r;if(isNaN(o))throw new Error(`Attempting to access a non-index property of an array. Property: ${r}.`);const s=t.__arrayOp;if(o===t.length&&s&&"push"===s)MutableDocument.pathAt(e,n,!0).push(i),t.push(i);else if(s){let n=t.__cachedSetOperations||[];if(o>t.length)n.push({index:o,value:i,path:a}),t.__cachedSetOperations=n;else{set(e,a,i),t[o]=i;let r=n.length;for(;r>0;){const i=n[r-1];i.index===t.length&&(set(e,i.path,i.value),t[i.index]=i.value,n.splice(r-1,1)),r--}}}else{if(!(o<=t.length))throw new Error(`Attempting to set an array index of ${o} but the array only has ${t.length} elements`);set(e,a,i),t[o]=i}}else{if(t instanceof Counter&&"value"===r);else{const n=+r;if(Number.isFinite(n))throw new Error(`Attempting to access an array index property (${n}) of an object: ${JSON.stringify(t)}.`);set(e,a,i)}t[r]=i}return!0},deleteProperty(t,r){if(r in t){const i=t.__arrayOp;if(i&&"pop"===i)return!0;const o=validateKeyPathComponent(r,""===n),a=`${n}${o}`;return MutableDocument.pathAt(e,a,!0).remove(),delete t[r],!0}return!1}})}function augmentJSONValue(t,e,n){let r={};if(""===n){for(const[n,i]of Object.entries(t))r[n]=augmentJSONValue(i,e,n);return r}if(t&&"object"==typeof t){if(Array.isArray(t))return t.map(((t,r)=>augmentJSONValue(t,e,`${n}[${r}]`)));if("ditto_counter"===t._type)return Counter.__newInternal(e,n,t._value);if("ditto_attachment"===t._type)return new AttachmentToken(t);for(const[r,i]of Object.entries(t))t[r]=augmentJSONValue(i,e,`${n}['${r}']`);return t}return t}function desugarJSObject(t,e){let n={};if(e){for(const[e,r]of Object.entries(t))n[e]=desugarJSObject(r,!1);return n}if(t&&"object"==typeof t){if(Array.isArray(t))return t.map(((t,e)=>desugarJSObject(t,!1)));if(t instanceof Counter)return t.value;if(t instanceof Attachment)return{_type:"ditto_attachment",_id:t.token.id,_len:t.token.len,_meta:t.token.metadata};for(const[e,n]of Object.entries(t))t[e]=desugarJSObject(n,!1);return t}return t}const D=/\.([A-Za-z_]\w*)/.source,A=/\[(\d+)\]/.source,E=/\[\'(.+?)\'\]/.source,S=/\[\"(.+?)\"\]/.source,H=`((${D})|(${A})|(${E})|(${S}))*`,P=new RegExp(`^${D}`),F=new RegExp(`^${A}`),R=new RegExp(`^${E}`),T=new RegExp(`^${S}`),B=new RegExp(`^${H}$`);class KeyPath{static withLeadingDot(t){if("number"==typeof t)return t;if("string"!=typeof t)throw new Error(`Key-path must be a string or a number but is ${typeof t}: ${t}`);return"string"==typeof t&&!!t.match(/^[A-Za-z_]/)?`.${t}`:t}static withoutLeadingDot(t){if("number"==typeof t)return t;if("string"!=typeof t)throw new Error(`Key-path must be a string or a number but is ${typeof t}: ${t}`);return"string"==typeof t&&!!t.match(/^\./)?t.slice(1):t}static validate(t,e={}){var n;const r=null!==(n=e.isInitial)&&void 0!==n&&n;if("number"==typeof t)return Math.floor(Math.abs(t));if("string"!=typeof t)throw new Error(`Key-path must be a string or a number but is ${typeof t}: ${t}`);const i=this.withLeadingDot(t);if(!B.test(i))throw new Error(`Key-path is not valid: ${t}`);return r?t:i}static evaluate(t,e,n={}){var r;const i=null!==(r=n.stopAtLastContainer)&&void 0!==r&&r,o={keyPath:t,object:e,options:{...n},coveredPath:null,nextPathComponent:null,remainingPath:t,value:e};return function recurse(t,e){if(""===e)return o.value=t,o;const{nextPathComponentRaw:n,nextPathComponent:r,remainingPath:a}=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(P);if(null!==e){const n=e[0],r=e[1];return{nextPathComponentRaw:n,nextPathComponent:r,remainingPath:t.slice(r.length+1)}}const n=t.match(F);if(null!==n){const e=n[0],r=n[1];return{nextPathComponentRaw:e,nextPathComponent:parseInt(r),remainingPath:t.slice(r.length+2)}}const r=t.match(R);if(null!==r){const e=r[0],n=r[1];return{nextPathComponentRaw:e,nextPathComponent:n,remainingPath:t.slice(n.length+4)}}const i=t.match(T);if(null!==i){const e=i[0],n=i[1];return{nextPathComponentRaw:e,nextPathComponent:n,remainingPath:t.slice(n.length+4)}}throw new Error(`Can't return value at keyPath because the following part of the keyPath is invalid: ${t}`)}(e);return o.nextPathComponent=r,o.remainingPath=a,null===o.coveredPath||"number"==typeof n?o.coveredPath=n:o.coveredPath+=n,""===a&&i?(o.value=t,o):recurse(t[r],a)}(e,this.withLeadingDot(t))}constructor(){}}class DocumentPath{constructor(t,e){this.document=t,this.path=e}at(t){if("string"==typeof t){const e=t,n=KeyPath.validate(e);return new DocumentPath(this.document,`${this.path}${n}`)}if("number"==typeof t){const e=validateNumber(t,{integer:!0,min:0,errorMessagePrefix:"DocumentPath.atIndex() validation failed index:"});return new DocumentPath(this.document,`${this.path}[${e.toString()}]`)}throw new Error(`Can't return document path at key-path or index, string or number expected but got ${typeof t}: ${t}`)}value(){return Document.valueAt(this.document,this.path)}atIndex(t){return Logger.warning("Method DocumentPath.atIndex() is deprecated, use DocumentPath.at() instead."),this.at(t)}}class MutableDocumentPath{constructor(t,e){this.mutableDocument=t,this.path=e}at(t){if("string"==typeof t){const e=t;return KeyPath.validate(e),new MutableDocumentPath(this.mutableDocument,`${this.path}.${e}`)}if("number"==typeof t){const e=validateNumber(t,{integer:!0,min:0,errorMessagePrefix:"MutableDocumentPath.atIndex() validation failed index:"});return new MutableDocumentPath(this.mutableDocument,`${this.path}[${e.toString()}]`)}throw new Error(`Can't return mutable document path at key-path or index, string or number expected but got ${typeof t}: ${t}`)}value(){return MutableDocument.valueAt(this.mutableDocument,this.path)}set(t,e){const n=$.pointerFor(this.mutableDocument),r=desugarJSObject(t,!1),i=CBOR.encode(r);e?documentSetCBORWithTimestamp(n,this.path,i,!0,0):documentSetCBOR(n,this.path,i,!0),this.updateInMemoryByReloadingLastPathComponent();const o=augmentJSONValue(CBOR.decode(i),this.mutableDocument,this.path),a=UpdateResult.set(MutableDocument.id(this.mutableDocument),this.path,o);this.recordUpdateResult(a)}remove(){documentRemove($.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(MutableDocument.id(this.mutableDocument),this.path);this.recordUpdateResult(t)}replaceWithCounter(t){const e=$.pointerFor(this.mutableDocument);t?documentReplaceWithCounterWithTimestamp(e,this.path,0):documentReplaceWithCounter(e,this.path),this.updateInMemoryByReloadingLastPathComponent();const n=UpdateResult.replacedWithCounter(MutableDocument.id(this.mutableDocument),this.path);this.recordUpdateResult(n)}increment(t){documentIncrementCounter($.pointerFor(this.mutableDocument),this.path,t),this.updateInMemoryByReloadingLastPathComponent();const e=UpdateResult.incremented(MutableDocument.id(this.mutableDocument),this.path,t);this.recordUpdateResult(e)}push(t){const e=$.pointerFor(this.mutableDocument),n=desugarJSObject(t,!1),r=CBOR.encode(n);documentPushCBOR(e,this.path,r),this.updateInMemory(((e,n)=>{const r=e[n];if(!Array.isArray(r))throw new Error(`Can't push value, object at key-path ${this.path} is not an array.`);r.push(t)}));const i=augmentJSONValue(CBOR.decode(r),this.mutableDocument,this.path),o=UpdateResult.pushed(MutableDocument.id(this.mutableDocument),this.path,i);this.recordUpdateResult(o)}pop(){const t=documentPopCBOR($.pointerFor(this.mutableDocument),this.path),e=augmentJSONValue(CBOR.decode(t),this.mutableDocument,this.path);this.updateInMemory(((t,e)=>{const n=t[e];if(!Array.isArray(n))throw new Error(`Can't pop, object at key-path ${this.path} is not an array.`);n.pop()}));const n=UpdateResult.popped(MutableDocument.id(this.mutableDocument),this.path,e);return this.recordUpdateResult(n),e}insert(t){const e=$.pointerFor(this.mutableDocument),n=desugarJSObject(t),r=CBOR.encode(n);documentInsertCBOR(e,this.path,r),this.updateInMemory(((e,n)=>{const r=e[n],i=n;if(!Array.isArray(r))throw new Error(`Can't insert value, object at key-path ${this.path} is not an array.`);if("number"==typeof i)throw new Error(`Can't insert value, last path component in key-path ${this.path} is not a number.`);r.splice(i,0,t)}));const i=augmentJSONValue(CBOR.decode(r),this.mutableDocument,this.path),o=UpdateResult.inserted(MutableDocument.id(this.mutableDocument),this.path,i);this.recordUpdateResult(o)}updateInMemory(t){const e=MutableDocument.value(this.mutableDocument),n=KeyPath.evaluate(this.path,e,{stopAtLastContainer:!0});t(n.value,n.nextPathComponent)}updateInMemoryByReloadingLastPathComponent(){const t=$.pointerFor(this.mutableDocument);this.updateInMemory(((e,n)=>{const r=documentGetCBOR(t,this.path),i=augmentJSONValue(CBOR.decode(r),this.mutableDocument,this.path);e[n]=i}))}recordUpdateResult(t){const e=this.mutableDocument["@ditto.updateResults"].slice();e.push(t),Object.freeze(e),this.mutableDocument["@ditto.updateResults"]=e}atIndex(t){return Logger.warning("Method MutableDocumentPath.atIndex() is deprecated, use MutableDocumentPath.at() instead."),this.at(t)}}class Document{static id(t){let e=t["@ditto.id"];if(void 0===e){const n=documentID(M.pointerFor(t));e=CBOR.decode(n),t["@ditto.id"]=e}return e}static value(t){let e=t["@ditto.value"];if(void 0===e){const n=documentCBOR(M.pointerFor(t));e=augmentJSONValue(CBOR.decode(n),void 0,""),t["@ditto.value"]=e}return e}static stringForID(t){return documentIDQueryCompatible(validateDocumentIDCBOR(CBOR.encode(t)),"WithQuotes")}static base64StringForID(t){const e=validateDocumentIDCBOR(CBOR.encode(t));return btoa(String.fromCharCode.apply(null,e))}static valueAt(t,e){const n=this.value(t);return KeyPath.evaluate(e,n).value}static pathAt(t,e,n=!1){const r=n?e:KeyPath.validate(e,{isInitial:!0});return new DocumentPath(t,r)}static hash(t){return documentsHash(documentsFrom(t).map((t=>M.pointerFor(t))))}static hashMnemonic(t){return documentsHashMnemonic(documentsFrom(t).map((t=>M.pointerFor(t))))}toJSON(){return Document.value(this)}constructor(){return new Proxy(this,{get:function(t,e,n){if("symbol"==typeof e)return t[e];if("_id"===e)return Document.id(n);if("_value"===e)return Document.value(n);if("_valueAt"===e)return t=>Document.valueAt(n,t);if("_pathAt"===e)return t=>Document.pathAt(n,t);if("toJSON"===e)return Reflect.get(t,e,n);if("constructor"===e)return Reflect.get(t,e,n);if("string"==typeof e&&e.startsWith("@ditto."))return Reflect.get(t,e,n);const r=Document.value(t);return r.hasOwnProperty(e)?Reflect.get(r,e,n):Reflect.get(t,e,n)},ownKeys:function(t){return Reflect.ownKeys(Document.value(t))},set:function(t,e,n){if("string"==typeof e&&e.startsWith("@ditto."))return Reflect.set(t,e,n);throw new Error("Document is immutable and can't be mutated.")}})}static idCBOR(t){return documentID(M.pointerFor(t))}static canonicalizedIDCBOR(t){return validateDocumentIDCBOR(t)}static isIDCBORCanonical(t){return t===this.canonicalizedIDCBOR(t)}}class MutableDocument{constructor(){this["@ditto.updateResults"]=[]}static id(t){let e=t["@ditto.id"];if(void 0===e){const n=documentID($.pointerFor(t));e=CBOR.decode(n),t["@ditto.id"]=e}return e}static value(t){let e=t["@ditto.value"];if(void 0===e){const n=documentCBOR($.pointerFor(t));e=augmentJSONValue(CBOR.decode(n),this,""),t["@ditto.value"]=e}return e}static valueAt(t,e){const n=this.value(t);return KeyPath.evaluate(e,n).value}static pathAt(t,e,n=!1){const r=n?e:KeyPath.validate(e,{isInitial:!0});return new MutableDocumentPath(t,r)}static replaceWithCounterAt(t,e,n=!1){this.pathAt(t,e,n).replaceWithCounter()}static incrementCounterAt(t,e,n,r=!1){this.pathAt(t,e,r).increment(n)}toJSON(){return MutableDocument.value(this)}static idCBOR(t){return documentID($.pointerFor(t))}}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}MutableDocument.canonicalizedIDCBOR=Document.canonicalizedIDCBOR,MutableDocument.isIDCBORCanonical=Document.isIDCBORCanonical;const M=new Bridge(Document,documentFree),$=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 AttachmentFetcher{constructor(t,e,n){this.ditto=t,this.token=e,this.eventHandler=n||null,this.cancelToken=null;const r=n||function(){};this.attachment=new Promise(((n,i)=>{const o=L.pointerFor(t);this.cancelToken=dittoResolveAttachment(o,e.id,{onComplete:t=>{this.eventHandler=null,this.cancelToken=null;const e=new Attachment(this.ditto,this.token);j.bridge(t,(()=>e),{throwIfAlreadyBridged:!0}),r({type:"Completed",attachment:e}),n(e)},onProgress:(t,e)=>{r({type:"Progress",totalBytes:e,downloadedBytes:t})},onDelete:()=>{this.eventHandler=null,this.cancelToken=null,r({type:"Deleted"}),n(null)}},(t=>{this.eventHandler=null,this.cancelToken=null,i(t)}))}))}stop(){const t=this.cancelToken;if(t){this.cancelToken=null;dittoCancelResolveAttachment(L.pointerFor(this.ditto),this.token.id,t)}}then(t,e){return this.attachment.then(t,e)}}class Subscription{constructor(t,e,n){this.isCancelled=!1,this.query=e,this.queryArgsCBOR=n,this.collection=t,this.contextInfo={ditto:t.store.ditto,collectionName:t.name,query:e,queryArgsCBOR:n},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(L.pointerFor(e.ditto),e.collectionName,e.query,e.queryArgsCBOR),this.finalizationRegistry.register(t,e,e)}static remove(t,e){removeSubscription(L.pointerFor(e.ditto),e.collectionName,e.query,e.queryArgsCBOR),t&&this.finalizationRegistry.unregister(e)}}Subscription.finalizationRegistry=new FinalizationRegistry((t=>{Subscription.remove(null,t)}));class UpdateResultsMap{constructor(t,e){const n=t.map((t=>Document.stringForID(t))).sort().join(", ");if(n!==Object.keys(e).sort().join(", "))throw new Error("Internal inconsistency, can't construct update results map, documentIDs must all be keys in update results (by document ID string)");this.documentIDs=t.slice(),this.updateResultsByDocumentIDString={...e}}get(t){const e=Document.stringForID(t);return this.updateResultsByDocumentIDString[e]}keys(){return this.documentIDs.slice()}}class LiveQueryEventInitial{constructor(){this.isInitial=!0}hash(t){return documentsHash(t.map((t=>M.pointerFor(t))))}hashMnemonic(t){return documentsHashMnemonic(t.map((t=>M.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=>M.pointerFor(t))))}hashMnemonic(t){return documentsHashMnemonic(t.map((t=>M.pointerFor(t))))}}class SingleDocumentLiveQueryEvent{constructor(t,e){this.isInitial=t,this.oldDocument=e}hash(t){return documentsHash(null===t?[]:[M.pointerFor(t)])}hashMnemonic(t){return documentsHashMnemonic(null===t?[]:[M.pointerFor(t)])}}class LiveQuery{constructor(t,e,n,r,i,o,a,s,c){this.query=t,this.queryArgs=e?Object.freeze({...e}):null,this.queryArgsCBOR=n,this.orderBys=r,this.limit=i,this.offset=o,this.collection=a,this.handler=c,s&&(this.subscription=s);const u=L.pointerFor(a.store.ditto),d=a.name;let l;const signalNext=async()=>{await liveQuerySignalAvailableNext(u,l)};if(l=liveQueryRegister(u,d,t,n,this.orderBys,i,o,(t=>{const e=t.documents.map((t=>M.bridge(t)));let n;n=t.is_initial?new LiveQueryEventInitial:new LiveQueryEventUpdate({oldDocuments:t.old_documents.map((t=>M.bridge(t))),insertions:t.insertions,deletions:t.deletions,updates:t.updates,moves:t.moves.map((t=>({from:t[0],to:t[1]})))}),c(e,n,signalNext)})),!l)throw new Error("Internal inconsistency, couldn't create a valid live query ID.");this.liveQueryID=l,liveQueryStart(u,l),a.store.ditto.keepAlive.retain(`LiveQuery.${l}`)}get collectionName(){return this.collection.name}get isStopped(){return null!==this.liveQueryID}stop(){var t;const e=this.liveQueryID;if(null!==e){this.collection.store.ditto.keepAlive.release(`LiveQuery.${e}`),this.liveQueryID=null;const n=L.pointerFor(this.collection.store.ditto);null===(t=this.subscription)||void 0===t||t.cancel(),liveQueryStop(n,e)}}async signalNext(){const t=L.pointerFor(this.collection.store.ditto);await liveQuerySignalAvailableNext(t,this.liveQueryID)}}class PendingCursorOperation{constructor(t,e,n){this.currentLimit=-1,this.currentOffset=0,this.orderBys=[],this.query=validateQuery(t),this.queryArgs=e?Object.freeze({...e}):null,this.collection=n,this.queryArgsCBOR=e?CBOR.encode(e):null}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)}observe(t){return this._observe(t,!0,!1)}observeWithNextSignal(t){return 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=L.pointerFor(this.collection.store.ditto);return(await o((async()=>{const n=await writeTransaction(e),r=await collectionRemoveQueryStr(e,this.collection.name,n,t,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);return await writeTransactionCommit(e,n),r}))).map((t=>CBOR.decode(t)))}async evict(){const t=this.query,e=L.pointerFor(this.collection.store.ditto);return(await o((async()=>{const n=await writeTransaction(e),r=await collectionEvictQueryStr(e,this.collection.name,n,t,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);return await writeTransactionCommit(e,n),r}))).map((t=>CBOR.decode(t)))}async exec(){const t=this.query,e=L.pointerFor(this.collection.store.ditto);return(await o((async()=>{const n=await writeTransaction(e),r=await collectionExecQueryStr(e,this.collection.name,n,t,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);return await writeTransactionCommit(e,n),r}))).map((t=>M.bridge(t)))}async update(t){return await o((async()=>{const e=this.query,n=L.pointerFor(this.collection.store.ditto),r=await writeTransaction(n),i=await collectionExecQueryStr(n,this.collection.name,r,e,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset),o=i.map((t=>$.bridge(t,(()=>new MutableDocument)))),a=o.map((t=>proxyFactory(MutableDocument.value(t),t,"")));t(a);const s=[],c={};for(const t of o){const e=MutableDocument.id(t),n=Document.stringForID(e),r=t["@ditto.updateResults"];if(c[n])throw new Error(`Internal inconsistency, update results for document ID as string already exist: ${n}`);s.push(e),c[n]=r,$.pointerFor(t),$.unregister(t)}return await collectionUpdateMultiple(n,this.collection.name,r,i),await writeTransactionCommit(n,r),new UpdateResultsMap(s,c)}))}then(t,e){return this.exec().then(t,e)}_observe(t,e,n){const r=e?this.subscribe():null,i=n?t:function(e,n,r){try{return t.call(this,e,n)}finally{r()}};return new LiveQuery(this.query,this.queryArgs,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset,this.collection,r,i)}}class PendingIDSpecificOperation{constructor(t,e,n=!1){this.documentID=t,this.collection=e,this.documentIDCBOR=n?t:validateDocumentIDCBOR(CBOR.encode(t))}subscribe(){return new Subscription(this.collection,this.query,null)}observe(t){return this._observe(t,!0,!1)}observeWithNextSignal(t){return 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=L.pointerFor(this.collection.store.ditto);return await o((async()=>{const e=await writeTransaction(t),n=await collectionRemove(t,this.collection.name,e,this.documentIDCBOR);return await writeTransactionCommit(t,e),n}))}async evict(){const t=L.pointerFor(this.collection.store.ditto);return await o((async()=>{const e=await writeTransaction(t),n=await collectionEvict(t,this.collection.name,e,this.documentIDCBOR);return await writeTransactionCommit(t,e),n}))}async exec(){const t=L.pointerFor(this.collection.store.ditto);return await o((async()=>{const e=await readTransaction(t),n=await collectionGet(t,this.collection.name,this.documentIDCBOR,e);let r;return n&&(r=M.bridge(n)),readTransactionFree(e),r}))}async update(t){const e=L.pointerFor(this.collection.store.ditto),n=await readTransaction(e),r=await collectionGet(e,this.collection.name,this.documentIDCBOR,n);if(readTransactionFree(n),!r)throw new Error(`Can't update, document with ID '${this.documentID}' not found in collection named '${this.collection.name}'`);const i=$.bridge(r,(()=>new MutableDocument));t(proxyFactory(MutableDocument.value(i),i,"")),$.unregister(i);const o=await writeTransaction(e);return await collectionUpdate(e,this.collection.name,o,r),await writeTransactionCommit(e,o),i["@ditto.updateResults"].slice()}then(t,e){return this.exec().then(t,e)}get query(){return`_id == ${Document.stringForID(this.documentID)}`}_observe(t,e,n){const r=e?this.subscribe():null;return new LiveQuery(this.query,null,null,[],-1,0,this.collection,r,((e,r,i)=>{if(e.length>1){const t=e.map((t=>Document.base64StringForID(t._id)));throw new Error(`Internal inconsistency, single document live query returned more than one document. Query: ${this.query}, documentIDs: ${t.join(", ")}.`)}if(!1===r.isInitial&&r.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===r.isInitial&&r.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===r.isInitial&&r.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===r.isInitial&&r.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===r.isInitial&&r.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===r.isInitial?0:r.insertions.length+r.deletions.length+r.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,a=!0===r.isInitial?void 0:r.oldDocuments[0],s=new SingleDocumentLiveQueryEvent(r.isInitial,a);if(n)t(o,s,i);else try{t(o,s)}finally{i()}}))}}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=validateDocumentIDValue(t);return new PendingIDSpecificOperation(e,this)}async upsert(t,e={}){var n;const r=null!==(n=e.writeStrategy)&&void 0!==n?n:"merge";return this._insert(t,{writeStrategy:r})}async insert(t,e={}){return Logger.warning("Collection.insert() is deprecated, please use upsert() instead."),this._insert(t,e)}newAttachment(t,e={}){const n=this.store.ditto,r=L.pointerFor(n),{id:i,len:o,handle:a}=function(){if("string"==typeof t)throw new Error("Can't create attachment from file when running in the browser. Please pass the raw data (as a Uint8Array) instead.");if(t instanceof Uint8Array)return dittoNewAttachmentFromBytes(r,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}`)}(),s=new AttachmentToken({_type:"ditto_attachment",_id:i,_len:o,_meta:{...e}}),c=new Attachment(n,s);return j.bridge(a,(()=>c),{throwIfAlreadyBridged:!0})}fetchAttachment(t,e){const n=this.store.ditto;return new AttachmentFetcher(n,t,e)}findByIDCBOR(t){return new PendingIDSpecificOperation(t,this,!0)}async _insert(t,e={}){var n,r,i;const a=null!==(n=e.id)&&void 0!==n?n:t._id,s=null!==(r=e.isDefault)&&void 0!==r&&r,c=null!==(i=e.writeStrategy)&&void 0!==i?i:s?"insertDefaultIfAbsent":"overwrite";if(s&&e.writeStrategy&&"insertDefaultIfAbsent"!==e.writeStrategy)throw new Error("Incompatible isDefault and writeStrategy options.");const u=this.store.ditto,d=L.pointerFor(u),l=void 0===a?void 0:validateDocumentIDValue(a),h=void 0===l?null:validateDocumentIDCBOR(CBOR.encode(l)),b=desugarJSObject(t,!0),_=CBOR.encode(b),f=await o((()=>collectionInsertValue(d,this.name,_,h,c)));return CBOR.decode(f)}}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.pendingCursorOperation=new PendingCursorOperation("true",null,new Collection("__collections",t)),this.store=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 this.pendingCursorOperation.observe(((e,n)=>{const r=collectionsFromDocuments(e,this.store);let i;if(!0===n.isInitial)i=CollectionsEvent.initial(r);else{const t=collectionsFromDocuments(n.oldDocuments,this.store);i=new CollectionsEvent({isInitial:!1,collections:r,oldCollections:t,insertions:n.insertions,deletions:n.deletions,updates:n.updates,moves:n.moves})}t(i)}))}async exec(){return collectionsFromDocuments(await this.pendingCursorOperation.exec(),this.store)}then(t,e){return this.exec().then(t,e)}}function collectionsFromDocuments(t,e){const n=[];return t.forEach((t=>{const r=t.name;void 0!==r&&"string"==typeof r&&n.push(new Collection(r,e))})),n}class Store{constructor(t){this.ditto=t}collection(t){return new Collection(t,this)}collections(){return new PendingCollectionsOperation(this.ditto.store)}collectionNames(){return dittoGetCollectionNames(L.pointerFor(this.ditto))}registerLiveQueryWebhook(t,e,n){const r=validateQuery(e),i=liveQueryWebhookRegister(L.pointerFor(this.ditto),t,r,[],0,0,n);return CBOR.decode(i)}}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 PresenceManager{constructor(t){this.ditto=t,this.isRegistered=!1,this.currentRemotePeers=[],this.callbacksByPresenceToken={}}addObserver(t){this.registerIfNeeded();const e=this.generatePresenceToken();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=L.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(L.pointerFor(this.ditto),null),this.currentRemotePeers=[]}}generatePresenceToken(){let t;do{t=Math.ceil(Math.random()*Number.MAX_SAFE_INTEGER)}while(this.callbacksByPresenceToken.hasOwnProperty(t));return t}handlePresenceV1Callback(t){const e=this.decode(t).sort(this.compareRemotePeers);this.currentRemotePeers=e,this.notify()}notify(){for(const t in this.callbacksByPresenceToken){(0,this.callbacksByPresenceToken[t])(this.currentRemotePeers)}}decode(t){return JSON.parse(t).map((t=>{var e,n;return{networkID:t.network_id,deviceName:t.device_name,rssi:null!==(e=t.rssi)&&void 0!==e?e:void 0,approximateDistanceInMeters:null!==(n=t.approximate_distance_in_meters)&&void 0!==n?n:void 0,connections:t.connections}}))}finalize(t){this.removeObserver(t)}compareRemotePeers(t,e){return 0===t.connections.length&&e.connections.length>0?1:t.connections.length>0&&0===e.connections.length||t.deviceName<e.deviceName?-1:t.deviceName>e.deviceName?1:0}}class TransportConditionsManager extends ObserverManager{constructor(t){super("TransportConditionsObservation",t.keepAlive),this.ditto=t}register(t){return dittoRegisterTransportConditionChangedCallback(L.pointerFor(this.ditto),t)}unregister(){return dittoRegisterTransportConditionChangedCallback(L.pointerFor(this.ditto),null)}processCallback(t,e){let n,r;switch(t){case"Bluetooth":n="BLE";break;case"Tcp":n="TCP";break;case"Awdl":n="AWDL";break;case"Mdns":n="MDNS"}switch(e){case"Unknown":r="Unknown";break;case"Ok":r="OK";break;case"GenericFailure":r="GenericFailure";break;case"AppInBackground":r="AppInBackground";break;case"MdnsFailure":r="MDNSFailure";break;case"TcpListenFailure":r="TCPListenFailure";break;case"NoBleCentralPermission":r="NoBLECentralPermission";break;case"NoBlePeripheralPermission":r="NoBLEPeripheralPermission";break;case"CannotEstablishConnection":r="CannotEstablishConnection";break;case"BleDisabled":r="BLEDisabled";break;case"NoBleHardware":r="NoBLEHardware";break;case"WifiDisabled":r="WiFiDisabled";break;case"TemporarilyUnavailable":r="TemporarilyUnavailable"}return[r,n]}}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,n=stateFrom(this.parameters);this.updateGlobal(e,n),this.updatePeerToPeerBluetoothLE(e,n),this.updatePeerToPeerAWDL(e,n),this.updatePeerToPeerLAN(e,n),this.updateListenTCP(e,n),this.updateListenHTTP(e,n),this.updateConnectTCPServers(e,n),this.updateConnectWebsocketURLs(e,n),this.state=n}updatePeerToPeerBluetoothLE(t,e){const n=L.pointerFor(this.ditto),r=t.effectiveTransportConfig.peerToPeer.bluetoothLE,i=e.effectiveTransportConfig.peerToPeer.bluetoothLE,o=!r.isEnabled&&i.isEnabled,a=r.isEnabled&&!i.isEnabled;if(o&&this.bluetoothLETransportPointer)throw new Error("Internal inconsistency, when starting BLE transport, no BLE transport pointer should exist.");if(a&&!this.bluetoothLETransportPointer)throw new Error("Internal inconsistency, when stopping BLE transport, a BLE transport pointer should exist.");if(o){if(!function bleIsAvailable(t){return null!==w&&w.bleIsAvailable(t)}(n))throw new Error("Can't start P2P BluetoothLE transport because not available.");this.bluetoothLETransportPointer=function bleCreate(t){if(null!==w)return w.bleCreate(t);throw new Error("Can't create BluetoothLE handle, P2P BluetoothLE is not supported on this platform.")}(n)}a&&(!function bleDestroy(t){if(null!==w)return w.bleDestroy(t);throw new Error("Can't destroy BluetoothLE handle, P2P BluetoothLE is not supported on this platform.")}(this.bluetoothLETransportPointer),delete this.bluetoothLETransportPointer)}updatePeerToPeerAWDL(t,e){const n=L.pointerFor(this.ditto),r=t.effectiveTransportConfig.peerToPeer.awdl,i=e.effectiveTransportConfig.peerToPeer.awdl,o=!r.isEnabled&&i.isEnabled,a=r.isEnabled&&!i.isEnabled;if(o&&this.awdlTransportPointer)throw new Error("Internal inconsistency, when starting AWDL transport, no AWDL transport pointer should exist.");if(a&&!this.awdlTransportPointer)throw new Error("Internal inconsistency, when stopping AWDL transport, an AWDL transport pointer should exist.");if(o){if(!function awdlIsAvailable(t){return null!==w&&w.awdlIsAvailable(t)}(n))throw new Error("Can't start P2P AWDL transport because not available.");this.awdlTransportPointer=function awdlCreate(t){if(null!==w)return w.awdlCreate(t);throw new Error("Can't create AWDL handle, P2P AWDL transport is not supported on this platform.")}(n)}a&&(!function awdlDestroy(t){if(null!==w)return w.awdlDestroy(t);throw new Error("Can't destroy AWDL handle, P2P AWDL transport is not supported on this platform.")}(this.awdlTransportPointer),this.awdlTransportPointer=null)}updatePeerToPeerLAN(t,e){const n=L.pointerFor(this.ditto),r=t.effectiveTransportConfig.peerToPeer.lan,i=e.effectiveTransportConfig.peerToPeer.lan;if(r.isEnabled&&(r.isMdnsEnabled&&(!function lanDestroy(t){if(null!==w)return w.lanDestroy(t);throw new Error("Can't destroy LAN handle, P2P LAN transport is not supported on this platform.")}(this.lanTransportPointer),delete this.lanTransportPointer),r.isMulticastEnabled&&function dittoRemoveMulticastTransport(t){return ensureInitialized(),(void 0)(t)}(n)),i.isEnabled){if(i.isMdnsEnabled){if(!function lanIsAvailable(t){return null!==w&&w.lanIsAvailable(t)}(n))throw new Error("Can't start P2P LAN transport because not available.");this.lanTransportPointer=function lanCreate(t){if(null!==w)return w.lanCreate(t);throw new Error("Can't create LAN handle, P2P LAN transport is not supported on this platform.")}(n)}i.isMulticastEnabled&&function dittoAddMulticastTransport(t){return ensureInitialized(),(void 0)(t)}(n)}}updateListenTCP(t,e){const n=t.effectiveTransportConfig.listen.tcp,r=e.effectiveTransportConfig.listen.tcp;if(TransportConfig.areListenTCPsEqual(r,n))return;const i=L.pointerFor(this.ditto);n.isEnabled&&function dittoStopTCPServer(t){return ensureInitialized(),(void 0)(t)}(i),r.isEnabled&&function dittoStartTCPServer(t,e){return ensureInitialized(),(void 0)(t,bytesFromString(e))}(i,`${r.interfaceIP}:${r.port}`)}updateListenHTTP(t,e){const n=t.effectiveTransportConfig.listen.http,r=e.effectiveTransportConfig.listen.http;if(TransportConfig.areListenHTTPsEqual(n,r))return;const i=L.pointerFor(this.ditto);n.isEnabled&&function dittoStopHTTPServer(t){return ensureInitialized(),(void 0)(t)}(i),r.isEnabled&&function dittoStartHTTPServer(t,e,n,r,i,o){return ensureInitialized(),(void 0)(t,bytesFromString(e),bytesFromString(n),r,bytesFromString(i),bytesFromString(o))}(i,`${r.interfaceIP}:${r.port}`,r.staticContentPath||null,r.websocketSync?"Enabled":"Disabled",r.tlsCertificatePath||null,r.tlsKeyPath||null)}updateConnectTCPServers(t,e){const n=Object.getOwnPropertyNames(this.staticTCPClientsByAddress),i=e.effectiveTransportConfig.connect.tcpServers,o=new Set(i);for(const t of n)o.delete(t);const a=new Set(n);for(const t of i)a.delete(t);const s=o.values(),c=a.values();for(const t of s){const e=addStaticTCPClient(L.pointerFor(this.ditto),t),n=r.bridge(e);this.staticTCPClientsByAddress[t]=n}for(const t of c){const e=this.staticTCPClientsByAddress[t];if(!e)throw new Error(`Internal inconsistency, can't disconnect from TCP address '${t}', no staticTCPClient found.`);const n=r.pointerFor(e);r.unregister(e),staticTCPClientFreeHandle(n),delete this.staticTCPClientsByAddress[t]}}updateConnectWebsocketURLs(t,e){const n=Object.getOwnPropertyNames(this.websocketClientsByURL),r=e.effectiveTransportConfig.connect.websocketURLs.slice(),o=new Set(r);for(const t of n)o.delete(t);const a=new Set(n);for(const t of r)a.delete(t);const s=o.values(),c=a.values();for(const t of s){const e=addWebsocketClient(L.pointerFor(this.ditto),t),n=i.bridge(e);this.websocketClientsByURL[t]=n}for(const t of c){const e=this.websocketClientsByURL[t];if(!e)throw new Error(`Internal inconsistency, can't disconnect from websocket URL '${t}', no websocketClient found.`);const n=i.pointerFor(e);i.unregister(e),websocketClientFreeHandle(n),delete this.websocketClientsByURL[t]}}updateGlobal(t,e){t.effectiveTransportConfig.global.syncGroup!==e.effectiveTransportConfig.global.syncGroup&&dittoSetSyncGroup(L.pointerFor(this.ditto),e.effectiveTransportConfig.global.syncGroup)}}function stateFrom(t){const e=t.transportConfig.copy(),n=t.identity,r=t.isSyncActive,i=t.isX509Valid,o=t.isWebValid;let a;e.connect.tcpServers,e.connect.websocketURLs;let s=!1;return"online"!==n.type&&"onlinePlayground"!==n.type&&"onlineWithAuthentication"!==n.type||(a=n.appID,s=!n.hasOwnProperty("enableDittoCloudSync")||n.enableDittoCloudSync),r&&i||(e.peerToPeer.bluetoothLE.isEnabled=!1,e.peerToPeer.awdl.isEnabled=!1,e.peerToPeer.lan.isEnabled=!1,e.listen.tcp.isEnabled=!1,e.connect.tcpServers=[]),r&&o||(e.listen.http.isEnabled=!1,e.connect.websocketURLs=[]),r&&o&&s&&e.connect.websocketURLs.push(`wss://${a}.cloud.ditto.live`),e.peerToPeer.lan.isEnabled&&!e.listen.tcp.isEnabled&&(e.listen.tcp.isEnabled=!0,e.listen.tcp.interfaceIP="[::]",e.listen.tcp.port=0),{underlyingSyncParameters:t,effectiveTransportConfig:e.freeze()}}class Ditto{constructor(t,e){this.isWebValid=!1,this.isX509Valid=!1;const r=null!=t?t:{type:"offlinePlayground",appID:""},i=e&&e.trim().length>0?e:"ditto",o=Object.freeze(this.validateIdentity(r));this.identity=Object.freeze(o),this.path=i,this.deviceName=navigator.userAgent,this.keepAlive=new KeepAlive;const a=uninitializedDittoMake(i);let s=null;const c=(()=>{var t,e;if("development"===o.type||"offlinePlayground"===o.type)return dittoAuthClientMakeForDevelopment(i,o.appID,null!==(t=o.siteID)&&void 0!==t?t:0);if("manual"===o.type||"production"===o.type)return dittoAuthClientMakeWithStaticX509(o.certificate);if("sharedKey"===o.type)return dittoAuthClientMakeWithSharedKey(i,o.appID,o.sharedKey,o.siteID);if("onlinePlayground"===o.type)return dittoAuthClientMakeForDevelopment(i,o.appID,0);if("onlineWithAuthentication"===o.type||"online"===o.type){const t=null!==(e=o.customAuthURL)&&void 0!==e?e:`https://${o.appID}.cloud.ditto.live`,n=dittoAuthClientMakeLoginProvider((t=>{this.auth?this.auth["@ditto.authenticationExpiring"](t):s=t}));return dittoAuthClientMakeWithWeb(i,o.appID,t,n)}throw new Error(`Can't create Ditto, unsupported identity type: ${o}`)})();dittoAuthClientSetValidityListener(c,this.authClientValidityChanged.bind(this));const u=dittoAuthClientIsWebValid(c),d=dittoAuthClientIsX509Valid(c),l=dittoAuthClientGetSiteID(c),h=dittoMake(a,c);"onlineWithAuthentication"===o.type||"online"===o.type?this.auth=new OnlineAuthenticator(this.keepAlive,c,this,o.authHandler):(dittoAuthClientFree(c),this.auth=new NotAvailableAuthenticator(this.keepAlive));const b=new TransportConfig;this.siteID=l,this.transportConfig=b.copy().freeze(),this.isX509Valid=d,this.isWebValid=u,this.sync=new Sync(this),this.sync.update({isSyncActive:!1,isX509Valid:d,isWebValid:u,identity:o,transportConfig:b}),this.isActivated=n,this.store=new Store(this),this.presenceManager=new PresenceManager(this),this.transportConditionsManager=new TransportConditionsManager(this);const _=L.bridge(h,(()=>this));return null!==s&&this.auth["@ditto.authenticationExpiring"](s),_}get sdkVersion(){return L.pointerFor(this),dittoGetSDKVersion()}get isSyncEnabled(){return Logger.warning("Ditto.isSyncEnabled() is deprecated, use isSyncActive() instead."),this.isSyncActive}setLicenseToken(t){const{result:e,errorMessage:r}=verifyLicense(t);if("LicenseOk"!==e)throw this.isActivated=n,new Error(r);this.isActivated=!0}setAccessLicense(t){Logger.warning("Ditto.setAccessLicense() is deprecated, use setLicenseToken() instead."),this.setLicenseToken(t)}setTransportConfig(t){this.transportConfig,this.transportConfig=t.copy().freeze();const e=this.transportConfig,n=this.identity,r=this.isWebValid,i=this.isX509Valid;this.sync.update({transportConfig:e,identity:n,isWebValid:r,isX509Valid:i,isSyncActive:this.isSyncActive})}updateTransportConfig(t){const e=this.transportConfig.copy();return t(e),this.setTransportConfig(e),this}tryStartSync(){this.startSync()}startSync(){this.setSyncEnabled(!0)}stopSync(){this.setSyncEnabled(!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(L.pointerFor(this))}authClientValidityChanged(t,e){const n=this.transportConfig,r=this.identity,i=this.isSyncActive;this.isX509Valid,this.isWebValid,this.isX509Valid=e,this.isWebValid=t,this.auth["@ditto.authClientValidityChanged"](t,e),this.sync.update({transportConfig:n,identity:r,isWebValid:t,isX509Valid:e,isSyncActive:i})}validateIdentity(t){const e={...t},n=t.appName,r=t.appID;if(!["development","offlinePlayground","sharedKey","production","manual","onlinePlayground","online","onlineWithAuthentication"].includes(t.type))throw new Error(`Can't create Ditto instance, unknown identity type: ${t.type}`);if("development"!==t.type&&"offlinePlayground"!==t.type&&"sharedKey"!==t.type||void 0===n||void 0===r||(Logger.warning("Properties .appID and .appName (deprecated) are both given for identity, .appID will be used and .appName will be ignored."),delete e.appName),"development"!==t.type&&"offlinePlayground"!==t.type&&"sharedKey"!==t.type||void 0===n||void 0!==r||(Logger.warning("Property .appName of IdentityDevelopment and IdentitySharedKey is deprecated, use .appID instead."),e.appID=n,delete e.appName),("development"===t.type||"offlinePlayground"===t.type||"sharedKey"===t.type)&&void 0===n&&void 0===r)throw new Error(`Property .appID or the deprecated .appName must be given for identity, but aren't: ${JSON.stringify(t)}`);if(("onlinePlayground"===t.type||"online"===t.type||"onlineWithAuthentication"===t.type)&&void 0===r)throw new Error("Property .appID must be given for identity, but isn't.");if(void 0!==n&&"string"!=typeof n)throw new Error(`Property .appName must be be of type string, but is of type '${typeof n}': ${n}`);if(void 0!==r&&"string"!=typeof r)throw new Error(`Property .appID must be be of type string, but is of type '${typeof r}': ${r}`);if(("development"===t.type||"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")}return t.type,"production"===t.type&&Logger.warning("IdentityProduction (type: 'production') is deprecated, please use IdentityManual instead."),t.type,t.type,"online"===t.type||t.type,e}setSyncEnabled(t){if(t&&!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 `setLicenseToken`. 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=L.pointerFor(this);this.isSyncActive=t;const n=this.isWebValid,r=this.isX509Valid,i=this.identity,o=this.transportConfig;dittoSetDeviceName(e,this.deviceName),this.sync.update({identity:i,transportConfig:o,isWebValid:n,isX509Valid:r,isSyncActive:!!t})}}Ditto.webAssemblyModule=null;const L=new Bridge(Ditto,(function dittoDrop(t){return ensureInitialized(),function ditto_drop(t){return takeObject(a.ditto_drop(addHeapObject(t)))}(t)}));let z=!1;t.Attachment=Attachment,t.AttachmentFetcher=AttachmentFetcher,t.AttachmentToken=AttachmentToken,t.Authenticator=Authenticator,t.CBOR=CBOR,t.Collection=Collection,t.CollectionsEvent=CollectionsEvent,t.Counter=Counter,t.Ditto=Ditto,t.Document=Document,t.DocumentPath=DocumentPath,t.KeepAlive=KeepAlive,t.LiveQuery=LiveQuery,t.LiveQueryEventInitial=LiveQueryEventInitial,t.LiveQueryEventUpdate=LiveQueryEventUpdate,t.Logger=Logger,t.MutableDocument=MutableDocument,t.MutableDocumentPath=MutableDocumentPath,t.NotAvailableAuthenticator=NotAvailableAuthenticator,t.Observer=Observer,t.OnlineAuthenticator=OnlineAuthenticator,t.PendingCursorOperation=PendingCursorOperation,t.PendingIDSpecificOperation=PendingIDSpecificOperation,t.SingleDocumentLiveQueryEvent=SingleDocumentLiveQueryEvent,t.Store=Store,t.Subscription=Subscription,t.TransportConfig=TransportConfig,t.UpdateResult=UpdateResult,t.UpdateResultsMap=UpdateResultsMap,t.Value=Value,t.__log=function __log(t,e){Logger.warning("Function __log() is deprecated, use Logger.log() & friends instead."),Logger.log(t,e)},t.attachmentBridge=j,t.dittoBridge=L,t.documentBridge=M,t.init=async function init(t={}){if(!z){{const e=t.webAssemblyModule||Ditto.webAssemblyModule||"https://software.ditto.live/js/Ditto/1.1.1/ditto.wasm";await init$2(e),await async function init$1(){if(null!==w)return w.init()}(),initSDKVersion("Web","JavaScript","1.1.1"),loggerInit()}z=!0}},t.mutableDocumentBridge=$,t.validateDocumentIDCBOR=validateDocumentIDCBOR,t.validateDocumentIDValue=validateDocumentIDValue,Object.defineProperty(t,"__esModule",{value:!0})}));
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).Ditto={})}(this,(function(t){"use strict";class Meta{constructor(t,e,n){this.type=t,this.object=e,this.pointer=n}toString(){return`{ Meta | type: ${this.type.name}, object: ${this.object.deref()}, FFI address: ${this.pointer.addr}, FFI type: ${this.pointer.type} }`}}class Bridge{constructor(t,n,r={}){this.type=t,this.release=n,this.metaByAddrMap=e,this.finalizationRegistry=new FinalizationRegistry(this.finalize.bind(this))}pointerFor(t){return t["@ditto.ptr"]}objectFor(t){const e=this.metaByAddrMap[t.addr];if(!e)return;if(e.type!==this.type)throw new Error(`Can't return object for pointer, pointer is associated with an object of type ${e.type} but this bridge is configured for ${this.type}`);const n=e.object.deref();if(!n)throw new Error(`Internal inconsistency, found a meta entry for an object whose object is undefined (garbage collected): ${t}`);return n}bridge(t,e,n={}){const r=n.throwIfAlreadyBridged,i=this.objectFor(t);if(i&&r)throw new Error(`Can't bridge, pointer has already been bridged: ${JSON.stringify(t)}`);if(i)return i;e||(e=()=>Reflect.construct(this.type,[]));const o=e();if(!o)throw new Error(`Can't bridge, expected create() to return an object but got: ${o}`);return this.register(o,t),o}register(t,e){const n=t.constructor,r=this.type;if(n!==r)throw new Error(`Can't register, bridge is configured for type ${r.name} but passed in object is of type ${n.name}`);const i=this.pointerFor(t),o=this.metaByAddrMap[e.addr];if(i&&o)throw new Error(`Can't register, an object for the passed in pointer has previously been registered: ${o.pointer}`);if(i&&!o)throw new Error(`Internal inconsistency, trying to register an object which has an associated pointer but no meta entry: ${t}`);if(!i&&o)throw new Error(`Internal inconsistency, trying to register an object which has a meta entry but no associated pointer: ${t}`);const a=new Meta(n,new WeakRef(t),e);t["@ditto.ptr"]=e,this.metaByAddrMap[a.pointer.addr]=a,this.finalizationRegistry.register(t,e,t)}unregister(t){const e=t.constructor,n=this.type;if(e!==n)throw new Error(`Can't unregister, bridge is configured for type ${n.name} but passed in object is of type ${e.name}`);const r=this.pointerFor(t);if(!r)throw new Error(`Can't unregister, object that has not been registered before: ${t}`);const i=this.metaByAddrMap[r.addr];if(!i)throw new Error(`Internal inconsistency, trying to unregister an object which has an associated pointer but no meta entry: ${t}`);if(i.type!==n)throw new Error(`Internal inconsistency, trying to unregister an object that has a meta entry with a different type than that of the bridge: ${i}`);if(!i.object.deref())throw new Error(`Internal inconsistency, trying to unregister an object that has a meta entry whose object is undfined (garbage collected): ${i}`);if(i.object.deref()!==t)throw new Error(`Internal inconsistency, trying to unregister an object that has a meta entry holding a different object: ${i}`);this.finalizationRegistry.unregister(t),delete this.metaByAddrMap[r.addr],delete t["@ditto.ptr"]}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)}}const e={},n=!0;function validateNumber(t,e={}){var n;const r=null!==(n=e.errorMessagePrefix)&&void 0!==n?n:"Number validation failed:",i=!!e.integer,o=e.min,a=e.max,s=e.minX,c=e.maxX;if("number"!=typeof t)throw new Error(`${r} '${t}' is not a number.`);if(i&&Math.floor(t)!==t)throw new Error(`${r} '${t}' is not an integer.`);if(void 0!==o&&t<o)throw new Error(`${r} '${t}' must be >= ${o}.`);if(void 0!==a&&t>a)throw new Error(`${r} '${t}' must be <= ${a}.`);if(void 0!==s&&t<=s)throw new Error(`${r} '${t}' must be > ${s}.`);if(void 0!==c&&t>=c)throw new Error(`${r} '${t}' must be < ${c}.`);return t}function validateQuery(t,e={}){var n;const r=null!==(n=e.errorMessagePrefix)&&void 0!==n?n:"Query validation failed,";if("string"!=typeof t)throw new Error(`${r} query is not a string: ${t}`);if(""===t)throw new Error(`${r} query is an empty string.`);const i=t.trim();if(""===i)throw new Error(`${r} query contains only whitespace characters.`);return i}const r=new Bridge(class StaticTCPClient{},staticTCPClientFreeHandle),i=new Bridge(class WebsocketClient{},websocketClientFreeHandle);async function step(t){return await function sleep(t){return new Promise(((e,n)=>{setTimeout(e,t)}))}(0),t()}const o=step;let a;const s=new Array(32).fill(void 0);function getObject(t){return s[t]}s.push(void 0,null,!0,!1);let c=s.length;function takeObject(t){const e=getObject(t);return function dropObject(t){t<36||(s[t]=c,c=t)}(t),e}let d=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});d.decode();let u=null;function getUint8Memory0(){return null!==u&&u.buffer===a.memory.buffer||(u=new Uint8Array(a.memory.buffer)),u}function getStringFromWasm0(t,e){return d.decode(getUint8Memory0().subarray(t,t+e))}function addHeapObject(t){c===s.length&&s.push(s.length+1);const e=c;return c=s[e],s[e]=t,e}let l=0,h=new TextEncoder("utf-8");const b="function"==typeof h.encodeInto?function(t,e){return h.encodeInto(t,e)}:function(t,e){const n=h.encode(t);return e.set(n),{read:t.length,written:n.length}};function passStringToWasm0(t,e,n){if(void 0===n){const n=h.encode(t),r=e(n.length);return getUint8Memory0().subarray(r,r+n.length).set(n),l=n.length,r}let r=t.length,i=e(r);const o=getUint8Memory0();let a=0;for(;a<r;a++){const e=t.charCodeAt(a);if(e>127)break;o[i+a]=e}if(a!==r){0!==a&&(t=t.slice(a)),i=n(i,r,r=a+3*t.length);const e=getUint8Memory0().subarray(i+a,i+r);a+=b(t,e).written}return l=a,i}let _=null;function getInt32Memory0(){return null!==_&&_.buffer===a.memory.buffer||(_=new Int32Array(a.memory.buffer)),_}function debugString(t){const e=typeof t;if("number"==e||"boolean"==e||null==t)return`${t}`;if("string"==e)return`"${t}"`;if("symbol"==e){const e=t.description;return null==e?"Symbol":`Symbol(${e})`}if("function"==e){const e=t.name;return"string"==typeof e&&e.length>0?`Function(${e})`:"Function"}if(Array.isArray(t)){const e=t.length;let n="[";e>0&&(n+=debugString(t[0]));for(let r=1;r<e;r++)n+=", "+debugString(t[r]);return n+="]",n}const n=/\[object ([^\]]+)\]/.exec(toString.call(t));let r;if(!(n.length>1))return toString.call(t);if(r=n[1],"Object"==r)try{return"Object("+JSON.stringify(t)+")"}catch(t){return"Object"}return t instanceof Error?`${t.name}: ${t.message}\n${t.stack}`:r}const f=new FinalizationRegistry((t=>{a.__wbindgen_export_2.get(t.dtor)(t.a,t.b)}));function makeMutClosure(t,e,n,r){const i={a:t,b:e,cnt:1,dtor:n},real=(...t)=>{i.cnt++;const e=i.a;i.a=0;try{return r(e,i.b,...t)}finally{0==--i.cnt?(a.__wbindgen_export_2.get(i.dtor)(e,i.b),f.unregister(i)):i.a=e}};return real.original=i,f.register(real,i,i),real}function __wbg_adapter_36(t,e){a._dyn_core__ops__function__FnMut_____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__h7530c62e3d673a67(t,e)}function __wbg_adapter_39(t,e,n){a._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__hba533d1a144f84a3(t,e,addHeapObject(n))}function __wbg_adapter_42(t,e,n){a._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__he9d81343d5b05a75(t,e,addHeapObject(n))}function __wbg_adapter_45(t,e){a._dyn_core__ops__function__FnMut_____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__hcf2b54b9a4d93329(t,e)}function __wbg_adapter_48(t,e,n){a._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__h12036a797c03dada(t,e,addHeapObject(n))}function ditto_register_transport_condition_changed_callback(t,e){return takeObject(a.ditto_register_transport_condition_changed_callback(addHeapObject(t),addHeapObject(e)))}function ditto_logger_set_custom_log_cb(t){return takeObject(a.ditto_logger_set_custom_log_cb(addHeapObject(t)))}function handleError(t,e){try{return t.apply(this,e)}catch(t){a.__wbindgen_exn_store(addHeapObject(t))}}function getArrayU8FromWasm0(t,e){return getUint8Memory0().subarray(t/1,t/1+e)}function boxCStringIntoString(t){return takeObject(a.boxCStringIntoString(addHeapObject(t)))}function boxCBytesIntoBuffer(t){return takeObject(a.boxCBytesIntoBuffer(addHeapObject(t)))}function withOutPtr$1(t,e){return takeObject(a.withOutPtr(addHeapObject(t),addHeapObject(e)))}function withOutBoxCBytes(t){return takeObject(a.withOutBoxCBytes(addHeapObject(t)))}async function init$3(t){if(void 0===t)throw new Error("Can't load ditto.wasm, expected module to be provided at initialization time but got nothing.");const e={wbg:{}};e.wbg.__wbindgen_object_drop_ref=function(t){takeObject(t)},e.wbg.__wbindgen_string_new=function(t,e){return addHeapObject(getStringFromWasm0(t,e))},e.wbg.__wbindgen_cb_drop=function(t){const e=takeObject(t).original;if(1==e.cnt--)return e.a=0,!0;return!1},e.wbg.__wbg_log_fbcf63c42b370e42=function(t,e){try{console.log(getStringFromWasm0(t,e))}finally{a.__wbindgen_free(t,e)}},e.wbg.__wbg_new_693216e109162396=function(){return addHeapObject(new Error)},e.wbg.__wbg_stack_0ddaca5d1abfb52f=function(t,e){var n=passStringToWasm0(getObject(e).stack,a.__wbindgen_malloc,a.__wbindgen_realloc),r=l;getInt32Memory0()[t/4+1]=r,getInt32Memory0()[t/4+0]=n},e.wbg.__wbg_error_09919627ac0992f5=function(t,e){try{console.error(getStringFromWasm0(t,e))}finally{a.__wbindgen_free(t,e)}},e.wbg.__wbindgen_is_string=function(t){return"string"==typeof getObject(t)},e.wbg.__wbindgen_string_get=function(t,e){const n=getObject(e);var r="string"==typeof n?n:void 0,i=function isLikeNone(t){return null==t}(r)?0:passStringToWasm0(r,a.__wbindgen_malloc,a.__wbindgen_realloc),o=l;getInt32Memory0()[t/4+1]=o,getInt32Memory0()[t/4+0]=i},e.wbg.__wbindgen_object_clone_ref=function(t){return addHeapObject(getObject(t))},e.wbg.__wbg_fetch_fb26f738d9707b16=function(t){return addHeapObject(fetch(getObject(t)))},e.wbg.__wbg_Window_2b37b61fe0cb894b=function(t){return addHeapObject(getObject(t).Window)},e.wbg.__wbindgen_is_undefined=function(t){return void 0===getObject(t)},e.wbg.__wbg_WorkerGlobalScope_da7fa0bf3cb27800=function(t){return addHeapObject(getObject(t).WorkerGlobalScope)},e.wbg.__wbg_randomFillSync_64cc7d048f228ca8=function(){return handleError((function(t,e,n){getObject(t).randomFillSync(getArrayU8FromWasm0(e,n))}),arguments)},e.wbg.__wbg_getRandomValues_98117e9a7e993920=function(){return handleError((function(t,e){getObject(t).getRandomValues(getObject(e))}),arguments)},e.wbg.__wbg_process_2f24d6544ea7b200=function(t){return addHeapObject(getObject(t).process)},e.wbg.__wbindgen_is_object=function(t){const e=getObject(t);return"object"==typeof e&&null!==e},e.wbg.__wbg_versions_6164651e75405d4a=function(t){return addHeapObject(getObject(t).versions)},e.wbg.__wbg_node_4b517d861cbcb3bc=function(t){return addHeapObject(getObject(t).node)},e.wbg.__wbg_modulerequire_3440a4bcf44437db=function(){return handleError((function(t,e){return addHeapObject(r.require(getStringFromWasm0(t,e)))}),arguments)},e.wbg.__wbg_crypto_98fc271021c7d2ad=function(t){return addHeapObject(getObject(t).crypto)},e.wbg.__wbg_msCrypto_a2cdb043d2bfe57f=function(t){return addHeapObject(getObject(t).msCrypto)},e.wbg.__wbg_clearInterval_f94c74cd3759378b=function(t,e){getObject(t).clearInterval(e)},e.wbg.__wbg_clearTimeout_2c1ba0016d8bca41=function(t,e){getObject(t).clearTimeout(e)},e.wbg.__wbg_setInterval_ec2d9dc4a54a6566=function(){return handleError((function(t,e,n){return getObject(t).setInterval(getObject(e),n)}),arguments)},e.wbg.__wbg_setTimeout_df66d951b1726b78=function(){return handleError((function(t,e,n){return getObject(t).setTimeout(getObject(e),n)}),arguments)},e.wbg.__wbg_readyState_d14de08ffb5783f5=function(t){return getObject(t).readyState},e.wbg.__wbg_setonopen_33b75427f7db7ce1=function(t,e){getObject(t).onopen=getObject(e)},e.wbg.__wbg_setonerror_cb55f0521ac0da3a=function(t,e){getObject(t).onerror=getObject(e)},e.wbg.__wbg_setonclose_7094f96283d130e0=function(t,e){getObject(t).onclose=getObject(e)},e.wbg.__wbg_setonmessage_ca5f75e4a84134ef=function(t,e){getObject(t).onmessage=getObject(e)},e.wbg.__wbg_setbinaryType_c9a67ad8bb4125af=function(t,e){getObject(t).binaryType=takeObject(e)},e.wbg.__wbg_new_982fe22cd93d67f7=function(){return handleError((function(t,e){return addHeapObject(new WebSocket(getStringFromWasm0(t,e)))}),arguments)},e.wbg.__wbg_newwithstrsequence_15aec70da899280b=function(){return handleError((function(t,e,n){return addHeapObject(new WebSocket(getStringFromWasm0(t,e),getObject(n)))}),arguments)},e.wbg.__wbg_close_f2a10c1de90df5f0=function(){return handleError((function(t){getObject(t).close()}),arguments)},e.wbg.__wbg_send_503c2e7652e95bf5=function(){return handleError((function(t,e,n){getObject(t).send(getStringFromWasm0(e,n))}),arguments)},e.wbg.__wbg_send_73ab09dbae2da3c3=function(){return handleError((function(t,e,n){getObject(t).send(getArrayU8FromWasm0(e,n))}),arguments)},e.wbg.__wbg_code_18a1e10cf380ddc6=function(t){return getObject(t).code},e.wbg.__wbg_new_9c35e8e8b09fb4a3=function(){return handleError((function(){return addHeapObject(new Headers)}),arguments)},e.wbg.__wbg_append_fb85316567f7a798=function(){return handleError((function(t,e,n,r,i){getObject(t).append(getStringFromWasm0(e,n),getStringFromWasm0(r,i))}),arguments)},e.wbg.__wbg_instanceof_Response_e1b11afbefa5b563=function(t){return getObject(t)instanceof Response},e.wbg.__wbg_url_50e0bdb6051741be=function(t,e){var n=passStringToWasm0(getObject(e).url,a.__wbindgen_malloc,a.__wbindgen_realloc),r=l;getInt32Memory0()[t/4+1]=r,getInt32Memory0()[t/4+0]=n},e.wbg.__wbg_status_6d8bb444ddc5a7b2=function(t){return getObject(t).status},e.wbg.__wbg_headers_5ffa990806e04cfc=function(t){return addHeapObject(getObject(t).headers)},e.wbg.__wbg_arrayBuffer_b8937ed04beb0d36=function(){return handleError((function(t){return addHeapObject(getObject(t).arrayBuffer())}),arguments)},e.wbg.__wbg_clearInterval_708ee6c3f45bf733=function(t,e){getObject(t).clearInterval(e)},e.wbg.__wbg_clearTimeout_c1f246d6874c0679=function(t,e){getObject(t).clearTimeout(e)},e.wbg.__wbg_fetch_b4e81012e07ff95a=function(t,e){return addHeapObject(getObject(t).fetch(getObject(e)))},e.wbg.__wbg_setInterval_a02797f5ab1c7eb1=function(){return handleError((function(t,e,n){return getObject(t).setInterval(getObject(e),n)}),arguments)},e.wbg.__wbg_setTimeout_5314850184d61a44=function(){return handleError((function(t,e,n){return getObject(t).setTimeout(getObject(e),n)}),arguments)},e.wbg.__wbg_wasClean_f06e0966f0a58bfa=function(t){return getObject(t).wasClean},e.wbg.__wbg_code_c8c420857439c0b4=function(t){return getObject(t).code},e.wbg.__wbg_reason_a10c58463722f72e=function(t,e){var n=passStringToWasm0(getObject(e).reason,a.__wbindgen_malloc,a.__wbindgen_realloc),r=l;getInt32Memory0()[t/4+1]=r,getInt32Memory0()[t/4+0]=n},e.wbg.__wbg_now_559193109055ebad=function(t){return getObject(t).now()},e.wbg.__wbg_data_9e55e7d79ab13ef1=function(t){return addHeapObject(getObject(t).data)},e.wbg.__wbg_newwithstrandinit_9b0fa00478c37287=function(){return handleError((function(t,e,n){return addHeapObject(new Request(getStringFromWasm0(t,e),getObject(n)))}),arguments)},e.wbg.__wbg_instanceof_Blob_da9f4ebaadaae9ed=function(t){return getObject(t)instanceof Blob},e.wbg.__wbg_mksendret_2ddb0c3d74066b91=function(){return addHeapObject((function send_ret(t){return t}))},e.wbg.__wbg_trydownsize_6469cbea84321086=function(t){return addHeapObject(function try_downsize(t){switch(typeof t){case"bigint":if(-Number.MAX_SAFE_INTEGER<=t&&t<=Number.MAX_SAFE_INTEGER)return Number(t);case"number":return t;default:throw new Error(`number or bigint expected, got \`${t}\``)}}(takeObject(t)))},e.wbg.__wbg_isnumber_9dd7158c4e98db56=function(t){return function is_number(t){return"number"==typeof t}(getObject(t))},e.wbg.__wbg_tostring_e3961886d1042b76=function(t,e){var n=passStringToWasm0(function to_string(t){return t.toString()}(getObject(e)),a.__wbindgen_malloc,a.__wbindgen_realloc),r=l;getInt32Memory0()[t/4+1]=r,getInt32Memory0()[t/4+0]=n},e.wbg.__wbg_fromstring_02bfb2e556c6cc4c=function(t,e){return addHeapObject(function from_string(t){return BigInt(t)}(getStringFromWasm0(t,e)))},e.wbg.__wbg_getelement_8de75a26955a9ca9=function(t,e){return addHeapObject(function get_element(t,e){return t[e]}(getObject(t),e>>>0))},e.wbg.__wbg_typeof_005a8c22f80d0545=function(t,e){var n=passStringToWasm0(function typeof_(t){return typeof t}(getObject(e)),a.__wbindgen_malloc,a.__wbindgen_realloc),r=l;getInt32Memory0()[t/4+1]=r,getInt32Memory0()[t/4+0]=n},e.wbg.__wbindgen_number_new=function(t){return addHeapObject(t)},e.wbg.__wbindgen_is_null=function(t){return null===getObject(t)},e.wbg.__wbindgen_json_serialize=function(t,e){const n=getObject(e);var r=passStringToWasm0(JSON.stringify(void 0===n?null:n),a.__wbindgen_malloc,a.__wbindgen_realloc),i=l;getInt32Memory0()[t/4+1]=i,getInt32Memory0()[t/4+0]=r},e.wbg.__wbindgen_json_parse=function(t,e){return addHeapObject(JSON.parse(getStringFromWasm0(t,e)))},e.wbg.__wbg_new_949bbc1147195c4e=function(){return addHeapObject(new Array)},e.wbg.__wbg_valueOf_9578284a568a094f=function(t){return getObject(t).valueOf()},e.wbg.__wbindgen_is_function=function(t){return"function"==typeof getObject(t)},e.wbg.__wbg_newnoargs_be86524d73f67598=function(t,e){return addHeapObject(new Function(getStringFromWasm0(t,e)))},e.wbg.__wbg_next_c4151d46d5fa7097=function(t){return addHeapObject(getObject(t).next)},e.wbg.__wbg_next_7720502039b96d00=function(){return handleError((function(t){return addHeapObject(getObject(t).next())}),arguments)},e.wbg.__wbg_done_b06cf0578e89ff68=function(t){return getObject(t).done},e.wbg.__wbg_value_e74a542443d92451=function(t){return addHeapObject(getObject(t).value)},e.wbg.__wbg_iterator_4fc4ce93e6b92958=function(){return addHeapObject(Symbol.iterator)},e.wbg.__wbg_get_4d0f21c2f823742e=function(){return handleError((function(t,e){return addHeapObject(Reflect.get(getObject(t),getObject(e)))}),arguments)},e.wbg.__wbg_call_888d259a5fefc347=function(){return handleError((function(t,e){return addHeapObject(getObject(t).call(getObject(e)))}),arguments)},e.wbg.__wbg_new_0b83d3df67ecb33e=function(){return addHeapObject(new Object)},e.wbg.__wbg_push_284486ca27c6aa8b=function(t,e){return getObject(t).push(getObject(e))},e.wbg.__wbg_instanceof_ArrayBuffer_764b6d4119231cb3=function(t){return getObject(t)instanceof ArrayBuffer},e.wbg.__wbg_apply_7cfa6ebf144990a5=function(){return handleError((function(t,e,n){return addHeapObject(getObject(t).apply(getObject(e),getObject(n)))}),arguments)},e.wbg.__wbg_call_346669c262382ad7=function(){return handleError((function(t,e,n){return addHeapObject(getObject(t).call(getObject(e),getObject(n)))}),arguments)},e.wbg.__wbg_valueOf_99d85ac83228d11b=function(t){return getObject(t).valueOf()},e.wbg.__wbg_getTime_10d33f4f2959e5dd=function(t){return getObject(t).getTime()},e.wbg.__wbg_new0_fd3a3a290b25cdac=function(){return addHeapObject(new Date)},e.wbg.__wbg_now_af172eabe2e041ad=function(){return Date.now()},e.wbg.__wbg_instanceof_Object_66786225e0dbc8ba=function(t){return getObject(t)instanceof Object},e.wbg.__wbg_new_b1d61b5687f5e73a=function(t,e){try{var n={a:t,b:e},r=new Promise(((t,e)=>{const r=n.a;n.a=0;try{return function __wbg_adapter_327(t,e,n,r){a.wasm_bindgen__convert__closures__invoke2_mut__h1ddbd6d42d64ac99(t,e,addHeapObject(n),addHeapObject(r))}(r,n.b,t,e)}finally{n.a=r}}));return addHeapObject(r)}finally{n.a=n.b=0}},e.wbg.__wbg_resolve_d23068002f584f22=function(t){return addHeapObject(Promise.resolve(getObject(t)))},e.wbg.__wbg_then_2fcac196782070cc=function(t,e){return addHeapObject(getObject(t).then(getObject(e)))},e.wbg.__wbg_then_8c2d62e8ae5978f7=function(t,e,n){return addHeapObject(getObject(t).then(getObject(e),getObject(n)))},e.wbg.__wbg_self_c6fbdfc2918d5e58=function(){return handleError((function(){return addHeapObject(self.self)}),arguments)},e.wbg.__wbg_window_baec038b5ab35c54=function(){return handleError((function(){return addHeapObject(window.window)}),arguments)},e.wbg.__wbg_globalThis_3f735a5746d41fbd=function(){return handleError((function(){return addHeapObject(globalThis.globalThis)}),arguments)},e.wbg.__wbg_global_1bc0b39582740e95=function(){return handleError((function(){return addHeapObject(global.global)}),arguments)},e.wbg.__wbg_buffer_397eaa4d72ee94dd=function(t){return addHeapObject(getObject(t).buffer)},e.wbg.__wbg_newwithbyteoffsetandlength_4b9b8c4e3f5adbff=function(t,e,n){return addHeapObject(new Uint8Array(getObject(t),e>>>0,n>>>0))},e.wbg.__wbg_new_a7ce447f15ff496f=function(t){return addHeapObject(new Uint8Array(getObject(t)))},e.wbg.__wbg_set_969ad0a60e51d320=function(t,e,n){getObject(t).set(getObject(e),n>>>0)},e.wbg.__wbg_length_1eb8fc608a0d4cdb=function(t){return getObject(t).length},e.wbg.__wbg_instanceof_Uint8Array_08a1f3a179095e76=function(t){return getObject(t)instanceof Uint8Array},e.wbg.__wbg_newwithlength_929232475839a482=function(t){return addHeapObject(new Uint8Array(t>>>0))},e.wbg.__wbg_subarray_8b658422a224f479=function(t,e,n){return addHeapObject(getObject(t).subarray(e>>>0,n>>>0))},e.wbg.__wbg_has_1275b5eec3dc7a7a=function(){return handleError((function(t,e){return Reflect.has(getObject(t),getObject(e))}),arguments)},e.wbg.__wbg_set_82a4e8a85e31ac42=function(){return handleError((function(t,e,n){return Reflect.set(getObject(t),getObject(e),getObject(n))}),arguments)},e.wbg.__wbg_stringify_d4507a59932eed0c=function(){return handleError((function(t){return addHeapObject(JSON.stringify(getObject(t)))}),arguments)},e.wbg.__wbindgen_debug_string=function(t,e){var n=passStringToWasm0(debugString(getObject(e)),a.__wbindgen_malloc,a.__wbindgen_realloc),r=l;getInt32Memory0()[t/4+1]=r,getInt32Memory0()[t/4+0]=n},e.wbg.__wbindgen_throw=function(t,e){throw new Error(getStringFromWasm0(t,e))},e.wbg.__wbindgen_rethrow=function(t){throw takeObject(t)},e.wbg.__wbindgen_memory=function(){return addHeapObject(a.memory)},e.wbg.__wbindgen_closure_wrapper747=function(t,e,n){return addHeapObject(makeMutClosure(t,e,202,__wbg_adapter_36))},e.wbg.__wbindgen_closure_wrapper749=function(t,e,n){return addHeapObject(makeMutClosure(t,e,202,__wbg_adapter_39))},e.wbg.__wbindgen_closure_wrapper7605=function(t,e,n){return addHeapObject(makeMutClosure(t,e,2528,__wbg_adapter_42))},e.wbg.__wbindgen_closure_wrapper11610=function(t,e,n){return addHeapObject(makeMutClosure(t,e,3691,__wbg_adapter_45))},e.wbg.__wbindgen_closure_wrapper13425=function(t,e,n){return addHeapObject(makeMutClosure(t,e,4154,__wbg_adapter_48))},("string"==typeof t||"function"==typeof Request&&t instanceof Request||"function"==typeof URL&&t instanceof URL)&&(t=fetch(t));const{instance:n,module:r}=await async function load(t,e){if("function"==typeof Response&&t instanceof Response){if("function"==typeof WebAssembly.instantiateStreaming)try{return await WebAssembly.instantiateStreaming(t,e)}catch(e){if("application/wasm"==t.headers.get("Content-Type"))throw e;console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",e)}const n=await t.arrayBuffer();return await WebAssembly.instantiate(n,e)}{const n=await WebAssembly.instantiate(t,e);return n instanceof WebAssembly.Instance?{instance:n,module:t}:n}}(await t,e);return a=n.exports,init$3.__wbindgen_wasm_module=r,a}function documentSetCBORWithTimestamp(t,e,n,r,i){ensureInitialized();const o=function ditto_document_set_cbor_with_timestamp(t,e,n,r,i){return takeObject(a.ditto_document_set_cbor_with_timestamp(addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r),addHeapObject(i)))}(t,bytesFromString(e),n,r,i);if(0!==o)throw new Error(errorMessage()||`ditto_document_set_cbor_with_timestamp() failed with error code: ${o}`)}function documentSetCBOR(t,e,n,r){ensureInitialized();const i=function ditto_document_set_cbor(t,e,n,r){return takeObject(a.ditto_document_set_cbor(addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r)))}(t,bytesFromString(e),n,r);if(0!==i)throw new Error(errorMessage()||`ditto_document_set_cbor() failed with error code: ${i}`)}function documentID(t){ensureInitialized();return boxCBytesIntoBuffer(function ditto_document_id(t){return takeObject(a.ditto_document_id(addHeapObject(t)))}(t))}function documentCBOR(t){ensureInitialized();return boxCBytesIntoBuffer(function ditto_document_cbor(t){return takeObject(a.ditto_document_cbor(addHeapObject(t)))}(t))}function documentGetCBOR(t,e){ensureInitialized();const n=function ditto_document_get_cbor(t,e){return takeObject(a.ditto_document_get_cbor(addHeapObject(t),addHeapObject(e)))}(t,bytesFromString(e));return boxCBytesIntoBuffer(n)}function documentRemove(t,e){ensureInitialized();const n=function ditto_document_remove(t,e){return takeObject(a.ditto_document_remove(addHeapObject(t),addHeapObject(e)))}(t,bytesFromString(e));if(0!==n)throw new Error(errorMessage()||`ditto_document_remove() failed with error code: ${n}`)}function documentReplaceWithCounter(t,e){ensureInitialized();const n=function ditto_document_replace_with_counter(t,e){return takeObject(a.ditto_document_replace_with_counter(addHeapObject(t),addHeapObject(e)))}(t,bytesFromString(e)),r=errorMessage();if("InvalidPointer"===r)throw new Error(`Can't replace with counter, property does not exist at path or path is not valid: ${e}`);if(0!==n)throw new Error(r||`ditto_document_replace_with_counter() failed with error code: ${n}`)}function documentReplaceWithCounterWithTimestamp(t,e,n){ensureInitialized();const r=function ditto_document_replace_with_counter_with_timestamp(t,e,n){return takeObject(a.ditto_document_replace_with_counter_with_timestamp(addHeapObject(t),addHeapObject(e),addHeapObject(n)))}(t,bytesFromString(e),n),i=errorMessage();if("InvalidPointer"===i)throw new Error(`Can't replace with counter, property does not exist at path or path is not valid: ${e}`);if(0!==r)throw new Error(i||`ditto_document_replace_with_counter_with_timestamp() failed with error code: ${r}`)}function documentIncrementCounter(t,e,n){ensureInitialized();const r=function ditto_document_increment_counter(t,e,n){return takeObject(a.ditto_document_increment_counter(addHeapObject(t),addHeapObject(e),addHeapObject(n)))}(t,bytesFromString(e),n);if(0!==r)throw new Error(errorMessage()||`ditto_document_increment_counter() failed with error code: ${r}`)}function documentPushCBOR(t,e,n){ensureInitialized();const r=function ditto_document_push_cbor(t,e,n){return takeObject(a.ditto_document_push_cbor(addHeapObject(t),addHeapObject(e),addHeapObject(n)))}(t,bytesFromString(e),n);if(0!==r)throw new Error(errorMessage()||`ditto_document_push_cbor() failed with error code: ${r}`)}function documentPopCBOR(t,e){ensureInitialized();const n=bytesFromString(e),r=withOutBoxCBytes((e=>{const r=function ditto_document_pop_cbor(t,e,n){return takeObject(a.ditto_document_pop_cbor(addHeapObject(t),addHeapObject(e),addHeapObject(n)))}(t,n,e);if(0!==r)throw new Error(errorMessage()||`ditto_document_pop_cbor() failed with error code: ${r}`);return e}));return boxCBytesIntoBuffer(r)}function documentInsertCBOR(t,e,n){ensureInitialized();const r=function ditto_document_insert_cbor(t,e,n){return takeObject(a.ditto_document_insert_cbor(addHeapObject(t),addHeapObject(e),addHeapObject(n)))}(t,bytesFromString(e),n);if(0!==r)throw new Error(errorMessage()||`ditto_document_insert_cbor() failed with error code: ${r}`)}function documentFree(t){ensureInitialized(),function ditto_document_free(t){return takeObject(a.ditto_document_free(addHeapObject(t)))}(t)}function documentIDQueryCompatible(t,e){ensureInitialized();return boxCStringIntoString(function ditto_document_id_query_compatible(t,e){return takeObject(a.ditto_document_id_query_compatible(addHeapObject(t),addHeapObject(e)))}(t,e))}function validateDocumentID(t){ensureInitialized();return boxCBytesIntoBuffer(withOutBoxCBytes((e=>{const n=function ditto_validate_document_id(t,e){return takeObject(a.ditto_validate_document_id(addHeapObject(t),addHeapObject(e)))}(t,e);if(0!==n)throw new Error(errorMessage()||`ditto_validate_document_id() failed with error code: ${n}`);return e})))}async function collectionGet(t,e,n,r){ensureInitialized();const i=bytesFromString(e),{status_code:o,document:s}=await function ditto_collection_get(t,e,n,r){return takeObject(a.ditto_collection_get(addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r)))}(t,i,n,r);if(o===m)return null;if(0!==o)throw new Error(errorMessage()||`ditto_collection_get() failed with error code: ${o}`);return s}async function collectionInsertValue(t,e,n,r,i){ensureInitialized();const o=bytesFromString(e);let s;switch(i){case"merge":s="Merge";break;case"overwrite":s="Overwrite";break;case"insertIfAbsent":s="InsertIfAbsent";break;case"insertDefaultIfAbsent":s="InsertDefaultIfAbsent";break;default:throw new Error("Invalid write strategy provided")}const{status_code:c,id:d}=await function ditto_collection_insert_value(t,e,n,r,i,o){return takeObject(a.ditto_collection_insert_value(addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r),addHeapObject(i),addHeapObject(o)))}(t,o,n,r,s,null);if(0!==c)throw new Error(errorMessage()||`ditto_collection_insert_value() failed with error code: ${c}`);return boxCBytesIntoBuffer(d)}async function collectionRemove(t,e,n,r){ensureInitialized();const i=bytesFromString(e),{status_code:o,bool_value:s}=await function ditto_collection_remove(t,e,n,r){return takeObject(a.ditto_collection_remove(addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r)))}(t,i,n,r);if(0!==o)throw new Error(errorMessage()||`ditto_collection_remove() failed with error code: ${o}`);return s}async function collectionEvict(t,e,n,r){ensureInitialized();const i=bytesFromString(e),{status_code:o,bool_value:s}=await function ditto_collection_evict(t,e,n,r){return takeObject(a.ditto_collection_evict(addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r)))}(t,i,n,r);if(0!==o)throw new Error(errorMessage()||`ditto_collection_evict() failed with error code: ${o}`);return s}async function collectionUpdate(t,e,n,r){ensureInitialized();const i=bytesFromString(e),o=await function ditto_collection_update(t,e,n,r){return takeObject(a.ditto_collection_update(addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r)))}(t,i,n,r);if(0!==o)throw new Error(errorMessage()||`ditto_collection_update() failed with error code: ${o}`)}async function collectionUpdateMultiple(t,e,n,r){ensureInitialized();const i=bytesFromString(e),o=function jsDocsToCDocs(t){return takeObject(a.jsDocsToCDocs(addHeapObject(t)))}(r),s=await function ditto_collection_update_multiple(t,e,n,r){return takeObject(a.ditto_collection_update_multiple(addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r)))}(t,i,n,o);if(0!==s)throw new Error(errorMessage()||`ditto_collection_update_multiple() failed with error code: ${s}`)}async function collectionExecQueryStr(t,e,n,r,i,o,s,c){ensureInitialized();const d=bytesFromString(e),u=bytesFromString(r);return await function ditto_collection_exec_query_str(t,e,n,r,i,o,s,c){return takeObject(a.ditto_collection_exec_query_str(addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r),addHeapObject(i),addHeapObject(o),addHeapObject(s),addHeapObject(c)))}(t,d,n,u,i,o,s,c)}async function collectionRemoveQueryStr(t,e,n,r,i,o,s,c){ensureInitialized();const d=bytesFromString(e),u=bytesFromString(r);return await function ditto_collection_remove_query_str(t,e,n,r,i,o,s,c){return takeObject(a.ditto_collection_remove_query_str(addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r),addHeapObject(i),addHeapObject(o),addHeapObject(s),addHeapObject(c)))}(t,d,n,u,i,o,s,c)}async function collectionEvictQueryStr(t,e,n,r,i,o,s,c){ensureInitialized();const d=bytesFromString(e),u=bytesFromString(r);return await function ditto_collection_evict_query_str(t,e,n,r,i,o,s,c){return takeObject(a.ditto_collection_evict_query_str(addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r),addHeapObject(i),addHeapObject(o),addHeapObject(s),addHeapObject(c)))}(t,d,n,u,i,o,s,c)}function addSubscription(t,e,n,r){ensureInitialized();return function ditto_add_subscription(t,e,n,r){return takeObject(a.ditto_add_subscription(addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r)))}(t,bytesFromString(e),bytesFromString(n),r)}function removeSubscription(t,e,n,r){ensureInitialized();return function ditto_remove_subscription(t,e,n,r){return takeObject(a.ditto_remove_subscription(addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r)))}(t,bytesFromString(e),bytesFromString(n),r)}function liveQueryRegister(t,e,n,r,i,o,s,c,d){ensureInitialized();const u=bytesFromString(e),l=bytesFromString(n),{status_code:h,i64:b}=function ditto_live_query_register_str_detached(t,e,n,r,i,o,s,c){return takeObject(a.ditto_live_query_register_str_detached(addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r),addHeapObject(i),addHeapObject(o),addHeapObject(s),addHeapObject(c)))}(t,u,l,r,i,o,s,wrapBackgroundCbForFFI(d,c));if(0!==h)throw new Error(errorMessage()||`\`ditto_live_query_register_str()\` failed with error code: ${h}`);return b}async function liveQueryStart(t,e){ensureInitialized();const n=await function ditto_live_query_start(t,e){return takeObject(a.ditto_live_query_start(addHeapObject(t),addHeapObject(e)))}(t,e);if(0!==n)throw new Error(errorMessage()||`\`ditto_live_query_start()\` failed with error code: ${n}`)}function liveQueryStop(t,e){ensureInitialized(),function ditto_live_query_stop(t,e){return takeObject(a.ditto_live_query_stop(addHeapObject(t),addHeapObject(e)))}(t,e)}async function liveQuerySignalAvailableNext(t,e){ensureInitialized(),await function ditto_live_query_signal_available_next(t,e){return takeObject(a.ditto_live_query_signal_available_next(addHeapObject(t),addHeapObject(e)))}(t,e)}async function liveQueryWebhookRegister(t,e,n,r,i,o,s){ensureInitialized();const c=bytesFromString(e),d=bytesFromString(n),u=bytesFromString(s),{status_code:l,id:h}=await function ditto_live_query_webhook_register_str(t,e,n,r,i,o,s){return takeObject(a.ditto_live_query_webhook_register_str(addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r),addHeapObject(i),addHeapObject(o),addHeapObject(s)))}(t,c,d,r,i,o,u);if(0!==l)throw new Error(errorMessage()||`\`ditto_live_query_webhook_register_str()\` failed with error code: ${l}`);return boxCBytesIntoBuffer(h)}async function readTransaction(t){ensureInitialized();const{status_code:e,txn:n}=await function ditto_read_transaction(t){return takeObject(a.ditto_read_transaction(addHeapObject(t)))}(t);if(0!==e)throw new Error(errorMessage()||`\`ditto_read_transaction()\` failed with error code: ${e}`);return n}function readTransactionFree(t){return ensureInitialized(),function ditto_read_transaction_free(t){return takeObject(a.ditto_read_transaction_free(addHeapObject(t)))}(t)}async function writeTransaction(t){ensureInitialized();const{status_code:e,txn:n}=await function ditto_write_transaction(t){return takeObject(a.ditto_write_transaction(addHeapObject(t)))}(t);if(0!==e)throw new Error(errorMessage()||`ditto_write_transaction() failed with error code: ${e}`);return n}async function writeTransactionCommit(t,e){ensureInitialized();const n=await function ditto_write_transaction_commit(t,e){return takeObject(a.ditto_write_transaction_commit(addHeapObject(t),addHeapObject(e)))}(t,e);if(0!==n)throw new Error(errorMessage()||`ditto_write_transaction_commit() failed with error code: ${n}`)}function addStaticTCPClient(t,e){ensureInitialized();return(void 0)(t,bytesFromString(e))}function staticTCPClientFreeHandle(t){(void 0)(t)}function addWebsocketClient(t,e){ensureInitialized();return function ditto_add_websocket_client(t,e){return takeObject(a.ditto_add_websocket_client(addHeapObject(t),addHeapObject(e)))}(t,bytesFromString(e))}function websocketClientFreeHandle(t){ensureInitialized(),function websocket_client_free_handle(t){return takeObject(a.websocket_client_free_handle(addHeapObject(t)))}(t)}function loggerInit(){ensureInitialized(),function ditto_logger_init(){return takeObject(a.ditto_logger_init())}()}async function loggerSetCustomLogCb(t){if(ensureInitialized(),null===t)await ditto_logger_set_custom_log_cb(null);else{const e=wrapBackgroundCbForFFI(null,((e,n)=>{try{const r=boxCStringIntoString(n);t(e,r)}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(),function ditto_logger_enabled(t){return takeObject(a.ditto_logger_enabled(addHeapObject(t)))}(!!t)}function loggerEnabledGet(){return ensureInitialized(),!!function ditto_logger_enabled_get(){return takeObject(a.ditto_logger_enabled_get())}()}function loggerEmojiHeadingsEnabled(t){ensureInitialized(),function ditto_logger_emoji_headings_enabled(t){return takeObject(a.ditto_logger_emoji_headings_enabled(addHeapObject(t)))}(t)}function loggerEmojiHeadingsEnabledGet(){return ensureInitialized(),function ditto_logger_emoji_headings_enabled_get(){return takeObject(a.ditto_logger_emoji_headings_enabled_get())}()}function loggerMinimumLogLevel(t){ensureInitialized(),function ditto_logger_minimum_log_level(t){return takeObject(a.ditto_logger_minimum_log_level(addHeapObject(t)))}(t)}function loggerMinimumLogLevelGet(){return ensureInitialized(),function ditto_logger_minimum_log_level_get(){return takeObject(a.ditto_logger_minimum_log_level_get())}()}function loggerSetLogFile(t){ensureInitialized();if(0!==function ditto_logger_set_log_file(t){return takeObject(a.ditto_logger_set_log_file(addHeapObject(t)))}(t?bytesFromString(t):null))throw errorMessage(),new Error(`Can't set log file, due to error: ${errorMessage}`)}function log(t,e){ensureInitialized(),bytesFromString(t);!function ditto_log(t,e){return takeObject(a.ditto_log(addHeapObject(t),addHeapObject(e)))}(t,bytesFromString(e))}function dittoAuthClientMakeWithWeb(t,e,n,r){ensureInitialized();const i=bytesFromString(t),o=bytesFromString(e),s=bytesFromString(n),{status_code:c,auth_client:d}=function ditto_auth_client_make_with_web(t,e,n,r){return takeObject(a.ditto_auth_client_make_with_web(addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r)))}(i,o,s,r);if(0!==c)throw new Error(errorMessage()||`ditto_auth_client_make_with_web() failed with error code: ${c}`);return d}function dittoAuthClientMakeForDevelopment(t,e,n){ensureInitialized();const r=bytesFromString(t),i=bytesFromString(e),o=Number(n),{status_code:s,auth_client:c}=function ditto_auth_client_make_for_development(t,e,n){return takeObject(a.ditto_auth_client_make_for_development(addHeapObject(t),addHeapObject(e),addHeapObject(n)))}(r,i,o);if(0!==s)throw new Error(errorMessage()||`ditto_auth_client_make_for_development() failed with error code: ${s}`);return c}function dittoAuthClientMakeWithSharedKey(t,e,n,r){ensureInitialized();const i=bytesFromString(t),o=bytesFromString(e),s=bytesFromString(n),c=Number(r),{status_code:d,auth_client:u}=function ditto_auth_client_make_with_shared_key(t,e,n,r){return takeObject(a.ditto_auth_client_make_with_shared_key(addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r)))}(i,o,s,c);if(0!==d)throw new Error(errorMessage()||`ditto_auth_client_make_with_shared_key() failed with error code: ${d}`);return u}function dittoAuthClientMakeWithStaticX509(t){ensureInitialized();const e=bytesFromString(t),{status_code:n,auth_client:r}=function ditto_auth_client_make_with_static_x509(t){return takeObject(a.ditto_auth_client_make_with_static_x509(addHeapObject(t)))}(e);if(0!==n)throw new Error(errorMessage()||`ditto_auth_client_make_with_static_x509() failed with error code: ${n}`);return r}function dittoAuthClientGetSiteID(t){return ensureInitialized(),function ditto_auth_client_get_site_id(t){return takeObject(a.ditto_auth_client_get_site_id(addHeapObject(t)))}(t)}function dittoAuthClientFree(t){return ensureInitialized(),function ditto_auth_client_free(t){return takeObject(a.ditto_auth_client_free(addHeapObject(t)))}(t)}function dittoAuthClientIsWebValid(t){return ensureInitialized(),0!==function ditto_auth_client_is_web_valid(t){return takeObject(a.ditto_auth_client_is_web_valid(addHeapObject(t)))}(t)}function dittoAuthClientUserID(t){ensureInitialized();return boxCStringIntoString(function ditto_auth_client_user_id(t){return takeObject(a.ditto_auth_client_user_id(addHeapObject(t)))}(t))}function dittoAuthClientIsX509Valid(t){return ensureInitialized(),0!==function ditto_auth_client_is_x509_valid(t){return takeObject(a.ditto_auth_client_is_x509_valid(addHeapObject(t)))}(t)}async function dittoAuthClientLoginWithToken(t,e,n){ensureInitialized();const r=bytesFromString(e),i=bytesFromString(n),o=await function ditto_auth_client_login_with_token(t,e,n){return takeObject(a.ditto_auth_client_login_with_token(addHeapObject(t),addHeapObject(e),addHeapObject(n)))}(t,r,i);if(0!==o)throw new Error(errorMessage()||`Ditto failed to authenticate (error code: ${o}).`)}async function dittoAuthClientLoginWithUsernameAndPassword(t,e,n,r){ensureInitialized();const i=bytesFromString(e),o=bytesFromString(n),s=bytesFromString(r),c=await function ditto_auth_client_login_with_credentials(t,e,n,r){return takeObject(a.ditto_auth_client_login_with_credentials(addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r)))}(t,i,o,s);if(0!==c)throw new Error(errorMessage()||`Ditto failed to authenticate (error code: ${c}).`)}async function dittoAuthClientLogout(t){ensureInitialized();const e=await function ditto_auth_client_logout(t){return takeObject(a.ditto_auth_client_logout(addHeapObject(t)))}(t);if(0!==e)throw new Error(errorMessage()||`Ditto failed to logout (error code: ${e}).`)}function uninitializedDittoMake(t){ensureInitialized();return function uninitialized_ditto_make(t){return takeObject(a.uninitialized_ditto_make(addHeapObject(t)))}(bytesFromString(t))}function dittoMake(t,e){return ensureInitialized(),function ditto_make(t,e){return takeObject(a.ditto_make(addHeapObject(t),addHeapObject(e)))}(t,e)}async function dittoGetCollectionNames(t){ensureInitialized();const e=await function ditto_get_collection_names(t){return takeObject(a.ditto_get_collection_names(addHeapObject(t)))}(t),n=e.status_code,r=e.names;if(0!==n)throw new Error(errorMessage()||`ditto_get_collection_names() failed with error code: ${n}`);return function cStringVecToStringArray(t){return takeObject(a.cStringVecToStringArray(addHeapObject(t)))}(r)}async function dittoRegisterPresenceV1Callback(t,e){ensureInitialized(),e?function ditto_register_presence_v1_callback(t,e){return takeObject(a.ditto_register_presence_v1_callback(addHeapObject(t),addHeapObject(e)))}(t,wrapBackgroundCbForFFI((t=>console.error(`The registered presence callback errored with ${t}`)),(t=>{const n=function refCStringToString(t){return takeObject(a.refCStringToString(addHeapObject(t)))}(t);e(n)}))):await function ditto_clear_presence_callback(t){return takeObject(a.ditto_clear_presence_callback(addHeapObject(t)))}(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){ensureInitialized();let n=bytesFromString(e);if(n.length>64){n=bytesFromString(e.replace(/[^ -~]+/g,"").substr(0,63))}return function ditto_set_device_name(t,e){return takeObject(a.ditto_set_device_name(addHeapObject(t),addHeapObject(e)))}(t,n)}function dittoSetSyncGroup(t,e){return ensureInitialized(),function ditto_set_sync_group(t,e){return takeObject(a.ditto_set_sync_group(addHeapObject(t),addHeapObject(e)))}(t,e)}async function dittoNewAttachmentFromBytes(t,e){ensureInitialized();const n={},r=await function ditto_new_attachment_from_bytes(t,e,n){return takeObject(a.ditto_new_attachment_from_bytes(addHeapObject(t),addHeapObject(e),addHeapObject(n)))}(t,e,n);if(0!==r)throw new Error(errorMessage()||`ditto_new_attachment_from_bytes() failed with error code: ${r}`);return n}async function dittoResolveAttachment(t,e,n,r){ensureInitialized();const{onComplete:i,onProgress:o,onDelete:s}=n,{status_code:c,cancel_token:d}=await function ditto_resolve_attachment(t,e,n,r,i){return takeObject(a.ditto_resolve_attachment(addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r),addHeapObject(i)))}(t,e,wrapBackgroundCbForFFI(r,i),wrapBackgroundCbForFFI(r,o),wrapBackgroundCbForFFI(r,s));if(0!==c)throw new Error(errorMessage()||`ditto_resolve_attachment() failed with error code: ${c}`);return d}function dittoCancelResolveAttachment(t,e,n){ensureInitialized();const r=function ditto_cancel_resolve_attachment(t,e,n){return takeObject(a.ditto_cancel_resolve_attachment(addHeapObject(t),addHeapObject(e),addHeapObject(n)))}(t,e,n);if(0!==r)throw new Error(errorMessage()||`ditto_cancel_resolve_attachment() failed with error code: ${r}`)}async function dittoGetCompleteAttachmentData(t,e){ensureInitialized();const{status:n,data:r}=await function ditto_get_complete_attachment_data(t,e){return takeObject(a.ditto_get_complete_attachment_data(addHeapObject(t),addHeapObject(e)))}(t,e);if(0!==n)throw new Error(errorMessage()||`\`ditto_get_complete_attachment_data()\` failed with error code: ${n}`);return boxCBytesIntoBuffer(r)}function dittoGetSDKVersion(t){ensureInitialized();return boxCStringIntoString(function ditto_get_sdk_version(){return takeObject(a.ditto_get_sdk_version())}())}function dittoPresenceV1(t){ensureInitialized();return boxCStringIntoString(function ditto_presence_v1(t){return takeObject(a.ditto_presence_v1(addHeapObject(t)))}(t))}function dittoRunGarbageCollection(t){return ensureInitialized(),function ditto_run_garbage_collection(t){return takeObject(a.ditto_run_garbage_collection(addHeapObject(t)))}(t)}function documentsHash(t){ensureInitialized();const{status_code:e,u64:n}=function ditto_documents_hash(t){return takeObject(a.ditto_documents_hash(addHeapObject(t)))}(t);if(0!==e)throw new Error(errorMessage()||`\`ditto_documents_hash()\` failed with error code: ${e}`);return BigInt(n)}function documentsHashMnemonic(t){ensureInitialized();const{status_code:e,c_string:n}=function ditto_documents_hash_mnemonic(t){return takeObject(a.ditto_documents_hash_mnemonic(addHeapObject(t)))}(t);if(0!==e)throw new Error(errorMessage()||`\`ditto_documents_hash_mnemonic()\` failed with error code: ${e}`);return boxCStringIntoString(n)}function dittoAuthClientMakeLoginProvider(t,e){return ensureInitialized(),function ditto_auth_client_make_login_provider(t){return takeObject(a.ditto_auth_client_make_login_provider(addHeapObject(t)))}(wrapBackgroundCbForFFI(e,t))}function dittoAuthClientSetValidityListener(t,e,n){ensureInitialized();return function ditto_auth_client_set_validity_listener(t,e){return takeObject(a.ditto_auth_client_set_validity_listener(addHeapObject(t),addHeapObject(e)))}(t,wrapBackgroundCbForFFI(n,((t,n)=>e(1===t,1===n))))}let p,g=!1;async function init$2(t){t?await init$3(t):await init$3(),g=!0,p=function wrapFFIOutFunction(t){return function(...e){let n,r,i=!1;const o=e[e.length-1],a=e.splice(0,e.length-1),s=t(...a,(t=>{try{r=o(t),i=r===t}catch(t){n=t}}));if(n)throw n;return i?s:r}}(withOutPtr$1)}function initSDKVersion(t,e,n){ensureInitialized(),bytesFromString(t),bytesFromString(e);const r=function ditto_init_sdk_version(t,e,n){return takeObject(a.ditto_init_sdk_version(addHeapObject(t),addHeapObject(e),addHeapObject(n)))}(t,e,bytesFromString(n));if(void 0!==r&&0!==r)throw new Error(errorMessage()||`ditto_init_sdk_version() failed with error code: ${r}`)}const m=-30798;function wrapBackgroundCbForFFI(t,e){return void 0===t&&(t=console.error),(n,...r)=>{let i;try{i=e(...r)}catch(e){try{t(e)}catch(t){console.error(`Internal error: \`onError()\` handler oughtn't throw, but it did throw ${t}`)}}return n(i)}}function bytesFromString(t){if(void 0===t)return;if(null===t)return null;if("string"!=typeof t)throw new Error(`Can't convert string to Uint8Array, not a string: ${t}`);return(new TextEncoder).encode(`${t}\0`)}function errorMessage(){ensureInitialized();return boxCStringIntoString(function ditto_error_message(){return takeObject(a.ditto_error_message())}())}function ensureInitialized(){if(!g)throw new Error("Ditto needs to be initialized before using any of its API, please make sure to call `await init()` first.")}let w=null;if("undefined"!=typeof process&&"undefined"!=typeof require){const t=process.arch,e=process.platform;try{w=require(`./transports.${e}-${t}.node`)}catch(t){}}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}}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)}setLogFile(t){throw new Error("Deprecated, use Logger's static properties and methods directly instead.")}setLogFileURL(t){throw new Error("Deprecated, use Logger's static properties and methods directly instead.")}async setCustomLogCallback(t){throw new Error("Deprecated, use Logger's static properties and methods directly instead.")}static shared(){return Logger.warning("Logger.shared() is deprecated, use Logger's static properties & methods directly instead."),this}}class ObserverManager{constructor(t,e=null){this.id=t,this.keepAlive=e,this.isRegistered=!1,this.callbacksByToken={}}addObserver(t){var e;this.registerIfNeeded();const n=this.generateToken();return this.callbacksByToken[n]=t,null===(e=this.keepAlive)||void 0===e||e.retain(`${this.id}.${n}`),n}removeObserver(t){var e;delete this.callbacksByToken[t],null===(e=this.keepAlive)||void 0===e||e.release(`${this.id}.${t}`),this.unregisterIfNeeded()}notify(...t){const e=this.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(){!this.isRegistered&&(this.isRegistered=!0,this.register(this.notify.bind(this)))}unregisterIfNeeded(){!this.hasObservers()&&this.isRegistered&&(this.isRegistered=!1,this.unregister())}generateToken(){let t;do{t=Math.ceil(Math.random()*Number.MAX_SAFE_INTEGER)}while(this.callbacksByToken.hasOwnProperty(t));return t}async finalize(t){await this.removeObserver(t)}}class Observer{constructor(t,e,n={}){this.observerManager=t,this.token=e,this.options=n,n.stopsWhenFinalized&&Observer.finalizationRegistry.register(this,{observerManager:t,token:e},this)}get isStopped(){return void 0===this.token}stop(){const t=this.token;t&&(delete this.token,Observer.finalizationRegistry.unregister(this),this.observerManager.removeObserver(t))}static finalize(t){const{observerManager:e,token:n}=t;e.removeObserver(n)}}Observer.finalizationRegistry=new FinalizationRegistry(Observer.finalize);class Authenticator{constructor(t){this["@ditto.authenticationExpiring"]=function(t){throw new Error("Authenticator['@ditto.authenticationExpiring']() is abstract and must be implemented by subclasses.")},this["@ditto.authClientValidityChanged"]=function(t,e){throw new Error("Authenticator['@ditto.authClientValidityChanged']() is abstract and must be implemented by subclasses.")},this.keepAlive=t,this.status={isAuthenticated:!1,userID:null},this.loginSupported=!1,this.observerManager=new ObserverManager("AuthenticationStatusObservation",t)}get isAuthenticated(){return this.status.isAuthenticated}get userID(){return this.status.userID}loginWithToken(t,e){throw new Error("Authenticator.loginWithToken() is abstract and must be implemented by subclasses.")}loginWithUsernameAndPassword(t,e,n){throw new Error("Authenticator.loginWithUsernameAndPassword() is abstract and must be implemented by subclasses.")}logout(t){throw new Error("Authenticator.logout() is abstract and must be implemented by subclasses.")}observeStatus(t){const e=this.observerManager.addObserver(t);return new Observer(this.observerManager,e)}}class OnlineAuthenticator extends Authenticator{constructor(t,e,n,r){super(t),this["@ditto.authenticationExpiring"]=function(t){const e=this.authenticationHandler;t>0?e.authenticationExpiringSoon(this,t):e.authenticationRequired(this)},this["@ditto.authClientValidityChanged"]=function(t,e){this.updateAndNotify(!0)},this.loginSupported=!0,this.status={isAuthenticated:!1,userID:null},this.authClientPointer=e,this.ditto=new WeakRef(n),this.authenticationHandler=r,this.updateAndNotify(!1),OnlineAuthenticator.finalizationRegistry.register(this,e)}async loginWithToken(t,e){await dittoAuthClientLoginWithToken(this.authClientPointer,t,e)}async loginWithUsernameAndPassword(t,e,n){await dittoAuthClientLoginWithUsernameAndPassword(this.authClientPointer,t,e,n)}async logout(t){const e=this.ditto.deref();e?(await dittoAuthClientLogout(this.authClientPointer),e.stopSync(),null==t||t(this.ditto)):Logger.warning("Unable to logout, related Ditto object does not exist anymore.")}updateAndNotify(t){var e;const n=this.isAuthenticated,r=this.userID,i=dittoAuthClientIsWebValid(this.authClientPointer),o=dittoAuthClientUserID(this.authClientPointer),a={isAuthenticated:i,userID:o};if(this.status=a,t){!!n==!!i&&r===o||(null===(e=this.authenticationHandler.authenticationStatusDidChange)||void 0===e||e.call(this.authenticationHandler,this),this.observerManager.notify(a))}}static finalize(t){dittoAuthClientFree(t)}}OnlineAuthenticator.finalizationRegistry=new FinalizationRegistry(OnlineAuthenticator.finalize);class NotAvailableAuthenticator extends Authenticator{constructor(){super(...arguments),this["@ditto.authenticationExpiring"]=t=>{throw new Error(`Internal inconsistency, authentication is not available, yet the @ditto.authenticationExpiring() was called on authenticator: ${self}`)},this["@ditto.authClientValidityChanged"]=function(t,e){throw new Error(`Internal inconsistency, authentication is not available, yet the @ditto.authClientValidityChanged() was called on authenticator: ${self}`)}}async loginWithToken(t,e){throw new Error("Can't login, authentication is not supported for the identity in use, please use an onlineWithAuthentication identity.")}async loginWithUsernameAndPassword(t,e,n){throw new Error("Can't login, authentication is not supported for the identity in use, please use an onlineWithAuthentication identity.")}logout(t){throw new Error("Can't logout, authentication is not supported for the identity in use, please use an onlineWithAuthentication identity.")}}const y=["manual","sharedKey","offlinePlayground","development"],O=4294967296,v=9007199254740992;const j={decode:function decode(t,e,n){let r=new DataView(t),i=new Uint8Array(t),o=0,tagValueFunction=function(t,e){return t},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,i[o])}function readUint16(){return commitRead(2,r.getUint16(o))}function readUint32(){return commitRead(4,r.getUint32(o))}function readBreak(){return 255===i[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()*O+readUint32()}();if(31===t)return-1;throw new Error("Invalid length encoding")}function readIndefiniteStringLength(t){let e=readUint8();if(255===e)return-1;let n=readLength(31&e);if(n<0||e>>5!==t)throw new Error("Invalid indefinite length element");return n}function appendUtf16Data(t,e){for(let n=0;n<e;++n){let n=readUint8();128&n&&(n<224?(n=(31&n)<<6|63&readUint8(),e-=1):n<240?(n=(15&n)<<12|(63&readUint8())<<6|63&readUint8(),e-=2):(n=(15&n)<<18|(63&readUint8())<<12|(63&readUint8())<<6|63&readUint8(),e-=3)),n<65536?t.push(n):(n-=65536,t.push(55296|n>>10),t.push(56320|1023&n))}}"function"==typeof e&&(tagValueFunction=e),"function"==typeof n&&(simpleValFunction=n);let a=function decodeItem(){let t,e,n=readUint8(),i=n>>5,a=31&n;if(7===i)switch(a){case 25:return function readFloat16(){let t=new ArrayBuffer(4),e=new DataView(t),n=readUint16(),r=32768&n,i=31744&n,o=1023&n;if(31744===i)i=261120;else if(0!==i)i+=114688;else if(0!==o)return(r?-1:1)*o*5.960464477539063e-8;return e.setUint32(0,r<<16|i<<13|o<<13),e.getFloat32(0)}();case 26:return function readFloat32(){return commitRead(4,r.getFloat32(o))}();case 27:return function readFloat64(){return commitRead(8,r.getFloat64(o))}()}if(e=readLength(a),e<0&&(i<2||6<i))throw new Error("Invalid length");switch(i){case 0:return e;case 1:return-1-e;case 2:if(e<0){let n=[],r=0;for(;(e=readIndefiniteStringLength(i))>=0;)r+=e,n.push(readArrayBuffer(e));let o=new Uint8Array(r),a=0;for(t=0;t<n.length;++t)o.set(n[t],a),a+=n[t].length;return o}return readArrayBuffer(e);case 3:let n=[];if(e<0)for(;(e=readIndefiniteStringLength(i))>=0;)appendUtf16Data(n,e);else appendUtf16Data(n,e);let r="";for(t=0;t<n.length;t+=8192)r+=String.fromCharCode.apply(null,n.slice(t,t+8192));return r;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 a={};for(t=0;t<e||e<0&&!readBreak();++t){a[decodeItem()]=decodeItem()}return a;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 a},encode:function encode(t){let e,n=new ArrayBuffer(256),r=new DataView(n),i=new Uint8Array(n),o=0;function prepareWrite(t){let a=n.byteLength,s=o+t;for(;a<s;)a<<=1;if(a!==n.byteLength){let t=r;n=new ArrayBuffer(a),r=new DataView(n),i=new Uint8Array(n);let e=o+3>>2;for(let n=0;n<e;++n)r.setUint32(n<<2,t.getUint32(n<<2))}return e=t,r}function commitWrite(...t){o+=e}function writeUint8(t){commitWrite(prepareWrite(1).setUint8(o,t))}function writeUint8Array(t){prepareWrite(t.length),i.set(t,o),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),function writeUint16(t){commitWrite(prepareWrite(2).setUint16(o,t))}(e)):e<4294967296?(writeUint8(t<<5|26),function writeUint32(t){commitWrite(prepareWrite(4).setUint32(o,t))}(e)):(writeUint8(t<<5|27),function writeUint64(t){let e=t%O,n=(t-e)/O,r=prepareWrite(8);r.setUint32(o,n),r.setUint32(o+4,e),commitWrite()}(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(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}(t,-0))return writeUint8Array([249,128,0]);switch(typeof t){case"number":if(Math.floor(t)===t){if(0<=t&&t<=v)return writeTypeAndLength(0,t);if(-v<=t&&t<0)return writeTypeAndLength(1,-(t+1))}return writeUint8(251),function writeFloat64(t){commitWrite(prepareWrite(8).setFloat64(o,t))}(t);case"string":let n=[];for(e=0;e<t.length;++e){let r=t.charCodeAt(e);r<128?n.push(r):r<2048?(n.push(192|r>>6),n.push(128|63&r)):r<55296||r>=57344?(n.push(224|r>>12),n.push(128|r>>6&63),n.push(128|63&r)):(r=(1023&r)<<10,r|=1023&t.charCodeAt(++e),r+=65536,n.push(240|r>>18),n.push(128|r>>12&63),n.push(128|r>>6&63),n.push(128|63&r))}return writeTypeAndLength(3,n.length),writeUint8Array(n);default:let r,i;if(Array.isArray(t))for(r=t.length,writeTypeAndLength(4,r),e=0;e<r;e+=1)encodeItem(t[e]);else if(t instanceof Uint8Array)writeTypeAndLength(2,t.length),writeUint8Array(t);else if(ArrayBuffer.isView(t))i=new Uint8Array(t.buffer),writeTypeAndLength(2,i.length),writeUint8Array(i);else if(t instanceof ArrayBuffer||"function"==typeof SharedArrayBuffer&&t instanceof SharedArrayBuffer)i=new Uint8Array(t),writeTypeAndLength(2,i.length),writeUint8Array(i);else{let n=Object.keys(t);for(r=n.length,writeTypeAndLength(5,r),e=0;e<r;e+=1){let r=n[e];encodeItem(r),encodeItem(t[r])}}}}(t),"slice"in n)return n.slice(0,o);let a=new ArrayBuffer(o),s=new DataView(a);for(let t=0;t<o;++t)s.setUint8(t,r.getUint8(t));return a}};class CBOR{static encode(t){const e=j.encode(t);return new Uint8Array(e)}static decode(t){const e=t.buffer;return j.decode(e)}}class UpdateResult{constructor(t,e,n,r,i){this.type=t,this.docID=e,this.path=n,void 0!==r&&(this.value=r),void 0!==i&&(this.amount=i)}static set(t,e,n){return new UpdateResult("set",t,e,n,void 0)}static replacedWithCounter(t,e){return new UpdateResult("replacedWithCounter",t,e,void 0,void 0)}static incremented(t,e,n){return new UpdateResult("incremented",t,e,void 0,n)}static inserted(t,e,n){return new UpdateResult("inserted",t,e,n,void 0)}static removed(t,e){return new UpdateResult("removed",t,e,void 0,void 0)}static pushed(t,e,n){return new UpdateResult("pushed",t,e,n,void 0)}static popped(t,e,n){return new UpdateResult("popped",t,e,n,void 0)}}class AttachmentToken{constructor(t){if("ditto_attachment"!==t._type)throw new Error("Invalid attachment token");const e=t._id;if(!(e instanceof Uint8Array))throw new Error("Invalid attachment token id");const n=t._len;if("number"!=typeof n||n<0)throw new Error("Invalid attachment token length");const r=t._meta;if("object"!=typeof r)throw new Error("Invalid attachment token meta");this.id=e,this.len=n,this.metadata=r}}class Attachment{constructor(t,e){this.ditto=t,this.token=e}get metadata(){return this.token.metadata}getData(){return dittoGetCompleteAttachmentData(z.pointerFor(this.ditto),C.pointerFor(this))}copyToPath(t){throw new Error("Can't copy attachment to path, not available when running in the browser.")}}const C=new Bridge(Attachment,(function freeAttachmentHandle(t){ensureInitialized(),function ditto_free_attachment_handle(t){return takeObject(a.ditto_free_attachment_handle(addHeapObject(t)))}(t)}));class Counter{constructor(t,e){this.value=t,this.isDefault=!!e}increment(t){if(!this.mutDoc)throw new Error("Can't increment counter, only possible within the closure of a collection's update() method.");this.mutDoc.at(this.path,!0).increment(t),this.value+=t}static __newInternal(t,e,n){const r=new Counter(n);return r.mutDoc=t,r.path=e,r}}class Value{constructor(t,e={}){this.value=t,this.isDefault=!!e.isDefault}}const I=/^[A-Za-z0-9_]+$/,k=/^[A-Za-z_]/;function validateKeyPathComponent(t,e=!1){if(Number.isFinite(+t))return`[${t}]`;if("string"==typeof t)return k.test(t)&&I.test(t)?e?t:`.${t}`:`['${t}']`;throw new Error(`Invalid path component: ${t}.`)}const D=["push","pop","splice","unshift","shift"];function set(t,e,n){let r=n,i=!1;const o=n instanceof Counter,a=n instanceof Value;(o||a)&&(r=n.value,i=!!n.isDefault);const s=r instanceof Counter,c=r instanceof Value;if(o&&s)throw`Can't set counter at path '${e}', nesting of Counter within Counter is forbidden.`;if(o&&c)throw`Can't set counter at path '${e}', nesting of Value within Counter is forbidden.`;if(a&&s)throw`Can't set value at path '${e}', nesting of Counter within Value is forbidden.`;if(a&&c)throw`Can't set value at path '${e}', nesting of Value within Value is forbidden.`;MutableDocument.pathAt(t,e,!0).set(r,i),o&&MutableDocument.pathAt(t,e,!0).replaceWithCounter(i)}function proxyFactory(t,e,n){return new Proxy(t,{get(t,r,i){if("symbol"==typeof r)return t[r];if("object"==typeof t&&""===n){if("_value"===r)return MutableDocument.value(i);if("_valueAt"===r)return t=>MutableDocument.valueAt(i,t);if("_pathAt"===r)return t=>MutableDocument.pathAt(i,t);if("toJSON"===r)return MutableDocument.prototype.toJSON;if("string"==typeof r&&r.startsWith("@ditto."))return e[r]}if("_replaceWithCounterAt"===r)return t=>{const r=validateKeyPathComponent(t);return MutableDocument.replaceWithCounterAt(e,`${n}${r}`)};if("_incrementCounterAt"===r)return(t,r)=>{const i=validateKeyPathComponent(t);return MutableDocument.incrementCounterAt(e,`${n}${i}`,r)};if(t instanceof Counter)return t[r];const o=t[r],a=typeof o;if("undefined"!==a){if("function"===a&&D.includes(r)&&(t.__arrayOp=r),"object"!==a)return o;const i=validateKeyPathComponent(r,""===n);return proxyFactory(o,e,`${n}${i}`)}return o},set(t,r,i){const o=validateKeyPathComponent(r,""===n),a=`${n}${o}`;if("object"==typeof t&&""===n&&"string"==typeof r&&r.startsWith("@ditto."))return e[r]=i,!0;if("object"==typeof t&&Array.isArray(t)){if("length"===r){if(i===t.length-1){const r=t.__arrayOp;r&&"pop"===r&&(MutableDocument.pathAt(e,n,!0).pop(),t.pop())}return t[r]=i,delete t.__arrayOp,!0}const o=+r;if(isNaN(o))throw new Error(`Attempting to access a non-index property of an array. Property: ${r}.`);const s=t.__arrayOp;if(o===t.length&&s&&"push"===s)MutableDocument.pathAt(e,n,!0).push(i),t.push(i);else if(s){let n=t.__cachedSetOperations||[];if(o>t.length)n.push({index:o,value:i,path:a}),t.__cachedSetOperations=n;else{set(e,a,i),t[o]=i;let r=n.length;for(;r>0;){const i=n[r-1];i.index===t.length&&(set(e,i.path,i.value),t[i.index]=i.value,n.splice(r-1,1)),r--}}}else{if(!(o<=t.length))throw new Error(`Attempting to set an array index of ${o} but the array only has ${t.length} elements`);set(e,a,i),t[o]=i}}else{if(t instanceof Counter&&"value"===r);else{const n=+r;if(Number.isFinite(n))throw new Error(`Attempting to access an array index property (${n}) of an object: ${JSON.stringify(t)}.`);set(e,a,i)}t[r]=i}return!0},deleteProperty(t,r){if(r in t){const i=t.__arrayOp;if(i&&"pop"===i)return!0;const o=validateKeyPathComponent(r,""===n),a=`${n}${o}`;return MutableDocument.pathAt(e,a,!0).remove(),delete t[r],!0}return!1}})}function augmentJSONValue(t,e,n){let r={};if(""===n){for(const[n,i]of Object.entries(t))r[n]=augmentJSONValue(i,e,n);return r}if(t&&"object"==typeof t){if(Array.isArray(t))return t.map(((t,r)=>augmentJSONValue(t,e,`${n}[${r}]`)));if("ditto_counter"===t._type)return Counter.__newInternal(e,n,t._value);if("ditto_attachment"===t._type)return new AttachmentToken(t);for(const[r,i]of Object.entries(t))t[r]=augmentJSONValue(i,e,`${n}['${r}']`);return t}return t}function desugarJSObject(t,e){let n={};if(e){for(const[e,r]of Object.entries(t))n[e]=desugarJSObject(r,!1);return n}if(t&&"object"==typeof t){if(Array.isArray(t))return t.map(((t,e)=>desugarJSObject(t,!1)));if(t instanceof Counter)return t.value;if(t instanceof Attachment)return{_type:"ditto_attachment",_id:t.token.id,_len:t.token.len,_meta:t.token.metadata};for(const[e,n]of Object.entries(t))t[e]=desugarJSObject(n,!1);return t}return t}const E=/\.([A-Za-z_]\w*)/.source,A=/\[(\d+)\]/.source,S=/\[\'(.+?)\'\]/.source,P=/\[\"(.+?)\"\]/.source,H=`((${E})|(${A})|(${S})|(${P}))*`,F=new RegExp(`^${E}`),T=new RegExp(`^${A}`),R=new RegExp(`^${S}`),B=new RegExp(`^${P}`),M=new RegExp(`^${H}$`);class KeyPath{static withLeadingDot(t){if("number"==typeof t)return t;if("string"!=typeof t)throw new Error(`Key-path must be a string or a number but is ${typeof t}: ${t}`);return"string"==typeof t&&!!t.match(/^[A-Za-z_]/)?`.${t}`:t}static withoutLeadingDot(t){if("number"==typeof t)return t;if("string"!=typeof t)throw new Error(`Key-path must be a string or a number but is ${typeof t}: ${t}`);return"string"==typeof t&&!!t.match(/^\./)?t.slice(1):t}static validate(t,e={}){var n;const r=null!==(n=e.isInitial)&&void 0!==n&&n;if("number"==typeof t)return Math.floor(Math.abs(t));if("string"!=typeof t)throw new Error(`Key-path must be a string or a number but is ${typeof t}: ${t}`);const i=this.withLeadingDot(t);if(!M.test(i))throw new Error(`Key-path is not valid: ${t}`);return r?t:i}static evaluate(t,e,n={}){var r;const i=null!==(r=n.stopAtLastContainer)&&void 0!==r&&r,o={keyPath:t,object:e,options:{...n},coveredPath:null,nextPathComponent:null,remainingPath:t,value:e};return function recurse(t,e){if(""===e)return o.value=t,o;const{nextPathComponentRaw:n,nextPathComponent:r,remainingPath:a}=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(F);if(null!==e){const n=e[0],r=e[1];return{nextPathComponentRaw:n,nextPathComponent:r,remainingPath:t.slice(r.length+1)}}const n=t.match(T);if(null!==n){const e=n[0],r=n[1];return{nextPathComponentRaw:e,nextPathComponent:parseInt(r),remainingPath:t.slice(r.length+2)}}const r=t.match(R);if(null!==r){const e=r[0],n=r[1];return{nextPathComponentRaw:e,nextPathComponent:n,remainingPath:t.slice(n.length+4)}}const i=t.match(B);if(null!==i){const e=i[0],n=i[1];return{nextPathComponentRaw:e,nextPathComponent:n,remainingPath:t.slice(n.length+4)}}throw new Error(`Can't return value at keyPath because the following part of the keyPath is invalid: ${t}`)}(e);return o.nextPathComponent=r,o.remainingPath=a,null===o.coveredPath||"number"==typeof n?o.coveredPath=n:o.coveredPath+=n,""===a&&i?(o.value=t,o):recurse(t[r],a)}(e,this.withLeadingDot(t))}constructor(){}}class DocumentPath{constructor(t,e){this.document=t,this.path=e}at(t){if("string"==typeof t){const e=t,n=KeyPath.validate(e);return new DocumentPath(this.document,`${this.path}${n}`)}if("number"==typeof t){const e=validateNumber(t,{integer:!0,min:0,errorMessagePrefix:"DocumentPath.atIndex() validation failed index:"});return new DocumentPath(this.document,`${this.path}[${e.toString()}]`)}throw new Error(`Can't return document path at key-path or index, string or number expected but got ${typeof t}: ${t}`)}value(){return Document.valueAt(this.document,this.path)}atIndex(t){return Logger.warning("Method DocumentPath.atIndex() is deprecated, use DocumentPath.at() instead."),this.at(t)}}class MutableDocumentPath{constructor(t,e){this.mutableDocument=t,this.path=e}at(t){if("string"==typeof t){const e=t;return KeyPath.validate(e),new MutableDocumentPath(this.mutableDocument,`${this.path}.${e}`)}if("number"==typeof t){const e=validateNumber(t,{integer:!0,min:0,errorMessagePrefix:"MutableDocumentPath.atIndex() validation failed index:"});return new MutableDocumentPath(this.mutableDocument,`${this.path}[${e.toString()}]`)}throw new Error(`Can't return mutable document path at key-path or index, string or number expected but got ${typeof t}: ${t}`)}value(){return MutableDocument.valueAt(this.mutableDocument,this.path)}set(t,e){const n=L.pointerFor(this.mutableDocument),r=desugarJSObject(t,!1),i=CBOR.encode(r);e?documentSetCBORWithTimestamp(n,this.path,i,!0,0):documentSetCBOR(n,this.path,i,!0),this.updateInMemoryByReloadingLastPathComponent();const o=augmentJSONValue(CBOR.decode(i),this.mutableDocument,this.path),a=UpdateResult.set(MutableDocument.id(this.mutableDocument),this.path,o);this.recordUpdateResult(a)}remove(){documentRemove(L.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(MutableDocument.id(this.mutableDocument),this.path);this.recordUpdateResult(t)}replaceWithCounter(t){const e=L.pointerFor(this.mutableDocument);t?documentReplaceWithCounterWithTimestamp(e,this.path,0):documentReplaceWithCounter(e,this.path),this.updateInMemoryByReloadingLastPathComponent();const n=UpdateResult.replacedWithCounter(MutableDocument.id(this.mutableDocument),this.path);this.recordUpdateResult(n)}increment(t){documentIncrementCounter(L.pointerFor(this.mutableDocument),this.path,t),this.updateInMemoryByReloadingLastPathComponent();const e=UpdateResult.incremented(MutableDocument.id(this.mutableDocument),this.path,t);this.recordUpdateResult(e)}push(t){const e=L.pointerFor(this.mutableDocument),n=desugarJSObject(t,!1),r=CBOR.encode(n);documentPushCBOR(e,this.path,r),this.updateInMemory(((e,n)=>{const r=e[n];if(!Array.isArray(r))throw new Error(`Can't push value, object at key-path ${this.path} is not an array.`);r.push(t)}));const i=augmentJSONValue(CBOR.decode(r),this.mutableDocument,this.path),o=UpdateResult.pushed(MutableDocument.id(this.mutableDocument),this.path,i);this.recordUpdateResult(o)}pop(){const t=documentPopCBOR(L.pointerFor(this.mutableDocument),this.path),e=augmentJSONValue(CBOR.decode(t),this.mutableDocument,this.path);this.updateInMemory(((t,e)=>{const n=t[e];if(!Array.isArray(n))throw new Error(`Can't pop, object at key-path ${this.path} is not an array.`);n.pop()}));const n=UpdateResult.popped(MutableDocument.id(this.mutableDocument),this.path,e);return this.recordUpdateResult(n),e}insert(t){const e=L.pointerFor(this.mutableDocument),n=desugarJSObject(t),r=CBOR.encode(n);documentInsertCBOR(e,this.path,r),this.updateInMemory(((e,n)=>{const r=e[n],i=n;if(!Array.isArray(r))throw new Error(`Can't insert value, object at key-path ${this.path} is not an array.`);if("number"==typeof i)throw new Error(`Can't insert value, last path component in key-path ${this.path} is not a number.`);r.splice(i,0,t)}));const i=augmentJSONValue(CBOR.decode(r),this.mutableDocument,this.path),o=UpdateResult.inserted(MutableDocument.id(this.mutableDocument),this.path,i);this.recordUpdateResult(o)}updateInMemory(t){const e=MutableDocument.value(this.mutableDocument),n=KeyPath.evaluate(this.path,e,{stopAtLastContainer:!0});t(n.value,n.nextPathComponent)}updateInMemoryByReloadingLastPathComponent(){const t=L.pointerFor(this.mutableDocument);this.updateInMemory(((e,n)=>{const r=documentGetCBOR(t,this.path),i=augmentJSONValue(CBOR.decode(r),this.mutableDocument,this.path);e[n]=i}))}recordUpdateResult(t){const e=this.mutableDocument["@ditto.updateResults"].slice();e.push(t),Object.freeze(e),this.mutableDocument["@ditto.updateResults"]=e}atIndex(t){return Logger.warning("Method MutableDocumentPath.atIndex() is deprecated, use MutableDocumentPath.at() instead."),this.at(t)}}class Document{static id(t){let e=t["@ditto.id"];if(void 0===e){const n=documentID($.pointerFor(t));e=CBOR.decode(n),t["@ditto.id"]=e}return e}static value(t){let e=t["@ditto.value"];if(void 0===e){const n=documentCBOR($.pointerFor(t));e=augmentJSONValue(CBOR.decode(n),void 0,""),t["@ditto.value"]=e}return e}static stringForID(t){return documentIDQueryCompatible(validateDocumentIDCBOR(CBOR.encode(t)),"WithQuotes")}static base64StringForID(t){const e=validateDocumentIDCBOR(CBOR.encode(t));return btoa(String.fromCharCode.apply(null,e))}static valueAt(t,e){const n=this.value(t);return KeyPath.evaluate(e,n).value}static pathAt(t,e,n=!1){const r=n?e:KeyPath.validate(e,{isInitial:!0});return new DocumentPath(t,r)}static hash(t){return documentsHash(documentsFrom(t).map((t=>$.pointerFor(t))))}static hashMnemonic(t){return documentsHashMnemonic(documentsFrom(t).map((t=>$.pointerFor(t))))}toJSON(){return Document.value(this)}constructor(){return new Proxy(this,{get:function(t,e,n){if("symbol"==typeof e)return t[e];if("_id"===e)return Document.id(n);if("_value"===e)return Document.value(n);if("_valueAt"===e)return t=>Document.valueAt(n,t);if("_pathAt"===e)return t=>Document.pathAt(n,t);if("toJSON"===e)return Reflect.get(t,e,n);if("constructor"===e)return Reflect.get(t,e,n);if("string"==typeof e&&e.startsWith("@ditto."))return Reflect.get(t,e,n);const r=Document.value(t);return r.hasOwnProperty(e)?Reflect.get(r,e,n):Reflect.get(t,e,n)},ownKeys:function(t){return Reflect.ownKeys(Document.value(t))},set:function(t,e,n){if("string"==typeof e&&e.startsWith("@ditto."))return Reflect.set(t,e,n);throw new Error("Document is immutable and can't be mutated.")}})}static idCBOR(t){return documentID($.pointerFor(t))}static canonicalizedIDCBOR(t){return validateDocumentIDCBOR(t)}static isIDCBORCanonical(t){return t===this.canonicalizedIDCBOR(t)}}class MutableDocument{constructor(){this["@ditto.updateResults"]=[]}static id(t){let e=t["@ditto.id"];if(void 0===e){const n=documentID(L.pointerFor(t));e=CBOR.decode(n),t["@ditto.id"]=e}return e}static value(t){let e=t["@ditto.value"];if(void 0===e){const n=documentCBOR(L.pointerFor(t));e=augmentJSONValue(CBOR.decode(n),this,""),t["@ditto.value"]=e}return e}static valueAt(t,e){const n=this.value(t);return KeyPath.evaluate(e,n).value}static pathAt(t,e,n=!1){const r=n?e:KeyPath.validate(e,{isInitial:!0});return new MutableDocumentPath(t,r)}static replaceWithCounterAt(t,e,n=!1){this.pathAt(t,e,n).replaceWithCounter()}static incrementCounterAt(t,e,n,r=!1){this.pathAt(t,e,r).increment(n)}toJSON(){return MutableDocument.value(this)}static idCBOR(t){return documentID(L.pointerFor(t))}}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}MutableDocument.canonicalizedIDCBOR=Document.canonicalizedIDCBOR,MutableDocument.isIDCBORCanonical=Document.isIDCBORCanonical;const $=new Bridge(Document,documentFree),L=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 AttachmentFetcher{constructor(t,e,n){this.ditto=t,this.token=e,this.eventHandler=n||null,this.cancelToken=null;const r=n||function(){};this.attachment=new Promise(((n,i)=>{const o=z.pointerFor(t);this.cancelToken=dittoResolveAttachment(o,e.id,{onComplete:t=>{this.eventHandler=null,this.cancelToken=null;const e=new Attachment(this.ditto,this.token);C.bridge(t,(()=>e),{throwIfAlreadyBridged:!0}),r({type:"Completed",attachment:e}),n(e)},onProgress:(t,e)=>{r({type:"Progress",totalBytes:e,downloadedBytes:t})},onDelete:()=>{this.eventHandler=null,this.cancelToken=null,r({type:"Deleted"}),n(null)}},(t=>{this.eventHandler=null,this.cancelToken=null,i(t)}))}))}stop(){step((async()=>{const t=await this.cancelToken;if(t){this.cancelToken=null;dittoCancelResolveAttachment(z.pointerFor(this.ditto),this.token.id,t)}}))}then(t,e){return this.attachment.then(t,e)}}class Subscription{constructor(t,e,n){this.isCancelled=!1,this.query=e,this.queryArgsCBOR=n,this.collection=t,this.contextInfo={ditto:t.store.ditto,collectionName:t.name,query:e,queryArgsCBOR:n},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(z.pointerFor(e.ditto),e.collectionName,e.query,e.queryArgsCBOR),this.finalizationRegistry.register(t,e,e)}static remove(t,e){removeSubscription(z.pointerFor(e.ditto),e.collectionName,e.query,e.queryArgsCBOR),t&&this.finalizationRegistry.unregister(e)}}Subscription.finalizationRegistry=new FinalizationRegistry((t=>{Subscription.remove(null,t)}));class UpdateResultsMap{constructor(t,e){const n=t.map((t=>Document.stringForID(t))).sort().join(", ");if(n!==Object.keys(e).sort().join(", "))throw new Error("Internal inconsistency, can't construct update results map, documentIDs must all be keys in update results (by document ID string)");this.documentIDs=t.slice(),this.updateResultsByDocumentIDString={...e}}get(t){const e=Document.stringForID(t);return this.updateResultsByDocumentIDString[e]}keys(){return this.documentIDs.slice()}}class LiveQueryEventInitial{constructor(){this.isInitial=!0}hash(t){return documentsHash(t.map((t=>$.pointerFor(t))))}hashMnemonic(t){return documentsHashMnemonic(t.map((t=>$.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=>$.pointerFor(t))))}hashMnemonic(t){return documentsHashMnemonic(t.map((t=>$.pointerFor(t))))}}class SingleDocumentLiveQueryEvent{constructor(t,e){this.isInitial=t,this.oldDocument=e}hash(t){return documentsHash(null===t?[]:[$.pointerFor(t)])}hashMnemonic(t){return documentsHashMnemonic(null===t?[]:[$.pointerFor(t)])}}class LiveQuery{constructor(t,e,n,r,i,o,a,s,c){this.query=t,this.queryArgs=e?Object.freeze({...e}):null,this.queryArgsCBOR=n,this.orderBys=r,this.limit=i,this.offset=o,this.collection=a,this.handler=c,s&&(this.subscription=s);const d=z.pointerFor(a.store.ditto),u=a.name;let l;const signalNext=async()=>{await liveQuerySignalAvailableNext(d,l)};if(l=liveQueryRegister(d,u,t,n,this.orderBys,i,o,(t=>{const e=t.documents.map((t=>$.bridge(t)));let n;n=t.is_initial?new LiveQueryEventInitial:new LiveQueryEventUpdate({oldDocuments:t.old_documents.map((t=>$.bridge(t))),insertions:t.insertions,deletions:t.deletions,updates:t.updates,moves:t.moves.map((t=>({from:t[0],to:t[1]})))}),c(e,n,signalNext)})),!l)throw new Error("Internal inconsistency, couldn't create a valid live query ID.");this.liveQueryID=l,step((async()=>await liveQueryStart(d,l))),a.store.ditto.keepAlive.retain(`LiveQuery.${l}`)}get collectionName(){return this.collection.name}get isStopped(){return null!==this.liveQueryID}stop(){var t;const e=this.liveQueryID;if(null!==e){this.collection.store.ditto.keepAlive.release(`LiveQuery.${e}`),this.liveQueryID=null;const n=z.pointerFor(this.collection.store.ditto);null===(t=this.subscription)||void 0===t||t.cancel(),liveQueryStop(n,e)}}async signalNext(){const t=z.pointerFor(this.collection.store.ditto);await liveQuerySignalAvailableNext(t,this.liveQueryID)}}class PendingCursorOperation{constructor(t,e,n){this.currentLimit=-1,this.currentOffset=0,this.orderBys=[],this.query=validateQuery(t),this.queryArgs=e?Object.freeze({...e}):null,this.collection=n,this.queryArgsCBOR=e?CBOR.encode(e):null}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)}observe(t){return this._observe(t,!0,!1)}observeWithNextSignal(t){return 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=z.pointerFor(this.collection.store.ditto);return(await o((async()=>{const n=await writeTransaction(e),r=await collectionRemoveQueryStr(e,this.collection.name,n,t,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);return await writeTransactionCommit(e,n),r}))).map((t=>CBOR.decode(t)))}async evict(){const t=this.query,e=z.pointerFor(this.collection.store.ditto);return(await o((async()=>{const n=await writeTransaction(e),r=await collectionEvictQueryStr(e,this.collection.name,n,t,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);return await writeTransactionCommit(e,n),r}))).map((t=>CBOR.decode(t)))}async exec(){const t=this.query,e=z.pointerFor(this.collection.store.ditto);return(await o((async()=>{const n=await writeTransaction(e),r=await collectionExecQueryStr(e,this.collection.name,n,t,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);return await writeTransactionCommit(e,n),r}))).map((t=>$.bridge(t)))}async update(t){return await o((async()=>{const e=this.query,n=z.pointerFor(this.collection.store.ditto),r=await writeTransaction(n),i=await collectionExecQueryStr(n,this.collection.name,r,e,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset),o=i.map((t=>L.bridge(t,(()=>new MutableDocument)))),a=o.map((t=>proxyFactory(MutableDocument.value(t),t,"")));t(a);const s=[],c={};for(const t of o){const e=MutableDocument.id(t),n=Document.stringForID(e),r=t["@ditto.updateResults"];if(c[n])throw new Error(`Internal inconsistency, update results for document ID as string already exist: ${n}`);s.push(e),c[n]=r,L.pointerFor(t),L.unregister(t)}return await collectionUpdateMultiple(n,this.collection.name,r,i),await writeTransactionCommit(n,r),new UpdateResultsMap(s,c)}))}then(t,e){return this.exec().then(t,e)}_observe(t,e,n){const r=e?this.subscribe():null,i=n?t:function(e,n,r){try{return t.call(this,e,n)}finally{r()}};return new LiveQuery(this.query,this.queryArgs,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset,this.collection,r,i)}}class PendingIDSpecificOperation{constructor(t,e,n=!1){this.documentID=t,this.collection=e,this.documentIDCBOR=n?t:validateDocumentIDCBOR(CBOR.encode(t))}subscribe(){return new Subscription(this.collection,this.query,null)}observe(t){return this._observe(t,!0,!1)}observeWithNextSignal(t){return 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=z.pointerFor(this.collection.store.ditto);return await o((async()=>{const e=await writeTransaction(t),n=await collectionRemove(t,this.collection.name,e,this.documentIDCBOR);return await writeTransactionCommit(t,e),n}))}async evict(){const t=z.pointerFor(this.collection.store.ditto);return await o((async()=>{const e=await writeTransaction(t),n=await collectionEvict(t,this.collection.name,e,this.documentIDCBOR);return await writeTransactionCommit(t,e),n}))}async exec(){const t=z.pointerFor(this.collection.store.ditto);return await o((async()=>{const e=await readTransaction(t),n=await collectionGet(t,this.collection.name,this.documentIDCBOR,e);let r;return n&&(r=$.bridge(n)),readTransactionFree(e),r}))}async update(t){const e=z.pointerFor(this.collection.store.ditto),n=await readTransaction(e),r=await collectionGet(e,this.collection.name,this.documentIDCBOR,n);if(readTransactionFree(n),!r)throw new Error(`Can't update, document with ID '${this.documentID}' not found in collection named '${this.collection.name}'`);const i=L.bridge(r,(()=>new MutableDocument));t(proxyFactory(MutableDocument.value(i),i,"")),L.unregister(i);const o=await writeTransaction(e);return await collectionUpdate(e,this.collection.name,o,r),await writeTransactionCommit(e,o),i["@ditto.updateResults"].slice()}then(t,e){return this.exec().then(t,e)}get query(){return`_id == ${Document.stringForID(this.documentID)}`}_observe(t,e,n){const r=e?this.subscribe():null;return new LiveQuery(this.query,null,null,[],-1,0,this.collection,r,((e,r,i)=>{if(e.length>1){const t=e.map((t=>Document.base64StringForID(t._id)));throw new Error(`Internal inconsistency, single document live query returned more than one document. Query: ${this.query}, documentIDs: ${t.join(", ")}.`)}if(!1===r.isInitial&&r.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===r.isInitial&&r.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===r.isInitial&&r.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===r.isInitial&&r.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===r.isInitial&&r.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===r.isInitial?0:r.insertions.length+r.deletions.length+r.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,a=!0===r.isInitial?void 0:r.oldDocuments[0],s=new SingleDocumentLiveQueryEvent(r.isInitial,a);if(n)t(o,s,i);else try{t(o,s)}finally{i()}}))}}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=validateDocumentIDValue(t);return new PendingIDSpecificOperation(e,this)}async upsert(t,e={}){var n;const r=null!==(n=e.writeStrategy)&&void 0!==n?n:"merge";return this._insert(t,{writeStrategy:r})}async insert(t,e={}){return Logger.warning("Collection.insert() is deprecated, please use upsert() instead."),this._insert(t,e)}async newAttachment(t,e={}){const n=this.store.ditto,r=z.pointerFor(n),{id:i,len:o,handle:a}=await(async()=>{if("string"==typeof t)throw new Error("Can't create attachment from file when running in the browser. Please pass the raw data (as a Uint8Array) instead.");if(t instanceof Uint8Array)return await dittoNewAttachmentFromBytes(r,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}`)})(),s=new AttachmentToken({_type:"ditto_attachment",_id:i,_len:o,_meta:{...e}}),c=new Attachment(n,s);return C.bridge(a,(()=>c),{throwIfAlreadyBridged:!0})}fetchAttachment(t,e){const n=this.store.ditto;return new AttachmentFetcher(n,t,e)}findByIDCBOR(t){return new PendingIDSpecificOperation(t,this,!0)}async _insert(t,e={}){var n,r,i;const a=null!==(n=e.id)&&void 0!==n?n:t._id,s=null!==(r=e.isDefault)&&void 0!==r&&r,c=null!==(i=e.writeStrategy)&&void 0!==i?i:s?"insertDefaultIfAbsent":"overwrite";if(s&&e.writeStrategy&&"insertDefaultIfAbsent"!==e.writeStrategy)throw new Error("Incompatible isDefault and writeStrategy options.");const d=this.store.ditto,u=z.pointerFor(d),l=void 0===a?void 0:validateDocumentIDValue(a),h=void 0===l?null:validateDocumentIDCBOR(CBOR.encode(l)),b=desugarJSObject(t,!0),_=CBOR.encode(b),f=await o((async()=>await collectionInsertValue(u,this.name,_,h,c)));return CBOR.decode(f)}}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.pendingCursorOperation=new PendingCursorOperation("true",null,new Collection("__collections",t)),this.store=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 this.pendingCursorOperation.observe(((e,n)=>{const r=collectionsFromDocuments(e,this.store);let i;if(!0===n.isInitial)i=CollectionsEvent.initial(r);else{const t=collectionsFromDocuments(n.oldDocuments,this.store);i=new CollectionsEvent({isInitial:!1,collections:r,oldCollections:t,insertions:n.insertions,deletions:n.deletions,updates:n.updates,moves:n.moves})}t(i)}))}async exec(){return collectionsFromDocuments(await this.pendingCursorOperation.exec(),this.store)}then(t,e){return this.exec().then(t,e)}}function collectionsFromDocuments(t,e){const n=[];return t.forEach((t=>{const r=t.name;void 0!==r&&"string"==typeof r&&n.push(new Collection(r,e))})),n}class Store{constructor(t){this.ditto=t}collection(t){return new Collection(t,this)}collections(){return new PendingCollectionsOperation(this.ditto.store)}collectionNames(){return dittoGetCollectionNames(z.pointerFor(this.ditto))}async registerLiveQueryWebhook(t,e,n){const r=validateQuery(e),i=await liveQueryWebhookRegister(z.pointerFor(this.ditto),t,r,[],0,0,n);return CBOR.decode(i)}}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 PresenceManager{constructor(t){this.ditto=t,this.isRegistered=!1,this.currentRemotePeers=[],this.callbacksByPresenceToken={}}addObserver(t){this.registerIfNeeded();const e=this.generatePresenceToken();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=z.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(z.pointerFor(this.ditto),null),this.currentRemotePeers=[]}}generatePresenceToken(){let t;do{t=Math.ceil(Math.random()*Number.MAX_SAFE_INTEGER)}while(this.callbacksByPresenceToken.hasOwnProperty(t));return t}handlePresenceV1Callback(t){const e=this.decode(t).sort(this.compareRemotePeers);this.currentRemotePeers=e,this.notify()}notify(){for(const t in this.callbacksByPresenceToken){(0,this.callbacksByPresenceToken[t])(this.currentRemotePeers)}}decode(t){return JSON.parse(t).map((t=>{var e,n;return{networkID:t.network_id,deviceName:t.device_name,rssi:null!==(e=t.rssi)&&void 0!==e?e:void 0,approximateDistanceInMeters:null!==(n=t.approximate_distance_in_meters)&&void 0!==n?n:void 0,connections:t.connections}}))}finalize(t){this.removeObserver(t)}compareRemotePeers(t,e){return 0===t.connections.length&&e.connections.length>0?1:t.connections.length>0&&0===e.connections.length||t.deviceName<e.deviceName?-1:t.deviceName>e.deviceName?1:0}}class TransportConditionsManager extends ObserverManager{constructor(t){super("TransportConditionsObservation",t.keepAlive),this.ditto=t}register(t){return dittoRegisterTransportConditionChangedCallback(z.pointerFor(this.ditto),t)}unregister(){return dittoRegisterTransportConditionChangedCallback(z.pointerFor(this.ditto),null)}processCallback(t,e){let n,r;switch(t){case"Bluetooth":n="BLE";break;case"Tcp":n="TCP";break;case"Awdl":n="AWDL";break;case"Mdns":n="MDNS"}switch(e){case"Unknown":r="Unknown";break;case"Ok":r="OK";break;case"GenericFailure":r="GenericFailure";break;case"AppInBackground":r="AppInBackground";break;case"MdnsFailure":r="MDNSFailure";break;case"TcpListenFailure":r="TCPListenFailure";break;case"NoBleCentralPermission":r="NoBLECentralPermission";break;case"NoBlePeripheralPermission":r="NoBLEPeripheralPermission";break;case"CannotEstablishConnection":r="CannotEstablishConnection";break;case"BleDisabled":r="BLEDisabled";break;case"NoBleHardware":r="NoBLEHardware";break;case"WifiDisabled":r="WiFiDisabled";break;case"TemporarilyUnavailable":r="TemporarilyUnavailable"}return[r,n]}}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,n=stateFrom(this.parameters);this.updateGlobal(e,n),this.updatePeerToPeerBluetoothLE(e,n),this.updatePeerToPeerAWDL(e,n),this.updatePeerToPeerLAN(e,n),this.updateListenTCP(e,n),this.updateListenHTTP(e,n),this.updateConnectTCPServers(e,n),this.updateConnectWebsocketURLs(e,n),this.state=n}updatePeerToPeerBluetoothLE(t,e){const n=z.pointerFor(this.ditto),r=t.effectiveTransportConfig.peerToPeer.bluetoothLE,i=e.effectiveTransportConfig.peerToPeer.bluetoothLE,o=!r.isEnabled&&i.isEnabled,a=r.isEnabled&&!i.isEnabled;if(o&&this.bluetoothLETransportPointer)throw new Error("Internal inconsistency, when starting BLE transport, no BLE transport pointer should exist.");if(a&&!this.bluetoothLETransportPointer)throw new Error("Internal inconsistency, when stopping BLE transport, a BLE transport pointer should exist.");if(o){if(!function bleIsAvailable(t){return null!==w&&w.bleIsAvailable(t)}(n))throw new Error("Can't start P2P BluetoothLE transport because not available.");this.bluetoothLETransportPointer=function bleCreate(t){if(null!==w)return w.bleCreate(t);throw new Error("Can't create BluetoothLE handle, P2P BluetoothLE is not supported on this platform.")}(n)}a&&(!function bleDestroy(t){if(null!==w)return w.bleDestroy(t);throw new Error("Can't destroy BluetoothLE handle, P2P BluetoothLE is not supported on this platform.")}(this.bluetoothLETransportPointer),delete this.bluetoothLETransportPointer)}updatePeerToPeerAWDL(t,e){const n=z.pointerFor(this.ditto),r=t.effectiveTransportConfig.peerToPeer.awdl,i=e.effectiveTransportConfig.peerToPeer.awdl,o=!r.isEnabled&&i.isEnabled,a=r.isEnabled&&!i.isEnabled;if(o&&this.awdlTransportPointer)throw new Error("Internal inconsistency, when starting AWDL transport, no AWDL transport pointer should exist.");if(a&&!this.awdlTransportPointer)throw new Error("Internal inconsistency, when stopping AWDL transport, an AWDL transport pointer should exist.");if(o){if(!function awdlIsAvailable(t){return null!==w&&w.awdlIsAvailable(t)}(n))throw new Error("Can't start P2P AWDL transport because not available.");this.awdlTransportPointer=function awdlCreate(t){if(null!==w)return w.awdlCreate(t);throw new Error("Can't create AWDL handle, P2P AWDL transport is not supported on this platform.")}(n)}a&&(!function awdlDestroy(t){if(null!==w)return w.awdlDestroy(t);throw new Error("Can't destroy AWDL handle, P2P AWDL transport is not supported on this platform.")}(this.awdlTransportPointer),this.awdlTransportPointer=null)}updatePeerToPeerLAN(t,e){const n=z.pointerFor(this.ditto),r=t.effectiveTransportConfig.peerToPeer.lan,i=e.effectiveTransportConfig.peerToPeer.lan;if(r.isEnabled&&(r.isMdnsEnabled&&(!function lanDestroy(t){if(null!==w)return w.lanDestroy(t);throw new Error("Can't destroy LAN handle, P2P LAN transport is not supported on this platform.")}(this.lanTransportPointer),delete this.lanTransportPointer),r.isMulticastEnabled&&function dittoRemoveMulticastTransport(t){return ensureInitialized(),(void 0)(t)}(n)),i.isEnabled){if(i.isMdnsEnabled){if(!function lanIsAvailable(t){return null!==w&&w.lanIsAvailable(t)}(n))throw new Error("Can't start P2P LAN transport because not available.");this.lanTransportPointer=function lanCreate(t){if(null!==w)return w.lanCreate(t);throw new Error("Can't create LAN handle, P2P LAN transport is not supported on this platform.")}(n)}i.isMulticastEnabled&&function dittoAddMulticastTransport(t){return ensureInitialized(),(void 0)(t)}(n)}}updateListenTCP(t,e){const n=t.effectiveTransportConfig.listen.tcp,r=e.effectiveTransportConfig.listen.tcp;if(TransportConfig.areListenTCPsEqual(r,n))return;const i=z.pointerFor(this.ditto);n.isEnabled&&function dittoStopTCPServer(t){return ensureInitialized(),(void 0)(t)}(i),r.isEnabled&&function dittoStartTCPServer(t,e){return ensureInitialized(),(void 0)(t,bytesFromString(e))}(i,`${r.interfaceIP}:${r.port}`)}updateListenHTTP(t,e){const n=t.effectiveTransportConfig.listen.http,r=e.effectiveTransportConfig.listen.http;if(TransportConfig.areListenHTTPsEqual(n,r))return;const i=z.pointerFor(this.ditto);n.isEnabled&&function dittoStopHTTPServer(t){return ensureInitialized(),(void 0)(t)}(i),r.isEnabled&&function dittoStartHTTPServer(t,e,n,r,i,o){return ensureInitialized(),(void 0)(t,bytesFromString(e),bytesFromString(n),r,bytesFromString(i),bytesFromString(o))}(i,`${r.interfaceIP}:${r.port}`,r.staticContentPath||null,r.websocketSync?"Enabled":"Disabled",r.tlsCertificatePath||null,r.tlsKeyPath||null)}updateConnectTCPServers(t,e){const n=Object.getOwnPropertyNames(this.staticTCPClientsByAddress),i=e.effectiveTransportConfig.connect.tcpServers,o=new Set(i);for(const t of n)o.delete(t);const a=new Set(n);for(const t of i)a.delete(t);const s=o.values(),c=a.values();for(const t of s){const e=addStaticTCPClient(z.pointerFor(this.ditto),t),n=r.bridge(e);this.staticTCPClientsByAddress[t]=n}for(const t of c){const e=this.staticTCPClientsByAddress[t];if(!e)throw new Error(`Internal inconsistency, can't disconnect from TCP address '${t}', no staticTCPClient found.`);const n=r.pointerFor(e);r.unregister(e),staticTCPClientFreeHandle(n),delete this.staticTCPClientsByAddress[t]}}updateConnectWebsocketURLs(t,e){const n=Object.getOwnPropertyNames(this.websocketClientsByURL),r=e.effectiveTransportConfig.connect.websocketURLs.slice(),o=new Set(r);for(const t of n)o.delete(t);const a=new Set(n);for(const t of r)a.delete(t);const s=o.values(),c=a.values();for(const t of s){const e=addWebsocketClient(z.pointerFor(this.ditto),t),n=i.bridge(e);this.websocketClientsByURL[t]=n}for(const t of c){const e=this.websocketClientsByURL[t];if(!e)throw new Error(`Internal inconsistency, can't disconnect from websocket URL '${t}', no websocketClient found.`);const n=i.pointerFor(e);i.unregister(e),websocketClientFreeHandle(n),delete this.websocketClientsByURL[t]}}updateGlobal(t,e){t.effectiveTransportConfig.global.syncGroup!==e.effectiveTransportConfig.global.syncGroup&&dittoSetSyncGroup(z.pointerFor(this.ditto),e.effectiveTransportConfig.global.syncGroup)}}function stateFrom(t){const e=t.transportConfig.copy(),n=t.identity,r=t.isSyncActive,i=t.isX509Valid,o=t.isWebValid;let a;e.connect.tcpServers,e.connect.websocketURLs;let s=!1;"online"!==n.type&&"onlinePlayground"!==n.type&&"onlineWithAuthentication"!==n.type||(a=n.appID,s=!n.hasOwnProperty("enableDittoCloudSync")||n.enableDittoCloudSync);{const t=[];if(e.peerToPeer.bluetoothLE.isEnabled&&t.push("BluetoothLE"),e.peerToPeer.awdl.isEnabled&&t.push("AWDL"),e.peerToPeer.lan.isEnabled&&t.push("LAN"),t.length>0)throw new Error(`Ditto does not support P2P transports when running in the browser, but the following were enabled: ${t.join(", ")}`)}return r&&i||(e.peerToPeer.bluetoothLE.isEnabled=!1,e.peerToPeer.awdl.isEnabled=!1,e.peerToPeer.lan.isEnabled=!1,e.listen.tcp.isEnabled=!1,e.connect.tcpServers=[]),r&&o||(e.listen.http.isEnabled=!1,e.connect.websocketURLs=[]),r&&o&&s&&e.connect.websocketURLs.push(`wss://${a}.cloud.ditto.live`),e.peerToPeer.lan.isEnabled&&!e.listen.tcp.isEnabled&&(e.listen.tcp.isEnabled=!0,e.listen.tcp.interfaceIP="[::]",e.listen.tcp.port=0),{underlyingSyncParameters:t,effectiveTransportConfig:e.freeze()}}class Ditto{constructor(t,e){this.isWebValid=!1,this.isX509Valid=!1;const r=null!=t?t:{type:"offlinePlayground",appID:""},i=e&&e.trim().length>0?e:"ditto",o=Object.freeze(this.validateIdentity(r));this.identity=Object.freeze(o),this.path=i,this.deviceName=navigator.userAgent,this.keepAlive=new KeepAlive;const a=uninitializedDittoMake(i);let s=null;const c=(()=>{var t,e;if("development"===o.type||"offlinePlayground"===o.type)return dittoAuthClientMakeForDevelopment(i,o.appID,null!==(t=o.siteID)&&void 0!==t?t:0);if("manual"===o.type||"production"===o.type)return dittoAuthClientMakeWithStaticX509(o.certificate);if("sharedKey"===o.type)return dittoAuthClientMakeWithSharedKey(i,o.appID,o.sharedKey,o.siteID);if("onlinePlayground"===o.type)return dittoAuthClientMakeForDevelopment(i,o.appID,0);if("onlineWithAuthentication"===o.type||"online"===o.type){const t=null!==(e=o.customAuthURL)&&void 0!==e?e:`https://${o.appID}.cloud.ditto.live`,n=dittoAuthClientMakeLoginProvider((t=>{this.auth?this.auth["@ditto.authenticationExpiring"](t):s=t}));return dittoAuthClientMakeWithWeb(i,o.appID,t,n)}throw new Error(`Can't create Ditto, unsupported identity type: ${o}`)})();dittoAuthClientSetValidityListener(c,this.authClientValidityChanged.bind(this));const d=dittoAuthClientIsWebValid(c),u=dittoAuthClientIsX509Valid(c),l=dittoAuthClientGetSiteID(c),h=dittoMake(a,c);"onlineWithAuthentication"===o.type||"online"===o.type?this.auth=new OnlineAuthenticator(this.keepAlive,c,this,o.authHandler):(dittoAuthClientFree(c),this.auth=new NotAvailableAuthenticator(this.keepAlive));const b=new TransportConfig;this.siteID=l,this.transportConfig=b.copy().freeze(),this.isX509Valid=u,this.isWebValid=d,this.sync=new Sync(this),this.sync.update({isSyncActive:!1,isX509Valid:u,isWebValid:d,identity:o,transportConfig:b}),this.isActivated=n,this.store=new Store(this),this.presenceManager=new PresenceManager(this),this.transportConditionsManager=new TransportConditionsManager(this);const _=z.bridge(h,(()=>this));return null!==s&&this.auth["@ditto.authenticationExpiring"](s),_}get sdkVersion(){return z.pointerFor(this),dittoGetSDKVersion()}get isSyncEnabled(){return Logger.warning("Ditto.isSyncEnabled() is deprecated, use isSyncActive() instead."),this.isSyncActive}setAccessLicense(t){Logger.warning("Ditto.setAccessLicense() is deprecated, use setLicenseToken() instead."),this.setOfflineOnlyLicenseToken(t)}setLicenseToken(t){this.setOfflineOnlyLicenseToken(t)}setOfflineOnlyLicenseToken(t){Logger.info("Offline license token are ignored on web builds. Token validation will be skipped.")}setTransportConfig(t){this.transportConfig,this.transportConfig=t.copy().freeze();const e=this.transportConfig,n=this.identity,r=this.isWebValid,i=this.isX509Valid;this.sync.update({transportConfig:e,identity:n,isWebValid:r,isX509Valid:i,isSyncActive:this.isSyncActive})}updateTransportConfig(t){const e=this.transportConfig.copy();return t(e),this.setTransportConfig(e),this}tryStartSync(){this.startSync()}startSync(){this.setSyncEnabled(!0)}stopSync(){this.setSyncEnabled(!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(z.pointerFor(this))}authClientValidityChanged(t,e){const n=this.transportConfig,r=this.identity,i=this.isSyncActive;this.isX509Valid,this.isWebValid,this.isX509Valid=e,this.isWebValid=t,this.auth["@ditto.authClientValidityChanged"](t,e),this.sync.update({transportConfig:n,identity:r,isWebValid:t,isX509Valid:e,isSyncActive:i})}validateIdentity(t){const e={...t},n=t.appName,r=t.appID;if(!["development","offlinePlayground","sharedKey","production","manual","onlinePlayground","online","onlineWithAuthentication"].includes(t.type))throw new Error(`Can't create Ditto instance, unknown identity type: ${t.type}`);if("development"!==t.type&&"offlinePlayground"!==t.type&&"sharedKey"!==t.type||void 0===n||void 0===r||(Logger.warning("Properties .appID and .appName (deprecated) are both given for identity, .appID will be used and .appName will be ignored."),delete e.appName),"development"!==t.type&&"offlinePlayground"!==t.type&&"sharedKey"!==t.type||void 0===n||void 0!==r||(Logger.warning("Property .appName of IdentityDevelopment and IdentitySharedKey is deprecated, use .appID instead."),e.appID=n,delete e.appName),("development"===t.type||"offlinePlayground"===t.type||"sharedKey"===t.type)&&void 0===n&&void 0===r)throw new Error(`Property .appID or the deprecated .appName must be given for identity, but aren't: ${JSON.stringify(t)}`);if(("onlinePlayground"===t.type||"online"===t.type||"onlineWithAuthentication"===t.type)&&void 0===r)throw new Error("Property .appID must be given for identity, but isn't.");if(void 0!==n&&"string"!=typeof n)throw new Error(`Property .appName must be be of type string, but is of type '${typeof n}': ${n}`);if(void 0!==r&&"string"!=typeof r)throw new Error(`Property .appID must be be of type string, but is of type '${typeof r}': ${r}`);if(("development"===t.type||"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")}return t.type,"production"===t.type&&Logger.warning("IdentityProduction (type: 'production') is deprecated, please use IdentityManual instead."),t.type,t.type,"online"===t.type||t.type,e}setSyncEnabled(t){if(t&&y.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=z.pointerFor(this);this.isSyncActive=t;const n=this.isWebValid,r=this.isX509Valid,i=this.identity,o=this.transportConfig;dittoSetDeviceName(e,this.deviceName),this.sync.update({identity:i,transportConfig:o,isWebValid:n,isX509Valid:r,isSyncActive:!!t})}}Ditto.webAssemblyModule=null;const z=new Bridge(Ditto,(function dittoDrop(t){return ensureInitialized(),function ditto_drop(t){return takeObject(a.ditto_drop(addHeapObject(t)))}(t)}));let W=!1;t.Attachment=Attachment,t.AttachmentFetcher=AttachmentFetcher,t.AttachmentToken=AttachmentToken,t.Authenticator=Authenticator,t.CBOR=CBOR,t.Collection=Collection,t.CollectionsEvent=CollectionsEvent,t.Counter=Counter,t.Ditto=Ditto,t.Document=Document,t.DocumentPath=DocumentPath,t.IdentityTypesRequiringOfflineLicenseToken=y,t.KeepAlive=KeepAlive,t.LiveQuery=LiveQuery,t.LiveQueryEventInitial=LiveQueryEventInitial,t.LiveQueryEventUpdate=LiveQueryEventUpdate,t.Logger=Logger,t.MutableDocument=MutableDocument,t.MutableDocumentPath=MutableDocumentPath,t.NotAvailableAuthenticator=NotAvailableAuthenticator,t.Observer=Observer,t.OnlineAuthenticator=OnlineAuthenticator,t.PendingCursorOperation=PendingCursorOperation,t.PendingIDSpecificOperation=PendingIDSpecificOperation,t.SingleDocumentLiveQueryEvent=SingleDocumentLiveQueryEvent,t.Store=Store,t.Subscription=Subscription,t.TransportConfig=TransportConfig,t.UpdateResult=UpdateResult,t.UpdateResultsMap=UpdateResultsMap,t.Value=Value,t.__log=function __log(t,e){Logger.warning("Function __log() is deprecated, use Logger.log() & friends instead."),Logger.log(t,e)},t.attachmentBridge=C,t.dittoBridge=z,t.documentBridge=$,t.init=async function init(t={}){if(!W){{const e=t.webAssemblyModule||Ditto.webAssemblyModule||"https://software.ditto.live/js/Ditto/1.1.2/ditto.wasm";await init$2(e),await async function init$1(){if(null!==w)return w.init()}(),initSDKVersion("Web","JavaScript","1.1.2"),loggerInit()}W=!0}},t.mutableDocumentBridge=L,t.validateDocumentIDCBOR=validateDocumentIDCBOR,t.validateDocumentIDValue=validateDocumentIDValue,Object.defineProperty(t,"__esModule",{value:!0})}));
2
2
  //# sourceMappingURL=ditto.umd.js.map
package/web/ditto.wasm CHANGED
Binary file