@verdant-web/store 3.2.0 → 3.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bundle/index.js +8 -8
- package/dist/bundle/index.js.map +3 -3
- package/dist/cjs/queries/QueryableStorage.js +11 -1
- package/dist/cjs/queries/QueryableStorage.js.map +1 -1
- package/dist/cjs/sync/PushPullSync.d.ts +3 -1
- package/dist/cjs/sync/PushPullSync.js +3 -2
- package/dist/cjs/sync/PushPullSync.js.map +1 -1
- package/dist/cjs/sync/ServerSyncEndpointProvider.d.ts +8 -2
- package/dist/cjs/sync/ServerSyncEndpointProvider.js +2 -1
- package/dist/cjs/sync/ServerSyncEndpointProvider.js.map +1 -1
- package/dist/cjs/sync/Sync.d.ts +1 -1
- package/dist/cjs/sync/Sync.js +3 -1
- package/dist/cjs/sync/Sync.js.map +1 -1
- package/dist/esm/queries/QueryableStorage.js +11 -1
- package/dist/esm/queries/QueryableStorage.js.map +1 -1
- package/dist/esm/sync/PushPullSync.d.ts +3 -1
- package/dist/esm/sync/PushPullSync.js +3 -2
- package/dist/esm/sync/PushPullSync.js.map +1 -1
- package/dist/esm/sync/ServerSyncEndpointProvider.d.ts +8 -2
- package/dist/esm/sync/ServerSyncEndpointProvider.js +2 -1
- package/dist/esm/sync/ServerSyncEndpointProvider.js.map +1 -1
- package/dist/esm/sync/Sync.d.ts +1 -1
- package/dist/esm/sync/Sync.js +3 -1
- package/dist/esm/sync/Sync.js.map +1 -1
- package/dist/tsconfig-cjs.tsbuildinfo +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +1 -1
- package/src/queries/QueryableStorage.ts +16 -1
- package/src/sync/PushPullSync.ts +5 -1
- package/src/sync/ServerSyncEndpointProvider.ts +10 -3
- package/src/sync/Sync.ts +3 -0
package/dist/bundle/index.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
"use strict";var Lo=Object.create;var Ct=Object.defineProperty;var No=Object.getOwnPropertyDescriptor;var Uo=Object.getOwnPropertyNames;var Vo=Object.getPrototypeOf,Ko=Object.prototype.hasOwnProperty;var $o=(i,t)=>()=>(i&&(t=i(i=0)),t);var oe=(i,t)=>()=>(t||i((t={exports:{}}).exports,t),t.exports),Yi=(i,t)=>{for(var e in t)Ct(i,e,{get:t[e],enumerable:!0})},Gi=(i,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Uo(t))!Ko.call(i,r)&&r!==e&&Ct(i,r,{get:()=>t[r],enumerable:!(n=No(t,r))||n.enumerable});return i};var Qe=(i,t,e)=>(e=i!=null?Lo(Vo(i)):{},Gi(t||!i||!i.__esModule?Ct(e,"default",{value:i,enumerable:!0}):e,i)),Je=i=>Gi(Ct({},"__esModule",{value:!0}),i);var qn=oe((Pa,Xi)=>{Xi.exports=function(t,e){var n="000000000"+t;return n.substr(n.length-e)}});var er=oe((Aa,Zi)=>{var zo=qn(),qo=typeof window=="object"?window:self,Ho=Object.keys(qo).length,Wo=navigator.mimeTypes?navigator.mimeTypes.length:0,Qo=zo((Wo+navigator.userAgent.length).toString(36)+Ho.toString(36),4);Zi.exports=function(){return Qo}});var rr=oe((
|
|
1
|
+
"use strict";var Lo=Object.create;var Ct=Object.defineProperty;var No=Object.getOwnPropertyDescriptor;var Uo=Object.getOwnPropertyNames;var Vo=Object.getPrototypeOf,Ko=Object.prototype.hasOwnProperty;var $o=(i,t)=>()=>(i&&(t=i(i=0)),t);var oe=(i,t)=>()=>(t||i((t={exports:{}}).exports,t),t.exports),Yi=(i,t)=>{for(var e in t)Ct(i,e,{get:t[e],enumerable:!0})},Gi=(i,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Uo(t))!Ko.call(i,r)&&r!==e&&Ct(i,r,{get:()=>t[r],enumerable:!(n=No(t,r))||n.enumerable});return i};var Qe=(i,t,e)=>(e=i!=null?Lo(Vo(i)):{},Gi(t||!i||!i.__esModule?Ct(e,"default",{value:i,enumerable:!0}):e,i)),Je=i=>Gi(Ct({},"__esModule",{value:!0}),i);var qn=oe((Pa,Xi)=>{Xi.exports=function(t,e){var n="000000000"+t;return n.substr(n.length-e)}});var er=oe((Aa,Zi)=>{var zo=qn(),qo=typeof window=="object"?window:self,Ho=Object.keys(qo).length,Wo=navigator.mimeTypes?navigator.mimeTypes.length:0,Qo=zo((Wo+navigator.userAgent.length).toString(36)+Ho.toString(36),4);Zi.exports=function(){return Qo}});var rr=oe((Ra,ir)=>{var Hn,tr=typeof window<"u"&&(window.crypto||window.msCrypto)||typeof self<"u"&&self.crypto;tr?(nr=Math.pow(2,32)-1,Hn=function(){return Math.abs(tr.getRandomValues(new Uint32Array(1))[0]/nr)}):Hn=Math.random;var nr;ir.exports=Hn});var at=oe((Ta,cr)=>{var Pt=er(),or=qn(),Jo=rr(),ot=0,Qn=4,At=36,sr=Math.pow(At,Qn);function Wn(){return or((Jo()*sr<<0).toString(At),Qn)}function ar(){return ot=ot<sr?ot:0,ot++,ot-1}function st(){var i="c",t=new Date().getTime().toString(At),e=or(ar().toString(At),Qn),n=Pt(),r=Wn()+Wn();return i+t+e+n+r}st.slug=function(){var t=new Date().getTime().toString(36),e=ar().toString(36).slice(-4),n=Pt().slice(0,1)+Pt().slice(-1),r=Wn().slice(-2);return t.slice(-2)+e+n+r};st.isCuid=function(t){return typeof t!="string"?!1:!!t.startsWith("c")};st.isSlug=function(t){if(typeof t!="string")return!1;var e=t.length;return e>=7&&e<=10};st.fingerprint=Pt;cr.exports=st});var vr=oe((br,wr)=>{(function(i){var t;typeof br=="object"?wr.exports=i():typeof define=="function"&&define.amd?define(i):(typeof window<"u"?t=window:typeof global<"u"?t=global:typeof self<"u"&&(t=self),t.objectHash=i())})(function(){return function i(t,e,n){function r(a,p){if(!e[a]){if(!t[a]){var l=typeof require=="function"&&require;if(!p&&l)return l(a,!0);if(o)return o(a,!0);throw new Error("Cannot find module '"+a+"'")}p=e[a]={exports:{}},t[a][0].call(p.exports,function(m){var x=t[a][1][m];return r(x||m)},p,p.exports,i,t,e,n)}return e[a].exports}for(var o=typeof require=="function"&&require,s=0;s<n.length;s++)r(n[s]);return r}({1:[function(i,t,e){(function(n,r,o,s,a,p,l,m,x){"use strict";var y=i("crypto");function C(b,_){_=I(b,_);var u;return(u=_.algorithm!=="passthrough"?y.createHash(_.algorithm):new R).write===void 0&&(u.write=u.update,u.end=u.update),D(_,u).dispatch(b),u.update||u.end(""),u.digest?u.digest(_.encoding==="buffer"?void 0:_.encoding):(b=u.read(),_.encoding!=="buffer"?b.toString(_.encoding):b)}(e=t.exports=C).sha1=function(b){return C(b)},e.keys=function(b){return C(b,{excludeValues:!0,algorithm:"sha1",encoding:"hex"})},e.MD5=function(b){return C(b,{algorithm:"md5",encoding:"hex"})},e.keysMD5=function(b){return C(b,{algorithm:"md5",encoding:"hex",excludeValues:!0})};var w=y.getHashes?y.getHashes().slice():["sha1","md5"],S=(w.push("passthrough"),["buffer","hex","binary","base64"]);function I(b,_){var u={};if(u.algorithm=(_=_||{}).algorithm||"sha1",u.encoding=_.encoding||"hex",u.excludeValues=!!_.excludeValues,u.algorithm=u.algorithm.toLowerCase(),u.encoding=u.encoding.toLowerCase(),u.ignoreUnknown=_.ignoreUnknown===!0,u.respectType=_.respectType!==!1,u.respectFunctionNames=_.respectFunctionNames!==!1,u.respectFunctionProperties=_.respectFunctionProperties!==!1,u.unorderedArrays=_.unorderedArrays===!0,u.unorderedSets=_.unorderedSets!==!1,u.unorderedObjects=_.unorderedObjects!==!1,u.replacer=_.replacer||void 0,u.excludeKeys=_.excludeKeys||void 0,b===void 0)throw new Error("Object argument required.");for(var h=0;h<w.length;++h)w[h].toLowerCase()===u.algorithm.toLowerCase()&&(u.algorithm=w[h]);if(w.indexOf(u.algorithm)===-1)throw new Error('Algorithm "'+u.algorithm+'" not supported. supported values: '+w.join(", "));if(S.indexOf(u.encoding)===-1&&u.algorithm!=="passthrough")throw new Error('Encoding "'+u.encoding+'" not supported. supported values: '+S.join(", "));return u}function v(b){if(typeof b=="function")return/^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i.exec(Function.prototype.toString.call(b))!=null}function D(b,_,u){u=u||[];function h(d){return _.update?_.update(d,"utf8"):_.write(d,"utf8")}return{dispatch:function(d){return this["_"+((d=b.replacer?b.replacer(d):d)===null?"null":typeof d)](d)},_object:function(d){var O,E=Object.prototype.toString.call(d),M=/\[object (.*)\]/i.exec(E);if(M=(M=M?M[1]:"unknown:["+E+"]").toLowerCase(),0<=(E=u.indexOf(d)))return this.dispatch("[CIRCULAR:"+E+"]");if(u.push(d),o!==void 0&&o.isBuffer&&o.isBuffer(d))return h("buffer:"),h(d);if(M==="object"||M==="function"||M==="asyncfunction")return E=Object.keys(d),b.unorderedObjects&&(E=E.sort()),b.respectType===!1||v(d)||E.splice(0,0,"prototype","__proto__","constructor"),b.excludeKeys&&(E=E.filter(function(B){return!b.excludeKeys(B)})),h("object:"+E.length+":"),O=this,E.forEach(function(B){O.dispatch(B),h(":"),b.excludeValues||O.dispatch(d[B]),h(",")});if(!this["_"+M]){if(b.ignoreUnknown)return h("["+M+"]");throw new Error('Unknown object type "'+M+'"')}this["_"+M](d)},_array:function(d,B){B=B!==void 0?B:b.unorderedArrays!==!1;var E=this;if(h("array:"+d.length+":"),!B||d.length<=1)return d.forEach(function(j){return E.dispatch(j)});var M=[],B=d.map(function(j){var k=new R,q=u.slice();return D(b,k,q).dispatch(j),M=M.concat(q.slice(u.length)),k.read().toString()});return u=u.concat(M),B.sort(),this._array(B,!1)},_date:function(d){return h("date:"+d.toJSON())},_symbol:function(d){return h("symbol:"+d.toString())},_error:function(d){return h("error:"+d.toString())},_boolean:function(d){return h("bool:"+d.toString())},_string:function(d){h("string:"+d.length+":"),h(d.toString())},_function:function(d){h("fn:"),v(d)?this.dispatch("[native]"):this.dispatch(d.toString()),b.respectFunctionNames!==!1&&this.dispatch("function-name:"+String(d.name)),b.respectFunctionProperties&&this._object(d)},_number:function(d){return h("number:"+d.toString())},_xml:function(d){return h("xml:"+d.toString())},_null:function(){return h("Null")},_undefined:function(){return h("Undefined")},_regexp:function(d){return h("regex:"+d.toString())},_uint8array:function(d){return h("uint8array:"),this.dispatch(Array.prototype.slice.call(d))},_uint8clampedarray:function(d){return h("uint8clampedarray:"),this.dispatch(Array.prototype.slice.call(d))},_int8array:function(d){return h("int8array:"),this.dispatch(Array.prototype.slice.call(d))},_uint16array:function(d){return h("uint16array:"),this.dispatch(Array.prototype.slice.call(d))},_int16array:function(d){return h("int16array:"),this.dispatch(Array.prototype.slice.call(d))},_uint32array:function(d){return h("uint32array:"),this.dispatch(Array.prototype.slice.call(d))},_int32array:function(d){return h("int32array:"),this.dispatch(Array.prototype.slice.call(d))},_float32array:function(d){return h("float32array:"),this.dispatch(Array.prototype.slice.call(d))},_float64array:function(d){return h("float64array:"),this.dispatch(Array.prototype.slice.call(d))},_arraybuffer:function(d){return h("arraybuffer:"),this.dispatch(new Uint8Array(d))},_url:function(d){return h("url:"+d.toString())},_map:function(d){return h("map:"),d=Array.from(d),this._array(d,b.unorderedSets!==!1)},_set:function(d){return h("set:"),d=Array.from(d),this._array(d,b.unorderedSets!==!1)},_file:function(d){return h("file:"),this.dispatch([d.name,d.size,d.type,d.lastModfied])},_blob:function(){if(b.ignoreUnknown)return h("[blob]");throw Error(`Hashing Blob objects is currently not supported
|
|
2
2
|
(see https://github.com/puleos/object-hash/issues/26)
|
|
3
3
|
Use "options.replacer" or "options.ignoreUnknown"
|
|
4
|
-
`)},_domwindow:function(){return h("domwindow")},_bigint:function(
|
|
5
|
-
list should be an Array.`),a.length===0)return new w(0);if(a.length===1)return a[0];if(typeof f!="number")for(P=f=0;P<a.length;P++)f+=a[P].length;for(var y=new w(f),A=0,P=0;P<a.length;P++){var F=a[P];F.copy(y,A),A+=F.length}return y},w.prototype.write=function(a,f,y,A){isFinite(f)?isFinite(y)||(A=y,y=void 0):(G=A,A=f,f=y,y=G),f=Number(f)||0;var P,F,N,W,G=this.length-f;switch((!y||G<(y=Number(y)))&&(y=G),A=String(A||"utf8").toLowerCase()){case"hex":P=function(ye,ie,re,X){re=Number(re)||0;var Y=ye.length-re;(!X||Y<(X=Number(X)))&&(X=Y),R((Y=ie.length)%2==0,"Invalid hex string"),Y/2<X&&(X=Y/2);for(var We=0;We<X;We++){var Ji=parseInt(ie.substr(2*We,2),16);R(!isNaN(Ji),"Invalid hex string"),ye[re+We]=Ji}return w._charsWritten=2*We,We}(this,a,f,y);break;case"utf8":case"utf-8":F=this,N=f,W=y,P=w._charsWritten=Et(_e(a),F,N,W);break;case"ascii":case"binary":P=v(this,a,f,y);break;case"base64":F=this,N=f,W=y,P=w._charsWritten=Et(Hi(a),F,N,W);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":P=I(this,a,f,y);break;default:throw new Error("Unknown encoding")}return P},w.prototype.toString=function(a,f,y){var A,P,F,N,W=this;if(a=String(a||"utf8").toLowerCase(),f=Number(f)||0,(y=y!==void 0?Number(y):W.length)===f)return"";switch(a){case"hex":A=function(G,ye,ie){var re=G.length;(!ye||ye<0)&&(ye=0),(!ie||ie<0||re<ie)&&(ie=re);for(var X="",Y=ye;Y<ie;Y++)X+=z(G[Y]);return X}(W,f,y);break;case"utf8":case"utf-8":A=function(G,ye,ie){var re="",X="";ie=Math.min(G.length,ie);for(var Y=ye;Y<ie;Y++)G[Y]<=127?(re+=Wi(X)+String.fromCharCode(G[Y]),X=""):X+="%"+G[Y].toString(16);return re+Wi(X)}(W,f,y);break;case"ascii":case"binary":A=x(W,f,y);break;case"base64":P=W,N=y,A=(F=f)===0&&N===P.length?g.fromByteArray(P):g.fromByteArray(P.slice(F,N));break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":A=function(G,ye,ie){for(var re=G.slice(ye,ie),X="",Y=0;Y<re.length;Y+=2)X+=String.fromCharCode(re[Y]+256*re[Y+1]);return X}(W,f,y);break;default:throw new Error("Unknown encoding")}return A},w.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},w.prototype.copy=function(a,f,y,A){if(f=f||0,(A=A||A===0?A:this.length)!==(y=y||0)&&a.length!==0&&this.length!==0){R(y<=A,"sourceEnd < sourceStart"),R(0<=f&&f<a.length,"targetStart out of bounds"),R(0<=y&&y<this.length,"sourceStart out of bounds"),R(0<=A&&A<=this.length,"sourceEnd out of bounds"),A>this.length&&(A=this.length);var P=(A=a.length-f<A-y?a.length-f+y:A)-y;if(P<100||!w._useTypedArrays)for(var F=0;F<P;F++)a[F+f]=this[F+y];else a._set(this.subarray(y,y+P),f)}},w.prototype.slice=function(a,f){var y=this.length;if(a=q(a,y,0),f=q(f,y,y),w._useTypedArrays)return w._augment(this.subarray(a,f));for(var A=f-a,P=new w(A,void 0,!0),F=0;F<A;F++)P[F]=this[F+a];return P},w.prototype.get=function(a){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(a)},w.prototype.set=function(a,f){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(a,f)},w.prototype.readUInt8=function(a,f){if(f||(R(a!=null,"missing offset"),R(a<this.length,"Trying to read beyond buffer length")),!(a>=this.length))return this[a]},w.prototype.readUInt16LE=function(a,f){return D(this,a,!0,f)},w.prototype.readUInt16BE=function(a,f){return D(this,a,!1,f)},w.prototype.readUInt32LE=function(a,f){return T(this,a,!0,f)},w.prototype.readUInt32BE=function(a,f){return T(this,a,!1,f)},w.prototype.readInt8=function(a,f){if(f||(R(a!=null,"missing offset"),R(a<this.length,"Trying to read beyond buffer length")),!(a>=this.length))return 128&this[a]?-1*(255-this[a]+1):this[a]},w.prototype.readInt16LE=function(a,f){return b(this,a,!0,f)},w.prototype.readInt16BE=function(a,f){return b(this,a,!1,f)},w.prototype.readInt32LE=function(a,f){return _(this,a,!0,f)},w.prototype.readInt32BE=function(a,f){return _(this,a,!1,f)},w.prototype.readFloatLE=function(a,f){return u(this,a,!0,f)},w.prototype.readFloatBE=function(a,f){return u(this,a,!1,f)},w.prototype.readDoubleLE=function(a,f){return h(this,a,!0,f)},w.prototype.readDoubleBE=function(a,f){return h(this,a,!1,f)},w.prototype.writeUInt8=function(a,f,y){y||(R(a!=null,"missing value"),R(f!=null,"missing offset"),R(f<this.length,"trying to write beyond buffer length"),$n(a,255)),f>=this.length||(this[f]=a)},w.prototype.writeUInt16LE=function(a,f,y){l(this,a,f,!0,y)},w.prototype.writeUInt16BE=function(a,f,y){l(this,a,f,!1,y)},w.prototype.writeUInt32LE=function(a,f,y){O(this,a,f,!0,y)},w.prototype.writeUInt32BE=function(a,f,y){O(this,a,f,!1,y)},w.prototype.writeInt8=function(a,f,y){y||(R(a!=null,"missing value"),R(f!=null,"missing offset"),R(f<this.length,"Trying to write beyond buffer length"),zn(a,127,-128)),f>=this.length||(0<=a?this.writeUInt8(a,f,y):this.writeUInt8(255+a+1,f,y))},w.prototype.writeInt16LE=function(a,f,y){E(this,a,f,!0,y)},w.prototype.writeInt16BE=function(a,f,y){E(this,a,f,!1,y)},w.prototype.writeInt32LE=function(a,f,y){M(this,a,f,!0,y)},w.prototype.writeInt32BE=function(a,f,y){M(this,a,f,!1,y)},w.prototype.writeFloatLE=function(a,f,y){B(this,a,f,!0,y)},w.prototype.writeFloatBE=function(a,f,y){B(this,a,f,!1,y)},w.prototype.writeDoubleLE=function(a,f,y){j(this,a,f,!0,y)},w.prototype.writeDoubleBE=function(a,f,y){j(this,a,f,!1,y)},w.prototype.fill=function(a,f,y){if(f=f||0,y=y||this.length,R(typeof(a=typeof(a=a||0)=="string"?a.charCodeAt(0):a)=="number"&&!isNaN(a),"value is not a number"),R(f<=y,"end < start"),y!==f&&this.length!==0){R(0<=f&&f<this.length,"start out of bounds"),R(0<=y&&y<=this.length,"end out of bounds");for(var A=f;A<y;A++)this[A]=a}},w.prototype.inspect=function(){for(var a=[],f=this.length,y=0;y<f;y++)if(a[y]=z(this[y]),y===e.INSPECT_MAX_BYTES){a[y+1]="...";break}return"<Buffer "+a.join(" ")+">"},w.prototype.toArrayBuffer=function(){if(typeof Uint8Array>"u")throw new Error("Buffer.toArrayBuffer not supported in this browser");if(w._useTypedArrays)return new w(this).buffer;for(var a=new Uint8Array(this.length),f=0,y=a.length;f<y;f+=1)a[f]=this[f];return a.buffer};var k=w.prototype;function q(a,f,y){return typeof a!="number"?y:f<=(a=~~a)?f:0<=a||0<=(a+=f)?a:0}function te(a){return(a=~~Math.ceil(+a))<0?0:a}function H(a){return(Array.isArray||function(f){return Object.prototype.toString.call(f)==="[object Array]"})(a)}function z(a){return a<16?"0"+a.toString(16):a.toString(16)}function _e(a){for(var f=[],y=0;y<a.length;y++){var A=a.charCodeAt(y);if(A<=127)f.push(a.charCodeAt(y));else for(var P=y,F=(55296<=A&&A<=57343&&y++,encodeURIComponent(a.slice(P,y+1)).substr(1).split("%")),N=0;N<F.length;N++)f.push(parseInt(F[N],16))}return f}function Hi(a){return g.toByteArray(a)}function Et(a,f,y,A){for(var P=0;P<A&&!(P+y>=f.length||P>=a.length);P++)f[P+y]=a[P];return P}function Wi(a){try{return decodeURIComponent(a)}catch{return String.fromCharCode(65533)}}function $n(a,f){R(typeof a=="number","cannot write a non-number as a number"),R(0<=a,"specified a negative value for writing an unsigned value"),R(a<=f,"value is larger than maximum value for type"),R(Math.floor(a)===a,"value has a fractional component")}function zn(a,f,y){R(typeof a=="number","cannot write a non-number as a number"),R(a<=f,"value larger than maximum allowed value"),R(y<=a,"value smaller than minimum allowed value"),R(Math.floor(a)===a,"value has a fractional component")}function Qi(a,f,y){R(typeof a=="number","cannot write a non-number as a number"),R(a<=f,"value larger than maximum allowed value"),R(y<=a,"value smaller than minimum allowed value")}function R(a,f){if(!a)throw new Error(f||"Failed assertion")}w._augment=function(a){return a._isBuffer=!0,a._get=a.get,a._set=a.set,a.get=k.get,a.set=k.set,a.write=k.write,a.toString=k.toString,a.toLocaleString=k.toString,a.toJSON=k.toJSON,a.copy=k.copy,a.slice=k.slice,a.readUInt8=k.readUInt8,a.readUInt16LE=k.readUInt16LE,a.readUInt16BE=k.readUInt16BE,a.readUInt32LE=k.readUInt32LE,a.readUInt32BE=k.readUInt32BE,a.readInt8=k.readInt8,a.readInt16LE=k.readInt16LE,a.readInt16BE=k.readInt16BE,a.readInt32LE=k.readInt32LE,a.readInt32BE=k.readInt32BE,a.readFloatLE=k.readFloatLE,a.readFloatBE=k.readFloatBE,a.readDoubleLE=k.readDoubleLE,a.readDoubleBE=k.readDoubleBE,a.writeUInt8=k.writeUInt8,a.writeUInt16LE=k.writeUInt16LE,a.writeUInt16BE=k.writeUInt16BE,a.writeUInt32LE=k.writeUInt32LE,a.writeUInt32BE=k.writeUInt32BE,a.writeInt8=k.writeInt8,a.writeInt16LE=k.writeInt16LE,a.writeInt16BE=k.writeInt16BE,a.writeInt32LE=k.writeInt32LE,a.writeInt32BE=k.writeInt32BE,a.writeFloatLE=k.writeFloatLE,a.writeFloatBE=k.writeFloatBE,a.writeDoubleLE=k.writeDoubleLE,a.writeDoubleBE=k.writeDoubleBE,a.fill=k.fill,a.inspect=k.inspect,a.toArrayBuffer=k.toArrayBuffer,a}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/buffer/index.js","/node_modules/gulp-browserify/node_modules/buffer")},{"base64-js":2,buffer:3,ieee754:10,lYpoI2:11}],4:[function(i,t,e){(function(n,r,g,s,c,p,d,m,S){var g=i("buffer").Buffer,C=4,w=new g(C);w.fill(0),t.exports={hash:function(v,I,x,D){for(var T=I(function(l,O){l.length%C!=0&&(E=l.length+(C-l.length%C),l=g.concat([l,w],E));for(var E,M=[],B=O?l.readInt32BE:l.readInt32LE,j=0;j<l.length;j+=C)M.push(B.call(l,j));return M}(v=g.isBuffer(v)?v:new g(v),D),8*v.length),I=D,b=new g(x),_=I?b.writeInt32BE:b.writeInt32LE,u=0;u<T.length;u++)_.call(b,T[u],4*u,!0);return b}}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/helpers.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{buffer:3,lYpoI2:11}],5:[function(i,t,e){(function(n,r,g,s,c,p,d,m,S){var g=i("buffer").Buffer,C=i("./sha"),w=i("./sha256"),v=i("./rng"),I={sha1:C,sha256:w,md5:i("./md5")},x=64,D=new g(x);function T(l,O){var E=I[l=l||"sha1"],M=[];return E||b("algorithm:",l,"is not yet supported"),{update:function(B){return g.isBuffer(B)||(B=new g(B)),M.push(B),B.length,this},digest:function(B){var j=g.concat(M),j=O?function(k,q,te){g.isBuffer(q)||(q=new g(q)),g.isBuffer(te)||(te=new g(te)),q.length>x?q=k(q):q.length<x&&(q=g.concat([q,D],x));for(var H=new g(x),z=new g(x),_e=0;_e<x;_e++)H[_e]=54^q[_e],z[_e]=92^q[_e];return te=k(g.concat([H,te])),k(g.concat([z,te]))}(E,O,j):E(j);return M=null,B?j.toString(B):j}}}function b(){var l=[].slice.call(arguments).join(" ");throw new Error([l,"we accept pull requests","http://github.com/dominictarr/crypto-browserify"].join(`
|
|
6
|
-
`))}D.fill(0),e.createHash=function(l){return T(l)},e.createHmac=T,e.randomBytes=function(l,O){if(!O||!O.call)return new g(v(l));try{O.call(this,void 0,new g(v(l)))}catch(E){O(E)}};var _,u=["createCredentials","createCipher","createCipheriv","createDecipher","createDecipheriv","createSign","createVerify","createDiffieHellman","pbkdf2"],h=function(l){e[l]=function(){b("sorry,",l,"is not implemented yet")}};for(_ in u)h(u[_],_)}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/index.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./md5":6,"./rng":7,"./sha":8,"./sha256":9,buffer:3,lYpoI2:11}],6:[function(i,t,e){(function(n,r,o,s,c,p,d,m,S){var g=i("./helpers");function C(b,_){b[_>>5]|=128<<_%32,b[14+(_+64>>>9<<4)]=_;for(var u=1732584193,h=-271733879,l=-1732584194,O=271733878,E=0;E<b.length;E+=16){var M=u,B=h,j=l,k=O,u=v(u,h,l,O,b[E+0],7,-680876936),O=v(O,u,h,l,b[E+1],12,-389564586),l=v(l,O,u,h,b[E+2],17,606105819),h=v(h,l,O,u,b[E+3],22,-1044525330);u=v(u,h,l,O,b[E+4],7,-176418897),O=v(O,u,h,l,b[E+5],12,1200080426),l=v(l,O,u,h,b[E+6],17,-1473231341),h=v(h,l,O,u,b[E+7],22,-45705983),u=v(u,h,l,O,b[E+8],7,1770035416),O=v(O,u,h,l,b[E+9],12,-1958414417),l=v(l,O,u,h,b[E+10],17,-42063),h=v(h,l,O,u,b[E+11],22,-1990404162),u=v(u,h,l,O,b[E+12],7,1804603682),O=v(O,u,h,l,b[E+13],12,-40341101),l=v(l,O,u,h,b[E+14],17,-1502002290),u=I(u,h=v(h,l,O,u,b[E+15],22,1236535329),l,O,b[E+1],5,-165796510),O=I(O,u,h,l,b[E+6],9,-1069501632),l=I(l,O,u,h,b[E+11],14,643717713),h=I(h,l,O,u,b[E+0],20,-373897302),u=I(u,h,l,O,b[E+5],5,-701558691),O=I(O,u,h,l,b[E+10],9,38016083),l=I(l,O,u,h,b[E+15],14,-660478335),h=I(h,l,O,u,b[E+4],20,-405537848),u=I(u,h,l,O,b[E+9],5,568446438),O=I(O,u,h,l,b[E+14],9,-1019803690),l=I(l,O,u,h,b[E+3],14,-187363961),h=I(h,l,O,u,b[E+8],20,1163531501),u=I(u,h,l,O,b[E+13],5,-1444681467),O=I(O,u,h,l,b[E+2],9,-51403784),l=I(l,O,u,h,b[E+7],14,1735328473),u=x(u,h=I(h,l,O,u,b[E+12],20,-1926607734),l,O,b[E+5],4,-378558),O=x(O,u,h,l,b[E+8],11,-2022574463),l=x(l,O,u,h,b[E+11],16,1839030562),h=x(h,l,O,u,b[E+14],23,-35309556),u=x(u,h,l,O,b[E+1],4,-1530992060),O=x(O,u,h,l,b[E+4],11,1272893353),l=x(l,O,u,h,b[E+7],16,-155497632),h=x(h,l,O,u,b[E+10],23,-1094730640),u=x(u,h,l,O,b[E+13],4,681279174),O=x(O,u,h,l,b[E+0],11,-358537222),l=x(l,O,u,h,b[E+3],16,-722521979),h=x(h,l,O,u,b[E+6],23,76029189),u=x(u,h,l,O,b[E+9],4,-640364487),O=x(O,u,h,l,b[E+12],11,-421815835),l=x(l,O,u,h,b[E+15],16,530742520),u=D(u,h=x(h,l,O,u,b[E+2],23,-995338651),l,O,b[E+0],6,-198630844),O=D(O,u,h,l,b[E+7],10,1126891415),l=D(l,O,u,h,b[E+14],15,-1416354905),h=D(h,l,O,u,b[E+5],21,-57434055),u=D(u,h,l,O,b[E+12],6,1700485571),O=D(O,u,h,l,b[E+3],10,-1894986606),l=D(l,O,u,h,b[E+10],15,-1051523),h=D(h,l,O,u,b[E+1],21,-2054922799),u=D(u,h,l,O,b[E+8],6,1873313359),O=D(O,u,h,l,b[E+15],10,-30611744),l=D(l,O,u,h,b[E+6],15,-1560198380),h=D(h,l,O,u,b[E+13],21,1309151649),u=D(u,h,l,O,b[E+4],6,-145523070),O=D(O,u,h,l,b[E+11],10,-1120210379),l=D(l,O,u,h,b[E+2],15,718787259),h=D(h,l,O,u,b[E+9],21,-343485551),u=T(u,M),h=T(h,B),l=T(l,j),O=T(O,k)}return Array(u,h,l,O)}function w(b,_,u,h,l,O){return T((_=T(T(_,b),T(h,O)))<<l|_>>>32-l,u)}function v(b,_,u,h,l,O,E){return w(_&u|~_&h,b,_,l,O,E)}function I(b,_,u,h,l,O,E){return w(_&h|u&~h,b,_,l,O,E)}function x(b,_,u,h,l,O,E){return w(_^u^h,b,_,l,O,E)}function D(b,_,u,h,l,O,E){return w(u^(_|~h),b,_,l,O,E)}function T(b,_){var u=(65535&b)+(65535&_);return(b>>16)+(_>>16)+(u>>16)<<16|65535&u}t.exports=function(b){return g.hash(b,C,16)}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/md5.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],7:[function(i,t,e){(function(n,r,o,s,c,p,d,m,S){var g;t.exports=g||function(C){for(var w,v=new Array(C),I=0;I<C;I++)!(3&I)&&(w=4294967296*Math.random()),v[I]=w>>>((3&I)<<3)&255;return v}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/rng.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{buffer:3,lYpoI2:11}],8:[function(i,t,e){(function(n,r,o,s,c,p,d,m,S){var g=i("./helpers");function C(I,x){I[x>>5]|=128<<24-x%32,I[15+(x+64>>9<<4)]=x;for(var D,T,b,_=Array(80),u=1732584193,h=-271733879,l=-1732584194,O=271733878,E=-1009589776,M=0;M<I.length;M+=16){for(var B=u,j=h,k=l,q=O,te=E,H=0;H<80;H++){_[H]=H<16?I[M+H]:v(_[H-3]^_[H-8]^_[H-14]^_[H-16],1);var z=w(w(v(u,5),(z=h,T=l,b=O,(D=H)<20?z&T|~z&b:!(D<40)&&D<60?z&T|z&b|T&b:z^T^b)),w(w(E,_[H]),(D=H)<20?1518500249:D<40?1859775393:D<60?-1894007588:-899497514)),E=O,O=l,l=v(h,30),h=u,u=z}u=w(u,B),h=w(h,j),l=w(l,k),O=w(O,q),E=w(E,te)}return Array(u,h,l,O,E)}function w(I,x){var D=(65535&I)+(65535&x);return(I>>16)+(x>>16)+(D>>16)<<16|65535&D}function v(I,x){return I<<x|I>>>32-x}t.exports=function(I){return g.hash(I,C,20,!0)}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],9:[function(i,t,e){(function(n,r,o,s,c,p,d,m,S){function g(x,D){var T=(65535&x)+(65535&D);return(x>>16)+(D>>16)+(T>>16)<<16|65535&T}function C(x,D){var T,b=new Array(1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298),_=new Array(1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225),u=new Array(64);x[D>>5]|=128<<24-D%32,x[15+(D+64>>9<<4)]=D;for(var h,l,O=0;O<x.length;O+=16){for(var E=_[0],M=_[1],B=_[2],j=_[3],k=_[4],q=_[5],te=_[6],H=_[7],z=0;z<64;z++)u[z]=z<16?x[z+O]:g(g(g((l=u[z-2],v(l,17)^v(l,19)^I(l,10)),u[z-7]),(l=u[z-15],v(l,7)^v(l,18)^I(l,3))),u[z-16]),T=g(g(g(g(H,v(l=k,6)^v(l,11)^v(l,25)),k&q^~k&te),b[z]),u[z]),h=g(v(h=E,2)^v(h,13)^v(h,22),E&M^E&B^M&B),H=te,te=q,q=k,k=g(j,T),j=B,B=M,M=E,E=g(T,h);_[0]=g(E,_[0]),_[1]=g(M,_[1]),_[2]=g(B,_[2]),_[3]=g(j,_[3]),_[4]=g(k,_[4]),_[5]=g(q,_[5]),_[6]=g(te,_[6]),_[7]=g(H,_[7])}return _}var w=i("./helpers"),v=function(x,D){return x>>>D|x<<32-D},I=function(x,D){return x>>>D};t.exports=function(x){return w.hash(x,C,32,!0)}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha256.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],10:[function(i,t,e){(function(n,r,o,s,c,p,d,m,S){e.read=function(g,C,w,v,O){var x,D,T=8*O-v-1,b=(1<<T)-1,_=b>>1,u=-7,h=w?O-1:0,l=w?-1:1,O=g[C+h];for(h+=l,x=O&(1<<-u)-1,O>>=-u,u+=T;0<u;x=256*x+g[C+h],h+=l,u-=8);for(D=x&(1<<-u)-1,x>>=-u,u+=v;0<u;D=256*D+g[C+h],h+=l,u-=8);if(x===0)x=1-_;else{if(x===b)return D?NaN:1/0*(O?-1:1);D+=Math.pow(2,v),x-=_}return(O?-1:1)*D*Math.pow(2,x-v)},e.write=function(g,C,w,v,I,E){var D,T,b=8*E-I-1,_=(1<<b)-1,u=_>>1,h=I===23?Math.pow(2,-24)-Math.pow(2,-77):0,l=v?0:E-1,O=v?1:-1,E=C<0||C===0&&1/C<0?1:0;for(C=Math.abs(C),isNaN(C)||C===1/0?(T=isNaN(C)?1:0,D=_):(D=Math.floor(Math.log(C)/Math.LN2),C*(v=Math.pow(2,-D))<1&&(D--,v*=2),2<=(C+=1<=D+u?h/v:h*Math.pow(2,1-u))*v&&(D++,v/=2),_<=D+u?(T=0,D=_):1<=D+u?(T=(C*v-1)*Math.pow(2,I),D+=u):(T=C*Math.pow(2,u-1)*Math.pow(2,I),D=0));8<=I;g[w+l]=255&T,l+=O,T/=256,I-=8);for(D=D<<I|T,b+=I;0<b;g[w+l]=255&D,l+=O,D/=256,b-=8);g[w+l-O]|=128*E}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/ieee754/index.js","/node_modules/gulp-browserify/node_modules/ieee754")},{buffer:3,lYpoI2:11}],11:[function(i,t,e){(function(n,r,o,s,c,p,d,m,S){var g,C,w;function v(){}(n=t.exports={}).nextTick=(C=typeof window<"u"&&window.setImmediate,w=typeof window<"u"&&window.postMessage&&window.addEventListener,C?function(I){return window.setImmediate(I)}:w?(g=[],window.addEventListener("message",function(I){var x=I.source;x!==window&&x!==null||I.data!=="process-tick"||(I.stopPropagation(),0<g.length&&g.shift()())},!0),function(I){g.push(I),window.postMessage("process-tick","*")}):function(I){setTimeout(I,0)}),n.title="browser",n.browser=!0,n.env={},n.argv=[],n.on=v,n.addListener=v,n.once=v,n.off=v,n.removeListener=v,n.removeAllListeners=v,n.emit=v,n.binding=function(I){throw new Error("process.binding is not supported")},n.cwd=function(){return"/"},n.chdir=function(I){throw new Error("process.chdir is not supported")}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/process/browser.js","/node_modules/gulp-browserify/node_modules/process")},{buffer:3,lYpoI2:11}]},{},[1])(1)})});var ze={};Yi(ze,{__addDisposableResource:()=>So,__assign:()=>yn,__asyncDelegator:()=>po,__asyncGenerator:()=>fo,__asyncValues:()=>ho,__await:()=>nt,__awaiter:()=>oo,__classPrivateFieldGet:()=>bo,__classPrivateFieldIn:()=>vo,__classPrivateFieldSet:()=>wo,__createBinding:()=>wn,__decorate:()=>no,__disposeResources:()=>xo,__esDecorate:()=>ia,__exportStar:()=>ao,__extends:()=>eo,__generator:()=>so,__importDefault:()=>yo,__importStar:()=>go,__makeTemplateObject:()=>mo,__metadata:()=>ro,__param:()=>io,__propKey:()=>oa,__read:()=>Ci,__rest:()=>to,__runInitializers:()=>ra,__setFunctionName:()=>sa,__spread:()=>co,__spreadArray:()=>uo,__spreadArrays:()=>lo,__values:()=>bn,default:()=>la});function eo(i,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");Ei(i,t);function e(){this.constructor=i}i.prototype=t===null?Object.create(t):(e.prototype=t.prototype,new e)}function to(i,t){var e={};for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&t.indexOf(n)<0&&(e[n]=i[n]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,n=Object.getOwnPropertySymbols(i);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(i,n[r])&&(e[n[r]]=i[n[r]]);return e}function no(i,t,e,n){var r=arguments.length,o=r<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(i,t,e,n);else for(var c=i.length-1;c>=0;c--)(s=i[c])&&(o=(r<3?s(o):r>3?s(t,e,o):s(t,e))||o);return r>3&&o&&Object.defineProperty(t,e,o),o}function io(i,t){return function(e,n){t(e,n,i)}}function ia(i,t,e,n,r,o){function s(x){if(x!==void 0&&typeof x!="function")throw new TypeError("Function expected");return x}for(var c=n.kind,p=c==="getter"?"get":c==="setter"?"set":"value",d=!t&&i?n.static?i:i.prototype:null,m=t||(d?Object.getOwnPropertyDescriptor(d,n.name):{}),S,g=!1,C=e.length-1;C>=0;C--){var w={};for(var v in n)w[v]=v==="access"?{}:n[v];for(var v in n.access)w.access[v]=n.access[v];w.addInitializer=function(x){if(g)throw new TypeError("Cannot add initializers after decoration has completed");o.push(s(x||null))};var I=(0,e[C])(c==="accessor"?{get:m.get,set:m.set}:m[p],w);if(c==="accessor"){if(I===void 0)continue;if(I===null||typeof I!="object")throw new TypeError("Object expected");(S=s(I.get))&&(m.get=S),(S=s(I.set))&&(m.set=S),(S=s(I.init))&&r.unshift(S)}else(S=s(I))&&(c==="field"?r.unshift(S):m[p]=S)}d&&Object.defineProperty(d,n.name,m),g=!0}function ra(i,t,e){for(var n=arguments.length>2,r=0;r<t.length;r++)e=n?t[r].call(i,e):t[r].call(i);return n?e:void 0}function oa(i){return typeof i=="symbol"?i:"".concat(i)}function sa(i,t,e){return typeof t=="symbol"&&(t=t.description?"[".concat(t.description,"]"):""),Object.defineProperty(i,"name",{configurable:!0,value:e?"".concat(e," ",t):t})}function ro(i,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(i,t)}function oo(i,t,e,n){function r(o){return o instanceof e?o:new e(function(s){s(o)})}return new(e||(e=Promise))(function(o,s){function c(m){try{d(n.next(m))}catch(S){s(S)}}function p(m){try{d(n.throw(m))}catch(S){s(S)}}function d(m){m.done?o(m.value):r(m.value).then(c,p)}d((n=n.apply(i,t||[])).next())})}function so(i,t){var e={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},n,r,o,s;return s={next:c(0),throw:c(1),return:c(2)},typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function c(d){return function(m){return p([d,m])}}function p(d){if(n)throw new TypeError("Generator is already executing.");for(;s&&(s=0,d[0]&&(e=0)),e;)try{if(n=1,r&&(o=d[0]&2?r.return:d[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,d[1])).done)return o;switch(r=0,o&&(d=[d[0]&2,o.value]),d[0]){case 0:case 1:o=d;break;case 4:return e.label++,{value:d[1],done:!1};case 5:e.label++,r=d[1],d=[0];continue;case 7:d=e.ops.pop(),e.trys.pop();continue;default:if(o=e.trys,!(o=o.length>0&&o[o.length-1])&&(d[0]===6||d[0]===2)){e=0;continue}if(d[0]===3&&(!o||d[1]>o[0]&&d[1]<o[3])){e.label=d[1];break}if(d[0]===6&&e.label<o[1]){e.label=o[1],o=d;break}if(o&&e.label<o[2]){e.label=o[2],e.ops.push(d);break}o[2]&&e.ops.pop(),e.trys.pop();continue}d=t.call(i,e)}catch(m){d=[6,m],r=0}finally{n=o=0}if(d[0]&5)throw d[1];return{value:d[0]?d[1]:void 0,done:!0}}}function ao(i,t){for(var e in i)e!=="default"&&!Object.prototype.hasOwnProperty.call(t,e)&&wn(t,i,e)}function bn(i){var t=typeof Symbol=="function"&&Symbol.iterator,e=t&&i[t],n=0;if(e)return e.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&n>=i.length&&(i=void 0),{value:i&&i[n++],done:!i}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function Ci(i,t){var e=typeof Symbol=="function"&&i[Symbol.iterator];if(!e)return i;var n=e.call(i),r,o=[],s;try{for(;(t===void 0||t-- >0)&&!(r=n.next()).done;)o.push(r.value)}catch(c){s={error:c}}finally{try{r&&!r.done&&(e=n.return)&&e.call(n)}finally{if(s)throw s.error}}return o}function co(){for(var i=[],t=0;t<arguments.length;t++)i=i.concat(Ci(arguments[t]));return i}function lo(){for(var i=0,t=0,e=arguments.length;t<e;t++)i+=arguments[t].length;for(var n=Array(i),r=0,t=0;t<e;t++)for(var o=arguments[t],s=0,c=o.length;s<c;s++,r++)n[r]=o[s];return n}function uo(i,t,e){if(e||arguments.length===2)for(var n=0,r=t.length,o;n<r;n++)(o||!(n in t))&&(o||(o=Array.prototype.slice.call(t,0,n)),o[n]=t[n]);return i.concat(o||Array.prototype.slice.call(t))}function nt(i){return this instanceof nt?(this.v=i,this):new nt(i)}function fo(i,t,e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=e.apply(i,t||[]),r,o=[];return r={},s("next"),s("throw"),s("return"),r[Symbol.asyncIterator]=function(){return this},r;function s(g){n[g]&&(r[g]=function(C){return new Promise(function(w,v){o.push([g,C,w,v])>1||c(g,C)})})}function c(g,C){try{p(n[g](C))}catch(w){S(o[0][3],w)}}function p(g){g.value instanceof nt?Promise.resolve(g.value.v).then(d,m):S(o[0][2],g)}function d(g){c("next",g)}function m(g){c("throw",g)}function S(g,C){g(C),o.shift(),o.length&&c(o[0][0],o[0][1])}}function po(i){var t,e;return t={},n("next"),n("throw",function(r){throw r}),n("return"),t[Symbol.iterator]=function(){return this},t;function n(r,o){t[r]=i[r]?function(s){return(e=!e)?{value:nt(i[r](s)),done:!1}:o?o(s):s}:o}}function ho(i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=i[Symbol.asyncIterator],e;return t?t.call(i):(i=typeof bn=="function"?bn(i):i[Symbol.iterator](),e={},n("next"),n("throw"),n("return"),e[Symbol.asyncIterator]=function(){return this},e);function n(o){e[o]=i[o]&&function(s){return new Promise(function(c,p){s=i[o](s),r(c,p,s.done,s.value)})}}function r(o,s,c,p){Promise.resolve(p).then(function(d){o({value:d,done:c})},s)}}function mo(i,t){return Object.defineProperty?Object.defineProperty(i,"raw",{value:t}):i.raw=t,i}function go(i){if(i&&i.__esModule)return i;var t={};if(i!=null)for(var e in i)e!=="default"&&Object.prototype.hasOwnProperty.call(i,e)&&wn(t,i,e);return aa(t,i),t}function yo(i){return i&&i.__esModule?i:{default:i}}function bo(i,t,e,n){if(e==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?i!==t||!n:!t.has(i))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e==="m"?n:e==="a"?n.call(i):n?n.value:t.get(i)}function wo(i,t,e,n,r){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?i!==t||!r:!t.has(i))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?r.call(i,e):r?r.value=e:t.set(i,e),e}function vo(i,t){if(t===null||typeof t!="object"&&typeof t!="function")throw new TypeError("Cannot use 'in' operator on non-object");return typeof i=="function"?t===i:i.has(t)}function So(i,t,e){if(t!=null){if(typeof t!="object"&&typeof t!="function")throw new TypeError("Object expected.");var n;if(e){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(n===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose]}if(typeof n!="function")throw new TypeError("Object not disposable.");i.stack.push({value:t,dispose:n,async:e})}else e&&i.stack.push({async:!0});return t}function xo(i){function t(n){i.error=i.hasError?new ca(n,i.error,"An error was suppressed during disposal."):n,i.hasError=!0}function e(){for(;i.stack.length;){var n=i.stack.pop();try{var r=n.dispose&&n.dispose.call(n.value);if(n.async)return Promise.resolve(r).then(e,function(o){return t(o),e()})}catch(o){t(o)}}if(i.hasError)throw i.error}return e()}var Ei,yn,wn,aa,ca,la,qe=$o(()=>{Ei=function(i,t){return Ei=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,n){e.__proto__=n}||function(e,n){for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])},Ei(i,t)};yn=function(){return yn=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++){e=arguments[n];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o])}return t},yn.apply(this,arguments)};wn=Object.create?function(i,t,e,n){n===void 0&&(n=e);var r=Object.getOwnPropertyDescriptor(t,e);(!r||("get"in r?!t.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return t[e]}}),Object.defineProperty(i,n,r)}:function(i,t,e,n){n===void 0&&(n=e),i[n]=t[e]};aa=Object.create?function(i,t){Object.defineProperty(i,"default",{enumerable:!0,value:t})}:function(i,t){i.default=t};ca=typeof SuppressedError=="function"?SuppressedError:function(i,t,e){var n=new Error(e);return n.name="SuppressedError",n.error=i,n.suppressed=t,n};la={__extends:eo,__assign:yn,__rest:to,__decorate:no,__param:io,__metadata:ro,__awaiter:oo,__generator:so,__createBinding:wn,__exportStar:ao,__values:bn,__read:Ci,__spread:co,__spreadArrays:lo,__spreadArray:uo,__await:nt,__asyncGenerator:fo,__asyncDelegator:po,__asyncValues:ho,__makeTemplateObject:mo,__importStar:go,__importDefault:yo,__classPrivateFieldGet:bo,__classPrivateFieldSet:wo,__classPrivateFieldIn:vo,__addDisposableResource:So,__disposeResources:xo}});var Io=oe(Oo=>{"use strict";Object.defineProperty(Oo,"__esModule",{value:!0})});var Ai=oe(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.invokeEventHandlersAsync=De.invokeEventHandlers=De.eventHandlerSafeInvokeAsync=De.eventHandlerSafeInvoke=void 0;var Do=(qe(),Je(ze));function _o(i,t,e){try{return i(t,e),{succeeded:!0}}catch(n){return{error:n,succeeded:!1}}}De.eventHandlerSafeInvoke=_o;function Pi(i,t,e){return(0,Do.__awaiter)(this,void 0,void 0,function*(){try{return yield i(t,e),{succeeded:!0}}catch(n){return{error:n,succeeded:!1}}})}De.eventHandlerSafeInvokeAsync=Pi;function da(i,t,e,n){for(let r of i){let{succeeded:o,error:s}=_o(r,t,e);if(!o&&n?.swallowExceptions!==!0)throw s}}De.invokeEventHandlers=da;function ua(i,t,e,n){return(0,Do.__awaiter)(this,void 0,void 0,function*(){if(n?.parallelize===!1)for(let r of i){let{succeeded:o,error:s}=yield Pi(r,t,e);if(!o&&n?.swallowExceptions!==!0)throw s}else{let r=[];for(let o of i)r.push(Pi(o,t,e).then(({succeeded:s,error:c})=>{if(!s&&n?.swallowExceptions!==!0)throw c}));yield Promise.all(r)}})}De.invokeEventHandlersAsync=ua});var Po=oe(vn=>{"use strict";Object.defineProperty(vn,"__esModule",{value:!0});vn.TypedEvent=void 0;var fa=(qe(),Je(ze)),Eo=Ai(),Co={swallowExceptions:!1,parallelize:!0},Ti=class{constructor(){this._handlers=[]}attach(t){this._handlers.push(t)}detach(t){this.tryRemoveHandler(t)}invoke(t,e,n=Co){(0,Eo.invokeEventHandlers)(this._handlers,t,e,n)}invokeAsync(t,e,n=Co){return(0,fa.__awaiter)(this,void 0,void 0,function*(){yield(0,Eo.invokeEventHandlersAsync)(this._handlers,t,e,n)})}tryRemoveHandler(t){let e=this._handlers.findIndex(n=>n===t);e>=0&&this._handlers.splice(e,1)}};vn.TypedEvent=Ti});var Fi=oe(Ri=>{"use strict";Object.defineProperty(Ri,"__esModule",{value:!0});var pa=(qe(),Je(ze));(0,pa.__exportStar)(Po(),Ri)});var Ao=oe(Sn=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});Sn.FinalizationRegistryMissingError=void 0;var ki=class extends Error{};Sn.FinalizationRegistryMissingError=ki});var Mi=oe(xn=>{"use strict";Object.defineProperty(xn,"__esModule",{value:!0});xn.WeakHandlerHolder=void 0;var ha=Ao(),Bi=class{constructor(t){this._refs=[];try{this._finalizationRegistry=new FinalizationRegistry(t)}catch(e){throw e.name==="FinalizationRegistry"?new ha.FinalizationRegistryMissingError("FinalizationRegistry is not defined. Weak Events cannot be used. Please consult 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry' for compatibility information"):e}}getWeakHandler(t,e){let n=new WeakRef(e);return this._finalizationRegistry.register(e,{eventSource:t,handlerRef:n},n),this._refs.push(n),n}releaseWeakHandler(t){let n=this._refs.find(r=>r?.deref()===t)||new WeakRef(t);return this._finalizationRegistry.unregister(n),n}unregisterRef(t){this._finalizationRegistry.unregister(t)}};xn.WeakHandlerHolder=Bi});var To=oe(On=>{"use strict";Object.defineProperty(On,"__esModule",{value:!0});On.WeakEvent=void 0;var ji=(qe(),Je(ze)),ma=Fi(),ga=Mi(),Li=Ai(),ya={swallowExceptions:!1,parallelize:!0},Ni=class{constructor(){this._handlers=[],this._handlerFinalizedEvent=new ma.TypedEvent,this.handlerFinalizedEvent=this._handlerFinalizedEvent,this._refHolder=new ga.WeakHandlerHolder(t=>{this.onHandlerFinalizer(t)})}invoke(t,e,n){for(let r of this._handlers){let o=r?.deref();if(o){let{succeeded:s,error:c}=(0,Li.eventHandlerSafeInvoke)(o,t,e);if(!s&&n?.swallowExceptions!==!0)throw c}else this.releaseHandler(r)}}invokeAsync(t,e,n=ya){return(0,ji.__awaiter)(this,void 0,void 0,function*(){n?.parallelize===!1?yield this.sequentialInvokeAsync(t,e,n):yield this.parallelInvokeAsync(t,e,n)})}sequentialInvokeAsync(t,e,n){return(0,ji.__awaiter)(this,void 0,void 0,function*(){for(let r of this._handlers){let o=r?.deref();if(o){let{succeeded:s,error:c}=yield(0,Li.eventHandlerSafeInvokeAsync)(o,t,e);if(!s&&n.swallowExceptions!==!0)throw c}else this.releaseHandler(r)}})}parallelInvokeAsync(t,e,n){return(0,ji.__awaiter)(this,void 0,void 0,function*(){let r=[];for(let o of this._handlers){let s=o?.deref();s?r.push((0,Li.eventHandlerSafeInvokeAsync)(s,t,e).then(({succeeded:c,error:p})=>{if(!c&&n.swallowExceptions!==!0)throw p})):this.releaseHandler(o)}yield Promise.all(r)})}attach(t){this._handlers.push(this._refHolder.getWeakHandler(this,t))}detach(t){let e=this._refHolder.releaseWeakHandler(t);this.tryRemoveHandlerRef(e)}onHandlerFinalizer(t){this.tryRemoveHandlerRef(t?.handlerRef),this._handlerFinalizedEvent.invokeAsync(this,t,{swallowExceptions:!0})}tryRemoveHandlerRef(t){let e=this._handlers.findIndex(n=>n===t);e>=0&&this._handlers.splice(e,1)}releaseHandler(t){this._refHolder.unregisterRef(t),this.tryRemoveHandlerRef(t)}};On.WeakEvent=Ni});var Fo=oe(In=>{"use strict";Object.defineProperty(In,"__esModule",{value:!0});var Ro=(qe(),Je(ze));(0,Ro.__exportStar)(Mi(),In);(0,Ro.__exportStar)(To(),In)});var ko=oe(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});var Ui=(qe(),Je(ze));(0,Ui.__exportStar)(Io(),It);(0,Ui.__exportStar)(Fi(),It);(0,Ui.__exportStar)(Fo(),It)});var qi={};Yi(qi,{Client:()=>He,ClientDescriptor:()=>Kn,Entity:()=>ue,EntityFile:()=>de,MigrationPathError:()=>Ze,ServerSync:()=>rt,Storage:()=>He,StorageDescriptor:()=>Kn,collection:()=>gi,createDefaultMigration:()=>yi,createMigration:()=>bi,migrate:()=>Wt,schema:()=>gt});var pr=Qe(at(),1),Bt=4,lt=36;function lr(i){return i.toString(lt).padStart(Bt,"0")}function Yo(i){return i.toString().padStart(6,"0")}var Tt=class{constructor(){this.latest={time:Date.now(),counter:0,node:Go()};this.zeroCounter=0;this.now=t=>(this.latest=ur(this.latest),this.get(t,this.latest));this.OLD_now=t=>(this.latest=ur(this.latest),Yo(t)+Zo(this.latest));this.timerState=()=>this.latest;this.update=t=>{let e=t.slice(Bt);this.latest=Xo(this.latest,hr(e))};this.get=(t,e)=>lr(t)+dr(e);this.zero=t=>lr(t)+dr({time:0,counter:this.zeroCounter++,node:this.latest.node});this.getWallClockTime=Xn}},Rt=class extends Error{constructor(...e){super();this.type="ClockDriftError",this.message=["maximum clock drift exceeded"].concat(e).join(" ")}},Ft=class extends Error{constructor(){super();this.type="OverflowError",this.message="timestamp counter overflow"}},Jn=4,Yn=7,kt=60*1e3,ct=9;function Go(){return pr.default.slug().padStart(Yn,"0").slice(0,Yn)}function dr(i){let t=new Date(i.time).getTime().toString(lt).padStart(ct,"0"),e=i.counter.toString(lt).padStart(Jn,"0"),n=i.node.padStart(Yn,"0");return`${t}${e}${n}`}function ur(i){let t=Date.now(),e=Math.max(i.time,t),n=i.time===e?i.counter+1:0;if(e-t>kt)throw new Rt(e,t,kt);if(n>65535)throw new Ft;return{time:e,counter:n,node:i.node}}function Xo(i,t){let e=Date.now(),n=Math.max(e,Math.max(i.time,t.time)),r=Math.max(i.counter,t.counter),o;if(i.time===n&&t.time===n?o=r+1:i.time===n?o=i.counter+1:t.time===n?o=t.counter+1:o=0,n-e>kt)throw new Rt(n,e,kt);if(o>65535)throw new Ft;return{time:n,counter:o,node:i.node}}function hr(i){let t=i.slice(0,ct),e=i.slice(ct,ct+Jn),n=i.slice(ct+Jn),r=parseInt(t,lt),o=parseInt(e,lt);if(isNaN(r)||isNaN(o))throw new Error("invalid clock format");return{time:r,counter:o,node:n}}function Zo(i){let t=new Date(i.time).toISOString(),e=i.counter.toString(16).toUpperCase().padStart(4,"0"),n=i.node.padStart(16,"0");return`${t}-${e}-${n}`}function fr(i){return parseInt(i.slice(0,Bt),36)}function Gn(i,t){return fr(i)-fr(t)}function Xn(i){return hr(i.slice(Bt)).time}function be(i){return i&&i["@@type"]==="file"}function Mt(i){return{"@@type":"file",id:i}}var jt,es=new Uint8Array(16);function Zn(){if(!jt&&(jt=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!jt))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return jt(es)}var mr=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function ts(i){return typeof i=="string"&&mr.test(i)}var gr=ts;var ee=[];for(Lt=0;Lt<256;++Lt)ee.push((Lt+256).toString(16).substr(1));var Lt;function ns(i){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=(ee[i[t+0]]+ee[i[t+1]]+ee[i[t+2]]+ee[i[t+3]]+"-"+ee[i[t+4]]+ee[i[t+5]]+"-"+ee[i[t+6]]+ee[i[t+7]]+"-"+ee[i[t+8]]+ee[i[t+9]]+"-"+ee[i[t+10]]+ee[i[t+11]]+ee[i[t+12]]+ee[i[t+13]]+ee[i[t+14]]+ee[i[t+15]]).toLowerCase();if(!gr(e))throw TypeError("Stringified UUID is invalid");return e}var yr=ns;function is(i,t,e){i=i||{};var n=i.random||(i.rng||Zn)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){e=e||0;for(var r=0;r<16;++r)t[e+r]=n[r];return t}return yr(n)}var dt=is;function Q(i){return Se(i)||be(i)}function Ye(i,t){return i===t?!0:!(!Q(i)||!Q(t)||i["@@type"]!==t["@@type"]||i.id!==t.id)}var Sr=Qe(vr(),1);function rs(i,t){return typeof t!="object"||t===null||Array.isArray(t)?t:Object.fromEntries(Object.entries(t).sort(([e],[n])=>e<n?-1:e>n?1:0))}function ut(i){return JSON.stringify(i,rs)}function ae(i,t=!0){if(V(i)||Array.isArray(i)){let e=pe(i),n;if(Array.isArray(i))n=i.map(r=>ae(r,t));else{n={};for(let[r,o]of Object.entries(i))n[r]=ae(o,t)}return t&&e&&K(n,e),n}return i}function Te(i){return(0,Sr.default)(i)}function V(i){return i&&typeof i=="object"}function xr(i){for(var t=[],e=[i],n=0;e.length;){var r=e.pop();if(typeof r=="boolean")n+=4;else if(typeof r=="string")n+=r.length*2;else if(typeof r=="number")n+=8;else if(typeof r=="object"&&t.indexOf(r)===-1){t.push(r);for(var o in r)e.push(r[o])}}return n}function L(i,t="assertion failed"){if(!i)throw new Error(t)}function Nt(i=16){return dt().replace("-","").slice(0,i)}function Or(i,t){for(let e=i.length-1;e>=0;e--)if(t(i[e]))return e;return-1}function Ir(i,t){let e;return function(...n){let r=this;clearTimeout(e),e=setTimeout(()=>i.apply(r,n),t)}}var Be="__@@oid_do_not_use",Oe="@@id",os="/",pt=":",ti=new WeakMap;function ne(i){let t=pe(i);return L(!!t,`Object ${JSON.stringify(i)} does not have an OID assigned to it`),t}function pe(i){if(V(i))return ti.get(i)??i[Oe]??i[Be]}function K(i,t){return L(V(i),`Only objects can be assigned OIDs, received ${JSON.stringify(i)}`),ni(i)&&Kt(i),ti.set(i,t),i}function ni(i){return!!pe(i)}function Kt(i){return ti.delete(i),i}function ii(i){return i===Oe||i===Be}function ri(i,t,e){if(ni(i))return ne(i);{let n=xe(t,e);return K(i,n),n}}function Dr(i,t,e){if(ni(i)){let n=ne(i);if(Ee(n,t))return ne(i);{let r=xe(t,e);return K(i,r),r}}else{let n=xe(t,e);return K(i,n),n}}var ei={".":"˙","/":"&slash;",":":":"};function _r(i){return i.replace(/[/]/g,ei["/"]).replace(/[:]/g,ei[":"]).replace(/[.]/g,ei["."])}function Er(i){return i.replace(/&slash;/g,"/").replace(/:/g,":").replace(/˙/g,".")}function Z(i,t,e){let n=_r(i)+os+_r(t);return e&&(n+=pt+e),n}function xe(i,t=ls){let{collection:e,id:n}=me(i);return Z(e,n,t())}function me(i){let[t,e]=i.split(pt),[n,r,...o]=t.split("/");o.length&&(r+="/"+o.join("/"));let s;return r.includes(".")?s=r.slice(0,r.indexOf(".")):s=r,{collection:Er(n),id:Er(s),subId:e}}function Ge(i,t){let e=ne(i);if(Array.isArray(i)){let n;for(let r=0;r<i.length;r++)n=i[r],V(n)&&!Q(n)&&(Dr(n,e,t),Ge(n,t))}else if(V(i)&&!Q(i))for(let n of Object.keys(i))V(i[n])&&!Q(i[n])&&(Dr(i[n],e,t),Ge(i[n],t))}function ss(i){if(V(i))return i[Oe]||i[Be]}function as(i){return V(i)&&(delete i[Be],delete i[Oe]),i}function cs(i){let t=ss(i);t&&K(i,t)}function ft(i){if(cs(i),as(i),Array.isArray(i))for(let t=0;t<i.length;t++)ft(i[t]);else if(V(i))for(let t of Object.keys(i))ft(i[t])}function Ut(i){if(Kt(i),Array.isArray(i))for(let t=0;t<i.length;t++)Ut(i[t]);else if(V(i))for(let t of Object.keys(i))Ut(i[t])}function ls(){return dt().slice(0,8)}function he(i){return{"@@type":"ref",id:i}}function Vt(i,t=new Map){if(Array.isArray(i)){let e=ne(i),n=K([],e);for(let r=0;r<i.length;r++){let o=i[r];if(V(o)){if(Se(o))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(be(o)){n[r]=o;continue}else{let s=ne(o);n[r]=he(s),Vt(o,t)}}else n[r]=o}t.set(e,n)}else if(V(i)&&!Q(i)){let e=ne(i),n=K({},e);for(let r of Object.keys(i)){let o=i[r];if(V(o)){if(Se(o))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(be(o))n[r]=o;else{let s=ne(o);n[r]=he(s),Vt(o,t)}}else n[r]=o}t.set(e,n)}else Q(i);return t}function $(i){return i.split(".")[0].split(pt)[0]}function oi(i){let t=$(i),e=xe(t,()=>"\uFFFF");return[`${t}${pt}`,e]}function si(i){let t=$(i);return[`${t}.`,`${t}.\uFFFF`]}function Ee(i,t){return $(i)===$(t)}function ds(i){let{collection:t,id:e,subId:n}=me(i);return Z(t,e,n)}var us=/"\w+\/[^"]+?(\.[^"]+)+\:[\S]+?"/g;function fs(i){return i.replaceAll(us,t=>{let e=t.slice(1,t.length-1);return`"${ds(e)}"`})}function ai(i){return JSON.parse(fs(JSON.stringify(i)))}function Cr(i){return!i.includes(pt)}function Se(i){return i&&typeof i=="object"&&i["@@type"]==="ref"}function ci(i){return V(i)&&!Q(i)}function ps(i,t){return i===t?!0:Q(i)&&Q(t)?Ye(i,t):!1}function ht(i,t,e,n,r=[],o={}){let s=ne(i);function c(p,d,m){if(!ci(d))ps(d,m)||r.push({oid:s,timestamp:e(),data:{op:"set",name:p,value:d}});else{let S=pe(m),g=pe(d);g&&!Ee(s,g)?(d=ae(d,!1),g=xe(s,n),K(d,g)):o.mergeUnknownObjects?!g&&S?(K(d,S),g=S):g=ri(d,s,n):g=ri(d,s,n),L(!!g,"Error: no value OID was resolved during diff. This is a bug in Verdant."),L(Ee(s,g),`Error: value OID ${g} is not related to parent OID ${s}. This is a bug in Verdant.`),m===void 0||g!==S?(Re(d,g,e,n,r),r.push({oid:s,timestamp:e(),data:{op:"set",name:p,value:he(g)}}),S!==void 0&&r.push({oid:S,timestamp:e(),data:{op:"delete"}})):ht(m,d,e,n,r,o)}}if(Array.isArray(i)&&Array.isArray(t)){for(let d=0;d<t.length;d++){let m=t[d],S=i[d];c(d,m,S)}let p=i.length-t.length;if(p>0){for(let d=t.length;d<i.length;d++){let m=i[d],S=pe(m);S&&r.push({oid:S,timestamp:e(),data:{op:"delete"}})}r.push({oid:s,timestamp:e(),data:{op:"list-delete",index:t.length,count:p}})}}else{if(Array.isArray(i)||Array.isArray(t))throw new Error("Cannot diff an array with an object");if(ci(i)&&ci(t)){let p=new Set(Object.keys(i));for(let[d,m]of Object.entries(t)){if(m===void 0&&o.defaultUndefined||(p.delete(d),ii(d)))continue;let S=i[d];c(d,m,S)}if(!o.defaultUndefined)for(let d of p)ii(d)||r.push({oid:s,timestamp:e(),data:{op:"remove",name:d}})}}return r}function Re(i,t,e,n,r=[]){K(i,t),Ge(i,n);let o=Vt(i);for(let s of o.keys()){let c=o.get(s);r.push({oid:s,timestamp:e(),data:{op:"initialize",value:Kt(c)}})}return r}function mt(i){let t={};for(let e of i)e.oid in t?t[e.oid].push(e):t[e.oid]=[e];return t}function Ar(i){let t={};for(let e of i){let n=$(e.oid);n in t?t[n].push(e):t[n]=[e]}return t}function Tr(i){let t={};for(let e of i){let n=$(e.oid);n in t?t[n].push(e):t[n]=[e]}return t}function Me(i){return Array.isArray(i)?!0:(console.error(`Cannot apply list patch; expected array, received ${JSON.stringify(i)}. This suggests your data is changing from a list to an object over time. (OID: ${pe(i)})`),!1)}function je(i,t,e){if(i==null&&t.op!=="initialize")return i;let n=i,r,o;function s(c){e&&Q(c)&&e.push(c)}switch(t.op){case"set":s(n[t.name]),n[t.name]=t.value;break;case"remove":s(n[t.name]),delete n[t.name];break;case"list-push":Me(i)&&i.push(t.value);break;case"list-delete":Me(i)&&(s(i[t.index]),i.splice(t.index,t.count));break;case"list-move-by-index":Me(i)&&(o=i.splice(t.from,1),i.splice(t.to,0,o[0]));break;case"list-remove":if(Me(i))do{let c=t.value;t.only==="last"?Se(c)?r=Or(i,p=>p.id===c.id):r=i.lastIndexOf(c):Se(c)?r=i.findIndex(p=>p.id===c.id):r=i.indexOf(c),r!==-1&&(s(i[r]),i.splice(r,1))}while(!t.only&&r!==-1);break;case"list-add":Me(i)&&(i.some(p=>Se(p)&&Se(t.value)?p.id===t.value.id:p===t.value)||i.push(t.value));break;case"list-move-by-ref":Me(i)&&(r=i.findIndex(c=>Ye(c,t.value)),o=i.splice(r,1),i.splice(t.index,0,o[0]));break;case"list-insert":if(Me(i)){if(!t.value&&!t.values)throw new Error(`Cannot apply list insert patch; expected value or values, received ${JSON.stringify(t)}`);t.value?i.splice(t.index,0,t.value):i.splice(t.index,0,...t.values)}break;case"delete":Array.isArray(i)?i.forEach(s):V(i)&&Object.values(i||{}).forEach(s);return;case"initialize":return ae(t.value);case"touch":return i;default:throw new Error(`Unsupported patch operation: ${t.op}`)}return i}function $t(i,t,e=[]){if(Array.isArray(i))for(let n=0;n<i.length;n++){let r=i[n];i[n]=Pr(r,t,e),V(i[n])&&$t(i[n],t,e)}else if(!be(i)){if(V(i)){L(pe(i),`Object ${JSON.stringify(i)} must have an oid`);for(let n of Object.keys(i))i[n]=Pr(i[n],t,e),V(i[n])&&$t(i[n],t,e)}}return e}function Pr(i,t,e){if(Se(i)){e.push(i.id);let n=t.get(i.id);return L(!!n,`No value was found in object map for ${i.id}`),K(n,i.id)}else return i}var hs=i=>({type:"object",...i}),ms=i=>({type:"array",...i}),gs=i=>({type:"string",...i}),ys=i=>({type:"number",...i}),bs=i=>({type:"boolean",...i}),ws=i=>({type:"any",...i}),vs=i=>({type:"map",...i}),Ss=i=>({type:"file",...i}),Rr={object:hs,array:ms,string:gs,number:ys,boolean:bs,any:ws,map:vs,file:Ss};var Br=Qe(at(),1);function li(i){return i.equals!==void 0}function di(i){return i.gte!==void 0||i.lte!==void 0||i.gt!==void 0||i.lt!==void 0}function xs(i){return!!i.match}function ui(i){return i.startsWith!==void 0}function Fr(i){return!di(i)&&!li(i)&&!xs(i)&&!ui(i)&&i.order}function we(i){return i.type==="any"?!0:i.type==="map"?!1:i.nullable}function Ce(i){return i?i.type==="map"||i.type==="array"?!0:i.type==="file"?!1:i.default!==void 0:!1}function pi(i){if(!(!i||!Ce(i)))return i.type==="file"?we(i)?null:void 0:i.type==="map"?{}:i.type==="array"?we(i)?null:[]:i.type==="object"?we(i)?null:void 0:typeof i.default=="function"?i.default():i.default}function Pe(i,t){for(let[e,n]of Object.entries(i.fields)){let r=hi(n);(r!==void 0&&t[e]===void 0||!we(n)&&t[e]===null)&&(t[e]=r),t[e]&&Le(t[e],n)}return t}function Le(i,t){if(i==null)return i;if(t.type==="object")for(let[e,n]of Object.entries(t.properties)){if(i[e]===void 0){let r=hi(n);r!==void 0&&(i[e]=r)}Le(i[e],n)}else if(t.type==="array")for(let e of i)Le(e,t.items);else if(t.type==="map")for(let[e,n]of Object.entries(i))e===Oe||e===Be||Le(n,t.values)}function hi(i){if(i.type==="string"||i.type==="number"||i.type==="boolean"||i.type==="any"){if(i.default&&typeof i.default=="function")return i.default();if(i.default!==void 0)return JSON.parse(JSON.stringify(i.default))}if(i.type==="array")return[];if(i.type==="map")return{};if(i.type!=="any"&&i.nullable)return null;if(i.type==="object"&&i.default){let t=typeof i.default=="function"?i.default():JSON.parse(JSON.stringify(i.default));for(let[e,n]of Object.entries(i.properties))t[e]===void 0&&(t[e]=hi(n));return t}}function mi(i,t){for(let[e,n]of Object.entries(t))e===Oe||e===Be||(i.fields[e]?fi(n,i.fields[e]):delete t[e]);return t}function fi(i,t){if(V(i)&&t.type==="object")for(let[e,n]of Object.entries(i))t.properties[e]?fi(n,t.properties[e]):delete i[e];else if(Array.isArray(i)&&t.type==="array")for(let e of i)fi(e,t.items)}function kr(i,t){for(let[e,n]of Object.entries(t))if(e!==Oe){if(!i[e])return{type:"invalid-key",fieldPath:[e],message:`Invalid field "${e}"`};if(n){let r=Fe({field:i[e],value:n,fieldPath:[e]});if(r)return r}}}function Fe({field:i,value:t,fieldPath:e=[],depth:n,requireDefaults:r}){if(!(n!==void 0&&n<=0)&&!(we(i)&&t===null)){if(t===null&&(r||!Ce(i)))return{type:"no-default",fieldPath:e,message:`Invalid null value for field ${Ae(e)}`};if(i.type==="object"){if(!V(t))return{type:"invalid-type",fieldPath:e,message:`Expected object${i.nullable?" or null":""} for field ${Ae(e)}, got ${t}`};for(let[o,s]of Object.entries(i.properties))o!==Oe&&t[o]&&Fe({field:s,value:t[o],fieldPath:[...e,o],depth:n!==void 0?n-1:void 0});for(let o of Object.keys(t))if(!i.properties[o])return{type:"invalid-key",fieldPath:[...e,o],message:`Invalid unexpected field "${o}" on value ${Ae(e)}`}}else if(i.type==="array"){if(!Array.isArray(t))return t===null&&i.nullable?void 0:{type:"invalid-value",fieldPath:e,message:`Expected array${i.nullable?" or null":""} for field ${Ae(e)}, got ${t}`};for(let o of t)Fe({field:i.items,value:o,fieldPath:[...e,"[]"],depth:n!==void 0?n-1:void 0})}else if(i.type==="map"){if(!V(t))return{type:"invalid-type",fieldPath:e,message:`Expected map for field ${Ae(e)}, got ${t}`};for(let[o,s]of Object.entries(t))Fe({field:i.values,value:s,fieldPath:[...e,o],depth:n!==void 0?n-1:void 0})}else if(i.type==="string"){if(typeof t!="string")return{type:"invalid-type",fieldPath:e,message:`Expected string ${i.nullable?" or null":""} for field ${Ae(e)}, got ${t}`};if(i.options&&!i.options.includes(t))return{type:"invalid-value",fieldPath:e,message:`Expected one of ${i.options.join(", ")} for field ${Ae(e)}, got ${t}`}}else if(i.type==="boolean"){if(typeof t!="boolean")return{type:"invalid-type",fieldPath:e,message:`Expected boolean ${i.nullable?" or null":""} for field ${Ae(e)}, got ${t}`}}else if(i.type==="number"){if(typeof t!="number")return{type:"invalid-type",fieldPath:e,message:`Expected number ${i.nullable?" or null":""} for field ${Ae(e)}, got ${t}`}}else i.type}}function Ae(i){return i.length===0?"root":i.join(".")}function Ne(i,t){return i.type==="object"?i.properties[t]:i.type==="array"?i.items:i.type==="map"?i.values:i.type==="any"?i:"type"in i?null:i[t]??null}function gi({synthetics:i,indexes:t,...e}){let n={...i,...t};for(let[r,o]of Object.entries(e.fields))"indexed"in o&&(n[r]={field:r});return{...e,indexes:n}}function gt(i){return i}gt.collection=gi;gt.fields=Rr;gt.generated={id:Br.default};var zt="\uFFFFFE",Os="\0",Is="\uFFFFFF";function ce(...i){let t=Ds(i);return t.length===1?t[0]:t}function Ue(...i){return i.join(zt)+`${Is}`}function Ve(...i){return i.join(zt)+`${zt}${Os}`}function Ds(i){let t=[[]];for(let e of i)if(Array.isArray(e)){let n=[];for(let r of t)for(let o of e)n.push(r.concat(o));t=n}else for(let n of t)n.push(`${e}`);return Array.from(new Set(t.map(e=>e.join(zt))))}function _s(i){return!!i.field}function Es(i,t){let e={};for(let[n,r]of Object.entries(i.indexes||{})){let o=r;_s(o)?e[n]=ve(t[o.field]):e[n]=ve(o.compute(t))}return e}function Cs(i,t){return Object.entries(i.compounds||{}).reduce((e,[n,r])=>(e[n]=ce(...r.of.map(o=>t[o])),e),{})}function Ps(i,t){return Object.entries(i.fields).reduce((e,[n,r])=>("indexed"in r&&(e[n]=ve(t[n])),e),{})}function qt(i,t){let e={[i.primaryKey]:t[i.primaryKey],...Ps(i,t),...Es(i,t)};return Object.assign(e,Cs(i,{...t,...e})),e["@@@snapshot"]=t,e}var As="null";function ve(i){if(i===null)return As;if(typeof i=="string"||typeof i=="number")return i;if(typeof i=="boolean"||i===null)return`${i}`;if(i===void 0)return"undefined";if(Array.isArray(i))return i.map(ve);throw new Error(`Unsupported index value: ${i}`)}var Mr={version:0,collections:{}};function Wt(i,t,e){let n=typeof t=="function",r=n?Mr:i,o=n?i:t,s=n?t:e,c=Object.keys(o.collections).filter(v=>r.collections[v]&&ut(r.collections[v])!==ut(o.collections[v])),p=Object.keys(r.collections).filter(v=>!o.collections[v]),d=Object.keys(o.collections).filter(v=>!r.collections[v]),m=new Set;for(let v of c){let I=r.collections[v].fields,x=o.collections[v].fields;Object.keys(x).some(D=>!I[D]?.default&&x[D]?.default)&&m.add(v),Object.keys(I).some(D=>!x[D])&&m.add(v)}let S={},g={};for(let v of[...c,...d]){let I=Ht(r.collections[v]),x=Ht(o.collections[v]),D=x.filter(b=>!I.find(_=>_.name===b.name)),T=I.filter(b=>!x.find(_=>_.name===b.name));D.length>0&&(S[v]=D,c.includes(v)&&m.add(v)),T.length>0&&(g[v]=T,c.includes(v)&&m.add(v))}let C=(v,I)=>Pe(o.collections[v],I),w=v=>I=>{let x=o.collections[v];return Pe(x,mi(x,I))};return{version:o.version,migrate:async v=>{let I=[];if(await s({migrate:async(x,D)=>{let T=w(x),b=async _=>{let u=await D(_);return K(u,ne(_)),T(u)};await v.migrate(x,b),I.push(x),m.delete(x)},identity:x=>x,withDefaults:C,info:{changedCollections:c,addedCollections:d,removedCollections:p},queries:v.queries,mutations:v.mutations}),o.version>1){v.log("debug","auto-migrating collections with new defaults",m);for(let D of m)await v.migrate(D,w(D)),I.push(D);let x=c.filter(D=>!I.includes(D));x.length>0&&console.error(`Unmigrated changed collections from version ${r.version} to version ${o.version}:`,x)}},removedCollections:p,addedIndexes:S,removedIndexes:g,allCollections:Object.keys(o.collections),changedCollections:c,addedCollections:d,oldCollections:Object.keys(r.collections),oldSchema:r,newSchema:o}}function Ht(i){return i?[...Object.keys(i.indexes||{}).map(t=>({name:t,multiEntry:["array","string[]","number[]","boolean[]"].includes(i.indexes[t].type),synthetic:!0,compound:!1})),...Object.keys(i.compounds||{}).map(t=>({name:t,multiEntry:i.compounds[t].of.some(e=>(i.fields[e]||i.indexes[e]).type==="array"),synthetic:!1,compound:!0}))]:[]}function yi(i,t){return Wt(t?i:{version:0,collections:{}},t||i,async({migrate:n,info:r})=>{if((t||i).version!==1)for(let o of r.changedCollections)await n(o,s=>s)})}function bi(i,t,e){let n=typeof t=="function"||t===void 0,r=n?Mr:i,o=n?i:t,s=n?t:e;L(r,"Invalid arguments to createMigration"),L(o,"Invalid arguments to createMigration");let{changedCollections:c,addedCollections:p,removedCollections:d,addedIndexes:m,removedIndexes:S,autoMigratedCollections:g,autoMigration:C}=Ts(r,o);return{version:o.version,migrate:async w=>{let v=[];if(await s?.({migrate:async(x,D)=>{let T=C(x),b=async _=>{let u=await D(_);K(u,ne(_));let h=T(u),l=kr(o.collections[x].fields,h);return h};await w.migrate(x,b),v.push(x),g.delete(x)},info:{changedCollections:c,addedCollections:p,removedCollections:d},queries:w.queries,mutations:w.mutations}),o.version>1){w.log("debug","auto-migrating collections with new defaults",g);for(let D of g)await w.migrate(D,C(D)),v.push(D);for(let D of d)await w.deleteCollection(D);let x=c.filter(D=>!v.includes(D));x.length>0&&console.error(`Unmigrated changed collections from version ${r.version} to version ${o.version}:`,x)}},removedCollections:d,addedIndexes:m,removedIndexes:S,allCollections:Object.keys(o.collections),changedCollections:c,addedCollections:p,oldCollections:Object.keys(r.collections),oldSchema:r,newSchema:o}}function Ts(i,t){let e=Object.keys(t.collections).filter(m=>i.collections[m]&&ut(i.collections[m])!==ut(t.collections[m])),n=Object.keys(i.collections).filter(m=>!t.collections[m]),r=Object.keys(t.collections).filter(m=>!i.collections[m]),o=new Set;for(let m of e){let S=i.collections[m].fields,g=t.collections[m].fields;Object.keys(g).some(C=>!Ce(S[C])&&Ce(g[C]))&&o.add(m),Object.keys(S).some(C=>!g[C])&&o.add(m)}let s={},c={};for(let m of[...e,...r]){let S=Ht(i.collections[m]),g=Ht(t.collections[m]),C=g.filter(v=>!S.find(I=>I.name===v.name)),w=S.filter(v=>!g.find(I=>I.name===v.name));C.length>0&&(s[m]=C,e.includes(m)&&o.add(m)),w.length>0&&(c[m]=w,e.includes(m)&&o.add(m))}return{changedCollections:e,addedCollections:r,removedCollections:n,addedIndexes:s,removedIndexes:c,autoMigratedCollections:o,withDefaults:(m,S)=>Pe(t.collections[m],S),autoMigration:m=>S=>{let g=t.collections[m];return Pe(g,mi(g,S))}}}var Qt=class{constructor(t,e){this.getNow=t;this.createSubId=e;this.isPrimitive=t=>!V(t)||Q(t);this.createDiff=(t,e,n={})=>ht(t,e,this.getNow,this.createSubId,[],n);this.createInitialize=(t,e)=>Re(t,e,this.getNow,this.createSubId);this.createSet=(t,e,n)=>{if(this.isPrimitive(n))return[{oid:t,timestamp:this.getNow(),data:{op:"set",name:e,value:n}}];{let r=xe(t,this.createSubId);return[...Re(n,r,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"set",value:he(r),name:e}}]}};this.createRemove=(t,e)=>[{oid:t,timestamp:this.getNow(),data:{op:"remove",name:e}}];this.createListPush=(t,e)=>{if(this.isPrimitive(e))return[{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:e}}];{let n=xe(t,this.createSubId);return[...Re(e,n,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:he(n)}}]}};this.createListAdd=(t,e)=>this.isPrimitive(e)?[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:e}}]:[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:he(e)}}];this.createListInsert=(t,e,n)=>{if(this.isPrimitive(n))return[{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:n,index:e}}];{let r=xe(t,this.createSubId);return[...Re(n,r,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:he(r),index:e}}]}};this.createListRemove=(t,e,n)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-remove",value:e,only:n}}];this.createListDelete=(t,e,n=1)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-delete",index:e,count:n}}];this.createListMoveByRef=(t,e,n)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-move-by-ref",value:e,index:n}}];this.createListMoveByIndex=(t,e,n)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-move-by-index",from:e,to:n}}];this.createDelete=t=>[{oid:t,timestamp:this.getNow(),data:{op:"delete"}}];this.createDeleteAll=t=>t.map(e=>({oid:e,timestamp:this.getNow(),data:{op:"delete"}}))}};var U=class{constructor(t){this._onAllUnsubscribed=t;this.subscribers={};this.counts={};this._disabled=!1;this.disposed=!1;this.subscriberCount=t=>this.counts[t]??0;this.totalSubscriberCount=()=>Object.values(this.counts).reduce((t,e)=>t+e,0);this.subscribe=(t,e)=>{let n=Nt(),r=this.subscribers[t];return r||(r=this.subscribers[t]={}),r[n]=e,this.counts[t]=(this.counts[t]||0)+1,()=>{this.subscribers[t]&&(delete this.subscribers[t][n],this.counts[t]--,this.counts[t]===0&&(delete this.subscribers[t],delete this.counts[t],this._onAllUnsubscribed&&this._onAllUnsubscribed(t)))}};this.emit=(t,...e)=>{this._disabled||this.subscribers[t]&&Object.values(this.subscribers[t]).forEach(n=>n(...e))};this.dispose=()=>{this._disabled=!0,this.disposed=!0;let t=Object.keys(this.subscribers);this.subscribers={},this.counts={},t.forEach(e=>{this._onAllUnsubscribed&&this._onAllUnsubscribed(e)})};this.disable=()=>{this._disabled=!0}}get disabled(){return this._disabled}};function jr(i,t,e,n){if(t==null)return[{oid:i,timestamp:n(),data:{op:"delete"}}];let r=ae(t),o=[];for(let s of e){let c=Rs(i,r,s,n);o.unshift(...c),je(r,s.data)}return o}function Rs(i,t,e,n){let r=e.data;switch(r.op){case"set":case"remove":return[{oid:i,timestamp:n(),data:{op:"set",name:r.name,value:t[r.name]}}];case"list-insert":return[{oid:i,timestamp:n(),data:{op:"list-delete",index:r.index,count:1}}];case"list-delete":return[{oid:i,timestamp:n(),data:{op:"list-insert",index:r.index,values:t.slice(r.index,r.count)}}];case"list-move-by-ref":return[{oid:i,timestamp:n(),data:{op:"list-move-by-ref",value:r.value,index:t.indexOf(r.value)}}];case"list-move-by-index":return[{oid:i,timestamp:n(),data:{op:"list-move-by-index",from:r.to,to:r.from}}];case"delete":return[{oid:i,timestamp:n(),data:{op:"initialize",value:t}}];case"list-push":return[{oid:i,timestamp:n(),data:{op:"list-remove",value:r.value,only:"last"}}];case"list-remove":if(r.only==="last"){let o=t.lastIndexOf(r.value);return[{oid:i,timestamp:n(),data:{op:"list-insert",index:o,values:[r.value]}}]}else if(r.only==="first"){let o=t.indexOf(r.value);return[{oid:i,timestamp:n(),data:{op:"list-insert",index:o,values:[r.value]}}]}else{let o=[],s=t.indexOf(r.value);for(;s!==-1;)o.push(s),s=t.indexOf(r.value,s+1);return o.map(c=>({oid:i,timestamp:n(),data:{op:"list-insert",index:c,value:r.value}}))}case"list-add":return[{oid:i,timestamp:n(),data:{op:"list-remove",value:r.value,only:"last"}}];case"initialize":return[{oid:i,timestamp:n(),data:{op:"delete"}}];case"touch":return[];default:throw new Error(`Cannot undo operation type: ${r.op}`)}}var Xe=class{constructor(t){this.flusher=t;this.batches=new Map;this.flush=t=>{let e=this.batches.get(t);if(e)return e.flush()};this.discard=t=>{let e=this.batches.get(t);e&&(e.discard(),this.batches.delete(t))};this.flushAll=()=>[...this.batches.values()].map(t=>t.flush());this.getSize=t=>{let e=this.batches.get(t);return e?e.items.length:0}}add({key:t,userData:e,items:n,max:r,timeout:o}){let s=this.batches.get(t);return s||(s=new wi({max:r||null,startedAt:Date.now(),userData:e,timeout:o||null,flusher:this.flusher,key:t}),this.batches.set(t,s)),s.update({items:n,max:r,timeout:o,userData:e}),s}},wi=class{constructor({max:t,startedAt:e,timeout:n,userData:r,flusher:o,key:s}){this.items=[];this.update=({items:t,max:e,timeout:n,userData:r})=>{this.items.push(...t),e!==void 0&&(this.max=e),n!==void 0&&(this.timeout=n),r&&(this.userData=r);let o=this.items.length!==0&&this.timeout!==null&&!this.flushTimeout;this.max!==null&&this.items.length>=this.max?this.flush():o&&this.timeout!==null&&(this.flushTimeout=setTimeout(this.flush,this.timeout))};this.flush=()=>{this.flushTimeout&&clearTimeout(this.flushTimeout),this.flushTimeout=void 0;let t=this.items;return this.items=[],this.flusher(t,this.key,this.userData)};this.discard=()=>{this.flushTimeout&&clearTimeout(this.flushTimeout),this.flushTimeout=void 0,this.items=[]};this.max=t,this.startedAt=e,this.timeout=n,this.userData=r,this.flusher=o,this.key=s}};function Lr(i,t){let e,n;return(...r)=>{let o=t();return e&&e.length===o.length&&e.every((s,c)=>s===o[c])||(e=[...o],n=i(...r)),n}}var vi=(d=>(d[d.InvalidRequest=4e3]="InvalidRequest",d[d.BodyRequired=4001]="BodyRequired",d[d.NoToken=4010]="NoToken",d[d.InvalidToken=4011]="InvalidToken",d[d.TokenExpired=4012]="TokenExpired",d[d.NotFound=4040]="NotFound",d[d.Unexpected=5e3]="Unexpected",d[d.ConfigurationError=5010]="ConfigurationError",d[d.NoFileStorage=5011]="NoFileStorage",d))(vi||{}),Nr=class extends Error{constructor(e,n,r){super(r??`Verdant error: ${e}`,{cause:n});this.code=e;this.toResponse=()=>JSON.stringify({code:this.code})}static{this.Code=vi}get httpStatus(){let e=Math.floor(this.code/10);return e<600?e:500}};function Ur(i){return typeof i=="object"&&"code"in i&&typeof i.code=="number"}function le(i){return i instanceof Error&&i.name==="AbortError"}function J(i){return new Promise((t,e)=>{i.onsuccess=()=>{t(i.result)},i.onerror=()=>{i.error&&le(i.error)?t(i.result):e(i.error)}})}function yt(i,t){return new Promise((e,n)=>{let r=i.transaction([t],"readonly"),s=r.objectStore(t).openCursor(),c=0,p=0;s.onsuccess=function(d){let m=s.result;m&&(c++,p=p+xr(m.value),m.continue())},s.onerror=function(d){s.error&&le(s.error)?e({count:c,size:p}):n(s.error)},r.oncomplete=function(d){e({count:c,size:p})},r.onabort=function(d){n(d)},r.onerror=function(d){n(d)}})}function Vr(i,t){let e=i.transaction(t,"readonly"),n=t.map(r=>{let o=e.objectStore(r);return J(o.getAll())});return Promise.all(n)}async function Ke(i){i.close(),await new Promise((t,e)=>{t()})}async function Jt(i,t=window.indexedDB){let e=t.deleteDatabase([i,"meta"].join("_")),n=t.deleteDatabase([i,"collections"].join("_"));await Promise.all([new Promise((r,o)=>{e.onsuccess=r,e.onerror=o}),new Promise((r,o)=>{n.onsuccess=r,n.onerror=o})]),window.location.reload()}function Kr(i,t=window.indexedDB){return J(t.deleteDatabase(i))}async function $r(i=window.indexedDB){return i.databases()}function Yt(i,t,e,n,r){let o=i.transaction(t,e);if(n){let s=()=>{r?.("debug","aborting transaction");try{o.abort()}catch(c){r?.("debug","aborting transaction failed",c)}};n.addEventListener("abort",s),o.addEventListener("error",()=>{n.removeEventListener("abort",s)}),o.addEventListener("complete",()=>{n.removeEventListener("abort",s)})}return o}var Ie=class{constructor(){this._disposes=[];this.disposed=!1;this.dispose=()=>{this.disposed=!0,this._disposes.forEach(t=>t()),this._disposes=[]};this.addDispose=t=>{this._disposes.push(t)}}};var se=class extends Ie{constructor(e,{log:n}={}){super();this.db=e;this.globalAbortController=new AbortController;this.createTransaction=(e,n)=>{let r=Yt(this.db,e,n?.mode||"readonly",n?.abort,this.log);return this.globalAbortController.signal.addEventListener("abort",r.abort),r.addEventListener("complete",()=>{this.globalAbortController.signal.removeEventListener("abort",r.abort)}),r.addEventListener("error",()=>{this.globalAbortController.signal.removeEventListener("abort",r.abort)}),r};this.run=async(e,n,r)=>{if(this.disposed||r?.transaction?.error)return Promise.resolve(void 0);let s=(r?.transaction||this.createTransaction([e],r)).objectStore(e),c=n(s);return J(c)};this.runAll=async(e,n,r)=>{if(this.disposed||r?.transaction?.error)return Promise.resolve([]);let s=(r?.transaction||this.createTransaction([e],r)).objectStore(e),c=n(s);return Promise.all(c.map(J))};this.iterate=async(e,n,r,o)=>{let c=(o?.transaction||this.createTransaction([e],o)).objectStore(e),p=n(c);return Array.isArray(p)?Promise.all(p.map(d=>new Promise((m,S)=>{d.onsuccess=()=>{let g=d.result;g?(r(g.value,c),g.continue()):m()},d.onerror=()=>{d.error&&le(d.error)?m():S(d.error)}}))).then(()=>{}):new Promise((d,m)=>{p.onsuccess=()=>{let S=p.result;S?(r(S.value,c),S.continue()):d()},p.onerror=()=>{p.error&&le(p.error)?d():m(p.error)}})};this.clear=e=>this.run(e,n=>n.clear(),{mode:"readwrite"});this.log=n,this.addDispose(()=>{this.globalAbortController.abort()})}};var Gt=class extends se{constructor(){super(...arguments);this.getAckInfo=async()=>{let e=await this.run("info",n=>n.get("ack"));return e||{globalAckTimestamp:null,type:"ack"}};this.setGlobalAck=async e=>{await this.run("info",n=>n.put({type:"ack",globalAckTimestamp:e}),{mode:"readwrite"})}}};var Xt=class extends se{constructor(e,n){super(e,n);this.getAllForDocument=async(e,{mode:n="readonly",transaction:r}={})=>{let o=[];return await this.iterateOverAllForDocument(e,s=>{o.push(s)},{mode:n,transaction:r}),o};this.iterateOverAllForDocument=async(e,n,{mode:r="readonly",transaction:o}={})=>this.iterate("baselines",s=>{let c=$(e),[p,d]=oi(e),[m,S]=si(e);return[s.openCursor(IDBKeyRange.only(c)),s.openCursor(IDBKeyRange.bound(p,d,!1,!1)),s.openCursor(IDBKeyRange.bound(m,S,!1,!1))]},n,{mode:r,transaction:o});this.iterateOverAllForCollection=async(e,n,{mode:r="readonly",transaction:o}={})=>this.iterate("baselines",s=>[s.openCursor(IDBKeyRange.bound(e,e+"\uFFFF",!1,!1))],n,{mode:r,transaction:o});this.getAllForMultipleDocuments=async(e,{mode:n="readonly"}={})=>(await this.runAll("baselines",o=>e.flatMap(s=>{let c=$(s),[p,d]=oi(s),[m,S]=si(s);return[o.get(c),o.getAll(IDBKeyRange.bound(p,d,!1,!1)),o.getAll(IDBKeyRange.bound(m,S,!1,!1))]}),{mode:n})).flat();this.getAllSince=async(e,{mode:n="readonly"}={})=>this.run("baselines",r=>{let o=e?IDBKeyRange.lowerBound(e,!0):void 0;return r.index("timestamp").getAll(o)},{mode:n});this.get=async(e,{transaction:n,mode:r="readonly"}={})=>this.run("baselines",o=>o.get(e),{mode:r,transaction:n});this.set=async(e,{transaction:n}={})=>{await this.run("baselines",r=>r.put(e),{mode:"readwrite",transaction:n})};this.setAll=async(e,{transaction:n}={})=>{await this.runAll("baselines",r=>e.map(o=>r.put(o)),{mode:"readwrite",transaction:n})};this.reset=()=>this.clear("baselines");this.delete=async(e,{transaction:n})=>{await this.run("baselines",r=>r.delete(e),{mode:"readwrite",transaction:n})}}};var zr=Qe(at(),1);var Zt=class extends se{constructor(){super(...arguments);this.get=async({transaction:e}={})=>{if(this.cached)return this.cached;let n=await this.run("info",r=>r.get("localReplicaInfo"),{transaction:e});return n?(this.cached=n,n):(this._creating||(this._creating=(async()=>{let o={type:"localReplicaInfo",id:(0,zr.default)(),ackedLogicalTime:null,lastSyncedLogicalTime:null};await this.run("info",s=>s.put(o),{mode:"readwrite"}),this.cached=o})()),await this._creating,this.get({transaction:e}))};this.update=async(e,{transaction:n}={})=>{let r=await this.get({transaction:n});Object.assign(r,e),await this.run("info",o=>o.put(r),{mode:"readwrite"}),this.cached=r};this.reset=async()=>{let e=await this.get();e.ackedLogicalTime=null,e.lastSyncedLogicalTime=null,await this.run("info",n=>n.put(e),{mode:"readwrite"})}}};var en=class{constructor(t){this.meta=t;this.createOperation=async t=>{let e=await this.meta.localReplica.get();return{type:"op",timestamp:this.meta.now,replicaId:e.id,operations:t.operations.map(n=>({data:n.data,oid:n.oid,timestamp:n.timestamp}))}};this.createMigrationOperation=async({targetVersion:t,...e})=>{let n=await this.meta.localReplica.get();return{type:"op",operations:e.operations.map(r=>({...r,timestamp:this.meta.time.zero(t)})),timestamp:this.meta.time.zero(t),replicaId:n.id}};this.createSyncStep1=async t=>{let e=await this.meta.localReplica.get(),n=t===null?null:e.lastSyncedLogicalTime,r=[],o=new Set;n?await this.meta.operations.iterateOverAllLocalOperations(c=>{r.push({data:c.data,oid:c.oid,timestamp:c.timestamp}),o.add($(c.oid))},{after:n,mode:"readwrite"}):await this.meta.operations.iterateOverAllOperations(c=>{r.push({data:c.data,oid:c.oid,timestamp:c.timestamp}),o.add($(c.oid))},{mode:"readwrite"});let s=[];return n||(s=await this.meta.baselines.getAllSince("")),{type:"sync",schemaVersion:this.meta.schema.currentVersion,timestamp:this.meta.now,replicaId:e.id,resyncAll:!e.lastSyncedLogicalTime,operations:r,baselines:s,since:n}};this.createPresenceUpdate=async t=>{let e=await this.meta.localReplica.get();return{type:"presence-update",presence:t,replicaId:e.id}};this.createHeartbeat=async()=>{let t=await this.meta.localReplica.get();return{type:"heartbeat",timestamp:this.meta.now,replicaId:t.id}};this.createAck=async t=>{let e=await this.meta.localReplica.get();return{type:"ack",timestamp:this.meta.now,replicaId:e.id,nonce:t}}}};var tn=class extends se{constructor(e,n){super(e,n);this.iterateOverAllOperationsForDocument=async(e,n,{to:r,from:o,after:s,mode:c="readonly",transaction:p}={})=>{let m=(p||this.createTransaction(["operations"],{mode:c})).objectStore("operations"),S=m.index("d_t"),g=o||s,C=g?ce(e,g):Ve(e),w=r?ce(e,r):Ue(e),v=IDBKeyRange.bound(C,w,!!s,!1),I=S.openCursor(v,"next");return new Promise((x,D)=>{let T;I.onsuccess=b=>{let _=I.result;if(_){let u=_.value;L(u.oid.startsWith(e)),L(T===void 0||T<=u.timestamp,`expected ${T} <= ${u.timestamp}`),n(u,m),T=u.timestamp,_.continue()}else x()},I.onerror=b=>{if(le(I.error)){x();return}else D(I.error)}})};this.iterateOverAllOperationsForEntity=async(e,n,{after:r,to:o,mode:s,transaction:c})=>{let d=(c||this.createTransaction(["operations"],{mode:s})).objectStore("operations"),m=r?ce(e,r):Ve(e),S=o?ce(e,o):Ue(e),g=IDBKeyRange.bound(m,S,!!r,!1),C=d.openCursor(g,"next");return new Promise((w,v)=>{let I;C.onsuccess=x=>{let D=C.result;if(D){let T=D.value;L(T.oid.startsWith(e)),L(I===void 0||I<=T.timestamp,`expected ${I} <= ${T.timestamp}`),n(T,d),I=T.timestamp,D.continue()}else w()},C.onerror=x=>{le(C.error)?w():v(C.error)}})};this.iterateOverAllOperationsForCollection=async(e,n,{after:r,to:o,mode:s,transaction:c})=>{let p=c||this.createTransaction(["operations"],{mode:s});return this.iterate("operations",d=>d.openCursor(IDBKeyRange.bound(e,e+"\uFFFF",!1,!1),"next"),n,{mode:s,transaction:p})};this.iterateOverAllLocalOperations=async(e,{before:n,after:r,mode:o="readonly",transaction:s})=>{let p=(s||this.createTransaction(["operations"],{mode:o})).objectStore("operations"),d=p.index("l_t"),m=r?ce(!0,r):Ve(!0),S=n?ce(!0,n):Ue(!0),g=IDBKeyRange.bound(m,S,!!r,!0),C=d.openCursor(g,"next");return new Promise((w,v)=>{let I;C.onsuccess=x=>{let D=C.result;if(D){let T=D.value;L(I===void 0||I<=T.timestamp,`expected ${I} <= ${T.timestamp}`),e(T,p),I=T.timestamp,D.continue()}else w()},C.onerror=x=>{le(C.error)?w():v(C.error)}})};this.iterateOverAllOperations=async(e,{before:n,transaction:r,mode:o,from:s})=>{await this.iterate("operations",c=>{let p=s?Ve(s):void 0,d=n?Ue(n):void 0,m=p&&d?window.IDBKeyRange.bound(p,d,!1,!0):p?window.IDBKeyRange.lowerBound(p,!1):d?window.IDBKeyRange.upperBound(d,!0):void 0;return c.index("timestamp").openCursor(m,"next")},e,{mode:o,transaction:r})};this.addOperations=async(e,{transaction:n}={})=>this.insert(e.map(this.addCompoundIndexes),{transaction:n});this.addCompoundIndexes=e=>({...e,oid_timestamp:ce(e.oid,e.timestamp),l_t:ce(e.isLocal,e.timestamp),d_t:ce($(e.oid),e.timestamp)});this.insert=async(e,{transaction:n})=>{let r=new Set;return await this.runAll("operations",o=>e.map(s=>(r.add($(s.oid)),o.put(s))),{mode:"readwrite",transaction:n}),Array.from(r)};this.reset=()=>this.clear("operations")}};var nn=class{constructor(t,e){this.db=t;this.currentVersion=e;this.cached=null;this.get=async()=>{if(this.cached)return this.cached;let r=this.db.transaction("info","readonly").objectStore("info").get("schema"),o=await J(r);return o?(this.cached=JSON.parse(o.schema),this.cached):null};this.set=async t=>{let o=this.db.transaction("info","readwrite").objectStore("info").put({type:"schema",schema:JSON.stringify(t)});this.cached=t,await J(o)}}};var bt=class extends U{constructor({disableRebasing:e,context:n}){super();this.time=new Tt;this.disableRebasing=!1;this._closing=!1;this.setContext=e=>{this.context=e};this.close=()=>{this._closing=!0};this.createTransaction=(e,n={})=>Yt(this.db,e,"readwrite",n.abort,this.context.log);this.getAllDocumentRelatedOids=async e=>{let n=new Set,r=$(e);L(r===e,"Must be root document OID"),n.add(r);let o=this.createTransaction(["baselines","operations"]);return await Promise.all([this.baselines.iterateOverAllForDocument(r,s=>{n.add(s.oid)},{transaction:o}),this.operations.iterateOverAllOperationsForDocument(r,s=>{n.add(s.oid)},{transaction:o})]),Array.from(n)};this.getAllCollectionRelatedOids=async e=>{let n=new Set,r=this.db.transaction(["baselines","operations"],"readwrite");return await Promise.all([this.baselines.iterateOverAllForCollection(e,o=>{n.add(o.oid)},{transaction:r}),this.operations.iterateOverAllOperationsForCollection(e,o=>{n.add(o.oid)},{transaction:r})]),Array.from(n)};this.getDocumentSnapshot=async(e,n={})=>{let r=$(e);L(r===e,"Must be root document OID");let o=this.db.transaction(["baselines","operations"],"readwrite"),s=await this.baselines.getAllForDocument(r,{transaction:o}),c=new Map;for(let d of s)d.snapshot&&K(d.snapshot,d.oid),c.set(d.oid,d.snapshot);await this.operations.iterateOverAllOperationsForDocument(r,d=>{let m=c.get(d.oid)||void 0,S=je(m,d.data);S&&K(S,d.oid),c.set(d.oid,S)},{transaction:o,to:n.to||this.now});let p=c.get(r);return p&&$t(p,c),p};this.getDocumentData=async(e,n)=>{let r=this.createTransaction(["baselines","operations"],n),o=[],s={};return await Promise.all([this.baselines.iterateOverAllForDocument(e,c=>{o.push(c)},{transaction:r}),this.operations.iterateOverAllOperationsForDocument(e,c=>{s[c.oid]??=[],s[c.oid].push(c)},{transaction:r})]),{baselines:o,operations:s}};this.ack=async e=>{let n=await this.localReplica.get();e>this.now||(this.emit("message",{type:"ack",replicaId:n.id,timestamp:e}),!this._closing&&(!n.ackedLogicalTime||e>n.ackedLogicalTime)&&this.localReplica.update({ackedLogicalTime:e}))};this.insertLocalOperations=async(e,n)=>{if(e.length===0)return;this.log("debug",`Inserting ${e.length} local operations`,e);for(let o of e)o.isLocal=!0;await this.operations.addOperations(e,n);let r=await this.messageCreator.createOperation({operations:e});this.emit("message",r),this.tryAutonomousRebase()};this.insertRemoteOperations=async(e,n)=>{if(e.length===0)return[];this.log("debug",`Inserting ${e.length} remote operations`,e);let r=await this.operations.addOperations(e.map(o=>({...o,isLocal:!1})),n);return this.ack(e[e.length-1].timestamp),r};this.insertRemoteBaselines=async(e,n)=>{if(e.length===0)return[];this.log(`Inserting ${e.length} remote baselines`),await this.baselines.setAll(e,n);let r=new Set;return e.forEach(o=>{r.add($(o.oid))}),Array.from(r)};this.insertData=async(e,n)=>{let r=this.createTransaction(["baselines","operations"],n);e.baselines&&await this.insertRemoteBaselines(e.baselines,{transaction:r}),!n?.abort?.aborted&&e.operations&&(e.isLocal?await this.insertLocalOperations(e.operations,{transaction:r}):await this.insertRemoteOperations(e.operations,{transaction:r}))};this.updateLastSynced=async e=>{if(!this._closing)return this.localReplica.update({lastSyncedLogicalTime:e})};this.lastSyncedTimestamp=async()=>(await this.localReplica.get()).lastSyncedLogicalTime;this.tryAutonomousRebase=async()=>{this.disableRebasing||(await this.localReplica.get()).lastSyncedLogicalTime||await this.runRebase(this.now)};this.runRebase=async e=>{if(this._closing)return;let n,r=new Set,o=this.createTransaction(["baselines","operations"]),s=0;if(await this.operations.iterateOverAllOperations(p=>{r.add(p.oid),n=p.timestamp,s++},{before:e,transaction:o}),!r.size||this._closing)return;let c=[];for(let p of r)c.push(await this.rebase(p,n||e,o));this.emit("rebase",c)};this.rebase=async(e,n,r)=>{let o=(await this.localReplica.get()).id;this.log("[",o,"]","Rebasing",e,"up to",n);let s=r||this.createTransaction(["operations","baselines"]),c=await this.baselines.get(e,{transaction:s}),p=c?.snapshot||void 0,d=0,m=[];await this.operations.iterateOverAllOperationsForEntity(e,(g,C)=>{(!c||g.timestamp>c.timestamp)&&(p=je(p,g.data,m)),d++,C.delete(g.oid_timestamp)},{to:n,transaction:s}),p&&K(p,e);let S={oid:e,snapshot:p,timestamp:n};if(S.snapshot?await this.baselines.set(S,{transaction:s}):await this.baselines.delete(e,{transaction:s}),this.log("debug","successfully rebased",e,"up to",n,":",p,"and deleted",d,"operations"),m.length){let g=m.filter(be);g.length&&this.emit("filesDeleted",g)}return S};this.reset=async()=>{await this.operations.reset(),await this.baselines.reset(),await this.localReplica.reset()};this.updateSchema=async(e,n)=>{let r=await this.schema.get();if(r&&n===r.version&&r.version===e.version&&JSON.stringify(r)!==JSON.stringify(e))throw console.error(`Schema mismatch for version ${e.version}
|
|
4
|
+
`)},_domwindow:function(){return h("domwindow")},_bigint:function(d){return h("bigint:"+d.toString())},_process:function(){return h("process")},_timer:function(){return h("timer")},_pipe:function(){return h("pipe")},_tcp:function(){return h("tcp")},_udp:function(){return h("udp")},_tty:function(){return h("tty")},_statwatcher:function(){return h("statwatcher")},_securecontext:function(){return h("securecontext")},_connection:function(){return h("connection")},_zlib:function(){return h("zlib")},_context:function(){return h("context")},_nodescript:function(){return h("nodescript")},_httpparser:function(){return h("httpparser")},_dataview:function(){return h("dataview")},_signal:function(){return h("signal")},_fsevent:function(){return h("fsevent")},_tlswrap:function(){return h("tlswrap")}}}function R(){return{buf:"",write:function(b){this.buf+=b},end:function(b){this.buf+=b},read:function(){return this.buf}}}e.writeToStream=function(b,_,u){return u===void 0&&(u=_,_={}),D(_=I(b,_),u).dispatch(b)}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/fake_9a5aa49d.js","/")},{buffer:3,crypto:5,lYpoI2:11}],2:[function(i,t,e){(function(n,r,o,s,a,p,l,m,x){(function(y){"use strict";var C=typeof Uint8Array<"u"?Uint8Array:Array,w="+".charCodeAt(0),S="/".charCodeAt(0),I="0".charCodeAt(0),v="a".charCodeAt(0),D="A".charCodeAt(0),R="-".charCodeAt(0),b="_".charCodeAt(0);function _(u){return u=u.charCodeAt(0),u===w||u===R?62:u===S||u===b?63:u<I?-1:u<I+10?u-I+26+26:u<D+26?u-D:u<v+26?u-v+26:void 0}y.toByteArray=function(u){var h,d;if(0<u.length%4)throw new Error("Invalid string. Length must be a multiple of 4");var O=u.length,O=u.charAt(O-2)==="="?2:u.charAt(O-1)==="="?1:0,E=new C(3*u.length/4-O),M=0<O?u.length-4:u.length,B=0;function j(k){E[B++]=k}for(h=0;h<M;h+=4,0)j((16711680&(d=_(u.charAt(h))<<18|_(u.charAt(h+1))<<12|_(u.charAt(h+2))<<6|_(u.charAt(h+3))))>>16),j((65280&d)>>8),j(255&d);return O==2?j(255&(d=_(u.charAt(h))<<2|_(u.charAt(h+1))>>4)):O==1&&(j((d=_(u.charAt(h))<<10|_(u.charAt(h+1))<<4|_(u.charAt(h+2))>>2)>>8&255),j(255&d)),E},y.fromByteArray=function(u){var h,d,O,E,M=u.length%3,B="";function j(k){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(k)}for(h=0,O=u.length-M;h<O;h+=3)d=(u[h]<<16)+(u[h+1]<<8)+u[h+2],B+=j((E=d)>>18&63)+j(E>>12&63)+j(E>>6&63)+j(63&E);switch(M){case 1:B=(B+=j((d=u[u.length-1])>>2))+j(d<<4&63)+"==";break;case 2:B=(B=(B+=j((d=(u[u.length-2]<<8)+u[u.length-1])>>10))+j(d>>4&63))+j(d<<2&63)+"="}return B}})(e===void 0?this.base64js={}:e)}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/base64-js/lib/b64.js","/node_modules/gulp-browserify/node_modules/base64-js/lib")},{buffer:3,lYpoI2:11}],3:[function(i,t,e){(function(n,r,w,s,a,p,l,m,x){var y=i("base64-js"),C=i("ieee754");function w(c,f,g){if(!(this instanceof w))return new w(c,f,g);var A,P,F,N,W=typeof c;if(f==="base64"&&W=="string")for(c=(N=c).trim?N.trim():N.replace(/^\s+|\s+$/g,"");c.length%4!=0;)c+="=";if(W=="number")A=te(c);else if(W=="string")A=w.byteLength(c,f);else{if(W!="object")throw new Error("First argument needs to be a number, array or string.");A=te(c.length)}if(w._useTypedArrays?P=w._augment(new Uint8Array(A)):((P=this).length=A,P._isBuffer=!0),w._useTypedArrays&&typeof c.byteLength=="number")P._set(c);else if(H(N=c)||w.isBuffer(N)||N&&typeof N=="object"&&typeof N.length=="number")for(F=0;F<A;F++)w.isBuffer(c)?P[F]=c.readUInt8(F):P[F]=c[F];else if(W=="string")P.write(c,0,f);else if(W=="number"&&!w._useTypedArrays&&!g)for(F=0;F<A;F++)P[F]=0;return P}function S(c,f,g,A){return w._charsWritten=Et(function(P){for(var F=[],N=0;N<P.length;N++)F.push(255&P.charCodeAt(N));return F}(f),c,g,A)}function I(c,f,g,A){return w._charsWritten=Et(function(P){for(var F,N,W=[],G=0;G<P.length;G++)N=P.charCodeAt(G),F=N>>8,N=N%256,W.push(N),W.push(F);return W}(f),c,g,A)}function v(c,f,g){var A="";g=Math.min(c.length,g);for(var P=f;P<g;P++)A+=String.fromCharCode(c[P]);return A}function D(c,f,g,F){F||(T(typeof g=="boolean","missing or invalid endian"),T(f!=null,"missing offset"),T(f+1<c.length,"Trying to read beyond buffer length"));var P,F=c.length;if(!(F<=f))return g?(P=c[f],f+1<F&&(P|=c[f+1]<<8)):(P=c[f]<<8,f+1<F&&(P|=c[f+1])),P}function R(c,f,g,F){F||(T(typeof g=="boolean","missing or invalid endian"),T(f!=null,"missing offset"),T(f+3<c.length,"Trying to read beyond buffer length"));var P,F=c.length;if(!(F<=f))return g?(f+2<F&&(P=c[f+2]<<16),f+1<F&&(P|=c[f+1]<<8),P|=c[f],f+3<F&&(P+=c[f+3]<<24>>>0)):(f+1<F&&(P=c[f+1]<<16),f+2<F&&(P|=c[f+2]<<8),f+3<F&&(P|=c[f+3]),P+=c[f]<<24>>>0),P}function b(c,f,g,A){if(A||(T(typeof g=="boolean","missing or invalid endian"),T(f!=null,"missing offset"),T(f+1<c.length,"Trying to read beyond buffer length")),!(c.length<=f))return A=D(c,f,g,!0),32768&A?-1*(65535-A+1):A}function _(c,f,g,A){if(A||(T(typeof g=="boolean","missing or invalid endian"),T(f!=null,"missing offset"),T(f+3<c.length,"Trying to read beyond buffer length")),!(c.length<=f))return A=R(c,f,g,!0),2147483648&A?-1*(4294967295-A+1):A}function u(c,f,g,A){return A||(T(typeof g=="boolean","missing or invalid endian"),T(f+3<c.length,"Trying to read beyond buffer length")),C.read(c,f,g,23,4)}function h(c,f,g,A){return A||(T(typeof g=="boolean","missing or invalid endian"),T(f+7<c.length,"Trying to read beyond buffer length")),C.read(c,f,g,52,8)}function d(c,f,g,A,P){if(P||(T(f!=null,"missing value"),T(typeof A=="boolean","missing or invalid endian"),T(g!=null,"missing offset"),T(g+1<c.length,"trying to write beyond buffer length"),$n(f,65535)),P=c.length,!(P<=g))for(var F=0,N=Math.min(P-g,2);F<N;F++)c[g+F]=(f&255<<8*(A?F:1-F))>>>8*(A?F:1-F)}function O(c,f,g,A,P){if(P||(T(f!=null,"missing value"),T(typeof A=="boolean","missing or invalid endian"),T(g!=null,"missing offset"),T(g+3<c.length,"trying to write beyond buffer length"),$n(f,4294967295)),P=c.length,!(P<=g))for(var F=0,N=Math.min(P-g,4);F<N;F++)c[g+F]=f>>>8*(A?F:3-F)&255}function E(c,f,g,A,P){P||(T(f!=null,"missing value"),T(typeof A=="boolean","missing or invalid endian"),T(g!=null,"missing offset"),T(g+1<c.length,"Trying to write beyond buffer length"),zn(f,32767,-32768)),c.length<=g||d(c,0<=f?f:65535+f+1,g,A,P)}function M(c,f,g,A,P){P||(T(f!=null,"missing value"),T(typeof A=="boolean","missing or invalid endian"),T(g!=null,"missing offset"),T(g+3<c.length,"Trying to write beyond buffer length"),zn(f,2147483647,-2147483648)),c.length<=g||O(c,0<=f?f:4294967295+f+1,g,A,P)}function B(c,f,g,A,P){P||(T(f!=null,"missing value"),T(typeof A=="boolean","missing or invalid endian"),T(g!=null,"missing offset"),T(g+3<c.length,"Trying to write beyond buffer length"),Qi(f,34028234663852886e22,-34028234663852886e22)),c.length<=g||C.write(c,f,g,A,23,4)}function j(c,f,g,A,P){P||(T(f!=null,"missing value"),T(typeof A=="boolean","missing or invalid endian"),T(g!=null,"missing offset"),T(g+7<c.length,"Trying to write beyond buffer length"),Qi(f,17976931348623157e292,-17976931348623157e292)),c.length<=g||C.write(c,f,g,A,52,8)}e.Buffer=w,e.SlowBuffer=w,e.INSPECT_MAX_BYTES=50,w.poolSize=8192,w._useTypedArrays=function(){try{var c=new ArrayBuffer(0),f=new Uint8Array(c);return f.foo=function(){return 42},f.foo()===42&&typeof f.subarray=="function"}catch{return!1}}(),w.isEncoding=function(c){switch(String(c).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},w.isBuffer=function(c){return!(c==null||!c._isBuffer)},w.byteLength=function(c,f){var g;switch(c+="",f||"utf8"){case"hex":g=c.length/2;break;case"utf8":case"utf-8":g=_e(c).length;break;case"ascii":case"binary":case"raw":g=c.length;break;case"base64":g=Hi(c).length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":g=2*c.length;break;default:throw new Error("Unknown encoding")}return g},w.concat=function(c,f){if(T(H(c),`Usage: Buffer.concat(list, [totalLength])
|
|
5
|
+
list should be an Array.`),c.length===0)return new w(0);if(c.length===1)return c[0];if(typeof f!="number")for(P=f=0;P<c.length;P++)f+=c[P].length;for(var g=new w(f),A=0,P=0;P<c.length;P++){var F=c[P];F.copy(g,A),A+=F.length}return g},w.prototype.write=function(c,f,g,A){isFinite(f)?isFinite(g)||(A=g,g=void 0):(G=A,A=f,f=g,g=G),f=Number(f)||0;var P,F,N,W,G=this.length-f;switch((!g||G<(g=Number(g)))&&(g=G),A=String(A||"utf8").toLowerCase()){case"hex":P=function(ye,ie,re,X){re=Number(re)||0;var Y=ye.length-re;(!X||Y<(X=Number(X)))&&(X=Y),T((Y=ie.length)%2==0,"Invalid hex string"),Y/2<X&&(X=Y/2);for(var We=0;We<X;We++){var Ji=parseInt(ie.substr(2*We,2),16);T(!isNaN(Ji),"Invalid hex string"),ye[re+We]=Ji}return w._charsWritten=2*We,We}(this,c,f,g);break;case"utf8":case"utf-8":F=this,N=f,W=g,P=w._charsWritten=Et(_e(c),F,N,W);break;case"ascii":case"binary":P=S(this,c,f,g);break;case"base64":F=this,N=f,W=g,P=w._charsWritten=Et(Hi(c),F,N,W);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":P=I(this,c,f,g);break;default:throw new Error("Unknown encoding")}return P},w.prototype.toString=function(c,f,g){var A,P,F,N,W=this;if(c=String(c||"utf8").toLowerCase(),f=Number(f)||0,(g=g!==void 0?Number(g):W.length)===f)return"";switch(c){case"hex":A=function(G,ye,ie){var re=G.length;(!ye||ye<0)&&(ye=0),(!ie||ie<0||re<ie)&&(ie=re);for(var X="",Y=ye;Y<ie;Y++)X+=z(G[Y]);return X}(W,f,g);break;case"utf8":case"utf-8":A=function(G,ye,ie){var re="",X="";ie=Math.min(G.length,ie);for(var Y=ye;Y<ie;Y++)G[Y]<=127?(re+=Wi(X)+String.fromCharCode(G[Y]),X=""):X+="%"+G[Y].toString(16);return re+Wi(X)}(W,f,g);break;case"ascii":case"binary":A=v(W,f,g);break;case"base64":P=W,N=g,A=(F=f)===0&&N===P.length?y.fromByteArray(P):y.fromByteArray(P.slice(F,N));break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":A=function(G,ye,ie){for(var re=G.slice(ye,ie),X="",Y=0;Y<re.length;Y+=2)X+=String.fromCharCode(re[Y]+256*re[Y+1]);return X}(W,f,g);break;default:throw new Error("Unknown encoding")}return A},w.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},w.prototype.copy=function(c,f,g,A){if(f=f||0,(A=A||A===0?A:this.length)!==(g=g||0)&&c.length!==0&&this.length!==0){T(g<=A,"sourceEnd < sourceStart"),T(0<=f&&f<c.length,"targetStart out of bounds"),T(0<=g&&g<this.length,"sourceStart out of bounds"),T(0<=A&&A<=this.length,"sourceEnd out of bounds"),A>this.length&&(A=this.length);var P=(A=c.length-f<A-g?c.length-f+g:A)-g;if(P<100||!w._useTypedArrays)for(var F=0;F<P;F++)c[F+f]=this[F+g];else c._set(this.subarray(g,g+P),f)}},w.prototype.slice=function(c,f){var g=this.length;if(c=q(c,g,0),f=q(f,g,g),w._useTypedArrays)return w._augment(this.subarray(c,f));for(var A=f-c,P=new w(A,void 0,!0),F=0;F<A;F++)P[F]=this[F+c];return P},w.prototype.get=function(c){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(c)},w.prototype.set=function(c,f){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(c,f)},w.prototype.readUInt8=function(c,f){if(f||(T(c!=null,"missing offset"),T(c<this.length,"Trying to read beyond buffer length")),!(c>=this.length))return this[c]},w.prototype.readUInt16LE=function(c,f){return D(this,c,!0,f)},w.prototype.readUInt16BE=function(c,f){return D(this,c,!1,f)},w.prototype.readUInt32LE=function(c,f){return R(this,c,!0,f)},w.prototype.readUInt32BE=function(c,f){return R(this,c,!1,f)},w.prototype.readInt8=function(c,f){if(f||(T(c!=null,"missing offset"),T(c<this.length,"Trying to read beyond buffer length")),!(c>=this.length))return 128&this[c]?-1*(255-this[c]+1):this[c]},w.prototype.readInt16LE=function(c,f){return b(this,c,!0,f)},w.prototype.readInt16BE=function(c,f){return b(this,c,!1,f)},w.prototype.readInt32LE=function(c,f){return _(this,c,!0,f)},w.prototype.readInt32BE=function(c,f){return _(this,c,!1,f)},w.prototype.readFloatLE=function(c,f){return u(this,c,!0,f)},w.prototype.readFloatBE=function(c,f){return u(this,c,!1,f)},w.prototype.readDoubleLE=function(c,f){return h(this,c,!0,f)},w.prototype.readDoubleBE=function(c,f){return h(this,c,!1,f)},w.prototype.writeUInt8=function(c,f,g){g||(T(c!=null,"missing value"),T(f!=null,"missing offset"),T(f<this.length,"trying to write beyond buffer length"),$n(c,255)),f>=this.length||(this[f]=c)},w.prototype.writeUInt16LE=function(c,f,g){d(this,c,f,!0,g)},w.prototype.writeUInt16BE=function(c,f,g){d(this,c,f,!1,g)},w.prototype.writeUInt32LE=function(c,f,g){O(this,c,f,!0,g)},w.prototype.writeUInt32BE=function(c,f,g){O(this,c,f,!1,g)},w.prototype.writeInt8=function(c,f,g){g||(T(c!=null,"missing value"),T(f!=null,"missing offset"),T(f<this.length,"Trying to write beyond buffer length"),zn(c,127,-128)),f>=this.length||(0<=c?this.writeUInt8(c,f,g):this.writeUInt8(255+c+1,f,g))},w.prototype.writeInt16LE=function(c,f,g){E(this,c,f,!0,g)},w.prototype.writeInt16BE=function(c,f,g){E(this,c,f,!1,g)},w.prototype.writeInt32LE=function(c,f,g){M(this,c,f,!0,g)},w.prototype.writeInt32BE=function(c,f,g){M(this,c,f,!1,g)},w.prototype.writeFloatLE=function(c,f,g){B(this,c,f,!0,g)},w.prototype.writeFloatBE=function(c,f,g){B(this,c,f,!1,g)},w.prototype.writeDoubleLE=function(c,f,g){j(this,c,f,!0,g)},w.prototype.writeDoubleBE=function(c,f,g){j(this,c,f,!1,g)},w.prototype.fill=function(c,f,g){if(f=f||0,g=g||this.length,T(typeof(c=typeof(c=c||0)=="string"?c.charCodeAt(0):c)=="number"&&!isNaN(c),"value is not a number"),T(f<=g,"end < start"),g!==f&&this.length!==0){T(0<=f&&f<this.length,"start out of bounds"),T(0<=g&&g<=this.length,"end out of bounds");for(var A=f;A<g;A++)this[A]=c}},w.prototype.inspect=function(){for(var c=[],f=this.length,g=0;g<f;g++)if(c[g]=z(this[g]),g===e.INSPECT_MAX_BYTES){c[g+1]="...";break}return"<Buffer "+c.join(" ")+">"},w.prototype.toArrayBuffer=function(){if(typeof Uint8Array>"u")throw new Error("Buffer.toArrayBuffer not supported in this browser");if(w._useTypedArrays)return new w(this).buffer;for(var c=new Uint8Array(this.length),f=0,g=c.length;f<g;f+=1)c[f]=this[f];return c.buffer};var k=w.prototype;function q(c,f,g){return typeof c!="number"?g:f<=(c=~~c)?f:0<=c||0<=(c+=f)?c:0}function te(c){return(c=~~Math.ceil(+c))<0?0:c}function H(c){return(Array.isArray||function(f){return Object.prototype.toString.call(f)==="[object Array]"})(c)}function z(c){return c<16?"0"+c.toString(16):c.toString(16)}function _e(c){for(var f=[],g=0;g<c.length;g++){var A=c.charCodeAt(g);if(A<=127)f.push(c.charCodeAt(g));else for(var P=g,F=(55296<=A&&A<=57343&&g++,encodeURIComponent(c.slice(P,g+1)).substr(1).split("%")),N=0;N<F.length;N++)f.push(parseInt(F[N],16))}return f}function Hi(c){return y.toByteArray(c)}function Et(c,f,g,A){for(var P=0;P<A&&!(P+g>=f.length||P>=c.length);P++)f[P+g]=c[P];return P}function Wi(c){try{return decodeURIComponent(c)}catch{return String.fromCharCode(65533)}}function $n(c,f){T(typeof c=="number","cannot write a non-number as a number"),T(0<=c,"specified a negative value for writing an unsigned value"),T(c<=f,"value is larger than maximum value for type"),T(Math.floor(c)===c,"value has a fractional component")}function zn(c,f,g){T(typeof c=="number","cannot write a non-number as a number"),T(c<=f,"value larger than maximum allowed value"),T(g<=c,"value smaller than minimum allowed value"),T(Math.floor(c)===c,"value has a fractional component")}function Qi(c,f,g){T(typeof c=="number","cannot write a non-number as a number"),T(c<=f,"value larger than maximum allowed value"),T(g<=c,"value smaller than minimum allowed value")}function T(c,f){if(!c)throw new Error(f||"Failed assertion")}w._augment=function(c){return c._isBuffer=!0,c._get=c.get,c._set=c.set,c.get=k.get,c.set=k.set,c.write=k.write,c.toString=k.toString,c.toLocaleString=k.toString,c.toJSON=k.toJSON,c.copy=k.copy,c.slice=k.slice,c.readUInt8=k.readUInt8,c.readUInt16LE=k.readUInt16LE,c.readUInt16BE=k.readUInt16BE,c.readUInt32LE=k.readUInt32LE,c.readUInt32BE=k.readUInt32BE,c.readInt8=k.readInt8,c.readInt16LE=k.readInt16LE,c.readInt16BE=k.readInt16BE,c.readInt32LE=k.readInt32LE,c.readInt32BE=k.readInt32BE,c.readFloatLE=k.readFloatLE,c.readFloatBE=k.readFloatBE,c.readDoubleLE=k.readDoubleLE,c.readDoubleBE=k.readDoubleBE,c.writeUInt8=k.writeUInt8,c.writeUInt16LE=k.writeUInt16LE,c.writeUInt16BE=k.writeUInt16BE,c.writeUInt32LE=k.writeUInt32LE,c.writeUInt32BE=k.writeUInt32BE,c.writeInt8=k.writeInt8,c.writeInt16LE=k.writeInt16LE,c.writeInt16BE=k.writeInt16BE,c.writeInt32LE=k.writeInt32LE,c.writeInt32BE=k.writeInt32BE,c.writeFloatLE=k.writeFloatLE,c.writeFloatBE=k.writeFloatBE,c.writeDoubleLE=k.writeDoubleLE,c.writeDoubleBE=k.writeDoubleBE,c.fill=k.fill,c.inspect=k.inspect,c.toArrayBuffer=k.toArrayBuffer,c}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/buffer/index.js","/node_modules/gulp-browserify/node_modules/buffer")},{"base64-js":2,buffer:3,ieee754:10,lYpoI2:11}],4:[function(i,t,e){(function(n,r,y,s,a,p,l,m,x){var y=i("buffer").Buffer,C=4,w=new y(C);w.fill(0),t.exports={hash:function(S,I,v,D){for(var R=I(function(d,O){d.length%C!=0&&(E=d.length+(C-d.length%C),d=y.concat([d,w],E));for(var E,M=[],B=O?d.readInt32BE:d.readInt32LE,j=0;j<d.length;j+=C)M.push(B.call(d,j));return M}(S=y.isBuffer(S)?S:new y(S),D),8*S.length),I=D,b=new y(v),_=I?b.writeInt32BE:b.writeInt32LE,u=0;u<R.length;u++)_.call(b,R[u],4*u,!0);return b}}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/helpers.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{buffer:3,lYpoI2:11}],5:[function(i,t,e){(function(n,r,y,s,a,p,l,m,x){var y=i("buffer").Buffer,C=i("./sha"),w=i("./sha256"),S=i("./rng"),I={sha1:C,sha256:w,md5:i("./md5")},v=64,D=new y(v);function R(d,O){var E=I[d=d||"sha1"],M=[];return E||b("algorithm:",d,"is not yet supported"),{update:function(B){return y.isBuffer(B)||(B=new y(B)),M.push(B),B.length,this},digest:function(B){var j=y.concat(M),j=O?function(k,q,te){y.isBuffer(q)||(q=new y(q)),y.isBuffer(te)||(te=new y(te)),q.length>v?q=k(q):q.length<v&&(q=y.concat([q,D],v));for(var H=new y(v),z=new y(v),_e=0;_e<v;_e++)H[_e]=54^q[_e],z[_e]=92^q[_e];return te=k(y.concat([H,te])),k(y.concat([z,te]))}(E,O,j):E(j);return M=null,B?j.toString(B):j}}}function b(){var d=[].slice.call(arguments).join(" ");throw new Error([d,"we accept pull requests","http://github.com/dominictarr/crypto-browserify"].join(`
|
|
6
|
+
`))}D.fill(0),e.createHash=function(d){return R(d)},e.createHmac=R,e.randomBytes=function(d,O){if(!O||!O.call)return new y(S(d));try{O.call(this,void 0,new y(S(d)))}catch(E){O(E)}};var _,u=["createCredentials","createCipher","createCipheriv","createDecipher","createDecipheriv","createSign","createVerify","createDiffieHellman","pbkdf2"],h=function(d){e[d]=function(){b("sorry,",d,"is not implemented yet")}};for(_ in u)h(u[_],_)}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/index.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./md5":6,"./rng":7,"./sha":8,"./sha256":9,buffer:3,lYpoI2:11}],6:[function(i,t,e){(function(n,r,o,s,a,p,l,m,x){var y=i("./helpers");function C(b,_){b[_>>5]|=128<<_%32,b[14+(_+64>>>9<<4)]=_;for(var u=1732584193,h=-271733879,d=-1732584194,O=271733878,E=0;E<b.length;E+=16){var M=u,B=h,j=d,k=O,u=S(u,h,d,O,b[E+0],7,-680876936),O=S(O,u,h,d,b[E+1],12,-389564586),d=S(d,O,u,h,b[E+2],17,606105819),h=S(h,d,O,u,b[E+3],22,-1044525330);u=S(u,h,d,O,b[E+4],7,-176418897),O=S(O,u,h,d,b[E+5],12,1200080426),d=S(d,O,u,h,b[E+6],17,-1473231341),h=S(h,d,O,u,b[E+7],22,-45705983),u=S(u,h,d,O,b[E+8],7,1770035416),O=S(O,u,h,d,b[E+9],12,-1958414417),d=S(d,O,u,h,b[E+10],17,-42063),h=S(h,d,O,u,b[E+11],22,-1990404162),u=S(u,h,d,O,b[E+12],7,1804603682),O=S(O,u,h,d,b[E+13],12,-40341101),d=S(d,O,u,h,b[E+14],17,-1502002290),u=I(u,h=S(h,d,O,u,b[E+15],22,1236535329),d,O,b[E+1],5,-165796510),O=I(O,u,h,d,b[E+6],9,-1069501632),d=I(d,O,u,h,b[E+11],14,643717713),h=I(h,d,O,u,b[E+0],20,-373897302),u=I(u,h,d,O,b[E+5],5,-701558691),O=I(O,u,h,d,b[E+10],9,38016083),d=I(d,O,u,h,b[E+15],14,-660478335),h=I(h,d,O,u,b[E+4],20,-405537848),u=I(u,h,d,O,b[E+9],5,568446438),O=I(O,u,h,d,b[E+14],9,-1019803690),d=I(d,O,u,h,b[E+3],14,-187363961),h=I(h,d,O,u,b[E+8],20,1163531501),u=I(u,h,d,O,b[E+13],5,-1444681467),O=I(O,u,h,d,b[E+2],9,-51403784),d=I(d,O,u,h,b[E+7],14,1735328473),u=v(u,h=I(h,d,O,u,b[E+12],20,-1926607734),d,O,b[E+5],4,-378558),O=v(O,u,h,d,b[E+8],11,-2022574463),d=v(d,O,u,h,b[E+11],16,1839030562),h=v(h,d,O,u,b[E+14],23,-35309556),u=v(u,h,d,O,b[E+1],4,-1530992060),O=v(O,u,h,d,b[E+4],11,1272893353),d=v(d,O,u,h,b[E+7],16,-155497632),h=v(h,d,O,u,b[E+10],23,-1094730640),u=v(u,h,d,O,b[E+13],4,681279174),O=v(O,u,h,d,b[E+0],11,-358537222),d=v(d,O,u,h,b[E+3],16,-722521979),h=v(h,d,O,u,b[E+6],23,76029189),u=v(u,h,d,O,b[E+9],4,-640364487),O=v(O,u,h,d,b[E+12],11,-421815835),d=v(d,O,u,h,b[E+15],16,530742520),u=D(u,h=v(h,d,O,u,b[E+2],23,-995338651),d,O,b[E+0],6,-198630844),O=D(O,u,h,d,b[E+7],10,1126891415),d=D(d,O,u,h,b[E+14],15,-1416354905),h=D(h,d,O,u,b[E+5],21,-57434055),u=D(u,h,d,O,b[E+12],6,1700485571),O=D(O,u,h,d,b[E+3],10,-1894986606),d=D(d,O,u,h,b[E+10],15,-1051523),h=D(h,d,O,u,b[E+1],21,-2054922799),u=D(u,h,d,O,b[E+8],6,1873313359),O=D(O,u,h,d,b[E+15],10,-30611744),d=D(d,O,u,h,b[E+6],15,-1560198380),h=D(h,d,O,u,b[E+13],21,1309151649),u=D(u,h,d,O,b[E+4],6,-145523070),O=D(O,u,h,d,b[E+11],10,-1120210379),d=D(d,O,u,h,b[E+2],15,718787259),h=D(h,d,O,u,b[E+9],21,-343485551),u=R(u,M),h=R(h,B),d=R(d,j),O=R(O,k)}return Array(u,h,d,O)}function w(b,_,u,h,d,O){return R((_=R(R(_,b),R(h,O)))<<d|_>>>32-d,u)}function S(b,_,u,h,d,O,E){return w(_&u|~_&h,b,_,d,O,E)}function I(b,_,u,h,d,O,E){return w(_&h|u&~h,b,_,d,O,E)}function v(b,_,u,h,d,O,E){return w(_^u^h,b,_,d,O,E)}function D(b,_,u,h,d,O,E){return w(u^(_|~h),b,_,d,O,E)}function R(b,_){var u=(65535&b)+(65535&_);return(b>>16)+(_>>16)+(u>>16)<<16|65535&u}t.exports=function(b){return y.hash(b,C,16)}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/md5.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],7:[function(i,t,e){(function(n,r,o,s,a,p,l,m,x){var y;t.exports=y||function(C){for(var w,S=new Array(C),I=0;I<C;I++)!(3&I)&&(w=4294967296*Math.random()),S[I]=w>>>((3&I)<<3)&255;return S}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/rng.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{buffer:3,lYpoI2:11}],8:[function(i,t,e){(function(n,r,o,s,a,p,l,m,x){var y=i("./helpers");function C(I,v){I[v>>5]|=128<<24-v%32,I[15+(v+64>>9<<4)]=v;for(var D,R,b,_=Array(80),u=1732584193,h=-271733879,d=-1732584194,O=271733878,E=-1009589776,M=0;M<I.length;M+=16){for(var B=u,j=h,k=d,q=O,te=E,H=0;H<80;H++){_[H]=H<16?I[M+H]:S(_[H-3]^_[H-8]^_[H-14]^_[H-16],1);var z=w(w(S(u,5),(z=h,R=d,b=O,(D=H)<20?z&R|~z&b:!(D<40)&&D<60?z&R|z&b|R&b:z^R^b)),w(w(E,_[H]),(D=H)<20?1518500249:D<40?1859775393:D<60?-1894007588:-899497514)),E=O,O=d,d=S(h,30),h=u,u=z}u=w(u,B),h=w(h,j),d=w(d,k),O=w(O,q),E=w(E,te)}return Array(u,h,d,O,E)}function w(I,v){var D=(65535&I)+(65535&v);return(I>>16)+(v>>16)+(D>>16)<<16|65535&D}function S(I,v){return I<<v|I>>>32-v}t.exports=function(I){return y.hash(I,C,20,!0)}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],9:[function(i,t,e){(function(n,r,o,s,a,p,l,m,x){function y(v,D){var R=(65535&v)+(65535&D);return(v>>16)+(D>>16)+(R>>16)<<16|65535&R}function C(v,D){var R,b=new Array(1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298),_=new Array(1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225),u=new Array(64);v[D>>5]|=128<<24-D%32,v[15+(D+64>>9<<4)]=D;for(var h,d,O=0;O<v.length;O+=16){for(var E=_[0],M=_[1],B=_[2],j=_[3],k=_[4],q=_[5],te=_[6],H=_[7],z=0;z<64;z++)u[z]=z<16?v[z+O]:y(y(y((d=u[z-2],S(d,17)^S(d,19)^I(d,10)),u[z-7]),(d=u[z-15],S(d,7)^S(d,18)^I(d,3))),u[z-16]),R=y(y(y(y(H,S(d=k,6)^S(d,11)^S(d,25)),k&q^~k&te),b[z]),u[z]),h=y(S(h=E,2)^S(h,13)^S(h,22),E&M^E&B^M&B),H=te,te=q,q=k,k=y(j,R),j=B,B=M,M=E,E=y(R,h);_[0]=y(E,_[0]),_[1]=y(M,_[1]),_[2]=y(B,_[2]),_[3]=y(j,_[3]),_[4]=y(k,_[4]),_[5]=y(q,_[5]),_[6]=y(te,_[6]),_[7]=y(H,_[7])}return _}var w=i("./helpers"),S=function(v,D){return v>>>D|v<<32-D},I=function(v,D){return v>>>D};t.exports=function(v){return w.hash(v,C,32,!0)}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha256.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],10:[function(i,t,e){(function(n,r,o,s,a,p,l,m,x){e.read=function(y,C,w,S,O){var v,D,R=8*O-S-1,b=(1<<R)-1,_=b>>1,u=-7,h=w?O-1:0,d=w?-1:1,O=y[C+h];for(h+=d,v=O&(1<<-u)-1,O>>=-u,u+=R;0<u;v=256*v+y[C+h],h+=d,u-=8);for(D=v&(1<<-u)-1,v>>=-u,u+=S;0<u;D=256*D+y[C+h],h+=d,u-=8);if(v===0)v=1-_;else{if(v===b)return D?NaN:1/0*(O?-1:1);D+=Math.pow(2,S),v-=_}return(O?-1:1)*D*Math.pow(2,v-S)},e.write=function(y,C,w,S,I,E){var D,R,b=8*E-I-1,_=(1<<b)-1,u=_>>1,h=I===23?Math.pow(2,-24)-Math.pow(2,-77):0,d=S?0:E-1,O=S?1:-1,E=C<0||C===0&&1/C<0?1:0;for(C=Math.abs(C),isNaN(C)||C===1/0?(R=isNaN(C)?1:0,D=_):(D=Math.floor(Math.log(C)/Math.LN2),C*(S=Math.pow(2,-D))<1&&(D--,S*=2),2<=(C+=1<=D+u?h/S:h*Math.pow(2,1-u))*S&&(D++,S/=2),_<=D+u?(R=0,D=_):1<=D+u?(R=(C*S-1)*Math.pow(2,I),D+=u):(R=C*Math.pow(2,u-1)*Math.pow(2,I),D=0));8<=I;y[w+d]=255&R,d+=O,R/=256,I-=8);for(D=D<<I|R,b+=I;0<b;y[w+d]=255&D,d+=O,D/=256,b-=8);y[w+d-O]|=128*E}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/ieee754/index.js","/node_modules/gulp-browserify/node_modules/ieee754")},{buffer:3,lYpoI2:11}],11:[function(i,t,e){(function(n,r,o,s,a,p,l,m,x){var y,C,w;function S(){}(n=t.exports={}).nextTick=(C=typeof window<"u"&&window.setImmediate,w=typeof window<"u"&&window.postMessage&&window.addEventListener,C?function(I){return window.setImmediate(I)}:w?(y=[],window.addEventListener("message",function(I){var v=I.source;v!==window&&v!==null||I.data!=="process-tick"||(I.stopPropagation(),0<y.length&&y.shift()())},!0),function(I){y.push(I),window.postMessage("process-tick","*")}):function(I){setTimeout(I,0)}),n.title="browser",n.browser=!0,n.env={},n.argv=[],n.on=S,n.addListener=S,n.once=S,n.off=S,n.removeListener=S,n.removeAllListeners=S,n.emit=S,n.binding=function(I){throw new Error("process.binding is not supported")},n.cwd=function(){return"/"},n.chdir=function(I){throw new Error("process.chdir is not supported")}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/process/browser.js","/node_modules/gulp-browserify/node_modules/process")},{buffer:3,lYpoI2:11}]},{},[1])(1)})});var ze={};Yi(ze,{__addDisposableResource:()=>So,__assign:()=>yn,__asyncDelegator:()=>po,__asyncGenerator:()=>fo,__asyncValues:()=>ho,__await:()=>nt,__awaiter:()=>oo,__classPrivateFieldGet:()=>bo,__classPrivateFieldIn:()=>vo,__classPrivateFieldSet:()=>wo,__createBinding:()=>wn,__decorate:()=>no,__disposeResources:()=>xo,__esDecorate:()=>ia,__exportStar:()=>ao,__extends:()=>eo,__generator:()=>so,__importDefault:()=>yo,__importStar:()=>go,__makeTemplateObject:()=>mo,__metadata:()=>ro,__param:()=>io,__propKey:()=>oa,__read:()=>Ci,__rest:()=>to,__runInitializers:()=>ra,__setFunctionName:()=>sa,__spread:()=>co,__spreadArray:()=>uo,__spreadArrays:()=>lo,__values:()=>bn,default:()=>la});function eo(i,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");Ei(i,t);function e(){this.constructor=i}i.prototype=t===null?Object.create(t):(e.prototype=t.prototype,new e)}function to(i,t){var e={};for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&t.indexOf(n)<0&&(e[n]=i[n]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,n=Object.getOwnPropertySymbols(i);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(i,n[r])&&(e[n[r]]=i[n[r]]);return e}function no(i,t,e,n){var r=arguments.length,o=r<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(i,t,e,n);else for(var a=i.length-1;a>=0;a--)(s=i[a])&&(o=(r<3?s(o):r>3?s(t,e,o):s(t,e))||o);return r>3&&o&&Object.defineProperty(t,e,o),o}function io(i,t){return function(e,n){t(e,n,i)}}function ia(i,t,e,n,r,o){function s(v){if(v!==void 0&&typeof v!="function")throw new TypeError("Function expected");return v}for(var a=n.kind,p=a==="getter"?"get":a==="setter"?"set":"value",l=!t&&i?n.static?i:i.prototype:null,m=t||(l?Object.getOwnPropertyDescriptor(l,n.name):{}),x,y=!1,C=e.length-1;C>=0;C--){var w={};for(var S in n)w[S]=S==="access"?{}:n[S];for(var S in n.access)w.access[S]=n.access[S];w.addInitializer=function(v){if(y)throw new TypeError("Cannot add initializers after decoration has completed");o.push(s(v||null))};var I=(0,e[C])(a==="accessor"?{get:m.get,set:m.set}:m[p],w);if(a==="accessor"){if(I===void 0)continue;if(I===null||typeof I!="object")throw new TypeError("Object expected");(x=s(I.get))&&(m.get=x),(x=s(I.set))&&(m.set=x),(x=s(I.init))&&r.unshift(x)}else(x=s(I))&&(a==="field"?r.unshift(x):m[p]=x)}l&&Object.defineProperty(l,n.name,m),y=!0}function ra(i,t,e){for(var n=arguments.length>2,r=0;r<t.length;r++)e=n?t[r].call(i,e):t[r].call(i);return n?e:void 0}function oa(i){return typeof i=="symbol"?i:"".concat(i)}function sa(i,t,e){return typeof t=="symbol"&&(t=t.description?"[".concat(t.description,"]"):""),Object.defineProperty(i,"name",{configurable:!0,value:e?"".concat(e," ",t):t})}function ro(i,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(i,t)}function oo(i,t,e,n){function r(o){return o instanceof e?o:new e(function(s){s(o)})}return new(e||(e=Promise))(function(o,s){function a(m){try{l(n.next(m))}catch(x){s(x)}}function p(m){try{l(n.throw(m))}catch(x){s(x)}}function l(m){m.done?o(m.value):r(m.value).then(a,p)}l((n=n.apply(i,t||[])).next())})}function so(i,t){var e={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},n,r,o,s;return s={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function a(l){return function(m){return p([l,m])}}function p(l){if(n)throw new TypeError("Generator is already executing.");for(;s&&(s=0,l[0]&&(e=0)),e;)try{if(n=1,r&&(o=l[0]&2?r.return:l[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,l[1])).done)return o;switch(r=0,o&&(l=[l[0]&2,o.value]),l[0]){case 0:case 1:o=l;break;case 4:return e.label++,{value:l[1],done:!1};case 5:e.label++,r=l[1],l=[0];continue;case 7:l=e.ops.pop(),e.trys.pop();continue;default:if(o=e.trys,!(o=o.length>0&&o[o.length-1])&&(l[0]===6||l[0]===2)){e=0;continue}if(l[0]===3&&(!o||l[1]>o[0]&&l[1]<o[3])){e.label=l[1];break}if(l[0]===6&&e.label<o[1]){e.label=o[1],o=l;break}if(o&&e.label<o[2]){e.label=o[2],e.ops.push(l);break}o[2]&&e.ops.pop(),e.trys.pop();continue}l=t.call(i,e)}catch(m){l=[6,m],r=0}finally{n=o=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function ao(i,t){for(var e in i)e!=="default"&&!Object.prototype.hasOwnProperty.call(t,e)&&wn(t,i,e)}function bn(i){var t=typeof Symbol=="function"&&Symbol.iterator,e=t&&i[t],n=0;if(e)return e.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&n>=i.length&&(i=void 0),{value:i&&i[n++],done:!i}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function Ci(i,t){var e=typeof Symbol=="function"&&i[Symbol.iterator];if(!e)return i;var n=e.call(i),r,o=[],s;try{for(;(t===void 0||t-- >0)&&!(r=n.next()).done;)o.push(r.value)}catch(a){s={error:a}}finally{try{r&&!r.done&&(e=n.return)&&e.call(n)}finally{if(s)throw s.error}}return o}function co(){for(var i=[],t=0;t<arguments.length;t++)i=i.concat(Ci(arguments[t]));return i}function lo(){for(var i=0,t=0,e=arguments.length;t<e;t++)i+=arguments[t].length;for(var n=Array(i),r=0,t=0;t<e;t++)for(var o=arguments[t],s=0,a=o.length;s<a;s++,r++)n[r]=o[s];return n}function uo(i,t,e){if(e||arguments.length===2)for(var n=0,r=t.length,o;n<r;n++)(o||!(n in t))&&(o||(o=Array.prototype.slice.call(t,0,n)),o[n]=t[n]);return i.concat(o||Array.prototype.slice.call(t))}function nt(i){return this instanceof nt?(this.v=i,this):new nt(i)}function fo(i,t,e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=e.apply(i,t||[]),r,o=[];return r={},s("next"),s("throw"),s("return"),r[Symbol.asyncIterator]=function(){return this},r;function s(y){n[y]&&(r[y]=function(C){return new Promise(function(w,S){o.push([y,C,w,S])>1||a(y,C)})})}function a(y,C){try{p(n[y](C))}catch(w){x(o[0][3],w)}}function p(y){y.value instanceof nt?Promise.resolve(y.value.v).then(l,m):x(o[0][2],y)}function l(y){a("next",y)}function m(y){a("throw",y)}function x(y,C){y(C),o.shift(),o.length&&a(o[0][0],o[0][1])}}function po(i){var t,e;return t={},n("next"),n("throw",function(r){throw r}),n("return"),t[Symbol.iterator]=function(){return this},t;function n(r,o){t[r]=i[r]?function(s){return(e=!e)?{value:nt(i[r](s)),done:!1}:o?o(s):s}:o}}function ho(i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=i[Symbol.asyncIterator],e;return t?t.call(i):(i=typeof bn=="function"?bn(i):i[Symbol.iterator](),e={},n("next"),n("throw"),n("return"),e[Symbol.asyncIterator]=function(){return this},e);function n(o){e[o]=i[o]&&function(s){return new Promise(function(a,p){s=i[o](s),r(a,p,s.done,s.value)})}}function r(o,s,a,p){Promise.resolve(p).then(function(l){o({value:l,done:a})},s)}}function mo(i,t){return Object.defineProperty?Object.defineProperty(i,"raw",{value:t}):i.raw=t,i}function go(i){if(i&&i.__esModule)return i;var t={};if(i!=null)for(var e in i)e!=="default"&&Object.prototype.hasOwnProperty.call(i,e)&&wn(t,i,e);return aa(t,i),t}function yo(i){return i&&i.__esModule?i:{default:i}}function bo(i,t,e,n){if(e==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?i!==t||!n:!t.has(i))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e==="m"?n:e==="a"?n.call(i):n?n.value:t.get(i)}function wo(i,t,e,n,r){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?i!==t||!r:!t.has(i))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?r.call(i,e):r?r.value=e:t.set(i,e),e}function vo(i,t){if(t===null||typeof t!="object"&&typeof t!="function")throw new TypeError("Cannot use 'in' operator on non-object");return typeof i=="function"?t===i:i.has(t)}function So(i,t,e){if(t!=null){if(typeof t!="object"&&typeof t!="function")throw new TypeError("Object expected.");var n;if(e){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(n===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose]}if(typeof n!="function")throw new TypeError("Object not disposable.");i.stack.push({value:t,dispose:n,async:e})}else e&&i.stack.push({async:!0});return t}function xo(i){function t(n){i.error=i.hasError?new ca(n,i.error,"An error was suppressed during disposal."):n,i.hasError=!0}function e(){for(;i.stack.length;){var n=i.stack.pop();try{var r=n.dispose&&n.dispose.call(n.value);if(n.async)return Promise.resolve(r).then(e,function(o){return t(o),e()})}catch(o){t(o)}}if(i.hasError)throw i.error}return e()}var Ei,yn,wn,aa,ca,la,qe=$o(()=>{Ei=function(i,t){return Ei=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,n){e.__proto__=n}||function(e,n){for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])},Ei(i,t)};yn=function(){return yn=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++){e=arguments[n];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o])}return t},yn.apply(this,arguments)};wn=Object.create?function(i,t,e,n){n===void 0&&(n=e);var r=Object.getOwnPropertyDescriptor(t,e);(!r||("get"in r?!t.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return t[e]}}),Object.defineProperty(i,n,r)}:function(i,t,e,n){n===void 0&&(n=e),i[n]=t[e]};aa=Object.create?function(i,t){Object.defineProperty(i,"default",{enumerable:!0,value:t})}:function(i,t){i.default=t};ca=typeof SuppressedError=="function"?SuppressedError:function(i,t,e){var n=new Error(e);return n.name="SuppressedError",n.error=i,n.suppressed=t,n};la={__extends:eo,__assign:yn,__rest:to,__decorate:no,__param:io,__metadata:ro,__awaiter:oo,__generator:so,__createBinding:wn,__exportStar:ao,__values:bn,__read:Ci,__spread:co,__spreadArrays:lo,__spreadArray:uo,__await:nt,__asyncGenerator:fo,__asyncDelegator:po,__asyncValues:ho,__makeTemplateObject:mo,__importStar:go,__importDefault:yo,__classPrivateFieldGet:bo,__classPrivateFieldSet:wo,__classPrivateFieldIn:vo,__addDisposableResource:So,__disposeResources:xo}});var Io=oe(Oo=>{"use strict";Object.defineProperty(Oo,"__esModule",{value:!0})});var Ai=oe(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.invokeEventHandlersAsync=De.invokeEventHandlers=De.eventHandlerSafeInvokeAsync=De.eventHandlerSafeInvoke=void 0;var Do=(qe(),Je(ze));function _o(i,t,e){try{return i(t,e),{succeeded:!0}}catch(n){return{error:n,succeeded:!1}}}De.eventHandlerSafeInvoke=_o;function Pi(i,t,e){return(0,Do.__awaiter)(this,void 0,void 0,function*(){try{return yield i(t,e),{succeeded:!0}}catch(n){return{error:n,succeeded:!1}}})}De.eventHandlerSafeInvokeAsync=Pi;function da(i,t,e,n){for(let r of i){let{succeeded:o,error:s}=_o(r,t,e);if(!o&&n?.swallowExceptions!==!0)throw s}}De.invokeEventHandlers=da;function ua(i,t,e,n){return(0,Do.__awaiter)(this,void 0,void 0,function*(){if(n?.parallelize===!1)for(let r of i){let{succeeded:o,error:s}=yield Pi(r,t,e);if(!o&&n?.swallowExceptions!==!0)throw s}else{let r=[];for(let o of i)r.push(Pi(o,t,e).then(({succeeded:s,error:a})=>{if(!s&&n?.swallowExceptions!==!0)throw a}));yield Promise.all(r)}})}De.invokeEventHandlersAsync=ua});var Po=oe(vn=>{"use strict";Object.defineProperty(vn,"__esModule",{value:!0});vn.TypedEvent=void 0;var fa=(qe(),Je(ze)),Eo=Ai(),Co={swallowExceptions:!1,parallelize:!0},Ri=class{constructor(){this._handlers=[]}attach(t){this._handlers.push(t)}detach(t){this.tryRemoveHandler(t)}invoke(t,e,n=Co){(0,Eo.invokeEventHandlers)(this._handlers,t,e,n)}invokeAsync(t,e,n=Co){return(0,fa.__awaiter)(this,void 0,void 0,function*(){yield(0,Eo.invokeEventHandlersAsync)(this._handlers,t,e,n)})}tryRemoveHandler(t){let e=this._handlers.findIndex(n=>n===t);e>=0&&this._handlers.splice(e,1)}};vn.TypedEvent=Ri});var Fi=oe(Ti=>{"use strict";Object.defineProperty(Ti,"__esModule",{value:!0});var pa=(qe(),Je(ze));(0,pa.__exportStar)(Po(),Ti)});var Ao=oe(Sn=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});Sn.FinalizationRegistryMissingError=void 0;var ki=class extends Error{};Sn.FinalizationRegistryMissingError=ki});var Mi=oe(xn=>{"use strict";Object.defineProperty(xn,"__esModule",{value:!0});xn.WeakHandlerHolder=void 0;var ha=Ao(),Bi=class{constructor(t){this._refs=[];try{this._finalizationRegistry=new FinalizationRegistry(t)}catch(e){throw e.name==="FinalizationRegistry"?new ha.FinalizationRegistryMissingError("FinalizationRegistry is not defined. Weak Events cannot be used. Please consult 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry' for compatibility information"):e}}getWeakHandler(t,e){let n=new WeakRef(e);return this._finalizationRegistry.register(e,{eventSource:t,handlerRef:n},n),this._refs.push(n),n}releaseWeakHandler(t){let n=this._refs.find(r=>r?.deref()===t)||new WeakRef(t);return this._finalizationRegistry.unregister(n),n}unregisterRef(t){this._finalizationRegistry.unregister(t)}};xn.WeakHandlerHolder=Bi});var Ro=oe(On=>{"use strict";Object.defineProperty(On,"__esModule",{value:!0});On.WeakEvent=void 0;var ji=(qe(),Je(ze)),ma=Fi(),ga=Mi(),Li=Ai(),ya={swallowExceptions:!1,parallelize:!0},Ni=class{constructor(){this._handlers=[],this._handlerFinalizedEvent=new ma.TypedEvent,this.handlerFinalizedEvent=this._handlerFinalizedEvent,this._refHolder=new ga.WeakHandlerHolder(t=>{this.onHandlerFinalizer(t)})}invoke(t,e,n){for(let r of this._handlers){let o=r?.deref();if(o){let{succeeded:s,error:a}=(0,Li.eventHandlerSafeInvoke)(o,t,e);if(!s&&n?.swallowExceptions!==!0)throw a}else this.releaseHandler(r)}}invokeAsync(t,e,n=ya){return(0,ji.__awaiter)(this,void 0,void 0,function*(){n?.parallelize===!1?yield this.sequentialInvokeAsync(t,e,n):yield this.parallelInvokeAsync(t,e,n)})}sequentialInvokeAsync(t,e,n){return(0,ji.__awaiter)(this,void 0,void 0,function*(){for(let r of this._handlers){let o=r?.deref();if(o){let{succeeded:s,error:a}=yield(0,Li.eventHandlerSafeInvokeAsync)(o,t,e);if(!s&&n.swallowExceptions!==!0)throw a}else this.releaseHandler(r)}})}parallelInvokeAsync(t,e,n){return(0,ji.__awaiter)(this,void 0,void 0,function*(){let r=[];for(let o of this._handlers){let s=o?.deref();s?r.push((0,Li.eventHandlerSafeInvokeAsync)(s,t,e).then(({succeeded:a,error:p})=>{if(!a&&n.swallowExceptions!==!0)throw p})):this.releaseHandler(o)}yield Promise.all(r)})}attach(t){this._handlers.push(this._refHolder.getWeakHandler(this,t))}detach(t){let e=this._refHolder.releaseWeakHandler(t);this.tryRemoveHandlerRef(e)}onHandlerFinalizer(t){this.tryRemoveHandlerRef(t?.handlerRef),this._handlerFinalizedEvent.invokeAsync(this,t,{swallowExceptions:!0})}tryRemoveHandlerRef(t){let e=this._handlers.findIndex(n=>n===t);e>=0&&this._handlers.splice(e,1)}releaseHandler(t){this._refHolder.unregisterRef(t),this.tryRemoveHandlerRef(t)}};On.WeakEvent=Ni});var Fo=oe(In=>{"use strict";Object.defineProperty(In,"__esModule",{value:!0});var To=(qe(),Je(ze));(0,To.__exportStar)(Mi(),In);(0,To.__exportStar)(Ro(),In)});var ko=oe(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});var Ui=(qe(),Je(ze));(0,Ui.__exportStar)(Io(),It);(0,Ui.__exportStar)(Fi(),It);(0,Ui.__exportStar)(Fo(),It)});var qi={};Yi(qi,{Client:()=>He,ClientDescriptor:()=>Kn,Entity:()=>ue,EntityFile:()=>de,MigrationPathError:()=>Ze,ServerSync:()=>rt,Storage:()=>He,StorageDescriptor:()=>Kn,collection:()=>gi,createDefaultMigration:()=>yi,createMigration:()=>bi,migrate:()=>Wt,schema:()=>gt});var pr=Qe(at(),1),Bt=4,lt=36;function lr(i){return i.toString(lt).padStart(Bt,"0")}function Yo(i){return i.toString().padStart(6,"0")}var Rt=class{constructor(){this.latest={time:Date.now(),counter:0,node:Go()};this.zeroCounter=0;this.now=t=>(this.latest=ur(this.latest),this.get(t,this.latest));this.OLD_now=t=>(this.latest=ur(this.latest),Yo(t)+Zo(this.latest));this.timerState=()=>this.latest;this.update=t=>{let e=t.slice(Bt);this.latest=Xo(this.latest,hr(e))};this.get=(t,e)=>lr(t)+dr(e);this.zero=t=>lr(t)+dr({time:0,counter:this.zeroCounter++,node:this.latest.node});this.getWallClockTime=Xn}},Tt=class extends Error{constructor(...e){super();this.type="ClockDriftError",this.message=["maximum clock drift exceeded"].concat(e).join(" ")}},Ft=class extends Error{constructor(){super();this.type="OverflowError",this.message="timestamp counter overflow"}},Jn=4,Yn=7,kt=60*1e3,ct=9;function Go(){return pr.default.slug().padStart(Yn,"0").slice(0,Yn)}function dr(i){let t=new Date(i.time).getTime().toString(lt).padStart(ct,"0"),e=i.counter.toString(lt).padStart(Jn,"0"),n=i.node.padStart(Yn,"0");return`${t}${e}${n}`}function ur(i){let t=Date.now(),e=Math.max(i.time,t),n=i.time===e?i.counter+1:0;if(e-t>kt)throw new Tt(e,t,kt);if(n>65535)throw new Ft;return{time:e,counter:n,node:i.node}}function Xo(i,t){let e=Date.now(),n=Math.max(e,Math.max(i.time,t.time)),r=Math.max(i.counter,t.counter),o;if(i.time===n&&t.time===n?o=r+1:i.time===n?o=i.counter+1:t.time===n?o=t.counter+1:o=0,n-e>kt)throw new Tt(n,e,kt);if(o>65535)throw new Ft;return{time:n,counter:o,node:i.node}}function hr(i){let t=i.slice(0,ct),e=i.slice(ct,ct+Jn),n=i.slice(ct+Jn),r=parseInt(t,lt),o=parseInt(e,lt);if(isNaN(r)||isNaN(o))throw new Error("invalid clock format");return{time:r,counter:o,node:n}}function Zo(i){let t=new Date(i.time).toISOString(),e=i.counter.toString(16).toUpperCase().padStart(4,"0"),n=i.node.padStart(16,"0");return`${t}-${e}-${n}`}function fr(i){return parseInt(i.slice(0,Bt),36)}function Gn(i,t){return fr(i)-fr(t)}function Xn(i){return hr(i.slice(Bt)).time}function be(i){return i&&i["@@type"]==="file"}function Mt(i){return{"@@type":"file",id:i}}var jt,es=new Uint8Array(16);function Zn(){if(!jt&&(jt=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!jt))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return jt(es)}var mr=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function ts(i){return typeof i=="string"&&mr.test(i)}var gr=ts;var ee=[];for(Lt=0;Lt<256;++Lt)ee.push((Lt+256).toString(16).substr(1));var Lt;function ns(i){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=(ee[i[t+0]]+ee[i[t+1]]+ee[i[t+2]]+ee[i[t+3]]+"-"+ee[i[t+4]]+ee[i[t+5]]+"-"+ee[i[t+6]]+ee[i[t+7]]+"-"+ee[i[t+8]]+ee[i[t+9]]+"-"+ee[i[t+10]]+ee[i[t+11]]+ee[i[t+12]]+ee[i[t+13]]+ee[i[t+14]]+ee[i[t+15]]).toLowerCase();if(!gr(e))throw TypeError("Stringified UUID is invalid");return e}var yr=ns;function is(i,t,e){i=i||{};var n=i.random||(i.rng||Zn)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){e=e||0;for(var r=0;r<16;++r)t[e+r]=n[r];return t}return yr(n)}var dt=is;function Q(i){return Se(i)||be(i)}function Ye(i,t){return i===t?!0:!(!Q(i)||!Q(t)||i["@@type"]!==t["@@type"]||i.id!==t.id)}var Sr=Qe(vr(),1);function rs(i,t){return typeof t!="object"||t===null||Array.isArray(t)?t:Object.fromEntries(Object.entries(t).sort(([e],[n])=>e<n?-1:e>n?1:0))}function ut(i){return JSON.stringify(i,rs)}function ae(i,t=!0){if(V(i)||Array.isArray(i)){let e=pe(i),n;if(Array.isArray(i))n=i.map(r=>ae(r,t));else{n={};for(let[r,o]of Object.entries(i))n[r]=ae(o,t)}return t&&e&&K(n,e),n}return i}function Re(i){return(0,Sr.default)(i)}function V(i){return i&&typeof i=="object"}function xr(i){for(var t=[],e=[i],n=0;e.length;){var r=e.pop();if(typeof r=="boolean")n+=4;else if(typeof r=="string")n+=r.length*2;else if(typeof r=="number")n+=8;else if(typeof r=="object"&&t.indexOf(r)===-1){t.push(r);for(var o in r)e.push(r[o])}}return n}function L(i,t="assertion failed"){if(!i)throw new Error(t)}function Nt(i=16){return dt().replace("-","").slice(0,i)}function Or(i,t){for(let e=i.length-1;e>=0;e--)if(t(i[e]))return e;return-1}function Ir(i,t){let e;return function(...n){let r=this;clearTimeout(e),e=setTimeout(()=>i.apply(r,n),t)}}var Be="__@@oid_do_not_use",Oe="@@id",os="/",pt=":",ti=new WeakMap;function ne(i){let t=pe(i);return L(!!t,`Object ${JSON.stringify(i)} does not have an OID assigned to it`),t}function pe(i){if(V(i))return ti.get(i)??i[Oe]??i[Be]}function K(i,t){return L(V(i),`Only objects can be assigned OIDs, received ${JSON.stringify(i)}`),ni(i)&&Kt(i),ti.set(i,t),i}function ni(i){return!!pe(i)}function Kt(i){return ti.delete(i),i}function ii(i){return i===Oe||i===Be}function ri(i,t,e){if(ni(i))return ne(i);{let n=xe(t,e);return K(i,n),n}}function Dr(i,t,e){if(ni(i)){let n=ne(i);if(Ee(n,t))return ne(i);{let r=xe(t,e);return K(i,r),r}}else{let n=xe(t,e);return K(i,n),n}}var ei={".":"˙","/":"&slash;",":":":"};function _r(i){return i.replace(/[/]/g,ei["/"]).replace(/[:]/g,ei[":"]).replace(/[.]/g,ei["."])}function Er(i){return i.replace(/&slash;/g,"/").replace(/:/g,":").replace(/˙/g,".")}function Z(i,t,e){let n=_r(i)+os+_r(t);return e&&(n+=pt+e),n}function xe(i,t=ls){let{collection:e,id:n}=me(i);return Z(e,n,t())}function me(i){let[t,e]=i.split(pt),[n,r,...o]=t.split("/");o.length&&(r+="/"+o.join("/"));let s;return r.includes(".")?s=r.slice(0,r.indexOf(".")):s=r,{collection:Er(n),id:Er(s),subId:e}}function Ge(i,t){let e=ne(i);if(Array.isArray(i)){let n;for(let r=0;r<i.length;r++)n=i[r],V(n)&&!Q(n)&&(Dr(n,e,t),Ge(n,t))}else if(V(i)&&!Q(i))for(let n of Object.keys(i))V(i[n])&&!Q(i[n])&&(Dr(i[n],e,t),Ge(i[n],t))}function ss(i){if(V(i))return i[Oe]||i[Be]}function as(i){return V(i)&&(delete i[Be],delete i[Oe]),i}function cs(i){let t=ss(i);t&&K(i,t)}function ft(i){if(cs(i),as(i),Array.isArray(i))for(let t=0;t<i.length;t++)ft(i[t]);else if(V(i))for(let t of Object.keys(i))ft(i[t])}function Ut(i){if(Kt(i),Array.isArray(i))for(let t=0;t<i.length;t++)Ut(i[t]);else if(V(i))for(let t of Object.keys(i))Ut(i[t])}function ls(){return dt().slice(0,8)}function he(i){return{"@@type":"ref",id:i}}function Vt(i,t=new Map){if(Array.isArray(i)){let e=ne(i),n=K([],e);for(let r=0;r<i.length;r++){let o=i[r];if(V(o)){if(Se(o))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(be(o)){n[r]=o;continue}else{let s=ne(o);n[r]=he(s),Vt(o,t)}}else n[r]=o}t.set(e,n)}else if(V(i)&&!Q(i)){let e=ne(i),n=K({},e);for(let r of Object.keys(i)){let o=i[r];if(V(o)){if(Se(o))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(be(o))n[r]=o;else{let s=ne(o);n[r]=he(s),Vt(o,t)}}else n[r]=o}t.set(e,n)}else Q(i);return t}function $(i){return i.split(".")[0].split(pt)[0]}function oi(i){let t=$(i),e=xe(t,()=>"\uFFFF");return[`${t}${pt}`,e]}function si(i){let t=$(i);return[`${t}.`,`${t}.\uFFFF`]}function Ee(i,t){return $(i)===$(t)}function ds(i){let{collection:t,id:e,subId:n}=me(i);return Z(t,e,n)}var us=/"\w+\/[^"]+?(\.[^"]+)+\:[\S]+?"/g;function fs(i){return i.replaceAll(us,t=>{let e=t.slice(1,t.length-1);return`"${ds(e)}"`})}function ai(i){return JSON.parse(fs(JSON.stringify(i)))}function Cr(i){return!i.includes(pt)}function Se(i){return i&&typeof i=="object"&&i["@@type"]==="ref"}function ci(i){return V(i)&&!Q(i)}function ps(i,t){return i===t?!0:Q(i)&&Q(t)?Ye(i,t):!1}function ht(i,t,e,n,r=[],o={}){let s=ne(i);function a(p,l,m){if(!ci(l))ps(l,m)||r.push({oid:s,timestamp:e(),data:{op:"set",name:p,value:l}});else{let x=pe(m),y=pe(l);y&&!Ee(s,y)?(l=ae(l,!1),y=xe(s,n),K(l,y)):o.mergeUnknownObjects?!y&&x?(K(l,x),y=x):y=ri(l,s,n):y=ri(l,s,n),L(!!y,"Error: no value OID was resolved during diff. This is a bug in Verdant."),L(Ee(s,y),`Error: value OID ${y} is not related to parent OID ${s}. This is a bug in Verdant.`),m===void 0||y!==x?(Te(l,y,e,n,r),r.push({oid:s,timestamp:e(),data:{op:"set",name:p,value:he(y)}}),x!==void 0&&r.push({oid:x,timestamp:e(),data:{op:"delete"}})):ht(m,l,e,n,r,o)}}if(Array.isArray(i)&&Array.isArray(t)){for(let l=0;l<t.length;l++){let m=t[l],x=i[l];a(l,m,x)}let p=i.length-t.length;if(p>0){for(let l=t.length;l<i.length;l++){let m=i[l],x=pe(m);x&&r.push({oid:x,timestamp:e(),data:{op:"delete"}})}r.push({oid:s,timestamp:e(),data:{op:"list-delete",index:t.length,count:p}})}}else{if(Array.isArray(i)||Array.isArray(t))throw new Error("Cannot diff an array with an object");if(ci(i)&&ci(t)){let p=new Set(Object.keys(i));for(let[l,m]of Object.entries(t)){if(m===void 0&&o.defaultUndefined||(p.delete(l),ii(l)))continue;let x=i[l];a(l,m,x)}if(!o.defaultUndefined)for(let l of p)ii(l)||r.push({oid:s,timestamp:e(),data:{op:"remove",name:l}})}}return r}function Te(i,t,e,n,r=[]){K(i,t),Ge(i,n);let o=Vt(i);for(let s of o.keys()){let a=o.get(s);r.push({oid:s,timestamp:e(),data:{op:"initialize",value:Kt(a)}})}return r}function mt(i){let t={};for(let e of i)e.oid in t?t[e.oid].push(e):t[e.oid]=[e];return t}function Ar(i){let t={};for(let e of i){let n=$(e.oid);n in t?t[n].push(e):t[n]=[e]}return t}function Rr(i){let t={};for(let e of i){let n=$(e.oid);n in t?t[n].push(e):t[n]=[e]}return t}function Me(i){return Array.isArray(i)?!0:(console.error(`Cannot apply list patch; expected array, received ${JSON.stringify(i)}. This suggests your data is changing from a list to an object over time. (OID: ${pe(i)})`),!1)}function je(i,t,e){if(i==null&&t.op!=="initialize")return i;let n=i,r,o;function s(a){e&&Q(a)&&e.push(a)}switch(t.op){case"set":s(n[t.name]),n[t.name]=t.value;break;case"remove":s(n[t.name]),delete n[t.name];break;case"list-push":Me(i)&&i.push(t.value);break;case"list-delete":Me(i)&&(s(i[t.index]),i.splice(t.index,t.count));break;case"list-move-by-index":Me(i)&&(o=i.splice(t.from,1),i.splice(t.to,0,o[0]));break;case"list-remove":if(Me(i))do{let a=t.value;t.only==="last"?Se(a)?r=Or(i,p=>p.id===a.id):r=i.lastIndexOf(a):Se(a)?r=i.findIndex(p=>p.id===a.id):r=i.indexOf(a),r!==-1&&(s(i[r]),i.splice(r,1))}while(!t.only&&r!==-1);break;case"list-add":Me(i)&&(i.some(p=>Se(p)&&Se(t.value)?p.id===t.value.id:p===t.value)||i.push(t.value));break;case"list-move-by-ref":Me(i)&&(r=i.findIndex(a=>Ye(a,t.value)),o=i.splice(r,1),i.splice(t.index,0,o[0]));break;case"list-insert":if(Me(i)){if(!t.value&&!t.values)throw new Error(`Cannot apply list insert patch; expected value or values, received ${JSON.stringify(t)}`);t.value?i.splice(t.index,0,t.value):i.splice(t.index,0,...t.values)}break;case"delete":Array.isArray(i)?i.forEach(s):V(i)&&Object.values(i||{}).forEach(s);return;case"initialize":return ae(t.value);case"touch":return i;default:throw new Error(`Unsupported patch operation: ${t.op}`)}return i}function $t(i,t,e=[]){if(Array.isArray(i))for(let n=0;n<i.length;n++){let r=i[n];i[n]=Pr(r,t,e),V(i[n])&&$t(i[n],t,e)}else if(!be(i)){if(V(i)){L(pe(i),`Object ${JSON.stringify(i)} must have an oid`);for(let n of Object.keys(i))i[n]=Pr(i[n],t,e),V(i[n])&&$t(i[n],t,e)}}return e}function Pr(i,t,e){if(Se(i)){e.push(i.id);let n=t.get(i.id);return L(!!n,`No value was found in object map for ${i.id}`),K(n,i.id)}else return i}var hs=i=>({type:"object",...i}),ms=i=>({type:"array",...i}),gs=i=>({type:"string",...i}),ys=i=>({type:"number",...i}),bs=i=>({type:"boolean",...i}),ws=i=>({type:"any",...i}),vs=i=>({type:"map",...i}),Ss=i=>({type:"file",...i}),Tr={object:hs,array:ms,string:gs,number:ys,boolean:bs,any:ws,map:vs,file:Ss};var Br=Qe(at(),1);function li(i){return i.equals!==void 0}function di(i){return i.gte!==void 0||i.lte!==void 0||i.gt!==void 0||i.lt!==void 0}function xs(i){return!!i.match}function ui(i){return i.startsWith!==void 0}function Fr(i){return!di(i)&&!li(i)&&!xs(i)&&!ui(i)&&i.order}function we(i){return i.type==="any"?!0:i.type==="map"?!1:i.nullable}function Ce(i){return i?i.type==="map"||i.type==="array"?!0:i.type==="file"?!1:i.default!==void 0:!1}function pi(i){if(!(!i||!Ce(i)))return i.type==="file"?we(i)?null:void 0:i.type==="map"?{}:i.type==="array"?we(i)?null:[]:i.type==="object"?we(i)?null:void 0:typeof i.default=="function"?i.default():i.default}function Pe(i,t){for(let[e,n]of Object.entries(i.fields)){let r=hi(n);(r!==void 0&&t[e]===void 0||!we(n)&&t[e]===null)&&(t[e]=r),t[e]&&Le(t[e],n)}return t}function Le(i,t){if(i==null)return i;if(t.type==="object")for(let[e,n]of Object.entries(t.properties)){if(i[e]===void 0){let r=hi(n);r!==void 0&&(i[e]=r)}Le(i[e],n)}else if(t.type==="array")for(let e of i)Le(e,t.items);else if(t.type==="map")for(let[e,n]of Object.entries(i))e===Oe||e===Be||Le(n,t.values)}function hi(i){if(i.type==="string"||i.type==="number"||i.type==="boolean"||i.type==="any"){if(i.default&&typeof i.default=="function")return i.default();if(i.default!==void 0)return JSON.parse(JSON.stringify(i.default))}if(i.type==="array")return[];if(i.type==="map")return{};if(i.type!=="any"&&i.nullable)return null;if(i.type==="object"&&i.default){let t=typeof i.default=="function"?i.default():JSON.parse(JSON.stringify(i.default));for(let[e,n]of Object.entries(i.properties))t[e]===void 0&&(t[e]=hi(n));return t}}function mi(i,t){for(let[e,n]of Object.entries(t))e===Oe||e===Be||(i.fields[e]?fi(n,i.fields[e]):delete t[e]);return t}function fi(i,t){if(V(i)&&t.type==="object")for(let[e,n]of Object.entries(i))t.properties[e]?fi(n,t.properties[e]):delete i[e];else if(Array.isArray(i)&&t.type==="array")for(let e of i)fi(e,t.items)}function kr(i,t){for(let[e,n]of Object.entries(t))if(e!==Oe){if(!i[e])return{type:"invalid-key",fieldPath:[e],message:`Invalid field "${e}"`};if(n){let r=Fe({field:i[e],value:n,fieldPath:[e]});if(r)return r}}}function Fe({field:i,value:t,fieldPath:e=[],depth:n,requireDefaults:r}){if(!(n!==void 0&&n<=0)&&!(we(i)&&t===null)){if(t===null&&(r||!Ce(i)))return{type:"no-default",fieldPath:e,message:`Invalid null value for field ${Ae(e)}`};if(i.type==="object"){if(!V(t))return{type:"invalid-type",fieldPath:e,message:`Expected object${i.nullable?" or null":""} for field ${Ae(e)}, got ${t}`};for(let[o,s]of Object.entries(i.properties))o!==Oe&&t[o]&&Fe({field:s,value:t[o],fieldPath:[...e,o],depth:n!==void 0?n-1:void 0});for(let o of Object.keys(t))if(!i.properties[o])return{type:"invalid-key",fieldPath:[...e,o],message:`Invalid unexpected field "${o}" on value ${Ae(e)}`}}else if(i.type==="array"){if(!Array.isArray(t))return t===null&&i.nullable?void 0:{type:"invalid-value",fieldPath:e,message:`Expected array${i.nullable?" or null":""} for field ${Ae(e)}, got ${t}`};for(let o of t)Fe({field:i.items,value:o,fieldPath:[...e,"[]"],depth:n!==void 0?n-1:void 0})}else if(i.type==="map"){if(!V(t))return{type:"invalid-type",fieldPath:e,message:`Expected map for field ${Ae(e)}, got ${t}`};for(let[o,s]of Object.entries(t))Fe({field:i.values,value:s,fieldPath:[...e,o],depth:n!==void 0?n-1:void 0})}else if(i.type==="string"){if(typeof t!="string")return{type:"invalid-type",fieldPath:e,message:`Expected string ${i.nullable?" or null":""} for field ${Ae(e)}, got ${t}`};if(i.options&&!i.options.includes(t))return{type:"invalid-value",fieldPath:e,message:`Expected one of ${i.options.join(", ")} for field ${Ae(e)}, got ${t}`}}else if(i.type==="boolean"){if(typeof t!="boolean")return{type:"invalid-type",fieldPath:e,message:`Expected boolean ${i.nullable?" or null":""} for field ${Ae(e)}, got ${t}`}}else if(i.type==="number"){if(typeof t!="number")return{type:"invalid-type",fieldPath:e,message:`Expected number ${i.nullable?" or null":""} for field ${Ae(e)}, got ${t}`}}else i.type}}function Ae(i){return i.length===0?"root":i.join(".")}function Ne(i,t){return i.type==="object"?i.properties[t]:i.type==="array"?i.items:i.type==="map"?i.values:i.type==="any"?i:"type"in i?null:i[t]??null}function gi({synthetics:i,indexes:t,...e}){let n={...i,...t};for(let[r,o]of Object.entries(e.fields))"indexed"in o&&(n[r]={field:r});return{...e,indexes:n}}function gt(i){return i}gt.collection=gi;gt.fields=Tr;gt.generated={id:Br.default};var zt="\uFFFFFE",Os="\0",Is="\uFFFFFF";function ce(...i){let t=Ds(i);return t.length===1?t[0]:t}function Ue(...i){return i.join(zt)+`${Is}`}function Ve(...i){return i.join(zt)+`${zt}${Os}`}function Ds(i){let t=[[]];for(let e of i)if(Array.isArray(e)){let n=[];for(let r of t)for(let o of e)n.push(r.concat(o));t=n}else for(let n of t)n.push(`${e}`);return Array.from(new Set(t.map(e=>e.join(zt))))}function _s(i){return!!i.field}function Es(i,t){let e={};for(let[n,r]of Object.entries(i.indexes||{})){let o=r;_s(o)?e[n]=ve(t[o.field]):e[n]=ve(o.compute(t))}return e}function Cs(i,t){return Object.entries(i.compounds||{}).reduce((e,[n,r])=>(e[n]=ce(...r.of.map(o=>t[o])),e),{})}function Ps(i,t){return Object.entries(i.fields).reduce((e,[n,r])=>("indexed"in r&&(e[n]=ve(t[n])),e),{})}function qt(i,t){let e={[i.primaryKey]:t[i.primaryKey],...Ps(i,t),...Es(i,t)};return Object.assign(e,Cs(i,{...t,...e})),e["@@@snapshot"]=t,e}var As="null";function ve(i){if(i===null)return As;if(typeof i=="string"||typeof i=="number")return i;if(typeof i=="boolean"||i===null)return`${i}`;if(i===void 0)return"undefined";if(Array.isArray(i))return i.map(ve);throw new Error(`Unsupported index value: ${i}`)}var Mr={version:0,collections:{}};function Wt(i,t,e){let n=typeof t=="function",r=n?Mr:i,o=n?i:t,s=n?t:e,a=Object.keys(o.collections).filter(S=>r.collections[S]&&ut(r.collections[S])!==ut(o.collections[S])),p=Object.keys(r.collections).filter(S=>!o.collections[S]),l=Object.keys(o.collections).filter(S=>!r.collections[S]),m=new Set;for(let S of a){let I=r.collections[S].fields,v=o.collections[S].fields;Object.keys(v).some(D=>!I[D]?.default&&v[D]?.default)&&m.add(S),Object.keys(I).some(D=>!v[D])&&m.add(S)}let x={},y={};for(let S of[...a,...l]){let I=Ht(r.collections[S]),v=Ht(o.collections[S]),D=v.filter(b=>!I.find(_=>_.name===b.name)),R=I.filter(b=>!v.find(_=>_.name===b.name));D.length>0&&(x[S]=D,a.includes(S)&&m.add(S)),R.length>0&&(y[S]=R,a.includes(S)&&m.add(S))}let C=(S,I)=>Pe(o.collections[S],I),w=S=>I=>{let v=o.collections[S];return Pe(v,mi(v,I))};return{version:o.version,migrate:async S=>{let I=[];if(await s({migrate:async(v,D)=>{let R=w(v),b=async _=>{let u=await D(_);return K(u,ne(_)),R(u)};await S.migrate(v,b),I.push(v),m.delete(v)},identity:v=>v,withDefaults:C,info:{changedCollections:a,addedCollections:l,removedCollections:p},queries:S.queries,mutations:S.mutations}),o.version>1){S.log("debug","auto-migrating collections with new defaults",m);for(let D of m)await S.migrate(D,w(D)),I.push(D);let v=a.filter(D=>!I.includes(D));v.length>0&&console.error(`Unmigrated changed collections from version ${r.version} to version ${o.version}:`,v)}},removedCollections:p,addedIndexes:x,removedIndexes:y,allCollections:Object.keys(o.collections),changedCollections:a,addedCollections:l,oldCollections:Object.keys(r.collections),oldSchema:r,newSchema:o}}function Ht(i){return i?[...Object.keys(i.indexes||{}).map(t=>({name:t,multiEntry:["array","string[]","number[]","boolean[]"].includes(i.indexes[t].type),synthetic:!0,compound:!1})),...Object.keys(i.compounds||{}).map(t=>({name:t,multiEntry:i.compounds[t].of.some(e=>(i.fields[e]||i.indexes[e]).type==="array"),synthetic:!1,compound:!0}))]:[]}function yi(i,t){return Wt(t?i:{version:0,collections:{}},t||i,async({migrate:n,info:r})=>{if((t||i).version!==1)for(let o of r.changedCollections)await n(o,s=>s)})}function bi(i,t,e){let n=typeof t=="function"||t===void 0,r=n?Mr:i,o=n?i:t,s=n?t:e;L(r,"Invalid arguments to createMigration"),L(o,"Invalid arguments to createMigration");let{changedCollections:a,addedCollections:p,removedCollections:l,addedIndexes:m,removedIndexes:x,autoMigratedCollections:y,autoMigration:C}=Rs(r,o);return{version:o.version,migrate:async w=>{let S=[];if(await s?.({migrate:async(v,D)=>{let R=C(v),b=async _=>{let u=await D(_);K(u,ne(_));let h=R(u),d=kr(o.collections[v].fields,h);return h};await w.migrate(v,b),S.push(v),y.delete(v)},info:{changedCollections:a,addedCollections:p,removedCollections:l},queries:w.queries,mutations:w.mutations}),o.version>1){w.log("debug","auto-migrating collections with new defaults",y);for(let D of y)await w.migrate(D,C(D)),S.push(D);for(let D of l)await w.deleteCollection(D);let v=a.filter(D=>!S.includes(D));v.length>0&&console.error(`Unmigrated changed collections from version ${r.version} to version ${o.version}:`,v)}},removedCollections:l,addedIndexes:m,removedIndexes:x,allCollections:Object.keys(o.collections),changedCollections:a,addedCollections:p,oldCollections:Object.keys(r.collections),oldSchema:r,newSchema:o}}function Rs(i,t){let e=Object.keys(t.collections).filter(m=>i.collections[m]&&ut(i.collections[m])!==ut(t.collections[m])),n=Object.keys(i.collections).filter(m=>!t.collections[m]),r=Object.keys(t.collections).filter(m=>!i.collections[m]),o=new Set;for(let m of e){let x=i.collections[m].fields,y=t.collections[m].fields;Object.keys(y).some(C=>!Ce(x[C])&&Ce(y[C]))&&o.add(m),Object.keys(x).some(C=>!y[C])&&o.add(m)}let s={},a={};for(let m of[...e,...r]){let x=Ht(i.collections[m]),y=Ht(t.collections[m]),C=y.filter(S=>!x.find(I=>I.name===S.name)),w=x.filter(S=>!y.find(I=>I.name===S.name));C.length>0&&(s[m]=C,e.includes(m)&&o.add(m)),w.length>0&&(a[m]=w,e.includes(m)&&o.add(m))}return{changedCollections:e,addedCollections:r,removedCollections:n,addedIndexes:s,removedIndexes:a,autoMigratedCollections:o,withDefaults:(m,x)=>Pe(t.collections[m],x),autoMigration:m=>x=>{let y=t.collections[m];return Pe(y,mi(y,x))}}}var Qt=class{constructor(t,e){this.getNow=t;this.createSubId=e;this.isPrimitive=t=>!V(t)||Q(t);this.createDiff=(t,e,n={})=>ht(t,e,this.getNow,this.createSubId,[],n);this.createInitialize=(t,e)=>Te(t,e,this.getNow,this.createSubId);this.createSet=(t,e,n)=>{if(this.isPrimitive(n))return[{oid:t,timestamp:this.getNow(),data:{op:"set",name:e,value:n}}];{let r=xe(t,this.createSubId);return[...Te(n,r,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"set",value:he(r),name:e}}]}};this.createRemove=(t,e)=>[{oid:t,timestamp:this.getNow(),data:{op:"remove",name:e}}];this.createListPush=(t,e)=>{if(this.isPrimitive(e))return[{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:e}}];{let n=xe(t,this.createSubId);return[...Te(e,n,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:he(n)}}]}};this.createListAdd=(t,e)=>this.isPrimitive(e)?[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:e}}]:[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:he(e)}}];this.createListInsert=(t,e,n)=>{if(this.isPrimitive(n))return[{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:n,index:e}}];{let r=xe(t,this.createSubId);return[...Te(n,r,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:he(r),index:e}}]}};this.createListRemove=(t,e,n)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-remove",value:e,only:n}}];this.createListDelete=(t,e,n=1)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-delete",index:e,count:n}}];this.createListMoveByRef=(t,e,n)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-move-by-ref",value:e,index:n}}];this.createListMoveByIndex=(t,e,n)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-move-by-index",from:e,to:n}}];this.createDelete=t=>[{oid:t,timestamp:this.getNow(),data:{op:"delete"}}];this.createDeleteAll=t=>t.map(e=>({oid:e,timestamp:this.getNow(),data:{op:"delete"}}))}};var U=class{constructor(t){this._onAllUnsubscribed=t;this.subscribers={};this.counts={};this._disabled=!1;this.disposed=!1;this.subscriberCount=t=>this.counts[t]??0;this.totalSubscriberCount=()=>Object.values(this.counts).reduce((t,e)=>t+e,0);this.subscribe=(t,e)=>{let n=Nt(),r=this.subscribers[t];return r||(r=this.subscribers[t]={}),r[n]=e,this.counts[t]=(this.counts[t]||0)+1,()=>{this.subscribers[t]&&(delete this.subscribers[t][n],this.counts[t]--,this.counts[t]===0&&(delete this.subscribers[t],delete this.counts[t],this._onAllUnsubscribed&&this._onAllUnsubscribed(t)))}};this.emit=(t,...e)=>{this._disabled||this.subscribers[t]&&Object.values(this.subscribers[t]).forEach(n=>n(...e))};this.dispose=()=>{this._disabled=!0,this.disposed=!0;let t=Object.keys(this.subscribers);this.subscribers={},this.counts={},t.forEach(e=>{this._onAllUnsubscribed&&this._onAllUnsubscribed(e)})};this.disable=()=>{this._disabled=!0}}get disabled(){return this._disabled}};function jr(i,t,e,n){if(t==null)return[{oid:i,timestamp:n(),data:{op:"delete"}}];let r=ae(t),o=[];for(let s of e){let a=Ts(i,r,s,n);o.unshift(...a),je(r,s.data)}return o}function Ts(i,t,e,n){let r=e.data;switch(r.op){case"set":case"remove":return[{oid:i,timestamp:n(),data:{op:"set",name:r.name,value:t[r.name]}}];case"list-insert":return[{oid:i,timestamp:n(),data:{op:"list-delete",index:r.index,count:1}}];case"list-delete":return[{oid:i,timestamp:n(),data:{op:"list-insert",index:r.index,values:t.slice(r.index,r.count)}}];case"list-move-by-ref":return[{oid:i,timestamp:n(),data:{op:"list-move-by-ref",value:r.value,index:t.indexOf(r.value)}}];case"list-move-by-index":return[{oid:i,timestamp:n(),data:{op:"list-move-by-index",from:r.to,to:r.from}}];case"delete":return[{oid:i,timestamp:n(),data:{op:"initialize",value:t}}];case"list-push":return[{oid:i,timestamp:n(),data:{op:"list-remove",value:r.value,only:"last"}}];case"list-remove":if(r.only==="last"){let o=t.lastIndexOf(r.value);return[{oid:i,timestamp:n(),data:{op:"list-insert",index:o,values:[r.value]}}]}else if(r.only==="first"){let o=t.indexOf(r.value);return[{oid:i,timestamp:n(),data:{op:"list-insert",index:o,values:[r.value]}}]}else{let o=[],s=t.indexOf(r.value);for(;s!==-1;)o.push(s),s=t.indexOf(r.value,s+1);return o.map(a=>({oid:i,timestamp:n(),data:{op:"list-insert",index:a,value:r.value}}))}case"list-add":return[{oid:i,timestamp:n(),data:{op:"list-remove",value:r.value,only:"last"}}];case"initialize":return[{oid:i,timestamp:n(),data:{op:"delete"}}];case"touch":return[];default:throw new Error(`Cannot undo operation type: ${r.op}`)}}var Xe=class{constructor(t){this.flusher=t;this.batches=new Map;this.flush=t=>{let e=this.batches.get(t);if(e)return e.flush()};this.discard=t=>{let e=this.batches.get(t);e&&(e.discard(),this.batches.delete(t))};this.flushAll=()=>[...this.batches.values()].map(t=>t.flush());this.getSize=t=>{let e=this.batches.get(t);return e?e.items.length:0}}add({key:t,userData:e,items:n,max:r,timeout:o}){let s=this.batches.get(t);return s||(s=new wi({max:r||null,startedAt:Date.now(),userData:e,timeout:o||null,flusher:this.flusher,key:t}),this.batches.set(t,s)),s.update({items:n,max:r,timeout:o,userData:e}),s}},wi=class{constructor({max:t,startedAt:e,timeout:n,userData:r,flusher:o,key:s}){this.items=[];this.update=({items:t,max:e,timeout:n,userData:r})=>{this.items.push(...t),e!==void 0&&(this.max=e),n!==void 0&&(this.timeout=n),r&&(this.userData=r);let o=this.items.length!==0&&this.timeout!==null&&!this.flushTimeout;this.max!==null&&this.items.length>=this.max?this.flush():o&&this.timeout!==null&&(this.flushTimeout=setTimeout(this.flush,this.timeout))};this.flush=()=>{this.flushTimeout&&clearTimeout(this.flushTimeout),this.flushTimeout=void 0;let t=this.items;return this.items=[],this.flusher(t,this.key,this.userData)};this.discard=()=>{this.flushTimeout&&clearTimeout(this.flushTimeout),this.flushTimeout=void 0,this.items=[]};this.max=t,this.startedAt=e,this.timeout=n,this.userData=r,this.flusher=o,this.key=s}};function Lr(i,t){let e,n;return(...r)=>{let o=t();return e&&e.length===o.length&&e.every((s,a)=>s===o[a])||(e=[...o],n=i(...r)),n}}var vi=(l=>(l[l.InvalidRequest=4e3]="InvalidRequest",l[l.BodyRequired=4001]="BodyRequired",l[l.NoToken=4010]="NoToken",l[l.InvalidToken=4011]="InvalidToken",l[l.TokenExpired=4012]="TokenExpired",l[l.NotFound=4040]="NotFound",l[l.Unexpected=5e3]="Unexpected",l[l.ConfigurationError=5010]="ConfigurationError",l[l.NoFileStorage=5011]="NoFileStorage",l))(vi||{}),Nr=class extends Error{constructor(e,n,r){super(r??`Verdant error: ${e}`,{cause:n});this.code=e;this.toResponse=()=>JSON.stringify({code:this.code})}static{this.Code=vi}get httpStatus(){let e=Math.floor(this.code/10);return e<600?e:500}};function Ur(i){return typeof i=="object"&&"code"in i&&typeof i.code=="number"}function le(i){return i instanceof Error&&i.name==="AbortError"}function J(i){return new Promise((t,e)=>{i.onsuccess=()=>{t(i.result)},i.onerror=()=>{i.error&&le(i.error)?t(i.result):e(i.error)}})}function yt(i,t){return new Promise((e,n)=>{let r=i.transaction([t],"readonly"),s=r.objectStore(t).openCursor(),a=0,p=0;s.onsuccess=function(l){let m=s.result;m&&(a++,p=p+xr(m.value),m.continue())},s.onerror=function(l){s.error&&le(s.error)?e({count:a,size:p}):n(s.error)},r.oncomplete=function(l){e({count:a,size:p})},r.onabort=function(l){n(l)},r.onerror=function(l){n(l)}})}function Vr(i,t){let e=i.transaction(t,"readonly"),n=t.map(r=>{let o=e.objectStore(r);return J(o.getAll())});return Promise.all(n)}async function Ke(i){i.close(),await new Promise((t,e)=>{t()})}async function Jt(i,t=window.indexedDB){let e=t.deleteDatabase([i,"meta"].join("_")),n=t.deleteDatabase([i,"collections"].join("_"));await Promise.all([new Promise((r,o)=>{e.onsuccess=r,e.onerror=o}),new Promise((r,o)=>{n.onsuccess=r,n.onerror=o})]),window.location.reload()}function Kr(i,t=window.indexedDB){return J(t.deleteDatabase(i))}async function $r(i=window.indexedDB){return i.databases()}function Yt(i,t,e,n,r){let o=i.transaction(t,e);if(n){let s=()=>{r?.("debug","aborting transaction");try{o.abort()}catch(a){r?.("debug","aborting transaction failed",a)}};n.addEventListener("abort",s),o.addEventListener("error",()=>{n.removeEventListener("abort",s)}),o.addEventListener("complete",()=>{n.removeEventListener("abort",s)})}return o}var Ie=class{constructor(){this._disposes=[];this.disposed=!1;this.dispose=()=>{this.disposed=!0,this._disposes.forEach(t=>t()),this._disposes=[]};this.addDispose=t=>{this._disposes.push(t)}}};var se=class extends Ie{constructor(e,{log:n}={}){super();this.db=e;this.globalAbortController=new AbortController;this.createTransaction=(e,n)=>{let r=Yt(this.db,e,n?.mode||"readonly",n?.abort,this.log);return this.globalAbortController.signal.addEventListener("abort",r.abort),r.addEventListener("complete",()=>{this.globalAbortController.signal.removeEventListener("abort",r.abort)}),r.addEventListener("error",()=>{this.globalAbortController.signal.removeEventListener("abort",r.abort)}),r};this.run=async(e,n,r)=>{if(this.disposed||r?.transaction?.error)return Promise.resolve(void 0);let s=(r?.transaction||this.createTransaction([e],r)).objectStore(e),a=n(s);return J(a)};this.runAll=async(e,n,r)=>{if(this.disposed||r?.transaction?.error)return Promise.resolve([]);let s=(r?.transaction||this.createTransaction([e],r)).objectStore(e),a=n(s);return Promise.all(a.map(J))};this.iterate=async(e,n,r,o)=>{let a=(o?.transaction||this.createTransaction([e],o)).objectStore(e),p=n(a);return Array.isArray(p)?Promise.all(p.map(l=>new Promise((m,x)=>{l.onsuccess=()=>{let y=l.result;y?(r(y.value,a),y.continue()):m()},l.onerror=()=>{l.error&&le(l.error)?m():x(l.error)}}))).then(()=>{}):new Promise((l,m)=>{p.onsuccess=()=>{let x=p.result;x?(r(x.value,a),x.continue()):l()},p.onerror=()=>{p.error&&le(p.error)?l():m(p.error)}})};this.clear=e=>this.run(e,n=>n.clear(),{mode:"readwrite"});this.log=n,this.addDispose(()=>{this.globalAbortController.abort()})}};var Gt=class extends se{constructor(){super(...arguments);this.getAckInfo=async()=>{let e=await this.run("info",n=>n.get("ack"));return e||{globalAckTimestamp:null,type:"ack"}};this.setGlobalAck=async e=>{await this.run("info",n=>n.put({type:"ack",globalAckTimestamp:e}),{mode:"readwrite"})}}};var Xt=class extends se{constructor(e,n){super(e,n);this.getAllForDocument=async(e,{mode:n="readonly",transaction:r}={})=>{let o=[];return await this.iterateOverAllForDocument(e,s=>{o.push(s)},{mode:n,transaction:r}),o};this.iterateOverAllForDocument=async(e,n,{mode:r="readonly",transaction:o}={})=>this.iterate("baselines",s=>{let a=$(e),[p,l]=oi(e),[m,x]=si(e);return[s.openCursor(IDBKeyRange.only(a)),s.openCursor(IDBKeyRange.bound(p,l,!1,!1)),s.openCursor(IDBKeyRange.bound(m,x,!1,!1))]},n,{mode:r,transaction:o});this.iterateOverAllForCollection=async(e,n,{mode:r="readonly",transaction:o}={})=>this.iterate("baselines",s=>[s.openCursor(IDBKeyRange.bound(e,e+"\uFFFF",!1,!1))],n,{mode:r,transaction:o});this.getAllForMultipleDocuments=async(e,{mode:n="readonly"}={})=>(await this.runAll("baselines",o=>e.flatMap(s=>{let a=$(s),[p,l]=oi(s),[m,x]=si(s);return[o.get(a),o.getAll(IDBKeyRange.bound(p,l,!1,!1)),o.getAll(IDBKeyRange.bound(m,x,!1,!1))]}),{mode:n})).flat();this.getAllSince=async(e,{mode:n="readonly"}={})=>this.run("baselines",r=>{let o=e?IDBKeyRange.lowerBound(e,!0):void 0;return r.index("timestamp").getAll(o)},{mode:n});this.get=async(e,{transaction:n,mode:r="readonly"}={})=>this.run("baselines",o=>o.get(e),{mode:r,transaction:n});this.set=async(e,{transaction:n}={})=>{await this.run("baselines",r=>r.put(e),{mode:"readwrite",transaction:n})};this.setAll=async(e,{transaction:n}={})=>{await this.runAll("baselines",r=>e.map(o=>r.put(o)),{mode:"readwrite",transaction:n})};this.reset=()=>this.clear("baselines");this.delete=async(e,{transaction:n})=>{await this.run("baselines",r=>r.delete(e),{mode:"readwrite",transaction:n})}}};var zr=Qe(at(),1);var Zt=class extends se{constructor(){super(...arguments);this.get=async({transaction:e}={})=>{if(this.cached)return this.cached;let n=await this.run("info",r=>r.get("localReplicaInfo"),{transaction:e});return n?(this.cached=n,n):(this._creating||(this._creating=(async()=>{let o={type:"localReplicaInfo",id:(0,zr.default)(),ackedLogicalTime:null,lastSyncedLogicalTime:null};await this.run("info",s=>s.put(o),{mode:"readwrite"}),this.cached=o})()),await this._creating,this.get({transaction:e}))};this.update=async(e,{transaction:n}={})=>{let r=await this.get({transaction:n});Object.assign(r,e),await this.run("info",o=>o.put(r),{mode:"readwrite"}),this.cached=r};this.reset=async()=>{let e=await this.get();e.ackedLogicalTime=null,e.lastSyncedLogicalTime=null,await this.run("info",n=>n.put(e),{mode:"readwrite"})}}};var en=class{constructor(t){this.meta=t;this.createOperation=async t=>{let e=await this.meta.localReplica.get();return{type:"op",timestamp:this.meta.now,replicaId:e.id,operations:t.operations.map(n=>({data:n.data,oid:n.oid,timestamp:n.timestamp}))}};this.createMigrationOperation=async({targetVersion:t,...e})=>{let n=await this.meta.localReplica.get();return{type:"op",operations:e.operations.map(r=>({...r,timestamp:this.meta.time.zero(t)})),timestamp:this.meta.time.zero(t),replicaId:n.id}};this.createSyncStep1=async t=>{let e=await this.meta.localReplica.get(),n=t===null?null:e.lastSyncedLogicalTime,r=[],o=new Set;n?await this.meta.operations.iterateOverAllLocalOperations(a=>{r.push({data:a.data,oid:a.oid,timestamp:a.timestamp}),o.add($(a.oid))},{after:n,mode:"readwrite"}):await this.meta.operations.iterateOverAllOperations(a=>{r.push({data:a.data,oid:a.oid,timestamp:a.timestamp}),o.add($(a.oid))},{mode:"readwrite"});let s=[];return n||(s=await this.meta.baselines.getAllSince("")),{type:"sync",schemaVersion:this.meta.schema.currentVersion,timestamp:this.meta.now,replicaId:e.id,resyncAll:!e.lastSyncedLogicalTime,operations:r,baselines:s,since:n}};this.createPresenceUpdate=async t=>{let e=await this.meta.localReplica.get();return{type:"presence-update",presence:t,replicaId:e.id}};this.createHeartbeat=async()=>{let t=await this.meta.localReplica.get();return{type:"heartbeat",timestamp:this.meta.now,replicaId:t.id}};this.createAck=async t=>{let e=await this.meta.localReplica.get();return{type:"ack",timestamp:this.meta.now,replicaId:e.id,nonce:t}}}};var tn=class extends se{constructor(e,n){super(e,n);this.iterateOverAllOperationsForDocument=async(e,n,{to:r,from:o,after:s,mode:a="readonly",transaction:p}={})=>{let m=(p||this.createTransaction(["operations"],{mode:a})).objectStore("operations"),x=m.index("d_t"),y=o||s,C=y?ce(e,y):Ve(e),w=r?ce(e,r):Ue(e),S=IDBKeyRange.bound(C,w,!!s,!1),I=x.openCursor(S,"next");return new Promise((v,D)=>{let R;I.onsuccess=b=>{let _=I.result;if(_){let u=_.value;L(u.oid.startsWith(e)),L(R===void 0||R<=u.timestamp,`expected ${R} <= ${u.timestamp}`),n(u,m),R=u.timestamp,_.continue()}else v()},I.onerror=b=>{if(le(I.error)){v();return}else D(I.error)}})};this.iterateOverAllOperationsForEntity=async(e,n,{after:r,to:o,mode:s,transaction:a})=>{let l=(a||this.createTransaction(["operations"],{mode:s})).objectStore("operations"),m=r?ce(e,r):Ve(e),x=o?ce(e,o):Ue(e),y=IDBKeyRange.bound(m,x,!!r,!1),C=l.openCursor(y,"next");return new Promise((w,S)=>{let I;C.onsuccess=v=>{let D=C.result;if(D){let R=D.value;L(R.oid.startsWith(e)),L(I===void 0||I<=R.timestamp,`expected ${I} <= ${R.timestamp}`),n(R,l),I=R.timestamp,D.continue()}else w()},C.onerror=v=>{le(C.error)?w():S(C.error)}})};this.iterateOverAllOperationsForCollection=async(e,n,{after:r,to:o,mode:s,transaction:a})=>{let p=a||this.createTransaction(["operations"],{mode:s});return this.iterate("operations",l=>l.openCursor(IDBKeyRange.bound(e,e+"\uFFFF",!1,!1),"next"),n,{mode:s,transaction:p})};this.iterateOverAllLocalOperations=async(e,{before:n,after:r,mode:o="readonly",transaction:s})=>{let p=(s||this.createTransaction(["operations"],{mode:o})).objectStore("operations"),l=p.index("l_t"),m=r?ce(!0,r):Ve(!0),x=n?ce(!0,n):Ue(!0),y=IDBKeyRange.bound(m,x,!!r,!0),C=l.openCursor(y,"next");return new Promise((w,S)=>{let I;C.onsuccess=v=>{let D=C.result;if(D){let R=D.value;L(I===void 0||I<=R.timestamp,`expected ${I} <= ${R.timestamp}`),e(R,p),I=R.timestamp,D.continue()}else w()},C.onerror=v=>{le(C.error)?w():S(C.error)}})};this.iterateOverAllOperations=async(e,{before:n,transaction:r,mode:o,from:s})=>{await this.iterate("operations",a=>{let p=s?Ve(s):void 0,l=n?Ue(n):void 0,m=p&&l?window.IDBKeyRange.bound(p,l,!1,!0):p?window.IDBKeyRange.lowerBound(p,!1):l?window.IDBKeyRange.upperBound(l,!0):void 0;return a.index("timestamp").openCursor(m,"next")},e,{mode:o,transaction:r})};this.addOperations=async(e,{transaction:n}={})=>this.insert(e.map(this.addCompoundIndexes),{transaction:n});this.addCompoundIndexes=e=>({...e,oid_timestamp:ce(e.oid,e.timestamp),l_t:ce(e.isLocal,e.timestamp),d_t:ce($(e.oid),e.timestamp)});this.insert=async(e,{transaction:n})=>{let r=new Set;return await this.runAll("operations",o=>e.map(s=>(r.add($(s.oid)),o.put(s))),{mode:"readwrite",transaction:n}),Array.from(r)};this.reset=()=>this.clear("operations")}};var nn=class{constructor(t,e){this.db=t;this.currentVersion=e;this.cached=null;this.get=async()=>{if(this.cached)return this.cached;let r=this.db.transaction("info","readonly").objectStore("info").get("schema"),o=await J(r);return o?(this.cached=JSON.parse(o.schema),this.cached):null};this.set=async t=>{let o=this.db.transaction("info","readwrite").objectStore("info").put({type:"schema",schema:JSON.stringify(t)});this.cached=t,await J(o)}}};var bt=class extends U{constructor({disableRebasing:e,context:n}){super();this.time=new Rt;this.disableRebasing=!1;this._closing=!1;this.setContext=e=>{this.context=e};this.close=()=>{this._closing=!0};this.createTransaction=(e,n={})=>Yt(this.db,e,"readwrite",n.abort,this.context.log);this.getAllDocumentRelatedOids=async e=>{let n=new Set,r=$(e);L(r===e,"Must be root document OID"),n.add(r);let o=this.createTransaction(["baselines","operations"]);return await Promise.all([this.baselines.iterateOverAllForDocument(r,s=>{n.add(s.oid)},{transaction:o}),this.operations.iterateOverAllOperationsForDocument(r,s=>{n.add(s.oid)},{transaction:o})]),Array.from(n)};this.getAllCollectionRelatedOids=async e=>{let n=new Set,r=this.db.transaction(["baselines","operations"],"readwrite");return await Promise.all([this.baselines.iterateOverAllForCollection(e,o=>{n.add(o.oid)},{transaction:r}),this.operations.iterateOverAllOperationsForCollection(e,o=>{n.add(o.oid)},{transaction:r})]),Array.from(n)};this.getDocumentSnapshot=async(e,n={})=>{let r=$(e);L(r===e,"Must be root document OID");let o=this.db.transaction(["baselines","operations"],"readwrite"),s=await this.baselines.getAllForDocument(r,{transaction:o}),a=new Map;for(let l of s)l.snapshot&&K(l.snapshot,l.oid),a.set(l.oid,l.snapshot);await this.operations.iterateOverAllOperationsForDocument(r,l=>{let m=a.get(l.oid)||void 0,x=je(m,l.data);x&&K(x,l.oid),a.set(l.oid,x)},{transaction:o,to:n.to||this.now});let p=a.get(r);return p&&$t(p,a),p};this.getDocumentData=async(e,n)=>{let r=this.createTransaction(["baselines","operations"],n),o=[],s={};return await Promise.all([this.baselines.iterateOverAllForDocument(e,a=>{o.push(a)},{transaction:r}),this.operations.iterateOverAllOperationsForDocument(e,a=>{s[a.oid]??=[],s[a.oid].push(a)},{transaction:r})]),{baselines:o,operations:s}};this.ack=async e=>{let n=await this.localReplica.get();e>this.now||(this.emit("message",{type:"ack",replicaId:n.id,timestamp:e}),!this._closing&&(!n.ackedLogicalTime||e>n.ackedLogicalTime)&&this.localReplica.update({ackedLogicalTime:e}))};this.insertLocalOperations=async(e,n)=>{if(e.length===0)return;this.log("debug",`Inserting ${e.length} local operations`,e);for(let o of e)o.isLocal=!0;await this.operations.addOperations(e,n);let r=await this.messageCreator.createOperation({operations:e});this.emit("message",r),this.tryAutonomousRebase()};this.insertRemoteOperations=async(e,n)=>{if(e.length===0)return[];this.log("debug",`Inserting ${e.length} remote operations`,e);let r=await this.operations.addOperations(e.map(o=>({...o,isLocal:!1})),n);return this.ack(e[e.length-1].timestamp),r};this.insertRemoteBaselines=async(e,n)=>{if(e.length===0)return[];this.log(`Inserting ${e.length} remote baselines`),await this.baselines.setAll(e,n);let r=new Set;return e.forEach(o=>{r.add($(o.oid))}),Array.from(r)};this.insertData=async(e,n)=>{let r=this.createTransaction(["baselines","operations"],n);e.baselines&&await this.insertRemoteBaselines(e.baselines,{transaction:r}),!n?.abort?.aborted&&e.operations&&(e.isLocal?await this.insertLocalOperations(e.operations,{transaction:r}):await this.insertRemoteOperations(e.operations,{transaction:r}))};this.updateLastSynced=async e=>{if(!this._closing)return this.localReplica.update({lastSyncedLogicalTime:e})};this.lastSyncedTimestamp=async()=>(await this.localReplica.get()).lastSyncedLogicalTime;this.tryAutonomousRebase=async()=>{this.disableRebasing||(await this.localReplica.get()).lastSyncedLogicalTime||await this.runRebase(this.now)};this.runRebase=async e=>{if(this._closing)return;let n,r=new Set,o=this.createTransaction(["baselines","operations"]),s=0;if(await this.operations.iterateOverAllOperations(p=>{r.add(p.oid),n=p.timestamp,s++},{before:e,transaction:o}),!r.size||this._closing)return;let a=[];for(let p of r)a.push(await this.rebase(p,n||e,o));this.emit("rebase",a)};this.rebase=async(e,n,r)=>{let o=(await this.localReplica.get()).id;this.log("[",o,"]","Rebasing",e,"up to",n);let s=r||this.createTransaction(["operations","baselines"]),a=await this.baselines.get(e,{transaction:s}),p=a?.snapshot||void 0,l=0,m=[];await this.operations.iterateOverAllOperationsForEntity(e,(y,C)=>{(!a||y.timestamp>a.timestamp)&&(p=je(p,y.data,m)),l++,C.delete(y.oid_timestamp)},{to:n,transaction:s}),p&&K(p,e);let x={oid:e,snapshot:p,timestamp:n};if(x.snapshot?await this.baselines.set(x,{transaction:s}):await this.baselines.delete(e,{transaction:s}),this.log("debug","successfully rebased",e,"up to",n,":",p,"and deleted",l,"operations"),m.length){let y=m.filter(be);y.length&&this.emit("filesDeleted",y)}return x};this.reset=async()=>{await this.operations.reset(),await this.baselines.reset(),await this.localReplica.reset()};this.updateSchema=async(e,n)=>{let r=await this.schema.get();if(r&&n===r.version&&r.version===e.version&&JSON.stringify(r)!==JSON.stringify(e))throw console.error(`Schema mismatch for version ${e.version}
|
|
7
7
|
${JSON.stringify(r)}
|
|
8
|
-
${JSON.stringify(e)}`),new Error("Schema has changed without a version change! Any changes to your schema must be accompanied by a change in schema version and a migration routine.");await this.schema.set(e)};this.setGlobalAck=async e=>{this._closing||(await this.ackInfo.setGlobalAck(e),this.disableRebasing||await this.runRebase(e))};this.export=async()=>{let e=this.db,[n,r]=await Vr(e,["baselines","operations"]),o=await this.localReplica.get(),s=await this.schema.get();if(!s)throw new Error("Cannot export Client data before initializing");return{operations:r,baselines:n,localReplica:o,schema:s}};this.resetFrom=async e=>{let r=this.db.transaction(["baselines","operations","info"],"readwrite");await J(r.objectStore("baselines").clear()),await J(r.objectStore("operations").clear()),await J(r.objectStore("info").clear()),await this.localReplica.update({ackedLogicalTime:e.localReplica.ackedLogicalTime,lastSyncedLogicalTime:e.localReplica.lastSyncedLogicalTime},{transaction:r})};this.stats=async()=>{let e=this.db,n=await yt(e,"operations"),r=await yt(e,"baselines");return{operationsSize:n,baselinesSize:r}};this.context=n,this.schema=new nn(n.metaDb,n.schema.version),this.operations=new tn(this.db,{log:n.log}),this.baselines=new Xt(this.db,{log:n.log}),this.localReplica=new Zt(this.db),this.ackInfo=new Gt(this.db),this.messageCreator=new en(this),this.patchCreator=new Qt(()=>this.now),e&&(this.disableRebasing=e)}get db(){return this.context.metaDb}get log(){return this.context.log}get now(){return this.time.now(this.schema.currentVersion)}};var Fs=[ks,Bs,Ms,js,Ls];function rn({indexedDB:i=window.indexedDB,namespace:t,log:e,metadataVersion:n=5}){return new Promise((r,o)=>{let s=i.open(`${t}_meta`,n),c=!1;s.onupgradeneeded=async p=>{let d=s.result,m=s.transaction,S=Fs.slice(p.oldVersion);for(let g of S)await g(d,m);await new Promise((g,C)=>{m.addEventListener("complete",g),m.addEventListener("error",C)}),p.oldVersion||(c=!0)},s.onerror=()=>{console.error("Error opening database",s.error),o(s.error)},s.onsuccess=()=>{r({db:s.result,wasInitialized:c})}})}async function qr({wipNamespace:i,namespace:t,indexedDB:e,log:n,metadataVersion:r}){let o=await rn({namespace:i,indexedDB:e,log:n,metadataVersion:r});if(!o.wasInitialized)return o;n?.("debug","Beginning copy of production metadata database to WIP");let{db:s}=await rn({namespace:t,indexedDB:e,log:n,metadataVersion:r}),c=s.transaction(["baselines","operations","info"],"readonly"),[p,d,m]=await Promise.all([J(c.objectStore("baselines").getAll()),J(c.objectStore("operations").getAll()),J(c.objectStore("info").getAll())]),S=o.db.transaction(["baselines","operations","info"],"readwrite"),g=S.objectStore("baselines"),C=S.objectStore("operations"),w=S.objectStore("info");for(let v of p)g.put(v);for(let v of d)C.put(v);for(let v of m)w.put(v);return await new Promise((v,I)=>{S.oncomplete=()=>{v()},S.onerror=x=>{I(x)},S.onabort=x=>{I(x)}}),await Ke(s),n?.("debug","Finished copy of production metadata database to WIP. Copied:",p.length,"baselines,",d.length,"operations"),o}async function ks(i,t){let e=i.createObjectStore("baselines",{keyPath:"oid"}),n=i.createObjectStore("operations",{keyPath:"oid_timestamp"}),r=i.createObjectStore("info",{keyPath:"type"});e.createIndex("timestamp","timestamp"),n.createIndex("isLocal_timestamp","isLocal_timestamp"),n.createIndex("documentOid_timestamp","documentOid_timestamp")}async function Bs(i,t){let e=t.objectStore("operations");await new Promise((n,r)=>{let o=e.openCursor();o.onsuccess=()=>{let s=o.result;if(s){let{isLocal_timestamp:c,documentOid_timestamp:p,...d}=s.value;s.update({...d,l_t:c,d_t:p}),s.continue()}else n()},o.onerror=s=>{r(o.error)}}),e.deleteIndex("isLocal_timestamp"),e.deleteIndex("documentOid_timestamp"),e.createIndex("l_t","l_t",{unique:!1}),e.createIndex("o_t","o_t",{unique:!1}),e.createIndex("d_t","d_t",{unique:!1})}async function Ms(i,t){t.objectStore("operations").createIndex("timestamp","timestamp")}async function js(i,t){let e=i.createObjectStore("files",{keyPath:"id"});e.createIndex("remote","remote"),e.createIndex("deletedAt","deletedAt")}async function Ls(i,t){let e=t.objectStore("operations");await new Promise((r,o)=>{let s=e.openCursor();s.onsuccess=()=>{let c=s.result;if(c){let p=ai(c.value);p.oid_timestamp!==c.primaryKey?(c.delete(),e.put(p)):c.update(p),c.continue()}else r()},s.onerror=c=>{o(s.error)}});let n=t.objectStore("baselines");await new Promise((r,o)=>{let s=n.openCursor();s.onsuccess=()=>{let c=s.result;if(c){let p=ai(c.value);p.oid!==c.primaryKey?(c.delete(),n.put(p)):c.update(p),c.continue()}else r()},s.onerror=c=>{o(s.error)}})}var Ns=i=>IDBKeyRange.only(ve(i.equals)),Us=i=>{},Vs=i=>{let t=i.gte||i.gt,e=i.lte||i.lt;return t===e?IDBKeyRange.only(ve(t)):t?e?IDBKeyRange.bound(ve(t),ve(e),!!i.gt,!!i.lt):IDBKeyRange.lowerBound(ve(t),!!i.gt):IDBKeyRange.upperBound(ve(e),!!i.lt)},Ks=(i,t,e)=>{let n=i.collections[t].compounds[e.where];L(n,`Index ${e.where} does not exist on collection ${t}`);let r=Object.keys(e.match).sort((p,d)=>n.of.indexOf(p)-n.of.indexOf(d));for(let p of r)if(n.of.indexOf(p)!==r.indexOf(p))throw new Error(`Compound index ${e.where} does not have ${p} at the start of its order`);let o=r.map(p=>e.match[p]);if(r.length===n.of.length)return IDBKeyRange.only(ce(...o));let s=Ve(...o),c=Ue(...o);return IDBKeyRange.bound(s,c)};function $s(i){let t=i.startsWith,e=i.startsWith+"\uFFFF";return IDBKeyRange.bound(t,e)}function on(i,t,e){if(e)return di(e)?Vs(e):li(e)?Ns(e):Fr(e)?Us(e):ui(e)?$s(e):Ks(i,t,e)}function Si(i,t,e){return i.transaction(t,e?"readwrite":"readonly").objectStore(t)}async function sn({collection:i,index:t,context:e}){let n=Si(e.documentDb,i),r=t?.where?n.index(t.where):n,o=on(e.schema,i,t),s=t?.order==="desc"?"prev":"next",c=r.openCursor(o,s);return await new Promise((d,m)=>{c.onsuccess=()=>{let S=c.result;d(S?Z(i,S.primaryKey.toString()):null)},c.onerror=()=>{c.error?.name==="InvalidStateError"?(e.log("error","findOne query failed with InvalidStateError",c.error),d(null)):le(c.error)?d(null):m(c.error)}})}async function an({collection:i,index:t,context:e}){let n=Si(e.documentDb,i),r=t?.where?n.index(t.where):n,o=on(e.schema,i,t),s=t?.order==="desc"?"prev":"next",c=r.openCursor(o,s);return await new Promise((d,m)=>{let S=new Set;c.onsuccess=()=>{let g=c.result;g?(S.add(Z(i,g.primaryKey.toString())),g.continue()):d(Array.from(S))},c.onerror=()=>{c.error?.name==="InvalidStateError"?(e.log("error","findAll query failed with InvalidStateError",c.error),d([])):le(c.error)?d([]):m(c.error)}})}async function wt({collection:i,index:t,context:e,limit:n,offset:r}){let o=Si(e.documentDb,i),s=t?.where?o.index(t.where):o,c=on(e.schema,i,t),p=t?.order==="desc"?"prev":"next",d=s.openCursor(c,p),m=!r,S=!1,g=0;return{result:await new Promise((w,v)=>{let I=new Set;d.onsuccess=()=>{g++;let x=d.result;x?r&&!m?(x.advance(r),m=!0):(n&&I.size<n&&I.add(Z(i,x.primaryKey.toString())),n&&g>n?(S=!0,w(Array.from(I))):x.continue()):w(Array.from(I))},d.onerror=()=>{d.error?.name==="InvalidStateError"?(e.log("error","find query failed with InvalidStateError",d.error),w([])):le(d.error)?w([]):v(d.error)}}),hasNextPage:S}}async function xi(i,t,e,n){function r(c,p){let d,m,S=i.open([t,"collections"].join("_"),e);S.onupgradeneeded=async g=>{d=g.oldVersion;let C=S.transaction;m=S.result,C.abort()},S.onsuccess=g=>{c([S.result.version,S.result])},S.onblocked=g=>{n?.("Database blocked, waiting...")},S.onerror=g=>{c([d,m])}}let[o,s]=await new Promise(r);return await cn(s),o}async function cn(i){i.close(),await new Promise(t=>t())}async function Hr(i,t,e,n,r){function o(s,c){let p=i.open([t,"collections"].join("_"),e),d=!1;p.onupgradeneeded=m=>{let S=p.transaction;n(S,p.result,m),d=!0},p.onsuccess=m=>{p.result.close(),d?s():c(new Error("Database was not upgraded when a version change was expected"))},p.onerror=m=>{c(p.error||new Error("Unknown error"))},p.onblocked=m=>{r?.("Database upgrade blocked, waiting...")}}return new Promise(o)}async function Wr(i,t){typeof navigator<"u"&&navigator.locks?await navigator.locks.request(`verdant_migration_${i}`,t):await t()}async function $e(i,t,e,n){n?.("debug","Opening database",t,"at version",e);let r=await new Promise((o,s)=>{let c=i.open([t,"collections"].join("_"),e);c.onupgradeneeded=async p=>{c.transaction.abort(),n?.("error","Database upgrade needed, but not expected","Expected",e,"Got",c.result.version),s(c.error||new Error(`Migration error: database version changed unexpectedly when reading current data. Expected ${e}, got ${c.result.version}`))},c.onsuccess=p=>{o(c.result)},c.onblocked=p=>{s(new Error("Migration error: database blocked"))},c.onerror=p=>{s(new Error("Migration error: database error"))}});return r.addEventListener("versionchange",o=>{r.close()}),r}var Ze=class extends Error{constructor(e){super(e);this.message=e;this.name="MigrationPathError"}};function ln({currentVersion:i,targetVersion:t,migrations:e}){let n=Qr({currentVersion:i,targetVersion:t,migrations:e});if(!n)throw new Ze(`No migration path found from ${i} to ${t}! This is a bug. If you're seeing this, contact the developer and provide them with the full contents of this message.`);return n}function Qr({currentVersion:i,targetVersion:t,migrations:e}){if(i===t)return[];let n=e.filter(r=>r.oldSchema.version===i).sort((r,o)=>o.newSchema.version-r.newSchema.version);for(;n.length>0;){let r=n.shift();if(r.newSchema.version>t)return null;if(r.newSchema.version===t)return[r];let o=Qr({currentVersion:r.newSchema.version,targetVersion:t,migrations:e});if(o)return[r,...o]}return null}var Ii=typeof window<"u"?window.indexedDB:void 0;async function vt({version:i,indexedDB:t=Ii,migrations:e,meta:n,context:r}){if(r.schema.wip)throw new Error("Cannot open a production client with a WIP schema!");let o=await xi(t,r.namespace,i,r.log);r.log("debug","Current database version:",o,"target version:",i);let s=ln({currentVersion:o,targetVersion:i,migrations:e});return s.length>0&&(r.log("debug","Migrations to run:",s.map(c=>c.version)),await Oi({context:r,toRun:s,meta:n,indexedDB:t})),$e(t,r.namespace,i,r.log)}async function Jr({version:i,indexedDB:t=Ii,migrations:e,meta:n,context:r,wipNamespace:o}){r.log("debug","Opening WIP database",o);let s=await xi(t,o,i,r.log);if(s===i)r.log("info","WIP schema is up-to-date; not refreshing database");else{r.log("info","WIP schema is out-of-date; refreshing database");let c=ln({currentVersion:s,targetVersion:i-1,migrations:e});if(c.length>0){await Oi({context:r,toRun:c,meta:n,indexedDB:t,namespace:o});let d=await $e(t,r.namespace,i-1,r.log),m=await $e(t,o,i-1,r.log),S=new Array;for(let x=0;x<d.objectStoreNames.length;x++)S.push(d.objectStoreNames[x]);let g=d.transaction(S,"readonly"),C=S.map(x=>g.objectStore(x)),w=await Promise.all(C.map(x=>J(x.getAll()))),v=m.transaction(S,"readwrite"),I=S.map(x=>v.objectStore(x));for(let x=0;x<I.length;x++)await Promise.all(w[x].map(D=>J(I[x].put(D))))}let p=ln({currentVersion:i-1,targetVersion:i,migrations:e});p.length>0&&await Oi({context:r,toRun:p,meta:n,indexedDB:t,namespace:o})}return $e(t,o,i,r.log)}async function Oi({context:i,toRun:t,meta:e,indexedDB:n=Ii,namespace:r=i.namespace}){await Wr(r,async()=>{for(let o of t){let s;if(o.oldSchema.version===0)s=Hs({meta:e,migration:o,context:i}),await o.migrate(s);else{let d=await $e(n,r,o.oldSchema.version,i.log);s=qs({meta:e,migration:o,context:{...i,documentDb:d}});try{await o.migrate(s),await Promise.all(s.awaitables)}catch(m){throw i.log("critical",`Migration failed (${o.oldSchema.version} -> ${o.newSchema.version})`,m),m instanceof Error?m:new Error("Unknown error during migration")}await cn(d)}i.log("debug","Upgrading database",r,"to version",o.newSchema.version),await Hr(n,r,o.newSchema.version,(d,m)=>{for(let S of o.addedCollections)m.createObjectStore(S,{keyPath:o.newSchema.collections[S].primaryKey,autoIncrement:!1});for(let S of o.allCollections){let g=d.objectStore(S);for(let C of o.addedIndexes[S]||[])g.createIndex(C.name,C.name,{multiEntry:C.multiEntry});for(let C of o.removedIndexes[S]||[])g.deleteIndex(C.name)}for(let S of o.removedCollections)d.objectStore(S).clear()},i.log);let c=await Ys({meta:e,currentVersion:o.oldSchema.version,newVersion:o.newSchema.version}),p=await $e(n,r,o.newSchema.version,i.log);for(let d of o.allCollections){let S=p.transaction(d,"readwrite").objectStore(d),C=(await Ws(S)).map(D=>Z(d,`${D}`));C.push(...s.newOids.filter(D=>me(D).collection===d),...c.filter(D=>me(D).collection===d));let v=(await Promise.all(C.map(async D=>{try{let T=await e.getDocumentSnapshot(D);return[D,T]}catch(T){return i.log("error","Could not regenerate snapshot during migration for oid",D,"this document will not be preserved",T),null}}))).filter(D=>!!D).map(([D,T])=>{if(!T)return[D,void 0];let b=qt(o.newSchema.collections[d],T);return[D,b]}),x=p.transaction(d,"readwrite").objectStore(d);await Promise.all(v.map(([D,T])=>{if(T)return Js(x,T);{let{id:b}=me(D);return Qs(x,b)}}))}await cn(p),i.log("debug",`Migration of ${r} complete.`),i.log(`
|
|
8
|
+
${JSON.stringify(e)}`),new Error("Schema has changed without a version change! Any changes to your schema must be accompanied by a change in schema version and a migration routine.");await this.schema.set(e)};this.setGlobalAck=async e=>{this._closing||(await this.ackInfo.setGlobalAck(e),this.disableRebasing||await this.runRebase(e))};this.export=async()=>{let e=this.db,[n,r]=await Vr(e,["baselines","operations"]),o=await this.localReplica.get(),s=await this.schema.get();if(!s)throw new Error("Cannot export Client data before initializing");return{operations:r,baselines:n,localReplica:o,schema:s}};this.resetFrom=async e=>{let r=this.db.transaction(["baselines","operations","info"],"readwrite");await J(r.objectStore("baselines").clear()),await J(r.objectStore("operations").clear()),await J(r.objectStore("info").clear()),await this.localReplica.update({ackedLogicalTime:e.localReplica.ackedLogicalTime,lastSyncedLogicalTime:e.localReplica.lastSyncedLogicalTime},{transaction:r})};this.stats=async()=>{let e=this.db,n=await yt(e,"operations"),r=await yt(e,"baselines");return{operationsSize:n,baselinesSize:r}};this.context=n,this.schema=new nn(n.metaDb,n.schema.version),this.operations=new tn(this.db,{log:n.log}),this.baselines=new Xt(this.db,{log:n.log}),this.localReplica=new Zt(this.db),this.ackInfo=new Gt(this.db),this.messageCreator=new en(this),this.patchCreator=new Qt(()=>this.now),e&&(this.disableRebasing=e)}get db(){return this.context.metaDb}get log(){return this.context.log}get now(){return this.time.now(this.schema.currentVersion)}};var Fs=[ks,Bs,Ms,js,Ls];function rn({indexedDB:i=window.indexedDB,namespace:t,log:e,metadataVersion:n=5}){return new Promise((r,o)=>{let s=i.open(`${t}_meta`,n),a=!1;s.onupgradeneeded=async p=>{let l=s.result,m=s.transaction,x=Fs.slice(p.oldVersion);for(let y of x)await y(l,m);await new Promise((y,C)=>{m.addEventListener("complete",y),m.addEventListener("error",C)}),p.oldVersion||(a=!0)},s.onerror=()=>{console.error("Error opening database",s.error),o(s.error)},s.onsuccess=()=>{r({db:s.result,wasInitialized:a})}})}async function qr({wipNamespace:i,namespace:t,indexedDB:e,log:n,metadataVersion:r}){let o=await rn({namespace:i,indexedDB:e,log:n,metadataVersion:r});if(!o.wasInitialized)return o;n?.("debug","Beginning copy of production metadata database to WIP");let{db:s}=await rn({namespace:t,indexedDB:e,log:n,metadataVersion:r}),a=s.transaction(["baselines","operations","info"],"readonly"),[p,l,m]=await Promise.all([J(a.objectStore("baselines").getAll()),J(a.objectStore("operations").getAll()),J(a.objectStore("info").getAll())]),x=o.db.transaction(["baselines","operations","info"],"readwrite"),y=x.objectStore("baselines"),C=x.objectStore("operations"),w=x.objectStore("info");for(let S of p)y.put(S);for(let S of l)C.put(S);for(let S of m)w.put(S);return await new Promise((S,I)=>{x.oncomplete=()=>{S()},x.onerror=v=>{I(v)},x.onabort=v=>{I(v)}}),await Ke(s),n?.("debug","Finished copy of production metadata database to WIP. Copied:",p.length,"baselines,",l.length,"operations"),o}async function ks(i,t){let e=i.createObjectStore("baselines",{keyPath:"oid"}),n=i.createObjectStore("operations",{keyPath:"oid_timestamp"}),r=i.createObjectStore("info",{keyPath:"type"});e.createIndex("timestamp","timestamp"),n.createIndex("isLocal_timestamp","isLocal_timestamp"),n.createIndex("documentOid_timestamp","documentOid_timestamp")}async function Bs(i,t){let e=t.objectStore("operations");await new Promise((n,r)=>{let o=e.openCursor();o.onsuccess=()=>{let s=o.result;if(s){let{isLocal_timestamp:a,documentOid_timestamp:p,...l}=s.value;s.update({...l,l_t:a,d_t:p}),s.continue()}else n()},o.onerror=s=>{r(o.error)}}),e.deleteIndex("isLocal_timestamp"),e.deleteIndex("documentOid_timestamp"),e.createIndex("l_t","l_t",{unique:!1}),e.createIndex("o_t","o_t",{unique:!1}),e.createIndex("d_t","d_t",{unique:!1})}async function Ms(i,t){t.objectStore("operations").createIndex("timestamp","timestamp")}async function js(i,t){let e=i.createObjectStore("files",{keyPath:"id"});e.createIndex("remote","remote"),e.createIndex("deletedAt","deletedAt")}async function Ls(i,t){let e=t.objectStore("operations");await new Promise((r,o)=>{let s=e.openCursor();s.onsuccess=()=>{let a=s.result;if(a){let p=ai(a.value);p.oid_timestamp!==a.primaryKey?(a.delete(),e.put(p)):a.update(p),a.continue()}else r()},s.onerror=a=>{o(s.error)}});let n=t.objectStore("baselines");await new Promise((r,o)=>{let s=n.openCursor();s.onsuccess=()=>{let a=s.result;if(a){let p=ai(a.value);p.oid!==a.primaryKey?(a.delete(),n.put(p)):a.update(p),a.continue()}else r()},s.onerror=a=>{o(s.error)}})}var Ns=i=>IDBKeyRange.only(ve(i.equals)),Us=i=>{},Vs=i=>{let t=i.gte||i.gt,e=i.lte||i.lt;return t===e?IDBKeyRange.only(ve(t)):t?e?IDBKeyRange.bound(ve(t),ve(e),!!i.gt,!!i.lt):IDBKeyRange.lowerBound(ve(t),!!i.gt):IDBKeyRange.upperBound(ve(e),!!i.lt)},Ks=(i,t,e)=>{let n=i.collections[t].compounds[e.where];L(n,`Index ${e.where} does not exist on collection ${t}`);let r=Object.keys(e.match).sort((p,l)=>n.of.indexOf(p)-n.of.indexOf(l));for(let p of r)if(n.of.indexOf(p)!==r.indexOf(p))throw new Error(`Compound index ${e.where} does not have ${p} at the start of its order`);let o=r.map(p=>e.match[p]);if(r.length===n.of.length)return IDBKeyRange.only(ce(...o));let s=Ve(...o),a=Ue(...o);return IDBKeyRange.bound(s,a)};function $s(i){let t=i.startsWith,e=i.startsWith+"\uFFFF";return IDBKeyRange.bound(t,e)}function on(i,t,e){if(e)return di(e)?Vs(e):li(e)?Ns(e):Fr(e)?Us(e):ui(e)?$s(e):Ks(i,t,e)}function Si(i,t,e){return i.transaction(t,e?"readwrite":"readonly").objectStore(t)}async function sn({collection:i,index:t,context:e}){let n=Si(e.documentDb,i),r=t?.where?n.index(t.where):n,o=on(e.schema,i,t),s=t?.order==="desc"?"prev":"next",a=r.openCursor(o,s);return await new Promise((l,m)=>{a.onsuccess=()=>{let x=a.result;l(x?Z(i,x.primaryKey.toString()):null)},a.onerror=()=>{a.error?.name==="InvalidStateError"?(e.log("error","findOne query failed with InvalidStateError",a.error),l(null)):le(a.error)?l(null):m(a.error)}})}async function an({collection:i,index:t,context:e}){let n=Si(e.documentDb,i),r=t?.where?n.index(t.where):n,o=on(e.schema,i,t),s=t?.order==="desc"?"prev":"next",a=r.openCursor(o,s);return await new Promise((l,m)=>{let x=new Set;a.onsuccess=()=>{let y=a.result;y?(x.add(Z(i,y.primaryKey.toString())),y.continue()):l(Array.from(x))},a.onerror=()=>{a.error?.name==="InvalidStateError"?(e.log("error","findAll query failed with InvalidStateError",a.error),l([])):le(a.error)?l([]):m(a.error)}})}async function wt({collection:i,index:t,context:e,limit:n,offset:r}){let o=Si(e.documentDb,i),s=t?.where?o.index(t.where):o,a=on(e.schema,i,t),p=t?.order==="desc"?"prev":"next",l=s.openCursor(a,p),m=!r,x=!1,y=0;return{result:await new Promise((w,S)=>{let I=new Set;l.onsuccess=()=>{y++;let v=l.result;v?r&&!m?(v.advance(r),m=!0):(n&&I.size<n&&I.add(Z(i,v.primaryKey.toString())),n&&y>n?(x=!0,w(Array.from(I))):v.continue()):w(Array.from(I))},l.onerror=()=>{l.error?.name==="InvalidStateError"?(e.log("error","find query failed with InvalidStateError",l.error),w([])):le(l.error)?w([]):S(l.error)}}),hasNextPage:x}}async function xi(i,t,e,n){function r(a,p){let l,m,x=i.open([t,"collections"].join("_"),e);x.onupgradeneeded=async y=>{l=y.oldVersion;let C=x.transaction;m=x.result,C.abort()},x.onsuccess=y=>{a([x.result.version,x.result])},x.onblocked=y=>{n?.("Database blocked, waiting...")},x.onerror=y=>{a([l,m])}}let[o,s]=await new Promise(r);return await cn(s),o}async function cn(i){i.close(),await new Promise(t=>t())}async function Hr(i,t,e,n,r){function o(s,a){let p=i.open([t,"collections"].join("_"),e),l=!1;p.onupgradeneeded=m=>{let x=p.transaction;n(x,p.result,m),l=!0},p.onsuccess=m=>{p.result.close(),l?s():a(new Error("Database was not upgraded when a version change was expected"))},p.onerror=m=>{a(p.error||new Error("Unknown error"))},p.onblocked=m=>{r?.("Database upgrade blocked, waiting...")}}return new Promise(o)}async function Wr(i,t){typeof navigator<"u"&&navigator.locks?await navigator.locks.request(`verdant_migration_${i}`,t):await t()}async function $e(i,t,e,n){n?.("debug","Opening database",t,"at version",e);let r=await new Promise((o,s)=>{let a=i.open([t,"collections"].join("_"),e);a.onupgradeneeded=async p=>{a.transaction.abort(),n?.("error","Database upgrade needed, but not expected","Expected",e,"Got",a.result.version),s(a.error||new Error(`Migration error: database version changed unexpectedly when reading current data. Expected ${e}, got ${a.result.version}`))},a.onsuccess=p=>{o(a.result)},a.onblocked=p=>{s(new Error("Migration error: database blocked"))},a.onerror=p=>{s(new Error("Migration error: database error"))}});return r.addEventListener("versionchange",o=>{r.close()}),r}var Ze=class extends Error{constructor(e){super(e);this.message=e;this.name="MigrationPathError"}};function ln({currentVersion:i,targetVersion:t,migrations:e}){let n=Qr({currentVersion:i,targetVersion:t,migrations:e});if(!n)throw new Ze(`No migration path found from ${i} to ${t}! This is a bug. If you're seeing this, contact the developer and provide them with the full contents of this message.`);return n}function Qr({currentVersion:i,targetVersion:t,migrations:e}){if(i===t)return[];let n=e.filter(r=>r.oldSchema.version===i).sort((r,o)=>o.newSchema.version-r.newSchema.version);for(;n.length>0;){let r=n.shift();if(r.newSchema.version>t)return null;if(r.newSchema.version===t)return[r];let o=Qr({currentVersion:r.newSchema.version,targetVersion:t,migrations:e});if(o)return[r,...o]}return null}var Ii=typeof window<"u"?window.indexedDB:void 0;async function vt({version:i,indexedDB:t=Ii,migrations:e,meta:n,context:r}){if(r.schema.wip)throw new Error("Cannot open a production client with a WIP schema!");let o=await xi(t,r.namespace,i,r.log);r.log("debug","Current database version:",o,"target version:",i);let s=ln({currentVersion:o,targetVersion:i,migrations:e});return s.length>0&&(r.log("debug","Migrations to run:",s.map(a=>a.version)),await Oi({context:r,toRun:s,meta:n,indexedDB:t})),$e(t,r.namespace,i,r.log)}async function Jr({version:i,indexedDB:t=Ii,migrations:e,meta:n,context:r,wipNamespace:o}){r.log("debug","Opening WIP database",o);let s=await xi(t,o,i,r.log);if(s===i)r.log("info","WIP schema is up-to-date; not refreshing database");else{r.log("info","WIP schema is out-of-date; refreshing database");let a=ln({currentVersion:s,targetVersion:i-1,migrations:e});if(a.length>0){await Oi({context:r,toRun:a,meta:n,indexedDB:t,namespace:o});let l=await $e(t,r.namespace,i-1,r.log),m=await $e(t,o,i-1,r.log),x=new Array;for(let v=0;v<l.objectStoreNames.length;v++)x.push(l.objectStoreNames[v]);let y=l.transaction(x,"readonly"),C=x.map(v=>y.objectStore(v)),w=await Promise.all(C.map(v=>J(v.getAll()))),S=m.transaction(x,"readwrite"),I=x.map(v=>S.objectStore(v));for(let v=0;v<I.length;v++)await Promise.all(w[v].map(D=>J(I[v].put(D))))}let p=ln({currentVersion:i-1,targetVersion:i,migrations:e});p.length>0&&await Oi({context:r,toRun:p,meta:n,indexedDB:t,namespace:o})}return $e(t,o,i,r.log)}async function Oi({context:i,toRun:t,meta:e,indexedDB:n=Ii,namespace:r=i.namespace}){await Wr(r,async()=>{for(let o of t){let s;if(o.oldSchema.version===0)s=Hs({meta:e,migration:o,context:i}),await o.migrate(s);else{let l=await $e(n,r,o.oldSchema.version,i.log);s=qs({meta:e,migration:o,context:{...i,documentDb:l}});try{await o.migrate(s),await Promise.all(s.awaitables)}catch(m){throw i.log("critical",`Migration failed (${o.oldSchema.version} -> ${o.newSchema.version})`,m),m instanceof Error?m:new Error("Unknown error during migration")}await cn(l)}i.log("debug","Upgrading database",r,"to version",o.newSchema.version),await Hr(n,r,o.newSchema.version,(l,m)=>{for(let x of o.addedCollections)m.createObjectStore(x,{keyPath:o.newSchema.collections[x].primaryKey,autoIncrement:!1});for(let x of o.allCollections){let y=l.objectStore(x);for(let C of o.addedIndexes[x]||[])y.createIndex(C.name,C.name,{multiEntry:C.multiEntry});for(let C of o.removedIndexes[x]||[])y.deleteIndex(C.name)}for(let x of o.removedCollections)l.objectStore(x).clear()},i.log);let a=await Ys({meta:e,currentVersion:o.oldSchema.version,newVersion:o.newSchema.version}),p=await $e(n,r,o.newSchema.version,i.log);for(let l of o.allCollections){let x=p.transaction(l,"readwrite").objectStore(l),C=(await Ws(x)).map(D=>Z(l,`${D}`));C.push(...s.newOids.filter(D=>me(D).collection===l),...a.filter(D=>me(D).collection===l));let S=(await Promise.all(C.map(async D=>{try{let R=await e.getDocumentSnapshot(D);return[D,R]}catch(R){return i.log("error","Could not regenerate snapshot during migration for oid",D,"this document will not be preserved",R),null}}))).filter(D=>!!D).map(([D,R])=>{if(!R)return[D,void 0];let b=qt(o.newSchema.collections[l],R);return[D,b]}),v=p.transaction(l,"readwrite").objectStore(l);await Promise.all(S.map(([D,R])=>{if(R)return Js(v,R);{let{id:b}=me(D);return Qs(v,b)}}))}await cn(p),i.log("debug",`Migration of ${r} complete.`),i.log(`
|
|
9
9
|
\u2B06\uFE0F v${o.newSchema.version} Migration complete. Here's the rundown:
|
|
10
10
|
- Added collections: ${o.addedCollections.join(", ")}
|
|
11
11
|
- Removed collections: ${o.removedCollections.join(", ")}
|
|
12
12
|
- Changed collections: ${o.changedCollections.join(", ")}
|
|
13
|
-
- New indexes: ${Object.keys(o.addedIndexes).map(
|
|
14
|
-
- Removed indexes: ${Object.keys(o.removedIndexes).map(
|
|
15
|
-
`)}})}function Yr({migration:i,meta:t,getMigrationNow:e,newOids:n}){return i.allCollections.reduce((r,o)=>(r[o]={put:async s=>{Pe(i.newSchema.collections[o],s);let c=s[i.newSchema.collections[o].primaryKey],p=Z(o,c);return n.push(p),await t.insertLocalOperations(Re(s,p,e)),s},delete:async s=>{let c=Z(o,s),p=await t.getAllDocumentRelatedOids(c);return t.insertLocalOperations(p.map(d=>({oid:d,timestamp:e(),data:{op:"delete"}})))}},r),{})}function zs({migration:i,context:t,meta:e}){return i.oldCollections.reduce((n,r)=>(n[r]={get:async o=>{let s=Z(r,o);return await e.getDocumentSnapshot(s,{to:e.time.now(i.oldSchema.version)})},findOne:async o=>{let s=await sn({collection:r,index:o,context:t});return s?await e.getDocumentSnapshot(s,{to:e.time.now(i.oldSchema.version)}):null},findAll:async o=>{let s=await an({collection:r,index:o,context:t});return await Promise.all(s.map(p=>e.getDocumentSnapshot(p,{to:e.time.now(i.oldSchema.version)})))}},n),{})}function qs({meta:i,migration:t,context:e}){function n(){return i.time.zero(t.version)}let r=new Array,o=zs({migration:t,context:e,meta:i}),s=Yr({migration:t,getMigrationNow:n,newOids:r,meta:i}),c=async m=>{let S=await i.getAllCollectionRelatedOids(m);return i.insertLocalOperations(S.map(g=>({oid:g,timestamp:n(),data:{op:"delete"}})))},p=new Array;return{log:e.log,newOids:r,deleteCollection:c,migrate:async(m,S)=>{let g=await o[m].findAll();await Promise.all(g.filter(Boolean).map(async C=>{let w=ne(C);L(!!w,`Document is missing an OID: ${JSON.stringify(C)}`);let v=ae(C),I=await S(C);if(I){ft(v),ft(I),Ge(I);let x=ht(v,I,n,void 0,[],{mergeUnknownObjects:!0});x.length>0&&await i.insertLocalOperations(x)}}))},queries:o,mutations:s,awaitables:p}}function Hs({meta:i,migration:t,context:e}){function n(){return i.time.zero(t.version)}let r=new Array,o=new Proxy({},{get(){throw new Error("Queries are not available in initial migrations; there is no database yet!")}}),s=Yr({migration:t,getMigrationNow:n,newOids:r,meta:i});return{log:e.log,newOids:r,deleteCollection:()=>{throw new Error("Calling deleteCollection() in initial migrations is not supported! Use initial migrations to seed initial data using mutations.")},migrate:()=>{throw new Error("Calling migrate() in initial migrations is not supported! Use initial migrations to seed initial data using mutations.")},queries:o,mutations:s,awaitables:[]}}async function Ws(i){return new Promise((t,e)=>{let n=i.getAllKeys();n.onsuccess=r=>{t(n.result)},n.onerror=r=>{e(n.error)}})}async function Qs(i,t){let e=i.delete(t);return new Promise((n,r)=>{e.onsuccess=o=>{n()},e.onerror=o=>{r(e.error)}})}async function Js(i,t){let e=i.put(t);return new Promise((n,r)=>{e.onsuccess=o=>{n()},e.onerror=o=>{r(e.error)}})}async function Ys({meta:i,currentVersion:t,newVersion:e}){let n=[];return await i.operations.iterateOverAllOperations(r=>n.push(r),{from:i.time.zero(t+1)}),Array.from(new Set(n.map(r=>$(r.oid))))}var St=class extends U{constructor(){super(...arguments);this._undoable=[];this._undone=[];this.undo=async()=>{let e=this._undoable.pop();if(e){let n=await e();return n&&this._undone.push(n),this.emit("change"),!0}return!1};this.redo=async()=>{let e=this._undone.pop();if(e){let n=await e();return n&&this._undoable.push(n),this.emit("change"),!0}return!1};this.addUndo=e=>{this._undoable.push(e),this._undone=[],this.emit("change")};this.addRedo=e=>{this._undone.push(e),this.emit("change")};this.clear=()=>{this._undoable=[],this._undone=[],this.emit("change")}}get canUndo(){return this._undoable.length>0}get canRedo(){return this._undone.length>0}};var dn=class{constructor(t,e,n){this.meta=t;this.schema=e;this.entities=n;this.getOid=(t,e)=>{let n=this.schema.collections[t].primaryKey,r=e[n];return L(r,`Document must have a primary key: ${n.toString()} (got: ${JSON.stringify(e)})`),Z(t,r)};this.addDefaults=(t,e)=>{let n=this.schema.collections[t];return Pe(n,e)};this.create=(t,e,n={})=>{let r=this.addDefaults(t,e),o=this.getOid(t,r);return this.entities.create(r,o,n)};this.delete=async(t,e,n={})=>{let r=Z(t,e);return this.entities.delete(r,n)};this.deleteAll=async(t,e={})=>this.entities.deleteAll(t.map(([n,r])=>Z(n,r)),e);this.deleteAllFromCollection=async(t,e,n={})=>this.entities.deleteAll(e.map(r=>Z(t,r)),n)}};var et=Symbol("entity-file-update"),xt=Symbol("entity-file-mark-failed"),Gs,Xs,de=class extends U{constructor(e,{downloadRemote:n=!1}={}){super();this.id=e;this._objectUrl=null;this._fileData=null;this._loading=!0;this._failed=!1;this._downloadRemote=!1;this[Gs]=e=>{this._loading=!1,this._failed=!1,this._fileData=e,e.file&&(this._objectUrl&&URL.revokeObjectURL(this._objectUrl),this._objectUrl=URL.createObjectURL(e.file)),this.emit("change")};this[Xs]=()=>{this._failed=!0,this._loading=!1,this.emit("change")};this.destroy=()=>{this._objectUrl&&URL.revokeObjectURL(this._objectUrl),this.dispose()};this._downloadRemote=n}static{Gs=et,Xs=xt}get downloadRemote(){return this._downloadRemote}get url(){return this.loading?null:this._objectUrl?this._objectUrl:this._fileData?.url??null}get name(){return this._fileData?.name??null}get type(){return this._fileData?.type??null}get loading(){return this._loading}get failed(){return this._failed}getSnapshot(){return{id:this.id,url:this.loading||this.failed?void 0:this.url}}};var Gr=Qe(at(),1);function Zs(i){return{id:(0,Gr.default)(),file:i,url:void 0,remote:!1,name:i.name,type:i.type}}function Di(i){return i instanceof File||typeof Blob<"u"&&i instanceof Blob}function tt(i,t){if(typeof window<"u"&&Di(i)){let e=Zs(i);return t(e),Mt(e.id)}if(Array.isArray(i)){for(let e=0;e<i.length;e++)i[e]=tt(i[e],t);return i}if(typeof i=="object"){for(let e in i)i[e]=tt(i[e],t);return i}return i}function Xr(i){return new Promise((t,e)=>{let n=new FileReader;n.onload=()=>{t(n.result)},n.onerror=e,n.readAsArrayBuffer(i)})}var un=class extends se{constructor(){super(...arguments);this.addFile=async(e,{transaction:n,downloadRemote:r=!1}={})=>{let o=e.file?await Xr(e.file):void 0;if(!o&&r&&e.url)try{o=await fetch(e.url,{method:"GET",credentials:"include"}).then(s=>s.arrayBuffer())}catch(s){console.error("Failed to download file to cache it locally. The file will still be available using its URL. Check the file server's CORS configuration.",s)}return this.run("files",s=>s.put({id:e.id,remote:e.remote?"true":"false",deletedAt:null,name:e.name,type:e.type,url:e.url,buffer:o}),{mode:"readwrite",transaction:n})};this.hydrateFileData=e=>{e.remote=e.remote==="true";let n=e.buffer;return delete e.buffer,e.file=n?ea(n,e.type):void 0,e};this.markUploaded=async(e,{transaction:n}={})=>{let r=await this.getFileRaw(e,{transaction:n});if(!r)throw new Error("File is not in local database");return this.run("files",o=>o.put({...r,remote:"true"}),{mode:"readwrite",transaction:n})};this.getFileRaw=async(e,{transaction:n}={})=>{let r=await this.run("files",o=>o.get(e),{mode:"readonly",transaction:n});if(r)return r};this.getFile=async(e,{transaction:n}={})=>{let r=await this.getFileRaw(e,{transaction:n});if(r)return this.hydrateFileData(r)};this.markPendingDelete=async(e,{transaction:n}={})=>{let r=await this.getFileRaw(e,{transaction:n});if(!r)throw new Error("File is not in local database");return this.run("files",o=>o.put({...r,deletedAt:Date.now()}),{mode:"readwrite",transaction:n})};this.listUnsynced=async()=>(await this.run("files",n=>n.index("remote").getAll("false"),{mode:"readonly"})).map(this.hydrateFileData);this.iterateOverPendingDelete=(e,n)=>this.iterate("files",r=>r.index("deletedAt").openCursor(IDBKeyRange.lowerBound(0,!0)),(r,o)=>{e(this.hydrateFileData(r),o)},{mode:"readwrite",transaction:n})}deleteFile(e,{transaction:n}={}){return this.run("files",r=>r.delete(e),{mode:"readwrite",transaction:n})}};function ea(i,t){return new Blob([i],{type:t})}function ta(i){return i.deletedAt!==null&&i.deletedAt<Date.now()-1e3*60*24*3}var fn=class{constructor({db:t,sync:e,context:n,meta:r,config:o={}}){this.files=new Map;this.add=async t=>{let e=t;if(e.remote=!1,this.files.has(e.id))this.files.get(e.id)[et](e);else{let n=new de(e.id);n[et](e),this.files.set(e.id,n)}await this.storage.addFile(e),e.file&&await this.uploadFile(e,1)};this.uploadFile=async(t,e=0)=>{let n=await this.sync.uploadFile(t);n.success?await this.storage.markUploaded(t.id):n.retry&&e<5?(this.context.log("error","Error uploading file, retrying..."),setTimeout(this.uploadFile,1e3,t,e+1)):this.context.log("error","Failed to upload file. Not retrying until next sync.")};this.get=(t,e)=>{if(this.files.has(t))return this.files.get(t);let n=new de(t,e);return this.files.set(t,n),this.load(n),n};this.load=async(t,e=0)=>{if(e>5){this.context.log("error","Failed to load file after 5 retries"),t[xt]();return}let n=await this.storage.getFile(t.id);if(n)t[et](n);else try{let r=await this.sync.getFile(t.id);r.success?(t[et](r.data),await this.storage.addFile(r.data,{downloadRemote:t.downloadRemote})):(this.context.log("error","Failed to load file",r),t[xt](),r.retry&&setTimeout(this.load,1e3,t,e+1))}catch(r){this.context.log("error","Failed to load file",r),t[xt](),setTimeout(this.load,1e3,t,e+1)}};this.listUnsynced=async()=>this.storage.listUnsynced();this.onOnlineChange=async t=>{if(t){let e=await this.listUnsynced();await Promise.all(e.map(this.uploadFile))}};this.tryCleanupDeletedFiles=async()=>{let t=0,e=0;await this.storage.iterateOverPendingDelete((n,r)=>{this.config.canCleanupDeletedFile(n)?(t++,r.delete(n.id)):e++}),this.context.log("info",`Cleaned up ${t} files, skipped ${e} files`)};this.handleFileRefsDeleted=async t=>{let e=this.storage.createTransaction(["files"],{mode:"readwrite"});await Promise.all(t.map(async n=>{try{await this.storage.markPendingDelete(n.id,{transaction:e})}catch(r){this.context.log("error","Failed to mark file for deletion",r)}})),this.context.log("info",`Marked ${t.length} files as pending delete`)};this.storage=new un(t),this.sync=e,this.context=n,this.meta=r,this.config={canCleanupDeletedFile:ta,...o},this.sync.subscribe("onlineChange",this.onOnlineChange),this.meta.subscribe("filesDeleted",this.handleFileRefsDeleted),this.tryCleanupDeletedFiles()}};var pn=class{constructor({initial:t}={}){this.cache=new Map;this.get=t=>{if(this.cache.has(t.oid))return this.cache.get(t.oid);let e=new ue(t);return this.cache.set(t.oid,e),e};this.has=t=>this.cache.has(t);this.getFile=(t,e)=>{if(this.cache.has(t))return this.cache.get(t);let n=new de(t,e);return this.cache.set(t,n),n};this.getCached=t=>this.cache.get(t);if(t)for(let e of t)this.cache.set(e.oid,e)}};var ue=class i extends U{constructor({oid:e,schema:n,entityFamily:r,parent:o,ctx:s,metadataFamily:c,readonlyKeys:p,files:d,patchCreator:m,events:S}){super();this.fieldPath=[];this._viewData=void 0;this.validationError=void 0;this.cachedDeepUpdatedAt=null;this.wasDeletedLastChange=!1;this.cachedView=void 0;this.onAdd=(e,n)=>{n.oid===this.oid&&this.addConfirmedData(n)};this.onReplace=(e,n)=>{n.oid===this.oid&&this.replaceAllData(n)};this.onResetAll=()=>{this.resetAllData()};this.childIsNull=e=>{if(e instanceof i){let n=e.view;return n==null}return e==null};this.validate=Lr(()=>(this.validationError=Fe({field:this.schema,value:this.rawView,fieldPath:this.fieldPath,depth:1})??void 0,this.validationError),()=>[this.viewData]);this.viewWithMappedChildren=e=>{let n=this.view;if(!n)return null;if(Array.isArray(n)){let r=n.map(o=>o instanceof i||o instanceof de?e(o):o);return K(r,this.oid),r}else{let r=Object.entries(n).reduce((o,[s,c])=>(c instanceof i||c instanceof de?o[s]=e(c):o[s]=c,o),{});return K(r,this.oid),r}};this.getSnapshot=()=>this.viewWithMappedChildren(e=>e.getSnapshot());this.addPendingOperations=e=>{this.ctx.log("debug","Entity: adding pending operations",this.oid);let n=this.metadataFamily.addPendingData(e);for(let r of n)this.change(r)};this.addConfirmedData=e=>{this.ctx.log("debug","Entity: adding confirmed data",this.oid);let n=this.metadataFamily.addConfirmedData(e);for(let r of n)this.change(r)};this.replaceAllData=e=>{this.ctx.log("debug","Entity: replacing all data",this.oid);let n=this.metadataFamily.replaceAllData(e);for(let r of n)this.change(r)};this.resetAllData=()=>{this.ctx.log("debug","Entity: resetting all data",this.oid),this.cachedDeepUpdatedAt=null,this.cachedView=void 0,this._viewData=void 0;let e=this.metadataFamily.replaceAllData({});for(let n of e)this.change(n)};this.change=e=>{if(e.oid===this.oid)this._viewData=void 0,this.cachedView=void 0,this.deepChange(this,e),this.ctx.log("Emitting change event",this.oid),this.emit("change",{isLocal:e.isLocal}),this.parent||(this.deleted&&!this.wasDeletedLastChange?(this.ctx.log("debug","Entity deleted",this.oid),this.emit("delete",{isLocal:e.isLocal}),this.wasDeletedLastChange=!0):!this.deleted&&this.wasDeletedLastChange&&(this.ctx.log("debug","Entity restored",this.oid),this.emit("restore",{isLocal:e.isLocal}),this.wasDeletedLastChange=!1));else{let n=this.entityFamily.getCached(e.oid);n&&n instanceof i&&n.change(e)}};this.deepChange=(e,n)=>{this.cachedDeepUpdatedAt=null,this.cachedView=void 0,this.ctx.log("debug","Deep change detected at",this.oid,"reset cached view"),this.ctx.log("debug","Emitting deep change event",this.oid),this.emit("changeDeep",e,n),this.parent?.deepChange(e,n)};this.getChild=(e,n)=>{let r=Ne(this.schema,e);if(!r)throw new Error(`No schema for key ${String(e)} in ${JSON.stringify(this.schema)}`);return this.entityFamily.get({oid:n,schema:r,entityFamily:this.entityFamily,metadataFamily:this.metadataFamily,parent:this,ctx:this.ctx,files:this.files,fieldPath:[...this.fieldPath,e],patchCreator:this.patchCreator,events:this.events})};this.get=e=>{Zr(e);let n=this.rawView;if(!n)throw new Error(`Cannot access data at key ${e} on deleted entity ${this.oid}`);let r=n[e],o=Ne(this.schema,e);if(!o)throw new Error(`No schema for key ${String(e)} in ${JSON.stringify(this.schema)}`);if(Q(r))if(be(r)){if(o.type!=="file")throw new Error(`Expected file schema for key ${String(e)}, got ${o.type}`);let s=this.files.get(r.id,{downloadRemote:!!o.downloadRemote});return s.subscribe("change",()=>{this.deepChange(this,{isLocal:!1,oid:this.oid})}),s}else return this.getChild(e,r.id);else return Fe({field:o,value:r,fieldPath:[...this.fieldPath,e],depth:1,requireDefaults:!0})?Ce(o)?pi(o):we(o)?null:void 0:r};this.processInputValue=(e,n)=>{if(this.readonlyKeys.includes(n))throw new Error(`Cannot set readonly key ${n.toString()}`);Di(e)||(e=ae(e,!1));let r=Ne(this.schema,n);if(r){Le(e,r);let o=Fe({field:r,value:e,fieldPath:[...this.fieldPath,n]});if(o)throw new Error(o.message)}return tt(e,this.files.add)};this.getDeleteMode=e=>{if(this.readonlyKeys.includes(e))return!1;if(this.schema.type==="any"||this.schema.type==="map")return"delete";if(this.schema.type==="object"){let n=this.schema.properties[e];if(!n||n.type==="any")return"delete";if(n.type==="map")return!1;if(n.nullable)return"null"}return!1};this.getItemRefValue=e=>{if(e instanceof i)return he(e.oid);if(e instanceof de)return Mt(e.id);if(typeof e=="object"){let n=pe(e);if(!n||!this.entityFamily.has(n))throw new Error(`Cannot move object ${JSON.stringify(e)} which does not exist in this list`);return he(n)}else return e};this.set=(e,n)=>{Zr(e),this.addPendingOperations(this.patchCreator.createSet(this.oid,e,this.processInputValue(n,e)))};this.getAll=()=>this.view;this.delete=e=>{if(this.isList)na(e),this.addPendingOperations(this.patchCreator.createListDelete(this.oid,e));else{let n=this.getDeleteMode(e);if(!n)throw new Error(`Cannot delete key ${e.toString()} - the property is not marked as optional in the schema.`);n==="delete"?this.addPendingOperations(this.patchCreator.createRemove(this.oid,e)):this.addPendingOperations(this.patchCreator.createSet(this.oid,e,null))}};this.keys=()=>this.view?Object.keys(this.view):[];this.entries=()=>this.view?Object.entries(this.view):[];this.values=()=>this.view?Object.values(this.view):[];this.update=(e,{merge:n=!0,replaceSubObjects:r=!1}={})=>{if(!n&&this.schema.type!=="any"&&this.schema.type!=="map")throw new Error('Cannot use .update without merge if the field has a strict schema type. merge: false is only available on "any" or "map" types.');let o={};K(o,this.oid);for(let[s,c]of Object.entries(e)){if(this.readonlyKeys.includes(s))throw new Error(`Cannot set readonly key ${s.toString()}`);let p=Ne(this.schema,s);p&&Le(c,p),o[s]=this.processInputValue(c,s)}this.addPendingOperations(this.patchCreator.createDiff(this.getSnapshot(),o,{mergeUnknownObjects:!r,defaultUndefined:n}))};this.push=e=>{this.addPendingOperations(this.patchCreator.createListPush(this.oid,this.processInputValue(e,this.view.length)))};this.insert=(e,n)=>{this.addPendingOperations(this.patchCreator.createListInsert(this.oid,e,this.processInputValue(n,e)))};this.move=(e,n)=>{this.addPendingOperations(this.patchCreator.createListMoveByIndex(this.oid,e,n))};this.moveItem=(e,n)=>{let r=this.getItemRefValue(e);if(Q(r))this.addPendingOperations(this.patchCreator.createListMoveByRef(this.oid,r,n));else{let o=this.view.indexOf(e);if(o===-1)throw new Error(`Cannot move item ${JSON.stringify(e)} which does not exist in this list`);this.move(o,n)}};this.add=e=>{this.addPendingOperations(this.patchCreator.createListAdd(this.oid,this.processInputValue(e,this.view.length)))};this.removeAll=e=>{this.addPendingOperations(this.patchCreator.createListRemove(this.oid,this.getItemRefValue(e)))};this.removeFirst=e=>{this.addPendingOperations(this.patchCreator.createListRemove(this.oid,this.getItemRefValue(e),"first"))};this.removeLast=e=>{this.addPendingOperations(this.patchCreator.createListRemove(this.oid,this.getItemRefValue(e),"last"))};this.map=e=>this.view.map(e);this.filter=e=>this.view.filter(e);this.has=e=>{if(!this.isList)throw new Error("has() is only available on list entities");let n=this.getItemRefValue(e);return Q(n)?this.view.some(r=>{if(Q(r))return Ye(r,n)}):this.view.includes(e)};this.forEach=e=>{this.view.forEach(e)};this.some=e=>this.view.some(e);this.every=e=>this.view.every(e);this.find=e=>this.view.find(e);this.includes=this.has;this.__getViewData__=(e,n)=>this.metadataFamily.get(e).computeView(n==="confirmed");this.__getFamilyOids__=()=>this.metadataFamily.getAllOids();L(!!e,"oid is required"),this.oid=e,this.readonlyKeys=p||[],this.ctx=s,this.files=d,this.schema=n,this.entityFamily=r||new pn({initial:[this]}),this.patchCreator=m,this.metadataFamily=c,this.events=S,this.parent=o,this.parent||(S.add.attach(this.onAdd),S.replace.attach(this.onReplace),S.resetAll.attach(this.onResetAll))}get metadata(){return this.metadataFamily.get(this.oid)}get viewData(){return this._viewData===void 0&&(this._viewData=this.metadata.computeView(),this.validate()),this._viewData}get rawView(){return this.viewData.view}get view(){if(this.cachedView!==void 0)return this.cachedView;if(this.viewData.deleted)return null;let e=this.rawView;if(!e&&!we(this.schema)||this.schema.type==="array"&&!Array.isArray(e)||(this.schema.type==="object"||this.schema.type==="map")&&!V(e))return Ce(this.schema)?pi(this.schema):null;if(this.cachedView=this.isList?[]:{},K(this.cachedView,this.oid),Array.isArray(e)){let r=Ne(this.schema,0);if(!r)this.ctx.log("error","No child field schema for list entity.",this.oid);else for(let o=0;o<e.length;o++){let s=this.get(o);this.childIsNull(s)&&!we(r)?this.ctx.log("error","Child missing in non-nullable field",this.oid,"index:",o):this.cachedView.push(s)}}else if(V(e)){let r=this.schema.type==="object"?Object.keys(this.schema.properties):Object.keys(e);for(let o of r){let s=Ne(this.schema,o);if(!s){this.ctx.log("error","No child field schema for object entity at key",o),this.schema.type==="map"?this.cachedView={}:this.cachedView=null;break}let c=this.get(o);if(this.childIsNull(c)&&!we(s)){if(this.ctx.log("error","Child entity is missing for non-nullable field",this.oid,"key:",o),this.schema.type!=="map"){this.cachedView=null;break}}else this.cachedView[o]=c}}return this.cachedView}get uid(){return this.oid}get deleted(){return this.viewData.deleted||this.view===null}get invalid(){return!!this.validate()}get isList(){return this.schema.type==="array"||Array.isArray(this.viewData.view)}get updatedAt(){return this.viewData.updatedAt}get deepUpdatedAt(){if(this.cachedDeepUpdatedAt)return this.cachedDeepUpdatedAt;let e=this.updatedAt;return this.isList?this.forEach(n=>{if(n instanceof i){let r=n.deepUpdatedAt;r&&(!e||r>e)&&(e=r)}}):this.values().forEach(n=>{if(n instanceof i){let r=n.deepUpdatedAt;r&&(!e||r>e)&&(e=r)}}),this.cachedDeepUpdatedAt=e,e}get isOutdatedVersion(){return this.parent?this.parent.isOutdatedVersion:this.viewData.fromOlderVersion}get length(){return this.view.length}[Symbol.iterator](){let e=0,n=this.view?.length;return{next:()=>e<n?{value:this.get(e++),done:!1}:{value:void 0,done:!0}}}};function Zr(i){if(typeof i=="symbol")throw new Error("Symbol keys aren't supported")}function na(i){if(typeof i!="number")throw new Error("Only number keys are supported in list entities")}var _i=class{constructor({oid:t,ctx:e,confirmedOperations:n,pendingOperations:r,baseline:o}){this.baseline=null;this.confirmedOperations=[];this.pendingOperations=[];this.computeView=(t=!1)=>{let e=ae(this.baseline?.snapshot??void 0),n=this.baseline?.timestamp??null,r=this.applyOperations(e,!e,this.confirmedOperations,n,n);r.futureSeen&&this.ctx.globalEvents.emit("futureSeen",r.futureSeen);let o=t?r:this.applyOperations(r.view,r.deleted,this.pendingOperations,r.latestTimestamp,null);o.view&&K(o.view,this.oid);let s=!!r.latestTimestamp&&Gn(r.latestTimestamp,this.ctx.getNow())<0,c=!this.baseline&&!this.pendingOperations.length&&!this.confirmedOperations.length;c&&this.ctx.log("warn",`Tried to load Entity ${this.oid} with no data`);let p=o.latestTimestamp??r.latestTimestamp??n,d=p?Xn(p):0;if(!o.view&&!o.deleted&&!c){this.ctx.log("warn",`Entity ${this.oid} has no view, no deleted flag, and not empty`);debugger}return{view:o.view??void 0,deleted:o.deleted,empty:c,fromOlderVersion:s,updatedAt:d}};this.addBaseline=t=>{if(!(this.baseline&&this.baseline.timestamp>=t.timestamp))for(this.baseline=t;this.confirmedOperations[0]?.timestamp<t.timestamp;)this.confirmedOperations.shift()};this.addConfirmedOperations=t=>{let e=0;for(let n of t){let r=this.confirmedOperations.findIndex(s=>s.timestamp>=n.timestamp);r!==-1?this.confirmedOperations[r].timestamp!==n.timestamp&&(this.confirmedOperations.splice(r,0,n),e++):(this.confirmedOperations.push(n),e++);let o=this.pendingOperations.length;this.pendingOperations=this.pendingOperations.filter(s=>n.timestamp!==s.timestamp),e-=o-this.pendingOperations.length}return e};this.addPendingOperation=t=>{this.pendingOperations.push(t)};this.applyOperations=(t,e,n,r,o)=>{let s,c=this.ctx.getNow();for(let p of n)if(!(o&&p.timestamp<=o)){if(Gn(p.timestamp,c)>0){s=p.timestamp;continue}p.data.op==="delete"?e=!0:(t=je(t,p.data),p.data.op==="initialize"&&(e=!1)),(!r||p.timestamp>r)&&(r=p.timestamp)}return{view:t,latestTimestamp:r??null,deleted:e,futureSeen:s}};L(t,"oid is required"),this.ctx=e,this.oid=t,n&&(this.confirmedOperations=n),r&&(this.pendingOperations=r),o&&(this.baseline=o)}},hn=class{constructor({ctx:t,onPendingOperations:e,rootOid:n}){this.entities=new Map;this.get=t=>(L(t,"oid is required"),this.entities.has(t)||this.entities.set(t,new _i({oid:t,ctx:this.ctx})),this.entities.get(t));this.getAllOids=()=>Array.from(this.entities.keys());this.addConfirmedData=({baselines:t=[],operations:e={},isLocal:n=!1})=>{let r={};for(let o of t){if(!Ee(this.rootOid,o.oid))throw new Error(`Invalid baseline for entity ${this.rootOid}: `+JSON.stringify(o));this.get(o.oid).addBaseline(o)}for(let[o,s]of Object.entries(e)){if(!Ee(this.rootOid,o))throw new Error(`Invalid operations for entity ${this.rootOid}: `+JSON.stringify(s));this.get(o).addConfirmedOperations(s)!==0&&(r[o]??={oid:o,isLocal:n})}return Object.values(r)};this.addPendingData=t=>{let e={};for(let n of t)this.get(n.oid).addPendingOperation(n),e[n.oid]??={oid:n.oid,isLocal:!0};return this.onPendingOperations(t),Object.values(e)};this.replaceAllData=({operations:t={},baselines:e=[]})=>{let n=Array.from(this.entities.keys());this.entities.clear();let r={};for(let o of n)r[o]={oid:o,isLocal:!1};for(let o of e){if(!Ee(this.rootOid,o.oid))throw new Error(`Invalid baseline for entity ${this.rootOid}: `+JSON.stringify(o));this.get(o.oid).addBaseline(o),r[o.oid]??={oid:o.oid,isLocal:!1}}for(let[o,s]of Object.entries(t)){if(!Ee(this.rootOid,o))throw new Error(`Invalid operations for entity ${this.rootOid}: `+JSON.stringify(s));this.get(o).addConfirmedOperations(s),r[o]??={oid:o,isLocal:!1}}return Object.values(r)};this.ctx=t,this.rootOid=n,this.onPendingOperations=e}};var Ot="@@default",mn=class{constructor({batchTimeout:t=200,meta:e,ctx:n,entities:r}){this.currentBatchKey=Ot;this.flushOperations=async(t,e,n)=>{if(this.ctx.log("debug","Flushing",t.length,"operations from batch",e,"to storage / sync"),!!t.length){for(let r of t)r.timestamp=this.meta.now;await this.commitOperations(t,n)}};this.commitOperations=async(t,e)=>{if(t.length){if(e.undoable){let n=await this.createUndo({ops:t,source:e.source});n&&this.ctx.undoHistory.addUndo(n)}await this.entities.addData({operations:t,baselines:[],isLocal:!0})}};this.addOperations=t=>{t.length&&(this.batcher.add({key:this.currentBatchKey,items:t}),this.ctx.log("debug","added",t.length,"ops to batch",this.currentBatchKey,", size = ",this.batcher.getSize(this.currentBatchKey)))};this.batch=({undoable:t=!0,batchName:e=Nt(),max:n=null,timeout:r=this.defaultBatchTimeout}={})=>{let o=this.batcher.add({key:e,max:n,timeout:r,items:[],userData:{undoable:t}}),s={run:c=>(this.currentBatchKey=e,c(),this.currentBatchKey=Ot,s),commit:async()=>(await this.batcher.flush(Ot),o.flush()),flush:()=>s.commit(),discard:()=>{this.batcher.discard(e)}};return s};this.flushAll=()=>Promise.all(this.batcher.flushAll());this.createUndo=async t=>{let e=await this.getInverseOperations(t);return e.length?async()=>{let n=await this.createUndo({ops:e,source:t.source});for(let r of e)r.timestamp=this.meta.now;return await this.commitOperations(e,{undoable:!1}),n}:null};this.getInverseOperations=async({ops:t,source:e})=>{let n=mt(t),r=[],o=()=>this.meta.now;return await Promise.all(Object.entries(n).map(async([s,c])=>{let d=(e??await this.entities.hydrate($(s)))?.__getViewData__(s,"confirmed");if(!d){this.ctx.log("warn","could not find entity",s,"for undo operation",t);return}let m=jr(s,d.view,c,o);r.unshift(...m)})),r};this.meta=e,this.ctx=n,this.entities=r,this.defaultBatchTimeout=t,this.batcher=new Xe(this.flushOperations),this.batcher.add({key:Ot,items:[],max:100,timeout:t,userData:{undoable:!0}})}get isDefaultBatch(){return this.currentBatchKey===Ot}};var gn=class extends se{constructor({ctx:e}){super(e.documentDb,{log:e.log});this.reset=async()=>{let e=Object.keys(this.ctx.schema.collections),n=this.ctx.documentDb.transaction(e,"readwrite");await Promise.all(e.map(r=>{let o=n.objectStore(r);return J(o.clear())})),this.ctx.entityEvents.emit("collectionsChanged",e),this.ctx.log("info","\u{1F4A8} Reset queryable storage")};this.saveEntities=async(e,n)=>{if(e.length===0)return;let r=Array.from(new Set(e.map(s=>me(s.oid).collection))),o={transaction:this.createTransaction(r,{mode:"readwrite",abort:n?.abort})};await Promise.all(e.map(async s=>{let c=s.getSnapshot();try{await this.saveDocument(s.oid,c,o)}catch(p){throw this.ctx.log("error",`Error saving document ${s.oid} (${JSON.stringify(c)})`,p),p instanceof Error?p:new Error("Unknown error saving document")}})),o.transaction.commit(),this.ctx.entityEvents.emit("collectionsChanged",r);for(let s of e)this.ctx.entityEvents.emit("documentChanged",s.oid)};this.saveDocument=async(e,n,{transaction:r})=>{this.ctx.log("debug",`Saving document indexes for querying ${e}`,n);let{collection:o,id:s}=me(e);if(!n)await this.run(o,c=>c.delete(s),{mode:"readwrite",transaction:r}),this.ctx.log("debug",`Deleted document indexes for querying ${e}`);else{let c=this.ctx.schema.collections[o],p=qt(c,n);await this.run(o,d=>d.put(p),{mode:"readwrite",transaction:r}),this.ctx.log("debug",`Saved document indexes for querying ${e}`,n)}};this.ctx=e,this.addDispose(this.ctx.internalEvents.subscribe("documentDbChanged",n=>{this.db=n}))}};var Dn=Qe(ko(),1);var _n=class extends Ie{constructor({ctx:e,meta:n,files:r}){super();this.events={add:new Dn.WeakEvent,replace:new Dn.WeakEvent,resetAll:new Dn.WeakEvent};this.cache=new Map;this.pendingEntityPromises=new Map;this.abortDataQueueController=new AbortController;this.ongoingResetPromise=null;this.entityFinalizationRegistry=new FinalizationRegistry(e=>{this.ctx.log("debug","Entity GC",e)});this.addData=async e=>{if(this.disposed){this.ctx.log("warn","EntityStore is disposed, not adding incoming data");return}e.reset&&(this.ctx.log("info","Resetting local store to replicate remote synced data - dropping any current transactions"),this.abortDataQueueController.abort(0),this.abortDataQueueController=new AbortController,this.ongoingResetPromise=this.resetData().finally(()=>{this.ongoingResetPromise=null})),this.ongoingResetPromise&&(this.ctx.log("debug","Waiting for ongoing reset to complete"),await this.ongoingResetPromise,this.ctx.log("debug","Ongoing reset complete")),await this.processData(e)};this.resetData=async()=>{if(this.disposed){this.ctx.log("warn","EntityStore is disposed, not resetting local data");return}await this.meta.reset(),await this.queryableStorage.reset(),this.events.resetAll.invoke(this)};this.processData=async e=>{if(this.disposed){this.ctx.log("warn","EntityStore is disposed, not processing incoming data");return}let n=e?.baselines??[],r=e?.operations??[];this.ctx.log("debug","Processing incoming data",{operations:r.length,baselines:n.length,reset:!!e.reset});let o=Array.from(new Set(n.map(m=>$(m.oid)).concat(r.map(m=>$(m.oid))))),s=Tr(n),c=Ar(r);this.ctx.log("debug","Applying data to live entities");for(let m of o){let S=s[m],g=c[m]??[],C=mt(g),w=e.reset?this.events.replace:this.events.add,v=this.pendingEntityPromises.get(m);v?v.then(()=>{w.invoke(this,{oid:m,baselines:S,operations:C,isLocal:!1})}):(this.cache.has(m)&&this.ctx.log("debug","Cache has",m,", an event should follow."),w.invoke(this,{oid:m,baselines:S,operations:C,isLocal:!1}))}let p={abort:this.abortDataQueueController.signal};await this.meta.insertData(e,p);let d=await Promise.all(o.map(async m=>await this.hydrate(m,p)??{oid:m,getSnapshot(){return null}}));try{await this.queryableStorage.saveEntities(d,p)}catch(m){this.disposed?this.ctx.log("warn","Error saving entities to queryable storage - EntityStore is disposed",m):this.ctx.log("error","Error saving entities to queryable storage",m)}};this.hydrate=async(e,n)=>{if(!Cr(e))throw new Error("Cannot hydrate non-root entity");if(this.cache.has(e)){this.ctx.log("debug","Hydrating entity from cache",e);let o=this.cache.get(e);if(o){let s=o.deref();if(s)return s.deleted?null:s;this.ctx.log("debug","Removing GC'd entity from cache",e),this.cache.delete(e)}}let r=this.pendingEntityPromises.get(e);if(r)return this.ctx.log("debug","Waiting for entity hydration",e),r;{this.ctx.log("debug","Hydrating entity from storage",e);let o=this.constructEntity(e);if(!o)return null;let s=this.loadEntity(o,n);return s.finally(()=>{this.pendingEntityPromises.delete(e)}),this.pendingEntityPromises.set(e,s),s}};this.destroy=async()=>{this.dispose(),await this.batcher.flushAll()};this.create=async(e,n,{undoable:r=!0}={})=>{this.ctx.log("debug","Creating new entity",n);let{collection:o}=me(n);Ut(e);let s=tt(e,this.files.add);K(s,n);let c=this.constructEntity(n);if(!c)throw new Error(`Could not put new document: no schema exists for collection ${o}`);let p=this.meta.patchCreator.createInitialize(s,n);await this.batcher.commitOperations(p,{undoable:!!r,source:c});let d=mt(p);return this.events.add.invoke(this,{operations:d,isLocal:!0,oid:n}),this.cache.set(n,this.ctx.weakRef(c)),c};this.deleteAll=async(e,n)=>{this.ctx.log("info","Deleting documents",e),L(e.every(s=>s===$(s)),"Only root documents may be deleted via client methods");let r=await Promise.all(e.flatMap(async s=>(await this.hydrate(s))?.__getFamilyOids__()??[]));e.forEach(s=>{this.cache.delete(s),this.ctx.log("debug","Deleted document from cache",s)});let o=this.meta.patchCreator.createDeleteAll(r.flat());await this.batcher.commitOperations(o,{undoable:n?.undoable===void 0?!0:n.undoable})};this.delete=async(e,n)=>this.deleteAll([e],n);this.getCollectionSchema=e=>{let n=this.ctx.schema.collections[e];return n?{schema:{type:"object",nullable:!1,properties:n.fields},readonlyKeys:[n.primaryKey]}:(this.ctx.log("warn",`Missing schema for collection: ${e}`),{schema:null,readonlyKeys:[]})};this.constructEntity=e=>{let{collection:n}=me(e),{schema:r,readonlyKeys:o}=this.getCollectionSchema(n);if(!r)return null;if(this.disposed)throw new Error("Cannot hydrate entity after store has been disposed");let s=new hn({ctx:this.ctx,onPendingOperations:this.onPendingOperations,rootOid:e});return new ue({ctx:this.ctx,oid:e,schema:r,readonlyKeys:o,files:this.files,metadataFamily:s,patchCreator:this.meta.patchCreator,events:this.events})};this.onPendingOperations=e=>{this.batcher.addOperations(e)};this.loadEntity=async(e,n)=>{let{operations:r,baselines:o}=await this.meta.getDocumentData(e.oid,n);return!o.length&&!Object.keys(r).length?(this.ctx.log("debug","No data found for entity",e.oid),null):(this.ctx.log("debug","Loaded entity from storage",e.oid),this.events.replace.invoke(this,{oid:e.oid,baselines:o,operations:r,isLocal:!1}),this.cache.set(e.oid,this.ctx.weakRef(e)),this.entityFinalizationRegistry.register(e,e.oid),e)};this.ctx=e,this.meta=n,this.files=r,this.queryableStorage=new gn({ctx:e}),this.batcher=new mn({ctx:e,meta:n,entities:this})}get batch(){return this.batcher.batch}get flushAllBatches(){return this.batcher.flushAll}};var Vi=Symbol("handleMessage"),ba,Dt=class extends U{constructor({initialPresence:e,updateBatchTimeout:n=200,defaultProfile:r,replicaStore:o}){super();this._peers={};this._self={profile:{}};this._selfReplicaIds=new Set;this._peerIds=new Array;this.isSelf=(e,n)=>e.id===n.replicaId||this._selfReplicaIds.has(n.replicaId)||this._self.id===n.id;this[ba]=async(e,n)=>{let r=!1,o=new Set(this.peerIds);if(n.type==="presence-changed")this.isSelf(e,n.userInfo)?(this._self=n.userInfo,this._selfReplicaIds.add(n.userInfo.replicaId),this.emit("selfChanged",n.userInfo)):(o.add(n.userInfo.id),this._peers[n.userInfo.id]=n.userInfo,r=!0,this.emit("peerChanged",n.userInfo.id,n.userInfo));else if(n.type==="sync-resp"){this._peers={},o.clear();for(let[s,c]of Object.entries(n.peerPresence))this.isSelf(e,c)?(this._self=c,this._selfReplicaIds.add(c.replicaId),this.emit("selfChanged",c)):(r=!0,o.add(s),this._peers[s]=c,this.emit("peerChanged",s,c))}else if(n.type==="presence-offline"){o.delete(n.userId),this._selfReplicaIds.delete(n.replicaId);let s=this._peers[n.userId];delete this._peers[n.userId],r=!0,this.emit("peerLeft",n.userId,s)}r&&(this._peerIds=Array.from(o),this.emit("peersChanged",this._peers))};this.update=async e=>{this._updateBatch.update({items:[e]}),this.self.presence={...this.self.presence,...e},this.emit("selfChanged",this.self)};this.flushPresenceUpdates=e=>{let n=e.reduce((r,o)=>({...r,...o}),this.self.presence);this.emit("update",n)};this.self.presence=e,this.self.profile=r,this.self.id="",this.self.replicaId="",o.get().then(s=>{this.self.replicaId=s.id}),this._updateBatcher=new Xe(this.flushPresenceUpdates),this._updateBatch=this._updateBatcher.add({max:25,timeout:n,items:[],key:"default"})}static{ba=Vi}get self(){return this._self}get peers(){return this._peers}get peerIds(){return this._peerIds}get everyone(){let e={...this._peers};return e[this.self.id]=this.self,e}get selfReplicaIds(){return this._selfReplicaIds}};var En=class{constructor({endpointProvider:t,log:e}){this.uploadFile=async t=>{let e=t.file;if(!e)throw new Error("Cannot upload a non-local file");let{files:n,token:r}=await this.endpointProvider.getEndpoints(),o=new window.FormData;o.append("file",e);try{let s=await fetch(n+`/${t.id}`,{method:"POST",body:o,credentials:"include",headers:{Authorization:`Bearer ${r}`}});return s.ok?(this.log("info","File upload successful"),{success:!0,retry:!1}):(this.log("error","File upload failed",s.status,await s.text()),{success:!1,retry:s.status>=500})}catch(s){return this.log("error","File upload failed",s),{success:!1,retry:!0}}};this.getFile=async t=>{let{files:e,token:n}=await this.endpointProvider.getEndpoints();try{let r=await fetch(e+`/${t}`,{method:"GET",credentials:"include",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`}});return r.ok?{success:!0,data:await r.json()}:(this.log("error","File information fetch failed",r.status,await r.text()),{success:!1,retry:r.status>=500||r.status===404})}catch(r){return this.log("error","File information fetch failed",r),{success:!1,error:r,retry:!0}}};this.endpointProvider=t,this.log=e}};var it=class extends U{constructor({interval:e=15*1e3,deadlineLength:n=3*1e3,restartOnTabFocus:r=!0}={}){super();this.nextBeat=null;this.deadline=null;this.keepAlive=()=>{this.deadline&&(clearTimeout(this.deadline),this.deadline=null,this.start())};this.start=(e=!1)=>{this.stop(),e?this.beat():this.nextBeat=setTimeout(this.beat,this._interval)};this.stop=()=>{this.nextBeat&&clearTimeout(this.nextBeat),this.deadline&&clearTimeout(this.deadline)};this.beat=async()=>{this.emit("beat"),this.deadline=setTimeout(this.onDeadline,this.deadlineLength)};this.onDeadline=()=>{this.deadline=null,this.emit("missed")};this.setInterval=e=>{this._interval=e};this._interval=e,this.deadlineLength=n,typeof window<"u"&&r&&(window.addEventListener("pageshow",()=>this.start(!0)),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&this.start(!0)}))}get interval(){return this._interval}};var Cn=class extends U{constructor({endpointProvider:e,meta:n,presence:r,interval:o=15*1e3,log:s=()=>{}}){super();this.mode="pull";this._isConnected=!1;this._status="paused";this._hasSynced=!1;this.setInterval=e=>{this.heartbeat.setInterval(e)};this.sendRequest=async e=>{this.log("Sending sync request",e);try{let{http:n,token:r}=await this.endpointProvider.getEndpoints(),o=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({messages:e}),credentials:"include"});if(o.ok){this.heartbeat.keepAlive();let s=await o.json();for(let c of s.messages)this.handleServerMessage(c);this._isConnected||(this._isConnected=!0,this.emit("onlineChange",!0))}else{this.log("Sync request failed",o.status,await o.text()),this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1));let s=await o.json();Ur(s)&&s.code===4012&&(this.endpointProvider.clearCache(),this.heartbeat.keepAlive()),o.status>=500&&this.heartbeat.keepAlive()}}catch(n){this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1)),this.log(n),this.heartbeat.keepAlive()}};this.handleServerMessage=async e=>{e.type==="sync-resp"&&(e.ackThisNonce&&(this.log("Sending sync ack",e.ackThisNonce),this.sendRequest([await this.meta.messageCreator.createAck(e.ackThisNonce)])),this._hasSynced=!0),this.emit("message",e)};this.send=e=>{switch(e.type){case"presence-update":case"sync":case"heartbeat":return this.sendRequest([e]);case"op":if(this._hasSynced)return this.sendRequest([e]);break}};this.destroy=()=>{this.dispose(),this.stop()};this.onHeartbeat=async()=>{this.sendRequest([await this.meta.messageCreator.createPresenceUpdate(this.presence.self.presence),await this.meta.messageCreator.createSyncStep1()])};this.onHeartbeatMissed=async()=>{this.emit("onlineChange",!1),this.log("Missed heartbeat"),this._isConnected=!1};this.log=s,this.meta=n,this.presence=r,this.endpointProvider=e,this.heartbeat=new it({interval:o}),this.heartbeat.subscribe("beat",this.onHeartbeat),this.heartbeat.subscribe("missed",this.onHeartbeatMissed)}get interval(){return this.heartbeat.interval}start(){this.status!=="active"&&(this.heartbeat.start(!0),this._status="active")}stop(){this.heartbeat.stop(),this._status="paused"}reconnect(){this.heartbeat.start(!0)}ignoreIncoming(){this.stop()}get isConnected(){return this._isConnected}get status(){return this._status}};function Ki(i){this.message=i}Ki.prototype=new Error,Ki.prototype.name="InvalidCharacterError";var Bo=typeof window<"u"&&window.atob&&window.atob.bind(window)||function(i){var t=String(i).replace(/=+$/,"");if(t.length%4==1)throw new Ki("'atob' failed: The string to be decoded is not correctly encoded.");for(var e,n,r=0,o=0,s="";n=t.charAt(o++);~n&&(e=r%4?64*e+n:n,r++%4)?s+=String.fromCharCode(255&e>>(-2*r&6)):0)n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(n);return s};function wa(i){var t=i.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(Bo(e).replace(/(.)/g,function(n,r){var o=r.charCodeAt(0).toString(16).toUpperCase();return o.length<2&&(o="0"+o),"%"+o}))}(t)}catch{return Bo(t)}}function Pn(i){this.message=i}function va(i,t){if(typeof i!="string")throw new Pn("Invalid token specified");var e=(t=t||{}).header===!0?0:1;try{return JSON.parse(wa(i.split(".")[e]))}catch(n){throw new Pn("Invalid token specified: "+n.message)}}Pn.prototype=new Error,Pn.prototype.name="InvalidTokenError";var Mo=va;var An=class{constructor(t){this.config=t;this.cached=null;this.type=0;this.getEndpoints=async()=>{if(this.cached)return this.cached;let t;this.config.fetchAuth?t=await this.config.fetchAuth():t=await fetch(this.config.authEndpoint,{credentials:"include"}).then(c=>{if(c.ok)return c.json();throw new Error(`Auth endpoint returned non-200 response: ${c.status}`)}),L(t.accessToken,"No access token provided from auth endpoint");let e=Mo(t.accessToken);L(e.url,"No sync endpoint provided from auth endpoint"),L(e.type!==void 0,"No replica type provided from auth endpoint"),this.type=parseInt(e.type+"");let n=new URL(e.url);n.protocol=n.protocol.replace("ws","http");let r=n.toString();n.protocol=n.protocol.replace("http","ws");let o=n.toString(),s=e.file;if(!s){let c=new URL(r);c.pathname=c.pathname+"/files",s=c.toString()}return this.cached={http:r,websocket:o,files:s,token:t.accessToken},this.cached};this.clearCache=()=>{this.cached=null};if(!t.authEndpoint&&!t.fetchAuth)throw new Error("Either authEndpoint or fetchAuth must be provided to ServerSyncEndpointProvider")}};var Tn=class extends U{constructor(e){super();this.timer=null;this.isScheduled=!1;this.next=()=>{this.isScheduled||(this.isScheduled=!0,this.timer=setTimeout(()=>{this.emit("trigger"),this.isScheduled=!1,this.backoff.next()},this.backoff.current))};this.reset=()=>{this.backoff.reset(),this.timer&&(clearTimeout(this.timer),this.timer=null)};this.backoff=e}},Rn=class{constructor(t,e){this.current=0;this.next=()=>{this.current=Math.min(this.max,this.current*this.factor)};this.reset=()=>{this.current=0};this.max=t,this.factor=e}};var Fn=class extends U{constructor({endpointProvider:e,meta:n,presence:r,log:o}){super();this.socket=null;this.connectQueue=[];this.syncQueue=[];this.incomingQueue=[];this._status="paused";this.synced=!1;this.hasStartedSync=!1;this._ignoreIncoming=!1;this.mode="realtime";this.log=(...e)=>{};this.heartbeat=new it;this.reconnectScheduler=new Tn(new Rn(60*1e3,1.5));this.onOpen=()=>{if(!this.socket)throw new Error("Invalid sync state: online but socket is null");if(this.synced=!1,this.connectQueue.length){for(let e of this.connectQueue)this.log("Sending queued message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e));this.connectQueue=[]}this.log("Sync connected"),this.onOnlineChange(!0),this.reconnectScheduler.reset()};this.onOnlineChange=async e=>{this.log("Socket online change",e),!this.disposed&&(e?(this.log("Starting sync"),this.hasStartedSync=!0,this.synced=!1,this.send(await this.meta.messageCreator.createPresenceUpdate(this.presence.self.presence)),this.send(await this.meta.messageCreator.createSyncStep1()),this.heartbeat.start()):(this.hasStartedSync=!1,this.synced=!1,this.heartbeat.stop()),this.emit("onlineChange",e))};this.onMessage=async e=>{if(this._ignoreIncoming){this.log("Ignoring incoming message (ignore incoming flag set)",e.data);return}let n=JSON.parse(e.data);switch(n.type){case"sync-resp":if(n.ackThisNonce&&this.send(await this.meta.messageCreator.createAck(n.ackThisNonce)),this.hasStartedSync=!0,this.synced=!0,this.syncQueue.length)if(n.overwriteLocalData)this.log("warn","Overwriting local data - dropping outgoing message queue"),this.syncQueue=[];else{for(let r of this.syncQueue)this.send(r);this.syncQueue=[]}if(this.emit("message",n),this.incomingQueue.length){for(let r of this.incomingQueue)this.emit("message",r);this.incomingQueue=[]}break;case"need-since":case"presence-changed":case"presence-offline":this.emit("message",n);break;case"op-re":if(!this.synced){this.log("Enqueueing op-re message because sync hasn't finished yet",n),this.incomingQueue.push(n);break}this.emit("message",n);break;case"heartbeat-response":this.heartbeat.keepAlive(),this.emit("message",n);break;default:this.synced&&this.emit("message",n);break}};this.onError=e=>{this.log(e),this.reconnectScheduler.next(),this.log("Attempting reconnect to websocket sync")};this.onClose=e=>{this.log("Sync disconnected"),this.onOnlineChange(!1),this.onError(e)};this.initializeSocket=async()=>{let e=await this.endpointProvider.getEndpoints();return this.socket=new WebSocket(e.websocket,["Bearer",e.token]),this.socket.addEventListener("message",this.onMessage),this.socket.addEventListener("open",this.onOpen),this.socket.addEventListener("error",this.onError),this.socket.addEventListener("close",this.onClose),this.socket};this.sendHeartbeat=async()=>{this.send(await this.meta.messageCreator.createHeartbeat())};this.reconnect=()=>{this.stop(),this.start()};this.canSkipSyncWait=e=>e.type==="sync"||e.type==="presence-update"||e.type==="sync-ack"||e.type==="heartbeat";this.send=e=>{this.status==="active"&&(!this.hasStartedSync&&!this.canSkipSyncWait(e)||(this.canSkipSyncWait(e)?this.socket?.readyState===WebSocket.OPEN?(this.log("Sending message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e))):(this.log("Enqueueing message until socket is open",JSON.stringify(e,null,2)),this.connectQueue.push(e)):this.synced?this.socket?.readyState===WebSocket.OPEN&&(this.log("Sending message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e))):this.hasStartedSync&&(this.log("Enqueueing message until synced",JSON.stringify(e,null,2)),this.syncQueue.push(e))))};this.destroy=()=>{this.dispose(),this.stop()};this.start=()=>{this.socket||(this.initializeSocket(),this._status="active")};this.stop=()=>{this.socket?.removeEventListener("message",this.onMessage),this.socket?.removeEventListener("close",this.onClose),this.socket?.close(),this.socket=null,this._status="paused"};this.log=o||this.log,this.endpointProvider=e,this.meta=n,this.presence=r,this.reconnectScheduler.subscribe("trigger",this.initializeSocket),this.heartbeat.subscribe("beat",this.sendHeartbeat)}ignoreIncoming(){this.incomingQueue=[],this._ignoreIncoming=!0}get isConnected(){return this.socket?.readyState===WebSocket.OPEN}get status(){return this._status}};var kn=class extends U{constructor({meta:e}){super();this.mode="pull";this.destroy=()=>{};this.isConnected=!1;this.status="paused";this.pullInterval=0;this.uploadFile=async()=>({success:!1,retry:!1});this.getFile=async()=>({success:!1,retry:!1});this.presence=new Dt({initialPresence:null,defaultProfile:null,replicaStore:e.localReplica})}send(){}start(){}stop(){}ignoreIncoming(){}reconnect(){}setMode(){}setPullInterval(){}},rt=class extends U{constructor({authEndpoint:e,fetchAuth:n,initialPresence:r,automaticTransportSelection:o=!0,autoStart:s,initialTransport:c,pullInterval:p,presenceUpdateBatchTimeout:d,defaultProfile:m,useBroadcastChannel:S},{meta:g,log:C,onData:w}){super();this.broadcastChannel=null;this._activelySyncing=!1;this.handleBroadcastChannelMessage=e=>{e.data.type==="sync"&&this.handleMessage(e.data.message,{source:"broadcastChannel"})};this.onTokenExpired=()=>{this.endpointProvider.clearCache()};this.handleMessage=async(e,{source:n}={source:"network"})=>{if(e.type==="op-re"||e.type==="sync-resp")for(let r of e.operations)this.meta.time.update(r.timestamp);switch(this.log("sync message",JSON.stringify(e,null,2)),e.type){case"op-re":await this.onData({operations:e.operations,baselines:e.baselines}),e.globalAckTimestamp&&await this.meta.setGlobalAck(e.globalAckTimestamp);break;case"global-ack":await this.meta.setGlobalAck(e.timestamp);break;case"sync-resp":this._activelySyncing=!0,this.emit("syncingChange",!0),await this.onData({operations:e.operations,baselines:e.baselines,reset:e.overwriteLocalData}),e.globalAckTimestamp&&await this.meta.setGlobalAck(e.globalAckTimestamp),await this.meta.updateLastSynced(e.ackedTimestamp),this._activelySyncing=!1,this.emit("syncingChange",!1);break;case"need-since":this.activeSync.send(await this.meta.messageCreator.createSyncStep1(e.since));break;case"server-ack":await this.meta.updateLastSynced(e.timestamp)}n==="network"&&this.broadcastChannel?.postMessage({type:"sync",message:e}),this.presence[Vi](await this.meta.localReplica.get(),e)};this.handleOnlineChange=e=>{this.emit("onlineChange",e)};this.handlePresenceUpdate=async e=>{this.send(await this.meta.messageCreator.createPresenceUpdate(e))};this.setMode=e=>{if(e==="realtime"&&!this.canDoRealtime)throw new Error("Cannot switch to realtime mode, because the current auth token does not allow it");let n;e==="realtime"?n=this.webSocketSync:n=this.pushPullSync,n!==this.activeSync&&(this.log("debug","switching to",e,"mode"),this.activeSync.status==="active"&&n.start(),this.activeSync.stop(),this.activeSync=n)};this.setPullInterval=e=>{this.pushPullSync.setInterval(e)};this.send=e=>{if(this.activeSync.status==="active")return this.activeSync.send(e)};this.uploadFile=async e=>(this.log("info","Uploading file",{name:e.name,type:e.type,id:e.id}),this.activeSync.status==="active"?this.fileSync.uploadFile(e):{success:!1,retry:!1});this.getFile=async e=>{if(this.activeSync.status==="active")return this.fileSync.getFile(e);throw new Error("Offline, cannot retrieve remote file details")};this.start=()=>this.activeSync.start();this.stop=()=>this.activeSync.stop();this.destroy=()=>{this.dispose(),this.webSocketSync.destroy(),this.pushPullSync.destroy()};this.reconnect=()=>this.activeSync.reconnect();if(this.meta=g,this.onData=w,this.log=C||(()=>{}),this.presence=new Dt({initialPresence:r,defaultProfile:m,updateBatchTimeout:d,replicaStore:g.localReplica}),this.endpointProvider=new An({authEndpoint:e,fetchAuth:n}),this.webSocketSync=new Fn({endpointProvider:this.endpointProvider,meta:g,presence:this.presence,log:this.log}),this.pushPullSync=new Cn({endpointProvider:this.endpointProvider,meta:g,presence:this.presence,log:this.log,interval:p}),this.fileSync=new En({endpointProvider:this.endpointProvider,log:this.log}),S&&"BroadcastChannel"in window&&(this.broadcastChannel=new BroadcastChannel("verdant"),this.broadcastChannel.addEventListener("message",this.handleBroadcastChannelMessage)),c==="realtime"?this.activeSync=this.webSocketSync:this.activeSync=this.pushPullSync,this.presence.subscribe("update",this.handlePresenceUpdate),this.meta.subscribe("message",this.send),this.webSocketSync.subscribe("message",this.handleMessage),this.webSocketSync.subscribe("onlineChange",this.handleOnlineChange),this.pushPullSync.subscribe("message",this.handleMessage),this.pushPullSync.subscribe("onlineChange",this.handleOnlineChange),o&&this.canDoRealtime){let v=()=>{I&&clearTimeout(I);let D=Object.keys(this.presence.peers).length>0||o!=="peers-only"&&this.presence.selfReplicaIds.size>1;D&&this.mode==="pull"?this.setMode("realtime"):!D&&this.mode==="realtime"&&(I=setTimeout(()=>{Object.keys(this.presence.peers).length===0&&this.setMode("pull")},1e3))},I;this.presence.subscribe("peersChanged",v),o!=="peers-only"&&this.presence.subscribe("selfChanged",v)}s&&this.start()}get canDoRealtime(){return this.endpointProvider.type===0||this.endpointProvider.type===2||this.endpointProvider.type===5}get syncing(){return this._activelySyncing}get pullInterval(){return this.pushPullSync.interval}ignoreIncoming(){this.activeSync.ignoreIncoming()}get isConnected(){return this.activeSync.isConnected}get status(){return this.activeSync.status}get mode(){return this.activeSync.mode}};function xa(i){return i!==null}function $i(i){return Array.isArray(i)?i.map($i).filter(xa):i instanceof ue&&i.deleted?null:i}function ke(i,t){return!i&&!t||i&&t&&Te(i)===Te(t)}var zi=Symbol("ON_ALL_UNSUBSCRIBED"),fe=Symbol("UPDATE"),Oa,ge=class extends Ie{constructor({initial:e,context:n,collection:r,key:o,shouldUpdate:s}){super();this._internalUnsubscribes=[];this._status="initial";this._executionPromise=null;this.setValue=e=>{if(this._rawValue=e,this.subscribeToDeleteAndRestore(this._rawValue),this._value=$i(e),Array.isArray(this._value)&&this._value.some(n=>n.getSnapshot()===null))debugger;this._status="ready",this._events.emit("change",this._value)};this.refreshValue=()=>{this.setValue(this._rawValue)};this.subscribeToDeleteAndRestore=e=>{for(;this._internalUnsubscribes.length;)this._internalUnsubscribes.pop()?.();Array.isArray(e)?e.forEach(n=>{n instanceof ue&&(this._internalUnsubscribes.push(n.subscribe("delete",this.refreshValue)),this._internalUnsubscribes.push(n.subscribe("restore",this.refreshValue)))}):e instanceof ue&&(this._internalUnsubscribes.push(e.subscribe("delete",this.refreshValue)),this._internalUnsubscribes.push(e.subscribe("restore",()=>{this.refreshValue()})))};this.execute=()=>(this.context.log("debug","Executing query",this.key),this._status==="initial"?this._status="initializing":this._status==="ready"&&(this._status="revalidating"),this._executionPromise=this.run().then(()=>this._value).catch(e=>{if(e instanceof Error){if(e.name==="InvalidStateError"||e.name==="InvalidAccessError")return this._value;throw e}else throw new Error("Unknown error executing query")}),this._executionPromise);this[Oa]=e=>{this._allUnsubscribedHandler=e};this._rawValue=e,this._value=e,this._events=new U(p=>{p==="change"&&this._allUnsubscribedHandler?.(this)}),this.context=n,this.key=o,this.collection=r;let c=s||(p=>p.includes(r));this.addDispose(this.context.entityEvents.subscribe("collectionsChanged",p=>{c(p)&&(this.context.log("info","Updating query",this.key),this.execute())}))}static{Oa=zi}get current(){return this._value}get resolved(){return this.status==="ready"?Promise.resolve(this._value):this._executionPromise??this.execute()}get subscribed(){return this._events.totalSubscriberCount()>0}get status(){return this._status}subscribe(e,n){if(n===void 0&&typeof e=="function")return this.resolved,this._events.subscribe("change",e);if(e==="change"&&n!==void 0)return this.resolved,this._events.subscribe("change",n);if(e==="statusChange"&&typeof n=="function")return this._events.subscribe(e,n);throw new Error("Invalid invocation of Query.subscribe")}};var Bn=class extends ge{constructor({id:e,hydrate:n,...r}){super({initial:null,...r});this.run=async()=>{let e=await this.hydrate(this.oid);this.setValue(e)};this.oid=Z(r.collection,e),this.hydrate=n}};var Ia,Mn=class extends ge{constructor({index:e,hydrate:n,...r}){super({initial:null,...r});this.run=async()=>{let e=await sn({collection:this.collection,index:this.index,context:this.context});this.setValue(e?await this.hydrate(e):null)};this[Ia]=e=>{ke(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n}static{Ia=fe}};var Da,jn=class extends ge{constructor({index:e,hydrate:n,pageSize:r,page:o,...s}){super({initial:[],...s});this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:n}=await wt({collection:this.collection,index:this.index,context:this.context,limit:this._pageSize,offset:this._page*this._pageSize});this._hasNextPage=n,this.setValue(await Promise.all(e.map(this.hydrate)))};this.nextPage=async()=>{this.hasNextPage&&(this._page++,await this.run())};this.previousPage=async()=>{this._page!==0&&(this._page--,await this.run())};this.setPage=async e=>{this._page=e,await this.run()};this[Da]=e=>{ke(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n,this._pageSize=r,this._page=o}static{Da=fe}get pageSize(){return this._pageSize}get page(){return this._page}get hasNextPage(){return this._hasNextPage}get hasPreviousPage(){return this._page>0}};var _a,Ln=class extends ge{constructor({hydrate:e,pageSize:n,index:r,...o}){super({initial:[],...o});this._upToPage=1;this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:n}=await wt({collection:this.collection,context:this.context,limit:this._pageSize*this._upToPage,offset:0,index:this.index});this._hasNextPage=n,this.setValue(await Promise.all(e.map(this.hydrate)))};this.loadMore=async()=>{let{result:e,hasNextPage:n}=await wt({collection:this.collection,context:this.context,limit:this._pageSize,offset:this._pageSize*this._upToPage,index:this.index});this._hasNextPage=n,this._upToPage++,this.setValue([...this.current,...await Promise.all(e.map(this.hydrate))])};this[_a]=e=>{ke(this.index,e)||(this.index=e,this.execute())};this.index=r,this.hydrate=e,this._pageSize=n}static{_a=fe}get pageSize(){return this._pageSize}get hasMore(){return this._hasNextPage}};var Ea,Nn=class extends ge{constructor({index:e,hydrate:n,...r}){super({initial:[],...r});this.run=async()=>{let e=await an({collection:this.collection,index:this.index,context:this.context});this.context.log("debug",`FindAllQuery: ${e.length} oids found: ${e}`),this.setValue(await Promise.all(e.map(this.hydrate)))};this[Ea]=e=>{ke(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n}static{Ea=fe}};var Un=class{constructor({collection:t,cache:e,entities:n,context:r,documentManager:o}){this.serializeIndex=t=>t?Te(t):"";this.get=t=>{let e=`get:${this.collection}:${t}`;return this.cache.getOrSet(e,()=>new Bn({id:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:e}))};this.findOne=({index:t,key:e}={})=>{let n=e||`findOne:${this.collection}:${this.serializeIndex(t)}`;return this.cache.getOrSet(n,()=>new Mn({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:n}),r=>{r[fe](t)})};this.findAll=({index:t,key:e}={})=>{let n=e||`findAll:${this.collection}:${this.serializeIndex(t)}`;return this.cache.getOrSet(n,()=>new Nn({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:n}),r=>{r[fe](t)})};this.findPage=({index:t,pageSize:e,page:n,key:r})=>{let o=r||`findPage:${this.collection}:${this.serializeIndex(t)}:${e}`;return this.cache.getOrSet(o,()=>new jn({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:o,pageSize:e,page:n}),s=>{s[fe](t)})};this.findAllInfinite=({index:t,pageSize:e,key:n})=>{let r=n||`findAllInfinite:${this.collection}:${this.serializeIndex(t)}:${e}`;return this.cache.getOrSet(r,()=>new Ln({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:r,pageSize:e}),o=>{o[fe](t)})};this.cache=e,this.collection=t,this.hydrate=n.hydrate,this.context=r,this.documentManager=o,this.put=this.documentManager.create.bind(this.documentManager,this.collection),this.delete=this.documentManager.delete.bind(this.documentManager,this.collection),this.deleteAll=this.documentManager.deleteAllFromCollection.bind(this.documentManager,this.collection)}};var Vn=class extends Ie{constructor({evictionTime:e=5*1e3,context:n}){super();this._cache=new Map;this.onQueryUnsubscribed=e=>{setTimeout(()=>{e.subscribed||this._cache.get(e.key)===e&&this._cache.delete(e.key)},this._evictionTime)};this.dropAll=()=>{this._cache.forEach(e=>e.dispose()),this._cache.clear()};this._evictionTime=e,this.context=n}get(e){return this._cache.get(e)||null}set(e){return this._cache.set(e.key,e),e[zi](this.onQueryUnsubscribed),e}getOrSet(e,n,r){let o=this.get(e);return o?(r?.(o),o):this.set(n())}};var He=class extends U{constructor(e,n,r){super();this.config=e;this.context=n;this._closed=!1;this.addData=e=>this._entities.addData(e);this.stats=async()=>{let e=Object.keys(this.schema.collections),n={};for(let d of e)try{n[d]=await yt(this.documentDb,d)}catch(m){this.context.log?.("error",m)}let r=await this.meta.stats(),o=typeof navigator<"u"&&typeof navigator.storage<"u"&&"estimate"in navigator.storage?await navigator.storage.estimate():void 0,s=Object.values(n).reduce((d,{size:m})=>d+m,0),c=r.baselinesSize.size+r.operationsSize.size,p=c/s;return{collections:n,meta:r,storage:o,totalMetaSize:c,totalCollectionsSize:s,metaToDataRatio:p,quotaUsage:o?.usage&&o?.quota?o.usage/o.quota:void 0}};this.close=async()=>{this._closed=!0,this.sync.ignoreIncoming(),await this._entities.flushAllBatches(),this.sync.stop(),this.sync.destroy(),await this._entities.destroy(),this.meta.close(),await new Promise(async e=>{await Ke(this.documentDb),await Ke(this.metaDb),e()}),this.context.log?.("Client closed")};this.__dangerous__resetLocal=async()=>{this.sync.stop(),await Jt(this.namespace,indexedDB)};this.export=async()=>{let e=await this.meta.export();return Buffer.from(JSON.stringify(e))};this.import=async e=>{this.context.log("Importing data..."),await Ke(this.context.documentDb);let n=JSON.parse(e.toString());await this.meta.resetFrom(n);let r=n.schema.version,o=indexedDB.deleteDatabase([this.namespace,"collections"].join("_"));await new Promise((c,p)=>{o.onsuccess=c,o.onerror=p});let s=this.context.schema;this.context.schema=n.schema,this.context.documentDb=await vt({meta:this.meta,migrations:this.config.migrations,context:this.context,version:r}),this.context.internalEvents.emit("documentDbChanged",this.documentDb),this.context.log("Re-initializing data from imported data..."),await this._entities.addData({operations:n.operations,baselines:n.baselines,reset:!0}),await Ke(this.context.documentDb),this.context.log("Migrating up to latest schema..."),this.context.schema=s,this.context.documentDb=await vt({meta:this.meta,migrations:this.config.migrations,context:this.context,version:s.version}),this.context.internalEvents.emit("documentDbChanged",this.documentDb)};this.meta=r.meta,this.collectionNames=Object.keys(n.schema.collections),this._sync=this.config.syncConfig&&!n.schema.wip?new rt(this.config.syncConfig,{meta:this.meta,onData:this.addData,log:this.context.log}):new kn({meta:this.meta}),n.schema.wip&&this.config.syncConfig&&n.log("warn","\u26A0\uFE0F\u26A0\uFE0F Sync is disabled for WIP schemas. Commit your schema changes to start syncing again. \u26A0\uFE0F\u26A0\uFE0F"),this._fileManager=new fn({db:this.metaDb,sync:this.sync,context:this.context,config:this.config.files,meta:this.meta}),this._entities=new _n({ctx:this.context,meta:this.meta,files:this._fileManager}),this._queryCache=new Vn({context:n}),this._documentManager=new dn(this.meta,this.schema,this._entities);let o=Ir(()=>{this.emit("futureSeen")},300);this.context.globalEvents.subscribe("futureSeen",o),this.documentDb.addEventListener("versionchange",()=>{this.context.log?.(`Another tab has requested a version change for ${this.namespace}`),this.documentDb.close(),typeof window<"u"&&window.location.reload()}),this.metaDb.addEventListener("versionchange",()=>{this.context.log?.(`Another tab has requested a version change for ${this.namespace}`),this.metaDb.close(),typeof window<"u"&&window.location.reload()});for(let[s,c]of Object.entries(n.schema.collections)){let p=s;this[p]=new Un({collection:p,cache:this._queryCache,context:this.context,entities:this.entities,documentManager:this.documentManager})}}get sync(){return this._sync}get entities(){return this._entities}get documentManager(){return this._documentManager}get documentDb(){return this.context.documentDb}get metaDb(){return this.context.metaDb}get schema(){return this.context.schema}get namespace(){return this.context.namespace}get undoHistory(){return this.context.undoHistory}get presence(){return this.sync.presence}get batch(){return this.entities.batch}};var _t=class{constructor(t){this.value=t}deref(){return this.value}};var jo=Symbol("metadataVersion");var Kn=class{constructor(t){this.init=t;this._initializing=!1;this.initialize=async t=>{if(typeof window>"u"&&!t.indexedDb)throw new Error("A verdant client was initialized in an environment without IndexedDB. If you are using verdant in a server-rendered framework, you must enforce that all clients are initialized on the client-side, or you must provide some mock interface of IDBFactory to the ClientDescriptor options.");if(this._initializing||this._resolvedValue)return this._readyPromise;this._initializing=!0;try{let e;return t.schema.wip?e=await this.initializeWIPDatabases(t):(e=await this.initializeDatabases(t),this.cleanupWIPDatabases(t)),this.resolveReady(e),this._resolvedValue=e,e}catch(e){throw e instanceof Error?(this.rejectReady(e),e):new Error("Unknown error initializing storage")}finally{this._initializing=!1}};this.initializeDatabases=async t=>{let e=t[jo],{db:n}=await rn({indexedDB:t.indexedDb,log:t.log,namespace:t.namespace,metadataVersion:e}),r={namespace:this._namespace,metaDb:n,schema:t.schema,log:t.log||(()=>{}),undoHistory:t.undoHistory||new St,entityEvents:new U,globalEvents:new U,internalEvents:new U,weakRef:m=>t.EXPERIMENTAL_weakRefs?new WeakRef(m):new _t(m),migrations:t.migrations},o=new bt({context:r,disableRebasing:t.disableRebasing});await o.updateSchema(t.schema,t.overrideSchemaConflict);let s=Object.assign(r,{getNow:()=>o.now}),c=await vt({context:s,version:t.schema.version,meta:o,migrations:t.migrations,indexedDB:t.indexedDb}),p=Object.assign(s,{documentDb:c});return new He({syncConfig:t.sync,migrations:t.migrations,files:t.files},p,{meta:o})};this.initializeWIPDatabases=async t=>{let e=Te(t.schema);console.info(`WIP schema in use. Opening database with hash ${e}`);let n=`@@wip_${t.namespace}_${e}`,{db:r}=await qr({indexedDB:t.indexedDb,log:t.log,namespace:t.namespace,wipNamespace:n}),o={namespace:this._namespace,metaDb:r,schema:t.schema,log:t.log||(()=>{}),undoHistory:t.undoHistory||new St,entityEvents:new U,globalEvents:new U,internalEvents:new U,weakRef:S=>t.EXPERIMENTAL_weakRefs?new WeakRef(S):new _t(S),migrations:t.migrations},s=new bt({context:o,disableRebasing:t.disableRebasing}),c=Object.assign(o,{getNow:()=>s.now});await s.updateSchema(t.schema,t.overrideSchemaConflict);let p=await Jr({context:c,version:t.schema.version,meta:s,migrations:t.migrations,indexedDB:t.indexedDb,wipNamespace:n}),d=Object.assign(c,{documentDb:p});return new He({syncConfig:t.sync,migrations:t.migrations,files:t.files},d,{meta:s})};this.cleanupWIPDatabases=async t=>{let r=(await $r(t.indexedDb)).filter(o=>o.name?.startsWith("@@wip_")).map(o=>o.name).filter(o=>!o.startsWith(`@@wip_${t.namespace}_${Te(t.schema)}`));for(let o of r)await Kr(o,t.indexedDb)};this.open=()=>this.initialize(this.init);this.close=async()=>{this._resolvedValue&&this._resolvedValue.close(),this._initializing&&(await this._readyPromise).close()};this.__dangerous__resetLocal=async()=>{await Jt(this.namespace)};this._readyPromise=new Promise((e,n)=>{this.resolveReady=e,this.rejectReady=n}),this._namespace=t.namespace}get namespace(){return this._namespace}get current(){return this._resolvedValue}get readyPromise(){return this._readyPromise}get schema(){return this.init.schema}};window.Verdant=qi;
|
|
13
|
+
- New indexes: ${Object.keys(o.addedIndexes).map(l=>o.addedIndexes[l].map(m=>`${l}.${m.name}`)).flatMap(l=>l).join(", ")}
|
|
14
|
+
- Removed indexes: ${Object.keys(o.removedIndexes).map(l=>o.removedIndexes[l].map(m=>`${l}.${m.name}`)).flatMap(l=>l).join(", ")}
|
|
15
|
+
`)}})}function Yr({migration:i,meta:t,getMigrationNow:e,newOids:n}){return i.allCollections.reduce((r,o)=>(r[o]={put:async s=>{Pe(i.newSchema.collections[o],s);let a=s[i.newSchema.collections[o].primaryKey],p=Z(o,a);return n.push(p),await t.insertLocalOperations(Te(s,p,e)),s},delete:async s=>{let a=Z(o,s),p=await t.getAllDocumentRelatedOids(a);return t.insertLocalOperations(p.map(l=>({oid:l,timestamp:e(),data:{op:"delete"}})))}},r),{})}function zs({migration:i,context:t,meta:e}){return i.oldCollections.reduce((n,r)=>(n[r]={get:async o=>{let s=Z(r,o);return await e.getDocumentSnapshot(s,{to:e.time.now(i.oldSchema.version)})},findOne:async o=>{let s=await sn({collection:r,index:o,context:t});return s?await e.getDocumentSnapshot(s,{to:e.time.now(i.oldSchema.version)}):null},findAll:async o=>{let s=await an({collection:r,index:o,context:t});return await Promise.all(s.map(p=>e.getDocumentSnapshot(p,{to:e.time.now(i.oldSchema.version)})))}},n),{})}function qs({meta:i,migration:t,context:e}){function n(){return i.time.zero(t.version)}let r=new Array,o=zs({migration:t,context:e,meta:i}),s=Yr({migration:t,getMigrationNow:n,newOids:r,meta:i}),a=async m=>{let x=await i.getAllCollectionRelatedOids(m);return i.insertLocalOperations(x.map(y=>({oid:y,timestamp:n(),data:{op:"delete"}})))},p=new Array;return{log:e.log,newOids:r,deleteCollection:a,migrate:async(m,x)=>{let y=await o[m].findAll();await Promise.all(y.filter(Boolean).map(async C=>{let w=ne(C);L(!!w,`Document is missing an OID: ${JSON.stringify(C)}`);let S=ae(C),I=await x(C);if(I){ft(S),ft(I),Ge(I);let v=ht(S,I,n,void 0,[],{mergeUnknownObjects:!0});v.length>0&&await i.insertLocalOperations(v)}}))},queries:o,mutations:s,awaitables:p}}function Hs({meta:i,migration:t,context:e}){function n(){return i.time.zero(t.version)}let r=new Array,o=new Proxy({},{get(){throw new Error("Queries are not available in initial migrations; there is no database yet!")}}),s=Yr({migration:t,getMigrationNow:n,newOids:r,meta:i});return{log:e.log,newOids:r,deleteCollection:()=>{throw new Error("Calling deleteCollection() in initial migrations is not supported! Use initial migrations to seed initial data using mutations.")},migrate:()=>{throw new Error("Calling migrate() in initial migrations is not supported! Use initial migrations to seed initial data using mutations.")},queries:o,mutations:s,awaitables:[]}}async function Ws(i){return new Promise((t,e)=>{let n=i.getAllKeys();n.onsuccess=r=>{t(n.result)},n.onerror=r=>{e(n.error)}})}async function Qs(i,t){let e=i.delete(t);return new Promise((n,r)=>{e.onsuccess=o=>{n()},e.onerror=o=>{r(e.error)}})}async function Js(i,t){let e=i.put(t);return new Promise((n,r)=>{e.onsuccess=o=>{n()},e.onerror=o=>{r(e.error)}})}async function Ys({meta:i,currentVersion:t,newVersion:e}){let n=[];return await i.operations.iterateOverAllOperations(r=>n.push(r),{from:i.time.zero(t+1)}),Array.from(new Set(n.map(r=>$(r.oid))))}var St=class extends U{constructor(){super(...arguments);this._undoable=[];this._undone=[];this.undo=async()=>{let e=this._undoable.pop();if(e){let n=await e();return n&&this._undone.push(n),this.emit("change"),!0}return!1};this.redo=async()=>{let e=this._undone.pop();if(e){let n=await e();return n&&this._undoable.push(n),this.emit("change"),!0}return!1};this.addUndo=e=>{this._undoable.push(e),this._undone=[],this.emit("change")};this.addRedo=e=>{this._undone.push(e),this.emit("change")};this.clear=()=>{this._undoable=[],this._undone=[],this.emit("change")}}get canUndo(){return this._undoable.length>0}get canRedo(){return this._undone.length>0}};var dn=class{constructor(t,e,n){this.meta=t;this.schema=e;this.entities=n;this.getOid=(t,e)=>{let n=this.schema.collections[t].primaryKey,r=e[n];return L(r,`Document must have a primary key: ${n.toString()} (got: ${JSON.stringify(e)})`),Z(t,r)};this.addDefaults=(t,e)=>{let n=this.schema.collections[t];return Pe(n,e)};this.create=(t,e,n={})=>{let r=this.addDefaults(t,e),o=this.getOid(t,r);return this.entities.create(r,o,n)};this.delete=async(t,e,n={})=>{let r=Z(t,e);return this.entities.delete(r,n)};this.deleteAll=async(t,e={})=>this.entities.deleteAll(t.map(([n,r])=>Z(n,r)),e);this.deleteAllFromCollection=async(t,e,n={})=>this.entities.deleteAll(e.map(r=>Z(t,r)),n)}};var et=Symbol("entity-file-update"),xt=Symbol("entity-file-mark-failed"),Gs,Xs,de=class extends U{constructor(e,{downloadRemote:n=!1}={}){super();this.id=e;this._objectUrl=null;this._fileData=null;this._loading=!0;this._failed=!1;this._downloadRemote=!1;this[Gs]=e=>{this._loading=!1,this._failed=!1,this._fileData=e,e.file&&(this._objectUrl&&URL.revokeObjectURL(this._objectUrl),this._objectUrl=URL.createObjectURL(e.file)),this.emit("change")};this[Xs]=()=>{this._failed=!0,this._loading=!1,this.emit("change")};this.destroy=()=>{this._objectUrl&&URL.revokeObjectURL(this._objectUrl),this.dispose()};this._downloadRemote=n}static{Gs=et,Xs=xt}get downloadRemote(){return this._downloadRemote}get url(){return this.loading?null:this._objectUrl?this._objectUrl:this._fileData?.url??null}get name(){return this._fileData?.name??null}get type(){return this._fileData?.type??null}get loading(){return this._loading}get failed(){return this._failed}getSnapshot(){return{id:this.id,url:this.loading||this.failed?void 0:this.url}}};var Gr=Qe(at(),1);function Zs(i){return{id:(0,Gr.default)(),file:i,url:void 0,remote:!1,name:i.name,type:i.type}}function Di(i){return i instanceof File||typeof Blob<"u"&&i instanceof Blob}function tt(i,t){if(typeof window<"u"&&Di(i)){let e=Zs(i);return t(e),Mt(e.id)}if(Array.isArray(i)){for(let e=0;e<i.length;e++)i[e]=tt(i[e],t);return i}if(typeof i=="object"){for(let e in i)i[e]=tt(i[e],t);return i}return i}function Xr(i){return new Promise((t,e)=>{let n=new FileReader;n.onload=()=>{t(n.result)},n.onerror=e,n.readAsArrayBuffer(i)})}var un=class extends se{constructor(){super(...arguments);this.addFile=async(e,{transaction:n,downloadRemote:r=!1}={})=>{let o=e.file?await Xr(e.file):void 0;if(!o&&r&&e.url)try{o=await fetch(e.url,{method:"GET",credentials:"include"}).then(s=>s.arrayBuffer())}catch(s){console.error("Failed to download file to cache it locally. The file will still be available using its URL. Check the file server's CORS configuration.",s)}return this.run("files",s=>s.put({id:e.id,remote:e.remote?"true":"false",deletedAt:null,name:e.name,type:e.type,url:e.url,buffer:o}),{mode:"readwrite",transaction:n})};this.hydrateFileData=e=>{e.remote=e.remote==="true";let n=e.buffer;return delete e.buffer,e.file=n?ea(n,e.type):void 0,e};this.markUploaded=async(e,{transaction:n}={})=>{let r=await this.getFileRaw(e,{transaction:n});if(!r)throw new Error("File is not in local database");return this.run("files",o=>o.put({...r,remote:"true"}),{mode:"readwrite",transaction:n})};this.getFileRaw=async(e,{transaction:n}={})=>{let r=await this.run("files",o=>o.get(e),{mode:"readonly",transaction:n});if(r)return r};this.getFile=async(e,{transaction:n}={})=>{let r=await this.getFileRaw(e,{transaction:n});if(r)return this.hydrateFileData(r)};this.markPendingDelete=async(e,{transaction:n}={})=>{let r=await this.getFileRaw(e,{transaction:n});if(!r)throw new Error("File is not in local database");return this.run("files",o=>o.put({...r,deletedAt:Date.now()}),{mode:"readwrite",transaction:n})};this.listUnsynced=async()=>(await this.run("files",n=>n.index("remote").getAll("false"),{mode:"readonly"})).map(this.hydrateFileData);this.iterateOverPendingDelete=(e,n)=>this.iterate("files",r=>r.index("deletedAt").openCursor(IDBKeyRange.lowerBound(0,!0)),(r,o)=>{e(this.hydrateFileData(r),o)},{mode:"readwrite",transaction:n})}deleteFile(e,{transaction:n}={}){return this.run("files",r=>r.delete(e),{mode:"readwrite",transaction:n})}};function ea(i,t){return new Blob([i],{type:t})}function ta(i){return i.deletedAt!==null&&i.deletedAt<Date.now()-1e3*60*24*3}var fn=class{constructor({db:t,sync:e,context:n,meta:r,config:o={}}){this.files=new Map;this.add=async t=>{let e=t;if(e.remote=!1,this.files.has(e.id))this.files.get(e.id)[et](e);else{let n=new de(e.id);n[et](e),this.files.set(e.id,n)}await this.storage.addFile(e),e.file&&await this.uploadFile(e,1)};this.uploadFile=async(t,e=0)=>{let n=await this.sync.uploadFile(t);n.success?await this.storage.markUploaded(t.id):n.retry&&e<5?(this.context.log("error","Error uploading file, retrying..."),setTimeout(this.uploadFile,1e3,t,e+1)):this.context.log("error","Failed to upload file. Not retrying until next sync.")};this.get=(t,e)=>{if(this.files.has(t))return this.files.get(t);let n=new de(t,e);return this.files.set(t,n),this.load(n),n};this.load=async(t,e=0)=>{if(e>5){this.context.log("error","Failed to load file after 5 retries"),t[xt]();return}let n=await this.storage.getFile(t.id);if(n)t[et](n);else try{let r=await this.sync.getFile(t.id);r.success?(t[et](r.data),await this.storage.addFile(r.data,{downloadRemote:t.downloadRemote})):(this.context.log("error","Failed to load file",r),t[xt](),r.retry&&setTimeout(this.load,1e3,t,e+1))}catch(r){this.context.log("error","Failed to load file",r),t[xt](),setTimeout(this.load,1e3,t,e+1)}};this.listUnsynced=async()=>this.storage.listUnsynced();this.onOnlineChange=async t=>{if(t){let e=await this.listUnsynced();await Promise.all(e.map(this.uploadFile))}};this.tryCleanupDeletedFiles=async()=>{let t=0,e=0;await this.storage.iterateOverPendingDelete((n,r)=>{this.config.canCleanupDeletedFile(n)?(t++,r.delete(n.id)):e++}),this.context.log("info",`Cleaned up ${t} files, skipped ${e} files`)};this.handleFileRefsDeleted=async t=>{let e=this.storage.createTransaction(["files"],{mode:"readwrite"});await Promise.all(t.map(async n=>{try{await this.storage.markPendingDelete(n.id,{transaction:e})}catch(r){this.context.log("error","Failed to mark file for deletion",r)}})),this.context.log("info",`Marked ${t.length} files as pending delete`)};this.storage=new un(t),this.sync=e,this.context=n,this.meta=r,this.config={canCleanupDeletedFile:ta,...o},this.sync.subscribe("onlineChange",this.onOnlineChange),this.meta.subscribe("filesDeleted",this.handleFileRefsDeleted),this.tryCleanupDeletedFiles()}};var pn=class{constructor({initial:t}={}){this.cache=new Map;this.get=t=>{if(this.cache.has(t.oid))return this.cache.get(t.oid);let e=new ue(t);return this.cache.set(t.oid,e),e};this.has=t=>this.cache.has(t);this.getFile=(t,e)=>{if(this.cache.has(t))return this.cache.get(t);let n=new de(t,e);return this.cache.set(t,n),n};this.getCached=t=>this.cache.get(t);if(t)for(let e of t)this.cache.set(e.oid,e)}};var ue=class i extends U{constructor({oid:e,schema:n,entityFamily:r,parent:o,ctx:s,metadataFamily:a,readonlyKeys:p,files:l,patchCreator:m,events:x}){super();this.fieldPath=[];this._viewData=void 0;this.validationError=void 0;this.cachedDeepUpdatedAt=null;this.wasDeletedLastChange=!1;this.cachedView=void 0;this.onAdd=(e,n)=>{n.oid===this.oid&&this.addConfirmedData(n)};this.onReplace=(e,n)=>{n.oid===this.oid&&this.replaceAllData(n)};this.onResetAll=()=>{this.resetAllData()};this.childIsNull=e=>{if(e instanceof i){let n=e.view;return n==null}return e==null};this.validate=Lr(()=>(this.validationError=Fe({field:this.schema,value:this.rawView,fieldPath:this.fieldPath,depth:1})??void 0,this.validationError),()=>[this.viewData]);this.viewWithMappedChildren=e=>{let n=this.view;if(!n)return null;if(Array.isArray(n)){let r=n.map(o=>o instanceof i||o instanceof de?e(o):o);return K(r,this.oid),r}else{let r=Object.entries(n).reduce((o,[s,a])=>(a instanceof i||a instanceof de?o[s]=e(a):o[s]=a,o),{});return K(r,this.oid),r}};this.getSnapshot=()=>this.viewWithMappedChildren(e=>e.getSnapshot());this.addPendingOperations=e=>{this.ctx.log("debug","Entity: adding pending operations",this.oid);let n=this.metadataFamily.addPendingData(e);for(let r of n)this.change(r)};this.addConfirmedData=e=>{this.ctx.log("debug","Entity: adding confirmed data",this.oid);let n=this.metadataFamily.addConfirmedData(e);for(let r of n)this.change(r)};this.replaceAllData=e=>{this.ctx.log("debug","Entity: replacing all data",this.oid);let n=this.metadataFamily.replaceAllData(e);for(let r of n)this.change(r)};this.resetAllData=()=>{this.ctx.log("debug","Entity: resetting all data",this.oid),this.cachedDeepUpdatedAt=null,this.cachedView=void 0,this._viewData=void 0;let e=this.metadataFamily.replaceAllData({});for(let n of e)this.change(n)};this.change=e=>{if(e.oid===this.oid)this._viewData=void 0,this.cachedView=void 0,this.deepChange(this,e),this.ctx.log("Emitting change event",this.oid),this.emit("change",{isLocal:e.isLocal}),this.parent||(this.deleted&&!this.wasDeletedLastChange?(this.ctx.log("debug","Entity deleted",this.oid),this.emit("delete",{isLocal:e.isLocal}),this.wasDeletedLastChange=!0):!this.deleted&&this.wasDeletedLastChange&&(this.ctx.log("debug","Entity restored",this.oid),this.emit("restore",{isLocal:e.isLocal}),this.wasDeletedLastChange=!1));else{let n=this.entityFamily.getCached(e.oid);n&&n instanceof i&&n.change(e)}};this.deepChange=(e,n)=>{this.cachedDeepUpdatedAt=null,this.cachedView=void 0,this.ctx.log("debug","Deep change detected at",this.oid,"reset cached view"),this.ctx.log("debug","Emitting deep change event",this.oid),this.emit("changeDeep",e,n),this.parent?.deepChange(e,n)};this.getChild=(e,n)=>{let r=Ne(this.schema,e);if(!r)throw new Error(`No schema for key ${String(e)} in ${JSON.stringify(this.schema)}`);return this.entityFamily.get({oid:n,schema:r,entityFamily:this.entityFamily,metadataFamily:this.metadataFamily,parent:this,ctx:this.ctx,files:this.files,fieldPath:[...this.fieldPath,e],patchCreator:this.patchCreator,events:this.events})};this.get=e=>{Zr(e);let n=this.rawView;if(!n)throw new Error(`Cannot access data at key ${e} on deleted entity ${this.oid}`);let r=n[e],o=Ne(this.schema,e);if(!o)throw new Error(`No schema for key ${String(e)} in ${JSON.stringify(this.schema)}`);if(Q(r))if(be(r)){if(o.type!=="file")throw new Error(`Expected file schema for key ${String(e)}, got ${o.type}`);let s=this.files.get(r.id,{downloadRemote:!!o.downloadRemote});return s.subscribe("change",()=>{this.deepChange(this,{isLocal:!1,oid:this.oid})}),s}else return this.getChild(e,r.id);else return Fe({field:o,value:r,fieldPath:[...this.fieldPath,e],depth:1,requireDefaults:!0})?Ce(o)?pi(o):we(o)?null:void 0:r};this.processInputValue=(e,n)=>{if(this.readonlyKeys.includes(n))throw new Error(`Cannot set readonly key ${n.toString()}`);Di(e)||(e=ae(e,!1));let r=Ne(this.schema,n);if(r){Le(e,r);let o=Fe({field:r,value:e,fieldPath:[...this.fieldPath,n]});if(o)throw new Error(o.message)}return tt(e,this.files.add)};this.getDeleteMode=e=>{if(this.readonlyKeys.includes(e))return!1;if(this.schema.type==="any"||this.schema.type==="map")return"delete";if(this.schema.type==="object"){let n=this.schema.properties[e];if(!n||n.type==="any")return"delete";if(n.type==="map")return!1;if(n.nullable)return"null"}return!1};this.getItemRefValue=e=>{if(e instanceof i)return he(e.oid);if(e instanceof de)return Mt(e.id);if(typeof e=="object"){let n=pe(e);if(!n||!this.entityFamily.has(n))throw new Error(`Cannot move object ${JSON.stringify(e)} which does not exist in this list`);return he(n)}else return e};this.set=(e,n)=>{Zr(e),this.addPendingOperations(this.patchCreator.createSet(this.oid,e,this.processInputValue(n,e)))};this.getAll=()=>this.view;this.delete=e=>{if(this.isList)na(e),this.addPendingOperations(this.patchCreator.createListDelete(this.oid,e));else{let n=this.getDeleteMode(e);if(!n)throw new Error(`Cannot delete key ${e.toString()} - the property is not marked as optional in the schema.`);n==="delete"?this.addPendingOperations(this.patchCreator.createRemove(this.oid,e)):this.addPendingOperations(this.patchCreator.createSet(this.oid,e,null))}};this.keys=()=>this.view?Object.keys(this.view):[];this.entries=()=>this.view?Object.entries(this.view):[];this.values=()=>this.view?Object.values(this.view):[];this.update=(e,{merge:n=!0,replaceSubObjects:r=!1}={})=>{if(!n&&this.schema.type!=="any"&&this.schema.type!=="map")throw new Error('Cannot use .update without merge if the field has a strict schema type. merge: false is only available on "any" or "map" types.');let o={};K(o,this.oid);for(let[s,a]of Object.entries(e)){if(this.readonlyKeys.includes(s))throw new Error(`Cannot set readonly key ${s.toString()}`);let p=Ne(this.schema,s);p&&Le(a,p),o[s]=this.processInputValue(a,s)}this.addPendingOperations(this.patchCreator.createDiff(this.getSnapshot(),o,{mergeUnknownObjects:!r,defaultUndefined:n}))};this.push=e=>{this.addPendingOperations(this.patchCreator.createListPush(this.oid,this.processInputValue(e,this.view.length)))};this.insert=(e,n)=>{this.addPendingOperations(this.patchCreator.createListInsert(this.oid,e,this.processInputValue(n,e)))};this.move=(e,n)=>{this.addPendingOperations(this.patchCreator.createListMoveByIndex(this.oid,e,n))};this.moveItem=(e,n)=>{let r=this.getItemRefValue(e);if(Q(r))this.addPendingOperations(this.patchCreator.createListMoveByRef(this.oid,r,n));else{let o=this.view.indexOf(e);if(o===-1)throw new Error(`Cannot move item ${JSON.stringify(e)} which does not exist in this list`);this.move(o,n)}};this.add=e=>{this.addPendingOperations(this.patchCreator.createListAdd(this.oid,this.processInputValue(e,this.view.length)))};this.removeAll=e=>{this.addPendingOperations(this.patchCreator.createListRemove(this.oid,this.getItemRefValue(e)))};this.removeFirst=e=>{this.addPendingOperations(this.patchCreator.createListRemove(this.oid,this.getItemRefValue(e),"first"))};this.removeLast=e=>{this.addPendingOperations(this.patchCreator.createListRemove(this.oid,this.getItemRefValue(e),"last"))};this.map=e=>this.view.map(e);this.filter=e=>this.view.filter(e);this.has=e=>{if(!this.isList)throw new Error("has() is only available on list entities");let n=this.getItemRefValue(e);return Q(n)?this.view.some(r=>{if(Q(r))return Ye(r,n)}):this.view.includes(e)};this.forEach=e=>{this.view.forEach(e)};this.some=e=>this.view.some(e);this.every=e=>this.view.every(e);this.find=e=>this.view.find(e);this.includes=this.has;this.__getViewData__=(e,n)=>this.metadataFamily.get(e).computeView(n==="confirmed");this.__getFamilyOids__=()=>this.metadataFamily.getAllOids();L(!!e,"oid is required"),this.oid=e,this.readonlyKeys=p||[],this.ctx=s,this.files=l,this.schema=n,this.entityFamily=r||new pn({initial:[this]}),this.patchCreator=m,this.metadataFamily=a,this.events=x,this.parent=o,this.parent||(x.add.attach(this.onAdd),x.replace.attach(this.onReplace),x.resetAll.attach(this.onResetAll))}get metadata(){return this.metadataFamily.get(this.oid)}get viewData(){return this._viewData===void 0&&(this._viewData=this.metadata.computeView(),this.validate()),this._viewData}get rawView(){return this.viewData.view}get view(){if(this.cachedView!==void 0)return this.cachedView;if(this.viewData.deleted)return null;let e=this.rawView;if(!e&&!we(this.schema)||this.schema.type==="array"&&!Array.isArray(e)||(this.schema.type==="object"||this.schema.type==="map")&&!V(e))return Ce(this.schema)?pi(this.schema):null;if(this.cachedView=this.isList?[]:{},K(this.cachedView,this.oid),Array.isArray(e)){let r=Ne(this.schema,0);if(!r)this.ctx.log("error","No child field schema for list entity.",this.oid);else for(let o=0;o<e.length;o++){let s=this.get(o);this.childIsNull(s)&&!we(r)?this.ctx.log("error","Child missing in non-nullable field",this.oid,"index:",o):this.cachedView.push(s)}}else if(V(e)){let r=this.schema.type==="object"?Object.keys(this.schema.properties):Object.keys(e);for(let o of r){let s=Ne(this.schema,o);if(!s){this.ctx.log("error","No child field schema for object entity at key",o),this.schema.type==="map"?this.cachedView={}:this.cachedView=null;break}let a=this.get(o);if(this.childIsNull(a)&&!we(s)){if(this.ctx.log("error","Child entity is missing for non-nullable field",this.oid,"key:",o),this.schema.type!=="map"){this.cachedView=null;break}}else this.cachedView[o]=a}}return this.cachedView}get uid(){return this.oid}get deleted(){return this.viewData.deleted||this.view===null}get invalid(){return!!this.validate()}get isList(){return this.schema.type==="array"||Array.isArray(this.viewData.view)}get updatedAt(){return this.viewData.updatedAt}get deepUpdatedAt(){if(this.cachedDeepUpdatedAt)return this.cachedDeepUpdatedAt;let e=this.updatedAt;return this.isList?this.forEach(n=>{if(n instanceof i){let r=n.deepUpdatedAt;r&&(!e||r>e)&&(e=r)}}):this.values().forEach(n=>{if(n instanceof i){let r=n.deepUpdatedAt;r&&(!e||r>e)&&(e=r)}}),this.cachedDeepUpdatedAt=e,e}get isOutdatedVersion(){return this.parent?this.parent.isOutdatedVersion:this.viewData.fromOlderVersion}get length(){return this.view.length}[Symbol.iterator](){let e=0,n=this.view?.length;return{next:()=>e<n?{value:this.get(e++),done:!1}:{value:void 0,done:!0}}}};function Zr(i){if(typeof i=="symbol")throw new Error("Symbol keys aren't supported")}function na(i){if(typeof i!="number")throw new Error("Only number keys are supported in list entities")}var _i=class{constructor({oid:t,ctx:e,confirmedOperations:n,pendingOperations:r,baseline:o}){this.baseline=null;this.confirmedOperations=[];this.pendingOperations=[];this.computeView=(t=!1)=>{let e=ae(this.baseline?.snapshot??void 0),n=this.baseline?.timestamp??null,r=this.applyOperations(e,!e,this.confirmedOperations,n,n);r.futureSeen&&this.ctx.globalEvents.emit("futureSeen",r.futureSeen);let o=t?r:this.applyOperations(r.view,r.deleted,this.pendingOperations,r.latestTimestamp,null);o.view&&K(o.view,this.oid);let s=!!r.latestTimestamp&&Gn(r.latestTimestamp,this.ctx.getNow())<0,a=!this.baseline&&!this.pendingOperations.length&&!this.confirmedOperations.length;a&&this.ctx.log("warn",`Tried to load Entity ${this.oid} with no data`);let p=o.latestTimestamp??r.latestTimestamp??n,l=p?Xn(p):0;if(!o.view&&!o.deleted&&!a){this.ctx.log("warn",`Entity ${this.oid} has no view, no deleted flag, and not empty`);debugger}return{view:o.view??void 0,deleted:o.deleted,empty:a,fromOlderVersion:s,updatedAt:l}};this.addBaseline=t=>{if(!(this.baseline&&this.baseline.timestamp>=t.timestamp))for(this.baseline=t;this.confirmedOperations[0]?.timestamp<t.timestamp;)this.confirmedOperations.shift()};this.addConfirmedOperations=t=>{let e=0;for(let n of t){let r=this.confirmedOperations.findIndex(s=>s.timestamp>=n.timestamp);r!==-1?this.confirmedOperations[r].timestamp!==n.timestamp&&(this.confirmedOperations.splice(r,0,n),e++):(this.confirmedOperations.push(n),e++);let o=this.pendingOperations.length;this.pendingOperations=this.pendingOperations.filter(s=>n.timestamp!==s.timestamp),e-=o-this.pendingOperations.length}return e};this.addPendingOperation=t=>{this.pendingOperations.push(t)};this.applyOperations=(t,e,n,r,o)=>{let s,a=this.ctx.getNow();for(let p of n)if(!(o&&p.timestamp<=o)){if(Gn(p.timestamp,a)>0){s=p.timestamp;continue}p.data.op==="delete"?e=!0:(t=je(t,p.data),p.data.op==="initialize"&&(e=!1)),(!r||p.timestamp>r)&&(r=p.timestamp)}return{view:t,latestTimestamp:r??null,deleted:e,futureSeen:s}};L(t,"oid is required"),this.ctx=e,this.oid=t,n&&(this.confirmedOperations=n),r&&(this.pendingOperations=r),o&&(this.baseline=o)}},hn=class{constructor({ctx:t,onPendingOperations:e,rootOid:n}){this.entities=new Map;this.get=t=>(L(t,"oid is required"),this.entities.has(t)||this.entities.set(t,new _i({oid:t,ctx:this.ctx})),this.entities.get(t));this.getAllOids=()=>Array.from(this.entities.keys());this.addConfirmedData=({baselines:t=[],operations:e={},isLocal:n=!1})=>{let r={};for(let o of t){if(!Ee(this.rootOid,o.oid))throw new Error(`Invalid baseline for entity ${this.rootOid}: `+JSON.stringify(o));this.get(o.oid).addBaseline(o)}for(let[o,s]of Object.entries(e)){if(!Ee(this.rootOid,o))throw new Error(`Invalid operations for entity ${this.rootOid}: `+JSON.stringify(s));this.get(o).addConfirmedOperations(s)!==0&&(r[o]??={oid:o,isLocal:n})}return Object.values(r)};this.addPendingData=t=>{let e={};for(let n of t)this.get(n.oid).addPendingOperation(n),e[n.oid]??={oid:n.oid,isLocal:!0};return this.onPendingOperations(t),Object.values(e)};this.replaceAllData=({operations:t={},baselines:e=[]})=>{let n=Array.from(this.entities.keys());this.entities.clear();let r={};for(let o of n)r[o]={oid:o,isLocal:!1};for(let o of e){if(!Ee(this.rootOid,o.oid))throw new Error(`Invalid baseline for entity ${this.rootOid}: `+JSON.stringify(o));this.get(o.oid).addBaseline(o),r[o.oid]??={oid:o.oid,isLocal:!1}}for(let[o,s]of Object.entries(t)){if(!Ee(this.rootOid,o))throw new Error(`Invalid operations for entity ${this.rootOid}: `+JSON.stringify(s));this.get(o).addConfirmedOperations(s),r[o]??={oid:o,isLocal:!1}}return Object.values(r)};this.ctx=t,this.rootOid=n,this.onPendingOperations=e}};var Ot="@@default",mn=class{constructor({batchTimeout:t=200,meta:e,ctx:n,entities:r}){this.currentBatchKey=Ot;this.flushOperations=async(t,e,n)=>{if(this.ctx.log("debug","Flushing",t.length,"operations from batch",e,"to storage / sync"),!!t.length){for(let r of t)r.timestamp=this.meta.now;await this.commitOperations(t,n)}};this.commitOperations=async(t,e)=>{if(t.length){if(e.undoable){let n=await this.createUndo({ops:t,source:e.source});n&&this.ctx.undoHistory.addUndo(n)}await this.entities.addData({operations:t,baselines:[],isLocal:!0})}};this.addOperations=t=>{t.length&&(this.batcher.add({key:this.currentBatchKey,items:t}),this.ctx.log("debug","added",t.length,"ops to batch",this.currentBatchKey,", size = ",this.batcher.getSize(this.currentBatchKey)))};this.batch=({undoable:t=!0,batchName:e=Nt(),max:n=null,timeout:r=this.defaultBatchTimeout}={})=>{let o=this.batcher.add({key:e,max:n,timeout:r,items:[],userData:{undoable:t}}),s={run:a=>(this.currentBatchKey=e,a(),this.currentBatchKey=Ot,s),commit:async()=>(await this.batcher.flush(Ot),o.flush()),flush:()=>s.commit(),discard:()=>{this.batcher.discard(e)}};return s};this.flushAll=()=>Promise.all(this.batcher.flushAll());this.createUndo=async t=>{let e=await this.getInverseOperations(t);return e.length?async()=>{let n=await this.createUndo({ops:e,source:t.source});for(let r of e)r.timestamp=this.meta.now;return await this.commitOperations(e,{undoable:!1}),n}:null};this.getInverseOperations=async({ops:t,source:e})=>{let n=mt(t),r=[],o=()=>this.meta.now;return await Promise.all(Object.entries(n).map(async([s,a])=>{let l=(e??await this.entities.hydrate($(s)))?.__getViewData__(s,"confirmed");if(!l){this.ctx.log("warn","could not find entity",s,"for undo operation",t);return}let m=jr(s,l.view,a,o);r.unshift(...m)})),r};this.meta=e,this.ctx=n,this.entities=r,this.defaultBatchTimeout=t,this.batcher=new Xe(this.flushOperations),this.batcher.add({key:Ot,items:[],max:100,timeout:t,userData:{undoable:!0}})}get isDefaultBatch(){return this.currentBatchKey===Ot}};var gn=class extends se{constructor({ctx:e}){super(e.documentDb,{log:e.log});this.reset=async()=>{let e=Object.keys(this.ctx.schema.collections),n=this.ctx.documentDb.transaction(e,"readwrite");await Promise.all(e.map(r=>{let o=n.objectStore(r);return J(o.clear())})),this.ctx.entityEvents.emit("collectionsChanged",e),this.ctx.log("info","\u{1F4A8} Reset queryable storage")};this.saveEntities=async(e,n)=>{if(e.length===0)return;let r=Array.from(new Set(e.map(a=>me(a.oid).collection))),o=r.filter(a=>!this.ctx.schema.collections[a]);if(o.length>0){this.ctx.log("warn",`Ignoring entities from collections that no longer exist: ${o.join(", ")}`);let a=new Set(r);o.forEach(p=>a.delete(p)),r=Array.from(a)}let s={transaction:this.createTransaction(r,{mode:"readwrite",abort:n?.abort})};await Promise.all(e.map(async a=>{let p=a.getSnapshot();try{await this.saveDocument(a.oid,p,s)}catch(l){throw this.ctx.log("error",`Error saving document ${a.oid} (${JSON.stringify(p)})`,l),l instanceof Error?l:new Error("Unknown error saving document")}})),s.transaction.commit(),this.ctx.entityEvents.emit("collectionsChanged",r);for(let a of e)this.ctx.entityEvents.emit("documentChanged",a.oid)};this.saveDocument=async(e,n,{transaction:r})=>{this.ctx.log("debug",`Saving document indexes for querying ${e}`,n);let{collection:o,id:s}=me(e);if(!n)await this.run(o,a=>a.delete(s),{mode:"readwrite",transaction:r}),this.ctx.log("debug",`Deleted document indexes for querying ${e}`);else{let a=this.ctx.schema.collections[o],p=qt(a,n);await this.run(o,l=>l.put(p),{mode:"readwrite",transaction:r}),this.ctx.log("debug",`Saved document indexes for querying ${e}`,n)}};this.ctx=e,this.addDispose(this.ctx.internalEvents.subscribe("documentDbChanged",n=>{this.db=n}))}};var Dn=Qe(ko(),1);var _n=class extends Ie{constructor({ctx:e,meta:n,files:r}){super();this.events={add:new Dn.WeakEvent,replace:new Dn.WeakEvent,resetAll:new Dn.WeakEvent};this.cache=new Map;this.pendingEntityPromises=new Map;this.abortDataQueueController=new AbortController;this.ongoingResetPromise=null;this.entityFinalizationRegistry=new FinalizationRegistry(e=>{this.ctx.log("debug","Entity GC",e)});this.addData=async e=>{if(this.disposed){this.ctx.log("warn","EntityStore is disposed, not adding incoming data");return}e.reset&&(this.ctx.log("info","Resetting local store to replicate remote synced data - dropping any current transactions"),this.abortDataQueueController.abort(0),this.abortDataQueueController=new AbortController,this.ongoingResetPromise=this.resetData().finally(()=>{this.ongoingResetPromise=null})),this.ongoingResetPromise&&(this.ctx.log("debug","Waiting for ongoing reset to complete"),await this.ongoingResetPromise,this.ctx.log("debug","Ongoing reset complete")),await this.processData(e)};this.resetData=async()=>{if(this.disposed){this.ctx.log("warn","EntityStore is disposed, not resetting local data");return}await this.meta.reset(),await this.queryableStorage.reset(),this.events.resetAll.invoke(this)};this.processData=async e=>{if(this.disposed){this.ctx.log("warn","EntityStore is disposed, not processing incoming data");return}let n=e?.baselines??[],r=e?.operations??[];this.ctx.log("debug","Processing incoming data",{operations:r.length,baselines:n.length,reset:!!e.reset});let o=Array.from(new Set(n.map(m=>$(m.oid)).concat(r.map(m=>$(m.oid))))),s=Rr(n),a=Ar(r);this.ctx.log("debug","Applying data to live entities");for(let m of o){let x=s[m],y=a[m]??[],C=mt(y),w=e.reset?this.events.replace:this.events.add,S=this.pendingEntityPromises.get(m);S?S.then(()=>{w.invoke(this,{oid:m,baselines:x,operations:C,isLocal:!1})}):(this.cache.has(m)&&this.ctx.log("debug","Cache has",m,", an event should follow."),w.invoke(this,{oid:m,baselines:x,operations:C,isLocal:!1}))}let p={abort:this.abortDataQueueController.signal};await this.meta.insertData(e,p);let l=await Promise.all(o.map(async m=>await this.hydrate(m,p)??{oid:m,getSnapshot(){return null}}));try{await this.queryableStorage.saveEntities(l,p)}catch(m){this.disposed?this.ctx.log("warn","Error saving entities to queryable storage - EntityStore is disposed",m):this.ctx.log("error","Error saving entities to queryable storage",m)}};this.hydrate=async(e,n)=>{if(!Cr(e))throw new Error("Cannot hydrate non-root entity");if(this.cache.has(e)){this.ctx.log("debug","Hydrating entity from cache",e);let o=this.cache.get(e);if(o){let s=o.deref();if(s)return s.deleted?null:s;this.ctx.log("debug","Removing GC'd entity from cache",e),this.cache.delete(e)}}let r=this.pendingEntityPromises.get(e);if(r)return this.ctx.log("debug","Waiting for entity hydration",e),r;{this.ctx.log("debug","Hydrating entity from storage",e);let o=this.constructEntity(e);if(!o)return null;let s=this.loadEntity(o,n);return s.finally(()=>{this.pendingEntityPromises.delete(e)}),this.pendingEntityPromises.set(e,s),s}};this.destroy=async()=>{this.dispose(),await this.batcher.flushAll()};this.create=async(e,n,{undoable:r=!0}={})=>{this.ctx.log("debug","Creating new entity",n);let{collection:o}=me(n);Ut(e);let s=tt(e,this.files.add);K(s,n);let a=this.constructEntity(n);if(!a)throw new Error(`Could not put new document: no schema exists for collection ${o}`);let p=this.meta.patchCreator.createInitialize(s,n);await this.batcher.commitOperations(p,{undoable:!!r,source:a});let l=mt(p);return this.events.add.invoke(this,{operations:l,isLocal:!0,oid:n}),this.cache.set(n,this.ctx.weakRef(a)),a};this.deleteAll=async(e,n)=>{this.ctx.log("info","Deleting documents",e),L(e.every(s=>s===$(s)),"Only root documents may be deleted via client methods");let r=await Promise.all(e.flatMap(async s=>(await this.hydrate(s))?.__getFamilyOids__()??[]));e.forEach(s=>{this.cache.delete(s),this.ctx.log("debug","Deleted document from cache",s)});let o=this.meta.patchCreator.createDeleteAll(r.flat());await this.batcher.commitOperations(o,{undoable:n?.undoable===void 0?!0:n.undoable})};this.delete=async(e,n)=>this.deleteAll([e],n);this.getCollectionSchema=e=>{let n=this.ctx.schema.collections[e];return n?{schema:{type:"object",nullable:!1,properties:n.fields},readonlyKeys:[n.primaryKey]}:(this.ctx.log("warn",`Missing schema for collection: ${e}`),{schema:null,readonlyKeys:[]})};this.constructEntity=e=>{let{collection:n}=me(e),{schema:r,readonlyKeys:o}=this.getCollectionSchema(n);if(!r)return null;if(this.disposed)throw new Error("Cannot hydrate entity after store has been disposed");let s=new hn({ctx:this.ctx,onPendingOperations:this.onPendingOperations,rootOid:e});return new ue({ctx:this.ctx,oid:e,schema:r,readonlyKeys:o,files:this.files,metadataFamily:s,patchCreator:this.meta.patchCreator,events:this.events})};this.onPendingOperations=e=>{this.batcher.addOperations(e)};this.loadEntity=async(e,n)=>{let{operations:r,baselines:o}=await this.meta.getDocumentData(e.oid,n);return!o.length&&!Object.keys(r).length?(this.ctx.log("debug","No data found for entity",e.oid),null):(this.ctx.log("debug","Loaded entity from storage",e.oid),this.events.replace.invoke(this,{oid:e.oid,baselines:o,operations:r,isLocal:!1}),this.cache.set(e.oid,this.ctx.weakRef(e)),this.entityFinalizationRegistry.register(e,e.oid),e)};this.ctx=e,this.meta=n,this.files=r,this.queryableStorage=new gn({ctx:e}),this.batcher=new mn({ctx:e,meta:n,entities:this})}get batch(){return this.batcher.batch}get flushAllBatches(){return this.batcher.flushAll}};var Vi=Symbol("handleMessage"),ba,Dt=class extends U{constructor({initialPresence:e,updateBatchTimeout:n=200,defaultProfile:r,replicaStore:o}){super();this._peers={};this._self={profile:{}};this._selfReplicaIds=new Set;this._peerIds=new Array;this.isSelf=(e,n)=>e.id===n.replicaId||this._selfReplicaIds.has(n.replicaId)||this._self.id===n.id;this[ba]=async(e,n)=>{let r=!1,o=new Set(this.peerIds);if(n.type==="presence-changed")this.isSelf(e,n.userInfo)?(this._self=n.userInfo,this._selfReplicaIds.add(n.userInfo.replicaId),this.emit("selfChanged",n.userInfo)):(o.add(n.userInfo.id),this._peers[n.userInfo.id]=n.userInfo,r=!0,this.emit("peerChanged",n.userInfo.id,n.userInfo));else if(n.type==="sync-resp"){this._peers={},o.clear();for(let[s,a]of Object.entries(n.peerPresence))this.isSelf(e,a)?(this._self=a,this._selfReplicaIds.add(a.replicaId),this.emit("selfChanged",a)):(r=!0,o.add(s),this._peers[s]=a,this.emit("peerChanged",s,a))}else if(n.type==="presence-offline"){o.delete(n.userId),this._selfReplicaIds.delete(n.replicaId);let s=this._peers[n.userId];delete this._peers[n.userId],r=!0,this.emit("peerLeft",n.userId,s)}r&&(this._peerIds=Array.from(o),this.emit("peersChanged",this._peers))};this.update=async e=>{this._updateBatch.update({items:[e]}),this.self.presence={...this.self.presence,...e},this.emit("selfChanged",this.self)};this.flushPresenceUpdates=e=>{let n=e.reduce((r,o)=>({...r,...o}),this.self.presence);this.emit("update",n)};this.self.presence=e,this.self.profile=r,this.self.id="",this.self.replicaId="",o.get().then(s=>{this.self.replicaId=s.id}),this._updateBatcher=new Xe(this.flushPresenceUpdates),this._updateBatch=this._updateBatcher.add({max:25,timeout:n,items:[],key:"default"})}static{ba=Vi}get self(){return this._self}get peers(){return this._peers}get peerIds(){return this._peerIds}get everyone(){let e={...this._peers};return e[this.self.id]=this.self,e}get selfReplicaIds(){return this._selfReplicaIds}};var En=class{constructor({endpointProvider:t,log:e}){this.uploadFile=async t=>{let e=t.file;if(!e)throw new Error("Cannot upload a non-local file");let{files:n,token:r}=await this.endpointProvider.getEndpoints(),o=new window.FormData;o.append("file",e);try{let s=await fetch(n+`/${t.id}`,{method:"POST",body:o,credentials:"include",headers:{Authorization:`Bearer ${r}`}});return s.ok?(this.log("info","File upload successful"),{success:!0,retry:!1}):(this.log("error","File upload failed",s.status,await s.text()),{success:!1,retry:s.status>=500})}catch(s){return this.log("error","File upload failed",s),{success:!1,retry:!0}}};this.getFile=async t=>{let{files:e,token:n}=await this.endpointProvider.getEndpoints();try{let r=await fetch(e+`/${t}`,{method:"GET",credentials:"include",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`}});return r.ok?{success:!0,data:await r.json()}:(this.log("error","File information fetch failed",r.status,await r.text()),{success:!1,retry:r.status>=500||r.status===404})}catch(r){return this.log("error","File information fetch failed",r),{success:!1,error:r,retry:!0}}};this.endpointProvider=t,this.log=e}};var it=class extends U{constructor({interval:e=15*1e3,deadlineLength:n=3*1e3,restartOnTabFocus:r=!0}={}){super();this.nextBeat=null;this.deadline=null;this.keepAlive=()=>{this.deadline&&(clearTimeout(this.deadline),this.deadline=null,this.start())};this.start=(e=!1)=>{this.stop(),e?this.beat():this.nextBeat=setTimeout(this.beat,this._interval)};this.stop=()=>{this.nextBeat&&clearTimeout(this.nextBeat),this.deadline&&clearTimeout(this.deadline)};this.beat=async()=>{this.emit("beat"),this.deadline=setTimeout(this.onDeadline,this.deadlineLength)};this.onDeadline=()=>{this.deadline=null,this.emit("missed")};this.setInterval=e=>{this._interval=e};this._interval=e,this.deadlineLength=n,typeof window<"u"&&r&&(window.addEventListener("pageshow",()=>this.start(!0)),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&this.start(!0)}))}get interval(){return this._interval}};var Cn=class extends U{constructor({endpointProvider:e,meta:n,presence:r,interval:o=15*1e3,log:s=()=>{},fetch:a=window.fetch}){super();this.mode="pull";this._isConnected=!1;this._status="paused";this._hasSynced=!1;this.setInterval=e=>{this.heartbeat.setInterval(e)};this.sendRequest=async e=>{this.log("Sending sync request",e);try{let{http:n,token:r}=await this.endpointProvider.getEndpoints(),o=await this.fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({messages:e}),credentials:"include"});if(o.ok){this.heartbeat.keepAlive();let s=await o.json();for(let a of s.messages)this.handleServerMessage(a);this._isConnected||(this._isConnected=!0,this.emit("onlineChange",!0))}else{this.log("Sync request failed",o.status,await o.text()),this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1));let s=await o.json();Ur(s)&&s.code===4012&&(this.endpointProvider.clearCache(),this.heartbeat.keepAlive()),o.status>=500&&this.heartbeat.keepAlive()}}catch(n){this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1)),this.log(n),this.heartbeat.keepAlive()}};this.handleServerMessage=async e=>{e.type==="sync-resp"&&(e.ackThisNonce&&(this.log("Sending sync ack",e.ackThisNonce),this.sendRequest([await this.meta.messageCreator.createAck(e.ackThisNonce)])),this._hasSynced=!0),this.emit("message",e)};this.send=e=>{switch(e.type){case"presence-update":case"sync":case"heartbeat":return this.sendRequest([e]);case"op":if(this._hasSynced)return this.sendRequest([e]);break}};this.destroy=()=>{this.dispose(),this.stop()};this.onHeartbeat=async()=>{this.sendRequest([await this.meta.messageCreator.createPresenceUpdate(this.presence.self.presence),await this.meta.messageCreator.createSyncStep1()])};this.onHeartbeatMissed=async()=>{this.emit("onlineChange",!1),this.log("Missed heartbeat"),this._isConnected=!1};this.log=s,this.meta=n,this.presence=r,this.endpointProvider=e,this.fetch=a,this.heartbeat=new it({interval:o}),this.heartbeat.subscribe("beat",this.onHeartbeat),this.heartbeat.subscribe("missed",this.onHeartbeatMissed)}get interval(){return this.heartbeat.interval}start(){this.status!=="active"&&(this.heartbeat.start(!0),this._status="active")}stop(){this.heartbeat.stop(),this._status="paused"}reconnect(){this.heartbeat.start(!0)}ignoreIncoming(){this.stop()}get isConnected(){return this._isConnected}get status(){return this._status}};function Ki(i){this.message=i}Ki.prototype=new Error,Ki.prototype.name="InvalidCharacterError";var Bo=typeof window<"u"&&window.atob&&window.atob.bind(window)||function(i){var t=String(i).replace(/=+$/,"");if(t.length%4==1)throw new Ki("'atob' failed: The string to be decoded is not correctly encoded.");for(var e,n,r=0,o=0,s="";n=t.charAt(o++);~n&&(e=r%4?64*e+n:n,r++%4)?s+=String.fromCharCode(255&e>>(-2*r&6)):0)n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(n);return s};function wa(i){var t=i.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(Bo(e).replace(/(.)/g,function(n,r){var o=r.charCodeAt(0).toString(16).toUpperCase();return o.length<2&&(o="0"+o),"%"+o}))}(t)}catch{return Bo(t)}}function Pn(i){this.message=i}function va(i,t){if(typeof i!="string")throw new Pn("Invalid token specified");var e=(t=t||{}).header===!0?0:1;try{return JSON.parse(wa(i.split(".")[e]))}catch(n){throw new Pn("Invalid token specified: "+n.message)}}Pn.prototype=new Error,Pn.prototype.name="InvalidTokenError";var Mo=va;var An=class{constructor(t){this.config=t;this.cached=null;this.type=0;this.getEndpoints=async()=>{if(this.cached)return this.cached;let t;this.config.fetchAuth?t=await this.config.fetchAuth():t=await(this.config.fetch||fetch)(this.config.authEndpoint,{credentials:"include"}).then(p=>{if(p.ok)return p.json();throw new Error(`Auth endpoint returned non-200 response: ${p.status}`)}),L(t.accessToken,"No access token provided from auth endpoint");let e=Mo(t.accessToken);L(e.url,"No sync endpoint provided from auth endpoint"),L(e.type!==void 0,"No replica type provided from auth endpoint"),this.type=parseInt(e.type+"");let n=new URL(e.url);n.protocol=n.protocol.replace("ws","http");let r=n.toString();n.protocol=n.protocol.replace("http","ws");let o=n.toString(),s=e.file;if(!s){let a=new URL(r);a.pathname=a.pathname+"/files",s=a.toString()}return this.cached={http:r,websocket:o,files:s,token:t.accessToken},this.cached};this.clearCache=()=>{this.cached=null};if(!t.authEndpoint&&!t.fetchAuth)throw new Error("Either authEndpoint or fetchAuth must be provided to ServerSyncEndpointProvider")}};var Rn=class extends U{constructor(e){super();this.timer=null;this.isScheduled=!1;this.next=()=>{this.isScheduled||(this.isScheduled=!0,this.timer=setTimeout(()=>{this.emit("trigger"),this.isScheduled=!1,this.backoff.next()},this.backoff.current))};this.reset=()=>{this.backoff.reset(),this.timer&&(clearTimeout(this.timer),this.timer=null)};this.backoff=e}},Tn=class{constructor(t,e){this.current=0;this.next=()=>{this.current=Math.min(this.max,this.current*this.factor)};this.reset=()=>{this.current=0};this.max=t,this.factor=e}};var Fn=class extends U{constructor({endpointProvider:e,meta:n,presence:r,log:o}){super();this.socket=null;this.connectQueue=[];this.syncQueue=[];this.incomingQueue=[];this._status="paused";this.synced=!1;this.hasStartedSync=!1;this._ignoreIncoming=!1;this.mode="realtime";this.log=(...e)=>{};this.heartbeat=new it;this.reconnectScheduler=new Rn(new Tn(60*1e3,1.5));this.onOpen=()=>{if(!this.socket)throw new Error("Invalid sync state: online but socket is null");if(this.synced=!1,this.connectQueue.length){for(let e of this.connectQueue)this.log("Sending queued message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e));this.connectQueue=[]}this.log("Sync connected"),this.onOnlineChange(!0),this.reconnectScheduler.reset()};this.onOnlineChange=async e=>{this.log("Socket online change",e),!this.disposed&&(e?(this.log("Starting sync"),this.hasStartedSync=!0,this.synced=!1,this.send(await this.meta.messageCreator.createPresenceUpdate(this.presence.self.presence)),this.send(await this.meta.messageCreator.createSyncStep1()),this.heartbeat.start()):(this.hasStartedSync=!1,this.synced=!1,this.heartbeat.stop()),this.emit("onlineChange",e))};this.onMessage=async e=>{if(this._ignoreIncoming){this.log("Ignoring incoming message (ignore incoming flag set)",e.data);return}let n=JSON.parse(e.data);switch(n.type){case"sync-resp":if(n.ackThisNonce&&this.send(await this.meta.messageCreator.createAck(n.ackThisNonce)),this.hasStartedSync=!0,this.synced=!0,this.syncQueue.length)if(n.overwriteLocalData)this.log("warn","Overwriting local data - dropping outgoing message queue"),this.syncQueue=[];else{for(let r of this.syncQueue)this.send(r);this.syncQueue=[]}if(this.emit("message",n),this.incomingQueue.length){for(let r of this.incomingQueue)this.emit("message",r);this.incomingQueue=[]}break;case"need-since":case"presence-changed":case"presence-offline":this.emit("message",n);break;case"op-re":if(!this.synced){this.log("Enqueueing op-re message because sync hasn't finished yet",n),this.incomingQueue.push(n);break}this.emit("message",n);break;case"heartbeat-response":this.heartbeat.keepAlive(),this.emit("message",n);break;default:this.synced&&this.emit("message",n);break}};this.onError=e=>{this.log(e),this.reconnectScheduler.next(),this.log("Attempting reconnect to websocket sync")};this.onClose=e=>{this.log("Sync disconnected"),this.onOnlineChange(!1),this.onError(e)};this.initializeSocket=async()=>{let e=await this.endpointProvider.getEndpoints();return this.socket=new WebSocket(e.websocket,["Bearer",e.token]),this.socket.addEventListener("message",this.onMessage),this.socket.addEventListener("open",this.onOpen),this.socket.addEventListener("error",this.onError),this.socket.addEventListener("close",this.onClose),this.socket};this.sendHeartbeat=async()=>{this.send(await this.meta.messageCreator.createHeartbeat())};this.reconnect=()=>{this.stop(),this.start()};this.canSkipSyncWait=e=>e.type==="sync"||e.type==="presence-update"||e.type==="sync-ack"||e.type==="heartbeat";this.send=e=>{this.status==="active"&&(!this.hasStartedSync&&!this.canSkipSyncWait(e)||(this.canSkipSyncWait(e)?this.socket?.readyState===WebSocket.OPEN?(this.log("Sending message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e))):(this.log("Enqueueing message until socket is open",JSON.stringify(e,null,2)),this.connectQueue.push(e)):this.synced?this.socket?.readyState===WebSocket.OPEN&&(this.log("Sending message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e))):this.hasStartedSync&&(this.log("Enqueueing message until synced",JSON.stringify(e,null,2)),this.syncQueue.push(e))))};this.destroy=()=>{this.dispose(),this.stop()};this.start=()=>{this.socket||(this.initializeSocket(),this._status="active")};this.stop=()=>{this.socket?.removeEventListener("message",this.onMessage),this.socket?.removeEventListener("close",this.onClose),this.socket?.close(),this.socket=null,this._status="paused"};this.log=o||this.log,this.endpointProvider=e,this.meta=n,this.presence=r,this.reconnectScheduler.subscribe("trigger",this.initializeSocket),this.heartbeat.subscribe("beat",this.sendHeartbeat)}ignoreIncoming(){this.incomingQueue=[],this._ignoreIncoming=!0}get isConnected(){return this.socket?.readyState===WebSocket.OPEN}get status(){return this._status}};var kn=class extends U{constructor({meta:e}){super();this.mode="pull";this.destroy=()=>{};this.isConnected=!1;this.status="paused";this.pullInterval=0;this.uploadFile=async()=>({success:!1,retry:!1});this.getFile=async()=>({success:!1,retry:!1});this.presence=new Dt({initialPresence:null,defaultProfile:null,replicaStore:e.localReplica})}send(){}start(){}stop(){}ignoreIncoming(){}reconnect(){}setMode(){}setPullInterval(){}},rt=class extends U{constructor({authEndpoint:e,fetchAuth:n,fetch:r,initialPresence:o,automaticTransportSelection:s=!0,autoStart:a,initialTransport:p,pullInterval:l,presenceUpdateBatchTimeout:m,defaultProfile:x,useBroadcastChannel:y},{meta:C,log:w,onData:S}){super();this.broadcastChannel=null;this._activelySyncing=!1;this.handleBroadcastChannelMessage=e=>{e.data.type==="sync"&&this.handleMessage(e.data.message,{source:"broadcastChannel"})};this.onTokenExpired=()=>{this.endpointProvider.clearCache()};this.handleMessage=async(e,{source:n}={source:"network"})=>{if(e.type==="op-re"||e.type==="sync-resp")for(let r of e.operations)this.meta.time.update(r.timestamp);switch(this.log("sync message",JSON.stringify(e,null,2)),e.type){case"op-re":await this.onData({operations:e.operations,baselines:e.baselines}),e.globalAckTimestamp&&await this.meta.setGlobalAck(e.globalAckTimestamp);break;case"global-ack":await this.meta.setGlobalAck(e.timestamp);break;case"sync-resp":this._activelySyncing=!0,this.emit("syncingChange",!0),await this.onData({operations:e.operations,baselines:e.baselines,reset:e.overwriteLocalData}),e.globalAckTimestamp&&await this.meta.setGlobalAck(e.globalAckTimestamp),await this.meta.updateLastSynced(e.ackedTimestamp),this._activelySyncing=!1,this.emit("syncingChange",!1);break;case"need-since":this.activeSync.send(await this.meta.messageCreator.createSyncStep1(e.since));break;case"server-ack":await this.meta.updateLastSynced(e.timestamp)}n==="network"&&this.broadcastChannel?.postMessage({type:"sync",message:e}),this.presence[Vi](await this.meta.localReplica.get(),e)};this.handleOnlineChange=e=>{this.emit("onlineChange",e)};this.handlePresenceUpdate=async e=>{this.send(await this.meta.messageCreator.createPresenceUpdate(e))};this.setMode=e=>{if(e==="realtime"&&!this.canDoRealtime)throw new Error("Cannot switch to realtime mode, because the current auth token does not allow it");let n;e==="realtime"?n=this.webSocketSync:n=this.pushPullSync,n!==this.activeSync&&(this.log("debug","switching to",e,"mode"),this.activeSync.status==="active"&&n.start(),this.activeSync.stop(),this.activeSync=n)};this.setPullInterval=e=>{this.pushPullSync.setInterval(e)};this.send=e=>{if(this.activeSync.status==="active")return this.activeSync.send(e)};this.uploadFile=async e=>(this.log("info","Uploading file",{name:e.name,type:e.type,id:e.id}),this.activeSync.status==="active"?this.fileSync.uploadFile(e):{success:!1,retry:!1});this.getFile=async e=>{if(this.activeSync.status==="active")return this.fileSync.getFile(e);throw new Error("Offline, cannot retrieve remote file details")};this.start=()=>this.activeSync.start();this.stop=()=>this.activeSync.stop();this.destroy=()=>{this.dispose(),this.webSocketSync.destroy(),this.pushPullSync.destroy()};this.reconnect=()=>this.activeSync.reconnect();if(this.meta=C,this.onData=S,this.log=w||(()=>{}),this.presence=new Dt({initialPresence:o,defaultProfile:x,updateBatchTimeout:m,replicaStore:C.localReplica}),this.endpointProvider=new An({authEndpoint:e,fetchAuth:n,fetch:r}),this.webSocketSync=new Fn({endpointProvider:this.endpointProvider,meta:C,presence:this.presence,log:this.log}),this.pushPullSync=new Cn({endpointProvider:this.endpointProvider,meta:C,presence:this.presence,log:this.log,interval:l,fetch:r}),this.fileSync=new En({endpointProvider:this.endpointProvider,log:this.log}),y&&"BroadcastChannel"in window&&(this.broadcastChannel=new BroadcastChannel("verdant"),this.broadcastChannel.addEventListener("message",this.handleBroadcastChannelMessage)),p==="realtime"?this.activeSync=this.webSocketSync:this.activeSync=this.pushPullSync,this.presence.subscribe("update",this.handlePresenceUpdate),this.meta.subscribe("message",this.send),this.webSocketSync.subscribe("message",this.handleMessage),this.webSocketSync.subscribe("onlineChange",this.handleOnlineChange),this.pushPullSync.subscribe("message",this.handleMessage),this.pushPullSync.subscribe("onlineChange",this.handleOnlineChange),s&&this.canDoRealtime){let I=()=>{v&&clearTimeout(v);let R=Object.keys(this.presence.peers).length>0||s!=="peers-only"&&this.presence.selfReplicaIds.size>1;R&&this.mode==="pull"?this.setMode("realtime"):!R&&this.mode==="realtime"&&(v=setTimeout(()=>{Object.keys(this.presence.peers).length===0&&this.setMode("pull")},1e3))},v;this.presence.subscribe("peersChanged",I),s!=="peers-only"&&this.presence.subscribe("selfChanged",I)}a&&this.start()}get canDoRealtime(){return this.endpointProvider.type===0||this.endpointProvider.type===2||this.endpointProvider.type===5}get syncing(){return this._activelySyncing}get pullInterval(){return this.pushPullSync.interval}ignoreIncoming(){this.activeSync.ignoreIncoming()}get isConnected(){return this.activeSync.isConnected}get status(){return this.activeSync.status}get mode(){return this.activeSync.mode}};function xa(i){return i!==null}function $i(i){return Array.isArray(i)?i.map($i).filter(xa):i instanceof ue&&i.deleted?null:i}function ke(i,t){return!i&&!t||i&&t&&Re(i)===Re(t)}var zi=Symbol("ON_ALL_UNSUBSCRIBED"),fe=Symbol("UPDATE"),Oa,ge=class extends Ie{constructor({initial:e,context:n,collection:r,key:o,shouldUpdate:s}){super();this._internalUnsubscribes=[];this._status="initial";this._executionPromise=null;this.setValue=e=>{if(this._rawValue=e,this.subscribeToDeleteAndRestore(this._rawValue),this._value=$i(e),Array.isArray(this._value)&&this._value.some(n=>n.getSnapshot()===null))debugger;this._status="ready",this._events.emit("change",this._value)};this.refreshValue=()=>{this.setValue(this._rawValue)};this.subscribeToDeleteAndRestore=e=>{for(;this._internalUnsubscribes.length;)this._internalUnsubscribes.pop()?.();Array.isArray(e)?e.forEach(n=>{n instanceof ue&&(this._internalUnsubscribes.push(n.subscribe("delete",this.refreshValue)),this._internalUnsubscribes.push(n.subscribe("restore",this.refreshValue)))}):e instanceof ue&&(this._internalUnsubscribes.push(e.subscribe("delete",this.refreshValue)),this._internalUnsubscribes.push(e.subscribe("restore",()=>{this.refreshValue()})))};this.execute=()=>(this.context.log("debug","Executing query",this.key),this._status==="initial"?this._status="initializing":this._status==="ready"&&(this._status="revalidating"),this._executionPromise=this.run().then(()=>this._value).catch(e=>{if(e instanceof Error){if(e.name==="InvalidStateError"||e.name==="InvalidAccessError")return this._value;throw e}else throw new Error("Unknown error executing query")}),this._executionPromise);this[Oa]=e=>{this._allUnsubscribedHandler=e};this._rawValue=e,this._value=e,this._events=new U(p=>{p==="change"&&this._allUnsubscribedHandler?.(this)}),this.context=n,this.key=o,this.collection=r;let a=s||(p=>p.includes(r));this.addDispose(this.context.entityEvents.subscribe("collectionsChanged",p=>{a(p)&&(this.context.log("info","Updating query",this.key),this.execute())}))}static{Oa=zi}get current(){return this._value}get resolved(){return this.status==="ready"?Promise.resolve(this._value):this._executionPromise??this.execute()}get subscribed(){return this._events.totalSubscriberCount()>0}get status(){return this._status}subscribe(e,n){if(n===void 0&&typeof e=="function")return this.resolved,this._events.subscribe("change",e);if(e==="change"&&n!==void 0)return this.resolved,this._events.subscribe("change",n);if(e==="statusChange"&&typeof n=="function")return this._events.subscribe(e,n);throw new Error("Invalid invocation of Query.subscribe")}};var Bn=class extends ge{constructor({id:e,hydrate:n,...r}){super({initial:null,...r});this.run=async()=>{let e=await this.hydrate(this.oid);this.setValue(e)};this.oid=Z(r.collection,e),this.hydrate=n}};var Ia,Mn=class extends ge{constructor({index:e,hydrate:n,...r}){super({initial:null,...r});this.run=async()=>{let e=await sn({collection:this.collection,index:this.index,context:this.context});this.setValue(e?await this.hydrate(e):null)};this[Ia]=e=>{ke(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n}static{Ia=fe}};var Da,jn=class extends ge{constructor({index:e,hydrate:n,pageSize:r,page:o,...s}){super({initial:[],...s});this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:n}=await wt({collection:this.collection,index:this.index,context:this.context,limit:this._pageSize,offset:this._page*this._pageSize});this._hasNextPage=n,this.setValue(await Promise.all(e.map(this.hydrate)))};this.nextPage=async()=>{this.hasNextPage&&(this._page++,await this.run())};this.previousPage=async()=>{this._page!==0&&(this._page--,await this.run())};this.setPage=async e=>{this._page=e,await this.run()};this[Da]=e=>{ke(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n,this._pageSize=r,this._page=o}static{Da=fe}get pageSize(){return this._pageSize}get page(){return this._page}get hasNextPage(){return this._hasNextPage}get hasPreviousPage(){return this._page>0}};var _a,Ln=class extends ge{constructor({hydrate:e,pageSize:n,index:r,...o}){super({initial:[],...o});this._upToPage=1;this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:n}=await wt({collection:this.collection,context:this.context,limit:this._pageSize*this._upToPage,offset:0,index:this.index});this._hasNextPage=n,this.setValue(await Promise.all(e.map(this.hydrate)))};this.loadMore=async()=>{let{result:e,hasNextPage:n}=await wt({collection:this.collection,context:this.context,limit:this._pageSize,offset:this._pageSize*this._upToPage,index:this.index});this._hasNextPage=n,this._upToPage++,this.setValue([...this.current,...await Promise.all(e.map(this.hydrate))])};this[_a]=e=>{ke(this.index,e)||(this.index=e,this.execute())};this.index=r,this.hydrate=e,this._pageSize=n}static{_a=fe}get pageSize(){return this._pageSize}get hasMore(){return this._hasNextPage}};var Ea,Nn=class extends ge{constructor({index:e,hydrate:n,...r}){super({initial:[],...r});this.run=async()=>{let e=await an({collection:this.collection,index:this.index,context:this.context});this.context.log("debug",`FindAllQuery: ${e.length} oids found: ${e}`),this.setValue(await Promise.all(e.map(this.hydrate)))};this[Ea]=e=>{ke(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n}static{Ea=fe}};var Un=class{constructor({collection:t,cache:e,entities:n,context:r,documentManager:o}){this.serializeIndex=t=>t?Re(t):"";this.get=t=>{let e=`get:${this.collection}:${t}`;return this.cache.getOrSet(e,()=>new Bn({id:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:e}))};this.findOne=({index:t,key:e}={})=>{let n=e||`findOne:${this.collection}:${this.serializeIndex(t)}`;return this.cache.getOrSet(n,()=>new Mn({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:n}),r=>{r[fe](t)})};this.findAll=({index:t,key:e}={})=>{let n=e||`findAll:${this.collection}:${this.serializeIndex(t)}`;return this.cache.getOrSet(n,()=>new Nn({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:n}),r=>{r[fe](t)})};this.findPage=({index:t,pageSize:e,page:n,key:r})=>{let o=r||`findPage:${this.collection}:${this.serializeIndex(t)}:${e}`;return this.cache.getOrSet(o,()=>new jn({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:o,pageSize:e,page:n}),s=>{s[fe](t)})};this.findAllInfinite=({index:t,pageSize:e,key:n})=>{let r=n||`findAllInfinite:${this.collection}:${this.serializeIndex(t)}:${e}`;return this.cache.getOrSet(r,()=>new Ln({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:r,pageSize:e}),o=>{o[fe](t)})};this.cache=e,this.collection=t,this.hydrate=n.hydrate,this.context=r,this.documentManager=o,this.put=this.documentManager.create.bind(this.documentManager,this.collection),this.delete=this.documentManager.delete.bind(this.documentManager,this.collection),this.deleteAll=this.documentManager.deleteAllFromCollection.bind(this.documentManager,this.collection)}};var Vn=class extends Ie{constructor({evictionTime:e=5*1e3,context:n}){super();this._cache=new Map;this.onQueryUnsubscribed=e=>{setTimeout(()=>{e.subscribed||this._cache.get(e.key)===e&&this._cache.delete(e.key)},this._evictionTime)};this.dropAll=()=>{this._cache.forEach(e=>e.dispose()),this._cache.clear()};this._evictionTime=e,this.context=n}get(e){return this._cache.get(e)||null}set(e){return this._cache.set(e.key,e),e[zi](this.onQueryUnsubscribed),e}getOrSet(e,n,r){let o=this.get(e);return o?(r?.(o),o):this.set(n())}};var He=class extends U{constructor(e,n,r){super();this.config=e;this.context=n;this._closed=!1;this.addData=e=>this._entities.addData(e);this.stats=async()=>{let e=Object.keys(this.schema.collections),n={};for(let l of e)try{n[l]=await yt(this.documentDb,l)}catch(m){this.context.log?.("error",m)}let r=await this.meta.stats(),o=typeof navigator<"u"&&typeof navigator.storage<"u"&&"estimate"in navigator.storage?await navigator.storage.estimate():void 0,s=Object.values(n).reduce((l,{size:m})=>l+m,0),a=r.baselinesSize.size+r.operationsSize.size,p=a/s;return{collections:n,meta:r,storage:o,totalMetaSize:a,totalCollectionsSize:s,metaToDataRatio:p,quotaUsage:o?.usage&&o?.quota?o.usage/o.quota:void 0}};this.close=async()=>{this._closed=!0,this.sync.ignoreIncoming(),await this._entities.flushAllBatches(),this.sync.stop(),this.sync.destroy(),await this._entities.destroy(),this.meta.close(),await new Promise(async e=>{await Ke(this.documentDb),await Ke(this.metaDb),e()}),this.context.log?.("Client closed")};this.__dangerous__resetLocal=async()=>{this.sync.stop(),await Jt(this.namespace,indexedDB)};this.export=async()=>{let e=await this.meta.export();return Buffer.from(JSON.stringify(e))};this.import=async e=>{this.context.log("Importing data..."),await Ke(this.context.documentDb);let n=JSON.parse(e.toString());await this.meta.resetFrom(n);let r=n.schema.version,o=indexedDB.deleteDatabase([this.namespace,"collections"].join("_"));await new Promise((a,p)=>{o.onsuccess=a,o.onerror=p});let s=this.context.schema;this.context.schema=n.schema,this.context.documentDb=await vt({meta:this.meta,migrations:this.config.migrations,context:this.context,version:r}),this.context.internalEvents.emit("documentDbChanged",this.documentDb),this.context.log("Re-initializing data from imported data..."),await this._entities.addData({operations:n.operations,baselines:n.baselines,reset:!0}),await Ke(this.context.documentDb),this.context.log("Migrating up to latest schema..."),this.context.schema=s,this.context.documentDb=await vt({meta:this.meta,migrations:this.config.migrations,context:this.context,version:s.version}),this.context.internalEvents.emit("documentDbChanged",this.documentDb)};this.meta=r.meta,this.collectionNames=Object.keys(n.schema.collections),this._sync=this.config.syncConfig&&!n.schema.wip?new rt(this.config.syncConfig,{meta:this.meta,onData:this.addData,log:this.context.log}):new kn({meta:this.meta}),n.schema.wip&&this.config.syncConfig&&n.log("warn","\u26A0\uFE0F\u26A0\uFE0F Sync is disabled for WIP schemas. Commit your schema changes to start syncing again. \u26A0\uFE0F\u26A0\uFE0F"),this._fileManager=new fn({db:this.metaDb,sync:this.sync,context:this.context,config:this.config.files,meta:this.meta}),this._entities=new _n({ctx:this.context,meta:this.meta,files:this._fileManager}),this._queryCache=new Vn({context:n}),this._documentManager=new dn(this.meta,this.schema,this._entities);let o=Ir(()=>{this.emit("futureSeen")},300);this.context.globalEvents.subscribe("futureSeen",o),this.documentDb.addEventListener("versionchange",()=>{this.context.log?.(`Another tab has requested a version change for ${this.namespace}`),this.documentDb.close(),typeof window<"u"&&window.location.reload()}),this.metaDb.addEventListener("versionchange",()=>{this.context.log?.(`Another tab has requested a version change for ${this.namespace}`),this.metaDb.close(),typeof window<"u"&&window.location.reload()});for(let[s,a]of Object.entries(n.schema.collections)){let p=s;this[p]=new Un({collection:p,cache:this._queryCache,context:this.context,entities:this.entities,documentManager:this.documentManager})}}get sync(){return this._sync}get entities(){return this._entities}get documentManager(){return this._documentManager}get documentDb(){return this.context.documentDb}get metaDb(){return this.context.metaDb}get schema(){return this.context.schema}get namespace(){return this.context.namespace}get undoHistory(){return this.context.undoHistory}get presence(){return this.sync.presence}get batch(){return this.entities.batch}};var _t=class{constructor(t){this.value=t}deref(){return this.value}};var jo=Symbol("metadataVersion");var Kn=class{constructor(t){this.init=t;this._initializing=!1;this.initialize=async t=>{if(typeof window>"u"&&!t.indexedDb)throw new Error("A verdant client was initialized in an environment without IndexedDB. If you are using verdant in a server-rendered framework, you must enforce that all clients are initialized on the client-side, or you must provide some mock interface of IDBFactory to the ClientDescriptor options.");if(this._initializing||this._resolvedValue)return this._readyPromise;this._initializing=!0;try{let e;return t.schema.wip?e=await this.initializeWIPDatabases(t):(e=await this.initializeDatabases(t),this.cleanupWIPDatabases(t)),this.resolveReady(e),this._resolvedValue=e,e}catch(e){throw e instanceof Error?(this.rejectReady(e),e):new Error("Unknown error initializing storage")}finally{this._initializing=!1}};this.initializeDatabases=async t=>{let e=t[jo],{db:n}=await rn({indexedDB:t.indexedDb,log:t.log,namespace:t.namespace,metadataVersion:e}),r={namespace:this._namespace,metaDb:n,schema:t.schema,log:t.log||(()=>{}),undoHistory:t.undoHistory||new St,entityEvents:new U,globalEvents:new U,internalEvents:new U,weakRef:m=>t.EXPERIMENTAL_weakRefs?new WeakRef(m):new _t(m),migrations:t.migrations},o=new bt({context:r,disableRebasing:t.disableRebasing});await o.updateSchema(t.schema,t.overrideSchemaConflict);let s=Object.assign(r,{getNow:()=>o.now}),a=await vt({context:s,version:t.schema.version,meta:o,migrations:t.migrations,indexedDB:t.indexedDb}),p=Object.assign(s,{documentDb:a});return new He({syncConfig:t.sync,migrations:t.migrations,files:t.files},p,{meta:o})};this.initializeWIPDatabases=async t=>{let e=Re(t.schema);console.info(`WIP schema in use. Opening database with hash ${e}`);let n=`@@wip_${t.namespace}_${e}`,{db:r}=await qr({indexedDB:t.indexedDb,log:t.log,namespace:t.namespace,wipNamespace:n}),o={namespace:this._namespace,metaDb:r,schema:t.schema,log:t.log||(()=>{}),undoHistory:t.undoHistory||new St,entityEvents:new U,globalEvents:new U,internalEvents:new U,weakRef:x=>t.EXPERIMENTAL_weakRefs?new WeakRef(x):new _t(x),migrations:t.migrations},s=new bt({context:o,disableRebasing:t.disableRebasing}),a=Object.assign(o,{getNow:()=>s.now});await s.updateSchema(t.schema,t.overrideSchemaConflict);let p=await Jr({context:a,version:t.schema.version,meta:s,migrations:t.migrations,indexedDB:t.indexedDb,wipNamespace:n}),l=Object.assign(a,{documentDb:p});return new He({syncConfig:t.sync,migrations:t.migrations,files:t.files},l,{meta:s})};this.cleanupWIPDatabases=async t=>{let r=(await $r(t.indexedDb)).filter(o=>o.name?.startsWith("@@wip_")).map(o=>o.name).filter(o=>!o.startsWith(`@@wip_${t.namespace}_${Re(t.schema)}`));for(let o of r)await Kr(o,t.indexedDb)};this.open=()=>this.initialize(this.init);this.close=async()=>{this._resolvedValue&&this._resolvedValue.close(),this._initializing&&(await this._readyPromise).close()};this.__dangerous__resetLocal=async()=>{await Jt(this.namespace)};this._readyPromise=new Promise((e,n)=>{this.resolveReady=e,this.rejectReady=n}),this._namespace=t.namespace}get namespace(){return this._namespace}get current(){return this._resolvedValue}get readyPromise(){return this._readyPromise}get schema(){return this.init.schema}};window.Verdant=qi;
|
|
16
16
|
//# sourceMappingURL=index.js.map
|