@dittolive/ditto 4.2.2 → 4.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/node/ditto.cjs.js +1 -1
- package/node/ditto.darwin-arm64.node +0 -0
- package/node/ditto.darwin-x64.node +0 -0
- package/node/ditto.linux-arm.node +0 -0
- package/node/ditto.linux-x64.node +0 -0
- package/node/ditto.win32-x64.node +0 -0
- package/node/transports.darwin-arm64.node +0 -0
- package/node/transports.darwin-x64.node +0 -0
- package/package.json +1 -1
- package/web/ditto.es6.js +1 -1
- package/web/ditto.umd.js +1 -1
- package/web/ditto.wasm +0 -0
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 KeepAlive{get isActive(){return null!==this.intervalID}constructor(){this.countsByID={},this.intervalID=null}retain(t){if(void 0===this.countsByID[t]&&(this.countsByID[t]=0),this.countsByID[t]+=1,null===this.intervalID){const t=2147483647;this.intervalID=setInterval((()=>{}),t),KeepAlive.finalizationRegistry.register(this,this.intervalID,this)}}release(t){if(void 0===this.countsByID[t])throw new Error(`Internal inconsistency, trying to release a keep-alive ID that hasn't been retained before or isn't tracked anymore: ${t}`);this.countsByID[t]-=1,0===this.countsByID[t]&&delete this.countsByID[t],0===Object.keys(this.countsByID).length&&(KeepAlive.finalizationRegistry.unregister(this),clearInterval(this.intervalID),this.intervalID=null)}currentIDs(){return Object.keys(this.countsByID)}countForID(t){var e;return null!==(e=this.countsByID[t])&&void 0!==e?e:null}}KeepAlive.finalizationRegistry=new FinalizationRegistry(clearInterval);class 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 this.observerManager.hasObserver(this.token)}stop(){const t=this.token;t&&(delete this.token,Observer.finalizationRegistry.unregister(this),this.observerManager.removeObserver(t))}static finalize(t){const{observerManager:e,token:n}=t;e.removeObserver(n)}}Observer.finalizationRegistry=new FinalizationRegistry(Observer.finalize);const e="@ditto.64d129224a5377b63e9727479ec987d9";class Counter{constructor(){this.value=0}static"@ditto.create"(t,n,r){const i=t?new MutableCounter(e):new Counter;return i.mutDoc=t,i.path=n,i.value=r,i}}class MutableCounter extends Counter{increment(t){const e=this.mutDoc,n=this.path;if(!e)throw new Error("Can't increment counter, only possible within the closure of a collection's update() method.");e.at(n)["@ditto.increment"](t),this.value+=t}constructor(){if(arguments[0]!==e)throw new Error("MutableCounter constructor is for internal use only.");super()}}const n="@ditto.ff82dae89821c5ab822a8b539056bce4";class Register{get value(){return this["@ditto.value"]}constructor(t){this["@ditto.value"]=t}static"@ditto.create"(t,e,r){const i=t?new MutableRegister(r,n):new Register(r);return i["@ditto.mutableDocument"]=t,i["@ditto.path"]=e,i["@ditto.value"]=r,i}}class MutableRegister extends Register{get value(){return super.value}set value(t){this.set(t)}set(t){const e=this["@ditto.mutableDocument"],n=this["@ditto.path"];e.at(n)["@ditto.set"](t),this["@ditto.value"]=t}constructor(t){if(arguments[1]!==n)throw new Error("MutableRegister constructor is for internal use only.");super(t)}}let r;const i=new Array(32).fill(void 0);function getObject(t){return i[t]}i.push(void 0,null,!0,!1);let o=i.length;function takeObject(t){const e=getObject(t);return function dropObject(t){t<36||(i[t]=o,o=t)}(t),e}const a=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});a.decode();let s=new Uint8Array;function getUint8Memory0(){return 0===s.byteLength&&(s=new Uint8Array(r.memory.buffer)),s}function getStringFromWasm0(t,e){return a.decode(getUint8Memory0().subarray(t,t+e))}function addHeapObject(t){o===i.length&&i.push(i.length+1);const e=o;return o=i[e],i[e]=t,e}let c=0;const d=new TextEncoder("utf-8"),l="function"==typeof d.encodeInto?function(t,e){return d.encodeInto(t,e)}:function(t,e){const n=d.encode(t);return e.set(n),{read:t.length,written:n.length}};function passStringToWasm0(t,e,n){if(void 0===n){const n=d.encode(t),r=e(n.length);return getUint8Memory0().subarray(r,r+n.length).set(n),c=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+=l(t,e).written}return c=a,i}let u=new Int32Array;function getInt32Memory0(){return 0===u.byteLength&&(u=new Int32Array(r.memory.buffer)),u}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 _=new FinalizationRegistry((t=>{r.__wbindgen_export_2.get(t.dtor)(t.a,t.b)}));function makeMutClosure(t,e,n,i){const o={a:t,b:e,cnt:1,dtor:n},real=(...t)=>{o.cnt++;const e=o.a;o.a=0;try{return i(e,o.b,...t)}finally{0==--o.cnt?(r.__wbindgen_export_2.get(o.dtor)(e,o.b),_.unregister(o)):o.a=e}};return real.original=o,_.register(real,o,o),real}function __wbg_adapter_32(t,e,n){r._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__hd60745c96665bcb1(t,e,addHeapObject(n))}function __wbg_adapter_35(t,e){r._dyn_core__ops__function__FnMut_____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__he2527435e40d0841(t,e)}function __wbg_adapter_38(t,e,n){r._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__h163f568f0824965e(t,e,addHeapObject(n))}function __wbg_adapter_41(t,e){r._dyn_core__ops__function__FnMut_____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__hb27b6c99590413c8(t,e)}function __wbg_adapter_44(t,e,n){r._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__ha51957e1d4b3feff(t,e,addHeapObject(n))}function ditto_logger_set_custom_log_cb(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_logger_set_custom_log_cb(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}function ditto_register_transport_condition_changed_callback(t,e){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_register_transport_condition_changed_callback(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}function handleError(t,e){try{return t.apply(this,e)}catch(t){r.__wbindgen_exn_store(addHeapObject(t))}}function notDefined(t){return()=>{throw new Error(`${t} is not defined`)}}function getArrayU8FromWasm0(t,e){return getUint8Memory0().subarray(t/1,t/1+e)}function boxCStringIntoString(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.boxCStringIntoString(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}function refCStringToString(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.refCStringToString(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}function boxCBytesIntoBuffer(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.boxCBytesIntoBuffer(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}function withOutPtr$1(t,e){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.withOutPtr(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}function getImports(){const t={wbg:{}};return t.wbg.__wbindgen_object_drop_ref=function(t){takeObject(t)},t.wbg.__wbindgen_string_new=function(t,e){return addHeapObject(getStringFromWasm0(t,e))},t.wbg.__wbg_log_c6f7064ce12c2dfa=function(t,e){try{console.log(getStringFromWasm0(t,e))}finally{r.__wbindgen_free(t,e)}},t.wbg.__wbindgen_cb_drop=function(t){const e=takeObject(t).original;if(1==e.cnt--)return e.a=0,!0;return!1},t.wbg.__wbg_new_abda76e883ba8a5f=function(){return addHeapObject(new Error)},t.wbg.__wbg_stack_658279fe44541cf6=function(t,e){const n=passStringToWasm0(getObject(e).stack,r.__wbindgen_malloc,r.__wbindgen_realloc),i=c;getInt32Memory0()[t/4+1]=i,getInt32Memory0()[t/4+0]=n},t.wbg.__wbg_error_f851667af71bcfc6=function(t,e){try{console.error(getStringFromWasm0(t,e))}finally{r.__wbindgen_free(t,e)}},t.wbg.__wbindgen_is_string=function(t){return"string"==typeof getObject(t)},t.wbg.__wbindgen_string_get=function(t,e){const n=getObject(e),i="string"==typeof n?n:void 0;var o=function isLikeNone(t){return null==t}(i)?0:passStringToWasm0(i,r.__wbindgen_malloc,r.__wbindgen_realloc),a=c;getInt32Memory0()[t/4+1]=a,getInt32Memory0()[t/4+0]=o},t.wbg.__wbindgen_object_clone_ref=function(t){return addHeapObject(getObject(t))},t.wbg.__wbg_fetch_3894579f6e2af3be=function(t){return addHeapObject(fetch(getObject(t)))},t.wbg.__wbg_clearTimeout_23ee6db72c0ad922="function"==typeof clearTimeout?clearTimeout:notDefined("clearTimeout"),t.wbg.__wbg_setTimeout_09074a1669d0f224=function(){return handleError((function(t,e){return setTimeout(getObject(t),e)}),arguments)},t.wbg.__wbg_clearInterval_d5655e407a861314="function"==typeof clearInterval?clearInterval:notDefined("clearInterval"),t.wbg.__wbg_setInterval_fa82463ae3f43f48=function(){return handleError((function(t,e){return setInterval(getObject(t),e)}),arguments)},t.wbg.__wbg_crypto_e1d53a1d73fb10b8=function(t){return addHeapObject(getObject(t).crypto)},t.wbg.__wbindgen_is_object=function(t){const e=getObject(t);return"object"==typeof e&&null!==e},t.wbg.__wbg_process_038c26bf42b093f8=function(t){return addHeapObject(getObject(t).process)},t.wbg.__wbg_versions_ab37218d2f0b24a8=function(t){return addHeapObject(getObject(t).versions)},t.wbg.__wbg_node_080f4b19d15bc1fe=function(t){return addHeapObject(getObject(t).node)},t.wbg.__wbg_msCrypto_6e7d3e1f92610cbb=function(t){return addHeapObject(getObject(t).msCrypto)},t.wbg.__wbg_require_78a3dcfbdba9cbce=function(){return handleError((function(){return addHeapObject(module.require)}),arguments)},t.wbg.__wbindgen_is_function=function(t){return"function"==typeof getObject(t)},t.wbg.__wbg_getRandomValues_805f1c3d65988a5a=function(){return handleError((function(t,e){getObject(t).getRandomValues(getObject(e))}),arguments)},t.wbg.__wbg_randomFillSync_6894564c2c334c42=function(){return handleError((function(t,e,n){getObject(t).randomFillSync(getArrayU8FromWasm0(e,n))}),arguments)},t.wbg.__wbindgen_number_new=function(t){return addHeapObject(t)},t.wbg.__wbg_mksendret_91eb8c5592210ee0=function(){return addHeapObject((function send_ret(t){return t}))},t.wbg.__wbindgen_error_new=function(t,e){return addHeapObject(new Error(getStringFromWasm0(t,e)))},t.wbg.__wbg_trydownsize_28e49b8073c2a2fc=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)))},t.wbg.__wbg_isnumber_c97122a46d4ace09=function(t){return function is_number(t){return"number"==typeof t}(getObject(t))},t.wbg.__wbg_tostring_7847f1b7af649ba5=function(t,e){const n=passStringToWasm0(function to_string(t){return t.toString()}(getObject(e)),r.__wbindgen_malloc,r.__wbindgen_realloc),i=c;getInt32Memory0()[t/4+1]=i,getInt32Memory0()[t/4+0]=n},t.wbg.__wbg_fromstring_721719aff319c1fe=function(t,e){return addHeapObject(function from_string(t){return BigInt(t)}(getStringFromWasm0(t,e)))},t.wbg.__wbg_typeof_cb5c1bc26a697ea8=function(t,e){const n=passStringToWasm0(function typeof_(t){return typeof t}(getObject(e)),r.__wbindgen_malloc,r.__wbindgen_realloc),i=c;getInt32Memory0()[t/4+1]=i,getInt32Memory0()[t/4+0]=n},t.wbg.__wbindgen_is_null=function(t){return null===getObject(t)},t.wbg.__wbindgen_is_undefined=function(t){return void 0===getObject(t)},t.wbg.__wbg_getelement_cd48f1e89008c242=function(t,e){return addHeapObject(function get_element(t,e){return t[e]}(getObject(t),e>>>0))},t.wbg.__wbg_instanceof_Blob_d18d26355bccfd22=function(t){let e;try{e=getObject(t)instanceof Blob}catch{e=!1}return e},t.wbg.__wbg_instanceof_Response_eaa426220848a39e=function(t){let e;try{e=getObject(t)instanceof Response}catch{e=!1}return e},t.wbg.__wbg_url_74285ddf2747cb3d=function(t,e){const n=passStringToWasm0(getObject(e).url,r.__wbindgen_malloc,r.__wbindgen_realloc),i=c;getInt32Memory0()[t/4+1]=i,getInt32Memory0()[t/4+0]=n},t.wbg.__wbg_status_c4ef3dd591e63435=function(t){return getObject(t).status},t.wbg.__wbg_headers_fd64ad685cf22e5d=function(t){return addHeapObject(getObject(t).headers)},t.wbg.__wbg_arrayBuffer_4c27b6f00c530232=function(){return handleError((function(t){return addHeapObject(getObject(t).arrayBuffer())}),arguments)},t.wbg.__wbg_url_1f1b597f64482fd0=function(t,e){const n=passStringToWasm0(getObject(e).url,r.__wbindgen_malloc,r.__wbindgen_realloc),i=c;getInt32Memory0()[t/4+1]=i,getInt32Memory0()[t/4+0]=n},t.wbg.__wbg_readyState_9c0f66433e329c9e=function(t){return getObject(t).readyState},t.wbg.__wbg_setonopen_9ce48dce57e549b5=function(t,e){getObject(t).onopen=getObject(e)},t.wbg.__wbg_setonerror_02393260b3e29972=function(t,e){getObject(t).onerror=getObject(e)},t.wbg.__wbg_setonclose_4ce49fd8fd7783fb=function(t,e){getObject(t).onclose=getObject(e)},t.wbg.__wbg_setonmessage_c5a806b62a0c5607=function(t,e){getObject(t).onmessage=getObject(e)},t.wbg.__wbg_setbinaryType_ee55743ddf4beb37=function(t,e){getObject(t).binaryType=takeObject(e)},t.wbg.__wbg_new_d29e507f6606de91=function(){return handleError((function(t,e){return addHeapObject(new WebSocket(getStringFromWasm0(t,e)))}),arguments)},t.wbg.__wbg_newwithstrsequence_7b0c4aadc1ae1635=function(){return handleError((function(t,e,n){return addHeapObject(new WebSocket(getStringFromWasm0(t,e),getObject(n)))}),arguments)},t.wbg.__wbg_close_45d053bea59e7746=function(){return handleError((function(t){getObject(t).close()}),arguments)},t.wbg.__wbg_send_80b256d87a6779e5=function(){return handleError((function(t,e,n){getObject(t).send(getStringFromWasm0(e,n))}),arguments)},t.wbg.__wbg_send_640853f8eb0f0385=function(){return handleError((function(t,e,n){getObject(t).send(getArrayU8FromWasm0(e,n))}),arguments)},t.wbg.__wbg_fetch_749a56934f95c96c=function(t,e){return addHeapObject(getObject(t).fetch(getObject(e)))},t.wbg.__wbg_code_b09504754e0520f1=function(t){return getObject(t).code},t.wbg.__wbg_new_2d0053ee81e4dd2a=function(){return handleError((function(){return addHeapObject(new Headers)}),arguments)},t.wbg.__wbg_append_de37df908812970d=function(){return handleError((function(t,e,n,r,i){getObject(t).append(getStringFromWasm0(e,n),getStringFromWasm0(r,i))}),arguments)},t.wbg.__wbg_now_8172cd917e5eda6b=function(t){return getObject(t).now()},t.wbg.__wbg_newwithstrandinit_05d7180788420c40=function(){return handleError((function(t,e,n){return addHeapObject(new Request(getStringFromWasm0(t,e),getObject(n)))}),arguments)},t.wbg.__wbg_wasClean_2af04e6cf2076497=function(t){return getObject(t).wasClean},t.wbg.__wbg_code_24e161f043adce8a=function(t){return getObject(t).code},t.wbg.__wbg_reason_40159cc3d2fc655d=function(t,e){const n=passStringToWasm0(getObject(e).reason,r.__wbindgen_malloc,r.__wbindgen_realloc),i=c;getInt32Memory0()[t/4+1]=i,getInt32Memory0()[t/4+0]=n},t.wbg.__wbg_data_7b1f01f4e6a64fbe=function(t){return addHeapObject(getObject(t).data)},t.wbg.__wbg_new_1d9a920c6bfc44a8=function(){return addHeapObject(new Array)},t.wbg.__wbg_valueOf_8404142eb850b917=function(t){return getObject(t).valueOf()},t.wbg.__wbg_newnoargs_b5b063fc6c2f0376=function(t,e){return addHeapObject(new Function(getStringFromWasm0(t,e)))},t.wbg.__wbg_next_579e583d33566a86=function(t){return addHeapObject(getObject(t).next)},t.wbg.__wbg_next_aaef7c8aa5e212ac=function(){return handleError((function(t){return addHeapObject(getObject(t).next())}),arguments)},t.wbg.__wbg_done_1b73b0672e15f234=function(t){return getObject(t).done},t.wbg.__wbg_value_1ccc36bc03462d71=function(t){return addHeapObject(getObject(t).value)},t.wbg.__wbg_iterator_6f9d4f28845f426c=function(){return addHeapObject(Symbol.iterator)},t.wbg.__wbg_get_765201544a2b6869=function(){return handleError((function(t,e){return addHeapObject(Reflect.get(getObject(t),getObject(e)))}),arguments)},t.wbg.__wbg_call_97ae9d8645dc388b=function(){return handleError((function(t,e){return addHeapObject(getObject(t).call(getObject(e)))}),arguments)},t.wbg.__wbg_new_0b9bfdd97583284e=function(){return addHeapObject(new Object)},t.wbg.__wbg_self_6d479506f72c6a71=function(){return handleError((function(){return addHeapObject(self.self)}),arguments)},t.wbg.__wbg_window_f2557cc78490aceb=function(){return handleError((function(){return addHeapObject(window.window)}),arguments)},t.wbg.__wbg_globalThis_7f206bda628d5286=function(){return handleError((function(){return addHeapObject(globalThis.globalThis)}),arguments)},t.wbg.__wbg_global_ba75c50d1cf384f4=function(){return handleError((function(){return addHeapObject(global.global)}),arguments)},t.wbg.__wbg_push_740e4b286702d964=function(t,e){return getObject(t).push(getObject(e))},t.wbg.__wbg_instanceof_ArrayBuffer_e5e48f4762c5610b=function(t){let e;try{e=getObject(t)instanceof ArrayBuffer}catch{e=!1}return e},t.wbg.__wbg_apply_22a3220d244124da=function(){return handleError((function(t,e,n){return addHeapObject(getObject(t).apply(getObject(e),getObject(n)))}),arguments)},t.wbg.__wbg_call_168da88779e35f61=function(){return handleError((function(t,e,n){return addHeapObject(getObject(t).call(getObject(e),getObject(n)))}),arguments)},t.wbg.__wbg_valueOf_6b6effad03e5c546=function(t){return getObject(t).valueOf()},t.wbg.__wbg_getTime_cb82adb2556ed13e=function(t){return getObject(t).getTime()},t.wbg.__wbg_new0_a57059d72c5b7aee=function(){return addHeapObject(new Date)},t.wbg.__wbg_now_58886682b7e790d7=function(){return Date.now()},t.wbg.__wbg_instanceof_Object_595a1007518cbea3=function(t){let e;try{e=getObject(t)instanceof Object}catch{e=!1}return e},t.wbg.__wbg_new_9962f939219f1820=function(t,e){try{var n={a:t,b:e};const i=new Promise(((t,e)=>{const i=n.a;n.a=0;try{return function __wbg_adapter_326(t,e,n,i){r.wasm_bindgen__convert__closures__invoke2_mut__h3a53fb951e2471c7(t,e,addHeapObject(n),addHeapObject(i))}(i,n.b,t,e)}finally{n.a=i}}));return addHeapObject(i)}finally{n.a=n.b=0}},t.wbg.__wbg_resolve_99fe17964f31ffc0=function(t){return addHeapObject(Promise.resolve(getObject(t)))},t.wbg.__wbg_then_11f7a54d67b4bfad=function(t,e){return addHeapObject(getObject(t).then(getObject(e)))},t.wbg.__wbg_then_cedad20fbbd9418a=function(t,e,n){return addHeapObject(getObject(t).then(getObject(e),getObject(n)))},t.wbg.__wbg_buffer_3f3d764d4747d564=function(t){return addHeapObject(getObject(t).buffer)},t.wbg.__wbg_newwithbyteoffsetandlength_d9aa266703cb98be=function(t,e,n){return addHeapObject(new Uint8Array(getObject(t),e>>>0,n>>>0))},t.wbg.__wbg_new_8c3f0052272a457a=function(t){return addHeapObject(new Uint8Array(getObject(t)))},t.wbg.__wbg_set_83db9690f9353e79=function(t,e,n){getObject(t).set(getObject(e),n>>>0)},t.wbg.__wbg_length_9e1ae1900cb0fbd5=function(t){return getObject(t).length},t.wbg.__wbg_instanceof_Uint8Array_971eeda69eb75003=function(t){let e;try{e=getObject(t)instanceof Uint8Array}catch{e=!1}return e},t.wbg.__wbg_newwithlength_f5933855e4f48a19=function(t){return addHeapObject(new Uint8Array(t>>>0))},t.wbg.__wbg_subarray_58ad4efbb5bcb886=function(t,e,n){return addHeapObject(getObject(t).subarray(e>>>0,n>>>0))},t.wbg.__wbg_has_8359f114ce042f5a=function(){return handleError((function(t,e){return Reflect.has(getObject(t),getObject(e))}),arguments)},t.wbg.__wbg_set_bf3f89b92d5a34bf=function(){return handleError((function(t,e,n){return Reflect.set(getObject(t),getObject(e),getObject(n))}),arguments)},t.wbg.__wbg_stringify_d6471d300ded9b68=function(){return handleError((function(t){return addHeapObject(JSON.stringify(getObject(t)))}),arguments)},t.wbg.__wbindgen_debug_string=function(t,e){const n=passStringToWasm0(debugString(getObject(e)),r.__wbindgen_malloc,r.__wbindgen_realloc),i=c;getInt32Memory0()[t/4+1]=i,getInt32Memory0()[t/4+0]=n},t.wbg.__wbindgen_throw=function(t,e){throw new Error(getStringFromWasm0(t,e))},t.wbg.__wbindgen_memory=function(){return addHeapObject(r.memory)},t.wbg.__wbindgen_closure_wrapper4586=function(t,e,n){return addHeapObject(makeMutClosure(t,e,1293,__wbg_adapter_32))},t.wbg.__wbindgen_closure_wrapper4588=function(t,e,n){return addHeapObject(makeMutClosure(t,e,1293,__wbg_adapter_35))},t.wbg.__wbindgen_closure_wrapper12044=function(t,e,n){return addHeapObject(makeMutClosure(t,e,3413,__wbg_adapter_38))},t.wbg.__wbindgen_closure_wrapper19641=function(t,e,n){return addHeapObject(makeMutClosure(t,e,5354,__wbg_adapter_41))},t.wbg.__wbindgen_closure_wrapper21041=function(t,e,n){return addHeapObject(makeMutClosure(t,e,5816,__wbg_adapter_44))},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=getImports();("string"==typeof t||"function"==typeof Request&&t instanceof Request||"function"==typeof URL&&t instanceof URL)&&(t=fetch(t));const{instance:n,module:i}=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 function finalizeInit(t,e){return r=t.exports,init$3.__wbindgen_wasm_module=e,u=new Int32Array,s=new Uint8Array,r}(n,i)}const g="_ditto_internal_type_jkb12973t4b",h="_value";var b;function documentSetCBORWithTimestamp(t,e,n,i){ensureInitialized();const o=function ditto_document_set_cbor_with_timestamp(t,e,n,i){try{const s=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_document_set_cbor_with_timestamp(s,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(i));var o=getInt32Memory0()[s/4+0],a=getInt32Memory0()[s/4+1];if(getInt32Memory0()[s/4+2])throw takeObject(a);return takeObject(o)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,bytesFromString(e),n,i);if(0!==o)throw new Error(errorMessage()||`ditto_document_set_cbor_with_timestamp() failed with error code: ${o}`)}function documentSetCBOR(t,e,n){ensureInitialized();const i=function ditto_document_set_cbor(t,e,n){try{const a=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_document_set_cbor(a,addHeapObject(t),addHeapObject(e),addHeapObject(n));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,bytesFromString(e),n);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){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_document_id(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t))}function documentGetCBORWithPathType(t,e,n){ensureInitialized();const i=function ditto_document_get_cbor_with_path_type(t,e,n){try{const a=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_document_get_cbor_with_path_type(a,addHeapObject(t),addHeapObject(e),addHeapObject(n));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,bytesFromString(e),n);return{statusCode:i.status_code,cbor:boxCBytesIntoBuffer(i.cbor)}}function documentRemove(t,e){ensureInitialized();const n=function ditto_document_remove(t,e){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_document_remove(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,bytesFromString(e));if(0!==n)throw new Error(errorMessage()||`ditto_document_remove() failed with error code: ${n}`)}function documentIncrementCounter(t,e,n){ensureInitialized();const i=function ditto_document_increment_counter(t,e,n){try{const a=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_document_increment_counter(a,addHeapObject(t),addHeapObject(e),addHeapObject(n));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,bytesFromString(e),n);if(0!==i)throw new Error(errorMessage()||`ditto_document_increment_counter() failed with error code: ${i}`)}function documentFree(t){ensureInitialized(),function ditto_document_free(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_document_free(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t)}function documentIDQueryCompatible(t,e){ensureInitialized();return boxCStringIntoString(function ditto_document_id_query_compatible(t,e){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_document_id_query_compatible(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,e))}function validateDocumentID(t){ensureInitialized();return boxCBytesIntoBuffer(function withOutBoxCBytes(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.withOutBoxCBytes(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}((e=>{const n=function ditto_validate_document_id(t,e){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_validate_document_id(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,e);if(0!==n)throw new Error(errorMessage()||`ditto_validate_document_id() failed with error code: ${n}`);return e})))}async function collectionGet(t,e,n,i){ensureInitialized();const o=bytesFromString(e),{status_code:a,document:s}=await function ditto_collection_get(t,e,n,i){try{const s=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_collection_get(s,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(i));var o=getInt32Memory0()[s/4+0],a=getInt32Memory0()[s/4+1];if(getInt32Memory0()[s/4+2])throw takeObject(a);return takeObject(o)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,o,n,i);if(a===y)return null;if(0!==a)throw new Error(errorMessage()||`ditto_collection_get() failed with error code: ${a}`);return s}async function collectionInsertValue(t,e,n,i,o){ensureInitialized();const a=bytesFromString(e);let s;switch(i){case"merge":s="Merge";break;case"insertIfAbsent":s="InsertIfAbsent";break;case"insertDefaultIfAbsent":s="InsertDefaultIfAbsent";break;default:throw new Error("Invalid write strategy provided")}const{status_code:c,id:d}=await function ditto_collection_insert_value(t,e,n,i,o,a){try{const d=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_collection_insert_value(d,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(i),addHeapObject(o),addHeapObject(a));var s=getInt32Memory0()[d/4+0],c=getInt32Memory0()[d/4+1];if(getInt32Memory0()[d/4+2])throw takeObject(c);return takeObject(s)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,a,n,s,null,null!=o?o: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,i){ensureInitialized();const o=bytesFromString(e),{status_code:a,bool_value:s}=await function ditto_collection_remove(t,e,n,i){try{const s=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_collection_remove(s,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(i));var o=getInt32Memory0()[s/4+0],a=getInt32Memory0()[s/4+1];if(getInt32Memory0()[s/4+2])throw takeObject(a);return takeObject(o)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,o,n,i);if(0!==a)throw new Error(errorMessage()||`ditto_collection_remove() failed with error code: ${a}`);return s}async function collectionEvict(t,e,n,i){ensureInitialized();const o=bytesFromString(e),{status_code:a,bool_value:s}=await function ditto_collection_evict(t,e,n,i){try{const s=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_collection_evict(s,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(i));var o=getInt32Memory0()[s/4+0],a=getInt32Memory0()[s/4+1];if(getInt32Memory0()[s/4+2])throw takeObject(a);return takeObject(o)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,o,n,i);if(0!==a)throw new Error(errorMessage()||`ditto_collection_evict() failed with error code: ${a}`);return s}async function collectionUpdate(t,e,n,i){ensureInitialized();const o=bytesFromString(e),a=await function ditto_collection_update(t,e,n,i){try{const s=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_collection_update(s,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(i));var o=getInt32Memory0()[s/4+0],a=getInt32Memory0()[s/4+1];if(getInt32Memory0()[s/4+2])throw takeObject(a);return takeObject(o)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,o,n,i);if(0!==a)throw new Error(errorMessage()||`ditto_collection_update() failed with error code: ${a}`)}async function collectionUpdateMultiple(t,e,n,i){ensureInitialized();const o=bytesFromString(e),a=function jsDocsToCDocs(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.jsDocsToCDocs(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(i),s=await function ditto_collection_update_multiple(t,e,n,i){try{const s=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_collection_update_multiple(s,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(i));var o=getInt32Memory0()[s/4+0],a=getInt32Memory0()[s/4+1];if(getInt32Memory0()[s/4+2])throw takeObject(a);return takeObject(o)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,o,n,a);if(0!==s)throw new Error(errorMessage()||`ditto_collection_update_multiple() failed with error code: ${s}`)}async function collectionExecQueryStr(t,e,n,i,o,a,s,c){ensureInitialized();const d=bytesFromString(e),l=bytesFromString(i);return await function ditto_collection_exec_query_str(t,e,n,i,o,a,s,c){try{const u=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_collection_exec_query_str(u,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(i),addHeapObject(o),addHeapObject(a),addHeapObject(s),addHeapObject(c));var d=getInt32Memory0()[u/4+0],l=getInt32Memory0()[u/4+1];if(getInt32Memory0()[u/4+2])throw takeObject(l);return takeObject(d)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,d,n,l,o,a,s,c)}async function collectionRemoveQueryStr(t,e,n,i,o,a,s,c){ensureInitialized();const d=bytesFromString(e),l=bytesFromString(i);return await function ditto_collection_remove_query_str(t,e,n,i,o,a,s,c){try{const u=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_collection_remove_query_str(u,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(i),addHeapObject(o),addHeapObject(a),addHeapObject(s),addHeapObject(c));var d=getInt32Memory0()[u/4+0],l=getInt32Memory0()[u/4+1];if(getInt32Memory0()[u/4+2])throw takeObject(l);return takeObject(d)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,d,n,l,o,a,s,c)}async function collectionEvictQueryStr(t,e,n,i,o,a,s,c){ensureInitialized();const d=bytesFromString(e),l=bytesFromString(i);return await function ditto_collection_evict_query_str(t,e,n,i,o,a,s,c){try{const u=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_collection_evict_query_str(u,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(i),addHeapObject(o),addHeapObject(a),addHeapObject(s),addHeapObject(c));var d=getInt32Memory0()[u/4+0],l=getInt32Memory0()[u/4+1];if(getInt32Memory0()[u/4+2])throw takeObject(l);return takeObject(d)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,d,n,l,o,a,s,c)}async function experimentalExecQueryStr(t,e,n,i){ensureInitialized();const o=bytesFromString(n);return await function ditto_experimental_exec_query_str(t,e,n,i){try{const s=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_experimental_exec_query_str(s,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(i));var o=getInt32Memory0()[s/4+0],a=getInt32Memory0()[s/4+1];if(getInt32Memory0()[s/4+2])throw takeObject(a);return takeObject(o)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,e,o,i)}function addSubscription(t,e,n,i,o,a,s){ensureInitialized();return function ditto_add_subscription(t,e,n,i,o,a,s){try{const l=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_add_subscription(l,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(i),addHeapObject(o),addHeapObject(a),addHeapObject(s));var c=getInt32Memory0()[l/4+0],d=getInt32Memory0()[l/4+1];if(getInt32Memory0()[l/4+2])throw takeObject(d);return takeObject(c)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,bytesFromString(e),bytesFromString(n),i,o,a,s)}function removeSubscription(t,e,n,i,o,a,s){ensureInitialized();return function ditto_remove_subscription(t,e,n,i,o,a,s){try{const l=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_remove_subscription(l,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(i),addHeapObject(o),addHeapObject(a),addHeapObject(s));var c=getInt32Memory0()[l/4+0],d=getInt32Memory0()[l/4+1];if(getInt32Memory0()[l/4+2])throw takeObject(d);return takeObject(c)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,bytesFromString(e),bytesFromString(n),i,o,a,s)}function experimentalAddDqlSubscription(t,e,n){ensureInitialized();const i=function ditto_experimental_add_dql_subscription(t,e,n){try{const a=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_experimental_add_dql_subscription(a,addHeapObject(t),addHeapObject(e),addHeapObject(n));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,bytesFromString(e),n);if(0!==i)throw new Error(errorMessage()||`ditto_experimental_add_dql_subscription() failed with error code: ${i}`)}function experimentalRemoveDqlSubscription(t,e,n){ensureInitialized();const i=function ditto_experimental_remove_dql_subscription(t,e,n){try{const a=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_experimental_remove_dql_subscription(a,addHeapObject(t),addHeapObject(e),addHeapObject(n));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,bytesFromString(e),n);if(0!==i)throw new Error(errorMessage()||`ditto_experimental_remove_dql_subscription() failed with error code: ${i}`)}function liveQueryRegister(t,e,n,i,o,a,s,c,d){ensureInitialized();const l=bytesFromString(e),u=bytesFromString(n),{status_code:_,i64:g}=function ditto_live_query_register_str_detached(t,e,n,i,o,a,s,c){try{const u=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_live_query_register_str_detached(u,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(i),addHeapObject(o),addHeapObject(a),addHeapObject(s),addHeapObject(c));var d=getInt32Memory0()[u/4+0],l=getInt32Memory0()[u/4+1];if(getInt32Memory0()[u/4+2])throw takeObject(l);return takeObject(d)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,l,u,i,o,a,s,wrapBackgroundCbForFFI(d,c));if(0!==_)throw new Error(errorMessage()||`\`ditto_live_query_register_str()\` failed with error code: ${_}`);return g}async function liveQueryStart(t,e){ensureInitialized();const n=await function ditto_live_query_start(t,e){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_live_query_start(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(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){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_live_query_stop(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,e)}async function liveQuerySignalAvailableNext(t,e){ensureInitialized(),await function ditto_live_query_signal_available_next(t,e){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_live_query_signal_available_next(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,e)}async function liveQueryWebhookRegister(t,e,n,i,o,a,s){ensureInitialized();const c=bytesFromString(e),d=bytesFromString(n),l=bytesFromString(s),{status_code:u,id:_}=await function ditto_live_query_webhook_register_str(t,e,n,i,o,a,s){try{const l=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_live_query_webhook_register_str(l,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(i),addHeapObject(o),addHeapObject(a),addHeapObject(s));var c=getInt32Memory0()[l/4+0],d=getInt32Memory0()[l/4+1];if(getInt32Memory0()[l/4+2])throw takeObject(d);return takeObject(c)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,c,d,i,o,a,l);if(0!==u)throw new Error(errorMessage()||`\`ditto_live_query_webhook_register_str()\` failed with error code: ${u}`);return boxCBytesIntoBuffer(_)}async function readTransaction(t){ensureInitialized();const{status_code:e,txn:n}=await function ditto_read_transaction(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_read_transaction(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(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){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_read_transaction_free(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t)}async function writeTransaction(t){ensureInitialized();const{status_code:e,txn:n}=await function ditto_write_transaction(t,e){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_write_transaction(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,null);if(0!==e)throw new Error(errorMessage()||`ditto_write_transaction() failed with error code: ${e}`);return n}async function writeTransactionCommit(t,e){ensureInitialized();const n=await function ditto_write_transaction_commit(t,e){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_write_transaction_commit(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,e);if(0!==n)throw new Error(errorMessage()||`ditto_write_transaction_commit() failed with error code: ${n}`)}async function writeTransactionRollback(t,e){ensureInitialized();const n=await function ditto_write_transaction_rollback(t,e){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_write_transaction_rollback(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,e);if(0!==n)throw new Error(errorMessage()||`ditto_write_transaction_rollback() failed with error code: ${n}`)}function loggerInit(){ensureInitialized(),function ditto_logger_init(){try{const n=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_logger_init(n);var t=getInt32Memory0()[n/4+0],e=getInt32Memory0()[n/4+1];if(getInt32Memory0()[n/4+2])throw takeObject(e);return takeObject(t)}finally{r.__wbindgen_add_to_stack_pointer(16)}}()}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){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_logger_enabled(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(!!t)}function loggerEnabledGet(){return ensureInitialized(),!!function ditto_logger_enabled_get(){try{const n=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_logger_enabled_get(n);var t=getInt32Memory0()[n/4+0],e=getInt32Memory0()[n/4+1];if(getInt32Memory0()[n/4+2])throw takeObject(e);return takeObject(t)}finally{r.__wbindgen_add_to_stack_pointer(16)}}()}function loggerEmojiHeadingsEnabled(t){ensureInitialized(),function ditto_logger_emoji_headings_enabled(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_logger_emoji_headings_enabled(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t)}function loggerEmojiHeadingsEnabledGet(){return ensureInitialized(),function ditto_logger_emoji_headings_enabled_get(){try{const n=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_logger_emoji_headings_enabled_get(n);var t=getInt32Memory0()[n/4+0],e=getInt32Memory0()[n/4+1];if(getInt32Memory0()[n/4+2])throw takeObject(e);return takeObject(t)}finally{r.__wbindgen_add_to_stack_pointer(16)}}()}function loggerMinimumLogLevel(t){ensureInitialized(),function ditto_logger_minimum_log_level(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_logger_minimum_log_level(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t)}function loggerMinimumLogLevelGet(){return ensureInitialized(),function ditto_logger_minimum_log_level_get(){try{const n=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_logger_minimum_log_level_get(n);var t=getInt32Memory0()[n/4+0],e=getInt32Memory0()[n/4+1];if(getInt32Memory0()[n/4+2])throw takeObject(e);return takeObject(t)}finally{r.__wbindgen_add_to_stack_pointer(16)}}()}function loggerSetLogFile(t){ensureInitialized();if(0!==function ditto_logger_set_log_file(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_logger_set_log_file(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(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){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_log(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,bytesFromString(e))}function dittoIdentityConfigMakeOnlinePlayground(t,e,n){ensureInitialized();const i=bytesFromString(t),o=bytesFromString(e),a=bytesFromString(n),{status_code:s,identity_config:c}=function ditto_identity_config_make_online_playground(t,e,n){try{const a=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_identity_config_make_online_playground(a,addHeapObject(t),addHeapObject(e),addHeapObject(n));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(i,o,a);if(0!==s)throw new Error(errorMessage()||`ditto_identity_config_make_online_playground() failed with error code: ${s}`);return c}function dittoIdentityConfigMakeOnlineWithAuthentication(t,e){ensureInitialized();const n=bytesFromString(t),i=bytesFromString(e),{status_code:o,identity_config:a}=function ditto_identity_config_make_online_with_authentication(t,e){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_identity_config_make_online_with_authentication(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(n,i);if(0!==o)throw new Error(errorMessage()||`ditto_identity_config_make_online_with_authentication() failed with error code: ${o}`);return a}function dittoIdentityConfigMakeOfflinePlayground(t,e){ensureInitialized();const n=bytesFromString(t),i=Number(e),{status_code:o,identity_config:a}=function ditto_identity_config_make_offline_playground(t,e){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_identity_config_make_offline_playground(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(n,i);if(0!==o)throw new Error(errorMessage()||`ditto_identity_config_make_offline_playground() failed with error code: ${o}`);return a}function dittoIdentityConfigMakeSharedKey(t,e,n){ensureInitialized();const i=bytesFromString(t),o=bytesFromString(e),a=Number(n),{status_code:s,identity_config:c}=function ditto_identity_config_make_shared_key(t,e,n){try{const a=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_identity_config_make_shared_key(a,addHeapObject(t),addHeapObject(e),addHeapObject(n));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(i,o,a);if(0!==s)throw new Error(errorMessage()||`ditto_identity_config_make_shared_key() failed with error code: ${s}`);return c}function dittoIdentityConfigMakeManual(t){ensureInitialized();const e=bytesFromString(t),{status_code:n,identity_config:i}=function ditto_identity_config_make_manual_v0(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_identity_config_make_manual_v0(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(e);if(0!==n)throw new Error(errorMessage()||`ditto_identity_config_make_manual_v0() failed with error code: ${n}`);return i}function dittoAuthClientGetSiteID(t){return ensureInitialized(),function ditto_auth_client_get_site_id(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_auth_client_get_site_id(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t)}function dittoAuthClientIsWebValid(t){return ensureInitialized(),0!==function ditto_auth_client_is_web_valid(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_auth_client_is_web_valid(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t)}function dittoAuthClientUserID(t){ensureInitialized();const e=function ditto_auth_client_user_id(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_auth_client_user_id(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t);return boxCStringIntoString(e)}function dittoAuthClientIsX509Valid(t){return ensureInitialized(),0!==function ditto_auth_client_is_x509_valid(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_auth_client_is_x509_valid(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t)}async function dittoAuthClientLoginWithToken(t,e,n){ensureInitialized();const i=bytesFromString(e),o=bytesFromString(n),a=await function ditto_auth_client_login_with_token(t,e,n){try{const a=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_auth_client_login_with_token(a,addHeapObject(t),addHeapObject(e),addHeapObject(n));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,i,o);if(0!==a)throw new Error(errorMessage()||`Ditto failed to authenticate (error code: ${a}).`)}async function dittoAuthClientLoginWithUsernameAndPassword(t,e,n,i){ensureInitialized();const o=bytesFromString(e),a=bytesFromString(n),s=bytesFromString(i),c=await function ditto_auth_client_login_with_credentials(t,e,n,i){try{const s=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_auth_client_login_with_credentials(s,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(i));var o=getInt32Memory0()[s/4+0],a=getInt32Memory0()[s/4+1];if(getInt32Memory0()[s/4+2])throw takeObject(a);return takeObject(o)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,o,a,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){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_auth_client_logout(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(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){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.uninitialized_ditto_make(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(bytesFromString(t))}function dittoMake(t,e){return ensureInitialized(),function ditto_make(t,e,n){try{const a=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_make(a,addHeapObject(t),addHeapObject(e),addHeapObject(n));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,e,"Disabled")}async function dittoGetCollectionNames(t){ensureInitialized();const e=await function ditto_get_collection_names(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_get_collection_names(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t),n=e.status_code,i=e.names;if(0!==n)throw new Error(errorMessage()||`ditto_get_collection_names() failed with error code: ${n}`);return function cStringVecToStringArray(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.cStringVecToStringArray(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(i)}function dittoFree(t){return ensureInitialized(),function ditto_free(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_free(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t)}async function dittoRegisterPresenceV1Callback(t,e){ensureInitialized(),function ditto_register_presence_v1_callback(t,e){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_register_presence_v1_callback(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,wrapBackgroundCbForFFI((t=>console.error(`The registered presence callback v1 errored with ${t}`)),(t=>{const n=refCStringToString(t);e(n)})))}async function dittoClearPresenceCallback(t){ensureInitialized(),await function ditto_clear_presence_callback(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_clear_presence_callback(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t)}async function dittoRegisterPresenceV3Callback(t,e){ensureInitialized(),function ditto_register_presence_v3_callback(t,e){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_register_presence_v3_callback(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,wrapBackgroundCbForFFI((t=>console.error(`The registered presence callback v3 errored with ${t}`)),(t=>{const n=refCStringToString(t);e(n)})))}async function dittoClearPresenceV3Callback(t){ensureInitialized(),function ditto_clear_presence_v3_callback(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_clear_presence_v3_callback(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(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){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_set_device_name(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,n)}function dittoSetConnectRetryInterval(t,e){ensureInitialized();return function ditto_set_connect_retry_interval(t,e){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_set_connect_retry_interval(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,Math.min(Math.max(0,e),4294967295))}function dittoSetSyncGroup(t,e){return ensureInitialized(),function ditto_set_sync_group(t,e){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_set_sync_group(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,e)}async function dittoNewAttachmentFromBytes(t,e){ensureInitialized();const n={},i=await function ditto_new_attachment_from_bytes(t,e,n){try{const a=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_new_attachment_from_bytes(a,addHeapObject(t),addHeapObject(e),addHeapObject(n));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,e,n);if(0!==i)throw new Error(errorMessage()||`ditto_new_attachment_from_bytes() failed with error code: ${i}`);return n}async function dittoResolveAttachment(t,e,n,i){ensureInitialized();const{onComplete:o,onProgress:a,onDelete:s}=n,{status_code:c,cancel_token:d}=await function ditto_resolve_attachment(t,e,n,i,o){try{const c=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_resolve_attachment(c,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(i),addHeapObject(o));var a=getInt32Memory0()[c/4+0],s=getInt32Memory0()[c/4+1];if(getInt32Memory0()[c/4+2])throw takeObject(s);return takeObject(a)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,e,wrapBackgroundCbForFFI(i,o),wrapBackgroundCbForFFI(i,a),wrapBackgroundCbForFFI(i,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 i=function ditto_cancel_resolve_attachment(t,e,n){try{const a=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_cancel_resolve_attachment(a,addHeapObject(t),addHeapObject(e),addHeapObject(n));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,e,n);if(0!==i)throw new Error(errorMessage()||`ditto_cancel_resolve_attachment() failed with error code: ${i}`)}async function dittoGetCompleteAttachmentData(t,e){ensureInitialized();const{status:n,data:i}=await function ditto_get_complete_attachment_data(t,e){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_get_complete_attachment_data(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,e);if(0!==n)throw new Error(errorMessage()||`\`ditto_get_complete_attachment_data()\` failed with error code: ${n}`);return boxCBytesIntoBuffer(i)}function dittoGetSDKVersion(t){ensureInitialized();return boxCStringIntoString(function ditto_get_sdk_version(){try{const n=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_get_sdk_version(n);var t=getInt32Memory0()[n/4+0],e=getInt32Memory0()[n/4+1];if(getInt32Memory0()[n/4+2])throw takeObject(e);return takeObject(t)}finally{r.__wbindgen_add_to_stack_pointer(16)}}())}function dittoPresenceV1(t){ensureInitialized();return boxCStringIntoString(function ditto_presence_v1(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_presence_v1(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t))}function dittoPresenceV3(t){ensureInitialized();return boxCStringIntoString(function ditto_presence_v3(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_presence_v3(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t))}async function dittoShutdown(t){return ensureInitialized(),await function ditto_shutdown(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_shutdown(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t)}function dittoRunGarbageCollection(t){return ensureInitialized(),function ditto_run_garbage_collection(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_run_garbage_collection(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t)}async function dittoDisableSyncWithV3(t){ensureInitialized();const e=await function ditto_disable_sync_with_v3(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_disable_sync_with_v3(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t);if(0!==e)throw new Error(errorMessage()||`ditto_disable_sync_with_v3() failed with error code: ${e}`)}function dittoSetStaticWebsocketClients(t,e,n){ensureInitialized();!function ditto_set_static_websocket_clients(t,e,n){try{const a=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_set_static_websocket_clients(a,addHeapObject(t),addHeapObject(e),addHeapObject(n));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,e.map((t=>bytesFromString(t))),n)}function documentsHash(t){ensureInitialized();const{status_code:e,u64:n}=function ditto_documents_hash(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_documents_hash(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(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){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_documents_hash_mnemonic(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t);if(0!==e)throw new Error(errorMessage()||`\`ditto_documents_hash_mnemonic()\` failed with error code: ${e}`);return boxCStringIntoString(n)}async function dittoAuthSetLoginProvider(t,e){return ensureInitialized(),await function ditto_auth_set_login_provider(t,e){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_auth_set_login_provider(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,e)}function dittoAuthClientMakeLoginProvider(t,e){return ensureInitialized(),function ditto_auth_client_make_login_provider(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_auth_client_make_login_provider(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(wrapBackgroundCbForFFI(e,t))}function dittoAuthClientSetValidityListener(t,e,n){ensureInitialized();return function ditto_auth_client_set_validity_listener(t,e){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_auth_client_set_validity_listener(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,wrapBackgroundCbForFFI(n,(function(t,n){return e(1===t,1===n)})))}!function(t){t[t.counter=0]="counter",t[t.register=1]="register",t[t.attachment=2]="attachment",t[t.rga=3]="rga",t[t.rwMap=4]="rwMap"}(b||(b={}));let f,p=!1;async function init$2(t){t?await init$3(t):await init$3(),p=!0,f=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 i=function ditto_init_sdk_version(t,e,n){try{const a=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_init_sdk_version(a,addHeapObject(t),addHeapObject(e),addHeapObject(n));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,e,bytesFromString(n));if(void 0!==i&&0!==i)throw new Error(errorMessage()||`ditto_init_sdk_version() failed with error code: ${i}`)}const y=-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(){try{const n=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_error_message(n);var t=getInt32Memory0()[n/4+0],e=getInt32Memory0()[n/4+1];if(getInt32Memory0()[n/4+2])throw takeObject(e);return takeObject(t)}finally{r.__wbindgen_add_to_stack_pointer(16)}}())}function ensureInitialized(){if(!p)throw new Error("Ditto needs to be initialized before using any of its API, please make sure to call `await init()` first.")}class AttachmentToken{constructor(t){if(t[g]!==b.attachment)throw new Error("Invalid attachment token");const e=t._id;if(!(e instanceof Uint8Array))throw new Error("Invalid attachment token id");const n=t._len;if("number"!=typeof n||n<0)throw new Error("Invalid attachment token length");const r=t._meta;if("object"!=typeof r)throw new Error("Invalid attachment token meta");this.id=e,this.len=n,this.metadata=r}}let w=!1;class Logger{static setLogFile(t){t?(loggerSetLogFile(t),this.logFile=t):(loggerSetLogFile(null),delete this.logFile)}static setLogFileURL(t){this.setLogFile(null==t?void 0:t.pathname)}static get enabled(){return loggerEnabledGet()}static set enabled(t){loggerEnabled(t)}static get emojiLogLevelHeadingsEnabled(){return loggerEmojiHeadingsEnabledGet()}static set emojiLogLevelHeadingsEnabled(t){loggerEmojiHeadingsEnabled(t)}static get minimumLogLevel(){return loggerMinimumLogLevelGet()}static set minimumLogLevel(t){loggerMinimumLogLevel(t)}static async setCustomLogCallback(t){t?(await loggerSetCustomLogCb(t),this.customLogCallback=t):(await loggerSetCustomLogCb(null),delete this.customLogCallback)}static log(t,e){log(t,e)}static error(t){this.log("Error",t)}static warning(t){this.log("Warning",t)}static info(t){this.log("Info",t)}static debug(t){this.log("Debug",t)}static verbose(t){this.log("Verbose",t)}constructor(){throw new Error("Logger can't be instantiated, use it's static properties & methods directly instead.")}}const m=4294967296,O=9007199254740992;class TaggedValue{constructor(t,e){this.value=t,this.tag=e}}const v={decode:function decode(t,e,n){let r=new DataView(t),i=new Uint8Array(t),o=0,tagValueFunction=function(t,e){return new TaggedValue(t,e)},simpleValFunction=function(t){};function commitRead(t,e){return o+=t,e}function readArrayBuffer(e){return commitRead(e,new Uint8Array(t,o,e))}function readUint8(){return commitRead(1,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()*m+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 writeUint16(t){commitWrite(prepareWrite(2).setUint16(o,t))}function writeUint32(t){commitWrite(prepareWrite(4).setUint32(o,t))}function writeUint64(t){let e=t%m,n=(t-e)/m,r=prepareWrite(8);r.setUint32(o,n),r.setUint32(o+4,e),commitWrite()}function writeTypeAndLength(t,e){e<24?writeUint8(t<<5|e):e<256?(writeUint8(t<<5|24),writeUint8(e)):e<65536?(writeUint8(t<<5|25),writeUint16(e)):e<4294967296?(writeUint8(t<<5|26),writeUint32(e)):(writeUint8(t<<5|27),writeUint64(e))}if(function encodeItem(t){let e;if(!1===t)return writeUint8(244);if(!0===t)return writeUint8(245);if(null===t)return writeUint8(246);if(void 0===t)return writeUint8(247);if(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 if(t instanceof TaggedValue)!function writeVarUint(t,e){t<=255?t<24?writeUint8(t|e):(writeUint8(24|e),writeUint8(t)):t<=65535?(writeUint8(25|e),writeUint16(t)):t<=4294967295?(writeUint8(26|e),writeUint32(t)):(writeUint8(27|e),writeUint64(t))}(t.tag,192),encodeItem(t.value);else{let n=Object.keys(t);for(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 DocumentID{get value(){let t=this["@ditto.value"];return void 0===t&&(t=CBOR.decode(this["@ditto.cbor"]),this["@ditto.value"]=t),t}constructor(t,e=!1,n=!1){const r=e?t:CBOR.encode(t),i=n?r:validateDocumentIDCBOR(r);if(!i)throw new Error(`Can't create DocumentID, passed in value is not valid: ${t}`);this.isValidated=!n,this["@ditto.cbor"]=i}equals(t){const e=this["@ditto.cbor"],n=t["@ditto.cbor"];if(e===n)return!0;if(!(e instanceof Uint8Array))return!1;if(!(n instanceof Uint8Array))return!1;if(e.length!==n.length)return!1;for(let t=0;t<e.length;t+=1)if(e[t]!==n[t])return!1;return!0}toString(){return documentIDQueryCompatible(this["@ditto.cbor"],"WithoutQuotes")}toBase64String(){const t=this["@ditto.cbor"];return btoa(String.fromCharCode.apply(null,t))}toQueryCompatibleString(){return documentIDQueryCompatible(this["@ditto.cbor"],"WithQuotes")}toCBOR(){return this["@ditto.cbor"]}}function validateDocumentIDCBOR(t){const e=validateDocumentID(t);return null!=e?e:t}const I=[];class Handle{constructor(t,e){this.isClosed=!1,this.bridge=t,this.objectWeakRef=new WeakRef(e)}get type(){return this.bridge.type}deref(){const t=this.objectWeakRef.deref();if(null==t)throw new Error("Bridging error: can't get pointer for an object that has been garbage collected.");if(this.isClosed)throw new Error("Bridging error: can't get pointer for an object that has been closed.");const e=this.bridge.rawPointerFor(t);if(null==e)throw new Error(`Bridging error: ${this.type.name} object is not currently registered in this bridge.`);return e}derefOrNull(){const t=this.objectWeakRef.deref();if(null==t)return null;if(this.isClosed)return null;const e=this.bridge.rawPointerFor(t);return null!=e?e:null}object(){const t=this.objectWeakRef.deref();if(null==t)throw new Error(`Bridging error: ${this.bridge.type.name} object has already been garbage collected.`);if(this.isClosed)throw new Error(`Bridging error: ${this.bridge.type.name} object has already been closed.`);return t}objectOrNull(){var t;if(this.isClosed)throw new Error(`Bridging error: ${this.bridge.type.name} object has already been closed.`);return null!==(t=this.objectWeakRef.deref())&&void 0!==t?t:null}toString(){const t=this.derefOrNull();return`{ Handle | type: ${this.bridge.type}, object: ${this.objectWeakRef.deref()}, FFI address: ${null==t?void 0:t.addr}, FFI type: ${null==t?void 0:t.type} }`}}class Handles{constructor(t,e){this.handles=e.map((e=>t.handleFor(e)))}deref(){return this.handles.map((t=>t.deref()))}}class Bridge{constructor(t){this.internalType=null,this.pointerByObject=new WeakMap,this.release=t,this.handlesByAddress={},this.finalizationRegistry=new FinalizationRegistry(this.finalize.bind(this)),Bridge.all.push(new WeakRef(this))}get type(){if(null==this.internalType)throw new Error("Bridge type has not been registered yet.");return this.internalType}registerType(t){if(this.internalType!==t){if(this.internalType)throw new Error(`Can't register bridged type '${t.name}', another type was already registered: ${this.internalType}`);this.internalType=t}}handleFor(t){const e=this.pointerByObject.get(t);if(null==e)throw new Error(`Bridging error: ${this.type.name} object is not currently registered in this bridge.`);const n=this.handlesByAddress[e.addr];if(null==n)throw new Error(`Internal inconsistency, found a pointer for an object whose handle is undefined: ${e}`);return n}handlesFor(t){return new Handles(this,t)}objectFor(t){const e=this.handlesByAddress[t.addr];if(e){if(e.type!==this.type)throw new Error(`Can't return object for pointer, pointer is associated with an object of type ${e.type} but this bridge is configured for ${this.type}`);return e.object()}}bridge(t,e){const n=this.objectFor(t);if(n)return n;let r;if(e||(e=()=>Reflect.construct(this.type,[])),"function"==typeof e){if(r=e(),!(r instanceof this.type))throw new Error(`Can't bridge, expected passed in create function to return a ${this.type.name} object but got: ${r}`)}else r=e;return this.register(r,t),r}register(t,e){const n=t.constructor;if(n!==this.type)throw new Error(`Can't register, bridge is configured for type ${this.type.name} but passed in object is of type ${n.name}`);const r=this.pointerByObject.get(t),i=this.handlesByAddress[e.addr];if(null!=r&&null!=i)throw new Error(`Can't register, an object for the passed in pointer has previously been registered: ${i.object()}`);if(null!=r&&null==i)throw new Error(`Internal inconsistency, trying to register an object which has an associated pointer but no handle entry: ${n.name} at ${r.type} ${r.addr}`);if(null==r&&null!=i)throw new Error(`Internal inconsistency, trying to register an object which has a handle entry but no associated pointer: ${n.name} ${t}`);const o=new Handle(this,t);this.handlesByAddress[e.addr]=o,this.pointerByObject.set(t,e),this.finalizationRegistry.register(t,e,t),I.includes(this.type.name)&&console.log(`[VERBOSE] Bridge REGISTERED a new instance of ${this.type.name}, current count: ${Object.keys(this.handlesByAddress).length}`)}markAsClosed(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.pointerByObject.get(t);if(null==r)throw new Error(`Can't unregister, object that has not been registered before: ${t}`);const i=this.handlesByAddress[r.addr];if(null==i)throw new Error(`Internal inconsistency, trying to unregister an object which has an associated pointer but no handle: ${t}`);if(i.type!==n)throw new Error(`Internal inconsistency, trying to unregister an object that has a handle with a different type than that of the bridge: ${i}`);if(i.objectOrNull()!==t)throw new Error(`Internal inconsistency, trying to unregister an object whose associated handle holds a different object: ${i}`);i.isClosed=!0}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.pointerByObject.get(t);if(null==r)throw new Error(`Can't unregister, object that has not been registered before: ${t}`);const i=this.handlesByAddress[r.addr];if(null==i)throw new Error(`Internal inconsistency, trying to unregister an object which has an associated pointer but no handle: ${t}`);if(i.type!==n)throw new Error(`Internal inconsistency, trying to unregister an object that has a handle with a different type than that of the bridge: ${i}`);if(i.objectOrNull()!==t)throw new Error(`Internal inconsistency, trying to unregister an object whose associated handle holds a different object: ${i}`);this.finalizationRegistry.unregister(t),delete this.handlesByAddress[r.addr],this.pointerByObject.delete(t),I.includes(this.type.name)&&console.log(`[VERBOSE] Bridge UNREGISTERED an instance of ${this.type.name}, current count: ${Object.keys(this.handlesByAddress).length}`)}unregisterAll(){I.includes(this.type.name)&&console.log(`[VERBOSE] Unregistering ALL bridged instances of type ${this.type.name}.`);for(const t of Object.values(this.handlesByAddress)){const e=t.object();e&&this.unregister(e)}}get count(){return Object.keys(this.handlesByAddress).length}rawPointerFor(t){return this.pointerByObject.get(t)}finalize(t){const e=this.handlesByAddress[t.addr];if(!e)throw new Error(`Internal inconsistency, tried to finalize an instance for a pointer, that has no handle: ${t}`);delete this.handlesByAddress[t.addr],this.release(t,e),I.includes(this.type.name)&&console.log(`[VERBOSE] Bridge FINALIZED an instance of ${this.type.name}, current count: ${Object.keys(this.handlesByAddress).length}`)}}Bridge.all=[],Bridge.attachment=new Bridge((function freeAttachmentHandle(t){ensureInitialized(),function ditto_free_attachment_handle(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_free_attachment_handle(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t)})),Bridge.document=new Bridge(documentFree),Bridge.mutableDocument=new Bridge(documentFree),Bridge.staticTCPClient=new Bridge((function staticTCPClientFreeHandle(t){(void 0)(t)})),Bridge.websocketClient=new Bridge((function websocketClientFreeHandle(t){ensureInitialized(),function websocket_client_free_handle(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.websocket_client_free_handle(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t)})),Bridge.ditto=new Bridge((async(t,e)=>{dittoClearPresenceCallback(t),e.isClosed||await dittoShutdown(t),dittoFree(t)}));class UpdateResult{static set(t,e,n){return new UpdateResult("set",t,e,n,void 0)}static incremented(t,e,n){return new UpdateResult("incremented",t,e,void 0,n)}static removed(t,e){return new UpdateResult("removed",t,e,void 0,void 0)}constructor(t,e,n,r,i){this.type=t,this.docID=e,this.path=n,void 0!==r&&(this.value=r),void 0!==i&&(this.amount=i)}}class Attachment{get metadata(){return this.token.metadata}getData(){const t=this.ditto,e=Bridge.ditto.handleFor(t);return this.ditto.deferCloseAsync((async()=>{{const t=Bridge.attachment.handleFor(this);return await dittoGetCompleteAttachmentData(e.deref(),t.deref())}}))}copyToPath(t){const e=this.ditto;return Bridge.ditto.handleFor(e),this.ditto.deferCloseAsync((async()=>{throw new Error("Can't copy attachment to path, not available when running in the browser.")}))}constructor(t,e){this.ditto=t,this.token=e}}function augmentJSONValue(t,e,n){if(t&&"object"==typeof t){if(Array.isArray(t))return t.map(((t,r)=>augmentJSONValue(t,e,`${n}[${r}]`)));if(t[g]===b.counter)return Counter["@ditto.create"](e,n,t[h]);if(t[g]===b.register)return Register["@ditto.create"](e,n,t[h]);if(t[g]===b.attachment)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=!1){if(t&&"object"==typeof t){if(Array.isArray(t))return t.map(((t,e)=>desugarJSObject(t,!1)));if(t instanceof DocumentID)return t.value;if(t instanceof Counter){const e={};return e[g]=b.counter,e[h]=t.value,e}if(t instanceof Register){const e={};return e[g]=b.register,e[h]=t.value,e}if(t instanceof Attachment){const e={_id:t.token.id,_len:t.token.len,_meta:t.token.metadata};return e[g]=b.attachment,e}for(const[e,n]of Object.entries(t))t[e]=desugarJSObject(n,!1);return t}return function checkForUnsupportedValues(t){if(Number.isNaN(t)||t===1/0||t===-1/0)throw new Error("Non-finite float values are not supported")}(t),t}const k="cloud.ditto.live";function defaultAuthURL(t){return`https://${t}.${k}`}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}function generateEphemeralToken(){let t;t=crypto;const e=new Uint16Array(16);t.getRandomValues(e);return Array.from(e).map((t=>t.toString(16))).join("")}async function step(t){return await function sleep(t){return new Promise(((e,n)=>{setTimeout(e,t)}))}(0),t()}const j=step,C=/\.([A-Za-z_]\w*)/.source,M=/\[(\d+)\]/.source,E=/\[\'(.+?)\'\]/.source,D=/\[\"(.+?)\"\]/.source,A=`((${C})|(${M})|(${E})|(${D}))*`,B=new RegExp(`^${C}`),S=new RegExp(`^${M}`),P=new RegExp(`^${E}`),T=new RegExp(`^${D}`),H=new RegExp(`^${A}$`);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(!H.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(B);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(S);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(P);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{at(t){if("string"==typeof t){const e=t,n=KeyPath.validate(e),r=KeyPath.withoutLeadingDot(`${this.path}${n}`);return new DocumentPath(this.document,r,!1)}if("number"==typeof t){const e=validateNumber(t,{integer:!0,min:0,errorMessagePrefix:"DocumentPath.at() validation failed index:"});return new DocumentPath(this.document,`${this.path}[${e.toString()}]`,!1)}throw new Error(`Can't return document path at key-path or index, string or number expected but got ${typeof t}: ${t}`)}get value(){return this.underlyingValueForPathType("Any")}get counter(){const t=this.underlyingValueForPathType("Counter");return void 0!==t?Counter["@ditto.create"](null,this.path,t):null}get register(){const t=this.underlyingValueForPathType("Register");return void 0!==t?Register["@ditto.create"](null,this.path,t):null}get attachmentToken(){const t=this.underlyingValueForPathType("Attachment");return void 0!==t?new AttachmentToken(t):null}constructor(t,e,n){this.document=t,this.path=n?KeyPath.validate(e,{isInitial:!0}):e}underlyingValueForPathType(t){const e=this.path,n=this.document,r=documentGetCBORWithPathType(Bridge.document.handleFor(n).deref(),e,t);return null!==r.cbor?CBOR.decode(r.cbor):void 0}}class MutableDocumentPath{at(t){if("string"==typeof t){const e=t,n=KeyPath.validate(e),r=KeyPath.withoutLeadingDot(`${this.path}${n}`);return new MutableDocumentPath(this.mutableDocument,r,!1)}if("number"==typeof t){const e=validateNumber(t,{integer:!0,min:0,errorMessagePrefix:"MutableDocumentPath.at() validation failed index:"});return new MutableDocumentPath(this.mutableDocument,`${this.path}[${e.toString()}]`,!1)}throw new Error(`Can't return mutable document path at key-path or index, string or number expected but got ${typeof t}: ${t}`)}get value(){return this.underlyingValueForPathType("Any")}get counter(){const t=this.underlyingValueForPathType("Counter");return void 0!==t?Counter["@ditto.create"](this.mutableDocument,this.path,t):null}get register(){const t=this.underlyingValueForPathType("Register");return void 0!==t?Register["@ditto.create"](this.mutableDocument,this.path,t):null}get attachmentToken(){const t=this.underlyingValueForPathType("Attachment");return void 0!==t?new AttachmentToken(t):null}set(t,e){return this["@ditto.set"](t,e)}remove(){return this["@ditto.remove"]()}constructor(t,e,n){this.mutableDocument=t,this.path=n?KeyPath.validate(e,{isInitial:!0}):e}underlyingValueForPathType(t){const e=this.path,n=this.mutableDocument,r=documentGetCBORWithPathType(Bridge.mutableDocument.handleFor(n).deref(),e,t);return null!==r.cbor?CBOR.decode(r.cbor):void 0}"@ditto.increment"(t){documentIncrementCounter(Bridge.mutableDocument.handleFor(this.mutableDocument).deref(),this.path,t);const e=UpdateResult.incremented(this.mutableDocument.id,this.path,t);this.recordUpdateResult(e)}"@ditto.set"(t,e){const n=Bridge.mutableDocument.handleFor(this.mutableDocument),r=desugarJSObject(t,!1),i=CBOR.encode(r);e?documentSetCBORWithTimestamp(n.deref(),this.path,i,0):documentSetCBOR(n.deref(),this.path,i);const o=augmentJSONValue(CBOR.decode(i),this.mutableDocument,this.path),a=UpdateResult.set(this.mutableDocument.id,this.path,o);this.recordUpdateResult(a)}"@ditto.remove"(){documentRemove(Bridge.mutableDocument.handleFor(this.mutableDocument).deref(),this.path),this.updateInMemory(((t,e)=>{Array.isArray(t)&&"number"==typeof e?t.splice(e,1):delete t[e]}));const t=UpdateResult.removed(this.mutableDocument.id,this.path);this.recordUpdateResult(t)}updateInMemory(t){const e=this.mutableDocument.value,n=KeyPath.evaluate(this.path,e,{stopAtLastContainer:!0});t(n.value,n.nextPathComponent)}recordUpdateResult(t){const e=this.mutableDocument["@ditto.updateResults"].slice();e.push(t),Object.freeze(e),this.mutableDocument["@ditto.updateResults"]=e}}class Document{static hash(t){return documentsHash(documentsFrom(t).map((t=>Bridge.document.handleFor(t))).map((t=>t.deref())))}static hashMnemonic(t){const e=documentsFrom(t);return documentsHashMnemonic(Bridge.document.handlesFor(e).deref())}get id(){let t=this["@ditto.id"];if(void 0===t){const e=documentID(Bridge.document.handleFor(this).deref());t=new DocumentID(e,!0),this["@ditto.id"]=t}return t}get path(){return new DocumentPath(this,"",!1)}get value(){let t=this["@ditto.value"];return void 0===t&&(t=this.path.value,this["@ditto.value"]=t),t}at(t){return this.path.at(t)}constructor(){}static idCBOR(t){return documentID(Bridge.document.handleFor(t).deref())}static canonicalizedIDCBOR(t){return validateDocumentIDCBOR(t)}static isIDCBORCanonical(t){return t===this.canonicalizedIDCBOR(t)}}class MutableDocument{get id(){let t=this["@ditto.id"];if(void 0===t){const e=documentID(Bridge.mutableDocument.handleFor(this).deref());t=new DocumentID(e,!0),this["@ditto.id"]=t}return t}get path(){return new MutableDocumentPath(this,"",!1)}get value(){return this.path.value}at(t){return this.path.at(t)}constructor(){this["@ditto.updateResults"]=[]}static idCBOR(t){return documentID(Bridge.mutableDocument.handleFor(t).deref())}}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}`)}MutableDocument.canonicalizedIDCBOR=Document.canonicalizedIDCBOR,MutableDocument.isIDCBORCanonical=Document.isIDCBORCanonical;class UpdateResultsMap{get(t){const e=(t instanceof DocumentID?t:new DocumentID(t)).toString();return this.updateResultsByDocumentIDString[e]}keys(){return this.documentIDs.slice()}constructor(t,e){const n=t.map((t=>t.toString())).sort().join(", ");if(n!==Object.keys(e).sort().join(", "))throw new Error("Internal inconsistency, can't construct update results map, documentIDs must all be keys in update results (by document ID string)");this.documentIDs=t.slice(),this.updateResultsByDocumentIDString={...e}}}class BasePendingCursorOperation{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}async exec(){const t=this.collection.store.ditto,e=Bridge.ditto.handleFor(t);return t.deferCloseAsync((async()=>{const t=this.query;return(await j((async()=>await collectionExecQueryStr(e.deref(),this.collection.name,null,t,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset)))).map((t=>Bridge.document.bridge(t)))}))}async updateWithTransaction(t,e){const n=this.collection.store.ditto,r=Bridge.ditto.handleFor(n);return n.deferCloseAsync((async()=>await j((async()=>{const n=this.query,i=await collectionExecQueryStr(r.deref(),this.collection.name,e,n,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset),o=i.map((t=>Bridge.mutableDocument.bridge(t,(()=>new MutableDocument))));t(o);const a=[],s={};for(const t of o){const e=t.id,n=e.toString(),r=t["@ditto.updateResults"];if(s[n])throw new Error(`Internal inconsistency, update results for document ID as string already exist: ${n}`);a.push(e),s[n]=r,Bridge.mutableDocument.unregister(t)}return await collectionUpdateMultiple(r.deref(),this.collection.name,e,i),new UpdateResultsMap(a,s)}))))}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}then(t,e){return this.exec().then(t,e)}}class BasePendingIDSpecificOperation{async exec(){const t=this.collection.store.ditto,e=Bridge.ditto.handleFor(t);return t.deferCloseAsync((async()=>await j((async()=>{const t=await readTransaction(e.deref()),n=await collectionGet(e.deref(),this.collection.name,this.documentIDCBOR,t);let r;return n&&(r=Bridge.document.bridge(n)),readTransactionFree(t),r}))))}constructor(t,e){this.documentID=t,this.collection=e,this.documentIDCBOR=t.toCBOR()}then(t,e){return this.exec().then(t,e)}get query(){return`_id == ${this.documentID.toQueryCompatibleString()}`}}class ObserverManager{constructor(t,e={}){var n,r,i,o;const a=null!==(n=e.keepAlive)&&void 0!==n?n:null,s=null!==(r=e.register)&&void 0!==r?r:null,c=null!==(i=e.unregister)&&void 0!==i?i:null,d=null!==(o=e.process)&&void 0!==o?o:null;this.id=t,this.keepAlive=a,this.isClosed=!1,this.isRegistered=!1,this.callbacksByToken={},null!==s&&(this.register=s),null!==c&&(this.unregister=c),null!==d&&(this.process=d)}addObserver(t){var e;if(this.isClosed)throw new Error(`Internal inconsistency, can't add '${this.id}' observer, observer mananger close()-ed.`);this.registerIfNeeded();const n=generateEphemeralToken();return this.callbacksByToken[n]=t,null===(e=this.keepAlive)||void 0===e||e.retain(`${this.id}.${n}`),n}removeObserver(t){var e;const n=this.callbacksByToken[t];if(void 0===n)throw new Error(`Can't remove '${this.id}' observer, token '${t}' has never been registered before.`);null!==n&&(this.callbacksByToken[t]=null,null===(e=this.keepAlive)||void 0===e||e.release(`${this.id}.${t}`),this.unregisterIfNeeded())}hasObserver(t){return void 0!==this.callbacksByToken[t]}notify(...t){if(this.isClosed)return;const e=this.process(...t);for(const t in this.callbacksByToken){(0,this.callbacksByToken[t])(...e)}}close(){this.isClosed=!0;for(const t in this.callbacksByToken)this.removeObserver(t)}register(t){}unregister(){}process(...t){return t}hasObservers(){return Object.keys(this.callbacksByToken).length>0}registerIfNeeded(){if(!this.isRegistered){const t=new WeakRef(this);this.isRegistered=!0,this.register((function(...e){const n=t.deref();n&&n.notify(...e)}))}}unregisterIfNeeded(){!this.hasObservers()&&this.isRegistered&&(this.isRegistered=!1,this.unregister())}}class Authenticator{loginWithToken(t,e){throw new Error("Authenticator.loginWithToken() is abstract and must be implemented by subclasses.")}loginWithUsernameAndPassword(t,e,n){throw new Error("Authenticator.loginWithUsernameAndPassword() is abstract and must be implemented by subclasses.")}logout(t){throw new Error("Authenticator.logout() is abstract and must be implemented by subclasses.")}observeStatus(t){const e=this.observerManager.addObserver(t);return new Observer(this.observerManager,e,{stopsWhenFinalized:!0})}constructor(t){this.keepAlive=t,this.status={isAuthenticated:!1,userID:null},this.loginSupported=!1,this.observerManager=new ObserverManager("AuthenticationStatusObservation",{keepAlive:t})}"@ditto.authenticationExpiring"(t){throw new Error("Authenticator['@ditto.authenticationExpiring']() is abstract and must be implemented by subclasses.")}"@ditto.authClientValidityChanged"(t,e){throw new Error("Authenticator['@ditto.authClientValidityChanged']() is abstract and must be implemented by subclasses.")}close(){this.observerManager.close()}}class OnlineAuthenticator extends Authenticator{async loginWithToken(t,e){const n=this.ditto.deref();if(!n)return;const r=Bridge.ditto.handleFor(n).derefOrNull();return r?n.deferCloseAsync((async()=>{await dittoAuthClientLoginWithToken(r,t,e)})):void 0}async loginWithUsernameAndPassword(t,e,n){const r=this.ditto.deref();if(!r)return;const i=Bridge.ditto.handleFor(r).derefOrNull();return i?r.deferCloseAsync((async()=>{await dittoAuthClientLoginWithUsernameAndPassword(i,t,e,n)})):void 0}async logout(t){const e=this.ditto.deref();if(!e)return;const n=Bridge.ditto.handleFor(e).derefOrNull();return n?e.deferCloseAsync((async()=>{await dittoAuthClientLogout(n),e.stopSync(),null==t||t(this.ditto)})):void 0}constructor(t,e,n){super(t),this.loginSupported=!0,this.status={isAuthenticated:!1,userID:null},this.ditto=new WeakRef(e),this.authenticationHandler=n,this.updateAndNotify(!1)}"@ditto.authenticationExpiring"(t){const e=this.authenticationHandler;t>0?e.authenticationExpiringSoon(this,t):e.authenticationRequired(this)}"@ditto.authClientValidityChanged"(t,e){this.updateAndNotify(!0)}updateAndNotify(t){var e;const n=this.ditto.deref();if(!n)return void Logger.debug("Unable to update auth status and notify, related Ditto object does not exist anymore.");const r=Bridge.ditto.handleFor(n).derefOrNull();if(!r)return void Logger.debug("Unable to update auth status and notify, related Ditto object does not exist anymore.");const i=this.status.isAuthenticated,o=this.status.userID,a=dittoAuthClientIsWebValid(r),s=dittoAuthClientUserID(r),c={isAuthenticated:a,userID:s};if(this.status=c,t){!!i==!!a&&o===s||(null===(e=this.authenticationHandler.authenticationStatusDidChange)||void 0===e||e.call(this.authenticationHandler,this),this.observerManager.notify(c))}}}class NotAvailableAuthenticator extends Authenticator{async loginWithToken(t,e){throw new Error("Can't login, authentication is not supported for the identity in use, please use an onlineWithAuthentication identity.")}async loginWithUsernameAndPassword(t,e,n){throw new Error("Can't login, authentication is not supported for the identity in use, please use an onlineWithAuthentication identity.")}logout(t){throw new Error("Can't logout, authentication is not supported for the identity in use, please use an onlineWithAuthentication identity.")}"@ditto.authenticationExpiring"(t){throw new Error(`Internal inconsistency, authentication is not available, yet the @ditto.authenticationExpiring() was called on authenticator: ${this}`)}"@ditto.authClientValidityChanged"(t,e){throw new Error(`Internal inconsistency, authentication is not available, yet the @ditto.authClientValidityChanged() was called on authenticator: ${this}`)}}const F=["manual","sharedKey","offlinePlayground"];class TransportConfig{constructor(){this.peerToPeer={bluetoothLE:{isEnabled:!1},awdl:{isEnabled:!1},lan:{isEnabled:!1,isMdnsEnabled:!0,isMulticastEnabled:!0}},this.connect={tcpServers:[],websocketURLs:[],retryInterval:5e3},this.listen={tcp:{isEnabled:!1,interfaceIP:"0.0.0.0",port:4040},http:{isEnabled:!1,interfaceIP:"0.0.0.0",port:80,websocketSync:!0}},this.global={syncGroup:0,routingHint:0}}setAllPeerToPeerEnabled(t){this.peerToPeer.bluetoothLE.isEnabled=t,this.peerToPeer.lan.isEnabled=t,this.peerToPeer.awdl.isEnabled=t}freeze(){return this.isFrozen||(this.isFrozen=!0,Object.freeze(this.peerToPeer.bluetoothLE),Object.freeze(this.peerToPeer.awdl),Object.freeze(this.peerToPeer.lan),Object.freeze(this.peerToPeer),Object.freeze(this.connect.tcpServers),Object.freeze(this.connect.websocketURLs),Object.freeze(this.connect),Object.freeze(this.listen.tcp),Object.freeze(this.listen.http),Object.freeze(this.listen),Object.freeze(this.global)),this}copy(){const t=new TransportConfig;return t.peerToPeer.bluetoothLE.isEnabled=this.peerToPeer.bluetoothLE.isEnabled,t.peerToPeer.awdl.isEnabled=this.peerToPeer.awdl.isEnabled,t.peerToPeer.lan.isEnabled=this.peerToPeer.lan.isEnabled,t.peerToPeer.lan.isMdnsEnabled=this.peerToPeer.lan.isMdnsEnabled,t.peerToPeer.lan.isMulticastEnabled=this.peerToPeer.lan.isMulticastEnabled,t.connect.tcpServers=this.connect.tcpServers.slice(),t.connect.websocketURLs=this.connect.websocketURLs.slice(),t.listen.tcp={...this.listen.tcp},t.listen.http={...this.listen.http},t.global.syncGroup=this.global.syncGroup,t.global.routingHint=this.global.routingHint,t}static areListenTCPsEqual(t,e){return t.isEnabled===e.isEnabled&&t.interfaceIP===e.interfaceIP&&t.port===e.port}static areListenHTTPsEqual(t,e){return t.isEnabled===e.isEnabled&&t.interfaceIP===e.interfaceIP&&t.port===e.port&&t.staticContentPath===e.staticContentPath&&t.websocketSync===e.websocketSync&&t.tlsKeyPath===e.tlsKeyPath&&t.tlsCertificatePath===e.tlsCertificatePath}}class Subscription{get collectionName(){return this.collection.name}cancel(){this.isCancelled||(this.isCancelled=!0,this.manager.remove(this))}constructor(t,e,n,r,i,o){this.isCancelled=!1,this.query=e,this.queryArgsCBOR=n,this.collection=t,this.contextInfo={id:generateEphemeralToken(),collectionName:t.name,query:e,queryArgsCBOR:n,orderBys:r,limit:i,offset:o},this.manager=t.store.ditto.subscriptionManager,this.manager.add(this)}}class LiveQueryEventInitial{constructor(){this.isInitial=!0}hash(t){return documentsHash(Bridge.document.handlesFor(t).deref())}hashMnemonic(t){return documentsHashMnemonic(Bridge.document.handlesFor(t).deref())}}class LiveQueryEventUpdate{hash(t){return documentsHash(Bridge.document.handlesFor(t).deref())}hashMnemonic(t){return documentsHashMnemonic(Bridge.document.handlesFor(t).deref())}constructor(t){this.isInitial=!1,this.oldDocuments=t.oldDocuments,this.insertions=t.insertions,this.deletions=t.deletions,this.updates=t.updates,this.moves=t.moves}}class SingleDocumentLiveQueryEvent{hash(t){return documentsHash(Bridge.document.handlesFor(null==t?[]:[t]).deref())}hashMnemonic(t){return documentsHashMnemonic(Bridge.document.handlesFor(null==t?[]:[t]).deref())}constructor(t,e){this.isInitial=t,this.oldDocument=e}}class LiveQuery{get collectionName(){return this.collection.name}get isStopped(){return!this.liveQueryManager}stop(){this.isStopped||this.liveQueryManager.stopLiveQuery(this)}constructor(t,e,n,r,i,o,a,s){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=s,this.liveQueryManager=null;const c=a.name,d=new WeakRef(a.store.ditto);let l;const signalNext=async()=>{const t=d.deref();if(!t)return;const e=Bridge.ditto.handleFor(t).derefOrNull();return e?t.deferCloseAsync((async()=>{await liveQuerySignalAvailableNext(e,l)})):void 0},u=a.store.ditto,_=Bridge.ditto.handleFor(u);u.deferClose((()=>{if(l=liveQueryRegister(_.deref(),c,t,n,this.orderBys,i,o,(t=>{const e=t.documents.map((t=>Bridge.document.bridge(t)));let n;n=t.is_initial?new LiveQueryEventInitial:new LiveQueryEventUpdate({oldDocuments:t.old_documents.map((t=>Bridge.document.bridge(t))),insertions:t.insertions,deletions:t.deletions,updates:t.updates,moves:t.moves.map((t=>({from:t[0],to:t[1]})))}),s(e,n,signalNext)})),!l)throw new Error("Internal inconsistency, couldn't create a valid live query ID.");this.liveQueryID=l}))}async signalNext(){const t=this.collection.store.ditto,e=Bridge.ditto.handleFor(t);if(e.derefOrNull())return t.deferCloseAsync((async()=>{await liveQuerySignalAvailableNext(e.deref(),this.liveQueryID)}))}}class PendingCursorOperation extends BasePendingCursorOperation{sort(t,e="ascending"){return super.sort(t,e)}offset(t){return super.offset(t)}limit(t){return super.limit(t)}async remove(){const t=this.collection.store.ditto,e=Bridge.ditto.handleFor(t);return t.deferCloseAsync((async()=>{const t=this.query;return(await j((async()=>{const n=await writeTransaction(e.deref()),r=await collectionRemoveQueryStr(e.deref(),this.collection.name,n,t,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);return await writeTransactionCommit(e.deref(),n),r}))).map((t=>new DocumentID(t,!0)))}))}async evict(){const t=this.collection.store.ditto,e=Bridge.ditto.handleFor(t);return t.deferCloseAsync((async()=>{const t=this.query;return(await j((async()=>{const n=await writeTransaction(e.deref()),r=await collectionEvictQueryStr(e.deref(),this.collection.name,n,t,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);return await writeTransactionCommit(e.deref(),n),r}))).map((t=>new DocumentID(t,!0)))}))}async update(t){const e=this.collection.store.ditto,n=Bridge.ditto.handleFor(e);return e.deferCloseAsync((async()=>await j((async()=>{const e=await writeTransaction(n.deref()),r=await super.updateWithTransaction(t,e);return await writeTransactionCommit(n.deref(),e),r}))))}subscribe(){const t=new Subscription(this.collection,this.query,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);return this.collection.store.ditto.subscriptionManager.add(t),t}observeLocal(t){return this._observe(t,!1)}observeLocalWithNextSignal(t){return this._observe(t,!0)}constructor(t,e,n){super(t,e,n)}_observe(t,e){const n=e?t:function wrappedHandler(e,n,r){try{return t.call(this,e,n)}finally{r()}},r=new LiveQuery(this.query,this.queryArgs,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset,this.collection,n);return this.collection.store.ditto.liveQueryManager.startLiveQuery(r),r}}class PendingIDSpecificOperation extends BasePendingIDSpecificOperation{async remove(){const t=this.collection.store.ditto,e=Bridge.ditto.handleFor(t);return t.deferCloseAsync((async()=>await j((async()=>{const t=await writeTransaction(e.deref()),n=await collectionRemove(e.deref(),this.collection.name,t,this.documentIDCBOR);return await writeTransactionCommit(e.deref(),t),n}))))}async evict(){const t=this.collection.store.ditto,e=Bridge.ditto.handleFor(t);return t.deferCloseAsync((async()=>await j((async()=>{const t=await writeTransaction(e.deref()),n=await collectionEvict(e.deref(),this.collection.name,t,this.documentIDCBOR);return await writeTransactionCommit(e.deref(),t),n}))))}async update(t){const e=this.collection.store.ditto,n=Bridge.ditto.handleFor(e);return e.deferCloseAsync((async()=>{const e=await readTransaction(n.deref()),r=await collectionGet(n.deref(),this.collection.name,this.documentIDCBOR,e);if(readTransactionFree(e),!r)throw new Error(`Can't update, document with ID '${this.documentID.toString()}' not found in collection named '${this.collection.name}'`);const i=Bridge.mutableDocument.bridge(r,(()=>new MutableDocument));t(i),Bridge.mutableDocument.unregister(i);const o=await writeTransaction(n.deref());return await collectionUpdate(n.deref(),this.collection.name,o,r),await writeTransactionCommit(n.deref(),o),i["@ditto.updateResults"].slice()}))}subscribe(){const t=new Subscription(this.collection,this.query,null,[],-1,0);return this.collection.store.ditto.subscriptionManager.add(t),t}observeLocal(t){return this._observe(t,!1)}observeLocalWithNextSignal(t){return this._observe(t,!0)}constructor(t,e){super(t,e)}_observe(t,e){const n=new LiveQuery(this.query,null,null,[],-1,0,this.collection,((n,r,i)=>{if(n.length>1){const t=n.map((t=>t.id.toBase64String()));throw new Error(`Internal inconsistency, single document live query returned more than one document. Query: ${this.query}, documentIDs: ${t.join(", ")}.`)}if(!1===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=n[0]||null,a=!0===r.isInitial?void 0:r.oldDocuments[0],s=new SingleDocumentLiveQueryEvent(r.isInitial,a);if(e)t(o,s,i);else try{t(o,s)}finally{i()}}));return this.collection.store.ditto.liveQueryManager.startLiveQuery(n),n}}class Collection{find(t,e){return new PendingCursorOperation(t,null!=e?e:null,this)}findAll(){return this.find("true")}findByID(t){const e=t instanceof DocumentID?t:new DocumentID(t);return new PendingIDSpecificOperation(e,this)}async upsert(t,e={}){const n=this.store.ditto,r=Bridge.ditto.handleFor(n);return n.deferCloseAsync((async()=>{var n;const i=null!==(n=e.writeStrategy)&&void 0!==n?n:"merge",o=desugarJSObject(t,!0),a=CBOR.encode(o),s=await j((async()=>await collectionInsertValue(r.deref(),this.name,a,i,void 0)));return new DocumentID(s,!0)}))}async newAttachment(t,e={}){const n=this.store.ditto,r=Bridge.ditto.handleFor(n);return n.deferCloseAsync((async()=>{const{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.deref(),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={_id:i,_len:o,_meta:{...e}};s[g]=b.attachment;const c=new AttachmentToken(s),d=new Attachment(n,c);return Bridge.attachment.bridge(a,(()=>d))}))}fetchAttachment(t,e){if(null==t||!(t instanceof AttachmentToken))throw new Error(`Invalid attachment token: ${t}`);const n=this.store.ditto;return n.deferClose((()=>n.attachmentFetcherManager.startAttachmentFetcher(t,e)))}constructor(t,e){this.name=t,this.store=e}findByIDCBOR(t){const e=new DocumentID(t,!0,!0);return new PendingIDSpecificOperation(e,this)}}class CollectionsEvent{static initial(t){return new CollectionsEvent({isInitial:!0,collections:t,oldCollections:[],insertions:[],deletions:[],updates:[],moves:[]})}constructor(t){this.isInitial=t.isInitial,this.collections=t.collections,this.oldCollections=t.oldCollections,this.insertions=t.insertions,this.deletions=t.deletions,this.updates=t.updates,this.moves=t.moves}}class PendingCollectionsOperation{sort(t,e="ascending"){return this.pendingCursorOperation.sort(t,e),this}offset(t){return this.pendingCursorOperation.offset(t),this}limit(t){return this.pendingCursorOperation.limit(t),this}subscribe(){return this.pendingCursorOperation.subscribe()}observeLocal(t){return this._observe(t,!1)}observeLocalWithNextSignal(t){return this._observe(t,!0)}async exec(){return collectionsFromDocuments(await this.pendingCursorOperation.exec(),this.store)}constructor(t){this.store=t,this.pendingCursorOperation=new PendingCursorOperation("true",null,new Collection("__collections",t))}then(t,e){return this.exec().then(t,e)}_observe(t,e){const n=new WeakRef(this.store);return this.pendingCursorOperation._observe((function(r,i,o){const a=n.deref();if(!a)return;const s=collectionsFromDocuments(r,a);let c;if(!0===i.isInitial)c=CollectionsEvent.initial(s);else{const t=collectionsFromDocuments(i.oldDocuments,a);c=new CollectionsEvent({isInitial:!1,collections:s,oldCollections:t,insertions:i.insertions,deletions:i.deletions,updates:i.updates,moves:i.moves})}e?t(c,o):t(c)}),e)}}function collectionsFromDocuments(t,e){const n=[];for(const r of t){const t=r.at("name").value;void 0!==t&&"string"==typeof t&&n.push(new Collection(t,e))}return n}class ExperimentalSubscriptionManager{constructor(t){this.subscriptions={},this.finalizationRegistry=new FinalizationRegistry(this.removeWithContextInfo.bind(this)),this.ditto=t}addSubscription(t){if(null!=this.subscriptions[t.contextInfo.id])throw new Error(`Internal inconsistency, tried to add a subscription that is already tracked: ${t.contextInfo.id}`);const e=Bridge.ditto.handleFor(this.ditto);this.ditto.deferClose((()=>{experimentalAddDqlSubscription(e.deref(),t.query,t.queryArgsCBOR)})),this.subscriptions[t.contextInfo.id]=new WeakRef(t),this.finalizationRegistry.register(t,t.contextInfo,t)}removeSubscription(t){if(null==this.subscriptions[t.contextInfo.id])throw new Error(`Internal inconsistency, tried to remove a subscription that is not tracked: ${t.contextInfo.id}`);this.finalizationRegistry.unregister(t),delete this.subscriptions[t.contextInfo.id],this.removeWithContextInfo(t.contextInfo)}close(){Logger.debug(`ExperimentalSubscriptionManager.close() with ${this.subscriptions.length} queries`),this.ditto.deferClose((()=>{var t;for(const e of Object.values(this.subscriptions))null===(t=e.deref())||void 0===t||t.cancel()}))}removeWithContextInfo(t){const e=Bridge.ditto.handleFor(this.ditto);this.ditto.deferClose((()=>{experimentalRemoveDqlSubscription(e.deref(),t.query,t.queryArgsCBOR),delete this.subscriptions[t.id]}))}}class ExperimentalSubscription{cancel(){this.isCancelled||(this.isCancelled=!0,this.manager.removeSubscription(this))}constructor(t,e,n){this.isCancelled=!1,this.query=e,this.queryArgsCBOR=n,this.contextInfo={id:generateEphemeralToken(),query:e,queryArgsCBOR:n},this.manager=t,t.addSubscription(this)}}class ExperimentalStore{constructor(t){this.ditto=t,this.subscriptionManager=new ExperimentalSubscriptionManager(this.ditto)}close(){this.subscriptionManager.close()}async execute(t){Logger.debug(`ExperimentalStore.execute(query = ${t})`);const e=this.ditto,n=Bridge.ditto.handleFor(e);return e.deferCloseAsync((async()=>(await j((async()=>await experimentalExecQueryStr(n.deref(),null,t,null)))).map((t=>Bridge.document.bridge(t)))))}subscribe(t){return Logger.debug(`ExperimentalStore.subscribe(query = ${t})`),new ExperimentalSubscription(this.subscriptionManager,t,null)}}class WriteTransactionPendingCursorOperation extends BasePendingCursorOperation{sort(t,e="ascending"){return super.sort(t,e)}offset(t){return super.offset(t)}limit(t){return super.limit(t)}async remove(){const t=this.collection.store.ditto,e=Bridge.ditto.handleFor(t);return t.deferCloseAsync((async()=>{const t=this.query,n=this.collection.writeTransaction,r=(await j((async()=>collectionRemoveQueryStr(e.deref(),this.collection.name,n.writeTransactionPointer,t,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset)))).map((t=>new DocumentID(t,!0)));return r.forEach((t=>{n.addResult("removed",t,this.collection.name)})),r}))}async evict(){const t=this.collection.store.ditto,e=Bridge.ditto.handleFor(t);return t.deferCloseAsync((async()=>{const t=this.query,n=this.collection.writeTransaction,r=(await j((async()=>collectionEvictQueryStr(e.deref(),this.collection.name,n.writeTransactionPointer,t,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset)))).map((t=>new DocumentID(t,!0)));return r.forEach((t=>{n.addResult("evicted",t,this.collection.name)})),r}))}async update(t){const e=this.collection.writeTransaction,n=await super.updateWithTransaction(t,e.writeTransactionPointer);return n.keys().forEach((t=>{e.addResult("updated",t,this.collection.name)})),n}constructor(t,e,n){super(t,e,n)}}class WriteTransactionPendingIDSpecificOperation extends BasePendingIDSpecificOperation{async remove(){const t=this.collection.store.ditto,e=Bridge.ditto.handleFor(t);return t.deferCloseAsync((async()=>{const t=this.collection.writeTransaction,n=await j((async()=>collectionRemove(e.deref(),this.collection.name,t.writeTransactionPointer,this.documentIDCBOR)));return t.addResult("removed",this.documentID,this.collection.name),n}))}async evict(){const t=this.collection.store.ditto,e=Bridge.ditto.handleFor(t);return t.deferCloseAsync((async()=>{const t=this.collection.writeTransaction,n=await j((async()=>await collectionEvict(e.deref(),this.collection.name,t.writeTransactionPointer,this.documentIDCBOR)));return t.addResult("evicted",this.documentID,this.collection.name),n}))}async update(t){const e=this.collection.store.ditto,n=Bridge.ditto.handleFor(e);return e.deferCloseAsync((async()=>{const e=this.collection.writeTransaction,r=await readTransaction(n.deref()),i=await collectionGet(n.deref(),this.collection.name,this.documentIDCBOR,r);if(readTransactionFree(r),!i)throw new Error(`Can't update, document with ID '${this.documentID.toString()}' not found in collection named '${this.collection.name}'`);const o=Bridge.mutableDocument.bridge(i,(()=>new MutableDocument));return t(o),Bridge.mutableDocument.unregister(o),await collectionUpdate(n.deref(),this.collection.name,e.writeTransactionPointer,i),e.addResult("updated",this.documentID,this.collection.name),o["@ditto.updateResults"].slice()}))}constructor(t,e){super(t,e)}}class WriteTransactionCollection{find(t,e){return new WriteTransactionPendingCursorOperation(t,null!=e?e:null,this)}findAll(){return this.find("true")}findByID(t){const e=t instanceof DocumentID?t:new DocumentID(t);return new WriteTransactionPendingIDSpecificOperation(e,this)}async upsert(t,e={}){const n=this.store.ditto,r=Bridge.ditto.handleFor(n);return n.deferCloseAsync((async()=>{var n;const i=null!==(n=e.writeStrategy)&&void 0!==n?n:"merge",o=desugarJSObject(t,!0),a=CBOR.encode(o),s=await j((async()=>await collectionInsertValue(r.deref(),this.name,a,i,this.writeTransaction.writeTransactionPointer))),c=new DocumentID(s,!0);return this.writeTransaction.addResult("inserted",c,this.name),new DocumentID(s,!0)}))}findByIDCBOR(t){const e=new DocumentID(t,!0,!0);return new WriteTransactionPendingIDSpecificOperation(e,this)}constructor(t,e,n){this.name=t,this.store=e,this.writeTransaction=n}}class WriteTransaction{static async init(t){return t.deferCloseAsync((async()=>{const e=Bridge.ditto.handleFor(t),n=await writeTransaction(e.deref());return new WriteTransaction(t,n)}))}scoped(t){if("string"!=typeof t)throw new Error("Collection name must be a string");return new WriteTransactionCollection(t,this.ditto.store,this)}async commit(){const t=this.ditto,e=Bridge.ditto.handleFor(t);return t.deferCloseAsync((async()=>writeTransactionCommit(e.deref(),this.writeTransactionPointer)))}async rollback(){const t=this.ditto,e=Bridge.ditto.handleFor(t);return t.deferCloseAsync((async()=>writeTransactionRollback(e.deref(),this.writeTransactionPointer)))}addResult(t,e,n){this.results.push({type:t,docID:e,collectionName:n})}constructor(t,e){this.writeTransactionPointer=e,this.ditto=t,this.results=[]}}class Store{collection(t){return new Collection(t,this)}collections(){return new PendingCollectionsOperation(this)}collectionNames(){const t=this.ditto,e=Bridge.ditto.handleFor(t);return t.deferClose((()=>dittoGetCollectionNames(e.deref())))}async write(t){return this.ditto.deferCloseAsync((async()=>{const e=await WriteTransaction.init(this.ditto);try{await t(e)}catch(t){throw await e.rollback(),Logger.warning(`Transaction rolled back due to an error: ${null==t?void 0:t.message}`),t}return await e.commit(),e.results}))}constructor(t){this.ditto=t,this.experimental=new ExperimentalStore(t)}close(){this.experimental.close()}async registerLiveQueryWebhook(t,e,n){const r=this.ditto,i=Bridge.ditto.handleFor(r);return r.deferCloseAsync((async()=>{const r=validateQuery(e),o=await liveQueryWebhookRegister(i.deref(),t,r,[],0,0,n);return new DocumentID(o,!0)}))}}class Presence{get graph(){const t=this.ditto,e=Bridge.ditto.handleFor(t);return t.deferClose((()=>{const t=dittoPresenceV3(e.deref());return JSON.parse(t)}))}observe(t){const e=this.observerManager.addObserver(t),n=new Observer(this.observerManager,e,{stopsWhenFinalized:!0});return t(this.graph),n}constructor(t){this.ditto=t,this.observerManager=new ObserverManager("PresenceObservation",{keepAlive:t.keepAlive,register:t=>{const e=this.ditto,n=Bridge.ditto.handleFor(e);e.deferClose((()=>{dittoRegisterPresenceV3Callback(n.deref(),t)}))},unregister:()=>{const t=this.ditto,e=Bridge.ditto.handleFor(t);t.deferClose((()=>{dittoClearPresenceV3Callback(e.deref())}))},process:t=>[JSON.parse(t)]})}close(){this.observerManager.close()}}class LiveQueryManager{constructor(t,e){this.finalizationRegistry=new FinalizationRegistry(this.finalize),this.ditto=t,this.keepAlive=e,this.liveQueriesByID={}}startLiveQuery(t){const e=this.ditto,n=Bridge.ditto.handleFor(e);e.deferCloseAsync((async()=>{const r=t.liveQueryID;if(!r)throw new Error("Internal inconsistency, tried to add a live query that doesn't have a live query ID (probably stopped).");if(this.liveQueriesByID[r])throw new Error("Internal inconsistency, tried to add a live query with an ID that has already been added.");const i=new WeakRef(t);return this.liveQueriesByID[r]=i,this.finalizationRegistry.register(t,r,this.finalize),t.liveQueryManager=this,e.keepAlive.retain(`LiveQuery.${r}`),new Promise(((t,e)=>{step((async()=>{await liveQueryStart(n.deref(),r),t()}))}))}))}stopLiveQuery(t){this.finalizationRegistry.unregister(t);const e=t.liveQueryID;if(!e)throw new Error("Internal inconsistency, tried to remove a live query that doesn't have a live query ID (probably stopped).");t.liveQueryManager=null,this.stopLiveQueryWithID(e)}close(){for(const t in this.liveQueriesByID){const e=this.liveQueriesByID[t].deref();e&&this.stopLiveQuery(e)}}stopLiveQueryWithID(t){const e=this.ditto,n=Bridge.ditto.handleFor(e);e.deferClose((()=>{liveQueryStop(n.deref(),t),this.keepAlive.release(`LiveQuery.${t}`),delete this.liveQueriesByID[t]}))}finalize(t){this.stopLiveQueryWithID(t)}}class PresenceManager{constructor(t){this.ditto=t,this.isClosed=!1,this.isRegistered=!1,this.currentRemotePeers=[],this.callbacksByPresenceToken={}}addObserver(t){if(this.isClosed)throw new Error("Internal inconsistency, can't add presence observer, observer mananger close()-ed.");this.registerIfNeeded();const e=generateEphemeralToken();return this.callbacksByPresenceToken[e]=t,this.ditto.keepAlive.retain(`PresenceObservation.${e}`),t(this.currentRemotePeers),e}removeObserver(t){const e=this.callbacksByPresenceToken[t];if(void 0===e)throw new Error(`Can't remove presence observer, token '${t}' has never been registered before.`);null!==e&&void 0!==this.callbacksByPresenceToken[t]&&(this.ditto.keepAlive.release(`PresenceObservation.${t}`),this.callbacksByPresenceToken[t]=null,this.unregisterIfNeeded())}hasObserver(t){return void 0!==this.callbacksByPresenceToken[t]}close(){this.isClosed=!0;for(const t in this.callbacksByPresenceToken)this.removeObserver(t)}hasObservers(){return Object.keys(this.callbacksByPresenceToken).length>0}registerIfNeeded(){const t=this.ditto,e=Bridge.ditto.handleFor(this.ditto);t.deferClose((()=>{if(!this.isRegistered){this.isRegistered=!0;const t=dittoPresenceV1(e.deref());this.currentRemotePeers=this.decode(t).sort(this.compareRemotePeers),dittoRegisterPresenceV1Callback(e.deref(),this.handlePresenceV1Callback.bind(this))}}))}unregisterIfNeeded(){const t=this.ditto,e=Bridge.ditto.handleFor(t);t.deferClose((()=>{!this.hasObservers()&&this.isRegistered&&(this.isRegistered=!1,dittoClearPresenceCallback(e.deref()),this.currentRemotePeers=[])}))}handlePresenceV1Callback(t){const e=this.decode(t).sort(this.compareRemotePeers);this.currentRemotePeers=e,this.notify()}notify(){if(!this.isClosed)for(const t in this.callbacksByPresenceToken){(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}}))}compareRemotePeers(t,e){return 0===t.connections.length&&e.connections.length>0?1:t.connections.length>0&&0===e.connections.length||t.deviceName<e.deviceName?-1:t.deviceName>e.deviceName?1:0}}class TransportConditionsManager extends ObserverManager{constructor(t){super("TransportConditionsObservation",{keepAlive:t.keepAlive}),this.ditto=t}register(t){const e=this.ditto,n=Bridge.ditto.handleFor(e);return e.deferClose((()=>dittoRegisterTransportConditionChangedCallback(n.deref(),t)))}unregister(){const t=this.ditto,e=Bridge.ditto.handleFor(t);return t.deferClose((()=>dittoRegisterTransportConditionChangedCallback(e.deref(),null)))}process(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,this.mdnsClientTransportPointer=null,this.mdnsServerAdvertiserPointer=null;const e={identity:t.identity,transportConfig:new TransportConfig,ditto:t,isWebValid:!1,isX509Valid:!1,isSyncActive:!1};this.ditto=t,this.parameters=e,this.state=stateFrom(e)}update(t){this.parameters={...t};const e=this.state,n=stateFrom(this.parameters);this.updatePeerToPeerBluetoothLE(e,n),this.updatePeerToPeerAWDL(e,n),this.updatePeerToPeerLAN(e,n),this.updateListenTCP(e,n),this.updateListenHTTP(e,n),this.updateConnectTCPServers(e,n),this.updateConnectWebsocketURLs(e,n),this.updateGlobal(e,n),this.updateConnectRetryInterval(e,n),this.state=n}close(){if(this.parameters.isSyncActive)throw new Error("Internal inconsistency, can't close sync object while sync is active, please 'stopSync()' first.")}updatePeerToPeerBluetoothLE(t,e){const n=this.ditto,r=Bridge.ditto.handleFor(n);n.deferClose((()=>{const n=t.effectiveTransportConfig.peerToPeer.bluetoothLE,i=e.effectiveTransportConfig.peerToPeer.bluetoothLE,o=!n.isEnabled&&i.isEnabled,a=n.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.");o&&(this.bluetoothLETransportPointer=function bleCreate(t){throw new Error("Can't create BluetoothLE handle, P2P BluetoothLE is not supported on this platform.")}(r.deref())),a&&(!function 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=this.ditto,r=Bridge.ditto.handleFor(n);n.deferClose((()=>{const n=t.effectiveTransportConfig.peerToPeer.awdl,i=e.effectiveTransportConfig.peerToPeer.awdl,o=!n.isEnabled&&i.isEnabled,a=n.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.");o&&(this.awdlTransportPointer=function awdlCreate(t){throw new Error("Can't create AWDL handle, P2P AWDL transport is not supported on this platform.")}(r.deref())),a&&(!function 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=this.ditto,r=Bridge.ditto.handleFor(n);n.deferClose((()=>{const n=t.effectiveTransportConfig.peerToPeer.lan,i=e.effectiveTransportConfig.peerToPeer.lan;n.isEnabled&&(n.isMdnsEnabled&&(!function lanDestroy(t){throw new Error("Can't destroy LAN handle, P2P LAN transport is not supported on this platform.")}(this.lanTransportPointer),delete this.lanTransportPointer),n.isMulticastEnabled&&function dittoRemoveMulticastTransport(t){return ensureInitialized(),(void 0)(t)}(r.deref())),i.isEnabled&&(i.isMdnsEnabled&&(this.lanTransportPointer=function lanCreate(t){throw new Error("Can't create LAN handle, P2P LAN transport is not supported on this platform.")}(r.deref())),i.isMulticastEnabled&&function dittoAddMulticastTransport(t){return ensureInitialized(),(void 0)(t)}(r.deref()))}))}updateListenTCP(t,e){const n=this.ditto,r=Bridge.ditto.handleFor(n);n.deferClose((()=>{const n=t.effectiveTransportConfig.listen.tcp,i=e.effectiveTransportConfig.listen.tcp;TransportConfig.areListenTCPsEqual(i,n)||(n.isEnabled&&function dittoStopTCPServer(t){return ensureInitialized(),(void 0)(t)}(r.deref()),i.isEnabled&&function dittoStartTCPServer(t,e){return ensureInitialized(),(void 0)(t,bytesFromString(e))}(r.deref(),`${i.interfaceIP}:${i.port}`))}))}updateListenHTTP(t,e){const n=this.ditto,r=Bridge.ditto.handleFor(n);n.deferClose((()=>{const n=t.effectiveTransportConfig.listen.http,i=e.effectiveTransportConfig.listen.http;TransportConfig.areListenHTTPsEqual(n,i)||(n.isEnabled&&function dittoStopHTTPServer(t){return ensureInitialized(),(void 0)(t)}(r.deref()),i.isEnabled&&function dittoStartHTTPServer(t,e,n,r,i,o){return ensureInitialized(),(void 0)(t,bytesFromString(e),bytesFromString(n),r,bytesFromString(i),bytesFromString(o))}(r.deref(),`${i.interfaceIP}:${i.port}`,i.staticContentPath||null,i.websocketSync?"Enabled":"Disabled",i.tlsCertificatePath||null,i.tlsKeyPath||null))}))}updateConnectTCPServers(t,e){const n=this.ditto,r=Bridge.ditto.handleFor(n);n.deferClose((()=>{const t=e.effectiveTransportConfig.connect.tcpServers;!function dittoSetStaticTCPClients(t,e){if(ensureInitialized(),e.length>0)throw new Error(`Web variant of Ditto does not support connecting to TCP servers: ${e.join(", ")}`)}(r.deref(),t)}))}updateConnectWebsocketURLs(t,e){const n=this.ditto,r=Bridge.ditto.handleFor(n);n.deferClose((()=>{const t=e.effectiveTransportConfig.connect.websocketURLs,n=e.effectiveTransportConfig.global.routingHint;dittoSetStaticWebsocketClients(r.deref(),t,n)}))}updateGlobal(t,e){const n=this.ditto,r=Bridge.ditto.handleFor(n);n.deferClose((()=>{t.effectiveTransportConfig.global.syncGroup!==e.effectiveTransportConfig.global.syncGroup&&dittoSetSyncGroup(r.deref(),e.effectiveTransportConfig.global.syncGroup)}))}updateConnectRetryInterval(t,e){const n=this.ditto,r=Bridge.ditto.handleFor(n);n.deferClose((()=>{dittoSetConnectRetryInterval(r.deref(),e.effectiveTransportConfig.connect.retryInterval)}))}}function stateFrom(t){const e=t.ditto,n=Bridge.ditto.handleFor(e);return e.deferClose((()=>{var e;const r=t.transportConfig.copy(),i=t.identity,o=t.isSyncActive,a=t.isX509Valid,s=t.isWebValid;let c,d;r.connect.tcpServers,r.connect.websocketURLs;let l=!1;"onlinePlayground"!==i.type&&"onlineWithAuthentication"!==i.type||(c=i.appID,d=null!==(e=i.customDittoCloudURL)&&void 0!==e?e:null,l=!i.hasOwnProperty("enableDittoCloudSync")||i.enableDittoCloudSync);const u=[],_=(n.deref(),!1),g=(n.deref(),!1),h=(n.deref(),!1);if(r.peerToPeer.bluetoothLE.isEnabled&&!_&&u.push("BluetoothLE"),r.peerToPeer.awdl.isEnabled&&!g&&u.push("AWDL"),r.peerToPeer.lan.isEnabled&&!h&&u.push("LAN"),u.length>0)throw new Error(`The following P2P transports are enabled in the transport config but are not supported in the current environment: ${u.join(", ")}`);if(o&&a||(r.peerToPeer.bluetoothLE.isEnabled=!1,r.peerToPeer.awdl.isEnabled=!1,r.peerToPeer.lan.isEnabled=!1,r.listen.tcp.isEnabled=!1,r.connect.tcpServers=[]),o&&s||(r.connect.websocketURLs=[]),o||(r.listen.http.isEnabled=!1),o&&s&&l){const t=null!=d?d:function defaultDittoCloudURL(t){return`wss://${t}.${k}`}(c);r.connect.websocketURLs.push(t)}return{underlyingSyncParameters:t,effectiveTransportConfig:r.freeze()}}))}class SubscriptionManager{constructor(t){this.ditto=t,this.subscriptions={},this.finalizationRegistry=new FinalizationRegistry(this.removeWithContextInfo.bind(this))}add(t){const e=this.ditto,n=Bridge.ditto.handleFor(e),r=t.contextInfo;e.deferClose((async()=>{this.subscriptions[r.id]=new WeakRef(t),this.finalizationRegistry.register(t,t.contextInfo,t),addSubscription(n.deref(),r.collectionName,r.query,r.queryArgsCBOR,r.orderBys,r.limit,r.offset)}))}remove(t){if(null==this.subscriptions[t.contextInfo.id])throw new Error(`Internal inconsistency, tried to remove a subscription that is not tracked: ${t.contextInfo.id}`);this.finalizationRegistry.unregister(t),this.removeWithContextInfo(t.contextInfo)}close(){this.ditto.deferClose((async()=>{for(const t in this.subscriptions){const e=this.subscriptions[t].deref();null!=e&&this.remove(e)}}))}removeWithContextInfo(t){const e=this.ditto,n=Bridge.ditto.handleFor(e);e.deferClose((()=>{delete this.subscriptions[t.id],removeSubscription(n.deref(),t.collectionName,t.query,t.queryArgsCBOR,t.orderBys,t.limit,t.offset)}))}}class AttachmentFetcher{stop(){step((async()=>{await this.manager.stopAttachmentFetcher(this),null!=this.rejectPendingFetch&&this.rejectPendingFetch()}))}then(t,e){return this.attachment.then(t,e)}constructor(t,e,n,r){this.cancelTokenPromise=null,this.rejectPendingFetch=null,this.ditto=t,this.token=e,this.manager=n,this.id=generateEphemeralToken();const i=r||function(){},o=Bridge.ditto.handleFor(t);this.attachment=new Promise(((t,n)=>{this.rejectPendingFetch=()=>{n(new Error("Attachment fetch was canceled"))},this.cancelTokenPromise=dittoResolveAttachment(o.deref(),e.id,{onComplete:e=>{const n=new Attachment(this.ditto,this.token);Bridge.attachment.bridge(e,(()=>n)),i({type:"Completed",attachment:n}),this.rejectPendingFetch=null,t(n)},onProgress:(t,e)=>{i({type:"Progress",totalBytes:e,downloadedBytes:t})},onDelete:()=>{i({type:"Deleted"}),this.rejectPendingFetch=null,t(null)}},(()=>{}))}))}}class AttachmentFetcherManager{constructor(t){this.contextInfoByID={},this.finalizationRegistry=new FinalizationRegistry(this.stopWithContextInfo),this.ditto=t}startAttachmentFetcher(t,e){return this.ditto.deferClose((()=>{const n=new AttachmentFetcher(this.ditto,t,this,e),r={id:n.id,attachmentTokenID:t.id,cancelTokenPromise:n.cancelTokenPromise,attachmentFetcher:new WeakRef(n)};this.finalizationRegistry.register(n,r,n),this.contextInfoByID[n.id]=r;const resetCancelToken=()=>{null!=this.contextInfoByID[n.id]&&(this.contextInfoByID[n.id].cancelTokenPromise=null)};return n.attachment.then((t=>(resetCancelToken(),t)),(t=>(resetCancelToken(),t))),this.ditto.keepAlive.retain(`AttachmentFetcher.${n.id})`),n}))}async stopAttachmentFetcher(t){this.finalizationRegistry.unregister(t);const e=this.contextInfoByID[t.id];if(null==e)throw new Error(`Internal inconsistency: cannot stop attachment fetcher ${t.id}, which is not registered.`);await this.stopWithContextInfo(e)}close(){this.ditto.deferCloseAsync((async()=>{const t=Object.values(this.contextInfoByID).map((async t=>{const e=t.attachmentFetcher.deref();null!=e&&await this.stopAttachmentFetcher(e)}));await Promise.all(t)}))}stopWithContextInfo(t){const e=Bridge.ditto.handleFor(this.ditto);return this.ditto.deferCloseAsync((async()=>{if(null==this.contextInfoByID[t.id])throw new Error(`Internal inconsistency: attachment fetcher ${t.id} not found in active attachment fetchers.`);delete this.contextInfoByID[t.id],this.ditto.keepAlive.release(`AttachmentFetcher.${t.id})`);const n=await t.cancelTokenPromise;n&&dittoCancelResolveAttachment(e.deref(),t.attachmentTokenID,n)}))}}class Ditto{get sdkVersion(){const t=Bridge.ditto.handleFor(this);return this.deferClose((()=>dittoGetSDKVersion(t.deref())))}constructor(t,e){if(this.isClosed=!1,this.deferCloseAllowed=!0,this.isWebValid=!1,this.isX509Valid=!1,this.pendingOperations=new Set,!Ditto.isEnvironmentSupported())throw new Error("Ditto does not support this JavaScript environment. Please consult the Ditto JavaScript documentation for a list of supported environments and browsers. You can use `Ditto.isEnvironmentSupported()` to run this check anytime.");const n=null!=t?t:{type:"offlinePlayground",appID:""},r=e&&e.trim().length>0?e:"ditto",i=Object.freeze(this.validateIdentity(n));this.identity=Object.freeze(i),this.path=r,this.deviceName=navigator.userAgent,this.keepAlive=new KeepAlive;const o=uninitializedDittoMake(r);let a=null;const s=new WeakRef(this),c=dittoMake(o,(()=>{var t,e,n;if("offlinePlayground"===i.type)return dittoIdentityConfigMakeOfflinePlayground(i.appID,null!==(t=i.siteID)&&void 0!==t?t:0);if("manual"===i.type)return dittoIdentityConfigMakeManual(i.certificate);if("sharedKey"===i.type)return dittoIdentityConfigMakeSharedKey(i.appID,i.sharedKey,i.siteID);if("onlinePlayground"===i.type){const t=null!==(e=i.customAuthURL)&&void 0!==e?e:defaultAuthURL(i.appID);return dittoIdentityConfigMakeOnlinePlayground(i.appID,i.token,t)}if("onlineWithAuthentication"===i.type){const t=null!==(n=i.customAuthURL)&&void 0!==n?n:defaultAuthURL(i.appID);return dittoIdentityConfigMakeOnlineWithAuthentication(i.appID,t)}throw new Error(`Can't create Ditto, unsupported identity type: ${i}`)})());dittoAuthClientSetValidityListener(c,(function(...t){const e=s.deref();null==e||e.isClosed?Logger.info("Ditto is closed, ignoring auth client validity change"):e.authClientValidityChanged(...t)}));const d=dittoAuthClientIsWebValid(c),l=dittoAuthClientIsX509Valid(c),u=dittoAuthClientGetSiteID(c);if(Bridge.ditto.bridge(c,this),"onlineWithAuthentication"===i.type){this.auth=new OnlineAuthenticator(this.keepAlive,this,i.authHandler);dittoAuthSetLoginProvider(c,dittoAuthClientMakeLoginProvider((function(t){const e=s.deref();e?e.auth?e.auth["@ditto.authenticationExpiring"](t):a=t:Logger.warning("Internal inconsistency, LoginProvider callback fired after the corresponding Ditto instance has been deallocated.")})))}else"onlinePlayground"===i.type?this.auth=new OnlineAuthenticator(this.keepAlive,this,{authenticationRequired:function(t){},authenticationExpiringSoon:function(t,e){}}):this.auth=new NotAvailableAuthenticator(this.keepAlive);const _=this.makeDefaultTransportConfig();this.siteID=u,this.transportConfig=_.copy().freeze(),this.isX509Valid=l,this.isWebValid=d,this.sync=new Sync(this),this.sync.update({isSyncActive:!1,isX509Valid:l,isWebValid:d,identity:i,ditto:this,transportConfig:_}),this.isActivated=true,this.store=new Store(this),this.presence=new Presence(this),this.presenceManager=new PresenceManager(this),this.liveQueryManager=new LiveQueryManager(this,this.keepAlive),this.attachmentFetcherManager=new AttachmentFetcherManager(this),this.transportConditionsManager=new TransportConditionsManager(this),this.subscriptionManager=new SubscriptionManager(this),null!==a&&this.auth["@ditto.authenticationExpiring"](a)}static disableDeadlockDetection(){}static hasDeadlockDetection(){return!1}static isEnvironmentSupported(){const t="undefined"!=typeof window&&(-1!==window.navigator.userAgent.indexOf("MSIE")||window.navigator.appVersion.indexOf("Trident/")>-1);let e;try{e=checkAPIs()}catch(t){throw new Error(`Error checking environment support: ${t}`)}return!t&&e}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,ditto:this})}updateTransportConfig(t){const e=this.transportConfig.copy();return t(e),this.setTransportConfig(e),this}startSync(){this.setSyncActive(!0)}stopSync(){this.setSyncActive(!1)}observePeers(t){Logger.warning("`ditto.observePeers()` is deprecated, please use `ditto.presence.observe()` instead.");const e=this.presenceManager.addObserver(t);return new Observer(this.presenceManager,e,{stopsWhenFinalized:!0})}observeTransportConditions(t){const e=this.transportConditionsManager.addObserver(t);return new Observer(this.transportConditionsManager,e,{stopsWhenFinalized:!0})}runGarbageCollection(){const t=Bridge.ditto.handleFor(this);return this.deferClose((()=>{dittoRunGarbageCollection(t.deref())}))}disableSyncWithV3(){const t=Bridge.ditto.handleFor(this);return this.deferClose((()=>{dittoDisableSyncWithV3(t.deref())}))}async close(){if(this.isClosed)return;if(this.isClosed=!0,this.stopSync(),this.store.close(),this.presence.close(),this.auth.close(),this.sync.close(),this.presenceManager.close(),this.liveQueryManager.close(),this.attachmentFetcherManager.close(),this.transportConditionsManager.close(),this.subscriptionManager.close(),this.keepAlive.isActive)throw new Error("Internal inconsistency, still kept alive after the Ditto object has been close()-ed. ");do{await Promise.allSettled(this.pendingOperations)}while(this.pendingOperations.size>0);this.deferCloseAllowed=!1;const t=Bridge.ditto.handleFor(this);await dittoShutdown(t.deref()),Bridge.ditto.markAsClosed(this)}get numPendingOperations(){return this.pendingOperations.size}deferClose(t){if(!this.deferCloseAllowed)throw new Error("Can't perform operation using a Ditto instance that has been closed.");return t()}async deferCloseAsync(t){if(!this.deferCloseAllowed)throw new Error("Can't perform operation using a Ditto instance that has been closed.");const e=t();let n;this.pendingOperations.add(e);try{n=await e}finally{this.pendingOperations.delete(e)}return n}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,ditto:this})}validateIdentity(t){const e={...t};t.appName;const n=t.appID;if(!["offlinePlayground","sharedKey","manual","onlinePlayground","onlineWithAuthentication"].includes(t.type))throw new Error(`Can't create Ditto instance, unknown identity type: ${t.type}`);if(("offlinePlayground"===t.type||"sharedKey"===t.type||"onlinePlayground"===t.type||"onlineWithAuthentication"===t.type)&&void 0===n)throw new Error("Property .appID must be given for identity, but isn't.");if(void 0!==n&&"string"!=typeof n)throw new Error(`Property .appID must be be of type string, but is of type '${typeof n}': ${n}`);if(("offlinePlayground"===t.type||"sharedKey"===t.type)&&void 0!==t.siteID){const e=t.siteID;if(!("number"==typeof e||"bigint"==typeof e))throw new Error("Can't create Ditto instance, siteID must be a number or BigInt");if(e<0)throw new Error("Can't create Ditto instance, siteID must be >= 0");if(e>BigInt("0xffffffffffffffff"))throw new Error("Can't create Ditto instance, siteID must be < 2^64")}if(t.type,t.type,"onlinePlayground"===t.type){const e=t.token;if(void 0===e)throw new Error("Property .token must be given for identity but isn't. You can find the corresponding token on the Ditto Portal.");if(void 0!==e&&"string"!=typeof e)throw new Error(`Property .token of identity must be be of type string, but is of type '${typeof e}': ${e}`)}return t.type,e}setSyncActive(t){const e=Bridge.ditto.handleFor(this);this.deferClose((()=>{if(t&&F.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"),this.isSyncActive=t;const n=this.isWebValid,r=this.isX509Valid,i=this.identity,o=this.transportConfig;dittoSetDeviceName(e.deref(),this.deviceName),this.sync.update({identity:i,transportConfig:o,isWebValid:n,isX509Valid:r,isSyncActive:!!t,ditto:this})}))}makeDefaultTransportConfig(){const t=Bridge.ditto.handleFor(this);return this.deferClose((()=>{const e=new TransportConfig;return t.deref(),t.deref(),t.deref(),e.freeze()}))}}const checkAPIs=t=>{const e=t||globalThis||global||window;return["BigInt","WeakRef","FinalizationRegistry"].every((t=>!!e[t]))};Bridge.attachment.registerType(Attachment),Bridge.document.registerType(Document),Bridge.mutableDocument.registerType(MutableDocument),Bridge.staticTCPClient.registerType(class StaticTCPClient{}),Bridge.websocketClient.registerType(class WebsocketClient{}),Bridge.ditto.registerType(Ditto),t.Attachment=Attachment,t.AttachmentFetcher=AttachmentFetcher,t.AttachmentToken=AttachmentToken,t.Authenticator=Authenticator,t.BasePendingCursorOperation=BasePendingCursorOperation,t.BasePendingIDSpecificOperation=BasePendingIDSpecificOperation,t.CBOR=CBOR,t.Collection=Collection,t.CollectionsEvent=CollectionsEvent,t.Counter=Counter,t.Ditto=Ditto,t.Document=Document,t.DocumentID=DocumentID,t.DocumentPath=DocumentPath,t.ExperimentalStore=ExperimentalStore,t.ExperimentalSubscription=ExperimentalSubscription,t.ExperimentalSubscriptionManager=ExperimentalSubscriptionManager,t.IdentityTypesRequiringOfflineLicenseToken=F,t.KeepAlive=KeepAlive,t.LiveQuery=LiveQuery,t.LiveQueryEventInitial=LiveQueryEventInitial,t.LiveQueryEventUpdate=LiveQueryEventUpdate,t.Logger=Logger,t.MutableCounter=MutableCounter,t.MutableDocument=MutableDocument,t.MutableDocumentPath=MutableDocumentPath,t.MutableRegister=MutableRegister,t.NotAvailableAuthenticator=NotAvailableAuthenticator,t.Observer=Observer,t.OnlineAuthenticator=OnlineAuthenticator,t.PendingCollectionsOperation=PendingCollectionsOperation,t.PendingCursorOperation=PendingCursorOperation,t.PendingIDSpecificOperation=PendingIDSpecificOperation,t.Presence=Presence,t.Register=Register,t.SingleDocumentLiveQueryEvent=SingleDocumentLiveQueryEvent,t.Store=Store,t.Subscription=Subscription,t.TransportConfig=TransportConfig,t.UpdateResult=UpdateResult,t.UpdateResultsMap=UpdateResultsMap,t.Value=class Value{constructor(t,e={}){this.value=t,this.isDefault=!!e.isDefault}},t.WriteTransaction=WriteTransaction,t.WriteTransactionCollection=WriteTransactionCollection,t.WriteTransactionPendingCursorOperation=WriteTransactionPendingCursorOperation,t.WriteTransactionPendingIDSpecificOperation=WriteTransactionPendingIDSpecificOperation,t.addressToString=function addressToString(t){return`${t.siteId}-${t.pubkey}`},t.checkAPIs=checkAPIs,t.disableDeadlockTimeoutWhenDebugging=()=>{},t.getBridgeLoad=function getBridgeLoad(){const t={};return Bridge.all.map((e=>{const n=e.deref();return n?0===n.count?null:void(t[n.type.name]=n.count):null})),t},t.init=async function init(t={}){if(!w){{const e=t.webAssemblyModule||"https://software.ditto.live/js/Ditto/4.2.2/ditto.wasm";await init$2(e),await async function init$1(){}(),initSDKVersion("Web","JavaScript","4.2.2"),loggerInit()}w=!0}},t.validateDocumentIDCBOR=validateDocumentIDCBOR,t.validateDocumentIDValue=function validateDocumentIDValue(t){if(void 0===t)throw new Error(`Invalid document ID: ${t}`);return t}}));
|
|
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 KeepAlive{get isActive(){return null!==this.intervalID}constructor(){this.countsByID={},this.intervalID=null}retain(t){if(void 0===this.countsByID[t]&&(this.countsByID[t]=0),this.countsByID[t]+=1,null===this.intervalID){const t=2147483647;this.intervalID=setInterval((()=>{}),t),KeepAlive.finalizationRegistry.register(this,this.intervalID,this)}}release(t){if(void 0===this.countsByID[t])throw new Error(`Internal inconsistency, trying to release a keep-alive ID that hasn't been retained before or isn't tracked anymore: ${t}`);this.countsByID[t]-=1,0===this.countsByID[t]&&delete this.countsByID[t],0===Object.keys(this.countsByID).length&&(KeepAlive.finalizationRegistry.unregister(this),clearInterval(this.intervalID),this.intervalID=null)}currentIDs(){return Object.keys(this.countsByID)}countForID(t){var e;return null!==(e=this.countsByID[t])&&void 0!==e?e:null}}KeepAlive.finalizationRegistry=new FinalizationRegistry(clearInterval);class 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 this.observerManager.hasObserver(this.token)}stop(){const t=this.token;t&&(delete this.token,Observer.finalizationRegistry.unregister(this),this.observerManager.removeObserver(t))}static finalize(t){const{observerManager:e,token:n}=t;e.removeObserver(n)}}Observer.finalizationRegistry=new FinalizationRegistry(Observer.finalize);const e="@ditto.64d129224a5377b63e9727479ec987d9";class Counter{constructor(){this.value=0}static"@ditto.create"(t,n,r){const i=t?new MutableCounter(e):new Counter;return i.mutDoc=t,i.path=n,i.value=r,i}}class MutableCounter extends Counter{increment(t){const e=this.mutDoc,n=this.path;if(!e)throw new Error("Can't increment counter, only possible within the closure of a collection's update() method.");e.at(n)["@ditto.increment"](t),this.value+=t}constructor(){if(arguments[0]!==e)throw new Error("MutableCounter constructor is for internal use only.");super()}}const n="@ditto.ff82dae89821c5ab822a8b539056bce4";class Register{get value(){return this["@ditto.value"]}constructor(t){this["@ditto.value"]=t}static"@ditto.create"(t,e,r){const i=t?new MutableRegister(r,n):new Register(r);return i["@ditto.mutableDocument"]=t,i["@ditto.path"]=e,i["@ditto.value"]=r,i}}class MutableRegister extends Register{get value(){return super.value}set value(t){this.set(t)}set(t){const e=this["@ditto.mutableDocument"],n=this["@ditto.path"];e.at(n)["@ditto.set"](t),this["@ditto.value"]=t}constructor(t){if(arguments[1]!==n)throw new Error("MutableRegister constructor is for internal use only.");super(t)}}let r;const i=new Array(32).fill(void 0);function getObject(t){return i[t]}i.push(void 0,null,!0,!1);let o=i.length;function takeObject(t){const e=getObject(t);return function dropObject(t){t<36||(i[t]=o,o=t)}(t),e}const a=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});a.decode();let s=new Uint8Array;function getUint8Memory0(){return 0===s.byteLength&&(s=new Uint8Array(r.memory.buffer)),s}function getStringFromWasm0(t,e){return a.decode(getUint8Memory0().subarray(t,t+e))}function addHeapObject(t){o===i.length&&i.push(i.length+1);const e=o;return o=i[e],i[e]=t,e}let c=0;const d=new TextEncoder("utf-8"),l="function"==typeof d.encodeInto?function(t,e){return d.encodeInto(t,e)}:function(t,e){const n=d.encode(t);return e.set(n),{read:t.length,written:n.length}};function passStringToWasm0(t,e,n){if(void 0===n){const n=d.encode(t),r=e(n.length);return getUint8Memory0().subarray(r,r+n.length).set(n),c=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+=l(t,e).written}return c=a,i}let u=new Int32Array;function getInt32Memory0(){return 0===u.byteLength&&(u=new Int32Array(r.memory.buffer)),u}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 _=new FinalizationRegistry((t=>{r.__wbindgen_export_2.get(t.dtor)(t.a,t.b)}));function makeMutClosure(t,e,n,i){const o={a:t,b:e,cnt:1,dtor:n},real=(...t)=>{o.cnt++;const e=o.a;o.a=0;try{return i(e,o.b,...t)}finally{0==--o.cnt?(r.__wbindgen_export_2.get(o.dtor)(e,o.b),_.unregister(o)):o.a=e}};return real.original=o,_.register(real,o,o),real}function __wbg_adapter_32(t,e,n){r._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__hd60745c96665bcb1(t,e,addHeapObject(n))}function __wbg_adapter_35(t,e){r._dyn_core__ops__function__FnMut_____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__he2527435e40d0841(t,e)}function __wbg_adapter_38(t,e,n){r._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__h163f568f0824965e(t,e,addHeapObject(n))}function __wbg_adapter_41(t,e){r._dyn_core__ops__function__FnMut_____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__hb27b6c99590413c8(t,e)}function __wbg_adapter_44(t,e,n){r._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__ha51957e1d4b3feff(t,e,addHeapObject(n))}function ditto_logger_set_custom_log_cb(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_logger_set_custom_log_cb(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}function ditto_register_transport_condition_changed_callback(t,e){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_register_transport_condition_changed_callback(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}function handleError(t,e){try{return t.apply(this,e)}catch(t){r.__wbindgen_exn_store(addHeapObject(t))}}function notDefined(t){return()=>{throw new Error(`${t} is not defined`)}}function getArrayU8FromWasm0(t,e){return getUint8Memory0().subarray(t/1,t/1+e)}function boxCStringIntoString(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.boxCStringIntoString(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}function refCStringToString(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.refCStringToString(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}function boxCBytesIntoBuffer(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.boxCBytesIntoBuffer(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}function withOutPtr$1(t,e){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.withOutPtr(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}function getImports(){const t={wbg:{}};return t.wbg.__wbindgen_object_drop_ref=function(t){takeObject(t)},t.wbg.__wbindgen_string_new=function(t,e){return addHeapObject(getStringFromWasm0(t,e))},t.wbg.__wbg_log_c6f7064ce12c2dfa=function(t,e){try{console.log(getStringFromWasm0(t,e))}finally{r.__wbindgen_free(t,e)}},t.wbg.__wbindgen_cb_drop=function(t){const e=takeObject(t).original;if(1==e.cnt--)return e.a=0,!0;return!1},t.wbg.__wbg_new_abda76e883ba8a5f=function(){return addHeapObject(new Error)},t.wbg.__wbg_stack_658279fe44541cf6=function(t,e){const n=passStringToWasm0(getObject(e).stack,r.__wbindgen_malloc,r.__wbindgen_realloc),i=c;getInt32Memory0()[t/4+1]=i,getInt32Memory0()[t/4+0]=n},t.wbg.__wbg_error_f851667af71bcfc6=function(t,e){try{console.error(getStringFromWasm0(t,e))}finally{r.__wbindgen_free(t,e)}},t.wbg.__wbindgen_is_string=function(t){return"string"==typeof getObject(t)},t.wbg.__wbindgen_string_get=function(t,e){const n=getObject(e),i="string"==typeof n?n:void 0;var o=function isLikeNone(t){return null==t}(i)?0:passStringToWasm0(i,r.__wbindgen_malloc,r.__wbindgen_realloc),a=c;getInt32Memory0()[t/4+1]=a,getInt32Memory0()[t/4+0]=o},t.wbg.__wbindgen_object_clone_ref=function(t){return addHeapObject(getObject(t))},t.wbg.__wbg_fetch_3894579f6e2af3be=function(t){return addHeapObject(fetch(getObject(t)))},t.wbg.__wbg_clearTimeout_23ee6db72c0ad922="function"==typeof clearTimeout?clearTimeout:notDefined("clearTimeout"),t.wbg.__wbg_setTimeout_09074a1669d0f224=function(){return handleError((function(t,e){return setTimeout(getObject(t),e)}),arguments)},t.wbg.__wbg_clearInterval_d5655e407a861314="function"==typeof clearInterval?clearInterval:notDefined("clearInterval"),t.wbg.__wbg_setInterval_fa82463ae3f43f48=function(){return handleError((function(t,e){return setInterval(getObject(t),e)}),arguments)},t.wbg.__wbg_crypto_e1d53a1d73fb10b8=function(t){return addHeapObject(getObject(t).crypto)},t.wbg.__wbindgen_is_object=function(t){const e=getObject(t);return"object"==typeof e&&null!==e},t.wbg.__wbg_process_038c26bf42b093f8=function(t){return addHeapObject(getObject(t).process)},t.wbg.__wbg_versions_ab37218d2f0b24a8=function(t){return addHeapObject(getObject(t).versions)},t.wbg.__wbg_node_080f4b19d15bc1fe=function(t){return addHeapObject(getObject(t).node)},t.wbg.__wbg_msCrypto_6e7d3e1f92610cbb=function(t){return addHeapObject(getObject(t).msCrypto)},t.wbg.__wbg_require_78a3dcfbdba9cbce=function(){return handleError((function(){return addHeapObject(module.require)}),arguments)},t.wbg.__wbindgen_is_function=function(t){return"function"==typeof getObject(t)},t.wbg.__wbg_getRandomValues_805f1c3d65988a5a=function(){return handleError((function(t,e){getObject(t).getRandomValues(getObject(e))}),arguments)},t.wbg.__wbg_randomFillSync_6894564c2c334c42=function(){return handleError((function(t,e,n){getObject(t).randomFillSync(getArrayU8FromWasm0(e,n))}),arguments)},t.wbg.__wbindgen_number_new=function(t){return addHeapObject(t)},t.wbg.__wbg_mksendret_91eb8c5592210ee0=function(){return addHeapObject((function send_ret(t){return t}))},t.wbg.__wbindgen_error_new=function(t,e){return addHeapObject(new Error(getStringFromWasm0(t,e)))},t.wbg.__wbg_trydownsize_28e49b8073c2a2fc=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)))},t.wbg.__wbg_isnumber_c97122a46d4ace09=function(t){return function is_number(t){return"number"==typeof t}(getObject(t))},t.wbg.__wbg_tostring_7847f1b7af649ba5=function(t,e){const n=passStringToWasm0(function to_string(t){return t.toString()}(getObject(e)),r.__wbindgen_malloc,r.__wbindgen_realloc),i=c;getInt32Memory0()[t/4+1]=i,getInt32Memory0()[t/4+0]=n},t.wbg.__wbg_fromstring_721719aff319c1fe=function(t,e){return addHeapObject(function from_string(t){return BigInt(t)}(getStringFromWasm0(t,e)))},t.wbg.__wbg_typeof_cb5c1bc26a697ea8=function(t,e){const n=passStringToWasm0(function typeof_(t){return typeof t}(getObject(e)),r.__wbindgen_malloc,r.__wbindgen_realloc),i=c;getInt32Memory0()[t/4+1]=i,getInt32Memory0()[t/4+0]=n},t.wbg.__wbindgen_is_null=function(t){return null===getObject(t)},t.wbg.__wbindgen_is_undefined=function(t){return void 0===getObject(t)},t.wbg.__wbg_getelement_cd48f1e89008c242=function(t,e){return addHeapObject(function get_element(t,e){return t[e]}(getObject(t),e>>>0))},t.wbg.__wbg_instanceof_Blob_d18d26355bccfd22=function(t){let e;try{e=getObject(t)instanceof Blob}catch{e=!1}return e},t.wbg.__wbg_instanceof_Response_eaa426220848a39e=function(t){let e;try{e=getObject(t)instanceof Response}catch{e=!1}return e},t.wbg.__wbg_url_74285ddf2747cb3d=function(t,e){const n=passStringToWasm0(getObject(e).url,r.__wbindgen_malloc,r.__wbindgen_realloc),i=c;getInt32Memory0()[t/4+1]=i,getInt32Memory0()[t/4+0]=n},t.wbg.__wbg_status_c4ef3dd591e63435=function(t){return getObject(t).status},t.wbg.__wbg_headers_fd64ad685cf22e5d=function(t){return addHeapObject(getObject(t).headers)},t.wbg.__wbg_arrayBuffer_4c27b6f00c530232=function(){return handleError((function(t){return addHeapObject(getObject(t).arrayBuffer())}),arguments)},t.wbg.__wbg_url_1f1b597f64482fd0=function(t,e){const n=passStringToWasm0(getObject(e).url,r.__wbindgen_malloc,r.__wbindgen_realloc),i=c;getInt32Memory0()[t/4+1]=i,getInt32Memory0()[t/4+0]=n},t.wbg.__wbg_readyState_9c0f66433e329c9e=function(t){return getObject(t).readyState},t.wbg.__wbg_setonopen_9ce48dce57e549b5=function(t,e){getObject(t).onopen=getObject(e)},t.wbg.__wbg_setonerror_02393260b3e29972=function(t,e){getObject(t).onerror=getObject(e)},t.wbg.__wbg_setonclose_4ce49fd8fd7783fb=function(t,e){getObject(t).onclose=getObject(e)},t.wbg.__wbg_setonmessage_c5a806b62a0c5607=function(t,e){getObject(t).onmessage=getObject(e)},t.wbg.__wbg_setbinaryType_ee55743ddf4beb37=function(t,e){getObject(t).binaryType=takeObject(e)},t.wbg.__wbg_new_d29e507f6606de91=function(){return handleError((function(t,e){return addHeapObject(new WebSocket(getStringFromWasm0(t,e)))}),arguments)},t.wbg.__wbg_newwithstrsequence_7b0c4aadc1ae1635=function(){return handleError((function(t,e,n){return addHeapObject(new WebSocket(getStringFromWasm0(t,e),getObject(n)))}),arguments)},t.wbg.__wbg_close_45d053bea59e7746=function(){return handleError((function(t){getObject(t).close()}),arguments)},t.wbg.__wbg_send_80b256d87a6779e5=function(){return handleError((function(t,e,n){getObject(t).send(getStringFromWasm0(e,n))}),arguments)},t.wbg.__wbg_send_640853f8eb0f0385=function(){return handleError((function(t,e,n){getObject(t).send(getArrayU8FromWasm0(e,n))}),arguments)},t.wbg.__wbg_fetch_749a56934f95c96c=function(t,e){return addHeapObject(getObject(t).fetch(getObject(e)))},t.wbg.__wbg_code_b09504754e0520f1=function(t){return getObject(t).code},t.wbg.__wbg_new_2d0053ee81e4dd2a=function(){return handleError((function(){return addHeapObject(new Headers)}),arguments)},t.wbg.__wbg_append_de37df908812970d=function(){return handleError((function(t,e,n,r,i){getObject(t).append(getStringFromWasm0(e,n),getStringFromWasm0(r,i))}),arguments)},t.wbg.__wbg_now_8172cd917e5eda6b=function(t){return getObject(t).now()},t.wbg.__wbg_newwithstrandinit_05d7180788420c40=function(){return handleError((function(t,e,n){return addHeapObject(new Request(getStringFromWasm0(t,e),getObject(n)))}),arguments)},t.wbg.__wbg_wasClean_2af04e6cf2076497=function(t){return getObject(t).wasClean},t.wbg.__wbg_code_24e161f043adce8a=function(t){return getObject(t).code},t.wbg.__wbg_reason_40159cc3d2fc655d=function(t,e){const n=passStringToWasm0(getObject(e).reason,r.__wbindgen_malloc,r.__wbindgen_realloc),i=c;getInt32Memory0()[t/4+1]=i,getInt32Memory0()[t/4+0]=n},t.wbg.__wbg_data_7b1f01f4e6a64fbe=function(t){return addHeapObject(getObject(t).data)},t.wbg.__wbg_new_1d9a920c6bfc44a8=function(){return addHeapObject(new Array)},t.wbg.__wbg_valueOf_8404142eb850b917=function(t){return getObject(t).valueOf()},t.wbg.__wbg_newnoargs_b5b063fc6c2f0376=function(t,e){return addHeapObject(new Function(getStringFromWasm0(t,e)))},t.wbg.__wbg_next_579e583d33566a86=function(t){return addHeapObject(getObject(t).next)},t.wbg.__wbg_next_aaef7c8aa5e212ac=function(){return handleError((function(t){return addHeapObject(getObject(t).next())}),arguments)},t.wbg.__wbg_done_1b73b0672e15f234=function(t){return getObject(t).done},t.wbg.__wbg_value_1ccc36bc03462d71=function(t){return addHeapObject(getObject(t).value)},t.wbg.__wbg_iterator_6f9d4f28845f426c=function(){return addHeapObject(Symbol.iterator)},t.wbg.__wbg_get_765201544a2b6869=function(){return handleError((function(t,e){return addHeapObject(Reflect.get(getObject(t),getObject(e)))}),arguments)},t.wbg.__wbg_call_97ae9d8645dc388b=function(){return handleError((function(t,e){return addHeapObject(getObject(t).call(getObject(e)))}),arguments)},t.wbg.__wbg_new_0b9bfdd97583284e=function(){return addHeapObject(new Object)},t.wbg.__wbg_self_6d479506f72c6a71=function(){return handleError((function(){return addHeapObject(self.self)}),arguments)},t.wbg.__wbg_window_f2557cc78490aceb=function(){return handleError((function(){return addHeapObject(window.window)}),arguments)},t.wbg.__wbg_globalThis_7f206bda628d5286=function(){return handleError((function(){return addHeapObject(globalThis.globalThis)}),arguments)},t.wbg.__wbg_global_ba75c50d1cf384f4=function(){return handleError((function(){return addHeapObject(global.global)}),arguments)},t.wbg.__wbg_push_740e4b286702d964=function(t,e){return getObject(t).push(getObject(e))},t.wbg.__wbg_instanceof_ArrayBuffer_e5e48f4762c5610b=function(t){let e;try{e=getObject(t)instanceof ArrayBuffer}catch{e=!1}return e},t.wbg.__wbg_apply_22a3220d244124da=function(){return handleError((function(t,e,n){return addHeapObject(getObject(t).apply(getObject(e),getObject(n)))}),arguments)},t.wbg.__wbg_call_168da88779e35f61=function(){return handleError((function(t,e,n){return addHeapObject(getObject(t).call(getObject(e),getObject(n)))}),arguments)},t.wbg.__wbg_valueOf_6b6effad03e5c546=function(t){return getObject(t).valueOf()},t.wbg.__wbg_getTime_cb82adb2556ed13e=function(t){return getObject(t).getTime()},t.wbg.__wbg_new0_a57059d72c5b7aee=function(){return addHeapObject(new Date)},t.wbg.__wbg_now_58886682b7e790d7=function(){return Date.now()},t.wbg.__wbg_instanceof_Object_595a1007518cbea3=function(t){let e;try{e=getObject(t)instanceof Object}catch{e=!1}return e},t.wbg.__wbg_new_9962f939219f1820=function(t,e){try{var n={a:t,b:e};const i=new Promise(((t,e)=>{const i=n.a;n.a=0;try{return function __wbg_adapter_326(t,e,n,i){r.wasm_bindgen__convert__closures__invoke2_mut__h3a53fb951e2471c7(t,e,addHeapObject(n),addHeapObject(i))}(i,n.b,t,e)}finally{n.a=i}}));return addHeapObject(i)}finally{n.a=n.b=0}},t.wbg.__wbg_resolve_99fe17964f31ffc0=function(t){return addHeapObject(Promise.resolve(getObject(t)))},t.wbg.__wbg_then_11f7a54d67b4bfad=function(t,e){return addHeapObject(getObject(t).then(getObject(e)))},t.wbg.__wbg_then_cedad20fbbd9418a=function(t,e,n){return addHeapObject(getObject(t).then(getObject(e),getObject(n)))},t.wbg.__wbg_buffer_3f3d764d4747d564=function(t){return addHeapObject(getObject(t).buffer)},t.wbg.__wbg_newwithbyteoffsetandlength_d9aa266703cb98be=function(t,e,n){return addHeapObject(new Uint8Array(getObject(t),e>>>0,n>>>0))},t.wbg.__wbg_new_8c3f0052272a457a=function(t){return addHeapObject(new Uint8Array(getObject(t)))},t.wbg.__wbg_set_83db9690f9353e79=function(t,e,n){getObject(t).set(getObject(e),n>>>0)},t.wbg.__wbg_length_9e1ae1900cb0fbd5=function(t){return getObject(t).length},t.wbg.__wbg_instanceof_Uint8Array_971eeda69eb75003=function(t){let e;try{e=getObject(t)instanceof Uint8Array}catch{e=!1}return e},t.wbg.__wbg_newwithlength_f5933855e4f48a19=function(t){return addHeapObject(new Uint8Array(t>>>0))},t.wbg.__wbg_subarray_58ad4efbb5bcb886=function(t,e,n){return addHeapObject(getObject(t).subarray(e>>>0,n>>>0))},t.wbg.__wbg_has_8359f114ce042f5a=function(){return handleError((function(t,e){return Reflect.has(getObject(t),getObject(e))}),arguments)},t.wbg.__wbg_set_bf3f89b92d5a34bf=function(){return handleError((function(t,e,n){return Reflect.set(getObject(t),getObject(e),getObject(n))}),arguments)},t.wbg.__wbg_stringify_d6471d300ded9b68=function(){return handleError((function(t){return addHeapObject(JSON.stringify(getObject(t)))}),arguments)},t.wbg.__wbindgen_debug_string=function(t,e){const n=passStringToWasm0(debugString(getObject(e)),r.__wbindgen_malloc,r.__wbindgen_realloc),i=c;getInt32Memory0()[t/4+1]=i,getInt32Memory0()[t/4+0]=n},t.wbg.__wbindgen_throw=function(t,e){throw new Error(getStringFromWasm0(t,e))},t.wbg.__wbindgen_memory=function(){return addHeapObject(r.memory)},t.wbg.__wbindgen_closure_wrapper4586=function(t,e,n){return addHeapObject(makeMutClosure(t,e,1293,__wbg_adapter_32))},t.wbg.__wbindgen_closure_wrapper4588=function(t,e,n){return addHeapObject(makeMutClosure(t,e,1293,__wbg_adapter_35))},t.wbg.__wbindgen_closure_wrapper12044=function(t,e,n){return addHeapObject(makeMutClosure(t,e,3413,__wbg_adapter_38))},t.wbg.__wbindgen_closure_wrapper19641=function(t,e,n){return addHeapObject(makeMutClosure(t,e,5354,__wbg_adapter_41))},t.wbg.__wbindgen_closure_wrapper21041=function(t,e,n){return addHeapObject(makeMutClosure(t,e,5816,__wbg_adapter_44))},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=getImports();("string"==typeof t||"function"==typeof Request&&t instanceof Request||"function"==typeof URL&&t instanceof URL)&&(t=fetch(t));const{instance:n,module:i}=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 function finalizeInit(t,e){return r=t.exports,init$3.__wbindgen_wasm_module=e,u=new Int32Array,s=new Uint8Array,r}(n,i)}const g="_ditto_internal_type_jkb12973t4b",h="_value";var b;function documentSetCBORWithTimestamp(t,e,n,i){ensureInitialized();const o=function ditto_document_set_cbor_with_timestamp(t,e,n,i){try{const s=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_document_set_cbor_with_timestamp(s,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(i));var o=getInt32Memory0()[s/4+0],a=getInt32Memory0()[s/4+1];if(getInt32Memory0()[s/4+2])throw takeObject(a);return takeObject(o)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,bytesFromString(e),n,i);if(0!==o)throw new Error(errorMessage()||`ditto_document_set_cbor_with_timestamp() failed with error code: ${o}`)}function documentSetCBOR(t,e,n){ensureInitialized();const i=function ditto_document_set_cbor(t,e,n){try{const a=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_document_set_cbor(a,addHeapObject(t),addHeapObject(e),addHeapObject(n));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,bytesFromString(e),n);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){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_document_id(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t))}function documentGetCBORWithPathType(t,e,n){ensureInitialized();const i=function ditto_document_get_cbor_with_path_type(t,e,n){try{const a=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_document_get_cbor_with_path_type(a,addHeapObject(t),addHeapObject(e),addHeapObject(n));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,bytesFromString(e),n);return{statusCode:i.status_code,cbor:boxCBytesIntoBuffer(i.cbor)}}function documentRemove(t,e){ensureInitialized();const n=function ditto_document_remove(t,e){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_document_remove(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,bytesFromString(e));if(0!==n)throw new Error(errorMessage()||`ditto_document_remove() failed with error code: ${n}`)}function documentIncrementCounter(t,e,n){ensureInitialized();const i=function ditto_document_increment_counter(t,e,n){try{const a=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_document_increment_counter(a,addHeapObject(t),addHeapObject(e),addHeapObject(n));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,bytesFromString(e),n);if(0!==i)throw new Error(errorMessage()||`ditto_document_increment_counter() failed with error code: ${i}`)}function documentFree(t){ensureInitialized(),function ditto_document_free(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_document_free(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t)}function documentIDQueryCompatible(t,e){ensureInitialized();return boxCStringIntoString(function ditto_document_id_query_compatible(t,e){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_document_id_query_compatible(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,e))}function validateDocumentID(t){ensureInitialized();return boxCBytesIntoBuffer(function withOutBoxCBytes(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.withOutBoxCBytes(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}((e=>{const n=function ditto_validate_document_id(t,e){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_validate_document_id(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,e);if(0!==n)throw new Error(errorMessage()||`ditto_validate_document_id() failed with error code: ${n}`);return e})))}async function collectionGet(t,e,n,i){ensureInitialized();const o=bytesFromString(e),{status_code:a,document:s}=await function ditto_collection_get(t,e,n,i){try{const s=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_collection_get(s,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(i));var o=getInt32Memory0()[s/4+0],a=getInt32Memory0()[s/4+1];if(getInt32Memory0()[s/4+2])throw takeObject(a);return takeObject(o)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,o,n,i);if(a===y)return null;if(0!==a)throw new Error(errorMessage()||`ditto_collection_get() failed with error code: ${a}`);return s}async function collectionInsertValue(t,e,n,i,o){ensureInitialized();const a=bytesFromString(e);let s;switch(i){case"merge":s="Merge";break;case"insertIfAbsent":s="InsertIfAbsent";break;case"insertDefaultIfAbsent":s="InsertDefaultIfAbsent";break;default:throw new Error("Invalid write strategy provided")}const{status_code:c,id:d}=await function ditto_collection_insert_value(t,e,n,i,o,a){try{const d=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_collection_insert_value(d,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(i),addHeapObject(o),addHeapObject(a));var s=getInt32Memory0()[d/4+0],c=getInt32Memory0()[d/4+1];if(getInt32Memory0()[d/4+2])throw takeObject(c);return takeObject(s)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,a,n,s,null,null!=o?o: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,i){ensureInitialized();const o=bytesFromString(e),{status_code:a,bool_value:s}=await function ditto_collection_remove(t,e,n,i){try{const s=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_collection_remove(s,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(i));var o=getInt32Memory0()[s/4+0],a=getInt32Memory0()[s/4+1];if(getInt32Memory0()[s/4+2])throw takeObject(a);return takeObject(o)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,o,n,i);if(0!==a)throw new Error(errorMessage()||`ditto_collection_remove() failed with error code: ${a}`);return s}async function collectionEvict(t,e,n,i){ensureInitialized();const o=bytesFromString(e),{status_code:a,bool_value:s}=await function ditto_collection_evict(t,e,n,i){try{const s=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_collection_evict(s,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(i));var o=getInt32Memory0()[s/4+0],a=getInt32Memory0()[s/4+1];if(getInt32Memory0()[s/4+2])throw takeObject(a);return takeObject(o)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,o,n,i);if(0!==a)throw new Error(errorMessage()||`ditto_collection_evict() failed with error code: ${a}`);return s}async function collectionUpdate(t,e,n,i){ensureInitialized();const o=bytesFromString(e),a=await function ditto_collection_update(t,e,n,i){try{const s=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_collection_update(s,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(i));var o=getInt32Memory0()[s/4+0],a=getInt32Memory0()[s/4+1];if(getInt32Memory0()[s/4+2])throw takeObject(a);return takeObject(o)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,o,n,i);if(0!==a)throw new Error(errorMessage()||`ditto_collection_update() failed with error code: ${a}`)}async function collectionUpdateMultiple(t,e,n,i){ensureInitialized();const o=bytesFromString(e),a=function jsDocsToCDocs(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.jsDocsToCDocs(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(i),s=await function ditto_collection_update_multiple(t,e,n,i){try{const s=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_collection_update_multiple(s,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(i));var o=getInt32Memory0()[s/4+0],a=getInt32Memory0()[s/4+1];if(getInt32Memory0()[s/4+2])throw takeObject(a);return takeObject(o)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,o,n,a);if(0!==s)throw new Error(errorMessage()||`ditto_collection_update_multiple() failed with error code: ${s}`)}async function collectionExecQueryStr(t,e,n,i,o,a,s,c){ensureInitialized();const d=bytesFromString(e),l=bytesFromString(i);return await function ditto_collection_exec_query_str(t,e,n,i,o,a,s,c){try{const u=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_collection_exec_query_str(u,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(i),addHeapObject(o),addHeapObject(a),addHeapObject(s),addHeapObject(c));var d=getInt32Memory0()[u/4+0],l=getInt32Memory0()[u/4+1];if(getInt32Memory0()[u/4+2])throw takeObject(l);return takeObject(d)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,d,n,l,o,a,s,c)}async function collectionRemoveQueryStr(t,e,n,i,o,a,s,c){ensureInitialized();const d=bytesFromString(e),l=bytesFromString(i);return await function ditto_collection_remove_query_str(t,e,n,i,o,a,s,c){try{const u=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_collection_remove_query_str(u,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(i),addHeapObject(o),addHeapObject(a),addHeapObject(s),addHeapObject(c));var d=getInt32Memory0()[u/4+0],l=getInt32Memory0()[u/4+1];if(getInt32Memory0()[u/4+2])throw takeObject(l);return takeObject(d)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,d,n,l,o,a,s,c)}async function collectionEvictQueryStr(t,e,n,i,o,a,s,c){ensureInitialized();const d=bytesFromString(e),l=bytesFromString(i);return await function ditto_collection_evict_query_str(t,e,n,i,o,a,s,c){try{const u=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_collection_evict_query_str(u,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(i),addHeapObject(o),addHeapObject(a),addHeapObject(s),addHeapObject(c));var d=getInt32Memory0()[u/4+0],l=getInt32Memory0()[u/4+1];if(getInt32Memory0()[u/4+2])throw takeObject(l);return takeObject(d)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,d,n,l,o,a,s,c)}async function experimentalExecQueryStr(t,e,n,i){ensureInitialized();const o=bytesFromString(n);return await function ditto_experimental_exec_query_str(t,e,n,i){try{const s=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_experimental_exec_query_str(s,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(i));var o=getInt32Memory0()[s/4+0],a=getInt32Memory0()[s/4+1];if(getInt32Memory0()[s/4+2])throw takeObject(a);return takeObject(o)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,e,o,i)}function addSubscription(t,e,n,i,o,a,s){ensureInitialized();return function ditto_add_subscription(t,e,n,i,o,a,s){try{const l=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_add_subscription(l,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(i),addHeapObject(o),addHeapObject(a),addHeapObject(s));var c=getInt32Memory0()[l/4+0],d=getInt32Memory0()[l/4+1];if(getInt32Memory0()[l/4+2])throw takeObject(d);return takeObject(c)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,bytesFromString(e),bytesFromString(n),i,o,a,s)}function removeSubscription(t,e,n,i,o,a,s){ensureInitialized();return function ditto_remove_subscription(t,e,n,i,o,a,s){try{const l=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_remove_subscription(l,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(i),addHeapObject(o),addHeapObject(a),addHeapObject(s));var c=getInt32Memory0()[l/4+0],d=getInt32Memory0()[l/4+1];if(getInt32Memory0()[l/4+2])throw takeObject(d);return takeObject(c)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,bytesFromString(e),bytesFromString(n),i,o,a,s)}function experimentalAddDqlSubscription(t,e,n){ensureInitialized();const i=function ditto_experimental_add_dql_subscription(t,e,n){try{const a=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_experimental_add_dql_subscription(a,addHeapObject(t),addHeapObject(e),addHeapObject(n));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,bytesFromString(e),n);if(0!==i)throw new Error(errorMessage()||`ditto_experimental_add_dql_subscription() failed with error code: ${i}`)}function experimentalRemoveDqlSubscription(t,e,n){ensureInitialized();const i=function ditto_experimental_remove_dql_subscription(t,e,n){try{const a=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_experimental_remove_dql_subscription(a,addHeapObject(t),addHeapObject(e),addHeapObject(n));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,bytesFromString(e),n);if(0!==i)throw new Error(errorMessage()||`ditto_experimental_remove_dql_subscription() failed with error code: ${i}`)}function liveQueryRegister(t,e,n,i,o,a,s,c,d){ensureInitialized();const l=bytesFromString(e),u=bytesFromString(n),{status_code:_,i64:g}=function ditto_live_query_register_str_detached(t,e,n,i,o,a,s,c){try{const u=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_live_query_register_str_detached(u,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(i),addHeapObject(o),addHeapObject(a),addHeapObject(s),addHeapObject(c));var d=getInt32Memory0()[u/4+0],l=getInt32Memory0()[u/4+1];if(getInt32Memory0()[u/4+2])throw takeObject(l);return takeObject(d)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,l,u,i,o,a,s,wrapBackgroundCbForFFI(d,c));if(0!==_)throw new Error(errorMessage()||`\`ditto_live_query_register_str()\` failed with error code: ${_}`);return g}async function liveQueryStart(t,e){ensureInitialized();const n=await function ditto_live_query_start(t,e){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_live_query_start(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(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){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_live_query_stop(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,e)}async function liveQuerySignalAvailableNext(t,e){ensureInitialized(),await function ditto_live_query_signal_available_next(t,e){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_live_query_signal_available_next(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,e)}async function liveQueryWebhookRegister(t,e,n,i,o,a,s){ensureInitialized();const c=bytesFromString(e),d=bytesFromString(n),l=bytesFromString(s),{status_code:u,id:_}=await function ditto_live_query_webhook_register_str(t,e,n,i,o,a,s){try{const l=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_live_query_webhook_register_str(l,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(i),addHeapObject(o),addHeapObject(a),addHeapObject(s));var c=getInt32Memory0()[l/4+0],d=getInt32Memory0()[l/4+1];if(getInt32Memory0()[l/4+2])throw takeObject(d);return takeObject(c)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,c,d,i,o,a,l);if(0!==u)throw new Error(errorMessage()||`\`ditto_live_query_webhook_register_str()\` failed with error code: ${u}`);return boxCBytesIntoBuffer(_)}async function readTransaction(t){ensureInitialized();const{status_code:e,txn:n}=await function ditto_read_transaction(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_read_transaction(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(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){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_read_transaction_free(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t)}async function writeTransaction(t){ensureInitialized();const{status_code:e,txn:n}=await function ditto_write_transaction(t,e){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_write_transaction(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,null);if(0!==e)throw new Error(errorMessage()||`ditto_write_transaction() failed with error code: ${e}`);return n}async function writeTransactionCommit(t,e){ensureInitialized();const n=await function ditto_write_transaction_commit(t,e){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_write_transaction_commit(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,e);if(0!==n)throw new Error(errorMessage()||`ditto_write_transaction_commit() failed with error code: ${n}`)}async function writeTransactionRollback(t,e){ensureInitialized();const n=await function ditto_write_transaction_rollback(t,e){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_write_transaction_rollback(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,e);if(0!==n)throw new Error(errorMessage()||`ditto_write_transaction_rollback() failed with error code: ${n}`)}function loggerInit(){ensureInitialized(),function ditto_logger_init(){try{const n=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_logger_init(n);var t=getInt32Memory0()[n/4+0],e=getInt32Memory0()[n/4+1];if(getInt32Memory0()[n/4+2])throw takeObject(e);return takeObject(t)}finally{r.__wbindgen_add_to_stack_pointer(16)}}()}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){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_logger_enabled(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(!!t)}function loggerEnabledGet(){return ensureInitialized(),!!function ditto_logger_enabled_get(){try{const n=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_logger_enabled_get(n);var t=getInt32Memory0()[n/4+0],e=getInt32Memory0()[n/4+1];if(getInt32Memory0()[n/4+2])throw takeObject(e);return takeObject(t)}finally{r.__wbindgen_add_to_stack_pointer(16)}}()}function loggerEmojiHeadingsEnabled(t){ensureInitialized(),function ditto_logger_emoji_headings_enabled(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_logger_emoji_headings_enabled(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t)}function loggerEmojiHeadingsEnabledGet(){return ensureInitialized(),function ditto_logger_emoji_headings_enabled_get(){try{const n=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_logger_emoji_headings_enabled_get(n);var t=getInt32Memory0()[n/4+0],e=getInt32Memory0()[n/4+1];if(getInt32Memory0()[n/4+2])throw takeObject(e);return takeObject(t)}finally{r.__wbindgen_add_to_stack_pointer(16)}}()}function loggerMinimumLogLevel(t){ensureInitialized(),function ditto_logger_minimum_log_level(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_logger_minimum_log_level(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t)}function loggerMinimumLogLevelGet(){return ensureInitialized(),function ditto_logger_minimum_log_level_get(){try{const n=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_logger_minimum_log_level_get(n);var t=getInt32Memory0()[n/4+0],e=getInt32Memory0()[n/4+1];if(getInt32Memory0()[n/4+2])throw takeObject(e);return takeObject(t)}finally{r.__wbindgen_add_to_stack_pointer(16)}}()}function loggerSetLogFile(t){ensureInitialized();if(0!==function ditto_logger_set_log_file(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_logger_set_log_file(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(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){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_log(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,bytesFromString(e))}function dittoIdentityConfigMakeOnlinePlayground(t,e,n){ensureInitialized();const i=bytesFromString(t),o=bytesFromString(e),a=bytesFromString(n),{status_code:s,identity_config:c}=function ditto_identity_config_make_online_playground(t,e,n){try{const a=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_identity_config_make_online_playground(a,addHeapObject(t),addHeapObject(e),addHeapObject(n));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(i,o,a);if(0!==s)throw new Error(errorMessage()||`ditto_identity_config_make_online_playground() failed with error code: ${s}`);return c}function dittoIdentityConfigMakeOnlineWithAuthentication(t,e){ensureInitialized();const n=bytesFromString(t),i=bytesFromString(e),{status_code:o,identity_config:a}=function ditto_identity_config_make_online_with_authentication(t,e){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_identity_config_make_online_with_authentication(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(n,i);if(0!==o)throw new Error(errorMessage()||`ditto_identity_config_make_online_with_authentication() failed with error code: ${o}`);return a}function dittoIdentityConfigMakeOfflinePlayground(t,e){ensureInitialized();const n=bytesFromString(t),i=Number(e),{status_code:o,identity_config:a}=function ditto_identity_config_make_offline_playground(t,e){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_identity_config_make_offline_playground(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(n,i);if(0!==o)throw new Error(errorMessage()||`ditto_identity_config_make_offline_playground() failed with error code: ${o}`);return a}function dittoIdentityConfigMakeSharedKey(t,e,n){ensureInitialized();const i=bytesFromString(t),o=bytesFromString(e),a=Number(n),{status_code:s,identity_config:c}=function ditto_identity_config_make_shared_key(t,e,n){try{const a=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_identity_config_make_shared_key(a,addHeapObject(t),addHeapObject(e),addHeapObject(n));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(i,o,a);if(0!==s)throw new Error(errorMessage()||`ditto_identity_config_make_shared_key() failed with error code: ${s}`);return c}function dittoIdentityConfigMakeManual(t){ensureInitialized();const e=bytesFromString(t),{status_code:n,identity_config:i}=function ditto_identity_config_make_manual_v0(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_identity_config_make_manual_v0(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(e);if(0!==n)throw new Error(errorMessage()||`ditto_identity_config_make_manual_v0() failed with error code: ${n}`);return i}function dittoAuthClientGetSiteID(t){return ensureInitialized(),function ditto_auth_client_get_site_id(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_auth_client_get_site_id(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t)}function dittoAuthClientIsWebValid(t){return ensureInitialized(),0!==function ditto_auth_client_is_web_valid(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_auth_client_is_web_valid(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t)}function dittoAuthClientUserID(t){ensureInitialized();const e=function ditto_auth_client_user_id(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_auth_client_user_id(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t);return boxCStringIntoString(e)}function dittoAuthClientIsX509Valid(t){return ensureInitialized(),0!==function ditto_auth_client_is_x509_valid(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_auth_client_is_x509_valid(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t)}async function dittoAuthClientLoginWithToken(t,e,n){ensureInitialized();const i=bytesFromString(e),o=bytesFromString(n),a=await function ditto_auth_client_login_with_token(t,e,n){try{const a=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_auth_client_login_with_token(a,addHeapObject(t),addHeapObject(e),addHeapObject(n));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,i,o);if(0!==a)throw new Error(errorMessage()||`Ditto failed to authenticate (error code: ${a}).`)}async function dittoAuthClientLoginWithUsernameAndPassword(t,e,n,i){ensureInitialized();const o=bytesFromString(e),a=bytesFromString(n),s=bytesFromString(i),c=await function ditto_auth_client_login_with_credentials(t,e,n,i){try{const s=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_auth_client_login_with_credentials(s,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(i));var o=getInt32Memory0()[s/4+0],a=getInt32Memory0()[s/4+1];if(getInt32Memory0()[s/4+2])throw takeObject(a);return takeObject(o)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,o,a,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){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_auth_client_logout(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(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){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.uninitialized_ditto_make(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(bytesFromString(t))}function dittoMake(t,e){return ensureInitialized(),function ditto_make(t,e,n){try{const a=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_make(a,addHeapObject(t),addHeapObject(e),addHeapObject(n));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,e,"Disabled")}async function dittoGetCollectionNames(t){ensureInitialized();const e=await function ditto_get_collection_names(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_get_collection_names(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t),n=e.status_code,i=e.names;if(0!==n)throw new Error(errorMessage()||`ditto_get_collection_names() failed with error code: ${n}`);return function cStringVecToStringArray(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.cStringVecToStringArray(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(i)}function dittoFree(t){return ensureInitialized(),function ditto_free(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_free(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t)}async function dittoRegisterPresenceV1Callback(t,e){ensureInitialized(),function ditto_register_presence_v1_callback(t,e){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_register_presence_v1_callback(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,wrapBackgroundCbForFFI((t=>console.error(`The registered presence callback v1 errored with ${t}`)),(t=>{const n=refCStringToString(t);e(n)})))}async function dittoClearPresenceCallback(t){ensureInitialized(),await function ditto_clear_presence_callback(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_clear_presence_callback(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t)}async function dittoRegisterPresenceV3Callback(t,e){ensureInitialized(),function ditto_register_presence_v3_callback(t,e){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_register_presence_v3_callback(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,wrapBackgroundCbForFFI((t=>console.error(`The registered presence callback v3 errored with ${t}`)),(t=>{const n=refCStringToString(t);e(n)})))}async function dittoClearPresenceV3Callback(t){ensureInitialized(),function ditto_clear_presence_v3_callback(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_clear_presence_v3_callback(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(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){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_set_device_name(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,n)}function dittoSetConnectRetryInterval(t,e){ensureInitialized();return function ditto_set_connect_retry_interval(t,e){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_set_connect_retry_interval(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,Math.min(Math.max(0,e),4294967295))}function dittoSetSyncGroup(t,e){return ensureInitialized(),function ditto_set_sync_group(t,e){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_set_sync_group(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,e)}async function dittoNewAttachmentFromBytes(t,e){ensureInitialized();const n={},i=await function ditto_new_attachment_from_bytes(t,e,n){try{const a=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_new_attachment_from_bytes(a,addHeapObject(t),addHeapObject(e),addHeapObject(n));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,e,n);if(0!==i)throw new Error(errorMessage()||`ditto_new_attachment_from_bytes() failed with error code: ${i}`);return n}async function dittoResolveAttachment(t,e,n,i){ensureInitialized();const{onComplete:o,onProgress:a,onDelete:s}=n,{status_code:c,cancel_token:d}=await function ditto_resolve_attachment(t,e,n,i,o){try{const c=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_resolve_attachment(c,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(i),addHeapObject(o));var a=getInt32Memory0()[c/4+0],s=getInt32Memory0()[c/4+1];if(getInt32Memory0()[c/4+2])throw takeObject(s);return takeObject(a)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,e,wrapBackgroundCbForFFI(i,o),wrapBackgroundCbForFFI(i,a),wrapBackgroundCbForFFI(i,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 i=function ditto_cancel_resolve_attachment(t,e,n){try{const a=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_cancel_resolve_attachment(a,addHeapObject(t),addHeapObject(e),addHeapObject(n));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,e,n);if(0!==i)throw new Error(errorMessage()||`ditto_cancel_resolve_attachment() failed with error code: ${i}`)}async function dittoGetCompleteAttachmentData(t,e){ensureInitialized();const{status:n,data:i}=await function ditto_get_complete_attachment_data(t,e){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_get_complete_attachment_data(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,e);if(0!==n)throw new Error(errorMessage()||`\`ditto_get_complete_attachment_data()\` failed with error code: ${n}`);return boxCBytesIntoBuffer(i)}function dittoGetSDKVersion(t){ensureInitialized();return boxCStringIntoString(function ditto_get_sdk_version(){try{const n=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_get_sdk_version(n);var t=getInt32Memory0()[n/4+0],e=getInt32Memory0()[n/4+1];if(getInt32Memory0()[n/4+2])throw takeObject(e);return takeObject(t)}finally{r.__wbindgen_add_to_stack_pointer(16)}}())}function dittoPresenceV1(t){ensureInitialized();return boxCStringIntoString(function ditto_presence_v1(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_presence_v1(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t))}function dittoPresenceV3(t){ensureInitialized();return boxCStringIntoString(function ditto_presence_v3(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_presence_v3(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t))}async function dittoShutdown(t){return ensureInitialized(),await function ditto_shutdown(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_shutdown(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t)}function dittoRunGarbageCollection(t){return ensureInitialized(),function ditto_run_garbage_collection(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_run_garbage_collection(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t)}async function dittoDisableSyncWithV3(t){ensureInitialized();const e=await function ditto_disable_sync_with_v3(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_disable_sync_with_v3(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t);if(0!==e)throw new Error(errorMessage()||`ditto_disable_sync_with_v3() failed with error code: ${e}`)}function dittoSetStaticWebsocketClients(t,e,n){ensureInitialized();!function ditto_set_static_websocket_clients(t,e,n){try{const a=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_set_static_websocket_clients(a,addHeapObject(t),addHeapObject(e),addHeapObject(n));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,e.map((t=>bytesFromString(t))),n)}function documentsHash(t){ensureInitialized();const{status_code:e,u64:n}=function ditto_documents_hash(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_documents_hash(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(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){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_documents_hash_mnemonic(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t);if(0!==e)throw new Error(errorMessage()||`\`ditto_documents_hash_mnemonic()\` failed with error code: ${e}`);return boxCStringIntoString(n)}async function dittoAuthSetLoginProvider(t,e){return ensureInitialized(),await function ditto_auth_set_login_provider(t,e){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_auth_set_login_provider(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,e)}function dittoAuthClientMakeLoginProvider(t,e){return ensureInitialized(),function ditto_auth_client_make_login_provider(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_auth_client_make_login_provider(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(wrapBackgroundCbForFFI(e,t))}function dittoAuthClientSetValidityListener(t,e,n){ensureInitialized();return function ditto_auth_client_set_validity_listener(t,e){try{const o=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_auth_client_set_validity_listener(o,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(n)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,wrapBackgroundCbForFFI(n,(function(t,n){return e(1===t,1===n)})))}!function(t){t[t.counter=0]="counter",t[t.register=1]="register",t[t.attachment=2]="attachment",t[t.rga=3]="rga",t[t.rwMap=4]="rwMap"}(b||(b={}));let f,p=!1;async function init$2(t){t?await init$3(t):await init$3(),p=!0,f=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 i=function ditto_init_sdk_version(t,e,n){try{const a=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_init_sdk_version(a,addHeapObject(t),addHeapObject(e),addHeapObject(n));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t,e,bytesFromString(n));if(void 0!==i&&0!==i)throw new Error(errorMessage()||`ditto_init_sdk_version() failed with error code: ${i}`)}const y=-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(){try{const n=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_error_message(n);var t=getInt32Memory0()[n/4+0],e=getInt32Memory0()[n/4+1];if(getInt32Memory0()[n/4+2])throw takeObject(e);return takeObject(t)}finally{r.__wbindgen_add_to_stack_pointer(16)}}())}function ensureInitialized(){if(!p)throw new Error("Ditto needs to be initialized before using any of its API, please make sure to call `await init()` first.")}class AttachmentToken{constructor(t){if(t[g]!==b.attachment)throw new Error("Invalid attachment token");const e=t._id;if(!(e instanceof Uint8Array))throw new Error("Invalid attachment token id");const n=t._len;if("number"!=typeof n||n<0)throw new Error("Invalid attachment token length");const r=t._meta;if("object"!=typeof r)throw new Error("Invalid attachment token meta");this.id=e,this.len=n,this.metadata=r}}let w=!1;class Logger{static setLogFile(t){t?(loggerSetLogFile(t),this.logFile=t):(loggerSetLogFile(null),delete this.logFile)}static setLogFileURL(t){this.setLogFile(null==t?void 0:t.pathname)}static get enabled(){return loggerEnabledGet()}static set enabled(t){loggerEnabled(t)}static get emojiLogLevelHeadingsEnabled(){return loggerEmojiHeadingsEnabledGet()}static set emojiLogLevelHeadingsEnabled(t){loggerEmojiHeadingsEnabled(t)}static get minimumLogLevel(){return loggerMinimumLogLevelGet()}static set minimumLogLevel(t){loggerMinimumLogLevel(t)}static async setCustomLogCallback(t){t?(await loggerSetCustomLogCb(t),this.customLogCallback=t):(await loggerSetCustomLogCb(null),delete this.customLogCallback)}static log(t,e){log(t,e)}static error(t){this.log("Error",t)}static warning(t){this.log("Warning",t)}static info(t){this.log("Info",t)}static debug(t){this.log("Debug",t)}static verbose(t){this.log("Verbose",t)}constructor(){throw new Error("Logger can't be instantiated, use it's static properties & methods directly instead.")}}const m=4294967296,O=9007199254740992;class TaggedValue{constructor(t,e){this.value=t,this.tag=e}}const v={decode:function decode(t,e,n){let r=new DataView(t),i=new Uint8Array(t),o=0,tagValueFunction=function(t,e){return new TaggedValue(t,e)},simpleValFunction=function(t){};function commitRead(t,e){return o+=t,e}function readArrayBuffer(e){return commitRead(e,new Uint8Array(t,o,e))}function readUint8(){return commitRead(1,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()*m+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 writeUint16(t){commitWrite(prepareWrite(2).setUint16(o,t))}function writeUint32(t){commitWrite(prepareWrite(4).setUint32(o,t))}function writeUint64(t){let e=t%m,n=(t-e)/m,r=prepareWrite(8);r.setUint32(o,n),r.setUint32(o+4,e),commitWrite()}function writeTypeAndLength(t,e){e<24?writeUint8(t<<5|e):e<256?(writeUint8(t<<5|24),writeUint8(e)):e<65536?(writeUint8(t<<5|25),writeUint16(e)):e<4294967296?(writeUint8(t<<5|26),writeUint32(e)):(writeUint8(t<<5|27),writeUint64(e))}if(function encodeItem(t){let e;if(!1===t)return writeUint8(244);if(!0===t)return writeUint8(245);if(null===t)return writeUint8(246);if(void 0===t)return writeUint8(247);if(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 if(t instanceof TaggedValue)!function writeVarUint(t,e){t<=255?t<24?writeUint8(t|e):(writeUint8(24|e),writeUint8(t)):t<=65535?(writeUint8(25|e),writeUint16(t)):t<=4294967295?(writeUint8(26|e),writeUint32(t)):(writeUint8(27|e),writeUint64(t))}(t.tag,192),encodeItem(t.value);else{let n=Object.keys(t);for(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 DocumentID{get value(){let t=this["@ditto.value"];return void 0===t&&(t=CBOR.decode(this["@ditto.cbor"]),this["@ditto.value"]=t),t}constructor(t,e=!1,n=!1){const r=e?t:CBOR.encode(t),i=n?r:validateDocumentIDCBOR(r);if(!i)throw new Error(`Can't create DocumentID, passed in value is not valid: ${t}`);this.isValidated=!n,this["@ditto.cbor"]=i}equals(t){const e=this["@ditto.cbor"],n=t["@ditto.cbor"];if(e===n)return!0;if(!(e instanceof Uint8Array))return!1;if(!(n instanceof Uint8Array))return!1;if(e.length!==n.length)return!1;for(let t=0;t<e.length;t+=1)if(e[t]!==n[t])return!1;return!0}toString(){return documentIDQueryCompatible(this["@ditto.cbor"],"WithoutQuotes")}toBase64String(){const t=this["@ditto.cbor"];return btoa(String.fromCharCode.apply(null,t))}toQueryCompatibleString(){return documentIDQueryCompatible(this["@ditto.cbor"],"WithQuotes")}toCBOR(){return this["@ditto.cbor"]}}function validateDocumentIDCBOR(t){const e=validateDocumentID(t);return null!=e?e:t}const I=[];class Handle{constructor(t,e){this.isClosed=!1,this.bridge=t,this.objectWeakRef=new WeakRef(e)}get type(){return this.bridge.type}deref(){const t=this.objectWeakRef.deref();if(null==t)throw new Error("Bridging error: can't get pointer for an object that has been garbage collected.");if(this.isClosed)throw new Error("Bridging error: can't get pointer for an object that has been closed.");const e=this.bridge.rawPointerFor(t);if(null==e)throw new Error(`Bridging error: ${this.type.name} object is not currently registered in this bridge.`);return e}derefOrNull(){const t=this.objectWeakRef.deref();if(null==t)return null;if(this.isClosed)return null;const e=this.bridge.rawPointerFor(t);return null!=e?e:null}object(){const t=this.objectWeakRef.deref();if(null==t)throw new Error(`Bridging error: ${this.bridge.type.name} object has already been garbage collected.`);if(this.isClosed)throw new Error(`Bridging error: ${this.bridge.type.name} object has already been closed.`);return t}objectOrNull(){var t;if(this.isClosed)throw new Error(`Bridging error: ${this.bridge.type.name} object has already been closed.`);return null!==(t=this.objectWeakRef.deref())&&void 0!==t?t:null}toString(){const t=this.derefOrNull();return`{ Handle | type: ${this.bridge.type}, object: ${this.objectWeakRef.deref()}, FFI address: ${null==t?void 0:t.addr}, FFI type: ${null==t?void 0:t.type} }`}}class Handles{constructor(t,e){this.handles=e.map((e=>t.handleFor(e)))}deref(){return this.handles.map((t=>t.deref()))}}class Bridge{constructor(t){this.internalType=null,this.pointerByObject=new WeakMap,this.release=t,this.handlesByAddress={},this.finalizationRegistry=new FinalizationRegistry(this.finalize.bind(this)),Bridge.all.push(new WeakRef(this))}get type(){if(null==this.internalType)throw new Error("Bridge type has not been registered yet.");return this.internalType}registerType(t){if(this.internalType!==t){if(this.internalType)throw new Error(`Can't register bridged type '${t.name}', another type was already registered: ${this.internalType}`);this.internalType=t}}handleFor(t){const e=this.pointerByObject.get(t);if(null==e)throw new Error(`Bridging error: ${this.type.name} object is not currently registered in this bridge.`);const n=this.handlesByAddress[e.addr];if(null==n)throw new Error(`Internal inconsistency, found a pointer for an object whose handle is undefined: ${e}`);return n}handlesFor(t){return new Handles(this,t)}objectFor(t){const e=this.handlesByAddress[t.addr];if(e){if(e.type!==this.type)throw new Error(`Can't return object for pointer, pointer is associated with an object of type ${e.type} but this bridge is configured for ${this.type}`);return e.object()}}bridge(t,e){const n=this.objectFor(t);if(n)return n;let r;if(e||(e=()=>Reflect.construct(this.type,[])),"function"==typeof e){if(r=e(),!(r instanceof this.type))throw new Error(`Can't bridge, expected passed in create function to return a ${this.type.name} object but got: ${r}`)}else r=e;return this.register(r,t),r}register(t,e){const n=t.constructor;if(n!==this.type)throw new Error(`Can't register, bridge is configured for type ${this.type.name} but passed in object is of type ${n.name}`);const r=this.pointerByObject.get(t),i=this.handlesByAddress[e.addr];if(null!=r&&null!=i)throw new Error(`Can't register, an object for the passed in pointer has previously been registered: ${i.object()}`);if(null!=r&&null==i)throw new Error(`Internal inconsistency, trying to register an object which has an associated pointer but no handle entry: ${n.name} at ${r.type} ${r.addr}`);if(null==r&&null!=i)throw new Error(`Internal inconsistency, trying to register an object which has a handle entry but no associated pointer: ${n.name} ${t}`);const o=new Handle(this,t);this.handlesByAddress[e.addr]=o,this.pointerByObject.set(t,e),this.finalizationRegistry.register(t,e,t),I.includes(this.type.name)&&console.log(`[VERBOSE] Bridge REGISTERED a new instance of ${this.type.name}, current count: ${Object.keys(this.handlesByAddress).length}`)}markAsClosed(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.pointerByObject.get(t);if(null==r)throw new Error(`Can't unregister, object that has not been registered before: ${t}`);const i=this.handlesByAddress[r.addr];if(null==i)throw new Error(`Internal inconsistency, trying to unregister an object which has an associated pointer but no handle: ${t}`);if(i.type!==n)throw new Error(`Internal inconsistency, trying to unregister an object that has a handle with a different type than that of the bridge: ${i}`);if(i.objectOrNull()!==t)throw new Error(`Internal inconsistency, trying to unregister an object whose associated handle holds a different object: ${i}`);i.isClosed=!0}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.pointerByObject.get(t);if(null==r)throw new Error(`Can't unregister, object that has not been registered before: ${t}`);const i=this.handlesByAddress[r.addr];if(null==i)throw new Error(`Internal inconsistency, trying to unregister an object which has an associated pointer but no handle: ${t}`);if(i.type!==n)throw new Error(`Internal inconsistency, trying to unregister an object that has a handle with a different type than that of the bridge: ${i}`);if(i.objectOrNull()!==t)throw new Error(`Internal inconsistency, trying to unregister an object whose associated handle holds a different object: ${i}`);this.finalizationRegistry.unregister(t),delete this.handlesByAddress[r.addr],this.pointerByObject.delete(t),I.includes(this.type.name)&&console.log(`[VERBOSE] Bridge UNREGISTERED an instance of ${this.type.name}, current count: ${Object.keys(this.handlesByAddress).length}`)}unregisterAll(){I.includes(this.type.name)&&console.log(`[VERBOSE] Unregistering ALL bridged instances of type ${this.type.name}.`);for(const t of Object.values(this.handlesByAddress)){const e=t.object();e&&this.unregister(e)}}get count(){return Object.keys(this.handlesByAddress).length}rawPointerFor(t){return this.pointerByObject.get(t)}finalize(t){const e=this.handlesByAddress[t.addr];if(!e)throw new Error(`Internal inconsistency, tried to finalize an instance for a pointer, that has no handle: ${t}`);delete this.handlesByAddress[t.addr],this.release(t,e),I.includes(this.type.name)&&console.log(`[VERBOSE] Bridge FINALIZED an instance of ${this.type.name}, current count: ${Object.keys(this.handlesByAddress).length}`)}}Bridge.all=[],Bridge.attachment=new Bridge((function freeAttachmentHandle(t){ensureInitialized(),function ditto_free_attachment_handle(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.ditto_free_attachment_handle(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t)})),Bridge.document=new Bridge(documentFree),Bridge.mutableDocument=new Bridge(documentFree),Bridge.staticTCPClient=new Bridge((function staticTCPClientFreeHandle(t){(void 0)(t)})),Bridge.websocketClient=new Bridge((function websocketClientFreeHandle(t){ensureInitialized(),function websocket_client_free_handle(t){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.websocket_client_free_handle(i,addHeapObject(t));var e=getInt32Memory0()[i/4+0],n=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(n);return takeObject(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}(t)})),Bridge.ditto=new Bridge((async(t,e)=>{dittoClearPresenceCallback(t),e.isClosed||await dittoShutdown(t),dittoFree(t)}));class UpdateResult{static set(t,e,n){return new UpdateResult("set",t,e,n,void 0)}static incremented(t,e,n){return new UpdateResult("incremented",t,e,void 0,n)}static removed(t,e){return new UpdateResult("removed",t,e,void 0,void 0)}constructor(t,e,n,r,i){this.type=t,this.docID=e,this.path=n,void 0!==r&&(this.value=r),void 0!==i&&(this.amount=i)}}class Attachment{get metadata(){return this.token.metadata}getData(){const t=this.ditto,e=Bridge.ditto.handleFor(t);return this.ditto.deferCloseAsync((async()=>{{const t=Bridge.attachment.handleFor(this);return await dittoGetCompleteAttachmentData(e.deref(),t.deref())}}))}copyToPath(t){const e=this.ditto;return Bridge.ditto.handleFor(e),this.ditto.deferCloseAsync((async()=>{throw new Error("Can't copy attachment to path, not available when running in the browser.")}))}constructor(t,e){this.ditto=t,this.token=e}}function augmentJSONValue(t,e,n){if(t&&"object"==typeof t){if(Array.isArray(t))return t.map(((t,r)=>augmentJSONValue(t,e,`${n}[${r}]`)));if(t[g]===b.counter)return Counter["@ditto.create"](e,n,t[h]);if(t[g]===b.register)return Register["@ditto.create"](e,n,t[h]);if(t[g]===b.attachment)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=!1){if(t&&"object"==typeof t){if(Array.isArray(t))return t.map(((t,e)=>desugarJSObject(t,!1)));if(t instanceof DocumentID)return t.value;if(t instanceof Counter){const e={};return e[g]=b.counter,e[h]=t.value,e}if(t instanceof Register){const e={};return e[g]=b.register,e[h]=t.value,e}if(t instanceof Attachment){const e={_id:t.token.id,_len:t.token.len,_meta:t.token.metadata};return e[g]=b.attachment,e}for(const[e,n]of Object.entries(t))t[e]=desugarJSObject(n,!1);return t}return function checkForUnsupportedValues(t){if(Number.isNaN(t)||t===1/0||t===-1/0)throw new Error("Non-finite float values are not supported")}(t),t}const k="cloud.ditto.live";function defaultAuthURL(t){return`https://${t}.${k}`}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}function generateEphemeralToken(){let t;t=crypto;const e=new Uint16Array(16);t.getRandomValues(e);return Array.from(e).map((t=>t.toString(16))).join("")}async function step(t){return await function sleep(t){return new Promise(((e,n)=>{setTimeout(e,t)}))}(0),t()}const j=step,C=/\.([A-Za-z_]\w*)/.source,M=/\[(\d+)\]/.source,E=/\[\'(.+?)\'\]/.source,D=/\[\"(.+?)\"\]/.source,A=`((${C})|(${M})|(${E})|(${D}))*`,B=new RegExp(`^${C}`),S=new RegExp(`^${M}`),P=new RegExp(`^${E}`),T=new RegExp(`^${D}`),H=new RegExp(`^${A}$`);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(!H.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(B);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(S);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(P);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{at(t){if("string"==typeof t){const e=t,n=KeyPath.validate(e),r=KeyPath.withoutLeadingDot(`${this.path}${n}`);return new DocumentPath(this.document,r,!1)}if("number"==typeof t){const e=validateNumber(t,{integer:!0,min:0,errorMessagePrefix:"DocumentPath.at() validation failed index:"});return new DocumentPath(this.document,`${this.path}[${e.toString()}]`,!1)}throw new Error(`Can't return document path at key-path or index, string or number expected but got ${typeof t}: ${t}`)}get value(){return this.underlyingValueForPathType("Any")}get counter(){const t=this.underlyingValueForPathType("Counter");return void 0!==t?Counter["@ditto.create"](null,this.path,t):null}get register(){const t=this.underlyingValueForPathType("Register");return void 0!==t?Register["@ditto.create"](null,this.path,t):null}get attachmentToken(){const t=this.underlyingValueForPathType("Attachment");return void 0!==t?new AttachmentToken(t):null}constructor(t,e,n){this.document=t,this.path=n?KeyPath.validate(e,{isInitial:!0}):e}underlyingValueForPathType(t){const e=this.path,n=this.document,r=documentGetCBORWithPathType(Bridge.document.handleFor(n).deref(),e,t);return null!==r.cbor?CBOR.decode(r.cbor):void 0}}class MutableDocumentPath{at(t){if("string"==typeof t){const e=t,n=KeyPath.validate(e),r=KeyPath.withoutLeadingDot(`${this.path}${n}`);return new MutableDocumentPath(this.mutableDocument,r,!1)}if("number"==typeof t){const e=validateNumber(t,{integer:!0,min:0,errorMessagePrefix:"MutableDocumentPath.at() validation failed index:"});return new MutableDocumentPath(this.mutableDocument,`${this.path}[${e.toString()}]`,!1)}throw new Error(`Can't return mutable document path at key-path or index, string or number expected but got ${typeof t}: ${t}`)}get value(){return this.underlyingValueForPathType("Any")}get counter(){const t=this.underlyingValueForPathType("Counter");return void 0!==t?Counter["@ditto.create"](this.mutableDocument,this.path,t):null}get register(){const t=this.underlyingValueForPathType("Register");return void 0!==t?Register["@ditto.create"](this.mutableDocument,this.path,t):null}get attachmentToken(){const t=this.underlyingValueForPathType("Attachment");return void 0!==t?new AttachmentToken(t):null}set(t,e){return this["@ditto.set"](t,e)}remove(){return this["@ditto.remove"]()}constructor(t,e,n){this.mutableDocument=t,this.path=n?KeyPath.validate(e,{isInitial:!0}):e}underlyingValueForPathType(t){const e=this.path,n=this.mutableDocument,r=documentGetCBORWithPathType(Bridge.mutableDocument.handleFor(n).deref(),e,t);return null!==r.cbor?CBOR.decode(r.cbor):void 0}"@ditto.increment"(t){documentIncrementCounter(Bridge.mutableDocument.handleFor(this.mutableDocument).deref(),this.path,t);const e=UpdateResult.incremented(this.mutableDocument.id,this.path,t);this.recordUpdateResult(e)}"@ditto.set"(t,e){const n=Bridge.mutableDocument.handleFor(this.mutableDocument),r=desugarJSObject(t,!1),i=CBOR.encode(r);e?documentSetCBORWithTimestamp(n.deref(),this.path,i,0):documentSetCBOR(n.deref(),this.path,i);const o=augmentJSONValue(CBOR.decode(i),this.mutableDocument,this.path),a=UpdateResult.set(this.mutableDocument.id,this.path,o);this.recordUpdateResult(a)}"@ditto.remove"(){documentRemove(Bridge.mutableDocument.handleFor(this.mutableDocument).deref(),this.path),this.updateInMemory(((t,e)=>{Array.isArray(t)&&"number"==typeof e?t.splice(e,1):delete t[e]}));const t=UpdateResult.removed(this.mutableDocument.id,this.path);this.recordUpdateResult(t)}updateInMemory(t){const e=this.mutableDocument.value,n=KeyPath.evaluate(this.path,e,{stopAtLastContainer:!0});t(n.value,n.nextPathComponent)}recordUpdateResult(t){const e=this.mutableDocument["@ditto.updateResults"].slice();e.push(t),Object.freeze(e),this.mutableDocument["@ditto.updateResults"]=e}}class Document{static hash(t){return documentsHash(documentsFrom(t).map((t=>Bridge.document.handleFor(t))).map((t=>t.deref())))}static hashMnemonic(t){const e=documentsFrom(t);return documentsHashMnemonic(Bridge.document.handlesFor(e).deref())}get id(){let t=this["@ditto.id"];if(void 0===t){const e=documentID(Bridge.document.handleFor(this).deref());t=new DocumentID(e,!0),this["@ditto.id"]=t}return t}get path(){return new DocumentPath(this,"",!1)}get value(){let t=this["@ditto.value"];return void 0===t&&(t=this.path.value,this["@ditto.value"]=t),t}at(t){return this.path.at(t)}constructor(){}static idCBOR(t){return documentID(Bridge.document.handleFor(t).deref())}static canonicalizedIDCBOR(t){return validateDocumentIDCBOR(t)}static isIDCBORCanonical(t){return t===this.canonicalizedIDCBOR(t)}}class MutableDocument{get id(){let t=this["@ditto.id"];if(void 0===t){const e=documentID(Bridge.mutableDocument.handleFor(this).deref());t=new DocumentID(e,!0),this["@ditto.id"]=t}return t}get path(){return new MutableDocumentPath(this,"",!1)}get value(){return this.path.value}at(t){return this.path.at(t)}constructor(){this["@ditto.updateResults"]=[]}static idCBOR(t){return documentID(Bridge.mutableDocument.handleFor(t).deref())}}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}`)}MutableDocument.canonicalizedIDCBOR=Document.canonicalizedIDCBOR,MutableDocument.isIDCBORCanonical=Document.isIDCBORCanonical;class UpdateResultsMap{get(t){const e=(t instanceof DocumentID?t:new DocumentID(t)).toString();return this.updateResultsByDocumentIDString[e]}keys(){return this.documentIDs.slice()}constructor(t,e){const n=t.map((t=>t.toString())).sort().join(", ");if(n!==Object.keys(e).sort().join(", "))throw new Error("Internal inconsistency, can't construct update results map, documentIDs must all be keys in update results (by document ID string)");this.documentIDs=t.slice(),this.updateResultsByDocumentIDString={...e}}}class BasePendingCursorOperation{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}async exec(){const t=this.collection.store.ditto,e=Bridge.ditto.handleFor(t);return t.deferCloseAsync((async()=>{const t=this.query;return(await j((async()=>await collectionExecQueryStr(e.deref(),this.collection.name,null,t,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset)))).map((t=>Bridge.document.bridge(t)))}))}async updateWithTransaction(t,e){const n=this.collection.store.ditto,r=Bridge.ditto.handleFor(n);return n.deferCloseAsync((async()=>await j((async()=>{const n=this.query,i=await collectionExecQueryStr(r.deref(),this.collection.name,e,n,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset),o=i.map((t=>Bridge.mutableDocument.bridge(t,(()=>new MutableDocument))));t(o);const a=[],s={};for(const t of o){const e=t.id,n=e.toString(),r=t["@ditto.updateResults"];if(s[n])throw new Error(`Internal inconsistency, update results for document ID as string already exist: ${n}`);a.push(e),s[n]=r,Bridge.mutableDocument.unregister(t)}return await collectionUpdateMultiple(r.deref(),this.collection.name,e,i),new UpdateResultsMap(a,s)}))))}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}then(t,e){return this.exec().then(t,e)}}class BasePendingIDSpecificOperation{async exec(){const t=this.collection.store.ditto,e=Bridge.ditto.handleFor(t);return t.deferCloseAsync((async()=>await j((async()=>{const t=await readTransaction(e.deref()),n=await collectionGet(e.deref(),this.collection.name,this.documentIDCBOR,t);let r;return n&&(r=Bridge.document.bridge(n)),readTransactionFree(t),r}))))}constructor(t,e){this.documentID=t,this.collection=e,this.documentIDCBOR=t.toCBOR()}then(t,e){return this.exec().then(t,e)}get query(){return`_id == ${this.documentID.toQueryCompatibleString()}`}}class ObserverManager{constructor(t,e={}){var n,r,i,o;const a=null!==(n=e.keepAlive)&&void 0!==n?n:null,s=null!==(r=e.register)&&void 0!==r?r:null,c=null!==(i=e.unregister)&&void 0!==i?i:null,d=null!==(o=e.process)&&void 0!==o?o:null;this.id=t,this.keepAlive=a,this.isClosed=!1,this.isRegistered=!1,this.callbacksByToken={},null!==s&&(this.register=s),null!==c&&(this.unregister=c),null!==d&&(this.process=d)}addObserver(t){var e;if(this.isClosed)throw new Error(`Internal inconsistency, can't add '${this.id}' observer, observer mananger close()-ed.`);this.registerIfNeeded();const n=generateEphemeralToken();return this.callbacksByToken[n]=t,null===(e=this.keepAlive)||void 0===e||e.retain(`${this.id}.${n}`),n}removeObserver(t){var e;const n=this.callbacksByToken[t];if(void 0===n)throw new Error(`Can't remove '${this.id}' observer, token '${t}' has never been registered before.`);null!==n&&(this.callbacksByToken[t]=null,null===(e=this.keepAlive)||void 0===e||e.release(`${this.id}.${t}`),this.unregisterIfNeeded())}hasObserver(t){return void 0!==this.callbacksByToken[t]}notify(...t){if(this.isClosed)return;const e=this.process(...t);for(const t in this.callbacksByToken){(0,this.callbacksByToken[t])(...e)}}close(){this.isClosed=!0;for(const t in this.callbacksByToken)this.removeObserver(t)}register(t){}unregister(){}process(...t){return t}hasObservers(){return Object.keys(this.callbacksByToken).length>0}registerIfNeeded(){if(!this.isRegistered){const t=new WeakRef(this);this.isRegistered=!0,this.register((function(...e){const n=t.deref();n&&n.notify(...e)}))}}unregisterIfNeeded(){!this.hasObservers()&&this.isRegistered&&(this.isRegistered=!1,this.unregister())}}class Authenticator{loginWithToken(t,e){throw new Error("Authenticator.loginWithToken() is abstract and must be implemented by subclasses.")}loginWithUsernameAndPassword(t,e,n){throw new Error("Authenticator.loginWithUsernameAndPassword() is abstract and must be implemented by subclasses.")}logout(t){throw new Error("Authenticator.logout() is abstract and must be implemented by subclasses.")}observeStatus(t){const e=this.observerManager.addObserver(t);return new Observer(this.observerManager,e,{stopsWhenFinalized:!0})}constructor(t){this.keepAlive=t,this.status={isAuthenticated:!1,userID:null},this.loginSupported=!1,this.observerManager=new ObserverManager("AuthenticationStatusObservation",{keepAlive:t})}"@ditto.authenticationExpiring"(t){throw new Error("Authenticator['@ditto.authenticationExpiring']() is abstract and must be implemented by subclasses.")}"@ditto.authClientValidityChanged"(t,e){throw new Error("Authenticator['@ditto.authClientValidityChanged']() is abstract and must be implemented by subclasses.")}close(){this.observerManager.close()}}class OnlineAuthenticator extends Authenticator{async loginWithToken(t,e){const n=this.ditto.deref();if(!n)return;const r=Bridge.ditto.handleFor(n).derefOrNull();return r?n.deferCloseAsync((async()=>{await dittoAuthClientLoginWithToken(r,t,e)})):void 0}async loginWithUsernameAndPassword(t,e,n){const r=this.ditto.deref();if(!r)return;const i=Bridge.ditto.handleFor(r).derefOrNull();return i?r.deferCloseAsync((async()=>{await dittoAuthClientLoginWithUsernameAndPassword(i,t,e,n)})):void 0}async logout(t){const e=this.ditto.deref();if(!e)return;const n=Bridge.ditto.handleFor(e).derefOrNull();return n?e.deferCloseAsync((async()=>{await dittoAuthClientLogout(n),e.stopSync(),null==t||t(this.ditto)})):void 0}constructor(t,e,n){super(t),this.loginSupported=!0,this.status={isAuthenticated:!1,userID:null},this.ditto=new WeakRef(e),this.authenticationHandler=n,this.updateAndNotify(!1)}"@ditto.authenticationExpiring"(t){const e=this.authenticationHandler;t>0?e.authenticationExpiringSoon(this,t):e.authenticationRequired(this)}"@ditto.authClientValidityChanged"(t,e){this.updateAndNotify(!0)}updateAndNotify(t){var e;const n=this.ditto.deref();if(!n)return void Logger.debug("Unable to update auth status and notify, related Ditto object does not exist anymore.");const r=Bridge.ditto.handleFor(n).derefOrNull();if(!r)return void Logger.debug("Unable to update auth status and notify, related Ditto object does not exist anymore.");const i=this.status.isAuthenticated,o=this.status.userID,a=dittoAuthClientIsWebValid(r),s=dittoAuthClientUserID(r),c={isAuthenticated:a,userID:s};if(this.status=c,t){!!i==!!a&&o===s||(null===(e=this.authenticationHandler.authenticationStatusDidChange)||void 0===e||e.call(this.authenticationHandler,this),this.observerManager.notify(c))}}}class NotAvailableAuthenticator extends Authenticator{async loginWithToken(t,e){throw new Error("Can't login, authentication is not supported for the identity in use, please use an onlineWithAuthentication identity.")}async loginWithUsernameAndPassword(t,e,n){throw new Error("Can't login, authentication is not supported for the identity in use, please use an onlineWithAuthentication identity.")}logout(t){throw new Error("Can't logout, authentication is not supported for the identity in use, please use an onlineWithAuthentication identity.")}"@ditto.authenticationExpiring"(t){throw new Error(`Internal inconsistency, authentication is not available, yet the @ditto.authenticationExpiring() was called on authenticator: ${this}`)}"@ditto.authClientValidityChanged"(t,e){throw new Error(`Internal inconsistency, authentication is not available, yet the @ditto.authClientValidityChanged() was called on authenticator: ${this}`)}}const F=["manual","sharedKey","offlinePlayground"];class TransportConfig{constructor(){this.peerToPeer={bluetoothLE:{isEnabled:!1},awdl:{isEnabled:!1},lan:{isEnabled:!1,isMdnsEnabled:!0,isMulticastEnabled:!0}},this.connect={tcpServers:[],websocketURLs:[],retryInterval:5e3},this.listen={tcp:{isEnabled:!1,interfaceIP:"0.0.0.0",port:4040},http:{isEnabled:!1,interfaceIP:"0.0.0.0",port:80,websocketSync:!0}},this.global={syncGroup:0,routingHint:0}}setAllPeerToPeerEnabled(t){this.peerToPeer.bluetoothLE.isEnabled=t,this.peerToPeer.lan.isEnabled=t,this.peerToPeer.awdl.isEnabled=t}freeze(){return this.isFrozen||(this.isFrozen=!0,Object.freeze(this.peerToPeer.bluetoothLE),Object.freeze(this.peerToPeer.awdl),Object.freeze(this.peerToPeer.lan),Object.freeze(this.peerToPeer),Object.freeze(this.connect.tcpServers),Object.freeze(this.connect.websocketURLs),Object.freeze(this.connect),Object.freeze(this.listen.tcp),Object.freeze(this.listen.http),Object.freeze(this.listen),Object.freeze(this.global)),this}copy(){const t=new TransportConfig;return t.peerToPeer.bluetoothLE.isEnabled=this.peerToPeer.bluetoothLE.isEnabled,t.peerToPeer.awdl.isEnabled=this.peerToPeer.awdl.isEnabled,t.peerToPeer.lan.isEnabled=this.peerToPeer.lan.isEnabled,t.peerToPeer.lan.isMdnsEnabled=this.peerToPeer.lan.isMdnsEnabled,t.peerToPeer.lan.isMulticastEnabled=this.peerToPeer.lan.isMulticastEnabled,t.connect.tcpServers=this.connect.tcpServers.slice(),t.connect.websocketURLs=this.connect.websocketURLs.slice(),t.listen.tcp={...this.listen.tcp},t.listen.http={...this.listen.http},t.global.syncGroup=this.global.syncGroup,t.global.routingHint=this.global.routingHint,t}static areListenTCPsEqual(t,e){return t.isEnabled===e.isEnabled&&t.interfaceIP===e.interfaceIP&&t.port===e.port}static areListenHTTPsEqual(t,e){return t.isEnabled===e.isEnabled&&t.interfaceIP===e.interfaceIP&&t.port===e.port&&t.staticContentPath===e.staticContentPath&&t.websocketSync===e.websocketSync&&t.tlsKeyPath===e.tlsKeyPath&&t.tlsCertificatePath===e.tlsCertificatePath}}class Subscription{get collectionName(){return this.collection.name}cancel(){this.isCancelled||(this.isCancelled=!0,this.manager.remove(this))}constructor(t,e,n,r,i,o){this.isCancelled=!1,this.query=e,this.queryArgsCBOR=n,this.collection=t,this.contextInfo={id:generateEphemeralToken(),collectionName:t.name,query:e,queryArgsCBOR:n,orderBys:r,limit:i,offset:o},this.manager=t.store.ditto.subscriptionManager,this.manager.add(this)}}class LiveQueryEventInitial{constructor(){this.isInitial=!0}hash(t){return documentsHash(Bridge.document.handlesFor(t).deref())}hashMnemonic(t){return documentsHashMnemonic(Bridge.document.handlesFor(t).deref())}}class LiveQueryEventUpdate{hash(t){return documentsHash(Bridge.document.handlesFor(t).deref())}hashMnemonic(t){return documentsHashMnemonic(Bridge.document.handlesFor(t).deref())}constructor(t){this.isInitial=!1,this.oldDocuments=t.oldDocuments,this.insertions=t.insertions,this.deletions=t.deletions,this.updates=t.updates,this.moves=t.moves}}class SingleDocumentLiveQueryEvent{hash(t){return documentsHash(Bridge.document.handlesFor(null==t?[]:[t]).deref())}hashMnemonic(t){return documentsHashMnemonic(Bridge.document.handlesFor(null==t?[]:[t]).deref())}constructor(t,e){this.isInitial=t,this.oldDocument=e}}class LiveQuery{get collectionName(){return this.collection.name}get isStopped(){return!this.liveQueryManager}stop(){this.isStopped||this.liveQueryManager.stopLiveQuery(this)}constructor(t,e,n,r,i,o,a,s){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=s,this.liveQueryManager=null;const c=a.name,d=new WeakRef(a.store.ditto);let l;const signalNext=async()=>{const t=d.deref();if(!t)return;const e=Bridge.ditto.handleFor(t).derefOrNull();return e?t.deferCloseAsync((async()=>{await liveQuerySignalAvailableNext(e,l)})):void 0},u=a.store.ditto,_=Bridge.ditto.handleFor(u);u.deferClose((()=>{if(l=liveQueryRegister(_.deref(),c,t,n,this.orderBys,i,o,(t=>{const e=t.documents.map((t=>Bridge.document.bridge(t)));let n;n=t.is_initial?new LiveQueryEventInitial:new LiveQueryEventUpdate({oldDocuments:t.old_documents.map((t=>Bridge.document.bridge(t))),insertions:t.insertions,deletions:t.deletions,updates:t.updates,moves:t.moves.map((t=>({from:t[0],to:t[1]})))}),s(e,n,signalNext)})),!l)throw new Error("Internal inconsistency, couldn't create a valid live query ID.");this.liveQueryID=l}))}async signalNext(){const t=this.collection.store.ditto,e=Bridge.ditto.handleFor(t);if(e.derefOrNull())return t.deferCloseAsync((async()=>{await liveQuerySignalAvailableNext(e.deref(),this.liveQueryID)}))}}class PendingCursorOperation extends BasePendingCursorOperation{sort(t,e="ascending"){return super.sort(t,e)}offset(t){return super.offset(t)}limit(t){return super.limit(t)}async remove(){const t=this.collection.store.ditto,e=Bridge.ditto.handleFor(t);return t.deferCloseAsync((async()=>{const t=this.query;return(await j((async()=>{const n=await writeTransaction(e.deref()),r=await collectionRemoveQueryStr(e.deref(),this.collection.name,n,t,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);return await writeTransactionCommit(e.deref(),n),r}))).map((t=>new DocumentID(t,!0)))}))}async evict(){const t=this.collection.store.ditto,e=Bridge.ditto.handleFor(t);return t.deferCloseAsync((async()=>{const t=this.query;return(await j((async()=>{const n=await writeTransaction(e.deref()),r=await collectionEvictQueryStr(e.deref(),this.collection.name,n,t,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);return await writeTransactionCommit(e.deref(),n),r}))).map((t=>new DocumentID(t,!0)))}))}async update(t){const e=this.collection.store.ditto,n=Bridge.ditto.handleFor(e);return e.deferCloseAsync((async()=>await j((async()=>{const e=await writeTransaction(n.deref()),r=await super.updateWithTransaction(t,e);return await writeTransactionCommit(n.deref(),e),r}))))}subscribe(){const t=new Subscription(this.collection,this.query,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);return this.collection.store.ditto.subscriptionManager.add(t),t}observeLocal(t){return this._observe(t,!1)}observeLocalWithNextSignal(t){return this._observe(t,!0)}constructor(t,e,n){super(t,e,n)}_observe(t,e){const n=e?t:function wrappedHandler(e,n,r){try{return t.call(this,e,n)}finally{r()}},r=new LiveQuery(this.query,this.queryArgs,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset,this.collection,n);return this.collection.store.ditto.liveQueryManager.startLiveQuery(r),r}}class PendingIDSpecificOperation extends BasePendingIDSpecificOperation{async remove(){const t=this.collection.store.ditto,e=Bridge.ditto.handleFor(t);return t.deferCloseAsync((async()=>await j((async()=>{const t=await writeTransaction(e.deref()),n=await collectionRemove(e.deref(),this.collection.name,t,this.documentIDCBOR);return await writeTransactionCommit(e.deref(),t),n}))))}async evict(){const t=this.collection.store.ditto,e=Bridge.ditto.handleFor(t);return t.deferCloseAsync((async()=>await j((async()=>{const t=await writeTransaction(e.deref()),n=await collectionEvict(e.deref(),this.collection.name,t,this.documentIDCBOR);return await writeTransactionCommit(e.deref(),t),n}))))}async update(t){const e=this.collection.store.ditto,n=Bridge.ditto.handleFor(e);return e.deferCloseAsync((async()=>{const e=await readTransaction(n.deref()),r=await collectionGet(n.deref(),this.collection.name,this.documentIDCBOR,e);if(readTransactionFree(e),!r)throw new Error(`Can't update, document with ID '${this.documentID.toString()}' not found in collection named '${this.collection.name}'`);const i=Bridge.mutableDocument.bridge(r,(()=>new MutableDocument));t(i),Bridge.mutableDocument.unregister(i);const o=await writeTransaction(n.deref());return await collectionUpdate(n.deref(),this.collection.name,o,r),await writeTransactionCommit(n.deref(),o),i["@ditto.updateResults"].slice()}))}subscribe(){const t=new Subscription(this.collection,this.query,null,[],-1,0);return this.collection.store.ditto.subscriptionManager.add(t),t}observeLocal(t){return this._observe(t,!1)}observeLocalWithNextSignal(t){return this._observe(t,!0)}constructor(t,e){super(t,e)}_observe(t,e){const n=new LiveQuery(this.query,null,null,[],-1,0,this.collection,((n,r,i)=>{if(n.length>1){const t=n.map((t=>t.id.toBase64String()));throw new Error(`Internal inconsistency, single document live query returned more than one document. Query: ${this.query}, documentIDs: ${t.join(", ")}.`)}if(!1===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=n[0]||null,a=!0===r.isInitial?void 0:r.oldDocuments[0],s=new SingleDocumentLiveQueryEvent(r.isInitial,a);if(e)t(o,s,i);else try{t(o,s)}finally{i()}}));return this.collection.store.ditto.liveQueryManager.startLiveQuery(n),n}}class Collection{find(t,e){return new PendingCursorOperation(t,null!=e?e:null,this)}findAll(){return this.find("true")}findByID(t){const e=t instanceof DocumentID?t:new DocumentID(t);return new PendingIDSpecificOperation(e,this)}async upsert(t,e={}){const n=this.store.ditto,r=Bridge.ditto.handleFor(n);return n.deferCloseAsync((async()=>{var n;const i=null!==(n=e.writeStrategy)&&void 0!==n?n:"merge",o=desugarJSObject(t,!0),a=CBOR.encode(o),s=await j((async()=>await collectionInsertValue(r.deref(),this.name,a,i,void 0)));return new DocumentID(s,!0)}))}async newAttachment(t,e={}){const n=this.store.ditto,r=Bridge.ditto.handleFor(n);return n.deferCloseAsync((async()=>{const{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.deref(),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={_id:i,_len:o,_meta:{...e}};s[g]=b.attachment;const c=new AttachmentToken(s),d=new Attachment(n,c);return Bridge.attachment.bridge(a,(()=>d))}))}fetchAttachment(t,e){if(null==t||!(t instanceof AttachmentToken))throw new Error(`Invalid attachment token: ${t}`);const n=this.store.ditto;return n.deferClose((()=>n.attachmentFetcherManager.startAttachmentFetcher(t,e)))}constructor(t,e){this.name=t,this.store=e}findByIDCBOR(t){const e=new DocumentID(t,!0,!0);return new PendingIDSpecificOperation(e,this)}}class CollectionsEvent{static initial(t){return new CollectionsEvent({isInitial:!0,collections:t,oldCollections:[],insertions:[],deletions:[],updates:[],moves:[]})}constructor(t){this.isInitial=t.isInitial,this.collections=t.collections,this.oldCollections=t.oldCollections,this.insertions=t.insertions,this.deletions=t.deletions,this.updates=t.updates,this.moves=t.moves}}class PendingCollectionsOperation{sort(t,e="ascending"){return this.pendingCursorOperation.sort(t,e),this}offset(t){return this.pendingCursorOperation.offset(t),this}limit(t){return this.pendingCursorOperation.limit(t),this}subscribe(){return this.pendingCursorOperation.subscribe()}observeLocal(t){return this._observe(t,!1)}observeLocalWithNextSignal(t){return this._observe(t,!0)}async exec(){return collectionsFromDocuments(await this.pendingCursorOperation.exec(),this.store)}constructor(t){this.store=t,this.pendingCursorOperation=new PendingCursorOperation("true",null,new Collection("__collections",t))}then(t,e){return this.exec().then(t,e)}_observe(t,e){const n=new WeakRef(this.store);return this.pendingCursorOperation._observe((function(r,i,o){const a=n.deref();if(!a)return;const s=collectionsFromDocuments(r,a);let c;if(!0===i.isInitial)c=CollectionsEvent.initial(s);else{const t=collectionsFromDocuments(i.oldDocuments,a);c=new CollectionsEvent({isInitial:!1,collections:s,oldCollections:t,insertions:i.insertions,deletions:i.deletions,updates:i.updates,moves:i.moves})}e?t(c,o):t(c)}),e)}}function collectionsFromDocuments(t,e){const n=[];for(const r of t){const t=r.at("name").value;void 0!==t&&"string"==typeof t&&n.push(new Collection(t,e))}return n}class ExperimentalSubscriptionManager{constructor(t){this.subscriptions={},this.finalizationRegistry=new FinalizationRegistry(this.removeWithContextInfo.bind(this)),this.ditto=t}addSubscription(t){if(null!=this.subscriptions[t.contextInfo.id])throw new Error(`Internal inconsistency, tried to add a subscription that is already tracked: ${t.contextInfo.id}`);const e=Bridge.ditto.handleFor(this.ditto);this.ditto.deferClose((()=>{experimentalAddDqlSubscription(e.deref(),t.query,t.queryArgsCBOR)})),this.subscriptions[t.contextInfo.id]=new WeakRef(t),this.finalizationRegistry.register(t,t.contextInfo,t)}removeSubscription(t){if(null==this.subscriptions[t.contextInfo.id])throw new Error(`Internal inconsistency, tried to remove a subscription that is not tracked: ${t.contextInfo.id}`);this.finalizationRegistry.unregister(t),delete this.subscriptions[t.contextInfo.id],this.removeWithContextInfo(t.contextInfo)}close(){Logger.debug(`ExperimentalSubscriptionManager.close() with ${this.subscriptions.length} queries`),this.ditto.deferClose((()=>{var t;for(const e of Object.values(this.subscriptions))null===(t=e.deref())||void 0===t||t.cancel()}))}removeWithContextInfo(t){const e=Bridge.ditto.handleFor(this.ditto);this.ditto.deferClose((()=>{experimentalRemoveDqlSubscription(e.deref(),t.query,t.queryArgsCBOR),delete this.subscriptions[t.id]}))}}class ExperimentalSubscription{cancel(){this.isCancelled||(this.isCancelled=!0,this.manager.removeSubscription(this))}constructor(t,e,n){this.isCancelled=!1,this.query=e,this.queryArgsCBOR=n,this.contextInfo={id:generateEphemeralToken(),query:e,queryArgsCBOR:n},this.manager=t,t.addSubscription(this)}}class ExperimentalStore{constructor(t){this.ditto=t,this.subscriptionManager=new ExperimentalSubscriptionManager(this.ditto)}close(){this.subscriptionManager.close()}async execute(t){Logger.debug(`ExperimentalStore.execute(query = ${t})`);const e=this.ditto,n=Bridge.ditto.handleFor(e);return e.deferCloseAsync((async()=>(await j((async()=>await experimentalExecQueryStr(n.deref(),null,t,null)))).map((t=>Bridge.document.bridge(t)))))}subscribe(t){return Logger.debug(`ExperimentalStore.subscribe(query = ${t})`),new ExperimentalSubscription(this.subscriptionManager,t,null)}}class WriteTransactionPendingCursorOperation extends BasePendingCursorOperation{sort(t,e="ascending"){return super.sort(t,e)}offset(t){return super.offset(t)}limit(t){return super.limit(t)}async remove(){const t=this.collection.store.ditto,e=Bridge.ditto.handleFor(t);return t.deferCloseAsync((async()=>{const t=this.query,n=this.collection.writeTransaction,r=(await j((async()=>collectionRemoveQueryStr(e.deref(),this.collection.name,n.writeTransactionPointer,t,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset)))).map((t=>new DocumentID(t,!0)));return r.forEach((t=>{n.addResult("removed",t,this.collection.name)})),r}))}async evict(){const t=this.collection.store.ditto,e=Bridge.ditto.handleFor(t);return t.deferCloseAsync((async()=>{const t=this.query,n=this.collection.writeTransaction,r=(await j((async()=>collectionEvictQueryStr(e.deref(),this.collection.name,n.writeTransactionPointer,t,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset)))).map((t=>new DocumentID(t,!0)));return r.forEach((t=>{n.addResult("evicted",t,this.collection.name)})),r}))}async update(t){const e=this.collection.writeTransaction,n=await super.updateWithTransaction(t,e.writeTransactionPointer);return n.keys().forEach((t=>{e.addResult("updated",t,this.collection.name)})),n}constructor(t,e,n){super(t,e,n)}}class WriteTransactionPendingIDSpecificOperation extends BasePendingIDSpecificOperation{async remove(){const t=this.collection.store.ditto,e=Bridge.ditto.handleFor(t);return t.deferCloseAsync((async()=>{const t=this.collection.writeTransaction,n=await j((async()=>collectionRemove(e.deref(),this.collection.name,t.writeTransactionPointer,this.documentIDCBOR)));return t.addResult("removed",this.documentID,this.collection.name),n}))}async evict(){const t=this.collection.store.ditto,e=Bridge.ditto.handleFor(t);return t.deferCloseAsync((async()=>{const t=this.collection.writeTransaction,n=await j((async()=>await collectionEvict(e.deref(),this.collection.name,t.writeTransactionPointer,this.documentIDCBOR)));return t.addResult("evicted",this.documentID,this.collection.name),n}))}async update(t){const e=this.collection.store.ditto,n=Bridge.ditto.handleFor(e);return e.deferCloseAsync((async()=>{const e=this.collection.writeTransaction,r=await readTransaction(n.deref()),i=await collectionGet(n.deref(),this.collection.name,this.documentIDCBOR,r);if(readTransactionFree(r),!i)throw new Error(`Can't update, document with ID '${this.documentID.toString()}' not found in collection named '${this.collection.name}'`);const o=Bridge.mutableDocument.bridge(i,(()=>new MutableDocument));return t(o),Bridge.mutableDocument.unregister(o),await collectionUpdate(n.deref(),this.collection.name,e.writeTransactionPointer,i),e.addResult("updated",this.documentID,this.collection.name),o["@ditto.updateResults"].slice()}))}constructor(t,e){super(t,e)}}class WriteTransactionCollection{find(t,e){return new WriteTransactionPendingCursorOperation(t,null!=e?e:null,this)}findAll(){return this.find("true")}findByID(t){const e=t instanceof DocumentID?t:new DocumentID(t);return new WriteTransactionPendingIDSpecificOperation(e,this)}async upsert(t,e={}){const n=this.store.ditto,r=Bridge.ditto.handleFor(n);return n.deferCloseAsync((async()=>{var n;const i=null!==(n=e.writeStrategy)&&void 0!==n?n:"merge",o=desugarJSObject(t,!0),a=CBOR.encode(o),s=await j((async()=>await collectionInsertValue(r.deref(),this.name,a,i,this.writeTransaction.writeTransactionPointer))),c=new DocumentID(s,!0);return this.writeTransaction.addResult("inserted",c,this.name),new DocumentID(s,!0)}))}findByIDCBOR(t){const e=new DocumentID(t,!0,!0);return new WriteTransactionPendingIDSpecificOperation(e,this)}constructor(t,e,n){this.name=t,this.store=e,this.writeTransaction=n}}class WriteTransaction{static async init(t){return t.deferCloseAsync((async()=>{const e=Bridge.ditto.handleFor(t),n=await writeTransaction(e.deref());return new WriteTransaction(t,n)}))}scoped(t){if("string"!=typeof t)throw new Error("Collection name must be a string");return new WriteTransactionCollection(t,this.ditto.store,this)}async commit(){const t=this.ditto,e=Bridge.ditto.handleFor(t);return t.deferCloseAsync((async()=>writeTransactionCommit(e.deref(),this.writeTransactionPointer)))}async rollback(){const t=this.ditto,e=Bridge.ditto.handleFor(t);return t.deferCloseAsync((async()=>writeTransactionRollback(e.deref(),this.writeTransactionPointer)))}addResult(t,e,n){this.results.push({type:t,docID:e,collectionName:n})}constructor(t,e){this.writeTransactionPointer=e,this.ditto=t,this.results=[]}}class Store{collection(t){return new Collection(t,this)}collections(){return new PendingCollectionsOperation(this)}collectionNames(){const t=this.ditto,e=Bridge.ditto.handleFor(t);return t.deferClose((()=>dittoGetCollectionNames(e.deref())))}async write(t){return this.ditto.deferCloseAsync((async()=>{const e=await WriteTransaction.init(this.ditto);try{await t(e)}catch(t){throw await e.rollback(),Logger.warning(`Transaction rolled back due to an error: ${null==t?void 0:t.message}`),t}return await e.commit(),e.results}))}constructor(t){this.ditto=t,this.experimental=new ExperimentalStore(t)}close(){this.experimental.close()}async registerLiveQueryWebhook(t,e,n){const r=this.ditto,i=Bridge.ditto.handleFor(r);return r.deferCloseAsync((async()=>{const r=validateQuery(e),o=await liveQueryWebhookRegister(i.deref(),t,r,[],0,0,n);return new DocumentID(o,!0)}))}}class Presence{get graph(){const t=this.ditto,e=Bridge.ditto.handleFor(t);return t.deferClose((()=>{const t=dittoPresenceV3(e.deref());return JSON.parse(t)}))}observe(t){const e=this.observerManager.addObserver(t),n=new Observer(this.observerManager,e,{stopsWhenFinalized:!0});return t(this.graph),n}constructor(t){this.ditto=t,this.observerManager=new ObserverManager("PresenceObservation",{keepAlive:t.keepAlive,register:t=>{const e=this.ditto,n=Bridge.ditto.handleFor(e);e.deferClose((()=>{dittoRegisterPresenceV3Callback(n.deref(),t)}))},unregister:()=>{const t=this.ditto,e=Bridge.ditto.handleFor(t);t.deferClose((()=>{dittoClearPresenceV3Callback(e.deref())}))},process:t=>[JSON.parse(t)]})}close(){this.observerManager.close()}}class LiveQueryManager{constructor(t,e){this.finalizationRegistry=new FinalizationRegistry(this.finalize),this.ditto=t,this.keepAlive=e,this.liveQueriesByID={}}startLiveQuery(t){const e=this.ditto,n=Bridge.ditto.handleFor(e);e.deferCloseAsync((async()=>{const r=t.liveQueryID;if(!r)throw new Error("Internal inconsistency, tried to add a live query that doesn't have a live query ID (probably stopped).");if(this.liveQueriesByID[r])throw new Error("Internal inconsistency, tried to add a live query with an ID that has already been added.");const i=new WeakRef(t);return this.liveQueriesByID[r]=i,this.finalizationRegistry.register(t,r,this.finalize),t.liveQueryManager=this,e.keepAlive.retain(`LiveQuery.${r}`),new Promise(((t,e)=>{step((async()=>{await liveQueryStart(n.deref(),r),t()}))}))}))}stopLiveQuery(t){this.finalizationRegistry.unregister(t);const e=t.liveQueryID;if(!e)throw new Error("Internal inconsistency, tried to remove a live query that doesn't have a live query ID (probably stopped).");t.liveQueryManager=null,this.stopLiveQueryWithID(e)}close(){for(const t in this.liveQueriesByID){const e=this.liveQueriesByID[t].deref();e&&this.stopLiveQuery(e)}}stopLiveQueryWithID(t){const e=this.ditto,n=Bridge.ditto.handleFor(e);e.deferClose((()=>{liveQueryStop(n.deref(),t),this.keepAlive.release(`LiveQuery.${t}`),delete this.liveQueriesByID[t]}))}finalize(t){this.stopLiveQueryWithID(t)}}class PresenceManager{constructor(t){this.ditto=t,this.isClosed=!1,this.isRegistered=!1,this.currentRemotePeers=[],this.callbacksByPresenceToken={}}addObserver(t){if(this.isClosed)throw new Error("Internal inconsistency, can't add presence observer, observer mananger close()-ed.");this.registerIfNeeded();const e=generateEphemeralToken();return this.callbacksByPresenceToken[e]=t,this.ditto.keepAlive.retain(`PresenceObservation.${e}`),t(this.currentRemotePeers),e}removeObserver(t){const e=this.callbacksByPresenceToken[t];if(void 0===e)throw new Error(`Can't remove presence observer, token '${t}' has never been registered before.`);null!==e&&void 0!==this.callbacksByPresenceToken[t]&&(this.ditto.keepAlive.release(`PresenceObservation.${t}`),this.callbacksByPresenceToken[t]=null,this.unregisterIfNeeded())}hasObserver(t){return void 0!==this.callbacksByPresenceToken[t]}close(){this.isClosed=!0;for(const t in this.callbacksByPresenceToken)this.removeObserver(t)}hasObservers(){return Object.keys(this.callbacksByPresenceToken).length>0}registerIfNeeded(){const t=this.ditto,e=Bridge.ditto.handleFor(this.ditto);t.deferClose((()=>{if(!this.isRegistered){this.isRegistered=!0;const t=dittoPresenceV1(e.deref());this.currentRemotePeers=this.decode(t).sort(this.compareRemotePeers),dittoRegisterPresenceV1Callback(e.deref(),this.handlePresenceV1Callback.bind(this))}}))}unregisterIfNeeded(){const t=this.ditto,e=Bridge.ditto.handleFor(t);t.deferClose((()=>{!this.hasObservers()&&this.isRegistered&&(this.isRegistered=!1,dittoClearPresenceCallback(e.deref()),this.currentRemotePeers=[])}))}handlePresenceV1Callback(t){const e=this.decode(t).sort(this.compareRemotePeers);this.currentRemotePeers=e,this.notify()}notify(){if(!this.isClosed)for(const t in this.callbacksByPresenceToken){(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}}))}compareRemotePeers(t,e){return 0===t.connections.length&&e.connections.length>0?1:t.connections.length>0&&0===e.connections.length||t.deviceName<e.deviceName?-1:t.deviceName>e.deviceName?1:0}}class TransportConditionsManager extends ObserverManager{constructor(t){super("TransportConditionsObservation",{keepAlive:t.keepAlive}),this.ditto=t}register(t){const e=this.ditto,n=Bridge.ditto.handleFor(e);return e.deferClose((()=>dittoRegisterTransportConditionChangedCallback(n.deref(),t)))}unregister(){const t=this.ditto,e=Bridge.ditto.handleFor(t);return t.deferClose((()=>dittoRegisterTransportConditionChangedCallback(e.deref(),null)))}process(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,this.mdnsClientTransportPointer=null,this.mdnsServerAdvertiserPointer=null;const e={identity:t.identity,transportConfig:new TransportConfig,ditto:t,isWebValid:!1,isX509Valid:!1,isSyncActive:!1};this.ditto=t,this.parameters=e,this.state=stateFrom(e)}update(t){this.parameters={...t};const e=this.state,n=stateFrom(this.parameters);this.updatePeerToPeerBluetoothLE(e,n),this.updatePeerToPeerAWDL(e,n),this.updatePeerToPeerLAN(e,n),this.updateListenTCP(e,n),this.updateListenHTTP(e,n),this.updateConnectTCPServers(e,n),this.updateConnectWebsocketURLs(e,n),this.updateGlobal(e,n),this.updateConnectRetryInterval(e,n),this.state=n}close(){if(this.parameters.isSyncActive)throw new Error("Internal inconsistency, can't close sync object while sync is active, please 'stopSync()' first.")}updatePeerToPeerBluetoothLE(t,e){const n=this.ditto,r=Bridge.ditto.handleFor(n);n.deferClose((()=>{const n=t.effectiveTransportConfig.peerToPeer.bluetoothLE,i=e.effectiveTransportConfig.peerToPeer.bluetoothLE,o=!n.isEnabled&&i.isEnabled,a=n.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.");o&&(this.bluetoothLETransportPointer=function bleCreate(t){throw new Error("Can't create BluetoothLE handle, P2P BluetoothLE is not supported on this platform.")}(r.deref())),a&&(!function 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=this.ditto,r=Bridge.ditto.handleFor(n);n.deferClose((()=>{const n=t.effectiveTransportConfig.peerToPeer.awdl,i=e.effectiveTransportConfig.peerToPeer.awdl,o=!n.isEnabled&&i.isEnabled,a=n.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.");o&&(this.awdlTransportPointer=function awdlCreate(t){throw new Error("Can't create AWDL handle, P2P AWDL transport is not supported on this platform.")}(r.deref())),a&&(!function 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=this.ditto,r=Bridge.ditto.handleFor(n);n.deferClose((()=>{const n=t.effectiveTransportConfig.peerToPeer.lan,i=e.effectiveTransportConfig.peerToPeer.lan;n.isEnabled&&(n.isMdnsEnabled&&(!function lanDestroy(t){throw new Error("Can't destroy LAN handle, P2P LAN transport is not supported on this platform.")}(this.lanTransportPointer),delete this.lanTransportPointer),n.isMulticastEnabled&&function dittoRemoveMulticastTransport(t){return ensureInitialized(),(void 0)(t)}(r.deref())),i.isEnabled&&(i.isMdnsEnabled&&(this.lanTransportPointer=function lanCreate(t){throw new Error("Can't create LAN handle, P2P LAN transport is not supported on this platform.")}(r.deref())),i.isMulticastEnabled&&function dittoAddMulticastTransport(t){return ensureInitialized(),(void 0)(t)}(r.deref()))}))}updateListenTCP(t,e){const n=this.ditto,r=Bridge.ditto.handleFor(n);n.deferClose((()=>{const n=t.effectiveTransportConfig.listen.tcp,i=e.effectiveTransportConfig.listen.tcp;TransportConfig.areListenTCPsEqual(i,n)||(n.isEnabled&&function dittoStopTCPServer(t){return ensureInitialized(),(void 0)(t)}(r.deref()),i.isEnabled&&function dittoStartTCPServer(t,e){return ensureInitialized(),(void 0)(t,bytesFromString(e))}(r.deref(),`${i.interfaceIP}:${i.port}`))}))}updateListenHTTP(t,e){const n=this.ditto,r=Bridge.ditto.handleFor(n);n.deferClose((()=>{const n=t.effectiveTransportConfig.listen.http,i=e.effectiveTransportConfig.listen.http;TransportConfig.areListenHTTPsEqual(n,i)||(n.isEnabled&&function dittoStopHTTPServer(t){return ensureInitialized(),(void 0)(t)}(r.deref()),i.isEnabled&&function dittoStartHTTPServer(t,e,n,r,i,o){return ensureInitialized(),(void 0)(t,bytesFromString(e),bytesFromString(n),r,bytesFromString(i),bytesFromString(o))}(r.deref(),`${i.interfaceIP}:${i.port}`,i.staticContentPath||null,i.websocketSync?"Enabled":"Disabled",i.tlsCertificatePath||null,i.tlsKeyPath||null))}))}updateConnectTCPServers(t,e){const n=this.ditto,r=Bridge.ditto.handleFor(n);n.deferClose((()=>{const t=e.effectiveTransportConfig.connect.tcpServers;!function dittoSetStaticTCPClients(t,e){if(ensureInitialized(),e.length>0)throw new Error(`Web variant of Ditto does not support connecting to TCP servers: ${e.join(", ")}`)}(r.deref(),t)}))}updateConnectWebsocketURLs(t,e){const n=this.ditto,r=Bridge.ditto.handleFor(n);n.deferClose((()=>{const t=e.effectiveTransportConfig.connect.websocketURLs,n=e.effectiveTransportConfig.global.routingHint;dittoSetStaticWebsocketClients(r.deref(),t,n)}))}updateGlobal(t,e){const n=this.ditto,r=Bridge.ditto.handleFor(n);n.deferClose((()=>{t.effectiveTransportConfig.global.syncGroup!==e.effectiveTransportConfig.global.syncGroup&&dittoSetSyncGroup(r.deref(),e.effectiveTransportConfig.global.syncGroup)}))}updateConnectRetryInterval(t,e){const n=this.ditto,r=Bridge.ditto.handleFor(n);n.deferClose((()=>{dittoSetConnectRetryInterval(r.deref(),e.effectiveTransportConfig.connect.retryInterval)}))}}function stateFrom(t){const e=t.ditto,n=Bridge.ditto.handleFor(e);return e.deferClose((()=>{var e;const r=t.transportConfig.copy(),i=t.identity,o=t.isSyncActive,a=t.isX509Valid,s=t.isWebValid;let c,d;r.connect.tcpServers,r.connect.websocketURLs;let l=!1;"onlinePlayground"!==i.type&&"onlineWithAuthentication"!==i.type||(c=i.appID,d=null!==(e=i.customDittoCloudURL)&&void 0!==e?e:null,l=!i.hasOwnProperty("enableDittoCloudSync")||i.enableDittoCloudSync);const u=[],_=(n.deref(),!1),g=(n.deref(),!1),h=(n.deref(),!1);if(r.peerToPeer.bluetoothLE.isEnabled&&!_&&u.push("BluetoothLE"),r.peerToPeer.awdl.isEnabled&&!g&&u.push("AWDL"),r.peerToPeer.lan.isEnabled&&!h&&u.push("LAN"),u.length>0)throw new Error(`The following P2P transports are enabled in the transport config but are not supported in the current environment: ${u.join(", ")}`);if(o&&a||(r.peerToPeer.bluetoothLE.isEnabled=!1,r.peerToPeer.awdl.isEnabled=!1,r.peerToPeer.lan.isEnabled=!1,r.listen.tcp.isEnabled=!1,r.connect.tcpServers=[]),o&&s||(r.connect.websocketURLs=[]),o||(r.listen.http.isEnabled=!1),o&&s&&l){const t=null!=d?d:function defaultDittoCloudURL(t){return`wss://${t}.${k}`}(c);r.connect.websocketURLs.push(t)}return{underlyingSyncParameters:t,effectiveTransportConfig:r.freeze()}}))}class SubscriptionManager{constructor(t){this.ditto=t,this.subscriptions={},this.finalizationRegistry=new FinalizationRegistry(this.removeWithContextInfo.bind(this))}add(t){const e=this.ditto,n=Bridge.ditto.handleFor(e),r=t.contextInfo;e.deferClose((async()=>{this.subscriptions[r.id]=new WeakRef(t),this.finalizationRegistry.register(t,t.contextInfo,t),addSubscription(n.deref(),r.collectionName,r.query,r.queryArgsCBOR,r.orderBys,r.limit,r.offset)}))}remove(t){if(null==this.subscriptions[t.contextInfo.id])throw new Error(`Internal inconsistency, tried to remove a subscription that is not tracked: ${t.contextInfo.id}`);this.finalizationRegistry.unregister(t),this.removeWithContextInfo(t.contextInfo)}close(){this.ditto.deferClose((async()=>{for(const t in this.subscriptions){const e=this.subscriptions[t].deref();null!=e&&this.remove(e)}}))}removeWithContextInfo(t){const e=this.ditto,n=Bridge.ditto.handleFor(e);e.deferClose((()=>{delete this.subscriptions[t.id],removeSubscription(n.deref(),t.collectionName,t.query,t.queryArgsCBOR,t.orderBys,t.limit,t.offset)}))}}class AttachmentFetcher{stop(){step((async()=>{await this.manager.stopAttachmentFetcher(this),null!=this.rejectPendingFetch&&this.rejectPendingFetch()}))}then(t,e){return this.attachment.then(t,e)}constructor(t,e,n,r){this.cancelTokenPromise=null,this.rejectPendingFetch=null,this.ditto=t,this.token=e,this.manager=n,this.id=generateEphemeralToken();const i=r||function(){},o=Bridge.ditto.handleFor(t);this.attachment=new Promise(((t,n)=>{this.rejectPendingFetch=()=>{n(new Error("Attachment fetch was canceled"))},this.cancelTokenPromise=dittoResolveAttachment(o.deref(),e.id,{onComplete:e=>{const n=new Attachment(this.ditto,this.token);Bridge.attachment.bridge(e,(()=>n)),i({type:"Completed",attachment:n}),this.rejectPendingFetch=null,t(n)},onProgress:(t,e)=>{i({type:"Progress",totalBytes:e,downloadedBytes:t})},onDelete:()=>{i({type:"Deleted"}),this.rejectPendingFetch=null,t(null)}},(()=>{}))}))}}class AttachmentFetcherManager{constructor(t){this.contextInfoByID={},this.finalizationRegistry=new FinalizationRegistry(this.stopWithContextInfo),this.ditto=t}startAttachmentFetcher(t,e){return this.ditto.deferClose((()=>{const n=new AttachmentFetcher(this.ditto,t,this,e),r={id:n.id,attachmentTokenID:t.id,cancelTokenPromise:n.cancelTokenPromise,attachmentFetcher:new WeakRef(n)};this.finalizationRegistry.register(n,r,n),this.contextInfoByID[n.id]=r;const resetCancelToken=()=>{null!=this.contextInfoByID[n.id]&&(this.contextInfoByID[n.id].cancelTokenPromise=null)};return n.attachment.then((t=>(resetCancelToken(),t)),(t=>(resetCancelToken(),t))),this.ditto.keepAlive.retain(`AttachmentFetcher.${n.id})`),n}))}async stopAttachmentFetcher(t){this.finalizationRegistry.unregister(t);const e=this.contextInfoByID[t.id];if(null==e)throw new Error(`Internal inconsistency: cannot stop attachment fetcher ${t.id}, which is not registered.`);await this.stopWithContextInfo(e)}close(){this.ditto.deferCloseAsync((async()=>{const t=Object.values(this.contextInfoByID).map((async t=>{const e=t.attachmentFetcher.deref();null!=e&&await this.stopAttachmentFetcher(e)}));await Promise.all(t)}))}stopWithContextInfo(t){const e=Bridge.ditto.handleFor(this.ditto);return this.ditto.deferCloseAsync((async()=>{if(null==this.contextInfoByID[t.id])throw new Error(`Internal inconsistency: attachment fetcher ${t.id} not found in active attachment fetchers.`);delete this.contextInfoByID[t.id],this.ditto.keepAlive.release(`AttachmentFetcher.${t.id})`);const n=await t.cancelTokenPromise;n&&dittoCancelResolveAttachment(e.deref(),t.attachmentTokenID,n)}))}}class Ditto{get sdkVersion(){const t=Bridge.ditto.handleFor(this);return this.deferClose((()=>dittoGetSDKVersion(t.deref())))}constructor(t,e){if(this.isClosed=!1,this.deferCloseAllowed=!0,this.isWebValid=!1,this.isX509Valid=!1,this.pendingOperations=new Set,!Ditto.isEnvironmentSupported())throw new Error("Ditto does not support this JavaScript environment. Please consult the Ditto JavaScript documentation for a list of supported environments and browsers. You can use `Ditto.isEnvironmentSupported()` to run this check anytime.");const n=null!=t?t:{type:"offlinePlayground",appID:""},r=e&&e.trim().length>0?e:"ditto",i=Object.freeze(this.validateIdentity(n));this.identity=Object.freeze(i),this.path=r,this.deviceName=navigator.userAgent,this.keepAlive=new KeepAlive;const o=uninitializedDittoMake(r);let a=null;const s=new WeakRef(this),c=dittoMake(o,(()=>{var t,e,n;if("offlinePlayground"===i.type)return dittoIdentityConfigMakeOfflinePlayground(i.appID,null!==(t=i.siteID)&&void 0!==t?t:0);if("manual"===i.type)return dittoIdentityConfigMakeManual(i.certificate);if("sharedKey"===i.type)return dittoIdentityConfigMakeSharedKey(i.appID,i.sharedKey,i.siteID);if("onlinePlayground"===i.type){const t=null!==(e=i.customAuthURL)&&void 0!==e?e:defaultAuthURL(i.appID);return dittoIdentityConfigMakeOnlinePlayground(i.appID,i.token,t)}if("onlineWithAuthentication"===i.type){const t=null!==(n=i.customAuthURL)&&void 0!==n?n:defaultAuthURL(i.appID);return dittoIdentityConfigMakeOnlineWithAuthentication(i.appID,t)}throw new Error(`Can't create Ditto, unsupported identity type: ${i}`)})());dittoAuthClientSetValidityListener(c,(function(...t){const e=s.deref();null==e||e.isClosed?Logger.info("Ditto is closed, ignoring auth client validity change"):e.authClientValidityChanged(...t)}));const d=dittoAuthClientIsWebValid(c),l=dittoAuthClientIsX509Valid(c),u=dittoAuthClientGetSiteID(c);if(Bridge.ditto.bridge(c,this),"onlineWithAuthentication"===i.type){this.auth=new OnlineAuthenticator(this.keepAlive,this,i.authHandler);dittoAuthSetLoginProvider(c,dittoAuthClientMakeLoginProvider((function(t){const e=s.deref();e?e.auth?e.auth["@ditto.authenticationExpiring"](t):a=t:Logger.warning("Internal inconsistency, LoginProvider callback fired after the corresponding Ditto instance has been deallocated.")})))}else"onlinePlayground"===i.type?this.auth=new OnlineAuthenticator(this.keepAlive,this,{authenticationRequired:function(t){},authenticationExpiringSoon:function(t,e){}}):this.auth=new NotAvailableAuthenticator(this.keepAlive);const _=this.makeDefaultTransportConfig();this.siteID=u,this.transportConfig=_.copy().freeze(),this.isX509Valid=l,this.isWebValid=d,this.sync=new Sync(this),this.sync.update({isSyncActive:!1,isX509Valid:l,isWebValid:d,identity:i,ditto:this,transportConfig:_}),this.isActivated=true,this.store=new Store(this),this.presence=new Presence(this),this.presenceManager=new PresenceManager(this),this.liveQueryManager=new LiveQueryManager(this,this.keepAlive),this.attachmentFetcherManager=new AttachmentFetcherManager(this),this.transportConditionsManager=new TransportConditionsManager(this),this.subscriptionManager=new SubscriptionManager(this),null!==a&&this.auth["@ditto.authenticationExpiring"](a)}static disableDeadlockDetection(){}static hasDeadlockDetection(){return!1}static isEnvironmentSupported(){const t="undefined"!=typeof window&&(-1!==window.navigator.userAgent.indexOf("MSIE")||window.navigator.appVersion.indexOf("Trident/")>-1);let e;try{e=checkAPIs()}catch(t){throw new Error(`Error checking environment support: ${t}`)}return!t&&e}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,ditto:this})}updateTransportConfig(t){const e=this.transportConfig.copy();return t(e),this.setTransportConfig(e),this}startSync(){this.setSyncActive(!0)}stopSync(){this.setSyncActive(!1)}observePeers(t){Logger.warning("`ditto.observePeers()` is deprecated, please use `ditto.presence.observe()` instead.");const e=this.presenceManager.addObserver(t);return new Observer(this.presenceManager,e,{stopsWhenFinalized:!0})}observeTransportConditions(t){const e=this.transportConditionsManager.addObserver(t);return new Observer(this.transportConditionsManager,e,{stopsWhenFinalized:!0})}runGarbageCollection(){const t=Bridge.ditto.handleFor(this);return this.deferClose((()=>{dittoRunGarbageCollection(t.deref())}))}disableSyncWithV3(){const t=Bridge.ditto.handleFor(this);return this.deferClose((()=>{dittoDisableSyncWithV3(t.deref())}))}async close(){if(this.isClosed)return;if(this.isClosed=!0,this.stopSync(),this.store.close(),this.presence.close(),this.auth.close(),this.sync.close(),this.presenceManager.close(),this.liveQueryManager.close(),this.attachmentFetcherManager.close(),this.transportConditionsManager.close(),this.subscriptionManager.close(),this.keepAlive.isActive)throw new Error("Internal inconsistency, still kept alive after the Ditto object has been close()-ed. ");do{await Promise.allSettled(this.pendingOperations)}while(this.pendingOperations.size>0);this.deferCloseAllowed=!1;const t=Bridge.ditto.handleFor(this);await dittoShutdown(t.deref()),Bridge.ditto.markAsClosed(this)}get numPendingOperations(){return this.pendingOperations.size}deferClose(t){if(!this.deferCloseAllowed)throw new Error("Can't perform operation using a Ditto instance that has been closed.");return t()}async deferCloseAsync(t){if(!this.deferCloseAllowed)throw new Error("Can't perform operation using a Ditto instance that has been closed.");const e=t();let n;this.pendingOperations.add(e);try{n=await e}finally{this.pendingOperations.delete(e)}return n}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,ditto:this})}validateIdentity(t){const e={...t};t.appName;const n=t.appID;if(!["offlinePlayground","sharedKey","manual","onlinePlayground","onlineWithAuthentication"].includes(t.type))throw new Error(`Can't create Ditto instance, unknown identity type: ${t.type}`);if(("offlinePlayground"===t.type||"sharedKey"===t.type||"onlinePlayground"===t.type||"onlineWithAuthentication"===t.type)&&void 0===n)throw new Error("Property .appID must be given for identity, but isn't.");if(void 0!==n&&"string"!=typeof n)throw new Error(`Property .appID must be be of type string, but is of type '${typeof n}': ${n}`);if(("offlinePlayground"===t.type||"sharedKey"===t.type)&&void 0!==t.siteID){const e=t.siteID;if(!("number"==typeof e||"bigint"==typeof e))throw new Error("Can't create Ditto instance, siteID must be a number or BigInt");if(e<0)throw new Error("Can't create Ditto instance, siteID must be >= 0");if(e>BigInt("0xffffffffffffffff"))throw new Error("Can't create Ditto instance, siteID must be < 2^64")}if(t.type,t.type,"onlinePlayground"===t.type){const e=t.token;if(void 0===e)throw new Error("Property .token must be given for identity but isn't. You can find the corresponding token on the Ditto Portal.");if(void 0!==e&&"string"!=typeof e)throw new Error(`Property .token of identity must be be of type string, but is of type '${typeof e}': ${e}`)}return t.type,e}setSyncActive(t){const e=Bridge.ditto.handleFor(this);this.deferClose((()=>{if(t&&F.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"),this.isSyncActive=t;const n=this.isWebValid,r=this.isX509Valid,i=this.identity,o=this.transportConfig;dittoSetDeviceName(e.deref(),this.deviceName),this.sync.update({identity:i,transportConfig:o,isWebValid:n,isX509Valid:r,isSyncActive:!!t,ditto:this})}))}makeDefaultTransportConfig(){const t=Bridge.ditto.handleFor(this);return this.deferClose((()=>{const e=new TransportConfig;return t.deref(),t.deref(),t.deref(),e.freeze()}))}}const checkAPIs=t=>{const e=t||globalThis||global||window;return["BigInt","WeakRef","FinalizationRegistry"].every((t=>!!e[t]))};Bridge.attachment.registerType(Attachment),Bridge.document.registerType(Document),Bridge.mutableDocument.registerType(MutableDocument),Bridge.staticTCPClient.registerType(class StaticTCPClient{}),Bridge.websocketClient.registerType(class WebsocketClient{}),Bridge.ditto.registerType(Ditto),t.Attachment=Attachment,t.AttachmentFetcher=AttachmentFetcher,t.AttachmentToken=AttachmentToken,t.Authenticator=Authenticator,t.BasePendingCursorOperation=BasePendingCursorOperation,t.BasePendingIDSpecificOperation=BasePendingIDSpecificOperation,t.CBOR=CBOR,t.Collection=Collection,t.CollectionsEvent=CollectionsEvent,t.Counter=Counter,t.Ditto=Ditto,t.Document=Document,t.DocumentID=DocumentID,t.DocumentPath=DocumentPath,t.ExperimentalStore=ExperimentalStore,t.ExperimentalSubscription=ExperimentalSubscription,t.ExperimentalSubscriptionManager=ExperimentalSubscriptionManager,t.IdentityTypesRequiringOfflineLicenseToken=F,t.KeepAlive=KeepAlive,t.LiveQuery=LiveQuery,t.LiveQueryEventInitial=LiveQueryEventInitial,t.LiveQueryEventUpdate=LiveQueryEventUpdate,t.Logger=Logger,t.MutableCounter=MutableCounter,t.MutableDocument=MutableDocument,t.MutableDocumentPath=MutableDocumentPath,t.MutableRegister=MutableRegister,t.NotAvailableAuthenticator=NotAvailableAuthenticator,t.Observer=Observer,t.OnlineAuthenticator=OnlineAuthenticator,t.PendingCollectionsOperation=PendingCollectionsOperation,t.PendingCursorOperation=PendingCursorOperation,t.PendingIDSpecificOperation=PendingIDSpecificOperation,t.Presence=Presence,t.Register=Register,t.SingleDocumentLiveQueryEvent=SingleDocumentLiveQueryEvent,t.Store=Store,t.Subscription=Subscription,t.TransportConfig=TransportConfig,t.UpdateResult=UpdateResult,t.UpdateResultsMap=UpdateResultsMap,t.Value=class Value{constructor(t,e={}){this.value=t,this.isDefault=!!e.isDefault}},t.WriteTransaction=WriteTransaction,t.WriteTransactionCollection=WriteTransactionCollection,t.WriteTransactionPendingCursorOperation=WriteTransactionPendingCursorOperation,t.WriteTransactionPendingIDSpecificOperation=WriteTransactionPendingIDSpecificOperation,t.addressToString=function addressToString(t){return`${t.siteId}-${t.pubkey}`},t.checkAPIs=checkAPIs,t.disableDeadlockTimeoutWhenDebugging=()=>{},t.getBridgeLoad=function getBridgeLoad(){const t={};return Bridge.all.map((e=>{const n=e.deref();return n?0===n.count?null:void(t[n.type.name]=n.count):null})),t},t.init=async function init(t={}){if(!w){{const e=t.webAssemblyModule||"https://software.ditto.live/js/Ditto/4.2.3/ditto.wasm";await init$2(e),await async function init$1(){}(),initSDKVersion("Web","JavaScript","4.2.3"),loggerInit()}w=!0}},t.validateDocumentIDCBOR=validateDocumentIDCBOR,t.validateDocumentIDValue=function validateDocumentIDValue(t){if(void 0===t)throw new Error(`Invalid document ID: ${t}`);return t}}));
|
|
2
2
|
//# sourceMappingURL=ditto.umd.js.map
|