@verdant-web/store 4.2.0 → 4.3.0

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.
@@ -1,14 +1,16 @@
1
- "use strict";var co=Object.create;var jt=Object.defineProperty;var lo=Object.getOwnPropertyDescriptor;var uo=Object.getOwnPropertyNames;var fo=Object.getPrototypeOf,ho=Object.prototype.hasOwnProperty;var po=(i,n)=>()=>(i&&(n=i(i=0)),n);var ae=(i,n)=>()=>(n||i((n={exports:{}}).exports,n),n.exports),or=(i,n)=>{for(var e in n)jt(i,e,{get:n[e],enumerable:!0})},ar=(i,n,e,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of uo(n))!ho.call(i,r)&&r!==e&&jt(i,r,{get:()=>n[r],enumerable:!(t=lo(n,r))||t.enumerable});return i};var Ae=(i,n,e)=>(e=i!=null?co(fo(i)):{},ar(n||!i||!i.__esModule?jt(e,"default",{value:i,enumerable:!0}):e,i)),Ge=i=>ar(jt({},"__esModule",{value:!0}),i);var mr=ae((hr,pr)=>{(function(i){var n;typeof hr=="object"?pr.exports=i():typeof define=="function"&&define.amd?define(i):(typeof window<"u"?n=window:typeof global<"u"?n=global:typeof self<"u"&&(n=self),n.objectHash=i())})(function(){return function i(n,e,t){function r(a,f){if(!e[a]){if(!n[a]){var p=typeof require=="function"&&require;if(!f&&p)return p(a,!0);if(s)return s(a,!0);throw new Error("Cannot find module '"+a+"'")}f=e[a]={exports:{}},n[a][0].call(f.exports,function(y){var D=n[a][1][y];return r(D||y)},f,f.exports,i,n,e,t)}return e[a].exports}for(var s=typeof require=="function"&&require,o=0;o<t.length;o++)r(t[o]);return r}({1:[function(i,n,e){(function(t,r,s,o,a,f,p,y,D){"use strict";var w=i("crypto");function A(b,S){S=E(b,S);var d;return(d=S.algorithm!=="passthrough"?w.createHash(S.algorithm):new k).write===void 0&&(d.write=d.update,d.end=d.update),_(S,d).dispatch(b),d.update||d.end(""),d.digest?d.digest(S.encoding==="buffer"?void 0:S.encoding):(b=d.read(),S.encoding!=="buffer"?b.toString(S.encoding):b)}(e=n.exports=A).sha1=function(b){return A(b)},e.keys=function(b){return A(b,{excludeValues:!0,algorithm:"sha1",encoding:"hex"})},e.MD5=function(b){return A(b,{algorithm:"md5",encoding:"hex"})},e.keysMD5=function(b){return A(b,{algorithm:"md5",encoding:"hex",excludeValues:!0})};var g=w.getHashes?w.getHashes().slice():["sha1","md5"],I=(g.push("passthrough"),["buffer","hex","binary","base64"]);function E(b,S){var d={};if(d.algorithm=(S=S||{}).algorithm||"sha1",d.encoding=S.encoding||"hex",d.excludeValues=!!S.excludeValues,d.algorithm=d.algorithm.toLowerCase(),d.encoding=d.encoding.toLowerCase(),d.ignoreUnknown=S.ignoreUnknown===!0,d.respectType=S.respectType!==!1,d.respectFunctionNames=S.respectFunctionNames!==!1,d.respectFunctionProperties=S.respectFunctionProperties!==!1,d.unorderedArrays=S.unorderedArrays===!0,d.unorderedSets=S.unorderedSets!==!1,d.unorderedObjects=S.unorderedObjects!==!1,d.replacer=S.replacer||void 0,d.excludeKeys=S.excludeKeys||void 0,b===void 0)throw new Error("Object argument required.");for(var h=0;h<g.length;++h)g[h].toLowerCase()===d.algorithm.toLowerCase()&&(d.algorithm=g[h]);if(g.indexOf(d.algorithm)===-1)throw new Error('Algorithm "'+d.algorithm+'" not supported. supported values: '+g.join(", "));if(I.indexOf(d.encoding)===-1&&d.algorithm!=="passthrough")throw new Error('Encoding "'+d.encoding+'" not supported. supported values: '+I.join(", "));return d}function O(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 _(b,S,d){d=d||[];function h(l){return S.update?S.update(l,"utf8"):S.write(l,"utf8")}return{dispatch:function(l){return this["_"+((l=b.replacer?b.replacer(l):l)===null?"null":typeof l)](l)},_object:function(l){var v,x=Object.prototype.toString.call(l),L=/\[object (.*)\]/i.exec(x);if(L=(L=L?L[1]:"unknown:["+x+"]").toLowerCase(),0<=(x=d.indexOf(l)))return this.dispatch("[CIRCULAR:"+x+"]");if(d.push(l),s!==void 0&&s.isBuffer&&s.isBuffer(l))return h("buffer:"),h(l);if(L==="object"||L==="function"||L==="asyncfunction")return x=Object.keys(l),b.unorderedObjects&&(x=x.sort()),b.respectType===!1||O(l)||x.splice(0,0,"prototype","__proto__","constructor"),b.excludeKeys&&(x=x.filter(function(B){return!b.excludeKeys(B)})),h("object:"+x.length+":"),v=this,x.forEach(function(B){v.dispatch(B),h(":"),b.excludeValues||v.dispatch(l[B]),h(",")});if(!this["_"+L]){if(b.ignoreUnknown)return h("["+L+"]");throw new Error('Unknown object type "'+L+'"')}this["_"+L](l)},_array:function(l,B){B=B!==void 0?B:b.unorderedArrays!==!1;var x=this;if(h("array:"+l.length+":"),!B||l.length<=1)return l.forEach(function(j){return x.dispatch(j)});var L=[],B=l.map(function(j){var T=new k,q=d.slice();return _(b,T,q).dispatch(j),L=L.concat(q.slice(d.length)),T.read().toString()});return d=d.concat(L),B.sort(),this._array(B,!1)},_date:function(l){return h("date:"+l.toJSON())},_symbol:function(l){return h("symbol:"+l.toString())},_error:function(l){return h("error:"+l.toString())},_boolean:function(l){return h("bool:"+l.toString())},_string:function(l){h("string:"+l.length+":"),h(l.toString())},_function:function(l){h("fn:"),O(l)?this.dispatch("[native]"):this.dispatch(l.toString()),b.respectFunctionNames!==!1&&this.dispatch("function-name:"+String(l.name)),b.respectFunctionProperties&&this._object(l)},_number:function(l){return h("number:"+l.toString())},_xml:function(l){return h("xml:"+l.toString())},_null:function(){return h("Null")},_undefined:function(){return h("Undefined")},_regexp:function(l){return h("regex:"+l.toString())},_uint8array:function(l){return h("uint8array:"),this.dispatch(Array.prototype.slice.call(l))},_uint8clampedarray:function(l){return h("uint8clampedarray:"),this.dispatch(Array.prototype.slice.call(l))},_int8array:function(l){return h("int8array:"),this.dispatch(Array.prototype.slice.call(l))},_uint16array:function(l){return h("uint16array:"),this.dispatch(Array.prototype.slice.call(l))},_int16array:function(l){return h("int16array:"),this.dispatch(Array.prototype.slice.call(l))},_uint32array:function(l){return h("uint32array:"),this.dispatch(Array.prototype.slice.call(l))},_int32array:function(l){return h("int32array:"),this.dispatch(Array.prototype.slice.call(l))},_float32array:function(l){return h("float32array:"),this.dispatch(Array.prototype.slice.call(l))},_float64array:function(l){return h("float64array:"),this.dispatch(Array.prototype.slice.call(l))},_arraybuffer:function(l){return h("arraybuffer:"),this.dispatch(new Uint8Array(l))},_url:function(l){return h("url:"+l.toString())},_map:function(l){return h("map:"),l=Array.from(l),this._array(l,b.unorderedSets!==!1)},_set:function(l){return h("set:"),l=Array.from(l),this._array(l,b.unorderedSets!==!1)},_file:function(l){return h("file:"),this.dispatch([l.name,l.size,l.type,l.lastModfied])},_blob:function(){if(b.ignoreUnknown)return h("[blob]");throw Error(`Hashing Blob objects is currently not supported
1
+ "use strict";var ho=Object.create;var Vt=Object.defineProperty;var po=Object.getOwnPropertyDescriptor;var mo=Object.getOwnPropertyNames;var go=Object.getPrototypeOf,yo=Object.prototype.hasOwnProperty;var bo=(i,n)=>()=>(i&&(n=i(i=0)),n);var le=(i,n)=>()=>(n||i((n={exports:{}}).exports,n),n.exports),cr=(i,n)=>{for(var e in n)Vt(i,e,{get:n[e],enumerable:!0})},lr=(i,n,e,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of mo(n))!yo.call(i,r)&&r!==e&&Vt(i,r,{get:()=>n[r],enumerable:!(t=po(n,r))||t.enumerable});return i};var Te=(i,n,e)=>(e=i!=null?ho(go(i)):{},lr(n||!i||!i.__esModule?Vt(e,"default",{value:i,enumerable:!0}):e,i)),Ze=i=>lr(Vt({},"__esModule",{value:!0}),i);var yr=le((mr,gr)=>{(function(i){var n;typeof mr=="object"?gr.exports=i():typeof define=="function"&&define.amd?define(i):(typeof window<"u"?n=window:typeof global<"u"?n=global:typeof self<"u"&&(n=self),n.objectHash=i())})(function(){return function i(n,e,t){function r(a,d){if(!e[a]){if(!n[a]){var m=typeof require=="function"&&require;if(!d&&m)return m(a,!0);if(s)return s(a,!0);throw new Error("Cannot find module '"+a+"'")}d=e[a]={exports:{}},n[a][0].call(d.exports,function(h){var O=n[a][1][h];return r(O||h)},d,d.exports,i,n,e,t)}return e[a].exports}for(var s=typeof require=="function"&&require,o=0;o<t.length;o++)r(t[o]);return r}({1:[function(i,n,e){(function(t,r,s,o,a,d,m,h,O){"use strict";var w=i("crypto");function C(b,S){S=E(b,S);var u;return(u=S.algorithm!=="passthrough"?w.createHash(S.algorithm):new k).write===void 0&&(u.write=u.update,u.end=u.update),D(S,u).dispatch(b),u.update||u.end(""),u.digest?u.digest(S.encoding==="buffer"?void 0:S.encoding):(b=u.read(),S.encoding!=="buffer"?b.toString(S.encoding):b)}(e=n.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 y=w.getHashes?w.getHashes().slice():["sha1","md5"],I=(y.push("passthrough"),["buffer","hex","binary","base64"]);function E(b,S){var u={};if(u.algorithm=(S=S||{}).algorithm||"sha1",u.encoding=S.encoding||"hex",u.excludeValues=!!S.excludeValues,u.algorithm=u.algorithm.toLowerCase(),u.encoding=u.encoding.toLowerCase(),u.ignoreUnknown=S.ignoreUnknown===!0,u.respectType=S.respectType!==!1,u.respectFunctionNames=S.respectFunctionNames!==!1,u.respectFunctionProperties=S.respectFunctionProperties!==!1,u.unorderedArrays=S.unorderedArrays===!0,u.unorderedSets=S.unorderedSets!==!1,u.unorderedObjects=S.unorderedObjects!==!1,u.replacer=S.replacer||void 0,u.excludeKeys=S.excludeKeys||void 0,b===void 0)throw new Error("Object argument required.");for(var p=0;p<y.length;++p)y[p].toLowerCase()===u.algorithm.toLowerCase()&&(u.algorithm=y[p]);if(y.indexOf(u.algorithm)===-1)throw new Error('Algorithm "'+u.algorithm+'" not supported. supported values: '+y.join(", "));if(I.indexOf(u.encoding)===-1&&u.algorithm!=="passthrough")throw new Error('Encoding "'+u.encoding+'" not supported. supported values: '+I.join(", "));return u}function _(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,S,u){u=u||[];function p(l){return S.update?S.update(l,"utf8"):S.write(l,"utf8")}return{dispatch:function(l){return this["_"+((l=b.replacer?b.replacer(l):l)===null?"null":typeof l)](l)},_object:function(l){var v,x=Object.prototype.toString.call(l),j=/\[object (.*)\]/i.exec(x);if(j=(j=j?j[1]:"unknown:["+x+"]").toLowerCase(),0<=(x=u.indexOf(l)))return this.dispatch("[CIRCULAR:"+x+"]");if(u.push(l),s!==void 0&&s.isBuffer&&s.isBuffer(l))return p("buffer:"),p(l);if(j==="object"||j==="function"||j==="asyncfunction")return x=Object.keys(l),b.unorderedObjects&&(x=x.sort()),b.respectType===!1||_(l)||x.splice(0,0,"prototype","__proto__","constructor"),b.excludeKeys&&(x=x.filter(function(B){return!b.excludeKeys(B)})),p("object:"+x.length+":"),v=this,x.forEach(function(B){v.dispatch(B),p(":"),b.excludeValues||v.dispatch(l[B]),p(",")});if(!this["_"+j]){if(b.ignoreUnknown)return p("["+j+"]");throw new Error('Unknown object type "'+j+'"')}this["_"+j](l)},_array:function(l,B){B=B!==void 0?B:b.unorderedArrays!==!1;var x=this;if(p("array:"+l.length+":"),!B||l.length<=1)return l.forEach(function(M){return x.dispatch(M)});var j=[],B=l.map(function(M){var T=new k,H=u.slice();return D(b,T,H).dispatch(M),j=j.concat(H.slice(u.length)),T.read().toString()});return u=u.concat(j),B.sort(),this._array(B,!1)},_date:function(l){return p("date:"+l.toJSON())},_symbol:function(l){return p("symbol:"+l.toString())},_error:function(l){return p("error:"+l.toString())},_boolean:function(l){return p("bool:"+l.toString())},_string:function(l){p("string:"+l.length+":"),p(l.toString())},_function:function(l){p("fn:"),_(l)?this.dispatch("[native]"):this.dispatch(l.toString()),b.respectFunctionNames!==!1&&this.dispatch("function-name:"+String(l.name)),b.respectFunctionProperties&&this._object(l)},_number:function(l){return p("number:"+l.toString())},_xml:function(l){return p("xml:"+l.toString())},_null:function(){return p("Null")},_undefined:function(){return p("Undefined")},_regexp:function(l){return p("regex:"+l.toString())},_uint8array:function(l){return p("uint8array:"),this.dispatch(Array.prototype.slice.call(l))},_uint8clampedarray:function(l){return p("uint8clampedarray:"),this.dispatch(Array.prototype.slice.call(l))},_int8array:function(l){return p("int8array:"),this.dispatch(Array.prototype.slice.call(l))},_uint16array:function(l){return p("uint16array:"),this.dispatch(Array.prototype.slice.call(l))},_int16array:function(l){return p("int16array:"),this.dispatch(Array.prototype.slice.call(l))},_uint32array:function(l){return p("uint32array:"),this.dispatch(Array.prototype.slice.call(l))},_int32array:function(l){return p("int32array:"),this.dispatch(Array.prototype.slice.call(l))},_float32array:function(l){return p("float32array:"),this.dispatch(Array.prototype.slice.call(l))},_float64array:function(l){return p("float64array:"),this.dispatch(Array.prototype.slice.call(l))},_arraybuffer:function(l){return p("arraybuffer:"),this.dispatch(new Uint8Array(l))},_url:function(l){return p("url:"+l.toString())},_map:function(l){return p("map:"),l=Array.from(l),this._array(l,b.unorderedSets!==!1)},_set:function(l){return p("set:"),l=Array.from(l),this._array(l,b.unorderedSets!==!1)},_file:function(l){return p("file:"),this.dispatch([l.name,l.size,l.type,l.lastModfied])},_blob:function(){if(b.ignoreUnknown)return p("[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(l){return h("bigint:"+l.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 k(){return{buf:"",write:function(b){this.buf+=b},end:function(b){this.buf+=b},read:function(){return this.buf}}}e.writeToStream=function(b,S,d){return d===void 0&&(d=S,S={}),_(S=E(b,S),d).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,n,e){(function(t,r,s,o,a,f,p,y,D){(function(w){"use strict";var A=typeof Uint8Array<"u"?Uint8Array:Array,g="+".charCodeAt(0),I="/".charCodeAt(0),E="0".charCodeAt(0),O="a".charCodeAt(0),_="A".charCodeAt(0),k="-".charCodeAt(0),b="_".charCodeAt(0);function S(d){return d=d.charCodeAt(0),d===g||d===k?62:d===I||d===b?63:d<E?-1:d<E+10?d-E+26+26:d<_+26?d-_:d<O+26?d-O+26:void 0}w.toByteArray=function(d){var h,l;if(0<d.length%4)throw new Error("Invalid string. Length must be a multiple of 4");var v=d.length,v=d.charAt(v-2)==="="?2:d.charAt(v-1)==="="?1:0,x=new A(3*d.length/4-v),L=0<v?d.length-4:d.length,B=0;function j(T){x[B++]=T}for(h=0;h<L;h+=4,0)j((16711680&(l=S(d.charAt(h))<<18|S(d.charAt(h+1))<<12|S(d.charAt(h+2))<<6|S(d.charAt(h+3))))>>16),j((65280&l)>>8),j(255&l);return v==2?j(255&(l=S(d.charAt(h))<<2|S(d.charAt(h+1))>>4)):v==1&&(j((l=S(d.charAt(h))<<10|S(d.charAt(h+1))<<4|S(d.charAt(h+2))>>2)>>8&255),j(255&l)),x},w.fromByteArray=function(d){var h,l,v,x,L=d.length%3,B="";function j(T){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(T)}for(h=0,v=d.length-L;h<v;h+=3)l=(d[h]<<16)+(d[h+1]<<8)+d[h+2],B+=j((x=l)>>18&63)+j(x>>12&63)+j(x>>6&63)+j(63&x);switch(L){case 1:B=(B+=j((l=d[d.length-1])>>2))+j(l<<4&63)+"==";break;case 2:B=(B=(B+=j((l=(d[d.length-2]<<8)+d[d.length-1])>>10))+j(l>>4&63))+j(l<<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,n,e){(function(t,r,g,o,a,f,p,y,D){var w=i("base64-js"),A=i("ieee754");function g(c,u,m){if(!(this instanceof g))return new g(c,u,m);var P,C,F,U,W=typeof c;if(u==="base64"&&W=="string")for(c=(U=c).trim?U.trim():U.replace(/^\s+|\s+$/g,"");c.length%4!=0;)c+="=";if(W=="number")P=te(c);else if(W=="string")P=g.byteLength(c,u);else{if(W!="object")throw new Error("First argument needs to be a number, array or string.");P=te(c.length)}if(g._useTypedArrays?C=g._augment(new Uint8Array(P)):((C=this).length=P,C._isBuffer=!0),g._useTypedArrays&&typeof c.byteLength=="number")C._set(c);else if(Q(U=c)||g.isBuffer(U)||U&&typeof U=="object"&&typeof U.length=="number")for(F=0;F<P;F++)g.isBuffer(c)?C[F]=c.readUInt8(F):C[F]=c[F];else if(W=="string")C.write(c,0,u);else if(W=="number"&&!g._useTypedArrays&&!m)for(F=0;F<P;F++)C[F]=0;return C}function I(c,u,m,P){return g._charsWritten=Lt(function(C){for(var F=[],U=0;U<C.length;U++)F.push(255&C.charCodeAt(U));return F}(u),c,m,P)}function E(c,u,m,P){return g._charsWritten=Lt(function(C){for(var F,U,W=[],Y=0;Y<C.length;Y++)U=C.charCodeAt(Y),F=U>>8,U=U%256,W.push(U),W.push(F);return W}(u),c,m,P)}function O(c,u,m){var P="";m=Math.min(c.length,m);for(var C=u;C<m;C++)P+=String.fromCharCode(c[C]);return P}function _(c,u,m,F){F||(R(typeof m=="boolean","missing or invalid endian"),R(u!=null,"missing offset"),R(u+1<c.length,"Trying to read beyond buffer length"));var C,F=c.length;if(!(F<=u))return m?(C=c[u],u+1<F&&(C|=c[u+1]<<8)):(C=c[u]<<8,u+1<F&&(C|=c[u+1])),C}function k(c,u,m,F){F||(R(typeof m=="boolean","missing or invalid endian"),R(u!=null,"missing offset"),R(u+3<c.length,"Trying to read beyond buffer length"));var C,F=c.length;if(!(F<=u))return m?(u+2<F&&(C=c[u+2]<<16),u+1<F&&(C|=c[u+1]<<8),C|=c[u],u+3<F&&(C+=c[u+3]<<24>>>0)):(u+1<F&&(C=c[u+1]<<16),u+2<F&&(C|=c[u+2]<<8),u+3<F&&(C|=c[u+3]),C+=c[u]<<24>>>0),C}function b(c,u,m,P){if(P||(R(typeof m=="boolean","missing or invalid endian"),R(u!=null,"missing offset"),R(u+1<c.length,"Trying to read beyond buffer length")),!(c.length<=u))return P=_(c,u,m,!0),32768&P?-1*(65535-P+1):P}function S(c,u,m,P){if(P||(R(typeof m=="boolean","missing or invalid endian"),R(u!=null,"missing offset"),R(u+3<c.length,"Trying to read beyond buffer length")),!(c.length<=u))return P=k(c,u,m,!0),2147483648&P?-1*(4294967295-P+1):P}function d(c,u,m,P){return P||(R(typeof m=="boolean","missing or invalid endian"),R(u+3<c.length,"Trying to read beyond buffer length")),A.read(c,u,m,23,4)}function h(c,u,m,P){return P||(R(typeof m=="boolean","missing or invalid endian"),R(u+7<c.length,"Trying to read beyond buffer length")),A.read(c,u,m,52,8)}function l(c,u,m,P,C){if(C||(R(u!=null,"missing value"),R(typeof P=="boolean","missing or invalid endian"),R(m!=null,"missing offset"),R(m+1<c.length,"trying to write beyond buffer length"),Xn(u,65535)),C=c.length,!(C<=m))for(var F=0,U=Math.min(C-m,2);F<U;F++)c[m+F]=(u&255<<8*(P?F:1-F))>>>8*(P?F:1-F)}function v(c,u,m,P,C){if(C||(R(u!=null,"missing value"),R(typeof P=="boolean","missing or invalid endian"),R(m!=null,"missing offset"),R(m+3<c.length,"trying to write beyond buffer length"),Xn(u,4294967295)),C=c.length,!(C<=m))for(var F=0,U=Math.min(C-m,4);F<U;F++)c[m+F]=u>>>8*(P?F:3-F)&255}function x(c,u,m,P,C){C||(R(u!=null,"missing value"),R(typeof P=="boolean","missing or invalid endian"),R(m!=null,"missing offset"),R(m+1<c.length,"Trying to write beyond buffer length"),Zn(u,32767,-32768)),c.length<=m||l(c,0<=u?u:65535+u+1,m,P,C)}function L(c,u,m,P,C){C||(R(u!=null,"missing value"),R(typeof P=="boolean","missing or invalid endian"),R(m!=null,"missing offset"),R(m+3<c.length,"Trying to write beyond buffer length"),Zn(u,2147483647,-2147483648)),c.length<=m||v(c,0<=u?u:4294967295+u+1,m,P,C)}function B(c,u,m,P,C){C||(R(u!=null,"missing value"),R(typeof P=="boolean","missing or invalid endian"),R(m!=null,"missing offset"),R(m+3<c.length,"Trying to write beyond buffer length"),rr(u,34028234663852886e22,-34028234663852886e22)),c.length<=m||A.write(c,u,m,P,23,4)}function j(c,u,m,P,C){C||(R(u!=null,"missing value"),R(typeof P=="boolean","missing or invalid endian"),R(m!=null,"missing offset"),R(m+7<c.length,"Trying to write beyond buffer length"),rr(u,17976931348623157e292,-17976931348623157e292)),c.length<=m||A.write(c,u,m,P,52,8)}e.Buffer=g,e.SlowBuffer=g,e.INSPECT_MAX_BYTES=50,g.poolSize=8192,g._useTypedArrays=function(){try{var c=new ArrayBuffer(0),u=new Uint8Array(c);return u.foo=function(){return 42},u.foo()===42&&typeof u.subarray=="function"}catch{return!1}}(),g.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}},g.isBuffer=function(c){return!(c==null||!c._isBuffer)},g.byteLength=function(c,u){var m;switch(c+="",u||"utf8"){case"hex":m=c.length/2;break;case"utf8":case"utf-8":m=Ie(c).length;break;case"ascii":case"binary":case"raw":m=c.length;break;case"base64":m=nr(c).length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":m=2*c.length;break;default:throw new Error("Unknown encoding")}return m},g.concat=function(c,u){if(R(Q(c),`Usage: Buffer.concat(list, [totalLength])
5
- list should be an Array.`),c.length===0)return new g(0);if(c.length===1)return c[0];if(typeof u!="number")for(C=u=0;C<c.length;C++)u+=c[C].length;for(var m=new g(u),P=0,C=0;C<c.length;C++){var F=c[C];F.copy(m,P),P+=F.length}return m},g.prototype.write=function(c,u,m,P){isFinite(u)?isFinite(m)||(P=m,m=void 0):(Y=P,P=u,u=m,m=Y),u=Number(u)||0;var C,F,U,W,Y=this.length-u;switch((!m||Y<(m=Number(m)))&&(m=Y),P=String(P||"utf8").toLowerCase()){case"hex":C=function(me,se,oe,X){oe=Number(oe)||0;var G=me.length-oe;(!X||G<(X=Number(X)))&&(X=G),R((G=se.length)%2==0,"Invalid hex string"),G/2<X&&(X=G/2);for(var Je=0;Je<X;Je++){var sr=parseInt(se.substr(2*Je,2),16);R(!isNaN(sr),"Invalid hex string"),me[oe+Je]=sr}return g._charsWritten=2*Je,Je}(this,c,u,m);break;case"utf8":case"utf-8":F=this,U=u,W=m,C=g._charsWritten=Lt(Ie(c),F,U,W);break;case"ascii":case"binary":C=I(this,c,u,m);break;case"base64":F=this,U=u,W=m,C=g._charsWritten=Lt(nr(c),F,U,W);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":C=E(this,c,u,m);break;default:throw new Error("Unknown encoding")}return C},g.prototype.toString=function(c,u,m){var P,C,F,U,W=this;if(c=String(c||"utf8").toLowerCase(),u=Number(u)||0,(m=m!==void 0?Number(m):W.length)===u)return"";switch(c){case"hex":P=function(Y,me,se){var oe=Y.length;(!me||me<0)&&(me=0),(!se||se<0||oe<se)&&(se=oe);for(var X="",G=me;G<se;G++)X+=K(Y[G]);return X}(W,u,m);break;case"utf8":case"utf-8":P=function(Y,me,se){var oe="",X="";se=Math.min(Y.length,se);for(var G=me;G<se;G++)Y[G]<=127?(oe+=ir(X)+String.fromCharCode(Y[G]),X=""):X+="%"+Y[G].toString(16);return oe+ir(X)}(W,u,m);break;case"ascii":case"binary":P=O(W,u,m);break;case"base64":C=W,U=m,P=(F=u)===0&&U===C.length?w.fromByteArray(C):w.fromByteArray(C.slice(F,U));break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":P=function(Y,me,se){for(var oe=Y.slice(me,se),X="",G=0;G<oe.length;G+=2)X+=String.fromCharCode(oe[G]+256*oe[G+1]);return X}(W,u,m);break;default:throw new Error("Unknown encoding")}return P},g.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},g.prototype.copy=function(c,u,m,P){if(u=u||0,(P=P||P===0?P:this.length)!==(m=m||0)&&c.length!==0&&this.length!==0){R(m<=P,"sourceEnd < sourceStart"),R(0<=u&&u<c.length,"targetStart out of bounds"),R(0<=m&&m<this.length,"sourceStart out of bounds"),R(0<=P&&P<=this.length,"sourceEnd out of bounds"),P>this.length&&(P=this.length);var C=(P=c.length-u<P-m?c.length-u+m:P)-m;if(C<100||!g._useTypedArrays)for(var F=0;F<C;F++)c[F+u]=this[F+m];else c._set(this.subarray(m,m+C),u)}},g.prototype.slice=function(c,u){var m=this.length;if(c=q(c,m,0),u=q(u,m,m),g._useTypedArrays)return g._augment(this.subarray(c,u));for(var P=u-c,C=new g(P,void 0,!0),F=0;F<P;F++)C[F]=this[F+c];return C},g.prototype.get=function(c){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(c)},g.prototype.set=function(c,u){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(c,u)},g.prototype.readUInt8=function(c,u){if(u||(R(c!=null,"missing offset"),R(c<this.length,"Trying to read beyond buffer length")),!(c>=this.length))return this[c]},g.prototype.readUInt16LE=function(c,u){return _(this,c,!0,u)},g.prototype.readUInt16BE=function(c,u){return _(this,c,!1,u)},g.prototype.readUInt32LE=function(c,u){return k(this,c,!0,u)},g.prototype.readUInt32BE=function(c,u){return k(this,c,!1,u)},g.prototype.readInt8=function(c,u){if(u||(R(c!=null,"missing offset"),R(c<this.length,"Trying to read beyond buffer length")),!(c>=this.length))return 128&this[c]?-1*(255-this[c]+1):this[c]},g.prototype.readInt16LE=function(c,u){return b(this,c,!0,u)},g.prototype.readInt16BE=function(c,u){return b(this,c,!1,u)},g.prototype.readInt32LE=function(c,u){return S(this,c,!0,u)},g.prototype.readInt32BE=function(c,u){return S(this,c,!1,u)},g.prototype.readFloatLE=function(c,u){return d(this,c,!0,u)},g.prototype.readFloatBE=function(c,u){return d(this,c,!1,u)},g.prototype.readDoubleLE=function(c,u){return h(this,c,!0,u)},g.prototype.readDoubleBE=function(c,u){return h(this,c,!1,u)},g.prototype.writeUInt8=function(c,u,m){m||(R(c!=null,"missing value"),R(u!=null,"missing offset"),R(u<this.length,"trying to write beyond buffer length"),Xn(c,255)),u>=this.length||(this[u]=c)},g.prototype.writeUInt16LE=function(c,u,m){l(this,c,u,!0,m)},g.prototype.writeUInt16BE=function(c,u,m){l(this,c,u,!1,m)},g.prototype.writeUInt32LE=function(c,u,m){v(this,c,u,!0,m)},g.prototype.writeUInt32BE=function(c,u,m){v(this,c,u,!1,m)},g.prototype.writeInt8=function(c,u,m){m||(R(c!=null,"missing value"),R(u!=null,"missing offset"),R(u<this.length,"Trying to write beyond buffer length"),Zn(c,127,-128)),u>=this.length||(0<=c?this.writeUInt8(c,u,m):this.writeUInt8(255+c+1,u,m))},g.prototype.writeInt16LE=function(c,u,m){x(this,c,u,!0,m)},g.prototype.writeInt16BE=function(c,u,m){x(this,c,u,!1,m)},g.prototype.writeInt32LE=function(c,u,m){L(this,c,u,!0,m)},g.prototype.writeInt32BE=function(c,u,m){L(this,c,u,!1,m)},g.prototype.writeFloatLE=function(c,u,m){B(this,c,u,!0,m)},g.prototype.writeFloatBE=function(c,u,m){B(this,c,u,!1,m)},g.prototype.writeDoubleLE=function(c,u,m){j(this,c,u,!0,m)},g.prototype.writeDoubleBE=function(c,u,m){j(this,c,u,!1,m)},g.prototype.fill=function(c,u,m){if(u=u||0,m=m||this.length,R(typeof(c=typeof(c=c||0)=="string"?c.charCodeAt(0):c)=="number"&&!isNaN(c),"value is not a number"),R(u<=m,"end < start"),m!==u&&this.length!==0){R(0<=u&&u<this.length,"start out of bounds"),R(0<=m&&m<=this.length,"end out of bounds");for(var P=u;P<m;P++)this[P]=c}},g.prototype.inspect=function(){for(var c=[],u=this.length,m=0;m<u;m++)if(c[m]=K(this[m]),m===e.INSPECT_MAX_BYTES){c[m+1]="...";break}return"<Buffer "+c.join(" ")+">"},g.prototype.toArrayBuffer=function(){if(typeof Uint8Array>"u")throw new Error("Buffer.toArrayBuffer not supported in this browser");if(g._useTypedArrays)return new g(this).buffer;for(var c=new Uint8Array(this.length),u=0,m=c.length;u<m;u+=1)c[u]=this[u];return c.buffer};var T=g.prototype;function q(c,u,m){return typeof c!="number"?m:u<=(c=~~c)?u:0<=c||0<=(c+=u)?c:0}function te(c){return(c=~~Math.ceil(+c))<0?0:c}function Q(c){return(Array.isArray||function(u){return Object.prototype.toString.call(u)==="[object Array]"})(c)}function K(c){return c<16?"0"+c.toString(16):c.toString(16)}function Ie(c){for(var u=[],m=0;m<c.length;m++){var P=c.charCodeAt(m);if(P<=127)u.push(c.charCodeAt(m));else for(var C=m,F=(55296<=P&&P<=57343&&m++,encodeURIComponent(c.slice(C,m+1)).substr(1).split("%")),U=0;U<F.length;U++)u.push(parseInt(F[U],16))}return u}function nr(c){return w.toByteArray(c)}function Lt(c,u,m,P){for(var C=0;C<P&&!(C+m>=u.length||C>=c.length);C++)u[C+m]=c[C];return C}function ir(c){try{return decodeURIComponent(c)}catch{return String.fromCharCode(65533)}}function Xn(c,u){R(typeof c=="number","cannot write a non-number as a number"),R(0<=c,"specified a negative value for writing an unsigned value"),R(c<=u,"value is larger than maximum value for type"),R(Math.floor(c)===c,"value has a fractional component")}function Zn(c,u,m){R(typeof c=="number","cannot write a non-number as a number"),R(c<=u,"value larger than maximum allowed value"),R(m<=c,"value smaller than minimum allowed value"),R(Math.floor(c)===c,"value has a fractional component")}function rr(c,u,m){R(typeof c=="number","cannot write a non-number as a number"),R(c<=u,"value larger than maximum allowed value"),R(m<=c,"value smaller than minimum allowed value")}function R(c,u){if(!c)throw new Error(u||"Failed assertion")}g._augment=function(c){return c._isBuffer=!0,c._get=c.get,c._set=c.set,c.get=T.get,c.set=T.set,c.write=T.write,c.toString=T.toString,c.toLocaleString=T.toString,c.toJSON=T.toJSON,c.copy=T.copy,c.slice=T.slice,c.readUInt8=T.readUInt8,c.readUInt16LE=T.readUInt16LE,c.readUInt16BE=T.readUInt16BE,c.readUInt32LE=T.readUInt32LE,c.readUInt32BE=T.readUInt32BE,c.readInt8=T.readInt8,c.readInt16LE=T.readInt16LE,c.readInt16BE=T.readInt16BE,c.readInt32LE=T.readInt32LE,c.readInt32BE=T.readInt32BE,c.readFloatLE=T.readFloatLE,c.readFloatBE=T.readFloatBE,c.readDoubleLE=T.readDoubleLE,c.readDoubleBE=T.readDoubleBE,c.writeUInt8=T.writeUInt8,c.writeUInt16LE=T.writeUInt16LE,c.writeUInt16BE=T.writeUInt16BE,c.writeUInt32LE=T.writeUInt32LE,c.writeUInt32BE=T.writeUInt32BE,c.writeInt8=T.writeInt8,c.writeInt16LE=T.writeInt16LE,c.writeInt16BE=T.writeInt16BE,c.writeInt32LE=T.writeInt32LE,c.writeInt32BE=T.writeInt32BE,c.writeFloatLE=T.writeFloatLE,c.writeFloatBE=T.writeFloatBE,c.writeDoubleLE=T.writeDoubleLE,c.writeDoubleBE=T.writeDoubleBE,c.fill=T.fill,c.inspect=T.inspect,c.toArrayBuffer=T.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,n,e){(function(t,r,w,o,a,f,p,y,D){var w=i("buffer").Buffer,A=4,g=new w(A);g.fill(0),n.exports={hash:function(I,E,O,_){for(var k=E(function(l,v){l.length%A!=0&&(x=l.length+(A-l.length%A),l=w.concat([l,g],x));for(var x,L=[],B=v?l.readInt32BE:l.readInt32LE,j=0;j<l.length;j+=A)L.push(B.call(l,j));return L}(I=w.isBuffer(I)?I:new w(I),_),8*I.length),E=_,b=new w(O),S=E?b.writeInt32BE:b.writeInt32LE,d=0;d<k.length;d++)S.call(b,k[d],4*d,!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,n,e){(function(t,r,w,o,a,f,p,y,D){var w=i("buffer").Buffer,A=i("./sha"),g=i("./sha256"),I=i("./rng"),E={sha1:A,sha256:g,md5:i("./md5")},O=64,_=new w(O);function k(l,v){var x=E[l=l||"sha1"],L=[];return x||b("algorithm:",l,"is not yet supported"),{update:function(B){return w.isBuffer(B)||(B=new w(B)),L.push(B),B.length,this},digest:function(B){var j=w.concat(L),j=v?function(T,q,te){w.isBuffer(q)||(q=new w(q)),w.isBuffer(te)||(te=new w(te)),q.length>O?q=T(q):q.length<O&&(q=w.concat([q,_],O));for(var Q=new w(O),K=new w(O),Ie=0;Ie<O;Ie++)Q[Ie]=54^q[Ie],K[Ie]=92^q[Ie];return te=T(w.concat([Q,te])),T(w.concat([K,te]))}(x,v,j):x(j);return L=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
- `))}_.fill(0),e.createHash=function(l){return k(l)},e.createHmac=k,e.randomBytes=function(l,v){if(!v||!v.call)return new w(I(l));try{v.call(this,void 0,new w(I(l)))}catch(x){v(x)}};var S,d=["createCredentials","createCipher","createCipheriv","createDecipher","createDecipheriv","createSign","createVerify","createDiffieHellman","pbkdf2"],h=function(l){e[l]=function(){b("sorry,",l,"is not implemented yet")}};for(S in d)h(d[S],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/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,n,e){(function(t,r,s,o,a,f,p,y,D){var w=i("./helpers");function A(b,S){b[S>>5]|=128<<S%32,b[14+(S+64>>>9<<4)]=S;for(var d=1732584193,h=-271733879,l=-1732584194,v=271733878,x=0;x<b.length;x+=16){var L=d,B=h,j=l,T=v,d=I(d,h,l,v,b[x+0],7,-680876936),v=I(v,d,h,l,b[x+1],12,-389564586),l=I(l,v,d,h,b[x+2],17,606105819),h=I(h,l,v,d,b[x+3],22,-1044525330);d=I(d,h,l,v,b[x+4],7,-176418897),v=I(v,d,h,l,b[x+5],12,1200080426),l=I(l,v,d,h,b[x+6],17,-1473231341),h=I(h,l,v,d,b[x+7],22,-45705983),d=I(d,h,l,v,b[x+8],7,1770035416),v=I(v,d,h,l,b[x+9],12,-1958414417),l=I(l,v,d,h,b[x+10],17,-42063),h=I(h,l,v,d,b[x+11],22,-1990404162),d=I(d,h,l,v,b[x+12],7,1804603682),v=I(v,d,h,l,b[x+13],12,-40341101),l=I(l,v,d,h,b[x+14],17,-1502002290),d=E(d,h=I(h,l,v,d,b[x+15],22,1236535329),l,v,b[x+1],5,-165796510),v=E(v,d,h,l,b[x+6],9,-1069501632),l=E(l,v,d,h,b[x+11],14,643717713),h=E(h,l,v,d,b[x+0],20,-373897302),d=E(d,h,l,v,b[x+5],5,-701558691),v=E(v,d,h,l,b[x+10],9,38016083),l=E(l,v,d,h,b[x+15],14,-660478335),h=E(h,l,v,d,b[x+4],20,-405537848),d=E(d,h,l,v,b[x+9],5,568446438),v=E(v,d,h,l,b[x+14],9,-1019803690),l=E(l,v,d,h,b[x+3],14,-187363961),h=E(h,l,v,d,b[x+8],20,1163531501),d=E(d,h,l,v,b[x+13],5,-1444681467),v=E(v,d,h,l,b[x+2],9,-51403784),l=E(l,v,d,h,b[x+7],14,1735328473),d=O(d,h=E(h,l,v,d,b[x+12],20,-1926607734),l,v,b[x+5],4,-378558),v=O(v,d,h,l,b[x+8],11,-2022574463),l=O(l,v,d,h,b[x+11],16,1839030562),h=O(h,l,v,d,b[x+14],23,-35309556),d=O(d,h,l,v,b[x+1],4,-1530992060),v=O(v,d,h,l,b[x+4],11,1272893353),l=O(l,v,d,h,b[x+7],16,-155497632),h=O(h,l,v,d,b[x+10],23,-1094730640),d=O(d,h,l,v,b[x+13],4,681279174),v=O(v,d,h,l,b[x+0],11,-358537222),l=O(l,v,d,h,b[x+3],16,-722521979),h=O(h,l,v,d,b[x+6],23,76029189),d=O(d,h,l,v,b[x+9],4,-640364487),v=O(v,d,h,l,b[x+12],11,-421815835),l=O(l,v,d,h,b[x+15],16,530742520),d=_(d,h=O(h,l,v,d,b[x+2],23,-995338651),l,v,b[x+0],6,-198630844),v=_(v,d,h,l,b[x+7],10,1126891415),l=_(l,v,d,h,b[x+14],15,-1416354905),h=_(h,l,v,d,b[x+5],21,-57434055),d=_(d,h,l,v,b[x+12],6,1700485571),v=_(v,d,h,l,b[x+3],10,-1894986606),l=_(l,v,d,h,b[x+10],15,-1051523),h=_(h,l,v,d,b[x+1],21,-2054922799),d=_(d,h,l,v,b[x+8],6,1873313359),v=_(v,d,h,l,b[x+15],10,-30611744),l=_(l,v,d,h,b[x+6],15,-1560198380),h=_(h,l,v,d,b[x+13],21,1309151649),d=_(d,h,l,v,b[x+4],6,-145523070),v=_(v,d,h,l,b[x+11],10,-1120210379),l=_(l,v,d,h,b[x+2],15,718787259),h=_(h,l,v,d,b[x+9],21,-343485551),d=k(d,L),h=k(h,B),l=k(l,j),v=k(v,T)}return Array(d,h,l,v)}function g(b,S,d,h,l,v){return k((S=k(k(S,b),k(h,v)))<<l|S>>>32-l,d)}function I(b,S,d,h,l,v,x){return g(S&d|~S&h,b,S,l,v,x)}function E(b,S,d,h,l,v,x){return g(S&h|d&~h,b,S,l,v,x)}function O(b,S,d,h,l,v,x){return g(S^d^h,b,S,l,v,x)}function _(b,S,d,h,l,v,x){return g(d^(S|~h),b,S,l,v,x)}function k(b,S){var d=(65535&b)+(65535&S);return(b>>16)+(S>>16)+(d>>16)<<16|65535&d}n.exports=function(b){return w.hash(b,A,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,n,e){(function(t,r,s,o,a,f,p,y,D){var w;n.exports=w||function(A){for(var g,I=new Array(A),E=0;E<A;E++)!(3&E)&&(g=4294967296*Math.random()),I[E]=g>>>((3&E)<<3)&255;return I}}).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,n,e){(function(t,r,s,o,a,f,p,y,D){var w=i("./helpers");function A(E,O){E[O>>5]|=128<<24-O%32,E[15+(O+64>>9<<4)]=O;for(var _,k,b,S=Array(80),d=1732584193,h=-271733879,l=-1732584194,v=271733878,x=-1009589776,L=0;L<E.length;L+=16){for(var B=d,j=h,T=l,q=v,te=x,Q=0;Q<80;Q++){S[Q]=Q<16?E[L+Q]:I(S[Q-3]^S[Q-8]^S[Q-14]^S[Q-16],1);var K=g(g(I(d,5),(K=h,k=l,b=v,(_=Q)<20?K&k|~K&b:!(_<40)&&_<60?K&k|K&b|k&b:K^k^b)),g(g(x,S[Q]),(_=Q)<20?1518500249:_<40?1859775393:_<60?-1894007588:-899497514)),x=v,v=l,l=I(h,30),h=d,d=K}d=g(d,B),h=g(h,j),l=g(l,T),v=g(v,q),x=g(x,te)}return Array(d,h,l,v,x)}function g(E,O){var _=(65535&E)+(65535&O);return(E>>16)+(O>>16)+(_>>16)<<16|65535&_}function I(E,O){return E<<O|E>>>32-O}n.exports=function(E){return w.hash(E,A,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,n,e){(function(t,r,s,o,a,f,p,y,D){function w(O,_){var k=(65535&O)+(65535&_);return(O>>16)+(_>>16)+(k>>16)<<16|65535&k}function A(O,_){var k,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),S=new Array(1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225),d=new Array(64);O[_>>5]|=128<<24-_%32,O[15+(_+64>>9<<4)]=_;for(var h,l,v=0;v<O.length;v+=16){for(var x=S[0],L=S[1],B=S[2],j=S[3],T=S[4],q=S[5],te=S[6],Q=S[7],K=0;K<64;K++)d[K]=K<16?O[K+v]:w(w(w((l=d[K-2],I(l,17)^I(l,19)^E(l,10)),d[K-7]),(l=d[K-15],I(l,7)^I(l,18)^E(l,3))),d[K-16]),k=w(w(w(w(Q,I(l=T,6)^I(l,11)^I(l,25)),T&q^~T&te),b[K]),d[K]),h=w(I(h=x,2)^I(h,13)^I(h,22),x&L^x&B^L&B),Q=te,te=q,q=T,T=w(j,k),j=B,B=L,L=x,x=w(k,h);S[0]=w(x,S[0]),S[1]=w(L,S[1]),S[2]=w(B,S[2]),S[3]=w(j,S[3]),S[4]=w(T,S[4]),S[5]=w(q,S[5]),S[6]=w(te,S[6]),S[7]=w(Q,S[7])}return S}var g=i("./helpers"),I=function(O,_){return O>>>_|O<<32-_},E=function(O,_){return O>>>_};n.exports=function(O){return g.hash(O,A,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,n,e){(function(t,r,s,o,a,f,p,y,D){e.read=function(w,A,g,I,v){var O,_,k=8*v-I-1,b=(1<<k)-1,S=b>>1,d=-7,h=g?v-1:0,l=g?-1:1,v=w[A+h];for(h+=l,O=v&(1<<-d)-1,v>>=-d,d+=k;0<d;O=256*O+w[A+h],h+=l,d-=8);for(_=O&(1<<-d)-1,O>>=-d,d+=I;0<d;_=256*_+w[A+h],h+=l,d-=8);if(O===0)O=1-S;else{if(O===b)return _?NaN:1/0*(v?-1:1);_+=Math.pow(2,I),O-=S}return(v?-1:1)*_*Math.pow(2,O-I)},e.write=function(w,A,g,I,E,x){var _,k,b=8*x-E-1,S=(1<<b)-1,d=S>>1,h=E===23?Math.pow(2,-24)-Math.pow(2,-77):0,l=I?0:x-1,v=I?1:-1,x=A<0||A===0&&1/A<0?1:0;for(A=Math.abs(A),isNaN(A)||A===1/0?(k=isNaN(A)?1:0,_=S):(_=Math.floor(Math.log(A)/Math.LN2),A*(I=Math.pow(2,-_))<1&&(_--,I*=2),2<=(A+=1<=_+d?h/I:h*Math.pow(2,1-d))*I&&(_++,I/=2),S<=_+d?(k=0,_=S):1<=_+d?(k=(A*I-1)*Math.pow(2,E),_+=d):(k=A*Math.pow(2,d-1)*Math.pow(2,E),_=0));8<=E;w[g+l]=255&k,l+=v,k/=256,E-=8);for(_=_<<E|k,b+=E;0<b;w[g+l]=255&_,l+=v,_/=256,b-=8);w[g+l-v]|=128*x}}).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,n,e){(function(t,r,s,o,a,f,p,y,D){var w,A,g;function I(){}(t=n.exports={}).nextTick=(A=typeof window<"u"&&window.setImmediate,g=typeof window<"u"&&window.postMessage&&window.addEventListener,A?function(E){return window.setImmediate(E)}:g?(w=[],window.addEventListener("message",function(E){var O=E.source;O!==window&&O!==null||E.data!=="process-tick"||(E.stopPropagation(),0<w.length&&w.shift()())},!0),function(E){w.push(E),window.postMessage("process-tick","*")}):function(E){setTimeout(E,0)}),t.title="browser",t.browser=!0,t.env={},t.argv=[],t.on=I,t.addListener=I,t.once=I,t.off=I,t.removeListener=I,t.removeAllListeners=I,t.emit=I,t.binding=function(E){throw new Error("process.binding is not supported")},t.cwd=function(){return"/"},t.chdir=function(E){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 hi=ae((gl,Ur)=>{Ur.exports=function(n,e){var t="000000000"+n;return t.substr(t.length-e)}});var Nr=ae((yl,Vr)=>{var zo=hi(),$o=typeof window=="object"?window:self,Ko=Object.keys($o).length,qo=navigator.mimeTypes?navigator.mimeTypes.length:0,Ho=zo((qo+navigator.userAgent.length).toString(36)+Ko.toString(36),4);Vr.exports=function(){return Ho}});var qr=ae((bl,Kr)=>{var pi,zr=typeof window<"u"&&(window.crypto||window.msCrypto)||typeof self<"u"&&self.crypto;zr?($r=Math.pow(2,32)-1,pi=function(){return Math.abs(zr.getRandomValues(new Uint32Array(1))[0]/$r)}):pi=Math.random;var $r;Kr.exports=pi});var $e=ae((vl,Jr)=>{var Jt=Nr(),Hr=hi(),Qo=qr(),_t=0,gi=4,Gt=36,Qr=Math.pow(Gt,gi);function mi(){return Hr((Qo()*Qr<<0).toString(Gt),gi)}function Wr(){return _t=_t<Qr?_t:0,_t++,_t-1}function Et(){var i="c",n=new Date().getTime().toString(Gt),e=Hr(Wr().toString(Gt),gi),t=Jt(),r=mi()+mi();return i+n+e+t+r}Et.slug=function(){var n=new Date().getTime().toString(36),e=Wr().toString(36).slice(-4),t=Jt().slice(0,1)+Jt().slice(-1),r=mi().slice(-2);return n.slice(-2)+e+t+r};Et.isCuid=function(n){return typeof n!="string"?!1:!!n.startsWith("c")};Et.isSlug=function(n){if(typeof n!="string")return!1;var e=n.length;return e>=7&&e<=10};Et.fingerprint=Jt;Jr.exports=Et});var qe={};or(qe,{__addDisposableResource:()=>As,__assign:()=>fn,__asyncDelegator:()=>Ss,__asyncGenerator:()=>xs,__asyncValues:()=>Os,__await:()=>st,__awaiter:()=>ms,__classPrivateFieldGet:()=>Ds,__classPrivateFieldIn:()=>Ps,__classPrivateFieldSet:()=>Cs,__createBinding:()=>pn,__decorate:()=>fs,__disposeResources:()=>Rs,__esDecorate:()=>ga,__exportStar:()=>ys,__extends:()=>ds,__generator:()=>gs,__importDefault:()=>Es,__importStar:()=>_s,__makeTemplateObject:()=>Is,__metadata:()=>ps,__param:()=>hs,__propKey:()=>ba,__read:()=>Ci,__rest:()=>us,__runInitializers:()=>ya,__setFunctionName:()=>va,__spread:()=>bs,__spreadArray:()=>ws,__spreadArrays:()=>vs,__values:()=>hn,default:()=>Sa});function ds(i,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");Di(i,n);function e(){this.constructor=i}i.prototype=n===null?Object.create(n):(e.prototype=n.prototype,new e)}function us(i,n){var e={};for(var t in i)Object.prototype.hasOwnProperty.call(i,t)&&n.indexOf(t)<0&&(e[t]=i[t]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,t=Object.getOwnPropertySymbols(i);r<t.length;r++)n.indexOf(t[r])<0&&Object.prototype.propertyIsEnumerable.call(i,t[r])&&(e[t[r]]=i[t[r]]);return e}function fs(i,n,e,t){var r=arguments.length,s=r<3?n:t===null?t=Object.getOwnPropertyDescriptor(n,e):t,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(i,n,e,t);else for(var a=i.length-1;a>=0;a--)(o=i[a])&&(s=(r<3?o(s):r>3?o(n,e,s):o(n,e))||s);return r>3&&s&&Object.defineProperty(n,e,s),s}function hs(i,n){return function(e,t){n(e,t,i)}}function ga(i,n,e,t,r,s){function o(O){if(O!==void 0&&typeof O!="function")throw new TypeError("Function expected");return O}for(var a=t.kind,f=a==="getter"?"get":a==="setter"?"set":"value",p=!n&&i?t.static?i:i.prototype:null,y=n||(p?Object.getOwnPropertyDescriptor(p,t.name):{}),D,w=!1,A=e.length-1;A>=0;A--){var g={};for(var I in t)g[I]=I==="access"?{}:t[I];for(var I in t.access)g.access[I]=t.access[I];g.addInitializer=function(O){if(w)throw new TypeError("Cannot add initializers after decoration has completed");s.push(o(O||null))};var E=(0,e[A])(a==="accessor"?{get:y.get,set:y.set}:y[f],g);if(a==="accessor"){if(E===void 0)continue;if(E===null||typeof E!="object")throw new TypeError("Object expected");(D=o(E.get))&&(y.get=D),(D=o(E.set))&&(y.set=D),(D=o(E.init))&&r.unshift(D)}else(D=o(E))&&(a==="field"?r.unshift(D):y[f]=D)}p&&Object.defineProperty(p,t.name,y),w=!0}function ya(i,n,e){for(var t=arguments.length>2,r=0;r<n.length;r++)e=t?n[r].call(i,e):n[r].call(i);return t?e:void 0}function ba(i){return typeof i=="symbol"?i:"".concat(i)}function va(i,n,e){return typeof n=="symbol"&&(n=n.description?"[".concat(n.description,"]"):""),Object.defineProperty(i,"name",{configurable:!0,value:e?"".concat(e," ",n):n})}function ps(i,n){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(i,n)}function ms(i,n,e,t){function r(s){return s instanceof e?s:new e(function(o){o(s)})}return new(e||(e=Promise))(function(s,o){function a(y){try{p(t.next(y))}catch(D){o(D)}}function f(y){try{p(t.throw(y))}catch(D){o(D)}}function p(y){y.done?s(y.value):r(y.value).then(a,f)}p((t=t.apply(i,n||[])).next())})}function gs(i,n){var e={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},t,r,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(p){return function(y){return f([p,y])}}function f(p){if(t)throw new TypeError("Generator is already executing.");for(;o&&(o=0,p[0]&&(e=0)),e;)try{if(t=1,r&&(s=p[0]&2?r.return:p[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,p[1])).done)return s;switch(r=0,s&&(p=[p[0]&2,s.value]),p[0]){case 0:case 1:s=p;break;case 4:return e.label++,{value:p[1],done:!1};case 5:e.label++,r=p[1],p=[0];continue;case 7:p=e.ops.pop(),e.trys.pop();continue;default:if(s=e.trys,!(s=s.length>0&&s[s.length-1])&&(p[0]===6||p[0]===2)){e=0;continue}if(p[0]===3&&(!s||p[1]>s[0]&&p[1]<s[3])){e.label=p[1];break}if(p[0]===6&&e.label<s[1]){e.label=s[1],s=p;break}if(s&&e.label<s[2]){e.label=s[2],e.ops.push(p);break}s[2]&&e.ops.pop(),e.trys.pop();continue}p=n.call(i,e)}catch(y){p=[6,y],r=0}finally{t=s=0}if(p[0]&5)throw p[1];return{value:p[0]?p[1]:void 0,done:!0}}}function ys(i,n){for(var e in i)e!=="default"&&!Object.prototype.hasOwnProperty.call(n,e)&&pn(n,i,e)}function hn(i){var n=typeof Symbol=="function"&&Symbol.iterator,e=n&&i[n],t=0;if(e)return e.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&t>=i.length&&(i=void 0),{value:i&&i[t++],done:!i}}};throw new TypeError(n?"Object is not iterable.":"Symbol.iterator is not defined.")}function Ci(i,n){var e=typeof Symbol=="function"&&i[Symbol.iterator];if(!e)return i;var t=e.call(i),r,s=[],o;try{for(;(n===void 0||n-- >0)&&!(r=t.next()).done;)s.push(r.value)}catch(a){o={error:a}}finally{try{r&&!r.done&&(e=t.return)&&e.call(t)}finally{if(o)throw o.error}}return s}function bs(){for(var i=[],n=0;n<arguments.length;n++)i=i.concat(Ci(arguments[n]));return i}function vs(){for(var i=0,n=0,e=arguments.length;n<e;n++)i+=arguments[n].length;for(var t=Array(i),r=0,n=0;n<e;n++)for(var s=arguments[n],o=0,a=s.length;o<a;o++,r++)t[r]=s[o];return t}function ws(i,n,e){if(e||arguments.length===2)for(var t=0,r=n.length,s;t<r;t++)(s||!(t in n))&&(s||(s=Array.prototype.slice.call(n,0,t)),s[t]=n[t]);return i.concat(s||Array.prototype.slice.call(n))}function st(i){return this instanceof st?(this.v=i,this):new st(i)}function xs(i,n,e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=e.apply(i,n||[]),r,s=[];return r={},o("next"),o("throw"),o("return"),r[Symbol.asyncIterator]=function(){return this},r;function o(w){t[w]&&(r[w]=function(A){return new Promise(function(g,I){s.push([w,A,g,I])>1||a(w,A)})})}function a(w,A){try{f(t[w](A))}catch(g){D(s[0][3],g)}}function f(w){w.value instanceof st?Promise.resolve(w.value.v).then(p,y):D(s[0][2],w)}function p(w){a("next",w)}function y(w){a("throw",w)}function D(w,A){w(A),s.shift(),s.length&&a(s[0][0],s[0][1])}}function Ss(i){var n,e;return n={},t("next"),t("throw",function(r){throw r}),t("return"),n[Symbol.iterator]=function(){return this},n;function t(r,s){n[r]=i[r]?function(o){return(e=!e)?{value:st(i[r](o)),done:!1}:s?s(o):o}:s}}function Os(i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=i[Symbol.asyncIterator],e;return n?n.call(i):(i=typeof hn=="function"?hn(i):i[Symbol.iterator](),e={},t("next"),t("throw"),t("return"),e[Symbol.asyncIterator]=function(){return this},e);function t(s){e[s]=i[s]&&function(o){return new Promise(function(a,f){o=i[s](o),r(a,f,o.done,o.value)})}}function r(s,o,a,f){Promise.resolve(f).then(function(p){s({value:p,done:a})},o)}}function Is(i,n){return Object.defineProperty?Object.defineProperty(i,"raw",{value:n}):i.raw=n,i}function _s(i){if(i&&i.__esModule)return i;var n={};if(i!=null)for(var e in i)e!=="default"&&Object.prototype.hasOwnProperty.call(i,e)&&pn(n,i,e);return wa(n,i),n}function Es(i){return i&&i.__esModule?i:{default:i}}function Ds(i,n,e,t){if(e==="a"&&!t)throw new TypeError("Private accessor was defined without a getter");if(typeof n=="function"?i!==n||!t:!n.has(i))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e==="m"?t:e==="a"?t.call(i):t?t.value:n.get(i)}function Cs(i,n,e,t,r){if(t==="m")throw new TypeError("Private method is not writable");if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof n=="function"?i!==n||!r:!n.has(i))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t==="a"?r.call(i,e):r?r.value=e:n.set(i,e),e}function Ps(i,n){if(n===null||typeof n!="object"&&typeof n!="function")throw new TypeError("Cannot use 'in' operator on non-object");return typeof i=="function"?n===i:i.has(n)}function As(i,n,e){if(n!=null){if(typeof n!="object"&&typeof n!="function")throw new TypeError("Object expected.");var t;if(e){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");t=n[Symbol.asyncDispose]}if(t===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");t=n[Symbol.dispose]}if(typeof t!="function")throw new TypeError("Object not disposable.");i.stack.push({value:n,dispose:t,async:e})}else e&&i.stack.push({async:!0});return n}function Rs(i){function n(t){i.error=i.hasError?new xa(t,i.error,"An error was suppressed during disposal."):t,i.hasError=!0}function e(){for(;i.stack.length;){var t=i.stack.pop();try{var r=t.dispose&&t.dispose.call(t.value);if(t.async)return Promise.resolve(r).then(e,function(s){return n(s),e()})}catch(s){n(s)}}if(i.hasError)throw i.error}return e()}var Di,fn,pn,wa,xa,Sa,He=po(()=>{Di=function(i,n){return Di=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},Di(i,n)};fn=function(){return fn=Object.assign||function(n){for(var e,t=1,r=arguments.length;t<r;t++){e=arguments[t];for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&(n[s]=e[s])}return n},fn.apply(this,arguments)};pn=Object.create?function(i,n,e,t){t===void 0&&(t=e);var r=Object.getOwnPropertyDescriptor(n,e);(!r||("get"in r?!n.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return n[e]}}),Object.defineProperty(i,t,r)}:function(i,n,e,t){t===void 0&&(t=e),i[t]=n[e]};wa=Object.create?function(i,n){Object.defineProperty(i,"default",{enumerable:!0,value:n})}:function(i,n){i.default=n};xa=typeof SuppressedError=="function"?SuppressedError:function(i,n,e){var t=new Error(e);return t.name="SuppressedError",t.error=i,t.suppressed=n,t};Sa={__extends:ds,__assign:fn,__rest:us,__decorate:fs,__param:hs,__metadata:ps,__awaiter:ms,__generator:gs,__createBinding:pn,__exportStar:ys,__values:hn,__read:Ci,__spread:bs,__spreadArrays:vs,__spreadArray:ws,__await:st,__asyncGenerator:xs,__asyncDelegator:Ss,__asyncValues:Os,__makeTemplateObject:Is,__importStar:_s,__importDefault:Es,__classPrivateFieldGet:Ds,__classPrivateFieldSet:Cs,__classPrivateFieldIn:Ps,__addDisposableResource:As,__disposeResources:Rs}});var Ts=ae(Fs=>{"use strict";Object.defineProperty(Fs,"__esModule",{value:!0})});var Ai=ae(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.invokeEventHandlersAsync=Oe.invokeEventHandlers=Oe.eventHandlerSafeInvokeAsync=Oe.eventHandlerSafeInvoke=void 0;var ks=(He(),Ge(qe));function Bs(i,n,e){try{return i(n,e),{succeeded:!0}}catch(t){return{error:t,succeeded:!1}}}Oe.eventHandlerSafeInvoke=Bs;function Pi(i,n,e){return(0,ks.__awaiter)(this,void 0,void 0,function*(){try{return yield i(n,e),{succeeded:!0}}catch(t){return{error:t,succeeded:!1}}})}Oe.eventHandlerSafeInvokeAsync=Pi;function Oa(i,n,e,t){for(let r of i){let{succeeded:s,error:o}=Bs(r,n,e);if(!s&&t?.swallowExceptions!==!0)throw o}}Oe.invokeEventHandlers=Oa;function Ia(i,n,e,t){return(0,ks.__awaiter)(this,void 0,void 0,function*(){if(t?.parallelize===!1)for(let r of i){let{succeeded:s,error:o}=yield Pi(r,n,e);if(!s&&t?.swallowExceptions!==!0)throw o}else{let r=[];for(let s of i)r.push(Pi(s,n,e).then(({succeeded:o,error:a})=>{if(!o&&t?.swallowExceptions!==!0)throw a}));yield Promise.all(r)}})}Oe.invokeEventHandlersAsync=Ia});var Ms=ae(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.TypedEvent=void 0;var _a=(He(),Ge(qe)),Ls=Ai(),js={swallowExceptions:!1,parallelize:!0},Ri=class{constructor(){this._handlers=[]}attach(n){this._handlers.push(n)}detach(n){this.tryRemoveHandler(n)}invoke(n,e,t=js){(0,Ls.invokeEventHandlers)(this._handlers,n,e,t)}invokeAsync(n,e,t=js){return(0,_a.__awaiter)(this,void 0,void 0,function*(){yield(0,Ls.invokeEventHandlersAsync)(this._handlers,n,e,t)})}tryRemoveHandler(n){let e=this._handlers.findIndex(t=>t===n);e>=0&&this._handlers.splice(e,1)}};mn.TypedEvent=Ri});var Ti=ae(Fi=>{"use strict";Object.defineProperty(Fi,"__esModule",{value:!0});var Ea=(He(),Ge(qe));(0,Ea.__exportStar)(Ms(),Fi)});var Us=ae(gn=>{"use strict";Object.defineProperty(gn,"__esModule",{value:!0});gn.FinalizationRegistryMissingError=void 0;var ki=class extends Error{};gn.FinalizationRegistryMissingError=ki});var Li=ae(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.WeakHandlerHolder=void 0;var Da=Us(),Bi=class{constructor(n){this._refs=[];try{this._finalizationRegistry=new FinalizationRegistry(n)}catch(e){throw e.name==="FinalizationRegistry"?new Da.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(n,e){let t=new WeakRef(e);return this._finalizationRegistry.register(e,{eventSource:n,handlerRef:t},t),this._refs.push(t),t}releaseWeakHandler(n){let t=this._refs.find(r=>r?.deref()===n)||new WeakRef(n);return this._finalizationRegistry.unregister(t),t}unregisterRef(n){this._finalizationRegistry.unregister(n)}};yn.WeakHandlerHolder=Bi});var Vs=ae(bn=>{"use strict";Object.defineProperty(bn,"__esModule",{value:!0});bn.WeakEvent=void 0;var ji=(He(),Ge(qe)),Ca=Ti(),Pa=Li(),Mi=Ai(),Aa={swallowExceptions:!1,parallelize:!0},Ui=class{constructor(){this._handlers=[],this._handlerFinalizedEvent=new Ca.TypedEvent,this.handlerFinalizedEvent=this._handlerFinalizedEvent,this._refHolder=new Pa.WeakHandlerHolder(n=>{this.onHandlerFinalizer(n)})}invoke(n,e,t){for(let r of this._handlers){let s=r?.deref();if(s){let{succeeded:o,error:a}=(0,Mi.eventHandlerSafeInvoke)(s,n,e);if(!o&&t?.swallowExceptions!==!0)throw a}else this.releaseHandler(r)}}invokeAsync(n,e,t=Aa){return(0,ji.__awaiter)(this,void 0,void 0,function*(){t?.parallelize===!1?yield this.sequentialInvokeAsync(n,e,t):yield this.parallelInvokeAsync(n,e,t)})}sequentialInvokeAsync(n,e,t){return(0,ji.__awaiter)(this,void 0,void 0,function*(){for(let r of this._handlers){let s=r?.deref();if(s){let{succeeded:o,error:a}=yield(0,Mi.eventHandlerSafeInvokeAsync)(s,n,e);if(!o&&t.swallowExceptions!==!0)throw a}else this.releaseHandler(r)}})}parallelInvokeAsync(n,e,t){return(0,ji.__awaiter)(this,void 0,void 0,function*(){let r=[];for(let s of this._handlers){let o=s?.deref();o?r.push((0,Mi.eventHandlerSafeInvokeAsync)(o,n,e).then(({succeeded:a,error:f})=>{if(!a&&t.swallowExceptions!==!0)throw f})):this.releaseHandler(s)}yield Promise.all(r)})}attach(n){this._handlers.push(this._refHolder.getWeakHandler(this,n))}detach(n){let e=this._refHolder.releaseWeakHandler(n);this.tryRemoveHandlerRef(e)}onHandlerFinalizer(n){this.tryRemoveHandlerRef(n?.handlerRef),this._handlerFinalizedEvent.invokeAsync(this,n,{swallowExceptions:!0})}tryRemoveHandlerRef(n){let e=this._handlers.findIndex(t=>t===n);e>=0&&this._handlers.splice(e,1)}releaseHandler(n){this._refHolder.unregisterRef(n),this.tryRemoveHandlerRef(n)}};bn.WeakEvent=Ui});var zs=ae(vn=>{"use strict";Object.defineProperty(vn,"__esModule",{value:!0});var Ns=(He(),Ge(qe));(0,Ns.__exportStar)(Li(),vn);(0,Ns.__exportStar)(Vs(),vn)});var $s=ae(Ft=>{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});var Vi=(He(),Ge(qe));(0,Vi.__exportStar)(Ts(),Ft);(0,Vi.__exportStar)(Ti(),Ft);(0,Vi.__exportStar)(zs(),Ft)});var tr={};or(tr,{Client:()=>ut,ClientDescriptor:()=>Yn,Entity:()=>de,EntityFile:()=>ve,IdbPersistence:()=>ft,ServerSync:()=>dt,Storage:()=>ut,StorageDescriptor:()=>Yn,UndoHistory:()=>ht,authorization:()=>lc,cliSync:()=>dc,createMigration:()=>ui,getEntityClient:()=>ls,id:()=>uc,schema:()=>Ct});function mo(i){return typeof Buffer<"u"?Buffer.from(i).toString("base64"):btoa(i)}function go(i){return typeof Buffer<"u"?Buffer.from(i,"base64").toString():atob(i)}var Ue={onlyUser:i=>mo(`u:${i}:*`),onlyMe:()=>Ue.onlyUser(ei),decode:i=>{let e=go(i).split(":");if(e.length!==3)throw new Error("Invalid authz string");return{scope:e[0],subject:e[1],action:e[2]}}},ei="$$_originator_$$";function cr(i,n){let{operations:e,baselines:t}=i;if(e)for(let r of e)r.authz&&Ue.decode(r.authz).subject===ei&&(r.authz=Ue.onlyUser(n));if(t)for(let r of t)r.authz&&Ue.decode(r.authz).subject===ei&&(r.authz=Ue.onlyUser(n))}var Ye=class{constructor(n){this.flusher=n,this.batches=new Map,this.flush=e=>{let t=this.batches.get(e);if(t)return t.flush()},this.discard=e=>{let t=this.batches.get(e);t&&(t.discard(),this.batches.delete(e))},this.flushAll=()=>[...this.batches.values()].map(e=>e.flush()),this.getSize=e=>{let t=this.batches.get(e);return t?t.items.length:0}}add({key:n,userData:e,items:t,max:r,timeout:s}){let o=this.batches.get(n);return o||(o=new ti({max:r||null,startedAt:Date.now(),userData:e,timeout:s||null,flusher:this.flusher,key:n}),this.batches.set(n,o)),o.update({items:t,max:r,timeout:s,userData:e}),o}},ti=class{constructor({max:n,startedAt:e,timeout:t,userData:r,flusher:s,key:o}){this.items=[],this.update=({items:a,max:f,timeout:p,userData:y})=>{this.items.push(...a),f!==void 0&&(this.max=f),p!==void 0&&(this.timeout=p),y&&(this.userData=y);let D=this.items.length!==0&&this.timeout!==null&&!this.flushTimeout;this.max!==null&&this.items.length>=this.max?this.flush():D&&this.timeout!==null&&(this.flushTimeout=setTimeout(this.flush,this.timeout))},this.flush=()=>{this.flushTimeout&&clearTimeout(this.flushTimeout),this.flushTimeout=void 0;let a=this.items;return this.items=[],this.flusher(a,this.key,this.userData)},this.discard=()=>{this.flushTimeout&&clearTimeout(this.flushTimeout),this.flushTimeout=void 0,this.items=[]},this.max=n,this.startedAt=e,this.timeout=t,this.userData=r,this.flusher=s,this.key=o}};var pt;(function(i){i[i.InvalidRequest=4e3]="InvalidRequest",i[i.BodyRequired=4001]="BodyRequired",i[i.NoToken=4010]="NoToken",i[i.InvalidToken=4011]="InvalidToken",i[i.TokenExpired=4012]="TokenExpired",i[i.Forbidden=4030]="Forbidden",i[i.NotFound=4040]="NotFound",i[i.Unexpected=5e3]="Unexpected",i[i.ConfigurationError=5010]="ConfigurationError",i[i.NoFileStorage=5011]="NoFileStorage",i[i.MigrationPathNotFound=7001]="MigrationPathNotFound",i[i.ImportFailed=7002]="ImportFailed",i[i.Offline=7003]="Offline"})(pt||(pt={}));var H=class extends Error{constructor(n,e,t){super(t??`Verdant error: ${n}`,{cause:e}),this.code=n,this.toResponse=()=>JSON.stringify({code:this.code})}get httpStatus(){let n=Math.floor(this.code/10);return n<600?n:500}};H.Code=pt;function lr(i){return typeof i=="object"&&"code"in i&&typeof i.code=="number"}var Mt,yo=new Uint8Array(16);function ni(){if(!Mt&&(Mt=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!Mt))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Mt(yo)}var dr=/^(?:[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 bo(i){return typeof i=="string"&&dr.test(i)}var ur=bo;var ee=[];for(Ut=0;Ut<256;++Ut)ee.push((Ut+256).toString(16).substr(1));var Ut;function vo(i){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=(ee[i[n+0]]+ee[i[n+1]]+ee[i[n+2]]+ee[i[n+3]]+"-"+ee[i[n+4]]+ee[i[n+5]]+"-"+ee[i[n+6]]+ee[i[n+7]]+"-"+ee[i[n+8]]+ee[i[n+9]]+"-"+ee[i[n+10]]+ee[i[n+11]]+ee[i[n+12]]+ee[i[n+13]]+ee[i[n+14]]+ee[i[n+15]]).toLowerCase();if(!ur(e))throw TypeError("Stringified UUID is invalid");return e}var fr=vo;function wo(i,n,e){i=i||{};var t=i.random||(i.rng||ni)();if(t[6]=t[6]&15|64,t[8]=t[8]&63|128,n){e=e||0;for(var r=0;r<16;++r)n[e+r]=t[r];return n}return fr(t)}var mt=wo;var gr=Ae(mr(),1);function xo(i,n){return typeof n!="object"||n===null||Array.isArray(n)?n:Object.fromEntries(Object.entries(n).sort(([e],[t])=>e<t?-1:e>t?1:0))}function ii(i){let n=new WeakMap,e=0;return JSON.stringify(i,(t,r)=>{if(typeof r=="object"&&r!==null){if(n.has(r))return{$ref:n.get(r)};n.set(r,`cyclic-ref:${e++}`)}return xo(t,r)})}function ce(i,n=!0){if(!n&&typeof structuredClone=="function")return structuredClone(i);if(M(i)||Array.isArray(i)){let e=ne(i),t;if(Array.isArray(i))t=i.map(r=>ce(r,n));else{t={};for(let[r,s]of Object.entries(i))t[r]=ce(s,n)}return n&&e&&$(t,e),t}return i}function Ve(i){return(0,gr.default)(i)}function M(i){return i&&typeof i=="object"}function yr(i){for(var n=[],e=[i],t=0;e.length;){var r=e.pop();if(typeof r=="boolean")t+=4;else if(typeof r=="string")t+=r.length*2;else if(typeof r=="number")t+=8;else if(typeof r=="object"&&n.indexOf(r)===-1){n.push(r);for(var s in r)e.push(r[s])}}return t}function N(i,n="assertion failed"){if(!i)throw new Error(n)}function gt(i=16){return mt().replace("-","").slice(0,i)}function br(i,n){for(let e=i.length-1;e>=0;e--)if(n(i[e]))return e;return-1}function vr(i,n){let e;return function(...t){let r=this;clearTimeout(e),e=setTimeout(()=>i.apply(r,t),n)}}function wr(i,n){let e=0,t;return function(...r){let s=this,o=Date.now();o-e>=n?(e=o,i.apply(s,r),clearTimeout(t)):(clearTimeout(t),t=setTimeout(()=>{e=o,i.apply(s,r)},n))}}function xr(){}function ge(i){return i&&i["@@type"]==="file"}function yt(i){return{"@@type":"file",id:i}}function Xe(i){return typeof File<"u"&&i instanceof File||typeof Blob<"u"&&i instanceof Blob}function Vt(i){return i&&M(i)&&typeof i.id=="string"&&typeof i.remote=="boolean"&&typeof i.name=="string"&&typeof i.type=="string"}function J(i){return we(i)||ge(i)}function Ne(i,n){return i===n?!0:!(!J(i)||!J(n)||i["@@type"]!==n["@@type"]||i.id!==n.id)}function we(i){return i&&typeof i=="object"&&i["@@type"]==="ref"}function Ze(i,n,e,t,r=[],s){$(i,n),et(i,t);let o=Kt(i);for(let a of o.keys()){let f=o.get(a),p={oid:a,timestamp:e(),data:{op:"initialize",value:$t(f)}};r.push(So(p,s?.authz))}return r}function So(i,n){return n&&(i.authz=n),i}function bt(i){let n={};for(let e of i)e.oid in n?n[e.oid].push(e):n[e.oid]=[e];return n}function Or(i){let n={};for(let e of i){let t=z(e.oid);t in n?n[t].push(e):n[t]=[e]}return n}function Ir(i){let n={};for(let e of i){let t=z(e.oid);t in n?n[t].push(e):n[t]=[e]}return n}function Re(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: ${ne(i)})`),!1)}function Fe(i,n,e){if(i==null&&n.op!=="initialize")return i;let t=i,r,s;function o(a){e&&J(a)&&e.push(a)}switch(n.op){case"set":o(t[n.name]),t[n.name]=n.value;break;case"remove":o(t[n.name]),delete t[n.name];break;case"list-set":Re(i)&&(o(i[n.index]),i[n.index]=n.value);break;case"list-push":Re(i)&&i.push(n.value);break;case"list-delete":Re(i)&&(o(i[n.index]),i.splice(n.index,n.count));break;case"list-move-by-index":Re(i)&&(s=i.splice(n.from,1),i.splice(n.to,0,s[0]));break;case"list-remove":if(Re(i))do{let a=n.value;n.only==="last"?we(a)?r=br(i,f=>f.id===a.id):r=i.lastIndexOf(a):we(a)?r=i.findIndex(f=>f.id===a.id):r=i.indexOf(a),r!==-1&&(o(i[r]),i.splice(r,1))}while(!n.only&&r!==-1);break;case"list-add":Re(i)&&(i.some(f=>we(f)&&we(n.value)?f.id===n.value.id:f===n.value)||i.push(n.value));break;case"list-move-by-ref":Re(i)&&(r=i.findIndex(a=>Ne(a,n.value)),s=i.splice(r,1),i.splice(n.index,0,s[0]));break;case"list-insert":if(Re(i)){if(!n.value&&!n.values)throw new Error(`Cannot apply list insert patch; expected value or values, received ${JSON.stringify(n)}`);n.value?i.splice(n.index,0,n.value):i.splice(n.index,0,...n.values)}break;case"delete":Array.isArray(i)?i.forEach(o):M(i)&&Object.values(i||{}).forEach(o);return;case"initialize":return ce(n.value);case"touch":return i;default:throw new Error(`Unsupported patch operation: ${n.op}`)}return i}function Nt(i,n,e=[]){if(Array.isArray(i))for(let t=0;t<i.length;t++){let r=i[t];i[t]=Sr(r,n,e),M(i[t])&&Nt(i[t],n,e)}else if(!ge(i)){if(M(i)){N(ne(i),`Object ${JSON.stringify(i)} must have an oid`);for(let t of Object.keys(i))i[t]=Sr(i[t],n,e),M(i[t])&&Nt(i[t],n,e)}}return e}function Sr(i,n,e){if(we(i)){e.push(i.id);let t=n.get(i.id);return N(!!t,`No value was found in object map for ${i.id}`),$(t,i.id)}else return i}function _r(i){return i.data.op==="set"?i.data.name:!1}function Er(i,n){return n.has(!0)?!0:i.data.op==="set"||i.data.op==="remove"?n.has(i.data.name):!1}function zt(i){return{oid:i.oid,timestamp:i.timestamp,data:i.data,authz:i.authz}}var Oo="/",vt=":",si=new WeakMap;function ie(i){let n=ne(i);return N(!!n,`Object ${JSON.stringify(i)} does not have an OID assigned to it`),n}function ne(i){if(M(i))return si.get(i)}function $(i,n){return N(M(i),`Only objects can be assigned OIDs, received ${JSON.stringify(i)}`),Ar(i)&&$t(i),si.set(i,n),i}function Ar(i){return!!ne(i)}function $t(i){return si.delete(i),i}function Dr(i,n,e){if(Ar(i)){let t=ie(i);if(ke(t,n))return ie(i);{let r=Te(n,e);return $(i,r),r}}else{let t=Te(n,e);return $(i,t),t}}var ri={".":"&dot;","/":"&slash;",":":"&colon;"};function Cr(i){return i.replace(/[/]/g,ri["/"]).replace(/[:]/g,ri[":"]).replace(/[.]/g,ri["."])}function Pr(i){return i.replace(/&slash;/g,"/").replace(/&colon;/g,":").replace(/&dot;/g,".")}function Z(i,n,e){let t=Cr(i)+Oo+Cr(n);return e&&(t+=vt+e),t}function Te(i,n=Io){let{collection:e,id:t}=le(i);return Z(e,t,n())}function le(i){let[n,e,...t]=i.split("/");t.length&&(console.error(`OID ${i} has more than 3 segments. Attempting to parse it anyway.`),e+="/"+t.join("/"));let[r,s]=e.split(vt),o;return r.includes(".")?o=r.slice(0,r.indexOf(".")):o=r,{collection:Pr(n),id:Pr(o),subId:s}}function et(i,n){let e=ie(i);if(Array.isArray(i)){let t;for(let r=0;r<i.length;r++)t=i[r],M(t)&&!J(t)&&(Dr(t,e,n),et(t,n))}else if(M(i)&&!J(i))for(let t of Object.keys(i))M(i[t])&&!J(i[t])&&(Dr(i[t],e,n),et(i[t],n))}function qt(i){if($t(i),Array.isArray(i))for(let n=0;n<i.length;n++)qt(i[n]);else if(M(i))for(let n of Object.keys(i))qt(i[n])}function Io(){return mt().slice(0,8)}function ye(i){return{"@@type":"ref",id:i}}function Kt(i,n=new Map){if(Array.isArray(i)){let e=ie(i),t=$([],e);for(let r=0;r<i.length;r++){let s=i[r];if(M(s)){if(we(s))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(ge(s)){t[r]=s;continue}else{let o=ie(s);t[r]=ye(o),Kt(s,n)}}else t[r]=s}n.set(e,t)}else if(M(i)&&!J(i)){let e=ie(i),t=$({},e);for(let r of Object.keys(i)){let s=i[r];if(M(s)){if(we(s))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(ge(s))t[r]=s;else{let o=ie(s);t[r]=ye(o),Kt(s,n)}}else t[r]=s}n.set(e,t)}else J(i);return n}function z(i){return i.split(".")[0].split(vt)[0]}function Rr(i){let n=z(i),e=Te(n,()=>"\uFFFF");return[`${n}${vt}`,e]}function ke(i,n){return z(i)===z(n)}function Ht(i){return!i.includes(vt)}var tt="__@@oid_do_not_use",_e="@@id";function _o(i){if(M(i))return i[_e]||i[tt]}function Eo(i){return M(i)&&(delete i[tt],delete i[_e]),i}function Do(i){let n=_o(i);n&&$(i,n)}function wt(i){if(Do(i),Eo(i),Array.isArray(i))for(let n=0;n<i.length;n++)wt(i[n]);else if(M(i))for(let n of Object.keys(i))wt(i[n])}function Co(i){let{collection:n,id:e,subId:t}=le(i);return Z(n,e,t)}var Po=/"\w+\/[^"]+?(\.[^"]+)+\:[\S]+?"/g;function Ao(i){return i.replaceAll(Po,n=>{let e=n.slice(1,n.length-1);return`"${Co(e)}"`})}function oi(i){return JSON.parse(Ao(JSON.stringify(i)))}function Fr(i){let n=z(i);return[`${n}.`,`${n}.\uFFFF`]}function ai(i){return i===_e||i===tt}var nt=class{constructor(n,e){this.getNow=n,this.createSubId=e,this.isPrimitive=t=>!M(t)||J(t),this.createDiff=(t,r,s={})=>Qt(t,r,this.getNow,this.createSubId,[],s),this.createInitialize=(t,r,s)=>Ze(t,r,this.getNow,this.createSubId,void 0,s?{authz:s}:void 0),this.createSet=(t,r,s,o)=>{if(this.isPrimitive(s))return[{oid:t,timestamp:this.getNow(),data:{op:"set",name:r,value:s},authz:o}];{let a=Te(t,this.createSubId);return[...Ze(s,a,this.getNow,this.createSubId,void 0,{authz:o}),{oid:t,timestamp:this.getNow(),data:{op:"set",value:ye(a),name:r},authz:o}]}},this.createRemove=(t,r,s)=>[{oid:t,timestamp:this.getNow(),data:{op:"remove",name:r},authz:s}],this.createListSet=(t,r,s,o)=>{if(this.isPrimitive(s))return[{oid:t,timestamp:this.getNow(),data:{op:"list-set",index:r,value:s},authz:o}];{let a=Te(t,this.createSubId);return[...Ze(s,a,this.getNow,this.createSubId,void 0,{authz:o}),{oid:t,timestamp:this.getNow(),data:{op:"list-set",index:r,value:ye(a)},authz:o}]}},this.createListPush=(t,r,s)=>{if(this.isPrimitive(r))return[{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:r},authz:s}];{let o=Te(t,this.createSubId);return[...Ze(r,o,this.getNow,void 0,void 0,{authz:s}),{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:ye(o)},authz:s}]}},this.createListAdd=(t,r,s)=>this.isPrimitive(r)?[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:r},authz:s}]:[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:ye(r)},authz:s}],this.createListInsert=(t,r,s,o)=>{if(this.isPrimitive(s))return[{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:s,index:r},authz:o}];{let a=Te(t,this.createSubId);return[...Ze(s,a,this.getNow,void 0,void 0,{authz:o}),{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:ye(a),index:r},authz:o}]}},this.createListRemove=(t,r,s,o)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-remove",value:r,only:s},authz:o}],this.createListDelete=(t,r,s=1,o)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-delete",index:r,count:s},authz:o}],this.createListMoveByRef=(t,r,s,o)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-move-by-ref",value:r,index:s},authz:o}],this.createListMoveByIndex=(t,r,s,o)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-move-by-index",from:r,to:s},authz:o}],this.createDelete=(t,r)=>[{oid:t,timestamp:this.getNow(),data:{op:"delete"},authz:r}],this.createDeleteAll=(t,r)=>t.map(s=>({oid:s,timestamp:this.getNow(),data:{op:"delete"},authz:r}))}};function xt(i,n){if(i===n)return!0;if(J(i)&&J(n))return Ne(i,n);let e=ne(i),t=ne(n);return!!(e&&t&&e===t)}function Tr(i,n,e,t){if(!Ot(n))return n;let r=ne(n);if(!r)t.mergeUnknownObjects&&e&&$(n,e);else if(!ke(i,r))return ce(n,!1);return n}function Ot(i){return M(i)&&!J(i)}function Qt(i,n,e,t,r,s){var o;let a={patches:[],mergeUnknownObjects:s?.mergeUnknownObjects,merge:(o=s?.merge)!==null&&o!==void 0?o:s?.defaultUndefined,authz:s?.authz,patchCreator:new nt(e,t)};return ci(i,n,a),a.patches}function ci(i,n,e){if(Array.isArray(i)&&Array.isArray(n))Ro(i,n,e);else{if(Array.isArray(i)||Array.isArray(n))throw new H(H.Code.Unexpected,void 0,"Cannot diff between array and non-array");Ot(i)&&Ot(n)&&Fo(i,n,e)}}function Ro(i,n,e){let t=ie(i),r=[...i];for(let a=0;a<n.length;a++){let f=n[a],p=i[a];n[a]=Tr(t,f,ne(p),e)}let s=!0;for(let a=0;a<n.length;a++){let f=n[a],p=r[a];if(f===void 0&&(s=!1),s&&a>=r.length)e.patches.push(...e.patchCreator.createListPush(t,f,e.authz));else if(xt(f,p))ci(p,f,e);else{let D=a===0||xt(n[a-1],r[a-1]),w=a===n.length-1||xt(n[a+1],r[a]);D&&w?(e.patches.push(...e.patchCreator.createListInsert(t,a,f,e.authz)),r.splice(a,0,void 0)):e.patches.push(...e.patchCreator.createListSet(t,a,f,e.authz))}}let o=r.length-n.length;if(o>0){for(let a=n.length;a<r.length;a++){let f=r[a];St(f,e)}e.patches.push(...e.patchCreator.createListDelete(t,n.length,o,e.authz))}}function Fo(i,n,e){let t=new Set(Object.keys(i)),r=ie(i);for(let s in n){let o=n[s];if(o===void 0&&e.merge||(t.delete(s),ai(s)))continue;let a=i[s];Ot(o)?(Tr(r,o,ne(a),e),a?xt(o,a)?ci(a,o,e):(e.patches.push(...e.patchCreator.createSet(r,s,o,e.authz)),St(a,e)):e.patches.push(...e.patchCreator.createSet(r,s,o,e.authz))):xt(o,a)||(o===void 0?e.patches.push(...e.patchCreator.createRemove(r,s,e.authz)):e.patches.push(...e.patchCreator.createSet(r,s,o,e.authz)),St(a,e))}if(!e.merge)for(let s of t)ai(s)||(e.patches.push(...e.patchCreator.createRemove(r,s,e.authz)),St(i[s],e))}function St(i,n){if(!Ot(i))return;let e=ne(i);if(e){n.patches.push(...n.patchCreator.createDelete(e,n.authz));for(let t in i){let r=i[t];St(r,n)}}}var V=class{constructor(n){this._onAllUnsubscribed=n,this.subscribers={},this.counts={},this._disabled=!1,this.disposed=!1,this.subscriberCount=e=>{var t;return(t=this.counts[e])!==null&&t!==void 0?t:0},this.totalSubscriberCount=()=>Object.values(this.counts).reduce((e,t)=>e+t,0),this.subscribe=(e,t)=>{let r=gt(),s=this.subscribers[e];return s||(s=this.subscribers[e]={}),s[r]=t,this.counts[e]=(this.counts[e]||0)+1,()=>{this.subscribers[e]&&(delete this.subscribers[e][r],this.counts[e]--,this.counts[e]===0&&(delete this.subscribers[e],delete this.counts[e],this._onAllUnsubscribed&&this._onAllUnsubscribed(e)))}},this.emit=(e,...t)=>{this._disabled||this.subscribers[e]&&Object.values(this.subscribers[e]).forEach(r=>r(...t))},this.dispose=()=>{this._disabled=!0,this.disposed=!0;let e=Object.keys(this.subscribers);this.subscribers={},this.counts={},e.forEach(t=>{this._onAllUnsubscribed&&this._onAllUnsubscribed(t)})},this.disable=()=>{this._disabled=!0}}get disabled(){return this._disabled}};var Wt="\uFFFFFE",To="\0",ko="\uFFFFFF";function fe(...i){let n=Bo(i);return n.length===1?n[0]:n}function Ee(...i){return i.join(Wt)+`${ko}`}function xe(...i){return i.join(Wt)+`${Wt}${To}`}function Bo(i){let n=[[]];for(let e of i)if(Array.isArray(e)){let t=[];for(let r of n)for(let s of e)t.push(r.concat(s));n=t}else for(let t of n)t.push(`${e}`);return Array.from(new Set(n.map(e=>e.join(Wt))))}function kr(i){return!!i.field}function Lo(i,n){let e={};for(let[t,r]of Object.entries(i.indexes||{})){let s=r;kr(s)?e[t]=be(n[s.field]):e[t]=be(s.compute(n))}return e}function jo(i,n){return Object.entries(i.compounds||{}).reduce((e,[t,r])=>(e[t]=fe(...r.of.map(s=>n[s])),e),{})}function Mo(i,n){return Object.entries(i.fields).reduce((e,[t,r])=>("indexed"in r&&(e[t]=be(n[t])),e),{})}function li(i,n){let e=Object.assign(Object.assign({[i.primaryKey]:n[i.primaryKey]},Mo(i,n)),Lo(i,n));return Object.assign(e,jo(i,Object.assign(Object.assign({},n),e))),e}var Uo="null";function be(i){if(i===null)return Uo;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(be);throw new Error(`Unsupported index value: ${i}`)}function Br(i,n){let e,t;return(...r)=>{let s=n();return e&&e.length===s.length&&e.every((o,a)=>o===s[a])||(e=[...s],t=i(...r)),t}}var Vo={version:0,collections:{}};function Lr(i){return i?[...Object.keys(i.indexes||{}).map(n=>{let e=i.indexes[n],t=e.type;!t&&e.field&&(t=i.fields[e.field].type),N(t,`Could not determine type of index ${i}.${n}. Index must have a type. Perhaps your schema is malformed?`);let r=It(i,n);return{name:n,multiEntry:r,synthetic:!0,compound:!1,type:t?.replace("[]","")}}),...Object.keys(i.compounds||{}).map(n=>({name:n,multiEntry:It(i,n),synthetic:!1,compound:!0,type:"string"}))]:[]}function ui(i,n,e){let t=typeof n=="function"||n===void 0,r=t?Vo:i,s=t?i:n,o=t?n:e;N(r,"Invalid arguments to createMigration"),N(s,"Invalid arguments to createMigration");let{changedCollections:a,addedCollections:f,removedCollections:p,addedIndexes:y,removedIndexes:D,autoMigratedCollections:w,autoMigration:A}=No(r,s);return{version:s.version,migrate:async g=>{let I=[];if(await o?.({migrate:async(O,_)=>{let k=A(O),b=async S=>{let d=await _(S);$(d,ie(S));let h=k(d),l=Mr(s.collections[O].fields,h);return h};await g.migrate(O,b),I.push(O),w.delete(O)},info:{changedCollections:a,addedCollections:f,removedCollections:p},queries:g.queries,mutations:g.mutations}),s.version>1){g.log("debug","auto-migrating collections with new defaults",w);for(let _ of w)await g.migrate(_,A(_)),I.push(_);for(let _ of p)await g.deleteCollection(_);let O=a.filter(_=>!I.includes(_));O.length>0&&g.log("error",`Unmigrated changed collections from version ${r.version} to version ${s.version}:`,O)}},removedCollections:p,addedIndexes:y,removedIndexes:D,allCollections:Object.keys(s.collections),changedCollections:a,addedCollections:f,oldCollections:Object.keys(r.collections),oldSchema:r,newSchema:s}}function No(i,n){let e=Object.keys(n.collections).filter(y=>i.collections[y]&&ii(i.collections[y])!==ii(n.collections[y])),t=Object.keys(i.collections).filter(y=>!n.collections[y]),r=Object.keys(n.collections).filter(y=>!i.collections[y]),s=new Set;for(let y of e){let D=i.collections[y].fields,w=n.collections[y].fields;Object.keys(w).some(A=>(!D[A]||di(D[A]))&&!di(w[A]))&&s.add(y),Object.keys(D).some(A=>!w[A])&&s.add(y)}let o={},a={};for(let y of[...e,...r]){let D=Lr(i.collections[y]),w=Lr(n.collections[y]),A=w.filter(I=>!D.find(E=>E.name===I.name)),g=D.filter(I=>!w.find(E=>E.name===I.name));A.length>0&&(o[y]=A,e.includes(y)&&s.add(y)),g.length>0&&(a[y]=g,e.includes(y)&&s.add(y))}return{changedCollections:e,addedCollections:r,removedCollections:t,addedIndexes:o,removedIndexes:a,autoMigratedCollections:s,withDefaults:(y,D)=>ze(n.collections[y],D),autoMigration:y=>D=>{let w=n.collections[y];return ze(w,jr(w,D))}}}var fi={};var Be;(function(i){i[i.Realtime=0]="Realtime",i[i.Push=1]="Push",i[i.PassiveRealtime=2]="PassiveRealtime",i[i.PassivePush=3]="PassivePush",i[i.ReadOnlyPull=4]="ReadOnlyPull",i[i.ReadOnlyRealtime=5]="ReadOnlyRealtime"})(Be||(Be={}));var Gr=Ae($e(),1),Wo=function(i,n){var e={};for(var t in i)Object.prototype.hasOwnProperty.call(i,t)&&n.indexOf(t)<0&&(e[t]=i[t]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,t=Object.getOwnPropertySymbols(i);r<t.length;r++)n.indexOf(t[r])<0&&Object.prototype.propertyIsEnumerable.call(i,t[r])&&(e[t[r]]=i[t[r]]);return e};function Jo(i){let{properties:n,fields:e}=i,t=Wo(i,["properties","fields"]),r=n||e;if(!r)throw new Error("objectField must be passed a properties object");return Object.assign(Object.assign({type:"object"},t),{properties:r})}function Go(i,n){return i.properties=n,i}function Yo(i){return Object.assign({type:"array"},i)}function Xo(i,n){return i.items=n,i}var Zo=i=>Object.assign({type:"string"},i),ea=i=>Object.assign({type:"number"},i),ta=i=>Object.assign({type:"boolean"},i),na=i=>Object.assign({type:"any"},i);function ia(i){return Object.assign({type:"map"},i)}function ra(i,n){return i.values=n,i}var sa=i=>Object.assign({type:"file"},i),oa=()=>({type:"string",default:Gr.default}),Yr={object:Jo,array:Yo,replaceObjectFields:Go,replaceArrayItems:Xo,string:Zo,number:ea,boolean:ta,any:na,map:ia,replaceMapValues:ra,file:sa,id:oa};var es=Ae($e(),1);function Yt(i){return i.equals!==void 0}function Xt(i){return i.gte!==void 0||i.lte!==void 0||i.gt!==void 0||i.lt!==void 0}function Xr(i){return!!i.match}function Zt(i){return i.startsWith!==void 0}function bi(i){return!Xt(i)&&!Yt(i)&&!Xr(i)&&!Zt(i)&&i.order}function It(i,n){var e,t;let r=(e=i.compounds)===null||e===void 0?void 0:e[n];if(r)return r.of.some(a=>It(i,a));let s=(t=i.indexes)===null||t===void 0?void 0:t[n];if(s){if("type"in s)return yi(s.type);if("field"in s){let a=i.fields[s.field];return a?yi(a.type):!1}}let o=i.fields[n];return o?yi(o.type):!1}function yi(i){return i==="array"||i.endsWith("[]")}function De(i){return i.type==="any"?!0:i.type==="map"?!1:i.nullable}function Dt(i){return i?i.type==="map"||i.type==="array"?!0:i.type==="file"?!1:i.default!==void 0:!1}function di(i){return!De(i)&&!Dt(i)}function ze(i,n){for(let[e,t]of Object.entries(i.fields)){let r=it(t);(r!==void 0&&n[e]===void 0||!De(t)&&n[e]===null)&&(n[e]=r),n[e]&&Ke(n[e],t)}return n}function Ke(i,n){if(i==null)return i;if(n.type==="object")for(let[e,t]of Object.entries(n.properties)){if(i[e]===void 0){let r=it(t);r!==void 0&&(i[e]=r)}Ke(i[e],t)}else if(n.type==="array")for(let e of i)Ke(e,n.items);else if(n.type==="map")for(let[e,t]of Object.entries(i))e===_e||e===tt||Ke(t,n.values)}function it(i){if("default"in i){let n=typeof i.default=="function"?i.default():i.default;if(n===null)return n;let e=structuredClone(n);if(i.type==="object")for(let[t,r]of Object.entries(i.properties))e[t]===void 0&&(e[t]=it(r));return e}if(De(i))return null;if(i.type==="array")return[];if(i.type==="map")return{}}function jr(i,n){for(let[e,t]of Object.entries(n))e===_e||e===tt||(i.fields[e]?vi(t,i.fields[e]):delete n[e]);return n}function vi(i,n){if(M(i)&&n.type==="object")for(let[e,t]of Object.entries(i))n.properties[e]?vi(t,n.properties[e]):delete i[e];else if(Array.isArray(i)&&n.type==="array")for(let e of i)vi(e,n.items)}function Mr(i,n){for(let[e,t]of Object.entries(n))if(e!==_e){if(!i[e])return{type:"invalid-key",fieldPath:[e],message:`Invalid field "${e}"`};if(t){let r=Ce({field:i[e],value:t,fieldPath:[e]});if(r)return r}}}function Ce({field:i,value:n,fieldPath:e=[],depth:t,requireDefaults:r}){if(!(t!==void 0&&t<=0)&&!(De(i)&&n===null)){if(n===null&&(r||!Dt(i)))return{type:"no-default",fieldPath:e,message:`Invalid null value for field ${Se(e)}`};if(i.type==="object"){if(!M(n))return{type:"invalid-type",fieldPath:e,message:`Expected object ${i.nullable?"or null ":""}for field ${Se(e)}, got ${n}`};for(let[s,o]of Object.entries(i.properties))s!==_e&&n[s]&&Ce({field:o,value:n[s],fieldPath:[...e,s],depth:t!==void 0?t-1:void 0});for(let s of Object.keys(n))if(!i.properties[s])return{type:"invalid-key",fieldPath:[...e,s],message:`Invalid unexpected field "${s}" on value ${Se(e)}`}}else if(i.type==="array"){if(!Array.isArray(n))return n===null&&i.nullable?void 0:{type:"invalid-value",fieldPath:e,message:`Expected array ${i.nullable?"or null ":""}for field ${Se(e)}, got ${n}`};for(let s of n)Ce({field:i.items,value:s,fieldPath:[...e,"[]"],depth:t!==void 0?t-1:void 0})}else if(i.type==="map"){if(!M(n))return{type:"invalid-type",fieldPath:e,message:`Expected map for field ${Se(e)}, got ${n}`};for(let[s,o]of Object.entries(n))Ce({field:i.values,value:o,fieldPath:[...e,s],depth:t!==void 0?t-1:void 0})}else if(i.type==="string"){if(typeof n!="string")return{type:"invalid-type",fieldPath:e,message:`Expected string ${i.nullable?"or null ":""}for field ${Se(e)}, got ${n}`};if(i.options&&!i.options.includes(n))return{type:"invalid-value",fieldPath:e,message:`Expected one of ${i.options.join(", ")} for field ${Se(e)}, got ${n}`}}else if(i.type==="boolean"){if(typeof n!="boolean")return{type:"invalid-type",fieldPath:e,message:`Expected boolean ${i.nullable?"or null ":""}for field ${Se(e)}, got ${n}`}}else if(i.type==="number"){if(typeof n!="number")return{type:"invalid-type",fieldPath:e,message:`Expected number ${i.nullable?"or null ":""}for field ${Se(e)}, got ${n}`}}else if(i.type==="file"&&!Xe(n)&&!Vt(n))return{type:"invalid-type",fieldPath:e,message:`Expected file ${i.nullable?"or null ":""}for field ${Se(e)}, got ${n}`}}}function Se(i){return i.length===0?"root":i.join(".")}function Zr(i,n){let e={};for(let[t,r]of Object.entries(n))i[t]&&(e[t]=en({field:i[t],value:r,fieldPath:[t]}));return e}function en({field:i,value:n,fieldPath:e=[],depth:t}){let r=Ce({field:i,value:n,fieldPath:e,depth:t,requireDefaults:!0});if(r)throw new Error(`Validation error: ${r.message}`);if(i.type==="object"){if(!M(n))return n;let s={};for(let[o,a]of Object.entries(i.properties))s[o]=en({field:a,value:n[o],fieldPath:[...e,o],depth:t!==void 0?t-1:void 0});return s}else{if(i.type==="array")return Array.isArray(n)?n.map(s=>en({field:i.items,value:s,fieldPath:[...e,"[]"],depth:t!==void 0?t-1:void 0})):n;if(i.type==="map"){if(!M(n))return n;let s={};for(let[o,a]of Object.entries(n))s[o]=en({field:i.values,value:a,fieldPath:[...e,o],depth:t!==void 0?t-1:void 0});return s}else return n}}function Le(i,n){var e;return i.type==="object"?i.properties[n]:i.type==="array"?i.items:i.type==="map"?i.values:i.type==="any"?i:"type"in i?null:(e=i[n])!==null&&e!==void 0?e:null}var aa=function(i,n){var e={};for(var t in i)Object.prototype.hasOwnProperty.call(i,t)&&n.indexOf(t)<0&&(e[t]=i[t]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,t=Object.getOwnPropertySymbols(i);r<t.length;r++)n.indexOf(t[r])<0&&Object.prototype.propertyIsEnumerable.call(i,t[r])&&(e[t[r]]=i[t[r]]);return e};function ca(i){var{synthetics:n,indexes:e}=i,t=aa(i,["synthetics","indexes"]);let r=Object.assign(Object.assign({},n),e);for(let[s,o]of Object.entries(t.fields))"indexed"in o&&(r[s]={field:s});return Object.assign(Object.assign({},t),{indexes:r})}function Ct(i){return i}Ct.collection=ca;Ct.fields=Yr;Ct.generated={id:es.default};var rs=Ae($e(),1),an=4,At=36;function ts(i){return i.toString(At).padStart(an,"0")}function la(i){return i.toString().padStart(6,"0")}var tn=class{constructor(){this.latest={time:Date.now(),counter:0,node:da()},this.zeroCounter=0,this.now=n=>(this.latest=is(this.latest),this.get(n,this.latest)),this.OLD_now=n=>(this.latest=is(this.latest),la(n)+fa(this.latest)),this.timerState=()=>this.latest,this.update=n=>{let e=n.slice(an);this.latest=ua(this.latest,ss(e))},this.get=(n,e)=>ts(n)+ns(e),this.zero=n=>ts(n)+ns({time:0,counter:this.zeroCounter++,node:this.latest.node}),this.getWallClockTime=Oi}},nn=class extends Error{constructor(...n){super(),this.type="ClockDriftError",this.message=["maximum clock drift exceeded"].concat(n).join(" ")}},rn=class extends Error{constructor(){super(),this.type="OverflowError",this.message="timestamp counter overflow"}},wi=4,xi=7,sn=60*1e3,Pt=9;function da(){return rs.default.slug().padStart(xi,"0").slice(0,xi)}function ns(i){let n=new Date(i.time).getTime().toString(At).padStart(Pt,"0"),e=i.counter.toString(At).padStart(wi,"0"),t=i.node.padStart(xi,"0");return`${n}${e}${t}`}function is(i){let n=Date.now(),e=Math.max(i.time,n),t=i.time===e?i.counter+1:0;if(e-n>sn)throw new nn(e,n,sn);if(t>65535)throw new rn;return{time:e,counter:t,node:i.node}}function ua(i,n){let e=Date.now(),t=Math.max(e,Math.max(i.time,n.time)),r=Math.max(i.counter,n.counter),s;if(i.time===t&&n.time===t?s=r+1:i.time===t?s=i.counter+1:n.time===t?s=n.counter+1:s=0,t-e>sn)throw new nn(t,e,sn);if(s>65535)throw new rn;return{time:t,counter:s,node:i.node}}function ss(i){let n=i.slice(0,Pt),e=i.slice(Pt,Pt+wi),t=i.slice(Pt+wi),r=parseInt(n,At),s=parseInt(e,At);if(isNaN(r)||isNaN(s))throw new Error("invalid clock format");return{time:r,counter:s,node:t}}function fa(i){let n=new Date(i.time).toISOString(),e=i.counter.toString(16).toUpperCase().padStart(4,"0"),t=i.node.padStart(16,"0");return`${n}-${e}-${t}`}function on(i){return parseInt(i.slice(0,an),36)}function Si(i,n){return on(i)-on(n)}function Oi(i){return ss(i.slice(an)).time}function os(i,n,e,t){if(n==null)return[{oid:i,timestamp:t(),data:{op:"delete"}}];let r=ce(n),s=[];for(let o of e){let a=ha(i,r,o,t);s.unshift(...a),Fe(r,o.data)}return s}function ha(i,n,e,t){let r=e.data;switch(r.op){case"set":case"remove":return[{oid:i,timestamp:t(),data:{op:"set",name:r.name,value:n[r.name]}}];case"list-insert":return[{oid:i,timestamp:t(),data:{op:"list-delete",index:r.index,count:1}}];case"list-delete":return[{oid:i,timestamp:t(),data:{op:"list-insert",index:r.index,values:n.slice(r.index,r.count)}}];case"list-move-by-ref":return[{oid:i,timestamp:t(),data:{op:"list-move-by-ref",value:r.value,index:n.indexOf(r.value)}}];case"list-move-by-index":return[{oid:i,timestamp:t(),data:{op:"list-move-by-index",from:r.to,to:r.from}}];case"delete":return[{oid:i,timestamp:t(),data:{op:"initialize",value:n}}];case"list-push":return[{oid:i,timestamp:t(),data:{op:"list-remove",value:r.value,only:"last"}}];case"list-remove":if(r.only==="last"){let s=n.lastIndexOf(r.value);return[{oid:i,timestamp:t(),data:{op:"list-insert",index:s,values:[r.value]}}]}else if(r.only==="first"){let s=n.indexOf(r.value);return[{oid:i,timestamp:t(),data:{op:"list-insert",index:s,values:[r.value]}}]}else{let s=[],o=n.indexOf(r.value);for(;o!==-1;)s.push(o),o=n.indexOf(r.value,o+1);return s.map(a=>({oid:i,timestamp:t(),data:{op:"list-insert",index:a,value:r.value}}))}case"list-add":return[{oid:i,timestamp:t(),data:{op:"list-remove",value:r.value,only:"last"}}];case"list-set":return n[r.index]?[{oid:i,timestamp:t(),data:{op:"list-set",index:r.index,value:n[r.index]}}]:[{oid:i,timestamp:t(),data:{op:"list-delete",index:r.index,count:1}}];case"initialize":return[{oid:i,timestamp:t(),data:{op:"delete"}}];case"touch":return[];default:throw new Error(`Cannot undo operation type: ${r.op}`)}}var cn=class{constructor(n,e){this.schema=n;this.entities=e;this.getOid=(n,e)=>{let t=this.schema.collections[n].primaryKey,r=e[t];return N(r,`Document must have a primary key: ${t.toString()} (got: ${JSON.stringify(e)})`),Z(n,r)};this.addDefaults=(n,e)=>{let t=this.schema.collections[n];return ze(t,e)};this.validate=(n,e)=>{let t=this.schema.collections[n];return Zr(t.fields,e)};this.create=async(n,e,t={})=>{let r=t,s=this.addDefaults(n,e),o=this.validate(n,s),a=this.getOid(n,o);if(t.access){let f=this.schema.collections[n];t.access!=="shared"&&e[f.primaryKey]&&!t.silenceAccessControlWithPrimaryKeyWarning&&console.warn("Using a custom primary key with access control is not supported. This may result in corrupted documents. Read more about why: https://verdant.dev/docs/sync/access#a-warning-about-custom-primaryKey"),r.access=t.access}return this.entities.create(o,a,r)};this.delete=async(n,e,t={})=>{let r=Z(n,e);return this.entities.delete(r,t)};this.deleteAll=async(n,e={})=>this.entities.deleteAll(n.map(([t,r])=>Z(t,r)),e);this.deleteAllFromCollection=async(n,e,t={})=>this.entities.deleteAll(e.map(r=>Z(n,r)),t);this.clone=async(n,e,t={})=>{if(!Ht(e.uid))throw new Error("Cannot clone non-root documents");let r=e.getSnapshot(),s=this.schema.collections[n];if(delete r[s.primaryKey],!s.fields[s.primaryKey].default){if(!t.primaryKey)throw new Error(`Error cloning document from collection ${n}: collection does not have a default on primary key. You must supply a value to options.primaryKey for the clone.`);r[s.primaryKey]=t.primaryKey}return this.create(n,r,t)}}};var Ii=Ae($e(),1);function pa(i){return{id:(0,Ii.default)(),file:i,url:void 0,remote:!1,name:i.name,type:i.type}}function rt(i,n){if(typeof window<"u"&&Xe(i)){let e=pa(i);return n(e),yt(e.id)}if(Vt(i)){let e={...i,id:(0,Ii.default)()};return n(e),yt(e.id)}if(Array.isArray(i)){for(let e=0;e<i.length;e++)i[e]=rt(i[e],n);return i}if(typeof i=="object"){for(let e in i)i[e]=rt(i[e],n);return i}return i}var ln=class{constructor({initial:n}={}){this.cache=new Map;this.get=n=>{if(this.cache.has(n.oid))return this.cache.get(n.oid);let e=new de(n);return this.cache.set(n.oid,e),e};this.has=n=>this.cache.has(n);this.getCached=n=>this.cache.get(n);if(n)for(let e of n)this.cache.set(e.oid,e)}};function as(i,n,e){let t={previousValue:i.get(n),isLocal:!1};function r(s){if(i.deleted)return;let o=i.get(n);o!==this.previousValue&&(this.isLocal=s.isLocal,e(o,this),this.previousValue=o)}return i.subscribe("change",r.bind(t))}var cs=Symbol("private entity context key"),de=class i extends V{constructor({oid:e,schema:t,entityFamily:r,parent:s,ctx:o,metadataFamily:a,readonlyKeys:f,files:p,storeEvents:y,deleteSelf:D}){super();this.fieldPath=[];this._viewData=void 0;this.validationError=void 0;this.cachedDeepUpdatedAt=null;this.wasDeletedLastChange=!1;this.cachedView=void 0;this.onAdd=(e,t)=>{t.oid===this.oid&&this.addConfirmedData(t)};this.onReplace=(e,t)=>{t.oid===this.oid&&this.replaceAllData(t)};this.onResetAll=()=>{this.resetAllData()};this.childIsNull=e=>{if(e instanceof i){let t=e.view;return t==null}return e==null};this.getFieldSchema=e=>{let t=Le(this.schema,e);return N(t,`No schema for key ${e}`),t};this.validate=Br(()=>(this.validationError=Ce({field:this.schema,value:this.rawView,fieldPath:this.fieldPath,depth:1})??void 0,this.validationError),()=>[this.viewData]);this.viewWithMappedChildren=e=>{let t=this.view;if(!t)return null;if(Array.isArray(t)){let r=t.map(s=>s instanceof i||s instanceof ve?e(s):s);return $(r,this.oid),r}else{let r=Object.entries(t).reduce((s,[o,a])=>(a instanceof i||a instanceof ve?s[o]=e(a):s[o]=a,s),{});return $(r,this.oid),r}};this.getSnapshot=()=>this.viewWithMappedChildren(e=>e.getSnapshot());this.addPendingOperations=e=>{if(this.ctx.log("debug","Entity: adding pending operations",this.oid),this.access)for(let r of e)r.authz=this.access;let t=this.metadataFamily.addPendingData(e);for(let r of t)this.change(r)};this.addConfirmedData=e=>{this.ctx.log("debug","Entity: adding confirmed data",this.oid);let t=this.metadataFamily.addConfirmedData(e);for(let r of t)this.change(r)};this.replaceAllData=e=>{this.ctx.log("debug","Entity: replacing all data",this.oid);let t=this.metadataFamily.replaceAllData(e);for(let r of t)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 t of e)this.change(t)};this.invalidateCachedView=()=>{this._viewData=void 0,this.cachedView=void 0};this.change=e=>{if(e.oid===this.oid)this.invalidateCachedView(),this.parent?this.changeNested(e):this.changeRoot(e);else{let t=this.entityFamily.getCached(e.oid);t&&t instanceof i&&t.change(e)}};this.changeRoot=e=>{this.deleted?this.wasDeletedLastChange||(this.ctx.log("debug","Entity deleted",this.oid),this.emit("delete",{isLocal:e.isLocal}),this.wasDeletedLastChange=!0):(this.wasDeletedLastChange&&(this.ctx.log("debug","Entity restored",this.oid),this.emit("restore",{isLocal:e.isLocal}),this.wasDeletedLastChange=!1),this.deepChange(this,e),this.emit("change",{isLocal:e.isLocal}))};this.changeNested=e=>{this.deepChange(this,e),this.emit("change",{isLocal:e.isLocal})};this.deepChange=(e,t)=>{this.cachedDeepUpdatedAt=null,this.cachedView=void 0,this.emit("changeDeep",e,t),this.parent?.deepChange(e,t)};this.getChild=(e,t)=>{let r=Le(this.schema,e);if(!r)throw new Error(`No schema for key ${String(e)} in ${JSON.stringify(this.schema)}`);return this.entityFamily.get({oid:t,schema:r,entityFamily:this.entityFamily,metadataFamily:this.metadataFamily,parent:this,ctx:this.ctx,files:this.files,fieldPath:[...this.fieldPath,e],storeEvents:this.storeEvents,deleteSelf:this.delete.bind(this,e)})};this.subscribeToField=(e,t,r)=>as(this,e,r);this.get=e=>{_i(e);let t=this.rawView;if(!t)throw new Error(`Cannot access data at key ${e} on deleted entity ${this.oid}`);let r=t[e],s=Le(this.schema,e);if(!s)throw new Error(`No schema for key ${String(e)} in ${JSON.stringify(this.schema)}`);if(J(r))if(ge(r)){if(s.type!=="file")throw new Error(`Expected file schema for key ${String(e)}, got ${s.type}`);let o=this.files.get(r.id,{downloadRemote:!!s.downloadRemote,ctx:this.ctx});return o.subscribe("change",()=>{this.deepChange(this,{isLocal:!1,oid:this.oid})}),o}else return this.getChild(e,r.id);else return this.schema.type==="map"&&r===void 0?void 0:Ce({field:s,value:r,fieldPath:[...this.fieldPath,e],depth:1,requireDefaults:!0})?it(s):r};this.getOrSet=(e,t)=>{_i(e);let r=this.get(e);return r||(this.set(e,t),this.get(e))};this.processInputValue=(e,t)=>{if(this.readonlyKeys.includes(t))throw new Error(`Cannot set readonly key ${t.toString()}`);Xe(e)||(e=ce(e,!1));let r=Le(this.schema,t);if(r){Ke(e,r);let s=Ce({field:r,value:e,fieldPath:[...this.fieldPath,t]});if(s)throw new Error(`Validation error: ${s.message}`,{cause:s})}return rt(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 t=this.schema.properties[e];if(!t||t.type==="any")return"delete";if(t.type==="map")return!1;if(t.nullable)return"null"}return!1};this.getItemRefValue=e=>{if(e instanceof i)return ye(e.oid);if(e instanceof ve)return yt(e.id);if(typeof e=="object"){let t=ne(e);if(!t||!this.entityFamily.has(t))throw new Error(`Cannot move object ${JSON.stringify(e)} which does not exist in this list`);return ye(t)}else return e};this.set=(e,t,r)=>{_i(e),!(!r?.force&&this.get(e)===t)&&(this.isList?this.addPendingOperations(this.patchCreator.createListSet(this.oid,e,this.processInputValue(t,e))):this.addPendingOperations(this.patchCreator.createSet(this.oid,e,this.processInputValue(t,e))))};this.getAll=()=>this.view;this.delete=e=>{if(this.isList)ma(e),this.addPendingOperations(this.patchCreator.createListDelete(this.oid,e));else{let t=this.getDeleteMode(e);if(!t)throw new Error(`Cannot delete key ${e.toString()} - the property is not marked as optional in the schema.`);t==="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:t=!0,replaceSubObjects:r=!1,preserveUndefined:s=!1,dangerouslyDisableMerge:o=!1}={})=>{if(!t&&!o&&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 a={};$(a,this.oid);for(let[f,p]of Object.entries(e)){if(this.readonlyKeys.includes(f))throw new Error(`Cannot set readonly key ${f.toString()}`);if(p===void 0&&!s)continue;let y=Le(this.schema,f);y&&Ke(p,y),a[f]=this.processInputValue(p,f)}this.addPendingOperations(this.patchCreator.createDiff(this.getSnapshot(),a,{mergeUnknownObjects:!r,defaultUndefined:t}))};this.push=e=>{this.addPendingOperations(this.patchCreator.createListPush(this.oid,this.processInputValue(e,this.view.length)))};this.insert=(e,t)=>{this.addPendingOperations(this.patchCreator.createListInsert(this.oid,e,this.processInputValue(t,e)))};this.move=(e,t)=>{this.addPendingOperations(this.patchCreator.createListMoveByIndex(this.oid,e,t))};this.moveItem=(e,t)=>{let r=this.getItemRefValue(e);if(J(r))this.addPendingOperations(this.patchCreator.createListMoveByRef(this.oid,r,t));else{let s=this.view.indexOf(e);if(s===-1)throw new Error(`Cannot move item ${JSON.stringify(e)} which does not exist in this list`);this.move(s,t)}};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 t=this.getItemRefValue(e);return J(t)?this.view.some(r=>{if(J(r))return Ne(r,t)}):this.view.includes(e)};this.forEach=e=>{this.view.forEach(e)};this.reduce=(e,t)=>this.view.reduce(e,t);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.deleteSelf=()=>this._deleteSelf();this.__getViewData__=(e,t)=>this.metadataFamily.get(e).computeView(t==="confirmed");this.__getFamilyOids__=()=>this.metadataFamily.getAllOids();this.__discardPendingOperation__=e=>{this.metadataFamily.discardPendingOperation(e),this.invalidateCachedView()};N(!!e,"oid is required"),this.oid=e,this.readonlyKeys=f||[],this.ctx=o,this.files=p,this.schema=t,this.entityFamily=r||new ln({initial:[this]}),this.metadataFamily=a,this.storeEvents=y,this.parent=s,this._deleteSelf=D,this.parent||(y.add.attach(this.onAdd),y.replace.attach(this.onReplace),y.resetAll.attach(this.onResetAll))}get[cs](){return this.ctx}get metadata(){return this.metadataFamily.get(this.oid)}get patchCreator(){return this.ctx.patchCreator}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&&!De(this.schema)||this.schema.type==="array"&&!Array.isArray(e)||(this.schema.type==="object"||this.schema.type==="map")&&!M(e))return Dt(this.schema)?it(this.schema):null;if(this.cachedView=this.isList?[]:{},$(this.cachedView,this.oid),Array.isArray(e)){let r=Le(this.schema,0);if(!r)this.ctx.log("error","No child field schema for list entity.",this.oid);else for(let s=0;s<e.length;s++){let o=this.get(s);this.childIsNull(o)&&!De(r)?this.ctx.log("error","Child missing in non-nullable field",this.oid,"index:",s):this.cachedView.push(o)}}else if(M(e)){let r=this.schema.type==="object"?Object.keys(this.schema.properties):Object.keys(e);for(let s of r){let o=Le(this.schema,s);if(!o){this.ctx.log("error","No child field schema for object entity at key",s),this.schema.type==="map"?this.cachedView={}:this.cachedView=null;break}let a=this.get(s);if(this.childIsNull(a)&&!De(o)){if(this.ctx.log("error","Child entity is missing for non-nullable field",this.oid,"key:",s),this.schema.type!=="map"){this.cachedView=null;break}}else this.cachedView[s]=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(t=>{if(t instanceof i){let r=t.deepUpdatedAt;r&&(!e||r>e)&&(e=r)}}):this.values().forEach(t=>{if(t instanceof i){let r=t.deepUpdatedAt;r&&(!e||r>e)&&(e=r)}}),this.cachedDeepUpdatedAt=e,e}get isOutdatedVersion(){return this.parent?this.parent.isOutdatedVersion:this.viewData.fromOlderVersion}get namespace(){return this.ctx.namespace}get access(){return this.viewData.authz}get isAuthorized(){return!!this.access}get size(){return this.isList?this.length:this.keys().length}get length(){return this.view.length}[Symbol.iterator](){let e=0,t=this.view?.length;return{next:()=>e<t?{value:this.get(e++),done:!1}:{value:void 0,done:!0}}}};function _i(i){if(typeof i=="symbol")throw new Error("Symbol keys aren't supported")}function ma(i){if(typeof i!="number")throw new Error("Only number keys are supported in list entities")}function ls(i){return i[cs].getClient()}var re=class{constructor(){this._disposes=[];this.disposed=!1;this.dispose=async()=>{this.disposed=!0,await Promise.all(this._disposes.map(async n=>{try{await n()}catch(e){console.error("Error disposing",e)}})),this._disposes=[]};this.compose=n=>this.addDispose(n.dispose.bind(n));this.addDispose=n=>{this._disposes.push(n)}}};var Ei=class{constructor({oid:n,ctx:e,confirmedOperations:t,pendingOperations:r,baseline:s}){this.baseline=null;this.confirmedOperations=[];this.pendingOperations=[];this.computeView=(n=!1)=>{let e=ce(this.baseline?.snapshot??void 0),t=this.baseline?.timestamp??null,r=this.baseline?.authz,s=this.applyOperations(e,!e,this.confirmedOperations,t,t);s.futureSeen&&this.ctx.globalEvents.emit("futureSeen",s.futureSeen),s.authz&&(r=s.authz);let o=n?s:this.applyOperations(s.view,s.deleted,this.pendingOperations,s.latestTimestamp,null);o.authz&&(r=o.authz),o.view&&$(o.view,this.oid);let a=!!s.latestTimestamp&&Si(s.latestTimestamp,this.ctx.time.now)<0,f=!this.baseline&&!this.pendingOperations.length&&!this.confirmedOperations.length;f&&this.ctx.log("warn",`Tried to load Entity ${this.oid} with no data`);let p=o.latestTimestamp??s.latestTimestamp??t,y=p?Oi(p):0;return!o.view&&!o.deleted&&!f&&this.ctx.log("warn",`Entity ${this.oid} has no view, no deleted flag, and not empty`),{view:o.view??void 0,deleted:o.deleted,empty:f,fromOlderVersion:a,updatedAt:y,latestTimestamp:p,authz:r}};this.addBaseline=n=>{if(!(this.baseline&&this.baseline.timestamp>=n.timestamp))for(this.baseline=n;this.confirmedOperations[0]?.timestamp<n.timestamp;)this.confirmedOperations.shift()};this.addConfirmedOperations=n=>{let e=0;for(let t of n){let r=this.confirmedOperations.findIndex(o=>o.timestamp>=t.timestamp);r!==-1?this.confirmedOperations[r].timestamp!==t.timestamp&&(this.confirmedOperations.splice(r,0,t),e++):(this.confirmedOperations.push(t),e++);let s=this.pendingOperations.length;this.discardPendingOperation(t),e-=s-this.pendingOperations.length}return e};this.addPendingOperation=n=>{this.pendingOperations.push(n)};this.discardPendingOperation=n=>{this.pendingOperations=this.pendingOperations.filter(e=>e.timestamp!==n.timestamp)};this.applyOperations=(n,e,t,r,s)=>{let o,a,f=this.ctx.time.now;for(let p of t)if(!(s&&p.timestamp<=s)){if(Si(p.timestamp,f)>0){o=p.timestamp;continue}p.data.op==="delete"?e=!0:(n=Fe(n,p.data),p.data.op==="initialize"&&(e=!1,p.authz&&(a=p.authz))),(!r||p.timestamp>r)&&(r=p.timestamp)}return{view:n,latestTimestamp:r??null,deleted:e,futureSeen:o,authz:a}};N(n,"oid is required"),this.ctx=e,this.oid=n,t&&(this.confirmedOperations=t),r&&(this.pendingOperations=r),s&&(this.baseline=s)}},dn=class{constructor({ctx:n,onPendingOperations:e,rootOid:t}){this.entities=new Map;this.get=n=>(N(n,"oid is required"),this.entities.has(n)||this.entities.set(n,new Ei({oid:n,ctx:this.ctx})),this.entities.get(n));this.getAllOids=()=>Array.from(this.entities.keys());this.addConfirmedData=({baselines:n=[],operations:e={},isLocal:t=!1})=>{let r={};for(let s of n){if(!ke(this.rootOid,s.oid))throw new Error(`Invalid baseline for entity ${this.rootOid}: `+JSON.stringify(s));this.get(s.oid).addBaseline(s),r[s.oid]??={oid:s.oid,isLocal:t}}for(let[s,o]of Object.entries(e)){if(!ke(this.rootOid,s))throw new Error(`Invalid operations for entity ${this.rootOid}: `+JSON.stringify(o));this.get(s).addConfirmedOperations(o)!==0&&(r[s]??={oid:s,isLocal:t})}return Object.values(r)};this.addPendingData=n=>{let e={};for(let t of n)this.get(t.oid).addPendingOperation(t),e[t.oid]??={oid:t.oid,isLocal:!0};return this.onPendingOperations(n),Object.values(e)};this.replaceAllData=({operations:n={},baselines:e=[]})=>{let t=Array.from(this.entities.keys());this.entities.clear();let r={};for(let s of t)r[s]={oid:s,isLocal:!1};for(let s of e){if(!ke(this.rootOid,s.oid))throw new Error(`Invalid baseline for entity ${this.rootOid}: `+JSON.stringify(s));this.get(s.oid).addBaseline(s),r[s.oid]??={oid:s.oid,isLocal:!1}}for(let[s,o]of Object.entries(n)){if(!ke(this.rootOid,s))throw new Error(`Invalid operations for entity ${this.rootOid}: `+JSON.stringify(o));this.get(s).addConfirmedOperations(o),r[s]??={oid:s,isLocal:!1}}return Object.values(r)};this.discardPendingOperation=n=>{this.entities.get(n.oid)?.discardPendingOperation(n)};this.ctx=n,this.rootOid=t,this.onPendingOperations=e}};var Rt="@@default",un=class{constructor({batchTimeout:n=200,ctx:e,entities:t}){this.currentBatchKey=Rt;this.flushOperations=async(n,e,t)=>{if(!n.length)return;this.ctx.log("debug","Flushing",n.length,"operations from batch",e,"to storage / sync");let r=[],s={};for(let o=n.length-1;o>=0;o--){let a=n[o],f=s[a.oid];if(f&&Er(a,f)){this.entities.discardPendingOperation(a);continue}let p=_r(a);p!==!1&&(s[a.oid]||(s[a.oid]=new Set),s[a.oid].add(p)),r.unshift(a)}for(let o of r)o.timestamp=this.ctx.time.now;await this.commitOperations(r,t)};this.commitOperations=async(n,e)=>{if(n.length){if(e.undoable){let t=await this.createUndo({ops:n,source:e.source});t&&this.ctx.undoHistory.addUndo(t)}await this.entities.addData({operations:n,baselines:[],isLocal:!0})}};this.addOperations=n=>{n.length&&(this.batcher.add({key:this.currentBatchKey,items:n}),this.ctx.log("debug","added",n.length,"ops to batch",this.currentBatchKey,", size = ",this.batcher.getSize(this.currentBatchKey)))};this.batch=({undoable:n=!0,batchName:e=gt(),max:t=null,timeout:r=this.defaultBatchTimeout}={})=>{let s=this.batcher.add({key:e,max:t,timeout:r,items:[],userData:{undoable:n}}),o={run:a=>(this.currentBatchKey=e,a(),this.currentBatchKey=Rt,o),commit:async()=>(await this.batcher.flush(Rt),s.flush()),flush:()=>o.commit(),discard:()=>{this.batcher.discard(e)}};return o};this.flushAll=()=>(this.ctx.log("debug","Flushing all operations"),Promise.all(this.batcher.flushAll()));this.createUndo=async n=>{let e=await this.getInverseOperations(n);return e.length?async()=>{let t=await this.createUndo({ops:e,source:n.source});for(let r of e)r.timestamp=this.ctx.time.now;return await this.commitOperations(e,{undoable:!1}),t}:null};this.getInverseOperations=async({ops:n,source:e})=>{let t=bt(n),r=[],s=()=>this.ctx.time.now;return await Promise.all(Object.entries(t).map(async([o,a])=>{let p=(e??await this.entities.hydrate(z(o)))?.__getViewData__(o,"confirmed");if(!p){this.ctx.log("warn","could not find entity",o,"for undo operation",n);return}let y=os(o,p.view,a,s);r.unshift(...y)})),r};this.ctx=e,this.entities=t,this.defaultBatchTimeout=n,this.batcher=new Ye(this.flushOperations),this.batcher.add({key:Rt,items:[],max:100,timeout:n,userData:{undoable:!0}})}get isDefaultBatch(){return this.currentBatchKey===Rt}};var wn=Ae($s(),1);var xn=class extends re{constructor({ctx:e,files:t}){super();this.events={add:new wn.WeakEvent,replace:new wn.WeakEvent,resetAll:new wn.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.ctx.globalEvents.emit("resetToServer")})),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.empty=async()=>{await this.ctx.documents.reset(),this.events.resetAll.invoke(this),this.cache.clear()};this.resetData=async()=>{if(this.disposed){this.ctx.log("warn","EntityStore is disposed, not resetting local data");return}await this.ctx.meta.reset(),await this.ctx.documents.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 t=e?.baselines??[],r=e?.operations??[];if(t.length===0&&r.length===0){this.ctx.log("debug","No data to process");return}this.ctx.log("debug","Processing incoming data",{operations:r.length,baselines:t.length,reset:!!e.reset});let s=Array.from(new Set(t.map(y=>z(y.oid)).concat(r.map(y=>z(y.oid))))),o=Ir(t),a=Or(r);this.ctx.log("debug","Applying data to live entities");for(let y of s){let D=o[y],w=a[y]??[],A=bt(w),g=e.reset?this.events.replace:this.events.add,I=this.pendingEntityPromises.get(y);I?(this.ctx.log("debug","Waiting for ongoing entity hydration",y),I.then(()=>{g.invoke(this,{oid:y,baselines:D,operations:A,isLocal:!1})})):(this.ctx.log("debug","Applying data to entity",y),g.invoke(this,{oid:y,baselines:D,operations:A,isLocal:!1}))}let f={abort:this.abortDataQueueController.signal};await this.ctx.meta.insertData(e,f),this.ctx.log("debug","Data processing complete, all data saved to metadata db.");let p=await Promise.all(s.map(async y=>await this.hydrate(y,f)??{oid:y,getSnapshot(){return null}}));try{this.ctx.log("debug","Saving entities to queryable storage"),await this.ctx.documents.saveEntities(p,f)}catch(y){this.disposed?this.ctx.log("warn","Error saving entities to queryable storage - EntityStore is disposed",y):this.ctx.log("error","Error saving entities to queryable storage",y)}};this.hydrate=async(e,t)=>{if(!Ht(e))throw new Error("Cannot hydrate non-root entity");if(this.cache.has(e)){let s=this.cache.get(e);if(s){let o=s.deref();if(o)return o.deleted?(this.ctx.log("debug","Hydrated entity is deleted",e),null):(this.ctx.log("debug","Hydrating entity from cache",e),o);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 ongoing entity hydration",e),r;{this.ctx.log("debug","Hydrating entity from storage",e);let s=this.constructEntity(e);if(!s)return this.ctx.log("warn","Entity schema not found, cannot construct",e),null;let o=this.loadEntity(s,t);return o.finally(()=>{this.pendingEntityPromises.delete(e)}),this.pendingEntityPromises.set(e,o),o}};this.destroy=async()=>{this.dispose(),await this.batcher.flushAll()};this.create=async(e,t,{undoable:r=!0,access:s}={})=>{this.ctx.log("debug","Creating new entity",t);let{collection:o}=le(t);qt(e);let a=rt(e,this.files.add);$(a,t);let f=this.constructEntity(t);if(!f)throw new Error(`Could not put new document: no schema exists for collection ${o}`);let p=this.ctx.patchCreator.createInitialize(a,t);s&&p.forEach(D=>{D.authz=s}),await this.batcher.commitOperations(p,{undoable:!!r,source:f});let y=bt(p);return this.events.add.invoke(this,{operations:y,isLocal:!0,oid:t}),this.cache.set(t,this.ctx.weakRef(f)),f};this.deleteAll=async(e,t)=>{this.ctx.log("info","Deleting documents",e),N(e.every(o=>o===z(o)),"Only root documents may be deleted via client methods");let r=await Promise.all(e.map(o=>this.hydrate(o)));e.forEach(o=>{this.cache.delete(o),this.ctx.log("debug","Deleted document from cache",o)});let s=[];for(let o of r)if(o){let a=o.__getFamilyOids__(),f=this.ctx.patchCreator.createDeleteAll(a);for(let p of f)p.authz=o.access;s.push(...f)}await this.batcher.commitOperations(s,{undoable:t?.undoable===void 0?!0:t.undoable})};this.delete=async(e,t)=>this.deleteAll([e],t);this.getCollectionSchema=e=>{let t=this.ctx.schema.collections[e];return t?{schema:{type:"object",nullable:!1,properties:t.fields},readonlyKeys:[t.primaryKey]}:(this.ctx.log("warn",`Missing schema for collection: ${e}`),{schema:null,readonlyKeys:[]})};this.constructEntity=e=>{N(!!e,"Cannot construct entity without OID");let{collection:t}=le(e),{schema:r,readonlyKeys:s}=this.getCollectionSchema(t);if(!r)return null;if(this.disposed)throw new Error("Cannot hydrate entity after store has been disposed");let o=new dn({ctx:this.ctx,onPendingOperations:this.onPendingOperations,rootOid:e});return new de({ctx:this.ctx,oid:e,schema:r,readonlyKeys:s,files:this.files,metadataFamily:o,storeEvents:this.events,deleteSelf:this.delete.bind(this,e)})};this.onPendingOperations=e=>{this.batcher.addOperations(e)};this.discardPendingOperation=e=>{let t=z(e.oid);this.cache.get(t)?.deref()?.__discardPendingOperation__(e)};this.loadEntity=async(e,t)=>(await this.loadEntityData(e,t),this.cache.set(e.oid,this.ctx.weakRef(e)),this.entityFinalizationRegistry.register(e,e.oid),e);this.loadEntityData=async(e,t)=>{let{operations:r,baselines:s}=await this.ctx.meta.getDocumentData(e.oid,t);return!s.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:s,operations:r,isLocal:!1}),e)};this.clearCache=()=>{this.ctx.log("debug","Emptying entity cache"),this.cache.clear()};this.ctx=e,this.files=t,this.batcher=new un({ctx:e,entities:this}),this.addDispose(this.ctx.internalEvents.subscribe("persistenceReset",this.clearCache))}get batch(){return this.batcher.batch}get flushAllBatches(){return this.batcher.flushAll}};function Ks({currentVersion:i,targetVersion:n,migrations:e}){let t=qs({currentVersion:i,targetVersion:n,migrations:e});if(!t)throw new H(H.Code.MigrationPathNotFound,void 0,`No migration path found from ${i} to ${n}! This is a bug. If you're seeing this, contact the developer and provide them with the full contents of this message.`);return t}function qs({currentVersion:i,targetVersion:n,migrations:e}){if(i===n)return[];let t=e.filter(r=>r.oldSchema.version===i).sort((r,s)=>s.newSchema.version-r.newSchema.version);for(;t.length>0;){let r=t.shift();if(r.newSchema.version>n)return null;if(r.newSchema.version===n)return[r];let s=qs({currentVersion:r.newSchema.version,targetVersion:n,migrations:e});if(s)return[r,...s]}return null}var ot=Symbol("entity-file-update"),Sn=Symbol("entity-file-mark-failed"),Ra,Fa,ve=class extends V{constructor(e,{downloadRemote:t=!1,ctx:r}){super();this.id=e;this._objectUrl=null;this._fileData=null;this._loading=!0;this._failed=!1;this._downloadRemote=!1;this._uploaded=!1;this.unsubscribes=[];this[Ra]=e=>{this.ctx.log("debug","EntityFile updated",this.id,e),this._loading=!1,this._failed=!1,this._fileData=e,e.file&&(this._objectUrl&&"revokeObjectURL"in URL&&URL.revokeObjectURL(this._objectUrl),this.ctx.log("debug","Creating object URL for file",this.id),this._objectUrl=URL.createObjectURL(e.file)),this.emit("change")};this[Fa]=()=>{this._failed=!0,this._loading=!1,this.emit("change")};this.onUploaded=e=>{this._fileData??=e,this._uploaded=!0,this.ctx.log("debug","File marked uploaded",this.id,this._fileData),this.emit("change")};this.destroy=()=>{this._objectUrl&&URL.revokeObjectURL(this._objectUrl),this.dispose()};this.ctx=r,this._downloadRemote=t,this.unsubscribes.push(this.ctx.internalEvents.subscribe(`fileUploaded:${e}`,this.onUploaded))}static{Ra=ot,Fa=Sn}get downloadRemote(){return this._downloadRemote}get isFile(){return!0}get isUploaded(){return this._uploaded||this._fileData?.remote||!1}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._objectUrl??this._fileData?.url??void 0,name:this.name??"unknown-file",remote:this._fileData?.remote??!1,type:this.type??"",file:this._fileData?.file}}};var On=class extends re{constructor({sync:e,context:t}){super();this.cache=new Map;this.add=async e=>{let t=this.cache.get(e.id);t||(t=new ve(e.id,{ctx:this.context}),this.cache.set(e.id,t)),e.remote||t[ot](e);let r=await this.context.files.add(e);t[ot](r)};this.get=(e,t)=>{if(this.cache.has(e))return this.cache.get(e);let r=new ve(e,t);return this.cache.set(e,r),this.load(r),r};this.load=async e=>{let t=await this.context.files.get(e.id);if(t)e[ot](t);else try{if(this.sync.status!=="active"){this.context.log("info","Sync is not active, waiting for online to load file",e.id,e.name);let s=this.sync.subscribe("onlineChange",o=>{o&&(s(),this.load(e))});return}let r=await this.sync.getFile(e.id);r.success?(await this.context.files.add(r.data),e[ot](r.data)):(this.context.log("error","Failed to load file",r),e[Sn]())}catch(r){this.context.log("error","Failed to load file",r),e[Sn]()}};this.onFileUploaded=e=>{this.context.log("debug","Marking file as uploaded",e.id),this.context.files.onUploaded(e.id)};this.sync=e,this.context=t,this.addDispose(this.context.internalEvents.subscribe("fileUploaded",this.onFileUploaded))}};var Ni=typeof window<"u"?window.indexedDB:void 0;function Qe(i){return i instanceof Error&&i.name==="AbortError"}function at(i){return new Promise((n,e)=>{i.onsuccess=()=>{n(i.result)},i.onerror=()=>{i.error&&Qe(i.error)?n(i.result):e(i.error)}})}function We(i,n){return new Promise((e,t)=>{let r=i.transaction([n],"readonly"),o=r.objectStore(n).openCursor(),a=0,f=0;o.onsuccess=function(p){let y=o.result;y&&(a++,f=f+yr(y.value),y.continue())},o.onerror=function(p){o.error&&Qe(o.error)?e({count:a,size:f}):t(o.error)},r.oncomplete=function(p){e({count:a,size:f})},r.onabort=function(p){t(p)},r.onerror=function(p){t(p)}})}function zi(i,n){let e=i.transaction(n,"readonly"),t=n.map(r=>{let s=e.objectStore(r);return at(s.getAll())});return Promise.all(t)}async function he(i){i.close(),await new Promise(n=>{n()}),await new Promise(n=>{n()})}async function In(i,n=Ni){let e=n.deleteDatabase([i,"meta"].join("_")),t=n.deleteDatabase([i,"collections"].join("_"));await Promise.all([new Promise((r,s)=>{e.onsuccess=r,e.onerror=s}),new Promise((r,s)=>{t.onsuccess=r,t.onerror=s})]),window.location.reload()}function _n(i,n=window.indexedDB){return at(n.deleteDatabase(i))}async function Ta(i=window.indexedDB){return i.databases()}function Hs(i,n,e,t,r){let s=i.transaction(n,e);if(t){let o=()=>{r?.("debug","aborting transaction");try{s.abort()}catch(a){r?.("debug","aborting transaction failed",a)}};t.addEventListener("abort",o),s.addEventListener("error",()=>{t.removeEventListener("abort",o)}),s.addEventListener("complete",()=>{t.removeEventListener("abort",o)})}return s}async function $i(i,n,e,t=window.indexedDB){(await Ta(t)).some(a=>a.name===n)&&(await _n(n,t),e.log("debug","Deleted existing database",n));let s=await new Promise((a,f)=>{e.log("debug","Opening reset database",n,"at",i.version);let p=t.open(n,i.version);p.onupgradeneeded=()=>{e.log("debug","Upgrading database",n,"to version",i.version);let y=i,D=p.transaction;if(!D)throw new Error("No transaction");for(let w of Array.from(y.objectStoreNames)){let A=y.transaction(w).objectStore(w);D.db.createObjectStore(w,{keyPath:A.keyPath,autoIncrement:A.autoIncrement});let g=D.objectStore(w),I=y.transaction(w).objectStore(w);for(let E of Array.from(I.indexNames)){let O=I.index(E);e.log("debug","Copying index",E),g.createIndex(E,O.keyPath,{unique:O.unique,multiEntry:O.multiEntry})}}},p.onsuccess=()=>{e.log("debug","Opened reset database",n),a(p.result)},p.onerror=()=>f(p.error??new Error("Unknown database upgrade error"))}),o=await zi(i,Array.from(i.objectStoreNames));await new Promise((a,f)=>{let p=s.transaction(Array.from(s.objectStoreNames),"readwrite");for(let y=0;y<o.length;y++){let D=p.objectStore(i.objectStoreNames[y]);for(let w of o[y])D.add(w)}p.oncomplete=()=>a(),p.onerror=y=>{let D=p.error??y.target.transaction?.error??new Error("Unknown error");e.log("critical","Error copying data",D),f(D)}}),await he(s)}function Qs(i,n,e=window.indexedDB){return new Promise((t,r)=>{let s=e.open(i,n);s.onsuccess=()=>{t(s.result)},s.onerror=()=>{r(s.error)},s.onblocked=()=>{r(new Error("Database blocked"))},s.onupgradeneeded=o=>{let a=s.result;a.version!==n&&(a.close(),r(new Error(`Migration error: database version changed unexpectedly when reading current data. Expected ${n}, got ${a.version}`)))}})}function Tt(i){return[i,"meta"].join("_")}function ct(i){return[i,"collections"].join("_")}function Ws(i){return i.name?.split("_")[0]}var Pe=class{constructor(n){this.log=n;this.consumed=!1;this.handlers=[];this.reset=()=>{this.consumed=!1}}register(n){this.handlers.push(n)}async shutdown(){this.consumed&&this.log?.("warn","ShutdownHandler already consumed"),this.consumed=!0,await Promise.all(this.handlers.map(n=>n())),this.handlers.length=0}get isShuttingDown(){return this.consumed}};function Js(i,n){return`@@wip-${i}-${Ve(n)}`}function Gs({migration:i,newOids:n,ctx:e}){return i.allCollections.reduce((t,r)=>(t[r]={put:async(s,o)=>{ze(i.newSchema.collections[r],s);let a=s[i.newSchema.collections[r].primaryKey],f=Z(r,a);return n.push(f),await e.time.withMigrationTime(i.version,()=>e.meta.insertData({operations:e.patchCreator.createInitialize(s,f,o?.access),isLocal:!0})),s},delete:async s=>{let o=Z(r,s);await e.time.withMigrationTime(i.version,()=>e.meta.deleteDocument(o))}},t),{})}function ka({migration:i,context:n,documents:e}){return i.oldCollections.reduce((t,r)=>(t[r]={get:async s=>{let o=Z(r,s);return await n.meta.getDocumentSnapshot(o,{to:n.time.nowWithVersion(i.oldSchema.version)})},findOne:async s=>{let o=await e.findOneOid({collection:r,index:s});return o?await n.meta.getDocumentSnapshot(o,{to:n.time.nowWithVersion(i.oldSchema.version)}):null},findAll:async s=>{let{result:o}=await e.findAllOids({collection:r,index:s});return await Promise.all(o.map(f=>n.meta.getDocumentSnapshot(f,{to:n.time.nowWithVersion(i.oldSchema.version)})))}},t),{})}async function Ys({migration:i,context:n,ns:e}){let t={...n,schema:i.oldSchema};if(i.oldSchema.version===0)return Ba({migration:i,context:t});let r=new Array,s=await e.openDocuments(t),o=ka({migration:i,context:t,documents:s}),a=Gs({migration:i,newOids:r,ctx:t}),f=async D=>{await n.meta.deleteCollection(D)},p=new Array;return{log:n.log,newOids:r,deleteCollection:f,migrate:async(D,w)=>{let A=await o[D].findAll();n.log("debug",`Migrating ${A.length} documents in ${D}`),await Promise.all(A.filter(Boolean).map(async g=>{let I=ie(g);N(!!I,`Document is missing an OID: ${JSON.stringify(g)}`);let E=await n.meta.getDocumentAuthz(I),O=ce(g),_=await w(g);if(_){wt(O),wt(_),et(_);let k=Qt(O,_,()=>n.time.zeroWithVersion(i.version),void 0,[],{mergeUnknownObjects:!0,defaultUndefined:!1,authz:E});k.length>0&&await n.meta.insertData({operations:k,isLocal:!0})}}))},queries:o,mutations:a,awaitables:p,close:async()=>{await s.close()}}}function Ba({migration:i,context:n}){let e=new Array,t=new Proxy({},{get(){throw new Error("Queries are not available in initial migrations; there is no database yet!")}}),r=Gs({migration:i,newOids:e,ctx:n});return{log:n.log,newOids:e,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:t,mutations:r,awaitables:[],close:()=>Promise.resolve()}}async function Xs({ctx:i,documents:n,migration:e,engine:t}){let r=await La({currentVersion:e.oldSchema.version,newVersion:e.newSchema.version,ctx:i});for(let s of e.allCollections){let{result:o}=await n.findAllOids({collection:s});o.push(...t.newOids.filter(p=>le(p).collection===s),...r.filter(p=>le(p).collection===s));let f=(await Promise.all(o.map(async p=>{try{let y=await i.meta.getDocumentSnapshot(p);return[p,y]}catch(y){return i.log("error","Could not regenerate snapshot during migration for oid",p,"this document will not be preserved",y),null}}))).filter(p=>!!p);await n.saveEntities(f.map(([p,y])=>({oid:p,getSnapshot(){return y}})),{collections:[s]})}}async function La({currentVersion:i,newVersion:n,ctx:e}){let t=[];return await e.meta.iterateAllOperations(r=>{t.push(r)},{from:e.time.zeroWithVersion(i+1)}),Array.from(new Set(t.map(r=>z(r.oid))))}async function Zs({context:i,version:n}){let e=await i.persistence.openNamespace(i.namespace,i);await ja(i.namespace,async()=>{let t=await i.persistence.getNamespaceVersion(i.namespace);i.log("debug","Opening index database",i.namespace,"Current database version:",t,"target version:",n,i.schema.wip?"(wip)":"");let r=Ks({currentVersion:t,targetVersion:n,migrations:i.migrations});r.length>0&&(i.log("debug","Migrations to run:",r.map(s=>s.version)),await Ma({context:i,ns:e,toRun:r}))})}async function ja(i,n){typeof navigator<"u"&&navigator.locks?await navigator.locks.request(`verdant_migration_${i}`,n):await n()}async function Ma({context:i,toRun:n,ns:e}){i.pauseRebasing=!0;for(let t of n){i.log("info",`\u{1F680} Running migration v${t.oldSchema.version} -> v${t.newSchema.version}`);let r={...i,schema:t.oldSchema,shutdownHandler:new Pe(i.log)},s=await Ys({migration:t,context:r,ns:e});try{i.log("debug","Migrating data",r.namespace,"from version",t.oldSchema.version,"to version",t.newSchema.version),await t.migrate(s),await Promise.all(s.awaitables)}catch(a){throw i.log("critical",`Migration failed (${t.oldSchema.version} -> ${t.newSchema.version})`,a),a instanceof Error?a:new Error("Unknown error during migration")}await s.close(),r.log("debug","Upgrading database",r.namespace,"from version",r.schema.version,"to version",t.newSchema.version),await e.applyMigration(r,t),r.schema=t.newSchema;let o=await e.openDocuments(r);await Xs({ctx:r,migration:t,engine:s,documents:o}),await o.close(),r.log("debug",`Migration of ${r.namespace} complete.`),r.log("info",`
4
+ `)},_domwindow:function(){return p("domwindow")},_bigint:function(l){return p("bigint:"+l.toString())},_process:function(){return p("process")},_timer:function(){return p("timer")},_pipe:function(){return p("pipe")},_tcp:function(){return p("tcp")},_udp:function(){return p("udp")},_tty:function(){return p("tty")},_statwatcher:function(){return p("statwatcher")},_securecontext:function(){return p("securecontext")},_connection:function(){return p("connection")},_zlib:function(){return p("zlib")},_context:function(){return p("context")},_nodescript:function(){return p("nodescript")},_httpparser:function(){return p("httpparser")},_dataview:function(){return p("dataview")},_signal:function(){return p("signal")},_fsevent:function(){return p("fsevent")},_tlswrap:function(){return p("tlswrap")}}}function k(){return{buf:"",write:function(b){this.buf+=b},end:function(b){this.buf+=b},read:function(){return this.buf}}}e.writeToStream=function(b,S,u){return u===void 0&&(u=S,S={}),D(S=E(b,S),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,n,e){(function(t,r,s,o,a,d,m,h,O){(function(w){"use strict";var C=typeof Uint8Array<"u"?Uint8Array:Array,y="+".charCodeAt(0),I="/".charCodeAt(0),E="0".charCodeAt(0),_="a".charCodeAt(0),D="A".charCodeAt(0),k="-".charCodeAt(0),b="_".charCodeAt(0);function S(u){return u=u.charCodeAt(0),u===y||u===k?62:u===I||u===b?63:u<E?-1:u<E+10?u-E+26+26:u<D+26?u-D:u<_+26?u-_+26:void 0}w.toByteArray=function(u){var p,l;if(0<u.length%4)throw new Error("Invalid string. Length must be a multiple of 4");var v=u.length,v=u.charAt(v-2)==="="?2:u.charAt(v-1)==="="?1:0,x=new C(3*u.length/4-v),j=0<v?u.length-4:u.length,B=0;function M(T){x[B++]=T}for(p=0;p<j;p+=4,0)M((16711680&(l=S(u.charAt(p))<<18|S(u.charAt(p+1))<<12|S(u.charAt(p+2))<<6|S(u.charAt(p+3))))>>16),M((65280&l)>>8),M(255&l);return v==2?M(255&(l=S(u.charAt(p))<<2|S(u.charAt(p+1))>>4)):v==1&&(M((l=S(u.charAt(p))<<10|S(u.charAt(p+1))<<4|S(u.charAt(p+2))>>2)>>8&255),M(255&l)),x},w.fromByteArray=function(u){var p,l,v,x,j=u.length%3,B="";function M(T){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(T)}for(p=0,v=u.length-j;p<v;p+=3)l=(u[p]<<16)+(u[p+1]<<8)+u[p+2],B+=M((x=l)>>18&63)+M(x>>12&63)+M(x>>6&63)+M(63&x);switch(j){case 1:B=(B+=M((l=u[u.length-1])>>2))+M(l<<4&63)+"==";break;case 2:B=(B=(B+=M((l=(u[u.length-2]<<8)+u[u.length-1])>>10))+M(l>>4&63))+M(l<<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,n,e){(function(t,r,y,o,a,d,m,h,O){var w=i("base64-js"),C=i("ieee754");function y(c,f,g){if(!(this instanceof y))return new y(c,f,g);var A,P,F,U,J=typeof c;if(f==="base64"&&J=="string")for(c=(U=c).trim?U.trim():U.replace(/^\s+|\s+$/g,"");c.length%4!=0;)c+="=";if(J=="number")A=ne(c);else if(J=="string")A=y.byteLength(c,f);else{if(J!="object")throw new Error("First argument needs to be a number, array or string.");A=ne(c.length)}if(y._useTypedArrays?P=y._augment(new Uint8Array(A)):((P=this).length=A,P._isBuffer=!0),y._useTypedArrays&&typeof c.byteLength=="number")P._set(c);else if(W(U=c)||y.isBuffer(U)||U&&typeof U=="object"&&typeof U.length=="number")for(F=0;F<A;F++)y.isBuffer(c)?P[F]=c.readUInt8(F):P[F]=c[F];else if(J=="string")P.write(c,0,f);else if(J=="number"&&!y._useTypedArrays&&!g)for(F=0;F<A;F++)P[F]=0;return P}function I(c,f,g,A){return y._charsWritten=Mt(function(P){for(var F=[],U=0;U<P.length;U++)F.push(255&P.charCodeAt(U));return F}(f),c,g,A)}function E(c,f,g,A){return y._charsWritten=Mt(function(P){for(var F,U,J=[],X=0;X<P.length;X++)U=P.charCodeAt(X),F=U>>8,U=U%256,J.push(U),J.push(F);return J}(f),c,g,A)}function _(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||(R(typeof g=="boolean","missing or invalid endian"),R(f!=null,"missing offset"),R(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 k(c,f,g,F){F||(R(typeof g=="boolean","missing or invalid endian"),R(f!=null,"missing offset"),R(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||(R(typeof g=="boolean","missing or invalid endian"),R(f!=null,"missing offset"),R(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 S(c,f,g,A){if(A||(R(typeof g=="boolean","missing or invalid endian"),R(f!=null,"missing offset"),R(f+3<c.length,"Trying to read beyond buffer length")),!(c.length<=f))return A=k(c,f,g,!0),2147483648&A?-1*(4294967295-A+1):A}function u(c,f,g,A){return A||(R(typeof g=="boolean","missing or invalid endian"),R(f+3<c.length,"Trying to read beyond buffer length")),C.read(c,f,g,23,4)}function p(c,f,g,A){return A||(R(typeof g=="boolean","missing or invalid endian"),R(f+7<c.length,"Trying to read beyond buffer length")),C.read(c,f,g,52,8)}function l(c,f,g,A,P){if(P||(R(f!=null,"missing value"),R(typeof A=="boolean","missing or invalid endian"),R(g!=null,"missing offset"),R(g+1<c.length,"trying to write beyond buffer length"),ti(f,65535)),P=c.length,!(P<=g))for(var F=0,U=Math.min(P-g,2);F<U;F++)c[g+F]=(f&255<<8*(A?F:1-F))>>>8*(A?F:1-F)}function v(c,f,g,A,P){if(P||(R(f!=null,"missing value"),R(typeof A=="boolean","missing or invalid endian"),R(g!=null,"missing offset"),R(g+3<c.length,"trying to write beyond buffer length"),ti(f,4294967295)),P=c.length,!(P<=g))for(var F=0,U=Math.min(P-g,4);F<U;F++)c[g+F]=f>>>8*(A?F:3-F)&255}function x(c,f,g,A,P){P||(R(f!=null,"missing value"),R(typeof A=="boolean","missing or invalid endian"),R(g!=null,"missing offset"),R(g+1<c.length,"Trying to write beyond buffer length"),ni(f,32767,-32768)),c.length<=g||l(c,0<=f?f:65535+f+1,g,A,P)}function j(c,f,g,A,P){P||(R(f!=null,"missing value"),R(typeof A=="boolean","missing or invalid endian"),R(g!=null,"missing offset"),R(g+3<c.length,"Trying to write beyond buffer length"),ni(f,2147483647,-2147483648)),c.length<=g||v(c,0<=f?f:4294967295+f+1,g,A,P)}function B(c,f,g,A,P){P||(R(f!=null,"missing value"),R(typeof A=="boolean","missing or invalid endian"),R(g!=null,"missing offset"),R(g+3<c.length,"Trying to write beyond buffer length"),or(f,34028234663852886e22,-34028234663852886e22)),c.length<=g||C.write(c,f,g,A,23,4)}function M(c,f,g,A,P){P||(R(f!=null,"missing value"),R(typeof A=="boolean","missing or invalid endian"),R(g!=null,"missing offset"),R(g+7<c.length,"Trying to write beyond buffer length"),or(f,17976931348623157e292,-17976931348623157e292)),c.length<=g||C.write(c,f,g,A,52,8)}e.Buffer=y,e.SlowBuffer=y,e.INSPECT_MAX_BYTES=50,y.poolSize=8192,y._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}}(),y.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}},y.isBuffer=function(c){return!(c==null||!c._isBuffer)},y.byteLength=function(c,f){var g;switch(c+="",f||"utf8"){case"hex":g=c.length/2;break;case"utf8":case"utf-8":g=Ee(c).length;break;case"ascii":case"binary":case"raw":g=c.length;break;case"base64":g=rr(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},y.concat=function(c,f){if(R(W(c),`Usage: Buffer.concat(list, [totalLength])
5
+ list should be an Array.`),c.length===0)return new y(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 y(f),A=0,P=0;P<c.length;P++){var F=c[P];F.copy(g,A),A+=F.length}return g},y.prototype.write=function(c,f,g,A){isFinite(f)?isFinite(g)||(A=g,g=void 0):(X=A,A=f,f=g,g=X),f=Number(f)||0;var P,F,U,J,X=this.length-f;switch((!g||X<(g=Number(g)))&&(g=X),A=String(A||"utf8").toLowerCase()){case"hex":P=function(xe,ae,ce,Z){ce=Number(ce)||0;var Y=xe.length-ce;(!Z||Y<(Z=Number(Z)))&&(Z=Y),R((Y=ae.length)%2==0,"Invalid hex string"),Y/2<Z&&(Z=Y/2);for(var Xe=0;Xe<Z;Xe++){var ar=parseInt(ae.substr(2*Xe,2),16);R(!isNaN(ar),"Invalid hex string"),xe[ce+Xe]=ar}return y._charsWritten=2*Xe,Xe}(this,c,f,g);break;case"utf8":case"utf-8":F=this,U=f,J=g,P=y._charsWritten=Mt(Ee(c),F,U,J);break;case"ascii":case"binary":P=I(this,c,f,g);break;case"base64":F=this,U=f,J=g,P=y._charsWritten=Mt(rr(c),F,U,J);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":P=E(this,c,f,g);break;default:throw new Error("Unknown encoding")}return P},y.prototype.toString=function(c,f,g){var A,P,F,U,J=this;if(c=String(c||"utf8").toLowerCase(),f=Number(f)||0,(g=g!==void 0?Number(g):J.length)===f)return"";switch(c){case"hex":A=function(X,xe,ae){var ce=X.length;(!xe||xe<0)&&(xe=0),(!ae||ae<0||ce<ae)&&(ae=ce);for(var Z="",Y=xe;Y<ae;Y++)Z+=q(X[Y]);return Z}(J,f,g);break;case"utf8":case"utf-8":A=function(X,xe,ae){var ce="",Z="";ae=Math.min(X.length,ae);for(var Y=xe;Y<ae;Y++)X[Y]<=127?(ce+=sr(Z)+String.fromCharCode(X[Y]),Z=""):Z+="%"+X[Y].toString(16);return ce+sr(Z)}(J,f,g);break;case"ascii":case"binary":A=_(J,f,g);break;case"base64":P=J,U=g,A=(F=f)===0&&U===P.length?w.fromByteArray(P):w.fromByteArray(P.slice(F,U));break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":A=function(X,xe,ae){for(var ce=X.slice(xe,ae),Z="",Y=0;Y<ce.length;Y+=2)Z+=String.fromCharCode(ce[Y]+256*ce[Y+1]);return Z}(J,f,g);break;default:throw new Error("Unknown encoding")}return A},y.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},y.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){R(g<=A,"sourceEnd < sourceStart"),R(0<=f&&f<c.length,"targetStart out of bounds"),R(0<=g&&g<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=c.length-f<A-g?c.length-f+g:A)-g;if(P<100||!y._useTypedArrays)for(var F=0;F<P;F++)c[F+f]=this[F+g];else c._set(this.subarray(g,g+P),f)}},y.prototype.slice=function(c,f){var g=this.length;if(c=H(c,g,0),f=H(f,g,g),y._useTypedArrays)return y._augment(this.subarray(c,f));for(var A=f-c,P=new y(A,void 0,!0),F=0;F<A;F++)P[F]=this[F+c];return P},y.prototype.get=function(c){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(c)},y.prototype.set=function(c,f){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(c,f)},y.prototype.readUInt8=function(c,f){if(f||(R(c!=null,"missing offset"),R(c<this.length,"Trying to read beyond buffer length")),!(c>=this.length))return this[c]},y.prototype.readUInt16LE=function(c,f){return D(this,c,!0,f)},y.prototype.readUInt16BE=function(c,f){return D(this,c,!1,f)},y.prototype.readUInt32LE=function(c,f){return k(this,c,!0,f)},y.prototype.readUInt32BE=function(c,f){return k(this,c,!1,f)},y.prototype.readInt8=function(c,f){if(f||(R(c!=null,"missing offset"),R(c<this.length,"Trying to read beyond buffer length")),!(c>=this.length))return 128&this[c]?-1*(255-this[c]+1):this[c]},y.prototype.readInt16LE=function(c,f){return b(this,c,!0,f)},y.prototype.readInt16BE=function(c,f){return b(this,c,!1,f)},y.prototype.readInt32LE=function(c,f){return S(this,c,!0,f)},y.prototype.readInt32BE=function(c,f){return S(this,c,!1,f)},y.prototype.readFloatLE=function(c,f){return u(this,c,!0,f)},y.prototype.readFloatBE=function(c,f){return u(this,c,!1,f)},y.prototype.readDoubleLE=function(c,f){return p(this,c,!0,f)},y.prototype.readDoubleBE=function(c,f){return p(this,c,!1,f)},y.prototype.writeUInt8=function(c,f,g){g||(R(c!=null,"missing value"),R(f!=null,"missing offset"),R(f<this.length,"trying to write beyond buffer length"),ti(c,255)),f>=this.length||(this[f]=c)},y.prototype.writeUInt16LE=function(c,f,g){l(this,c,f,!0,g)},y.prototype.writeUInt16BE=function(c,f,g){l(this,c,f,!1,g)},y.prototype.writeUInt32LE=function(c,f,g){v(this,c,f,!0,g)},y.prototype.writeUInt32BE=function(c,f,g){v(this,c,f,!1,g)},y.prototype.writeInt8=function(c,f,g){g||(R(c!=null,"missing value"),R(f!=null,"missing offset"),R(f<this.length,"Trying to write beyond buffer length"),ni(c,127,-128)),f>=this.length||(0<=c?this.writeUInt8(c,f,g):this.writeUInt8(255+c+1,f,g))},y.prototype.writeInt16LE=function(c,f,g){x(this,c,f,!0,g)},y.prototype.writeInt16BE=function(c,f,g){x(this,c,f,!1,g)},y.prototype.writeInt32LE=function(c,f,g){j(this,c,f,!0,g)},y.prototype.writeInt32BE=function(c,f,g){j(this,c,f,!1,g)},y.prototype.writeFloatLE=function(c,f,g){B(this,c,f,!0,g)},y.prototype.writeFloatBE=function(c,f,g){B(this,c,f,!1,g)},y.prototype.writeDoubleLE=function(c,f,g){M(this,c,f,!0,g)},y.prototype.writeDoubleBE=function(c,f,g){M(this,c,f,!1,g)},y.prototype.fill=function(c,f,g){if(f=f||0,g=g||this.length,R(typeof(c=typeof(c=c||0)=="string"?c.charCodeAt(0):c)=="number"&&!isNaN(c),"value is not a number"),R(f<=g,"end < start"),g!==f&&this.length!==0){R(0<=f&&f<this.length,"start out of bounds"),R(0<=g&&g<=this.length,"end out of bounds");for(var A=f;A<g;A++)this[A]=c}},y.prototype.inspect=function(){for(var c=[],f=this.length,g=0;g<f;g++)if(c[g]=q(this[g]),g===e.INSPECT_MAX_BYTES){c[g+1]="...";break}return"<Buffer "+c.join(" ")+">"},y.prototype.toArrayBuffer=function(){if(typeof Uint8Array>"u")throw new Error("Buffer.toArrayBuffer not supported in this browser");if(y._useTypedArrays)return new y(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 T=y.prototype;function H(c,f,g){return typeof c!="number"?g:f<=(c=~~c)?f:0<=c||0<=(c+=f)?c:0}function ne(c){return(c=~~Math.ceil(+c))<0?0:c}function W(c){return(Array.isArray||function(f){return Object.prototype.toString.call(f)==="[object Array]"})(c)}function q(c){return c<16?"0"+c.toString(16):c.toString(16)}function Ee(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("%")),U=0;U<F.length;U++)f.push(parseInt(F[U],16))}return f}function rr(c){return w.toByteArray(c)}function Mt(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 sr(c){try{return decodeURIComponent(c)}catch{return String.fromCharCode(65533)}}function ti(c,f){R(typeof c=="number","cannot write a non-number as a number"),R(0<=c,"specified a negative value for writing an unsigned value"),R(c<=f,"value is larger than maximum value for type"),R(Math.floor(c)===c,"value has a fractional component")}function ni(c,f,g){R(typeof c=="number","cannot write a non-number as a number"),R(c<=f,"value larger than maximum allowed value"),R(g<=c,"value smaller than minimum allowed value"),R(Math.floor(c)===c,"value has a fractional component")}function or(c,f,g){R(typeof c=="number","cannot write a non-number as a number"),R(c<=f,"value larger than maximum allowed value"),R(g<=c,"value smaller than minimum allowed value")}function R(c,f){if(!c)throw new Error(f||"Failed assertion")}y._augment=function(c){return c._isBuffer=!0,c._get=c.get,c._set=c.set,c.get=T.get,c.set=T.set,c.write=T.write,c.toString=T.toString,c.toLocaleString=T.toString,c.toJSON=T.toJSON,c.copy=T.copy,c.slice=T.slice,c.readUInt8=T.readUInt8,c.readUInt16LE=T.readUInt16LE,c.readUInt16BE=T.readUInt16BE,c.readUInt32LE=T.readUInt32LE,c.readUInt32BE=T.readUInt32BE,c.readInt8=T.readInt8,c.readInt16LE=T.readInt16LE,c.readInt16BE=T.readInt16BE,c.readInt32LE=T.readInt32LE,c.readInt32BE=T.readInt32BE,c.readFloatLE=T.readFloatLE,c.readFloatBE=T.readFloatBE,c.readDoubleLE=T.readDoubleLE,c.readDoubleBE=T.readDoubleBE,c.writeUInt8=T.writeUInt8,c.writeUInt16LE=T.writeUInt16LE,c.writeUInt16BE=T.writeUInt16BE,c.writeUInt32LE=T.writeUInt32LE,c.writeUInt32BE=T.writeUInt32BE,c.writeInt8=T.writeInt8,c.writeInt16LE=T.writeInt16LE,c.writeInt16BE=T.writeInt16BE,c.writeInt32LE=T.writeInt32LE,c.writeInt32BE=T.writeInt32BE,c.writeFloatLE=T.writeFloatLE,c.writeFloatBE=T.writeFloatBE,c.writeDoubleLE=T.writeDoubleLE,c.writeDoubleBE=T.writeDoubleBE,c.fill=T.fill,c.inspect=T.inspect,c.toArrayBuffer=T.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,n,e){(function(t,r,w,o,a,d,m,h,O){var w=i("buffer").Buffer,C=4,y=new w(C);y.fill(0),n.exports={hash:function(I,E,_,D){for(var k=E(function(l,v){l.length%C!=0&&(x=l.length+(C-l.length%C),l=w.concat([l,y],x));for(var x,j=[],B=v?l.readInt32BE:l.readInt32LE,M=0;M<l.length;M+=C)j.push(B.call(l,M));return j}(I=w.isBuffer(I)?I:new w(I),D),8*I.length),E=D,b=new w(_),S=E?b.writeInt32BE:b.writeInt32LE,u=0;u<k.length;u++)S.call(b,k[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,n,e){(function(t,r,w,o,a,d,m,h,O){var w=i("buffer").Buffer,C=i("./sha"),y=i("./sha256"),I=i("./rng"),E={sha1:C,sha256:y,md5:i("./md5")},_=64,D=new w(_);function k(l,v){var x=E[l=l||"sha1"],j=[];return x||b("algorithm:",l,"is not yet supported"),{update:function(B){return w.isBuffer(B)||(B=new w(B)),j.push(B),B.length,this},digest:function(B){var M=w.concat(j),M=v?function(T,H,ne){w.isBuffer(H)||(H=new w(H)),w.isBuffer(ne)||(ne=new w(ne)),H.length>_?H=T(H):H.length<_&&(H=w.concat([H,D],_));for(var W=new w(_),q=new w(_),Ee=0;Ee<_;Ee++)W[Ee]=54^H[Ee],q[Ee]=92^H[Ee];return ne=T(w.concat([W,ne])),T(w.concat([q,ne]))}(x,v,M):x(M);return j=null,B?M.toString(B):M}}}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 k(l)},e.createHmac=k,e.randomBytes=function(l,v){if(!v||!v.call)return new w(I(l));try{v.call(this,void 0,new w(I(l)))}catch(x){v(x)}};var S,u=["createCredentials","createCipher","createCipheriv","createDecipher","createDecipheriv","createSign","createVerify","createDiffieHellman","pbkdf2"],p=function(l){e[l]=function(){b("sorry,",l,"is not implemented yet")}};for(S in u)p(u[S],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/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,n,e){(function(t,r,s,o,a,d,m,h,O){var w=i("./helpers");function C(b,S){b[S>>5]|=128<<S%32,b[14+(S+64>>>9<<4)]=S;for(var u=1732584193,p=-271733879,l=-1732584194,v=271733878,x=0;x<b.length;x+=16){var j=u,B=p,M=l,T=v,u=I(u,p,l,v,b[x+0],7,-680876936),v=I(v,u,p,l,b[x+1],12,-389564586),l=I(l,v,u,p,b[x+2],17,606105819),p=I(p,l,v,u,b[x+3],22,-1044525330);u=I(u,p,l,v,b[x+4],7,-176418897),v=I(v,u,p,l,b[x+5],12,1200080426),l=I(l,v,u,p,b[x+6],17,-1473231341),p=I(p,l,v,u,b[x+7],22,-45705983),u=I(u,p,l,v,b[x+8],7,1770035416),v=I(v,u,p,l,b[x+9],12,-1958414417),l=I(l,v,u,p,b[x+10],17,-42063),p=I(p,l,v,u,b[x+11],22,-1990404162),u=I(u,p,l,v,b[x+12],7,1804603682),v=I(v,u,p,l,b[x+13],12,-40341101),l=I(l,v,u,p,b[x+14],17,-1502002290),u=E(u,p=I(p,l,v,u,b[x+15],22,1236535329),l,v,b[x+1],5,-165796510),v=E(v,u,p,l,b[x+6],9,-1069501632),l=E(l,v,u,p,b[x+11],14,643717713),p=E(p,l,v,u,b[x+0],20,-373897302),u=E(u,p,l,v,b[x+5],5,-701558691),v=E(v,u,p,l,b[x+10],9,38016083),l=E(l,v,u,p,b[x+15],14,-660478335),p=E(p,l,v,u,b[x+4],20,-405537848),u=E(u,p,l,v,b[x+9],5,568446438),v=E(v,u,p,l,b[x+14],9,-1019803690),l=E(l,v,u,p,b[x+3],14,-187363961),p=E(p,l,v,u,b[x+8],20,1163531501),u=E(u,p,l,v,b[x+13],5,-1444681467),v=E(v,u,p,l,b[x+2],9,-51403784),l=E(l,v,u,p,b[x+7],14,1735328473),u=_(u,p=E(p,l,v,u,b[x+12],20,-1926607734),l,v,b[x+5],4,-378558),v=_(v,u,p,l,b[x+8],11,-2022574463),l=_(l,v,u,p,b[x+11],16,1839030562),p=_(p,l,v,u,b[x+14],23,-35309556),u=_(u,p,l,v,b[x+1],4,-1530992060),v=_(v,u,p,l,b[x+4],11,1272893353),l=_(l,v,u,p,b[x+7],16,-155497632),p=_(p,l,v,u,b[x+10],23,-1094730640),u=_(u,p,l,v,b[x+13],4,681279174),v=_(v,u,p,l,b[x+0],11,-358537222),l=_(l,v,u,p,b[x+3],16,-722521979),p=_(p,l,v,u,b[x+6],23,76029189),u=_(u,p,l,v,b[x+9],4,-640364487),v=_(v,u,p,l,b[x+12],11,-421815835),l=_(l,v,u,p,b[x+15],16,530742520),u=D(u,p=_(p,l,v,u,b[x+2],23,-995338651),l,v,b[x+0],6,-198630844),v=D(v,u,p,l,b[x+7],10,1126891415),l=D(l,v,u,p,b[x+14],15,-1416354905),p=D(p,l,v,u,b[x+5],21,-57434055),u=D(u,p,l,v,b[x+12],6,1700485571),v=D(v,u,p,l,b[x+3],10,-1894986606),l=D(l,v,u,p,b[x+10],15,-1051523),p=D(p,l,v,u,b[x+1],21,-2054922799),u=D(u,p,l,v,b[x+8],6,1873313359),v=D(v,u,p,l,b[x+15],10,-30611744),l=D(l,v,u,p,b[x+6],15,-1560198380),p=D(p,l,v,u,b[x+13],21,1309151649),u=D(u,p,l,v,b[x+4],6,-145523070),v=D(v,u,p,l,b[x+11],10,-1120210379),l=D(l,v,u,p,b[x+2],15,718787259),p=D(p,l,v,u,b[x+9],21,-343485551),u=k(u,j),p=k(p,B),l=k(l,M),v=k(v,T)}return Array(u,p,l,v)}function y(b,S,u,p,l,v){return k((S=k(k(S,b),k(p,v)))<<l|S>>>32-l,u)}function I(b,S,u,p,l,v,x){return y(S&u|~S&p,b,S,l,v,x)}function E(b,S,u,p,l,v,x){return y(S&p|u&~p,b,S,l,v,x)}function _(b,S,u,p,l,v,x){return y(S^u^p,b,S,l,v,x)}function D(b,S,u,p,l,v,x){return y(u^(S|~p),b,S,l,v,x)}function k(b,S){var u=(65535&b)+(65535&S);return(b>>16)+(S>>16)+(u>>16)<<16|65535&u}n.exports=function(b){return w.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,n,e){(function(t,r,s,o,a,d,m,h,O){var w;n.exports=w||function(C){for(var y,I=new Array(C),E=0;E<C;E++)!(3&E)&&(y=4294967296*Math.random()),I[E]=y>>>((3&E)<<3)&255;return I}}).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,n,e){(function(t,r,s,o,a,d,m,h,O){var w=i("./helpers");function C(E,_){E[_>>5]|=128<<24-_%32,E[15+(_+64>>9<<4)]=_;for(var D,k,b,S=Array(80),u=1732584193,p=-271733879,l=-1732584194,v=271733878,x=-1009589776,j=0;j<E.length;j+=16){for(var B=u,M=p,T=l,H=v,ne=x,W=0;W<80;W++){S[W]=W<16?E[j+W]:I(S[W-3]^S[W-8]^S[W-14]^S[W-16],1);var q=y(y(I(u,5),(q=p,k=l,b=v,(D=W)<20?q&k|~q&b:!(D<40)&&D<60?q&k|q&b|k&b:q^k^b)),y(y(x,S[W]),(D=W)<20?1518500249:D<40?1859775393:D<60?-1894007588:-899497514)),x=v,v=l,l=I(p,30),p=u,u=q}u=y(u,B),p=y(p,M),l=y(l,T),v=y(v,H),x=y(x,ne)}return Array(u,p,l,v,x)}function y(E,_){var D=(65535&E)+(65535&_);return(E>>16)+(_>>16)+(D>>16)<<16|65535&D}function I(E,_){return E<<_|E>>>32-_}n.exports=function(E){return w.hash(E,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,n,e){(function(t,r,s,o,a,d,m,h,O){function w(_,D){var k=(65535&_)+(65535&D);return(_>>16)+(D>>16)+(k>>16)<<16|65535&k}function C(_,D){var k,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),S=new Array(1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225),u=new Array(64);_[D>>5]|=128<<24-D%32,_[15+(D+64>>9<<4)]=D;for(var p,l,v=0;v<_.length;v+=16){for(var x=S[0],j=S[1],B=S[2],M=S[3],T=S[4],H=S[5],ne=S[6],W=S[7],q=0;q<64;q++)u[q]=q<16?_[q+v]:w(w(w((l=u[q-2],I(l,17)^I(l,19)^E(l,10)),u[q-7]),(l=u[q-15],I(l,7)^I(l,18)^E(l,3))),u[q-16]),k=w(w(w(w(W,I(l=T,6)^I(l,11)^I(l,25)),T&H^~T&ne),b[q]),u[q]),p=w(I(p=x,2)^I(p,13)^I(p,22),x&j^x&B^j&B),W=ne,ne=H,H=T,T=w(M,k),M=B,B=j,j=x,x=w(k,p);S[0]=w(x,S[0]),S[1]=w(j,S[1]),S[2]=w(B,S[2]),S[3]=w(M,S[3]),S[4]=w(T,S[4]),S[5]=w(H,S[5]),S[6]=w(ne,S[6]),S[7]=w(W,S[7])}return S}var y=i("./helpers"),I=function(_,D){return _>>>D|_<<32-D},E=function(_,D){return _>>>D};n.exports=function(_){return y.hash(_,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,n,e){(function(t,r,s,o,a,d,m,h,O){e.read=function(w,C,y,I,v){var _,D,k=8*v-I-1,b=(1<<k)-1,S=b>>1,u=-7,p=y?v-1:0,l=y?-1:1,v=w[C+p];for(p+=l,_=v&(1<<-u)-1,v>>=-u,u+=k;0<u;_=256*_+w[C+p],p+=l,u-=8);for(D=_&(1<<-u)-1,_>>=-u,u+=I;0<u;D=256*D+w[C+p],p+=l,u-=8);if(_===0)_=1-S;else{if(_===b)return D?NaN:1/0*(v?-1:1);D+=Math.pow(2,I),_-=S}return(v?-1:1)*D*Math.pow(2,_-I)},e.write=function(w,C,y,I,E,x){var D,k,b=8*x-E-1,S=(1<<b)-1,u=S>>1,p=E===23?Math.pow(2,-24)-Math.pow(2,-77):0,l=I?0:x-1,v=I?1:-1,x=C<0||C===0&&1/C<0?1:0;for(C=Math.abs(C),isNaN(C)||C===1/0?(k=isNaN(C)?1:0,D=S):(D=Math.floor(Math.log(C)/Math.LN2),C*(I=Math.pow(2,-D))<1&&(D--,I*=2),2<=(C+=1<=D+u?p/I:p*Math.pow(2,1-u))*I&&(D++,I/=2),S<=D+u?(k=0,D=S):1<=D+u?(k=(C*I-1)*Math.pow(2,E),D+=u):(k=C*Math.pow(2,u-1)*Math.pow(2,E),D=0));8<=E;w[y+l]=255&k,l+=v,k/=256,E-=8);for(D=D<<E|k,b+=E;0<b;w[y+l]=255&D,l+=v,D/=256,b-=8);w[y+l-v]|=128*x}}).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,n,e){(function(t,r,s,o,a,d,m,h,O){var w,C,y;function I(){}(t=n.exports={}).nextTick=(C=typeof window<"u"&&window.setImmediate,y=typeof window<"u"&&window.postMessage&&window.addEventListener,C?function(E){return window.setImmediate(E)}:y?(w=[],window.addEventListener("message",function(E){var _=E.source;_!==window&&_!==null||E.data!=="process-tick"||(E.stopPropagation(),0<w.length&&w.shift()())},!0),function(E){w.push(E),window.postMessage("process-tick","*")}):function(E){setTimeout(E,0)}),t.title="browser",t.browser=!0,t.env={},t.argv=[],t.on=I,t.addListener=I,t.once=I,t.off=I,t.removeListener=I,t.removeAllListeners=I,t.emit=I,t.binding=function(E){throw new Error("process.binding is not supported")},t.cwd=function(){return"/"},t.chdir=function(E){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 mi=le((wl,$r)=>{$r.exports=function(n,e){var t="000000000"+n;return t.substr(t.length-e)}});var qr=le((vl,Kr)=>{var qo=mi(),Ho=typeof window=="object"?window:self,Qo=Object.keys(Ho).length,Wo=navigator.mimeTypes?navigator.mimeTypes.length:0,Jo=qo((Wo+navigator.userAgent.length).toString(36)+Qo.toString(36),4);Kr.exports=function(){return Jo}});var Jr=le((xl,Wr)=>{var gi,Hr=typeof window<"u"&&(window.crypto||window.msCrypto)||typeof self<"u"&&self.crypto;Hr?(Qr=Math.pow(2,32)-1,gi=function(){return Math.abs(Hr.getRandomValues(new Uint32Array(1))[0]/Qr)}):gi=Math.random;var Qr;Wr.exports=gi});var He=le((Sl,Zr)=>{var Xt=qr(),Gr=mi(),Go=Jr(),Et=0,bi=4,Zt=36,Yr=Math.pow(Zt,bi);function yi(){return Gr((Go()*Yr<<0).toString(Zt),bi)}function Xr(){return Et=Et<Yr?Et:0,Et++,Et-1}function Dt(){var i="c",n=new Date().getTime().toString(Zt),e=Gr(Xr().toString(Zt),bi),t=Xt(),r=yi()+yi();return i+n+e+t+r}Dt.slug=function(){var n=new Date().getTime().toString(36),e=Xr().toString(36).slice(-4),t=Xt().slice(0,1)+Xt().slice(-1),r=yi().slice(-2);return n.slice(-2)+e+t+r};Dt.isCuid=function(n){return typeof n!="string"?!1:!!n.startsWith("c")};Dt.isSlug=function(n){if(typeof n!="string")return!1;var e=n.length;return e>=7&&e<=10};Dt.fingerprint=Xt;Zr.exports=Dt});var We={};cr(We,{__addDisposableResource:()=>Rs,__assign:()=>fn,__asyncDelegator:()=>Os,__asyncGenerator:()=>Ss,__asyncValues:()=>Is,__await:()=>at,__awaiter:()=>gs,__classPrivateFieldGet:()=>Ps,__classPrivateFieldIn:()=>As,__classPrivateFieldSet:()=>Cs,__createBinding:()=>pn,__decorate:()=>hs,__disposeResources:()=>Fs,__esDecorate:()=>ya,__exportStar:()=>bs,__extends:()=>us,__generator:()=>ys,__importDefault:()=>Ds,__importStar:()=>Es,__makeTemplateObject:()=>_s,__metadata:()=>ms,__param:()=>ps,__propKey:()=>wa,__read:()=>Di,__rest:()=>fs,__runInitializers:()=>ba,__setFunctionName:()=>va,__spread:()=>ws,__spreadArray:()=>xs,__spreadArrays:()=>vs,__values:()=>hn,default:()=>Oa});function us(i,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");Ei(i,n);function e(){this.constructor=i}i.prototype=n===null?Object.create(n):(e.prototype=n.prototype,new e)}function fs(i,n){var e={};for(var t in i)Object.prototype.hasOwnProperty.call(i,t)&&n.indexOf(t)<0&&(e[t]=i[t]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,t=Object.getOwnPropertySymbols(i);r<t.length;r++)n.indexOf(t[r])<0&&Object.prototype.propertyIsEnumerable.call(i,t[r])&&(e[t[r]]=i[t[r]]);return e}function hs(i,n,e,t){var r=arguments.length,s=r<3?n:t===null?t=Object.getOwnPropertyDescriptor(n,e):t,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(i,n,e,t);else for(var a=i.length-1;a>=0;a--)(o=i[a])&&(s=(r<3?o(s):r>3?o(n,e,s):o(n,e))||s);return r>3&&s&&Object.defineProperty(n,e,s),s}function ps(i,n){return function(e,t){n(e,t,i)}}function ya(i,n,e,t,r,s){function o(_){if(_!==void 0&&typeof _!="function")throw new TypeError("Function expected");return _}for(var a=t.kind,d=a==="getter"?"get":a==="setter"?"set":"value",m=!n&&i?t.static?i:i.prototype:null,h=n||(m?Object.getOwnPropertyDescriptor(m,t.name):{}),O,w=!1,C=e.length-1;C>=0;C--){var y={};for(var I in t)y[I]=I==="access"?{}:t[I];for(var I in t.access)y.access[I]=t.access[I];y.addInitializer=function(_){if(w)throw new TypeError("Cannot add initializers after decoration has completed");s.push(o(_||null))};var E=(0,e[C])(a==="accessor"?{get:h.get,set:h.set}:h[d],y);if(a==="accessor"){if(E===void 0)continue;if(E===null||typeof E!="object")throw new TypeError("Object expected");(O=o(E.get))&&(h.get=O),(O=o(E.set))&&(h.set=O),(O=o(E.init))&&r.unshift(O)}else(O=o(E))&&(a==="field"?r.unshift(O):h[d]=O)}m&&Object.defineProperty(m,t.name,h),w=!0}function ba(i,n,e){for(var t=arguments.length>2,r=0;r<n.length;r++)e=t?n[r].call(i,e):n[r].call(i);return t?e:void 0}function wa(i){return typeof i=="symbol"?i:"".concat(i)}function va(i,n,e){return typeof n=="symbol"&&(n=n.description?"[".concat(n.description,"]"):""),Object.defineProperty(i,"name",{configurable:!0,value:e?"".concat(e," ",n):n})}function ms(i,n){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(i,n)}function gs(i,n,e,t){function r(s){return s instanceof e?s:new e(function(o){o(s)})}return new(e||(e=Promise))(function(s,o){function a(h){try{m(t.next(h))}catch(O){o(O)}}function d(h){try{m(t.throw(h))}catch(O){o(O)}}function m(h){h.done?s(h.value):r(h.value).then(a,d)}m((t=t.apply(i,n||[])).next())})}function ys(i,n){var e={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},t,r,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(m){return function(h){return d([m,h])}}function d(m){if(t)throw new TypeError("Generator is already executing.");for(;o&&(o=0,m[0]&&(e=0)),e;)try{if(t=1,r&&(s=m[0]&2?r.return:m[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,m[1])).done)return s;switch(r=0,s&&(m=[m[0]&2,s.value]),m[0]){case 0:case 1:s=m;break;case 4:return e.label++,{value:m[1],done:!1};case 5:e.label++,r=m[1],m=[0];continue;case 7:m=e.ops.pop(),e.trys.pop();continue;default:if(s=e.trys,!(s=s.length>0&&s[s.length-1])&&(m[0]===6||m[0]===2)){e=0;continue}if(m[0]===3&&(!s||m[1]>s[0]&&m[1]<s[3])){e.label=m[1];break}if(m[0]===6&&e.label<s[1]){e.label=s[1],s=m;break}if(s&&e.label<s[2]){e.label=s[2],e.ops.push(m);break}s[2]&&e.ops.pop(),e.trys.pop();continue}m=n.call(i,e)}catch(h){m=[6,h],r=0}finally{t=s=0}if(m[0]&5)throw m[1];return{value:m[0]?m[1]:void 0,done:!0}}}function bs(i,n){for(var e in i)e!=="default"&&!Object.prototype.hasOwnProperty.call(n,e)&&pn(n,i,e)}function hn(i){var n=typeof Symbol=="function"&&Symbol.iterator,e=n&&i[n],t=0;if(e)return e.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&t>=i.length&&(i=void 0),{value:i&&i[t++],done:!i}}};throw new TypeError(n?"Object is not iterable.":"Symbol.iterator is not defined.")}function Di(i,n){var e=typeof Symbol=="function"&&i[Symbol.iterator];if(!e)return i;var t=e.call(i),r,s=[],o;try{for(;(n===void 0||n-- >0)&&!(r=t.next()).done;)s.push(r.value)}catch(a){o={error:a}}finally{try{r&&!r.done&&(e=t.return)&&e.call(t)}finally{if(o)throw o.error}}return s}function ws(){for(var i=[],n=0;n<arguments.length;n++)i=i.concat(Di(arguments[n]));return i}function vs(){for(var i=0,n=0,e=arguments.length;n<e;n++)i+=arguments[n].length;for(var t=Array(i),r=0,n=0;n<e;n++)for(var s=arguments[n],o=0,a=s.length;o<a;o++,r++)t[r]=s[o];return t}function xs(i,n,e){if(e||arguments.length===2)for(var t=0,r=n.length,s;t<r;t++)(s||!(t in n))&&(s||(s=Array.prototype.slice.call(n,0,t)),s[t]=n[t]);return i.concat(s||Array.prototype.slice.call(n))}function at(i){return this instanceof at?(this.v=i,this):new at(i)}function Ss(i,n,e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=e.apply(i,n||[]),r,s=[];return r={},o("next"),o("throw"),o("return"),r[Symbol.asyncIterator]=function(){return this},r;function o(w){t[w]&&(r[w]=function(C){return new Promise(function(y,I){s.push([w,C,y,I])>1||a(w,C)})})}function a(w,C){try{d(t[w](C))}catch(y){O(s[0][3],y)}}function d(w){w.value instanceof at?Promise.resolve(w.value.v).then(m,h):O(s[0][2],w)}function m(w){a("next",w)}function h(w){a("throw",w)}function O(w,C){w(C),s.shift(),s.length&&a(s[0][0],s[0][1])}}function Os(i){var n,e;return n={},t("next"),t("throw",function(r){throw r}),t("return"),n[Symbol.iterator]=function(){return this},n;function t(r,s){n[r]=i[r]?function(o){return(e=!e)?{value:at(i[r](o)),done:!1}:s?s(o):o}:s}}function Is(i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=i[Symbol.asyncIterator],e;return n?n.call(i):(i=typeof hn=="function"?hn(i):i[Symbol.iterator](),e={},t("next"),t("throw"),t("return"),e[Symbol.asyncIterator]=function(){return this},e);function t(s){e[s]=i[s]&&function(o){return new Promise(function(a,d){o=i[s](o),r(a,d,o.done,o.value)})}}function r(s,o,a,d){Promise.resolve(d).then(function(m){s({value:m,done:a})},o)}}function _s(i,n){return Object.defineProperty?Object.defineProperty(i,"raw",{value:n}):i.raw=n,i}function Es(i){if(i&&i.__esModule)return i;var n={};if(i!=null)for(var e in i)e!=="default"&&Object.prototype.hasOwnProperty.call(i,e)&&pn(n,i,e);return xa(n,i),n}function Ds(i){return i&&i.__esModule?i:{default:i}}function Ps(i,n,e,t){if(e==="a"&&!t)throw new TypeError("Private accessor was defined without a getter");if(typeof n=="function"?i!==n||!t:!n.has(i))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e==="m"?t:e==="a"?t.call(i):t?t.value:n.get(i)}function Cs(i,n,e,t,r){if(t==="m")throw new TypeError("Private method is not writable");if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof n=="function"?i!==n||!r:!n.has(i))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t==="a"?r.call(i,e):r?r.value=e:n.set(i,e),e}function As(i,n){if(n===null||typeof n!="object"&&typeof n!="function")throw new TypeError("Cannot use 'in' operator on non-object");return typeof i=="function"?n===i:i.has(n)}function Rs(i,n,e){if(n!=null){if(typeof n!="object"&&typeof n!="function")throw new TypeError("Object expected.");var t;if(e){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");t=n[Symbol.asyncDispose]}if(t===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");t=n[Symbol.dispose]}if(typeof t!="function")throw new TypeError("Object not disposable.");i.stack.push({value:n,dispose:t,async:e})}else e&&i.stack.push({async:!0});return n}function Fs(i){function n(t){i.error=i.hasError?new Sa(t,i.error,"An error was suppressed during disposal."):t,i.hasError=!0}function e(){for(;i.stack.length;){var t=i.stack.pop();try{var r=t.dispose&&t.dispose.call(t.value);if(t.async)return Promise.resolve(r).then(e,function(s){return n(s),e()})}catch(s){n(s)}}if(i.hasError)throw i.error}return e()}var Ei,fn,pn,xa,Sa,Oa,Je=bo(()=>{Ei=function(i,n){return Ei=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},Ei(i,n)};fn=function(){return fn=Object.assign||function(n){for(var e,t=1,r=arguments.length;t<r;t++){e=arguments[t];for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&(n[s]=e[s])}return n},fn.apply(this,arguments)};pn=Object.create?function(i,n,e,t){t===void 0&&(t=e);var r=Object.getOwnPropertyDescriptor(n,e);(!r||("get"in r?!n.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return n[e]}}),Object.defineProperty(i,t,r)}:function(i,n,e,t){t===void 0&&(t=e),i[t]=n[e]};xa=Object.create?function(i,n){Object.defineProperty(i,"default",{enumerable:!0,value:n})}:function(i,n){i.default=n};Sa=typeof SuppressedError=="function"?SuppressedError:function(i,n,e){var t=new Error(e);return t.name="SuppressedError",t.error=i,t.suppressed=n,t};Oa={__extends:us,__assign:fn,__rest:fs,__decorate:hs,__param:ps,__metadata:ms,__awaiter:gs,__generator:ys,__createBinding:pn,__exportStar:bs,__values:hn,__read:Di,__spread:ws,__spreadArrays:vs,__spreadArray:xs,__await:at,__asyncGenerator:Ss,__asyncDelegator:Os,__asyncValues:Is,__makeTemplateObject:_s,__importStar:Es,__importDefault:Ds,__classPrivateFieldGet:Ps,__classPrivateFieldSet:Cs,__classPrivateFieldIn:As,__addDisposableResource:Rs,__disposeResources:Fs}});var ks=le(Ts=>{"use strict";Object.defineProperty(Ts,"__esModule",{value:!0})});var Ci=le(_e=>{"use strict";Object.defineProperty(_e,"__esModule",{value:!0});_e.invokeEventHandlersAsync=_e.invokeEventHandlers=_e.eventHandlerSafeInvokeAsync=_e.eventHandlerSafeInvoke=void 0;var Bs=(Je(),Ze(We));function Ls(i,n,e){try{return i(n,e),{succeeded:!0}}catch(t){return{error:t,succeeded:!1}}}_e.eventHandlerSafeInvoke=Ls;function Pi(i,n,e){return(0,Bs.__awaiter)(this,void 0,void 0,function*(){try{return yield i(n,e),{succeeded:!0}}catch(t){return{error:t,succeeded:!1}}})}_e.eventHandlerSafeInvokeAsync=Pi;function Ia(i,n,e,t){for(let r of i){let{succeeded:s,error:o}=Ls(r,n,e);if(!s&&t?.swallowExceptions!==!0)throw o}}_e.invokeEventHandlers=Ia;function _a(i,n,e,t){return(0,Bs.__awaiter)(this,void 0,void 0,function*(){if(t?.parallelize===!1)for(let r of i){let{succeeded:s,error:o}=yield Pi(r,n,e);if(!s&&t?.swallowExceptions!==!0)throw o}else{let r=[];for(let s of i)r.push(Pi(s,n,e).then(({succeeded:o,error:a})=>{if(!o&&t?.swallowExceptions!==!0)throw a}));yield Promise.all(r)}})}_e.invokeEventHandlersAsync=_a});var Vs=le(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.TypedEvent=void 0;var Ea=(Je(),Ze(We)),js=Ci(),Ms={swallowExceptions:!1,parallelize:!0},Ai=class{constructor(){this._handlers=[]}attach(n){this._handlers.push(n)}detach(n){this.tryRemoveHandler(n)}invoke(n,e,t=Ms){(0,js.invokeEventHandlers)(this._handlers,n,e,t)}invokeAsync(n,e,t=Ms){return(0,Ea.__awaiter)(this,void 0,void 0,function*(){yield(0,js.invokeEventHandlersAsync)(this._handlers,n,e,t)})}tryRemoveHandler(n){let e=this._handlers.findIndex(t=>t===n);e>=0&&this._handlers.splice(e,1)}};mn.TypedEvent=Ai});var Fi=le(Ri=>{"use strict";Object.defineProperty(Ri,"__esModule",{value:!0});var Da=(Je(),Ze(We));(0,Da.__exportStar)(Vs(),Ri)});var Us=le(gn=>{"use strict";Object.defineProperty(gn,"__esModule",{value:!0});gn.FinalizationRegistryMissingError=void 0;var Ti=class extends Error{};gn.FinalizationRegistryMissingError=Ti});var Bi=le(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.WeakHandlerHolder=void 0;var Pa=Us(),ki=class{constructor(n){this._refs=[];try{this._finalizationRegistry=new FinalizationRegistry(n)}catch(e){throw e.name==="FinalizationRegistry"?new Pa.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(n,e){let t=new WeakRef(e);return this._finalizationRegistry.register(e,{eventSource:n,handlerRef:t},t),this._refs.push(t),t}releaseWeakHandler(n){let t=this._refs.find(r=>r?.deref()===n)||new WeakRef(n);return this._finalizationRegistry.unregister(t),t}unregisterRef(n){this._finalizationRegistry.unregister(n)}};yn.WeakHandlerHolder=ki});var Ns=le(bn=>{"use strict";Object.defineProperty(bn,"__esModule",{value:!0});bn.WeakEvent=void 0;var Li=(Je(),Ze(We)),Ca=Fi(),Aa=Bi(),ji=Ci(),Ra={swallowExceptions:!1,parallelize:!0},Mi=class{constructor(){this._handlers=[],this._handlerFinalizedEvent=new Ca.TypedEvent,this.handlerFinalizedEvent=this._handlerFinalizedEvent,this._refHolder=new Aa.WeakHandlerHolder(n=>{this.onHandlerFinalizer(n)})}invoke(n,e,t){for(let r of this._handlers){let s=r?.deref();if(s){let{succeeded:o,error:a}=(0,ji.eventHandlerSafeInvoke)(s,n,e);if(!o&&t?.swallowExceptions!==!0)throw a}else this.releaseHandler(r)}}invokeAsync(n,e,t=Ra){return(0,Li.__awaiter)(this,void 0,void 0,function*(){t?.parallelize===!1?yield this.sequentialInvokeAsync(n,e,t):yield this.parallelInvokeAsync(n,e,t)})}sequentialInvokeAsync(n,e,t){return(0,Li.__awaiter)(this,void 0,void 0,function*(){for(let r of this._handlers){let s=r?.deref();if(s){let{succeeded:o,error:a}=yield(0,ji.eventHandlerSafeInvokeAsync)(s,n,e);if(!o&&t.swallowExceptions!==!0)throw a}else this.releaseHandler(r)}})}parallelInvokeAsync(n,e,t){return(0,Li.__awaiter)(this,void 0,void 0,function*(){let r=[];for(let s of this._handlers){let o=s?.deref();o?r.push((0,ji.eventHandlerSafeInvokeAsync)(o,n,e).then(({succeeded:a,error:d})=>{if(!a&&t.swallowExceptions!==!0)throw d})):this.releaseHandler(s)}yield Promise.all(r)})}attach(n){this._handlers.push(this._refHolder.getWeakHandler(this,n))}detach(n){let e=this._refHolder.releaseWeakHandler(n);this.tryRemoveHandlerRef(e)}onHandlerFinalizer(n){this.tryRemoveHandlerRef(n?.handlerRef),this._handlerFinalizedEvent.invokeAsync(this,n,{swallowExceptions:!0})}tryRemoveHandlerRef(n){let e=this._handlers.findIndex(t=>t===n);e>=0&&this._handlers.splice(e,1)}releaseHandler(n){this._refHolder.unregisterRef(n),this.tryRemoveHandlerRef(n)}};bn.WeakEvent=Mi});var $s=le(wn=>{"use strict";Object.defineProperty(wn,"__esModule",{value:!0});var zs=(Je(),Ze(We));(0,zs.__exportStar)(Bi(),wn);(0,zs.__exportStar)(Ns(),wn)});var Ks=le(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});var Vi=(Je(),Ze(We));(0,Vi.__exportStar)(ks(),Tt);(0,Vi.__exportStar)(Fi(),Tt);(0,Vi.__exportStar)($s(),Tt)});var ir={};cr(ir,{Client:()=>pt,ClientDescriptor:()=>ei,Entity:()=>pe,EntityFile:()=>be,IdbPersistence:()=>mt,ServerSync:()=>ht,Storage:()=>pt,StorageDescriptor:()=>ei,UndoHistory:()=>gt,authorization:()=>fc,cliSync:()=>hc,createMigration:()=>hi,getEntityClient:()=>Qs,id:()=>pc,schema:()=>Ct});function wo(i){return typeof Buffer<"u"?Buffer.from(i).toString("base64"):btoa(i)}function vo(i){return typeof Buffer<"u"?Buffer.from(i,"base64").toString():atob(i)}var ze={onlyUser:i=>wo(`u:${i}:*`),onlyMe:()=>ze.onlyUser(ii),decode:i=>{let e=vo(i).split(":");if(e.length!==3)throw new Error("Invalid authz string");return{scope:e[0],subject:e[1],action:e[2]}}},ii="$$_originator_$$";function dr(i,n){let{operations:e,baselines:t}=i;if(e)for(let r of e)r.authz&&ze.decode(r.authz).subject===ii&&(r.authz=ze.onlyUser(n));if(t)for(let r of t)r.authz&&ze.decode(r.authz).subject===ii&&(r.authz=ze.onlyUser(n))}var et=class{constructor(n){this.flusher=n,this.batches=new Map,this.flush=e=>{let t=this.batches.get(e);if(t)return t.flush()},this.discard=e=>{let t=this.batches.get(e);t&&(t.discard(),this.batches.delete(e))},this.flushAll=()=>[...this.batches.values()].map(e=>e.flush()),this.getSize=e=>{let t=this.batches.get(e);return t?t.items.length:0}}add({key:n,userData:e,items:t,max:r,timeout:s}){let o=this.batches.get(n);return o||(o=new ri({max:r||null,startedAt:Date.now(),userData:e,timeout:s||null,flusher:this.flusher,key:n}),this.batches.set(n,o)),o.update({items:t,max:r,timeout:s,userData:e}),o}},ri=class{constructor({max:n,startedAt:e,timeout:t,userData:r,flusher:s,key:o}){this.items=[],this.update=({items:a,max:d,timeout:m,userData:h})=>{this.items.push(...a),d!==void 0&&(this.max=d),m!==void 0&&(this.timeout=m),h&&(this.userData=h);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 a=this.items;return this.items=[],this.flusher(a,this.key,this.userData)},this.discard=()=>{this.flushTimeout&&clearTimeout(this.flushTimeout),this.flushTimeout=void 0,this.items=[]},this.max=n,this.startedAt=e,this.timeout=t,this.userData=r,this.flusher=s,this.key=o}};var yt;(function(i){i[i.InvalidRequest=4e3]="InvalidRequest",i[i.BodyRequired=4001]="BodyRequired",i[i.NoToken=4010]="NoToken",i[i.InvalidToken=4011]="InvalidToken",i[i.TokenExpired=4012]="TokenExpired",i[i.Forbidden=4030]="Forbidden",i[i.NotFound=4040]="NotFound",i[i.Unexpected=5e3]="Unexpected",i[i.ConfigurationError=5010]="ConfigurationError",i[i.NoFileStorage=5011]="NoFileStorage",i[i.MigrationPathNotFound=7001]="MigrationPathNotFound",i[i.ImportFailed=7002]="ImportFailed",i[i.Offline=7003]="Offline"})(yt||(yt={}));var Q=class extends Error{constructor(n,e,t){super(t??`Verdant error: ${n}`,{cause:e}),this.code=n,this.toResponse=()=>JSON.stringify({code:this.code})}get httpStatus(){let n=Math.floor(this.code/10);return n<600?n:500}};Q.Code=yt;function ur(i){return typeof i=="object"&&"code"in i&&typeof i.code=="number"}var Ut,xo=new Uint8Array(16);function si(){if(!Ut&&(Ut=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!Ut))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Ut(xo)}var fr=/^(?:[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 So(i){return typeof i=="string"&&fr.test(i)}var hr=So;var te=[];for(Nt=0;Nt<256;++Nt)te.push((Nt+256).toString(16).substr(1));var Nt;function Oo(i){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=(te[i[n+0]]+te[i[n+1]]+te[i[n+2]]+te[i[n+3]]+"-"+te[i[n+4]]+te[i[n+5]]+"-"+te[i[n+6]]+te[i[n+7]]+"-"+te[i[n+8]]+te[i[n+9]]+"-"+te[i[n+10]]+te[i[n+11]]+te[i[n+12]]+te[i[n+13]]+te[i[n+14]]+te[i[n+15]]).toLowerCase();if(!hr(e))throw TypeError("Stringified UUID is invalid");return e}var pr=Oo;function Io(i,n,e){i=i||{};var t=i.random||(i.rng||si)();if(t[6]=t[6]&15|64,t[8]=t[8]&63|128,n){e=e||0;for(var r=0;r<16;++r)n[e+r]=t[r];return n}return pr(t)}var bt=Io;var br=Te(yr(),1);function _o(i,n){return typeof n!="object"||n===null||Array.isArray(n)?n:Object.fromEntries(Object.entries(n).sort(([e],[t])=>e<t?-1:e>t?1:0))}function oi(i){let n=new WeakMap,e=0;return JSON.stringify(i,(t,r)=>{if(typeof r=="object"&&r!==null){if(n.has(r))return{$ref:n.get(r)};n.set(r,`cyclic-ref:${e++}`)}return _o(t,r)})}function de(i,n=!0){if(!n&&typeof structuredClone=="function")return structuredClone(i);if(V(i)||Array.isArray(i)){let e=G(i),t;if(Array.isArray(i))t=i.map(r=>de(r,n));else{t={};for(let[r,s]of Object.entries(i))t[r]=de(s,n)}return n&&e&&z(t,e),t}return i}function $e(i){return(0,br.default)(i)}function V(i){return i&&typeof i=="object"}function wr(i){for(var n=[],e=[i],t=0;e.length;){var r=e.pop();if(typeof r=="boolean")t+=4;else if(typeof r=="string")t+=r.length*2;else if(typeof r=="number")t+=8;else if(typeof r=="object"&&n.indexOf(r)===-1){n.push(r);for(var s in r)e.push(r[s])}}return t}function L(i,n="assertion failed"){if(!i)throw new Error(n)}function wt(i=16){return bt().replace("-","").slice(0,i)}function vr(i,n){for(let e=i.length-1;e>=0;e--)if(n(i[e]))return e;return-1}function xr(i,n){let e;return function(...t){let r=this;clearTimeout(e),e=setTimeout(()=>i.apply(r,t),n)}}function Sr(i,n){let e=0,t;return function(...r){let s=this,o=Date.now();o-e>=n?(e=o,i.apply(s,r),clearTimeout(t)):(clearTimeout(t),t=setTimeout(()=>{e=o,i.apply(s,r)},n))}}function Or(){}function he(i){return i&&i["@@type"]==="file"}function vt(i){return{"@@type":"file",id:i}}function tt(i){return typeof File<"u"&&i instanceof File||typeof Blob<"u"&&i instanceof Blob}function zt(i){return i&&V(i)&&typeof i.id=="string"&&typeof i.remote=="boolean"&&typeof i.name=="string"&&typeof i.type=="string"}function $(i){return re(i)||he(i)}function De(i,n){return i===n?!0:!(!$(i)||!$(n)||i["@@type"]!==n["@@type"]||i.id!==n.id)}function re(i){return i&&typeof i=="object"&&i["@@type"]==="ref"}function Ke(i,n,e,t,r=[],s){z(i,n),nt(i,t);let o=Ht(i);for(let a of o.keys()){let d=o.get(a),m={oid:a,timestamp:e(),data:{op:"initialize",value:qt(d)}};r.push(Er(m,s?.authz))}return r}function _r(i,n,e,t=[],r){let s={oid:n,timestamp:e(),data:{op:"initialize",value:i}};return t.push(Er(s,r?.authz)),t}function Er(i,n){return n&&(i.authz=n),i}function xt(i){let n={};for(let e of i)e.oid in n?n[e.oid].push(e):n[e.oid]=[e];return n}function Dr(i){let n={};for(let e of i){let t=K(e.oid);t in n?n[t].push(e):n[t]=[e]}return n}function Pr(i){let n={};for(let e of i){let t=K(e.oid);t in n?n[t].push(e):n[t]=[e]}return n}function ke(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: ${G(i)})`),!1)}function Be(i,n,e){if(i==null&&n.op!=="initialize")return i;let t=i,r,s;function o(a){e&&$(a)&&e.push(a)}switch(n.op){case"set":o(t[n.name]),t[n.name]=n.value;break;case"remove":o(t[n.name]),delete t[n.name];break;case"list-set":ke(i)&&(o(i[n.index]),i[n.index]=n.value);break;case"list-push":ke(i)&&i.push(n.value);break;case"list-delete":ke(i)&&(o(i[n.index]),i.splice(n.index,n.count));break;case"list-move-by-index":ke(i)&&(s=i.splice(n.from,1),i.splice(n.to,0,s[0]));break;case"list-remove":if(ke(i))do{let a=n.value;n.only==="last"?$(a)?r=vr(i,d=>$(d)&&De(d,a)):r=i.lastIndexOf(a):$(a)?r=i.findIndex(d=>$(d)&&De(d,a)):r=i.indexOf(a),r!==-1&&(o(i[r]),i.splice(r,1))}while(!n.only&&r!==-1);break;case"list-add":ke(i)&&(i.some(d=>re(d)&&re(n.value)?d.id===n.value.id:d===n.value)||i.push(n.value));break;case"list-move-by-ref":ke(i)&&(r=i.findIndex(a=>De(a,n.value)),s=i.splice(r,1),i.splice(n.index,0,s[0]));break;case"list-insert":if(ke(i)){if(!n.value&&!n.values)throw new Error(`Cannot apply list insert patch; expected value or values, received ${JSON.stringify(n)}`);n.value?i.splice(n.index,0,n.value):i.splice(n.index,0,...n.values)}break;case"delete":Array.isArray(i)?i.forEach(o):V(i)&&Object.values(i||{}).forEach(o);return;case"initialize":return de(n.value);case"touch":return i;default:throw new Error(`Unsupported patch operation: ${n.op}`)}return i}function $t(i,n,e=[]){if(Array.isArray(i))for(let t=0;t<i.length;t++){let r=i[t];i[t]=Ir(r,n,e),V(i[t])&&$t(i[t],n,e)}else if(!he(i)){if(V(i)){L(G(i),`Object ${JSON.stringify(i)} must have an oid`);for(let t of Object.keys(i))i[t]=Ir(i[t],n,e),V(i[t])&&$t(i[t],n,e)}}return e}function Ir(i,n,e){if(re(i)){e.push(i.id);let t=n.get(i.id);return L(!!t,`No value was found in object map for ${i.id}`),z(t,i.id)}else return i}function Cr(i){return i.data.op==="set"?i.data.name:!1}function Ar(i,n){return n.has(!0)?!0:i.data.op==="set"||i.data.op==="remove"?n.has(i.data.name):!1}function Kt(i){return{oid:i.oid,timestamp:i.timestamp,data:i.data,authz:i.authz}}var Eo="/",St=":",ci=new WeakMap;function se(i){let n=G(i);return L(!!n,`Object ${JSON.stringify(i)} does not have an OID assigned to it`),n}function G(i){if(V(i))return ci.get(i)}function z(i,n){return L(V(i),`Only objects can be assigned OIDs, received ${JSON.stringify(i)}`),kr(i)&&qt(i),ci.set(i,n),i}function kr(i){return!!G(i)}function qt(i){return ci.delete(i),i}function Rr(i,n,e){if(kr(i)){let t=se(i);if(Le(t,n))return se(i);{let r=Pe(n,e);return z(i,r),r}}else{let t=Pe(n,e);return z(i,t),t}}var ai={".":"&dot;","/":"&slash;",":":"&colon;"};function Fr(i){return i.replace(/[/]/g,ai["/"]).replace(/[:]/g,ai[":"]).replace(/[.]/g,ai["."])}function Tr(i){return i.replace(/&slash;/g,"/").replace(/&colon;/g,":").replace(/&dot;/g,".")}function ee(i,n,e){let t=Fr(i)+Eo+Fr(n);return e&&(t+=St+e),t}function Pe(i,n=Do){let{collection:e,id:t}=ue(i);return ee(e,t,n())}function ue(i){let[n,e,...t]=i.split("/");t.length&&(console.error(`OID ${i} has more than 3 segments. Attempting to parse it anyway.`),e+="/"+t.join("/"));let[r,s]=e.split(St),o;return r.includes(".")?o=r.slice(0,r.indexOf(".")):o=r,{collection:Tr(n),id:Tr(o),subId:s}}function nt(i,n){let e=se(i);if(Array.isArray(i)){let t;for(let r=0;r<i.length;r++)t=i[r],V(t)&&!$(t)&&(Rr(t,e,n),nt(t,n))}else if(V(i)&&!$(i))for(let t of Object.keys(i))V(i[t])&&!$(i[t])&&(Rr(i[t],e,n),nt(i[t],n))}function Qt(i){if(qt(i),Array.isArray(i))for(let n=0;n<i.length;n++)Qt(i[n]);else if(V(i))for(let n of Object.keys(i))Qt(i[n])}function Do(){return bt().slice(0,8)}function ie(i){return{"@@type":"ref",id:i}}function Ht(i,n=new Map){if(Array.isArray(i)){let e=se(i),t=z([],e);for(let r=0;r<i.length;r++){let s=i[r];if(V(s)){if(re(s))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(he(s)){t[r]=s;continue}else{let o=se(s);t[r]=ie(o),Ht(s,n)}}else t[r]=s}n.set(e,t)}else if(V(i)&&!$(i)){let e=se(i),t=z({},e);for(let r of Object.keys(i)){let s=i[r];if(V(s)){if(re(s))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(he(s))t[r]=s;else{let o=se(s);t[r]=ie(o),Ht(s,n)}}else t[r]=s}n.set(e,t)}else $(i);return n}function K(i){return i.split(".")[0].split(St)[0]}function Br(i){let n=K(i),e=Pe(n,()=>"\uFFFF");return[`${n}${St}`,e]}function Le(i,n){return K(i)===K(n)}function Wt(i){return!i.includes(St)}var it="__@@oid_do_not_use",Ce="@@id";function Po(i){if(V(i))return i[Ce]||i[it]}function Co(i){return V(i)&&(delete i[it],delete i[Ce]),i}function Ao(i){let n=Po(i);n&&z(i,n)}function Ot(i){if(Ao(i),Co(i),Array.isArray(i))for(let n=0;n<i.length;n++)Ot(i[n]);else if(V(i))for(let n of Object.keys(i))Ot(i[n])}function Ro(i){let{collection:n,id:e,subId:t}=ue(i);return ee(n,e,t)}var Fo=/"\w+\/[^"]+?(\.[^"]+)+\:[\S]+?"/g;function To(i){return i.replaceAll(Fo,n=>{let e=n.slice(1,n.length-1);return`"${Ro(e)}"`})}function li(i){return JSON.parse(To(JSON.stringify(i)))}function Lr(i){let n=K(i);return[`${n}.`,`${n}.\uFFFF`]}function di(i){return i===Ce||i===it}var je=class{constructor(n,e){this.getNow=n,this.createSubId=e,this.isPrimitive=t=>!V(t)||$(t),this.createDiff=(t,r,s={})=>Jt(t,r,this.getNow,this.createSubId,[],s),this.createInitialize=(t,r,s,o)=>o?_r(t,r,this.getNow,void 0,s?{authz:s}:void 0):Ke(t,r,this.getNow,this.createSubId,void 0,s?{authz:s}:void 0),this.createSet=(t,r,s,o)=>{if(this.isPrimitive(s))return[{oid:t,timestamp:this.getNow(),data:{op:"set",name:r,value:s},authz:o}];{let a=Pe(t,this.createSubId);return[...Ke(s,a,this.getNow,this.createSubId,void 0,{authz:o}),{oid:t,timestamp:this.getNow(),data:{op:"set",value:ie(a),name:r},authz:o}]}},this.createRemove=(t,r,s)=>[{oid:t,timestamp:this.getNow(),data:{op:"remove",name:r},authz:s}],this.createListSet=(t,r,s,o)=>{if(L(r>=0,"List index must be non-negative"),this.isPrimitive(s))return[{oid:t,timestamp:this.getNow(),data:{op:"list-set",index:r,value:s},authz:o}];{let a=Pe(t,this.createSubId);return[...Ke(s,a,this.getNow,this.createSubId,void 0,{authz:o}),{oid:t,timestamp:this.getNow(),data:{op:"list-set",index:r,value:ie(a)},authz:o}]}},this.createListPush=(t,r,s)=>{if(this.isPrimitive(r))return[{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:r},authz:s}];{let o=Pe(t,this.createSubId);return[...Ke(r,o,this.getNow,void 0,void 0,{authz:s}),{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:ie(o)},authz:s}]}},this.createListAdd=(t,r,s)=>this.isPrimitive(r)?[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:r},authz:s}]:[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:ie(r)},authz:s}],this.createListInsert=(t,r,s,o)=>{if(L(r>=0,"List index must be non-negative"),this.isPrimitive(s))return[{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:s,index:r},authz:o}];{let a=Pe(t,this.createSubId);return[...Ke(s,a,this.getNow,this.createSubId,void 0,o?{authz:o}:void 0),{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:ie(a),index:r},authz:o}]}},this.createListInsertMany=(t,r,s,o)=>{L(r>=0,"List index must be non-negative");let a=[],d=s.map(m=>{if(this.isPrimitive(m))return m;let h=Pe(t,this.createSubId);return a.push(...Ke(m,h,this.getNow,this.createSubId,void 0,{authz:o})),ie(h)});return a.push({oid:t,timestamp:this.getNow(),data:{op:"list-insert",values:d,index:r},authz:o}),a},this.createListRemove=(t,r,s,o)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-remove",value:r,only:s},authz:o}],this.createListDelete=(t,r,s=1,o)=>(L(r>=0,"List index must be non-negative"),L(s>0,"Count must be positive and non-zero"),[{oid:t,timestamp:this.getNow(),data:{op:"list-delete",index:r,count:s},authz:o}]),this.createListMoveByRef=(t,r,s,o)=>(L(s>=0,"List index must be non-negative"),[{oid:t,timestamp:this.getNow(),data:{op:"list-move-by-ref",value:r,index:s},authz:o}]),this.createListMoveByIndex=(t,r,s,o)=>(L(r>=0,"List move from index must be non-negative"),L(s>=0,"List move to index must be non-negative"),[{oid:t,timestamp:this.getNow(),data:{op:"list-move-by-index",from:r,to:s},authz:o}]),this.createDelete=(t,r)=>[{oid:t,timestamp:this.getNow(),data:{op:"delete"},authz:r}],this.createDeleteAll=(t,r)=>t.map(s=>({oid:s,timestamp:this.getNow(),data:{op:"delete"},authz:r}))}};function rt(i,n){if(i===n)return!0;if($(i)&&$(n))return De(i,n);let e=G(i),t=G(n);return!!(e&&t&&e===t)}function jr(i,n,e,t){if(!It(n))return n;let r=G(n);if(!r)t.mergeUnknownObjects&&e&&z(n,e);else if(!Le(i,r))return de(n,!1);return n}function It(i){return V(i)&&!$(i)}function Jt(i,n,e,t,r,s){var o;let a={patches:[],mergeUnknownObjects:s?.mergeUnknownObjects,merge:(o=s?.merge)!==null&&o!==void 0?o:s?.defaultUndefined,authz:s?.authz,patchCreator:new je(e,t)};return Gt(i,n,a),a.patches}function Gt(i,n,e){if(Array.isArray(i)&&Array.isArray(n))ko(i,n,e);else{if(Array.isArray(i)||Array.isArray(n))throw new Q(Q.Code.Unexpected,void 0,"Cannot diff between array and non-array");It(i)&&It(n)&&Bo(i,n,e)}}function ko(i,n,e){let t=se(i),r=[],s=new Set;for(let h=0;h<i.length;h++){let O=i[h];r[h]=O;let w=G(O);w&&s.add(w)}for(let h=0;h<n.length;h++){let O=n[h],w=i[h];n[h]=jr(t,O,G(w),e)}let o=!0,a=new Set,d=new Set;for(let h=0;h<n.length;h++){let O=n[h],w=r[h];O===void 0&&(o=!1);let C=G(O),y=o&&h>=r.length;if(C&&s.has(C))if(rt(O,w))Gt(w,O,e);else{e.patches.push(...e.patchCreator.createListMoveByRef(t,ie(C),h,e.authz));let I=G(w);I&&d.add(I),a.add(C)}else if(y)e.patches.push(...e.patchCreator.createListPush(t,O,e.authz));else if(rt(O,w))Gt(w,O,e);else{let I=h===0||rt(n[h-1],r[h-1]),E=h===n.length-1||rt(n[h+1],r[h]);I&&E?(e.patches.push(...e.patchCreator.createListInsert(t,h,O,e.authz)),r.splice(h,0,void 0)):e.patches.push(...e.patchCreator.createListSet(t,h,O,e.authz))}}if(r.length-n.length>0)for(let h=r.length-1;h>=n.length;h--){let O=r[h],w=G(O);w?a.has(w)||(st(O,e),e.patches.push(...e.patchCreator.createListRemove(t,ie(w),"last",e.authz))):e.patches.push(...e.patchCreator.createListRemove(t,O,"last",e.authz))}for(let h of d){if(a.has(h))continue;let O=i.find(w=>G(w)===h);O&&st(O,e),e.patches.push(...e.patchCreator.createListRemove(t,ie(h),"last",e.authz))}}function Bo(i,n,e){let t=new Set(Object.keys(i)),r=se(i);for(let s in n){let o=n[s];if(o===void 0&&e.merge||(t.delete(s),di(s)))continue;let a=i[s];It(o)?(jr(r,o,G(a),e),a?rt(o,a)?Gt(a,o,e):(e.patches.push(...e.patchCreator.createSet(r,s,o,e.authz)),st(a,e)):e.patches.push(...e.patchCreator.createSet(r,s,o,e.authz))):rt(o,a)||(o===void 0?e.patches.push(...e.patchCreator.createRemove(r,s,e.authz)):e.patches.push(...e.patchCreator.createSet(r,s,o,e.authz)),st(a,e))}if(!e.merge)for(let s of t)di(s)||(e.patches.push(...e.patchCreator.createRemove(r,s,e.authz)),st(i[s],e))}function st(i,n){if(!It(i))return;let e=G(i);if(e){n.patches.push(...n.patchCreator.createDelete(e,n.authz));for(let t in i){let r=i[t];st(r,n)}}}var N=class{constructor(n){this._onAllUnsubscribed=n,this.subscribers={},this.counts={},this._disabled=!1,this.disposed=!1,this.subscriberCount=e=>{var t;return(t=this.counts[e])!==null&&t!==void 0?t:0},this.totalSubscriberCount=()=>Object.values(this.counts).reduce((e,t)=>e+t,0),this.subscribe=(e,t)=>{let r=wt(),s=this.subscribers[e];return s||(s=this.subscribers[e]={}),s[r]=t,this.counts[e]=(this.counts[e]||0)+1,()=>{this.subscribers[e]&&(delete this.subscribers[e][r],this.counts[e]--,this.counts[e]===0&&(delete this.subscribers[e],delete this.counts[e],this._onAllUnsubscribed&&this._onAllUnsubscribed(e)))}},this.emit=(e,...t)=>{this._disabled||this.subscribers[e]&&Object.values(this.subscribers[e]).forEach(r=>r(...t))},this.dispose=()=>{this._disabled=!0,this.disposed=!0;let e=Object.keys(this.subscribers);this.subscribers={},this.counts={},e.forEach(t=>{this._onAllUnsubscribed&&this._onAllUnsubscribed(t)})},this.disable=()=>{this._disabled=!0}}get disabled(){return this._disabled}};var Yt="\uFFFFFE",Lo="\0",jo="\uFFFFFF";function ge(...i){let n=Mo(i);return n.length===1?n[0]:n}function Ae(...i){return i.join(Yt)+`${jo}`}function Oe(...i){return i.join(Yt)+`${Yt}${Lo}`}function Mo(i){let n=[[]];for(let e of i)if(Array.isArray(e)){let t=[];for(let r of n)for(let s of e)t.push(r.concat(s));n=t}else for(let t of n)t.push(`${e}`);return Array.from(new Set(n.map(e=>e.join(Yt))))}function Mr(i){return!!i.field}function Vo(i,n){let e={};for(let[t,r]of Object.entries(i.indexes||{})){let s=r;Mr(s)?e[t]=Se(n[s.field]):e[t]=Se(s.compute(n))}return e}function Uo(i,n){return Object.entries(i.compounds||{}).reduce((e,[t,r])=>(e[t]=ge(...r.of.map(s=>n[s])),e),{})}function No(i,n){return Object.entries(i.fields).reduce((e,[t,r])=>("indexed"in r&&(e[t]=Se(n[t])),e),{})}function ui(i,n){let e=Object.assign(Object.assign({[i.primaryKey]:n[i.primaryKey]},No(i,n)),Vo(i,n));return Object.assign(e,Uo(i,Object.assign(Object.assign({},n),e))),e}var zo="null";function Se(i){if(i===null)return zo;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(Se);throw new Error(`Unsupported index value: ${i}`)}function Vr(i,n){let e,t;return(...r)=>{let s=n();return e&&e.length===s.length&&e.every((o,a)=>o===s[a])||(e=[...s],t=i(...r)),t}}var $o={version:0,collections:{}};function Ur(i){return i?[...Object.keys(i.indexes||{}).map(n=>{let e=i.indexes[n],t=e.type;!t&&e.field&&(t=i.fields[e.field].type),L(t,`Could not determine type of index ${i}.${n}. Index must have a type. Perhaps your schema is malformed?`);let r=_t(i,n);return{name:n,multiEntry:r,synthetic:!0,compound:!1,type:t?.replace("[]","")}}),...Object.keys(i.compounds||{}).map(n=>({name:n,multiEntry:_t(i,n),synthetic:!1,compound:!0,type:"string"}))]:[]}function hi(i,n,e){let t=typeof n=="function"||n===void 0,r=t?$o:i,s=t?i:n,o=t?n:e;L(r,"Invalid arguments to createMigration"),L(s,"Invalid arguments to createMigration");let{changedCollections:a,addedCollections:d,removedCollections:m,addedIndexes:h,removedIndexes:O,autoMigratedCollections:w,autoMigration:C}=Ko(r,s);return{version:s.version,migrate:async y=>{let I=[];if(await o?.({migrate:async(_,D)=>{let k=C(_),b=async S=>{let u=await D(S);z(u,se(S));let p=k(u),l=zr(s.collections[_].fields,p);return p};await y.migrate(_,b),I.push(_),w.delete(_)},info:{changedCollections:a,addedCollections:d,removedCollections:m},queries:y.queries,mutations:y.mutations}),s.version>1){y.log("debug","auto-migrating collections with new defaults",w);for(let D of w)await y.migrate(D,C(D)),I.push(D);for(let D of m)await y.deleteCollection(D);let _=a.filter(D=>!I.includes(D));_.length>0&&y.log("error",`Unmigrated changed collections from version ${r.version} to version ${s.version}:`,_)}},removedCollections:m,addedIndexes:h,removedIndexes:O,allCollections:Object.keys(s.collections),changedCollections:a,addedCollections:d,oldCollections:Object.keys(r.collections),oldSchema:r,newSchema:s}}function Ko(i,n){let e=Object.keys(n.collections).filter(h=>i.collections[h]&&oi(i.collections[h])!==oi(n.collections[h])),t=Object.keys(i.collections).filter(h=>!n.collections[h]),r=Object.keys(n.collections).filter(h=>!i.collections[h]),s=new Set;for(let h of e){let O=i.collections[h].fields,w=n.collections[h].fields;Object.keys(w).some(C=>(!O[C]||fi(O[C]))&&!fi(w[C]))&&s.add(h),Object.keys(O).some(C=>!w[C])&&s.add(h)}let o={},a={};for(let h of[...e,...r]){let O=Ur(i.collections[h]),w=Ur(n.collections[h]),C=w.filter(I=>!O.find(E=>E.name===I.name)),y=O.filter(I=>!w.find(E=>E.name===I.name));C.length>0&&(o[h]=C,e.includes(h)&&s.add(h)),y.length>0&&(a[h]=y,e.includes(h)&&s.add(h))}return{changedCollections:e,addedCollections:r,removedCollections:t,addedIndexes:o,removedIndexes:a,autoMigratedCollections:s,withDefaults:(h,O)=>qe(n.collections[h],O),autoMigration:h=>O=>{let w=n.collections[h];return qe(w,Nr(w,O))}}}var pi={};var Me;(function(i){i[i.Realtime=0]="Realtime",i[i.Push=1]="Push",i[i.PassiveRealtime=2]="PassiveRealtime",i[i.PassivePush=3]="PassivePush",i[i.ReadOnlyPull=4]="ReadOnlyPull",i[i.ReadOnlyRealtime=5]="ReadOnlyRealtime"})(Me||(Me={}));var es=Te(He(),1),Yo=function(i,n){var e={};for(var t in i)Object.prototype.hasOwnProperty.call(i,t)&&n.indexOf(t)<0&&(e[t]=i[t]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,t=Object.getOwnPropertySymbols(i);r<t.length;r++)n.indexOf(t[r])<0&&Object.prototype.propertyIsEnumerable.call(i,t[r])&&(e[t[r]]=i[t[r]]);return e};function Xo(i){let{properties:n,fields:e}=i,t=Yo(i,["properties","fields"]),r=n||e;if(!r)throw new Error("objectField must be passed a properties object");return Object.assign(Object.assign({type:"object"},t),{properties:r})}function Zo(i,n){return i.properties=n,i}function ea(i){return Object.assign({type:"array"},i)}function ta(i,n){return i.items=n,i}var na=i=>Object.assign({type:"string"},i),ia=i=>Object.assign({type:"number"},i),ra=i=>Object.assign({type:"boolean"},i),sa=i=>Object.assign({type:"any"},i);function oa(i){return Object.assign({type:"map"},i)}function aa(i,n){return i.values=n,i}var ca=i=>Object.assign({type:"file"},i),la=()=>({type:"string",default:es.default}),ts={object:Xo,array:ea,replaceObjectFields:Zo,replaceArrayItems:ta,string:na,number:ia,boolean:ra,any:sa,map:oa,replaceMapValues:aa,file:ca,id:la};var rs=Te(He(),1);function en(i){return i.equals!==void 0}function tn(i){return i.gte!==void 0||i.lte!==void 0||i.gt!==void 0||i.lt!==void 0}function ns(i){return!!i.match}function nn(i){return i.startsWith!==void 0}function vi(i){return!tn(i)&&!en(i)&&!ns(i)&&!nn(i)&&i.order}function _t(i,n){var e,t;let r=(e=i.compounds)===null||e===void 0?void 0:e[n];if(r)return r.of.some(a=>_t(i,a));let s=(t=i.indexes)===null||t===void 0?void 0:t[n];if(s){if("type"in s)return wi(s.type);if("field"in s){let a=i.fields[s.field];return a?wi(a.type):!1}}let o=i.fields[n];return o?wi(o.type):!1}function wi(i){return i==="array"||i.endsWith("[]")}function Ie(i){return i.type==="any"?!0:i.type==="map"?!1:i.nullable}function Pt(i){return i?i.type==="map"||i.type==="array"?!0:i.type==="file"?!1:i.default!==void 0:!1}function fi(i){return!Ie(i)&&!Pt(i)}function qe(i,n){for(let[e,t]of Object.entries(i.fields)){let r=ot(t);(r!==void 0&&n[e]===void 0||!Ie(t)&&n[e]===null)&&(n[e]=r),n[e]&&Qe(n[e],t)}return n}function Qe(i,n){if(i==null)return i;if(n.type==="object")for(let[e,t]of Object.entries(n.properties)){if(i[e]===void 0){let r=ot(t);r!==void 0&&(i[e]=r)}Qe(i[e],t)}else if(n.type==="array")for(let e of i)Qe(e,n.items);else if(n.type==="map")for(let[e,t]of Object.entries(i))e===Ce||e===it||Qe(t,n.values)}function ot(i){if("default"in i){let n=typeof i.default=="function"?i.default():i.default;if(n===null)return n;let e=structuredClone(n);if(i.type==="object")for(let[t,r]of Object.entries(i.properties))e[t]===void 0&&(e[t]=ot(r));return e}if(Ie(i))return null;if(i.type==="array")return[];if(i.type==="map")return{}}function Nr(i,n){for(let[e,t]of Object.entries(n))e===Ce||e===it||(i.fields[e]?xi(t,i.fields[e]):delete n[e]);return n}function xi(i,n){if(V(i)&&n.type==="object")for(let[e,t]of Object.entries(i))n.properties[e]?xi(t,n.properties[e]):delete i[e];else if(Array.isArray(i)&&n.type==="array")for(let e of i)xi(e,n.items)}function zr(i,n){for(let[e,t]of Object.entries(n))if(e!==Ce){if(!i[e])return{type:"invalid-key",fieldPath:[e],message:`Invalid field "${e}"`};if(t){let r=Re({field:i[e],value:t,fieldPath:[e]});if(r)return r}}}function Re({field:i,value:n,fieldPath:e=[],depth:t,requireDefaults:r,expectRefs:s,hasPassedFirstLevel:o}){let a=s&&o;if(!(t!==void 0&&t<=0)&&!(Ie(i)&&n==null)){if(n==null&&(r||!Pt(i)))return{type:"no-default",fieldPath:e,message:`Invalid null value for field ${fe(e)}`};if(i.type==="object")if(a){if(!re(n))return{type:"invalid-type",fieldPath:e,message:`Expected ref for field ${fe(e)}, got ${ye(n)}`}}else{if(!V(n))return{type:"invalid-type",fieldPath:e,message:`Expected object ${i.nullable?"or null ":""}for field ${fe(e)}, got ${ye(n)}`};for(let[d,m]of Object.entries(i.properties)){if(d===Ce)continue;let h=Re({field:m,value:n[d],fieldPath:[...e,d],depth:t!==void 0?t-1:void 0,expectRefs:s,hasPassedFirstLevel:!0});if(h)return h}for(let d of Object.keys(n))if(!i.properties[d])return{type:"invalid-key",fieldPath:[...e,d],message:`Invalid unexpected field "${d}" on value ${fe(e)}`}}else if(i.type==="array")if(a){if(!re(n))return{type:"invalid-type",fieldPath:e,message:`Expected ref for field ${fe(e)}, got ${ye(n)}`}}else{if(!Array.isArray(n))return n===null&&i.nullable?void 0:{type:"invalid-value",fieldPath:e,message:`Expected array ${i.nullable?"or null ":""}for field ${fe(e)}, got ${ye(n)}`};for(let d of n){let m=Re({field:i.items,value:d,fieldPath:[...e,"[]"],depth:t!==void 0?t-1:void 0,expectRefs:s,hasPassedFirstLevel:!0});if(m)return m}}else if(i.type==="map")if(a){if(!re(n))return{type:"invalid-type",fieldPath:e,message:`Expected ref for field ${fe(e)}, got ${ye(n)}`}}else{if(!V(n))return{type:"invalid-type",fieldPath:e,message:`Expected map for field ${fe(e)}, got ${ye(n)}`};for(let[d,m]of Object.entries(n)){let h=Re({field:i.values,value:m,fieldPath:[...e,d],depth:t!==void 0?t-1:void 0,expectRefs:s,hasPassedFirstLevel:!0});if(h)return h}}else if(i.type==="string"){if(typeof n!="string")return{type:"invalid-type",fieldPath:e,message:`Expected string ${i.nullable?"or null ":""}for field ${fe(e)}, got ${ye(n)}`};if(i.options&&!i.options.includes(n))return{type:"invalid-value",fieldPath:e,message:`Expected one of ${i.options.join(", ")} for field ${fe(e)}, got ${ye(n)}`}}else if(i.type==="boolean"){if(typeof n!="boolean")return{type:"invalid-type",fieldPath:e,message:`Expected boolean ${i.nullable?"or null ":""}for field ${fe(e)}, got ${ye(n)}`}}else if(i.type==="number"){if(typeof n!="number")return{type:"invalid-type",fieldPath:e,message:`Expected number ${i.nullable?"or null ":""}for field ${fe(e)}, got ${ye(n)}`}}else if(i.type==="file"){if(a){if(!he(n))return{type:"invalid-type",fieldPath:e,message:`Expected file ref for field ${fe(e)}, got ${ye(n)}`}}else if(!tt(n)&&!zt(n))return{type:"invalid-type",fieldPath:e,message:`Expected file ${i.nullable?"or null ":""}for field ${fe(e)}, got ${ye(n)}`}}}}function ye(i){try{return JSON.stringify(i)}catch{return String(i)}}function fe(i){return i.length===0?"root":i.join(".")}function is(i,n){let e={};for(let[t,r]of Object.entries(n))i[t]&&(e[t]=rn({field:i[t],value:r,fieldPath:[t]}));return e}function rn({field:i,value:n,fieldPath:e=[],depth:t}){let r=Re({field:i,value:n,fieldPath:e,depth:t,requireDefaults:!0});if(r)throw new Error(`Validation error: ${r.message}`);if(i.type==="object"){if(!V(n))return n;let s={};for(let[o,a]of Object.entries(i.properties))s[o]=rn({field:a,value:n[o],fieldPath:[...e,o],depth:t!==void 0?t-1:void 0});return s}else{if(i.type==="array")return Array.isArray(n)?n.map(s=>rn({field:i.items,value:s,fieldPath:[...e,"[]"],depth:t!==void 0?t-1:void 0})):n;if(i.type==="map"){if(!V(n))return n;let s={};for(let[o,a]of Object.entries(n))s[o]=rn({field:i.values,value:a,fieldPath:[...e,o],depth:t!==void 0?t-1:void 0});return s}else return n}}function Ve(i,n){var e;return i.type==="object"?i.properties[n]:i.type==="array"?i.items:i.type==="map"?i.values:i.type==="any"?i:"type"in i?null:(e=i[n])!==null&&e!==void 0?e:null}var da=function(i,n){var e={};for(var t in i)Object.prototype.hasOwnProperty.call(i,t)&&n.indexOf(t)<0&&(e[t]=i[t]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,t=Object.getOwnPropertySymbols(i);r<t.length;r++)n.indexOf(t[r])<0&&Object.prototype.propertyIsEnumerable.call(i,t[r])&&(e[t[r]]=i[t[r]]);return e};function ua(i){var{synthetics:n,indexes:e}=i,t=da(i,["synthetics","indexes"]);let r=Object.assign(Object.assign({},n),e);for(let[s,o]of Object.entries(t.fields))"indexed"in o&&(r[s]={field:s});return Object.assign(Object.assign({},t),{indexes:r})}function Ct(i){return i}Ct.collection=ua;Ct.fields=ts;Ct.generated={id:rs.default};var cs=Te(He(),1),dn=4,Rt=36;function ss(i){return i.toString(Rt).padStart(dn,"0")}function fa(i){return i.toString().padStart(6,"0")}var sn=class{constructor(){this.latest={time:Date.now(),counter:0,node:ha()},this.zeroCounter=0,this.now=n=>(this.latest=as(this.latest),this.get(n,this.latest)),this.OLD_now=n=>(this.latest=as(this.latest),fa(n)+ma(this.latest)),this.timerState=()=>this.latest,this.update=n=>{let e=n.slice(dn);this.latest=pa(this.latest,ls(e))},this.get=(n,e)=>ss(n)+os(e),this.zero=n=>ss(n)+os({time:0,counter:this.zeroCounter++,node:this.latest.node}),this.getWallClockTime=_i}},on=class extends Error{constructor(...n){super(),this.type="ClockDriftError",this.message=["maximum clock drift exceeded"].concat(n).join(" ")}},an=class extends Error{constructor(){super(),this.type="OverflowError",this.message="timestamp counter overflow"}},Si=4,Oi=7,cn=60*1e3,At=9;function ha(){return cs.default.slug().padStart(Oi,"0").slice(0,Oi)}function os(i){let n=new Date(i.time).getTime().toString(Rt).padStart(At,"0"),e=i.counter.toString(Rt).padStart(Si,"0"),t=i.node.padStart(Oi,"0");return`${n}${e}${t}`}function as(i){let n=Date.now(),e=Math.max(i.time,n),t=i.time===e?i.counter+1:0;if(e-n>cn)throw new on(e,n,cn);if(t>65535)throw new an;return{time:e,counter:t,node:i.node}}function pa(i,n){let e=Date.now(),t=Math.max(e,Math.max(i.time,n.time)),r=Math.max(i.counter,n.counter),s;if(i.time===t&&n.time===t?s=r+1:i.time===t?s=i.counter+1:n.time===t?s=n.counter+1:s=0,t-e>cn)throw new on(t,e,cn);if(s>65535)throw new an;return{time:t,counter:s,node:i.node}}function ls(i){let n=i.slice(0,At),e=i.slice(At,At+Si),t=i.slice(At+Si),r=parseInt(n,Rt),s=parseInt(e,Rt);if(isNaN(r)||isNaN(s))throw new Error("invalid clock format");return{time:r,counter:s,node:t}}function ma(i){let n=new Date(i.time).toISOString(),e=i.counter.toString(16).toUpperCase().padStart(4,"0"),t=i.node.padStart(16,"0");return`${n}-${e}-${t}`}function ln(i){return parseInt(i.slice(0,dn),36)}function Ii(i,n){return ln(i)-ln(n)}function _i(i){return ls(i.slice(dn)).time}function ds(i,n,e,t,r,s){let o=new je(t,r);if(n==null)return[{oid:i,timestamp:t(),data:{op:"delete"},authz:s}];let a=de(n),d=[];for(let m of e){let h=ga(i,a,m,o,s);d.unshift(...h),Be(a,m.data)}return d}function ga(i,n,e,t,r){var s,o;let a=e.data;switch(a.op){case"set":return n[a.name]===void 0?t.createRemove(i,a.name,r):t.createSet(i,a.name,n[a.name],r);case"remove":return n[a.name]===void 0?[]:t.createSet(i,a.name,n[a.name],r);case"list-insert":return a.value===void 0&&((s=a.values)===null||s===void 0?void 0:s.length)===0?[]:t.createListDelete(i,a.index,a.value?1:((o=a.values)===null||o===void 0?void 0:o.length)||0,r);case"list-delete":return t.createListInsertMany(i,a.index,n.slice(a.index,a.index+a.count),r);case"list-move-by-ref":return t.createListMoveByRef(i,a.value,Ft(n,a.value),r);case"list-move-by-index":return t.createListMoveByIndex(i,a.to,a.from,r);case"delete":return t.createInitialize(n,i,r,!0);case"list-push":return t.createListRemove(i,a.value,"last",r);case"list-remove":if(a.only==="last"){let d=Ft(n,a.value,0,"backward");return d===-1?[]:t.createListInsert(i,d,a.value,r)}else if(a.only==="first"){let d=Ft(n,a.value);return d===-1?[]:t.createListInsert(i,d,a.value,r)}else{let d=[],m=Ft(n,a.value);for(;m!==-1;)d.push(m),m=Ft(n,a.value,m+1);return d.flatMap(h=>t.createListInsert(i,h,a.value,r))}case"list-add":return t.createListRemove(i,a.value,"last",r);case"list-set":return n[a.index]!==void 0?t.createListSet(i,a.index,n[a.index],r):t.createListDelete(i,a.index,1,r);case"initialize":return t.createDelete(i,r);case"touch":return[];default:throw new Error(`Cannot undo operation type: ${a.op}`)}}function Ft(i,n,e=0,t="forward"){let r=t==="forward"?"findIndex":"findLastIndex";return $(n)?i[r]((s,o)=>$(s)&&s.id===n.id&&o>=e):i[r]((s,o)=>s===n&&o>=e)}var un=class{constructor(n,e){this.schema=n;this.entities=e;this.getOid=(n,e)=>{let t=this.schema.collections[n].primaryKey,r=e[t];return L(r,`Document must have a primary key: ${t.toString()} (got: ${JSON.stringify(e)})`),ee(n,r)};this.addDefaults=(n,e)=>{let t=this.schema.collections[n];return qe(t,e)};this.validate=(n,e)=>{let t=this.schema.collections[n];return is(t.fields,e)};this.create=async(n,e,t={})=>{let r=t,s=this.addDefaults(n,e),o=this.validate(n,s),a=this.getOid(n,o);if(t.access){let d=this.schema.collections[n];t.access!=="shared"&&e[d.primaryKey]&&!t.silenceAccessControlWithPrimaryKeyWarning&&console.warn("Using a custom primary key with access control is not supported. This may result in corrupted documents. Read more about why: https://verdant.dev/docs/sync/access#a-warning-about-custom-primaryKey"),r.access=t.access}return this.entities.create(o,a,r)};this.delete=async(n,e,t={})=>{let r=ee(n,e);return this.entities.delete(r,t)};this.deleteAll=async(n,e={})=>this.entities.deleteAll(n.map(([t,r])=>ee(t,r)),e);this.deleteAllFromCollection=async(n,e,t={})=>this.entities.deleteAll(e.map(r=>ee(n,r)),t);this.clone=async(n,e,t={})=>{if(!Wt(e.uid))throw new Error("Cannot clone non-root documents");let r=e.getSnapshot(),s=this.schema.collections[n];if(delete r[s.primaryKey],!s.fields[s.primaryKey].default){if(!t.primaryKey)throw new Error(`Error cloning document from collection ${n}: collection does not have a default on primary key. You must supply a value to options.primaryKey for the clone.`);r[s.primaryKey]=t.primaryKey}return this.create(n,r,t)}}};var On=Te(Ks(),1);var Ui=Te(He(),1);function Fa(i){return{id:(0,Ui.default)(),file:i,url:void 0,remote:!1,name:i.name,type:i.type}}function ct(i,n){if(typeof window<"u"&&tt(i)){let e=Fa(i);return n(e),vt(e.id)}if(zt(i)){let e={...i,id:(0,Ui.default)()};return n(e),vt(e.id)}if(Array.isArray(i)){for(let e=0;e<i.length;e++)i[e]=ct(i[e],n);return i}if(typeof i=="object"){for(let e in i)i[e]=ct(i[e],n);return i}return i}var oe=class{constructor(){this._disposes=[];this.disposed=!1;this.dispose=async()=>{this.disposed=!0,await Promise.all(this._disposes.map(async n=>{try{await n()}catch(e){console.error("Error disposing",e)}})),this._disposes=[]};this.compose=n=>this.addDispose(n.dispose.bind(n));this.addDispose=n=>{this._disposes.push(n)}}};var vn=class{constructor({initial:n}={}){this.cache=new Map;this.get=n=>{if(this.cache.has(n.oid))return this.cache.get(n.oid);let e=new pe(n);return this.cache.set(n.oid,e),e};this.has=n=>this.cache.has(n);this.getCached=n=>this.cache.get(n);if(n)for(let e of n)this.cache.set(e.oid,e)}};function qs(i,n,e){let t={previousValue:i.get(n),isLocal:!1};function r(s){if(i.deleted)return;let o=i.get(n);o!==this.previousValue&&(this.isLocal=s.isLocal,e(o,this),this.previousValue=o)}return i.subscribe("change",r.bind(t))}var Hs=Symbol("private entity context key"),pe=class i extends N{constructor({oid:e,schema:t,entityFamily:r,parent:s,ctx:o,metadataFamily:a,readonlyKeys:d,files:m,storeEvents:h,deleteSelf:O}){super();this.fieldPath=[];this._viewData=void 0;this.validationError=void 0;this.cachedDeepUpdatedAt=null;this.wasDeletedLastChange=!1;this.cachedView=void 0;this.onAdd=(e,t)=>{t.oid===this.oid&&this.addConfirmedData(t)};this.onReplace=(e,t)=>{t.oid===this.oid&&this.replaceAllData(t)};this.onResetAll=()=>{this.resetAllData()};this.childIsNull=e=>{if(e instanceof i){let t=e.view;return t==null}return e==null};this.getFieldSchema=e=>{let t=Ve(this.schema,e);return L(t,`No schema for key ${e}`),t};this.validate=Vr(()=>(this.validationError=Re({field:this.schema,value:this.rawView,fieldPath:this.fieldPath,expectRefs:!0})??void 0,this.validationError),()=>[this.viewData]);this.viewWithMappedChildren=e=>{let t=this.view;if(!t)return null;if(Array.isArray(t)){let r=t.map(s=>s instanceof i||s instanceof be?e(s):s);return z(r,this.oid),r}else{let r=Object.entries(t).reduce((s,[o,a])=>(a instanceof i||a instanceof be?s[o]=e(a):s[o]=a,s),{});return z(r,this.oid),r}};this.rawViewWithMappedChildren=e=>{let t=this.rawView;if(!t)return null;if(Array.isArray(t)){let r=t.map((s,o)=>$(s)?e(this.getChild(o,s.id)):s);return z(r,this.oid),r}else{let r=Object.entries(t).reduce((s,[o,a])=>($(a)?s[o]=e(this.getChild(o,a.id)):s[o]=a,s),{});return z(r,this.oid),r}};this.getSnapshot=()=>this.viewWithMappedChildren(e=>e.getSnapshot());this.getUnprunedSnapshot=()=>this.rawViewWithMappedChildren(e=>e instanceof be?e.getSnapshot():e.getUnprunedSnapshot());this.addPendingOperations=e=>{this.ctx.log("debug","Entity: adding pending operations",this.oid,e),this.deepInvalid&&(this.ctx.log("warn","Changes are being applied to a pruned entity. This means that the pruned version is being treated as the new baseline and any pruned invalid data is lost.",this.oid),this.canonizePrunedVersion()),this.applyPendingOperations(e)};this.applyPendingOperations=e=>{if(this.access)for(let r of e)r.authz=this.access;let t=this.metadataFamily.addPendingData(e);for(let r of t)this.change(r)};this.canonizePrunedVersion=()=>{let e=this.getSnapshot(),t=this.getUnprunedSnapshot(),r=this.patchCreator.createDiff(t,e,{authz:this.access,merge:!1});this.applyPendingOperations(r)};this.addConfirmedData=e=>{this.ctx.log("debug","Entity: adding confirmed data",this.oid);let t=this.metadataFamily.addConfirmedData(e);for(let r of t)this.change(r)};this.replaceAllData=e=>{this.ctx.log("debug","Entity: replacing all data",this.oid);let t=this.metadataFamily.replaceAllData(e);for(let r of t)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 t of e)this.change(t)};this.invalidateCachedView=()=>{this._viewData=void 0,this.cachedView=void 0};this.change=e=>{if(e.oid===this.oid)this.invalidateCachedView(),this.parent?this.changeNested(e):this.changeRoot(e);else{let t=this.entityFamily.getCached(e.oid);t&&t instanceof i&&t.change(e)}};this.changeRoot=e=>{this.deleted?this.wasDeletedLastChange||(this.ctx.log("debug","Entity deleted",this.oid),this.emit("delete",{isLocal:e.isLocal}),this.wasDeletedLastChange=!0):(this.wasDeletedLastChange&&(this.ctx.log("debug","Entity restored",this.oid),this.emit("restore",{isLocal:e.isLocal}),this.wasDeletedLastChange=!1),this.deepChange(this,e),this.emit("change",{isLocal:e.isLocal}))};this.changeNested=e=>{this.deepChange(this,e),this.emit("change",{isLocal:e.isLocal})};this.deepChange=(e,t)=>{this.cachedDeepUpdatedAt=null,this.cachedView=void 0,this.emit("changeDeep",e,t),this.parent?.deepChange(e,t)};this.getChild=(e,t)=>{let r=Ve(this.schema,e);if(!r)throw new Error(`No schema for key ${String(e)} in ${JSON.stringify(this.schema)}`);return this.entityFamily.get({oid:t,schema:r,entityFamily:this.entityFamily,metadataFamily:this.metadataFamily,parent:this,ctx:this.ctx,files:this.files,fieldPath:[...this.fieldPath,e],storeEvents:this.storeEvents,deleteSelf:this.delete.bind(this,e)})};this.subscribeToField=(e,t,r)=>qs(this,e,r);this.get=e=>{Ni(e);let t=this.rawView;if(!t)throw new Error(`Cannot access data at key ${e} on deleted entity ${this.oid}`);let r=t[e],s=Ve(this.schema,e);if(!s)throw new Error(`No schema for key ${String(e)} in ${JSON.stringify(this.schema)}`);if($(r))if(he(r)){if(s.type!=="file")throw new Error(`Expected file schema for key ${String(e)}, got ${s.type}`);let o=this.files.get(r.id,{downloadRemote:!!s.downloadRemote,ctx:this.ctx});return o.subscribe("change",()=>{this.deepChange(this,{isLocal:!1,oid:this.oid})}),o}else return this.getChild(e,r.id);else return this.schema.type==="map"&&r===void 0?void 0:Re({field:s,value:r,fieldPath:[...this.fieldPath,e],depth:1,requireDefaults:!0})?ot(s):r};this.getOrSet=(e,t)=>{Ni(e);let r=this.get(e);return r||(this.set(e,t),this.get(e))};this.processInputValue=(e,t)=>{if(this.readonlyKeys.includes(t))throw new Error(`Cannot set readonly key ${t.toString()}`);tt(e)||(e=de(e,!1));let r=Ve(this.schema,t);if(r){Qe(e,r);let s=Re({field:r,value:e,fieldPath:[...this.fieldPath,t]});if(s)throw new Error(`Validation error: ${s.message}`,{cause:s})}return ct(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 t=this.schema.properties[e];if(!t||t.type==="any")return"delete";if(t.type==="map")return!1;if(t.nullable)return"null"}return!1};this.getItemRefValue=e=>{if(e instanceof i)return ie(e.oid);if(e instanceof be)return vt(e.id);if(typeof e=="object"){let t=G(e);if(!t||!this.entityFamily.has(t))throw new Error(`Cannot move object ${JSON.stringify(e)} which does not exist in this list`);return ie(t)}else return e};this.set=(e,t,r)=>{Ni(e),!(!r?.force&&this.get(e)===t)&&(this.isList?this.addPendingOperations(this.patchCreator.createListSet(this.oid,e,this.processInputValue(t,e))):this.addPendingOperations(this.patchCreator.createSet(this.oid,e,this.processInputValue(t,e))))};this.getAll=()=>this.view;this.delete=e=>{if(this.isList)Ta(e),this.addPendingOperations(this.patchCreator.createListDelete(this.oid,e));else{let t=this.getDeleteMode(e);if(!t)throw new Error(`Cannot delete key ${e.toString()} - the property is not marked as optional in the schema.`);t==="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:t=!0,replaceSubObjects:r=!1,preserveUndefined:s=!1,dangerouslyDisableMerge:o=!1}={})=>{if(!t&&!o&&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 a={};z(a,this.oid);for(let[d,m]of Object.entries(e)){if(this.readonlyKeys.includes(d))throw new Error(`Cannot set readonly key ${d.toString()}`);if(m===void 0&&!s)continue;let h=Ve(this.schema,d);h&&Qe(m,h),a[d]=this.processInputValue(m,d)}this.addPendingOperations(this.patchCreator.createDiff(this.getSnapshot(),a,{mergeUnknownObjects:!r,merge:t}))};this.push=e=>{this.addPendingOperations(this.patchCreator.createListPush(this.oid,this.processInputValue(e,this.view.length)))};this.insert=(e,t)=>{this.addPendingOperations(this.patchCreator.createListInsert(this.oid,e,this.processInputValue(t,e)))};this.move=(e,t)=>{this.addPendingOperations(this.patchCreator.createListMoveByIndex(this.oid,e,t))};this.moveItem=(e,t)=>{let r=this.getItemRefValue(e);if($(r))this.addPendingOperations(this.patchCreator.createListMoveByRef(this.oid,r,t));else{let s=this.view.indexOf(e);if(s===-1)throw new Error(`Cannot move item ${JSON.stringify(e)} which does not exist in this list`);this.move(s,t)}};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 t=this.getItemRefValue(e);return $(t)?this.view.some(r=>{if($(r))return De(r,t)}):this.view.includes(e)};this.forEach=e=>{this.view.forEach(e)};this.reduce=(e,t)=>this.view.reduce(e,t);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.deleteSelf=()=>this._deleteSelf();this.__getViewData__=(e,t)=>this.metadataFamily.get(e).computeView(t==="confirmed");this.__getFamilyOids__=()=>this.metadataFamily.getAllOids();this.__discardPendingOperation__=e=>{this.metadataFamily.discardPendingOperation(e),this.invalidateCachedView()};L(!!e,"oid is required"),this.oid=e,this.readonlyKeys=d||[],this.ctx=o,this.files=m,this.schema=t,this.entityFamily=r||new vn({initial:[this]}),this.metadataFamily=a,this.storeEvents=h,this.parent=s,this._deleteSelf=O,this.parent||(h.add.attach(this.onAdd),h.replace.attach(this.onReplace),h.resetAll.attach(this.onResetAll))}get[Hs](){return this.ctx}get metadata(){return this.metadataFamily.get(this.oid)}get patchCreator(){return this.ctx.patchCreator}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&&!Ie(this.schema)||this.schema.type==="array"&&!Array.isArray(e)||(this.schema.type==="object"||this.schema.type==="map")&&!V(e))return Pt(this.schema)?ot(this.schema):null;if(this.cachedView=this.isList?[]:{},z(this.cachedView,this.oid),Array.isArray(e)){let r=Ve(this.schema,0);if(!r)this.ctx.log("error","No child field schema for list entity.",this.oid);else for(let s=0;s<e.length;s++){let o=this.get(s);this.childIsNull(o)&&!Ie(r)?this.ctx.log("error","Child missing in non-nullable field",this.oid,"index:",s):this.cachedView.push(o)}}else if(V(e)){let r=this.schema.type==="object"?Object.keys(this.schema.properties):Object.keys(e);for(let s of r){let o=Ve(this.schema,s);if(!o){this.ctx.log("error","No child field schema for object entity at key",s),this.schema.type==="map"?this.cachedView={}:this.cachedView=null;break}let a=this.get(s);if(this.childIsNull(a)&&!Ie(o)){if(this.ctx.log("error","Child entity is missing for non-nullable field",this.oid,"key:",s),this.schema.type!=="map"){this.cachedView=null;break}}else Ie(o)&&a===void 0?this.cachedView[s]=null:this.cachedView[s]=a}}return this.cachedView}get uid(){return this.oid}get deleted(){return this.viewData.deleted||this.view===null}get invalid(){return!!this.validate()}get deepInvalid(){if(this.invalid)return!0;if(Array.isArray(this.rawView)){for(let e=0;e<this.rawView.length;e++)if(re(this.rawView[e])&&this.getChild(e,this.rawView[e].id).deepInvalid)return!0}else if(V(this.rawView)){for(let e in this.rawView)if(re(this.rawView[e])&&this.getChild(e,this.rawView[e].id).deepInvalid)return!0}return!1}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(t=>{if(t instanceof i){let r=t.deepUpdatedAt;r&&(!e||r>e)&&(e=r)}}):this.values().forEach(t=>{if(t instanceof i){let r=t.deepUpdatedAt;r&&(!e||r>e)&&(e=r)}}),this.cachedDeepUpdatedAt=e,e}get isOutdatedVersion(){return this.parent?this.parent.isOutdatedVersion:this.viewData.fromOlderVersion}get namespace(){return this.ctx.namespace}get access(){return this.viewData.authz}get isAuthorized(){return!!this.access}get size(){return this.isList?this.length:this.keys().length}get length(){return this.view.length}[Symbol.iterator](){let e=0,t=this.view?.length;return{next:()=>e<t?{value:this.get(e++),done:!1}:{value:void 0,done:!0}}}};function Ni(i){if(typeof i=="symbol")throw new Error("Symbol keys aren't supported")}function Ta(i){if(typeof i!="number")throw new Error("Only number keys are supported in list entities")}function Qs(i){return i[Hs].getClient()}var zi=class{constructor({oid:n,ctx:e,confirmedOperations:t,pendingOperations:r,baseline:s}){this.baseline=null;this.confirmedOperations=[];this.pendingOperations=[];this.computeView=(n=!1)=>{let e=de(this.baseline?.snapshot??void 0),t=this.baseline?.timestamp??null,r=this.baseline?.authz,s=this.applyOperations(e,!e,this.confirmedOperations,t,t);s.futureSeen&&this.ctx.globalEvents.emit("futureSeen",s.futureSeen),s.authz&&(r=s.authz);let o=n?s:this.applyOperations(s.view,s.deleted,this.pendingOperations,s.latestTimestamp,null);o.authz&&(r=o.authz),o.view&&z(o.view,this.oid);let a=!!s.latestTimestamp&&Ii(s.latestTimestamp,this.ctx.time.now)<0,d=!this.baseline&&!this.pendingOperations.length&&!this.confirmedOperations.length;d&&this.ctx.log("warn",`Tried to load Entity ${this.oid} with no data`);let m=o.latestTimestamp??s.latestTimestamp??t,h=m?_i(m):0;return!o.view&&!o.deleted&&!d&&this.ctx.log("warn",`Entity ${this.oid} has no view, no deleted flag, and not empty`),{view:o.view??void 0,deleted:o.deleted,empty:d,fromOlderVersion:a,updatedAt:h,latestTimestamp:m,authz:r}};this.addBaseline=n=>{if(!(this.baseline&&this.baseline.timestamp>=n.timestamp))for(this.baseline=n;this.confirmedOperations[0]?.timestamp<n.timestamp;)this.confirmedOperations.shift()};this.addConfirmedOperations=n=>{let e=0;for(let t of n){let r=this.confirmedOperations.findIndex(o=>o.timestamp>=t.timestamp);r!==-1?this.confirmedOperations[r].timestamp!==t.timestamp&&(this.confirmedOperations.splice(r,0,t),e++):(this.confirmedOperations.push(t),e++);let s=this.pendingOperations.length;this.discardPendingOperation(t),e-=s-this.pendingOperations.length}return e};this.addPendingOperation=n=>{this.pendingOperations.push(n)};this.discardPendingOperation=n=>{this.pendingOperations=this.pendingOperations.filter(e=>e.timestamp!==n.timestamp)};this.applyOperations=(n,e,t,r,s)=>{let o,a,d=this.ctx.time.now;for(let m of t)if(!(s&&m.timestamp<=s)){if(Ii(m.timestamp,d)>0){o=m.timestamp;continue}m.data.op==="delete"?e=!0:(n=Be(n,m.data),m.data.op==="initialize"&&(e=!1,m.authz&&(a=m.authz))),(!r||m.timestamp>r)&&(r=m.timestamp)}return{view:n,latestTimestamp:r??null,deleted:e,futureSeen:o,authz:a}};L(n,"oid is required"),this.ctx=e,this.oid=n,t&&(this.confirmedOperations=t),r&&(this.pendingOperations=r),s&&(this.baseline=s)}},xn=class{constructor({ctx:n,onPendingOperations:e,rootOid:t}){this.entities=new Map;this.get=n=>(L(n,"oid is required"),this.entities.has(n)||this.entities.set(n,new zi({oid:n,ctx:this.ctx})),this.entities.get(n));this.getAllOids=()=>Array.from(this.entities.keys());this.addConfirmedData=({baselines:n=[],operations:e={},isLocal:t=!1})=>{let r={};for(let s of n){if(!Le(this.rootOid,s.oid))throw new Error(`Invalid baseline for entity ${this.rootOid}: `+JSON.stringify(s));this.get(s.oid).addBaseline(s),r[s.oid]??={oid:s.oid,isLocal:t}}for(let[s,o]of Object.entries(e)){if(!Le(this.rootOid,s))throw new Error(`Invalid operations for entity ${this.rootOid}: `+JSON.stringify(o));this.get(s).addConfirmedOperations(o)!==0&&(r[s]??={oid:s,isLocal:t})}return Object.values(r)};this.addPendingData=n=>{let e={};for(let t of n)this.get(t.oid).addPendingOperation(t),e[t.oid]??={oid:t.oid,isLocal:!0};return this.onPendingOperations(n),Object.values(e)};this.replaceAllData=({operations:n={},baselines:e=[]})=>{let t=Array.from(this.entities.keys());this.entities.clear();let r={};for(let s of t)r[s]={oid:s,isLocal:!1};for(let s of e){if(!Le(this.rootOid,s.oid))throw new Error(`Invalid baseline for entity ${this.rootOid}: `+JSON.stringify(s));this.get(s.oid).addBaseline(s),r[s.oid]??={oid:s.oid,isLocal:!1}}for(let[s,o]of Object.entries(n)){if(!Le(this.rootOid,s))throw new Error(`Invalid operations for entity ${this.rootOid}: `+JSON.stringify(o));this.get(s).addConfirmedOperations(o),r[s]??={oid:s,isLocal:!1}}return Object.values(r)};this.discardPendingOperation=n=>{this.entities.get(n.oid)?.discardPendingOperation(n)};this.ctx=n,this.rootOid=t,this.onPendingOperations=e}};var kt="@@default",Sn=class{constructor({batchTimeout:n=200,ctx:e,entities:t}){this.currentBatchKey=kt;this.flushOperations=async(n,e,t)=>{if(!n.length)return;this.ctx.log("debug","Flushing",n.length,"operations from batch",e,"to storage / sync");let r=[],s={};for(let o=n.length-1;o>=0;o--){let a=n[o],d=s[a.oid];if(d&&Ar(a,d)){this.entities.discardPendingOperation(a);continue}let m=Cr(a);m!==!1&&(s[a.oid]||(s[a.oid]=new Set),s[a.oid].add(m)),r.unshift(a)}for(let o of r)o.timestamp=this.ctx.time.now;await this.commitOperations(r,t)};this.commitOperations=async(n,e)=>{if(n.length){if(e.undoable){let t=await this.createUndo({ops:n,source:e.source});t&&this.ctx.undoHistory.addUndo(t)}await this.entities.addData({operations:n,baselines:[],isLocal:!0})}};this.addOperations=n=>{n.length&&(this.batcher.add({key:this.currentBatchKey,items:n}),this.ctx.log("debug","added",n.length,"ops to batch",this.currentBatchKey,", size = ",this.batcher.getSize(this.currentBatchKey)))};this.batch=({undoable:n=!0,batchName:e=wt(),max:t=null,timeout:r=this.defaultBatchTimeout}={})=>{let s=this.batcher.add({key:e,max:t,timeout:r,items:[],userData:{undoable:n}}),o={run:a=>(this.currentBatchKey=e,a(),this.currentBatchKey=kt,o),commit:async()=>(await this.batcher.flush(kt),s.flush()),flush:()=>o.commit(),discard:()=>{this.batcher.discard(e)}};return o};this.flushAll=()=>(this.ctx.log("debug","Flushing all operations"),Promise.all(this.batcher.flushAll()));this.createUndo=async n=>{let e=await this.getInverseOperations(n);return e.length?async()=>{let t=await this.createUndo({ops:e,source:n.source,isRedo:!0});for(let r of e)r.timestamp=this.ctx.time.now;return this.ctx.log("debug",n.isRedo?"Redo":"Undo",e,`
7
+ was
8
+ `,n.ops),await this.commitOperations(e,{undoable:!1}),t}:null};this.getInverseOperations=async({ops:n,source:e})=>{let t=xt(n),r=[],s=()=>this.ctx.time.now;return await Promise.all(Object.entries(t).map(async([o,a])=>{let m=(e??await this.entities.hydrate(K(o)))?.__getViewData__(o,"confirmed");if(!m){this.ctx.log("warn","could not find entity",o,"for undo operation",n);return}let h=ds(o,m.view,a,s);r.unshift(...h)})),r};this.ctx=e,this.entities=t,this.defaultBatchTimeout=n,this.batcher=new et(this.flushOperations),this.batcher.add({key:kt,items:[],max:100,timeout:n,userData:{undoable:!0}})}get isDefaultBatch(){return this.currentBatchKey===kt}};var In=class extends oe{constructor({ctx:e,files:t}){super();this.events={add:new On.WeakEvent,replace:new On.WeakEvent,resetAll:new On.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.ctx.globalEvents.emit("resetToServer")})),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.empty=async()=>{await this.ctx.documents.reset(),this.events.resetAll.invoke(this),this.cache.clear()};this.resetData=async()=>{if(this.disposed){this.ctx.log("warn","EntityStore is disposed, not resetting local data");return}await this.ctx.meta.reset(),await this.ctx.documents.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 t=e?.baselines??[],r=e?.operations??[];if(t.length===0&&r.length===0){this.ctx.log("debug","No data to process");return}this.ctx.log("debug","Processing incoming data",{operations:r.length,baselines:t.length,reset:!!e.reset});let s=Array.from(new Set(t.map(h=>K(h.oid)).concat(r.map(h=>K(h.oid))))),o=Pr(t),a=Dr(r);this.ctx.log("debug","Applying data to live entities");for(let h of s){let O=o[h],w=a[h]??[],C=xt(w),y=e.reset?this.events.replace:this.events.add,I=this.pendingEntityPromises.get(h);I?(this.ctx.log("debug","Waiting for ongoing entity hydration",h),I.then(()=>{y.invoke(this,{oid:h,baselines:O,operations:C,isLocal:!1})})):(this.ctx.log("debug","Applying data to entity",h),y.invoke(this,{oid:h,baselines:O,operations:C,isLocal:!1}))}let d={abort:this.abortDataQueueController.signal};await this.ctx.meta.insertData(e,d),this.ctx.log("debug","Data processing complete, all data saved to metadata db.");let m=await Promise.all(s.map(async h=>await this.hydrate(h,d)??{oid:h,getSnapshot(){return null}}));try{this.ctx.log("debug","Saving entities to queryable storage"),await this.ctx.documents.saveEntities(m,d)}catch(h){this.disposed?this.ctx.log("warn","Error saving entities to queryable storage - EntityStore is disposed",h):this.ctx.log("error","Error saving entities to queryable storage",h)}};this.hydrate=async(e,t)=>{if(!Wt(e))throw new Error("Cannot hydrate non-root entity");if(this.cache.has(e)){let s=this.cache.get(e);if(s){let o=s.deref();if(o)return o.deleted?(this.ctx.log("debug","Hydrated entity is deleted",e),null):(this.ctx.log("debug","Hydrating entity from cache",e),o);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 ongoing entity hydration",e),r;{this.ctx.log("debug","Hydrating entity from storage",e);let s=this.constructEntity(e);if(!s)return this.ctx.log("warn","Entity schema not found, cannot construct",e),null;let o=this.loadEntity(s,t);return o.finally(()=>{this.pendingEntityPromises.delete(e)}),this.pendingEntityPromises.set(e,o),o}};this.destroy=async()=>{this.dispose(),await this.batcher.flushAll()};this.create=async(e,t,{undoable:r=!0,access:s}={})=>{this.ctx.log("debug","Creating new entity",t);let{collection:o}=ue(t);Qt(e);let a=ct(e,this.files.add);z(a,t);let d=this.constructEntity(t);if(!d)throw new Error(`Could not put new document: no schema exists for collection ${o}`);let m=this.ctx.patchCreator.createInitialize(a,t,s);await this.batcher.commitOperations(m,{undoable:!!r,source:d});let h=xt(m);return this.events.add.invoke(this,{operations:h,isLocal:!0,oid:t}),this.cache.set(t,this.ctx.weakRef(d)),d};this.deleteAll=async(e,t)=>{this.ctx.log("info","Deleting documents",e),L(e.every(o=>o===K(o)),"Only root documents may be deleted via client methods");let r=await Promise.all(e.map(o=>this.hydrate(o)));e.forEach(o=>{this.cache.delete(o),this.ctx.log("debug","Deleted document from cache",o)});let s=[];for(let o of r)if(o){let a=o.__getFamilyOids__(),d=this.ctx.patchCreator.createDeleteAll(a);for(let m of d)m.authz=o.access;s.push(...d)}await this.batcher.commitOperations(s,{undoable:t?.undoable===void 0?!0:t.undoable})};this.delete=async(e,t)=>this.deleteAll([e],t);this.getCollectionSchema=e=>{let t=this.ctx.schema.collections[e];return t?{schema:{type:"object",nullable:!1,properties:t.fields},readonlyKeys:[t.primaryKey]}:(this.ctx.log("warn",`Missing schema for collection: ${e}`),{schema:null,readonlyKeys:[]})};this.constructEntity=e=>{L(!!e,"Cannot construct entity without OID");let{collection:t}=ue(e),{schema:r,readonlyKeys:s}=this.getCollectionSchema(t);if(!r)return null;if(this.disposed)throw new Error("Cannot hydrate entity after store has been disposed");let o=new xn({ctx:this.ctx,onPendingOperations:this.onPendingOperations,rootOid:e});return new pe({ctx:this.ctx,oid:e,schema:r,readonlyKeys:s,files:this.files,metadataFamily:o,storeEvents:this.events,deleteSelf:this.delete.bind(this,e)})};this.onPendingOperations=e=>{this.batcher.addOperations(e)};this.discardPendingOperation=e=>{let t=K(e.oid);this.cache.get(t)?.deref()?.__discardPendingOperation__(e)};this.loadEntity=async(e,t)=>(await this.loadEntityData(e,t),this.cache.set(e.oid,this.ctx.weakRef(e)),this.entityFinalizationRegistry.register(e,e.oid),e);this.loadEntityData=async(e,t)=>{let{operations:r,baselines:s}=await this.ctx.meta.getDocumentData(e.oid,t);return!s.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:s,operations:r,isLocal:!1}),e)};this.clearCache=()=>{this.ctx.log("debug","Emptying entity cache"),this.cache.clear()};this.ctx=e,this.files=t,this.batcher=new Sn({ctx:e,entities:this}),this.addDispose(this.ctx.internalEvents.subscribe("persistenceReset",this.clearCache))}get batch(){return this.batcher.batch}get flushAllBatches(){return this.batcher.flushAll}};function Ws({currentVersion:i,targetVersion:n,migrations:e}){let t=Js({currentVersion:i,targetVersion:n,migrations:e});if(!t)throw new Q(Q.Code.MigrationPathNotFound,void 0,`No migration path found from ${i} to ${n}! This is a bug. If you're seeing this, contact the developer and provide them with the full contents of this message.`);return t}function Js({currentVersion:i,targetVersion:n,migrations:e}){if(i===n)return[];let t=e.filter(r=>r.oldSchema.version===i).sort((r,s)=>s.newSchema.version-r.newSchema.version);for(;t.length>0;){let r=t.shift();if(r.newSchema.version>n)return null;if(r.newSchema.version===n)return[r];let s=Js({currentVersion:r.newSchema.version,targetVersion:n,migrations:e});if(s)return[r,...s]}return null}var lt=Symbol("entity-file-update"),_n=Symbol("entity-file-mark-failed"),ka,Ba,be=class extends N{constructor(e,{downloadRemote:t=!1,ctx:r}){super();this.id=e;this._objectUrl=null;this._fileData=null;this._loading=!0;this._failed=!1;this._downloadRemote=!1;this._uploaded=!1;this.unsubscribes=[];this[ka]=e=>{this.ctx.log("debug","EntityFile updated",this.id,e),this._loading=!1,this._failed=!1,this._fileData=e,e.file&&(this._objectUrl&&"revokeObjectURL"in URL&&URL.revokeObjectURL(this._objectUrl),this.ctx.log("debug","Creating object URL for file",this.id),this._objectUrl=URL.createObjectURL(e.file)),this.emit("change")};this[Ba]=()=>{this._failed=!0,this._loading=!1,this.emit("change")};this.onUploaded=e=>{this._fileData??=e,this._uploaded=!0,this.ctx.log("debug","File marked uploaded",this.id,this._fileData),this.emit("change")};this.destroy=()=>{this._objectUrl&&URL.revokeObjectURL(this._objectUrl),this.dispose()};this.ctx=r,this._downloadRemote=t,this.unsubscribes.push(this.ctx.internalEvents.subscribe(`fileUploaded:${e}`,this.onUploaded))}static{ka=lt,Ba=_n}get downloadRemote(){return this._downloadRemote}get isFile(){return!0}get isUploaded(){return this._uploaded||this._fileData?.remote||!1}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._objectUrl??this._fileData?.url??void 0,name:this.name??"unknown-file",remote:this._fileData?.remote??!1,type:this.type??"",file:this._fileData?.file}}};var En=class extends oe{constructor({sync:e,context:t}){super();this.cache=new Map;this.add=async e=>{let t=this.cache.get(e.id);t||(t=new be(e.id,{ctx:this.context}),this.cache.set(e.id,t)),e.remote||t[lt](e);let r=await this.context.files.add(e);t[lt](r)};this.get=(e,t)=>{if(this.cache.has(e))return this.cache.get(e);let r=new be(e,t);return this.cache.set(e,r),this.load(r),r};this.load=async e=>{let t=await this.context.files.get(e.id);if(t)e[lt](t);else try{if(this.sync.status!=="active"){this.context.log("info","Sync is not active, waiting for online to load file",e.id,e.name);let s=this.sync.subscribe("onlineChange",o=>{o&&(s(),this.load(e))});return}let r=await this.sync.getFile(e.id);r.success?(await this.context.files.add(r.data),e[lt](r.data)):(this.context.log("error","Failed to load file",r),e[_n]())}catch(r){this.context.log("error","Failed to load file",r),e[_n]()}};this.onFileUploaded=e=>{this.context.log("debug","Marking file as uploaded",e.id),this.context.files.onUploaded(e.id)};this.sync=e,this.context=t,this.addDispose(this.context.internalEvents.subscribe("fileUploaded",this.onFileUploaded))}};var $i=typeof window<"u"?window.indexedDB:void 0;function Ge(i){return i instanceof Error&&i.name==="AbortError"}function dt(i){return new Promise((n,e)=>{i.onsuccess=()=>{n(i.result)},i.onerror=()=>{i.error&&Ge(i.error)?n(i.result):e(i.error)}})}function Ye(i,n){return new Promise((e,t)=>{let r=i.transaction([n],"readonly"),o=r.objectStore(n).openCursor(),a=0,d=0;o.onsuccess=function(m){let h=o.result;h&&(a++,d=d+wr(h.value),h.continue())},o.onerror=function(m){o.error&&Ge(o.error)?e({count:a,size:d}):t(o.error)},r.oncomplete=function(m){e({count:a,size:d})},r.onabort=function(m){t(m)},r.onerror=function(m){t(m)}})}function Ki(i,n){let e=i.transaction(n,"readonly"),t=n.map(r=>{let s=e.objectStore(r);return dt(s.getAll())});return Promise.all(t)}async function we(i){i.close(),await new Promise(n=>{n()}),await new Promise(n=>{n()})}async function Dn(i,n=$i){let e=n.deleteDatabase([i,"meta"].join("_")),t=n.deleteDatabase([i,"collections"].join("_"));await Promise.all([new Promise((r,s)=>{e.onsuccess=r,e.onerror=s}),new Promise((r,s)=>{t.onsuccess=r,t.onerror=s})]),window.location.reload()}function Pn(i,n=window.indexedDB){return dt(n.deleteDatabase(i))}async function La(i=window.indexedDB){return i.databases()}function Gs(i,n,e,t,r){let s=i.transaction(n,e);if(t){let o=()=>{r?.("debug","aborting transaction");try{s.abort()}catch(a){r?.("debug","aborting transaction failed",a)}};t.addEventListener("abort",o),s.addEventListener("error",()=>{t.removeEventListener("abort",o)}),s.addEventListener("complete",()=>{t.removeEventListener("abort",o)})}return s}async function qi(i,n,e,t=window.indexedDB){(await La(t)).some(a=>a.name===n)&&(await Pn(n,t),e.log("debug","Deleted existing database",n));let s=await new Promise((a,d)=>{e.log("debug","Opening reset database",n,"at",i.version);let m=t.open(n,i.version);m.onupgradeneeded=()=>{e.log("debug","Upgrading database",n,"to version",i.version);let h=i,O=m.transaction;if(!O)throw new Error("No transaction");for(let w of Array.from(h.objectStoreNames)){let C=h.transaction(w).objectStore(w);O.db.createObjectStore(w,{keyPath:C.keyPath,autoIncrement:C.autoIncrement});let y=O.objectStore(w),I=h.transaction(w).objectStore(w);for(let E of Array.from(I.indexNames)){let _=I.index(E);e.log("debug","Copying index",E),y.createIndex(E,_.keyPath,{unique:_.unique,multiEntry:_.multiEntry})}}},m.onsuccess=()=>{e.log("debug","Opened reset database",n),a(m.result)},m.onerror=()=>d(m.error??new Error("Unknown database upgrade error"))}),o=await Ki(i,Array.from(i.objectStoreNames));await new Promise((a,d)=>{let m=s.transaction(Array.from(s.objectStoreNames),"readwrite");for(let h=0;h<o.length;h++){let O=m.objectStore(i.objectStoreNames[h]);for(let w of o[h])O.add(w)}m.oncomplete=()=>a(),m.onerror=h=>{let O=m.error??h.target.transaction?.error??new Error("Unknown error");e.log("critical","Error copying data",O),d(O)}}),await we(s)}function Ys(i,n,e=window.indexedDB){return new Promise((t,r)=>{let s=e.open(i,n);s.onsuccess=()=>{t(s.result)},s.onerror=()=>{r(s.error)},s.onblocked=()=>{r(new Error("Database blocked"))},s.onupgradeneeded=o=>{let a=s.result;a.version!==n&&(a.close(),r(new Error(`Migration error: database version changed unexpectedly when reading current data. Expected ${n}, got ${a.version}`)))}})}function Bt(i){return[i,"meta"].join("_")}function ut(i){return[i,"collections"].join("_")}function Xs(i){return i.name?.split("_")[0]}var Fe=class{constructor(n){this.log=n;this.consumed=!1;this.handlers=[];this.reset=()=>{this.consumed=!1}}register(n){this.handlers.push(n)}async shutdown(){this.consumed&&this.log?.("warn","ShutdownHandler already consumed"),this.consumed=!0,await Promise.all(this.handlers.map(n=>n())),this.handlers.length=0}get isShuttingDown(){return this.consumed}};function Zs(i,n){return`@@wip-${i}-${$e(n)}`}function eo({migration:i,newOids:n,ctx:e}){return i.allCollections.reduce((t,r)=>(t[r]={put:async(s,o)=>{qe(i.newSchema.collections[r],s);let a=s[i.newSchema.collections[r].primaryKey],d=ee(r,a);return n.push(d),await e.time.withMigrationTime(i.version,()=>e.meta.insertData({operations:e.patchCreator.createInitialize(s,d,o?.access),isLocal:!0})),s},delete:async s=>{let o=ee(r,s);await e.time.withMigrationTime(i.version,()=>e.meta.deleteDocument(o))}},t),{})}function ja({migration:i,context:n,documents:e}){return i.oldCollections.reduce((t,r)=>(t[r]={get:async s=>{let o=ee(r,s);return await n.meta.getDocumentSnapshot(o,{to:n.time.nowWithVersion(i.oldSchema.version)})},findOne:async s=>{let o=await e.findOneOid({collection:r,index:s});return o?await n.meta.getDocumentSnapshot(o,{to:n.time.nowWithVersion(i.oldSchema.version)}):null},findAll:async s=>{let{result:o}=await e.findAllOids({collection:r,index:s});return await Promise.all(o.map(d=>n.meta.getDocumentSnapshot(d,{to:n.time.nowWithVersion(i.oldSchema.version)})))}},t),{})}async function to({migration:i,context:n,ns:e}){let t={...n,schema:i.oldSchema};if(i.oldSchema.version===0)return Ma({migration:i,context:t});let r=new Array,s=await e.openDocuments(t),o=ja({migration:i,context:t,documents:s}),a=eo({migration:i,newOids:r,ctx:t}),d=async O=>{await n.meta.deleteCollection(O)},m=new Array;return{log:n.log,newOids:r,deleteCollection:d,migrate:async(O,w)=>{let C=await o[O].findAll();n.log("debug",`Migrating ${C.length} documents in ${O}`),await Promise.all(C.filter(Boolean).map(async y=>{let I=se(y);L(!!I,`Document is missing an OID: ${JSON.stringify(y)}`);let E=await n.meta.getDocumentAuthz(I),_=de(y),D=await w(y);if(D){Ot(_),Ot(D),nt(D);let k=Jt(_,D,()=>n.time.zeroWithVersion(i.version),void 0,[],{mergeUnknownObjects:!0,defaultUndefined:!1,authz:E});k.length>0&&await n.meta.insertData({operations:k,isLocal:!0})}}))},queries:o,mutations:a,awaitables:m,close:async()=>{await s.close()}}}function Ma({migration:i,context:n}){let e=new Array,t=new Proxy({},{get(){throw new Error("Queries are not available in initial migrations; there is no database yet!")}}),r=eo({migration:i,newOids:e,ctx:n});return{log:n.log,newOids:e,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:t,mutations:r,awaitables:[],close:()=>Promise.resolve()}}async function no({ctx:i,documents:n,migration:e,engine:t}){let r=await Va({currentVersion:e.oldSchema.version,newVersion:e.newSchema.version,ctx:i});for(let s of e.allCollections){let{result:o}=await n.findAllOids({collection:s});o.push(...t.newOids.filter(m=>ue(m).collection===s),...r.filter(m=>ue(m).collection===s));let d=(await Promise.all(o.map(async m=>{try{let h=await i.meta.getDocumentSnapshot(m);return[m,h]}catch(h){return i.log("error","Could not regenerate snapshot during migration for oid",m,"this document will not be preserved",h),null}}))).filter(m=>!!m);await n.saveEntities(d.map(([m,h])=>({oid:m,getSnapshot(){return h}})),{collections:[s]})}}async function Va({currentVersion:i,newVersion:n,ctx:e}){let t=[];return await e.meta.iterateAllOperations(r=>{t.push(r)},{from:e.time.zeroWithVersion(i+1)}),Array.from(new Set(t.map(r=>K(r.oid))))}async function io({context:i,version:n}){let e=await i.persistence.openNamespace(i.namespace,i);await Ua(i.namespace,async()=>{let t=await i.persistence.getNamespaceVersion(i.namespace);i.log("debug","Opening index database",i.namespace,"Current database version:",t,"target version:",n,i.schema.wip?"(wip)":"");let r=Ws({currentVersion:t,targetVersion:n,migrations:i.migrations});r.length>0&&(i.log("debug","Migrations to run:",r.map(s=>s.version)),await Na({context:i,ns:e,toRun:r}))})}async function Ua(i,n){typeof navigator<"u"&&navigator.locks?await navigator.locks.request(`verdant_migration_${i}`,n):await n()}async function Na({context:i,toRun:n,ns:e}){i.pauseRebasing=!0;for(let t of n){i.log("info",`\u{1F680} Running migration v${t.oldSchema.version} -> v${t.newSchema.version}`);let r={...i,schema:t.oldSchema,shutdownHandler:new Fe(i.log)},s=await to({migration:t,context:r,ns:e});try{i.log("debug","Migrating data",r.namespace,"from version",t.oldSchema.version,"to version",t.newSchema.version),await t.migrate(s),await Promise.all(s.awaitables)}catch(a){throw i.log("critical",`Migration failed (${t.oldSchema.version} -> ${t.newSchema.version})`,a),a instanceof Error?a:new Error("Unknown error during migration")}await s.close(),r.log("debug","Upgrading database",r.namespace,"from version",r.schema.version,"to version",t.newSchema.version),await e.applyMigration(r,t),r.schema=t.newSchema;let o=await e.openDocuments(r);await no({ctx:r,migration:t,engine:s,documents:o}),await o.close(),r.log("debug",`Migration of ${r.namespace} complete.`),r.log("info",`
7
9
  \u2B06\uFE0F v${t.newSchema.version} Migration complete. Here's the rundown:
8
10
  - Added collections: ${t.addedCollections.join(", ")}
9
11
  - Removed collections: ${t.removedCollections.join(", ")}
10
12
  - Changed collections: ${t.changedCollections.join(", ")}
11
- - New indexes: ${Object.keys(t.addedIndexes).map(a=>t.addedIndexes[a].map(f=>`${a}.${f.name}`)).flatMap(a=>a).join(", ")}
12
- - Removed indexes: ${Object.keys(t.removedIndexes).map(a=>t.removedIndexes[a].map(f=>`${a}.${f.name}`)).flatMap(a=>a).join(", ")}
13
- `)}i.pauseRebasing=!1}var En=class{constructor(n,e){this.db=n;this.context=e;this.onServerReset=n=>this.db.resetSyncedStatusSince(n);this.add=async n=>{if(n.url&&!(n.localPath||n.file)){this.context.log("debug","Remote file added to an entity. This usually means an entity was cloned. Downloading remote file...",n.id);let e=await this.loadFileContents(n,0,3);n.file=new File([e],n.name,{type:n.type}),delete n.url,this.context.log("debug","Downloaded remote file",n.id,n.name,". Cleared its remote URL.")}else!n.url&&!n.file&&!n.localPath&&this.context.log("warn","File added without a file or URL. This file will not be available for use.",n.id);return n.remote=!1,await this.db.add(n),this.context.internalEvents.emit("fileAdded",n),this.context.globalEvents.emit("fileSaved",n),this.context.log("debug","File added",n.id,n.name,n.type,n.file?"with binary file":n.url?"with url":n.localPath?"with local path":"with no data"),n};this.onUploaded=this.db.markUploaded.bind(this.db);this.get=this.db.get.bind(this.db);this.getAll=this.db.getAll.bind(this.db);this.listUnsynced=this.db.listUnsynced.bind(this.db);this.iterateOverPendingDelete=this.db.iterateOverPendingDelete.bind(this.db);this.stats=this.db.stats.bind(this.db);this.getFileExportName=(n,e)=>`${e}___${n}`;this.export=async(n=!0)=>{let e=await this.getAll();if(n)for(let s of e)if(!s.file&&(s.url||s.localPath))try{let o=await this.loadFileContents(s);s.file=o}catch(o){this.context.log("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,o)}else s.file||this.context.log("warn",`File ${s.id} has no file or URL. It will be missing in the export.`,s);let t=[],r=[];for(let s of e){let o=s.file;if(delete s.file,t.push(s),o){let a=new File([o],this.getFileExportName(s.name,s.id),{type:s.type});r.push(a)}else this.context.log("warn",`File ${s.id} was could not be loaded locally or from the server. It will be missing in the export.`)}return{fileData:t,files:r}};this.import=async({fileData:n,files:e})=>{let t=new Map(e.map(s=>{let{id:o}=this.parseFileExportname(s.name);return[o,s]})),r=n.map(s=>{let o=t.get(s.id);return o?{...s,file:o}:(this.context.log("warn",`File ${s.id} was not found in import`),s)});await Promise.all(r.map(s=>this.add(s)))};this.parseFileExportname=n=>{let[e,t]=n.split("___");return{id:e,originalFileName:t}};this.loadFileContents=async(n,e=0,t=0)=>{try{return await this.db.loadFileContents(n,this.context)}catch(r){if(e<t)return new Promise((s,o)=>{setTimeout(()=>{this.loadFileContents(n,e+1,t).then(s,o)},1e3)});throw this.context.log("error",`Failed to download file after ${t} retries`,r),new Error(`Failed to download file after ${t} retries`,{cause:r})}};this.cleanupDeletedFiles=async()=>{let n=0,e=0,t=[];await this.iterateOverPendingDelete(r=>{this.config.canCleanupDeletedFile(r)?(n++,t.push(r.id)):e++});for(let r of t)await this.db.delete(r);this.context.log("info",`Cleaned up ${n} files, skipped ${e} files`)};this.onFileRefsDeleted=async n=>{await Promise.all(n.map(async e=>{try{await this.db.markPendingDelete(e.id)}catch(t){this.context.log("error","Failed to mark file for deletion",t)}})),this.context.log("info",`Marked ${n.length} files as pending delete`)};e.internalEvents.subscribe("filesDeleted",this.onFileRefsDeleted),this.cleanupDeletedFiles()}get config(){return{canCleanupDeletedFile(n){return n.deletedAt!==null&&n.deletedAt<Date.now()-1e3*60*24*3},...this.context.config.files}}};var Dn=class{constructor(n,e,t){this.db=n;this.meta=e;this.ctx=t;this.tryAutonomousRebase=async()=>{(await this.meta.getLocalReplica()).lastSyncedLogicalTime||this.ctx.closing||this.ctx.persistenceShutdownHandler.isShuttingDown||(this.ctx.log("debug","Running autonomous library rebase"),await this.runRebase(this.ctx.time.now))};this.runRebase=async n=>{this.ctx.closing||this.ctx.persistenceShutdownHandler.isShuttingDown||(await this.db.transaction({storeNames:["baselines","operations"],mode:"readwrite"},async e=>{let t=new Set,r,s=0;if(await this.db.iterateAllOperations(a=>{t.add(a.oid),r=a.timestamp,s++},{before:n,transaction:e}),!t.size||this.ctx.closing||this.ctx.persistenceShutdownHandler.isShuttingDown)return;let o=[];for(let a of t)o.push(await this.rebase(a,r||n,e))}),this.ctx.globalEvents.emit("rebase"))};this.scheduleRebase=async n=>{this.rebaseTimeout&&clearTimeout(this.rebaseTimeout),this.rebaseTimeout=setTimeout(this.runRebase,this.ctx.config.persistence?.rebaseTimeout??1e4,n),this.ctx.log("debug","Scheduled rebase up to global ack",n)};this.rebaseTimeout=null;this.rebase=async(n,e,t)=>{if(this.ctx.closing||this.ctx.persistenceShutdownHandler.isShuttingDown)return;let r=await this.db.getBaseline(n,{transaction:t}),s=r?.snapshot||void 0,o=0,a=r?.authz,f=[];if(this.ctx.closing||this.ctx.persistenceShutdownHandler.isShuttingDown)return;await this.db.iterateEntityOperations(n,y=>{(!r||y.timestamp>r.timestamp)&&(s=Fe(s,y.data,f),y.data.op==="initialize"&&(a=y.authz)),o++},{to:e,transaction:t}),s&&$(s,n);let p={oid:n,snapshot:s,timestamp:e,authz:a};if(!(this.ctx.closing||this.ctx.persistenceShutdownHandler.isShuttingDown))return this.ctx.closeLock=(async()=>{if(p.snapshot?await this.db.setBaselines([p],{transaction:t}):await this.db.deleteBaseline(n,{transaction:t}),await this.db.deleteEntityOperations(n,{to:e,transaction:t}),this.ctx.log("debug","rebased",n,"up to",e,":",s,"and deleted",o,"operations"),f.length){let y=f.filter(ge);y.length&&this.ctx.internalEvents.emit("filesDeleted",y)}})(),p}}};var Cn=class{constructor(n,e,t){this.db=n;this.meta=e;this.ctx=t;this.createOperation=async n=>{let e=await this.meta.getLocalReplica();return this.ctx.log("debug","Creating operation message",n.operations.length),{type:"op",timestamp:this.ctx.time.now,replicaId:e.id,operations:n.operations.map(zt)}};this.createSyncStep1=async n=>{let e=await this.meta.getLocalReplica(),t=n===null?null:e.lastSyncedLogicalTime,r=[],s=new Set;return this.db.transaction({mode:"readwrite",storeNames:["operations","baselines"]},async o=>{t?(this.ctx.log("debug","Syncing local operations since",t),await this.db.iterateLocalOperations(f=>{r.push(zt(f)),s.add(z(f.oid))},{after:t,transaction:o})):(this.ctx.log("debug","Syncing all operations"),await this.db.iterateAllOperations(f=>{r.push(zt(f)),s.add(z(f.oid))},{transaction:o}));let a=[];return t||await this.db.iterateAllBaselines(f=>{a.push(f)},{transaction:o}),r.length>0&&this.ctx.log("debug",`Syncing ${r.length} operations since ${t}`),{type:"sync",schemaVersion:this.ctx.schema.version,timestamp:this.ctx.time.now,replicaId:e.id,resyncAll:!e.lastSyncedLogicalTime,operations:r,baselines:a,since:t}})};this.createPresenceUpdate=async n=>{let e=await this.meta.getLocalReplica();return{type:"presence-update",presence:n.presence,replicaId:e.id,internal:n.internal}};this.createHeartbeat=async()=>{let n=await this.meta.getLocalReplica();return{type:"heartbeat",timestamp:this.ctx.time.now,replicaId:n.id}};this.createAck=async n=>{let e=await this.meta.getLocalReplica();return{type:"ack",timestamp:this.ctx.time.now,replicaId:e.id,nonce:n}}}};var eo=Ae($e(),1),Pn=class{constructor(n,e){this.db=n;this.ctx=e;this.events=new V;this.insertOperations=async(n,e)=>{this.ctx.log("debug",`Inserting ${n.length} operations`,n);let t=await this.db.addOperations(n,e);for(let r of n)this.ctx.globalEvents.emit("operation",r);return!this.ctx.config.persistence?.disableRebasing&&!this.ctx.pauseRebasing&&this.rebaser.tryAutonomousRebase(),t};this.insertLocalOperations=async(n,e)=>{if(n.length===0)return;for(let r of n)r.isLocal=!0;await this.insertOperations(n,e),this.ctx.log("debug",`Inserted ${n.length} local operations; sending sync message`);let t=await this.messageCreator.createOperation({operations:n});this.events.emit("syncMessage",t)};this.insertRemoteOperations=async(n,e)=>{if(n.length===0)return[];for(let t of n)t.isLocal=!1;await this.insertOperations(n,e),this.ack(n[n.length-1].timestamp)};this.insertRemoteBaselines=async(n,e)=>{if(n.length===0)return[];this.ctx.log("debug",`Inserting ${n.length} remote baselines`),await this.db.setBaselines(n,e);let t=new Set;return n.forEach(r=>{t.add(z(r.oid))}),Array.from(t)};this.deleteDocument=async n=>{let e=new Set,t=z(n);return N(t===n,"Must be root document OID"),e.add(t),this.db.transaction({storeNames:["baselines","operations"]},async r=>{await Promise.all([this.db.iterateDocumentBaselines(t,a=>{e.add(a.oid)},{transaction:r}),this.db.iterateDocumentOperations(t,a=>{e.add(a.oid)},{transaction:r})]);let s=await this.getDocumentAuthz(t),o=new Array;for(let a of e)o.push({oid:a,timestamp:this.ctx.time.now,data:{op:"delete"},authz:s});return this.insertLocalOperations(o,{transaction:r})})};this.deleteCollection=async n=>{let e=new Set;return this.db.transaction({storeNames:["baselines","operations"],mode:"readwrite"},async t=>{await Promise.all([this.db.iterateCollectionBaselines(n,s=>{e.add(s.oid)},{transaction:t}),this.db.iterateCollectionOperations(n,s=>{e.add(s.oid)},{transaction:t})]);let r=new Array;for(let s of e)r.push({oid:s,timestamp:this.ctx.time.now,data:{op:"delete"},authz:void 0});return this.insertLocalOperations(r,{transaction:t})})};this.getDocumentSnapshot=async(n,e={})=>{let t=z(n);return N(t===n,"Must be root document OID"),this.db.transaction({storeNames:["baselines","operations"],mode:"readwrite"},async r=>{let s=[];await this.db.iterateDocumentBaselines(t,f=>{s.push(f)},{transaction:r});let o=new Map;for(let f of s)f.snapshot&&$(f.snapshot,f.oid),o.set(f.oid,f.snapshot);await this.db.iterateDocumentOperations(t,f=>{let p=o.get(f.oid)||void 0,y=Fe(p,f.data);y&&$(y,f.oid),o.set(f.oid,y)},{transaction:r,to:e.to||this.ctx.time.now});let a=o.get(t);return a&&Nt(a,o),a})};this.getDocumentData=async(n,e)=>this.db.transaction({storeNames:["baselines","operations"],abort:e?.abort},async t=>{let r=[],s={};return await Promise.all([this.db.iterateDocumentBaselines(n,o=>{r.push(o)},{transaction:t}),this.db.iterateDocumentOperations(n,o=>{s[o.oid]??=[],s[o.oid].push(o)},{transaction:t})]),{baselines:r,operations:s}});this.getDocumentAuthz=async n=>{let e;return await this.db.iterateEntityOperations(n,t=>{if(t.data.op==="initialize")return e=t.authz,!0}),e};this.insertData=async(n,e)=>this.db.transaction({storeNames:["baselines","operations"],abort:e?.abort,mode:"readwrite"},async t=>{if(this.ctx.log("debug","Begin insert data transaction"),n.baselines&&await this.insertRemoteBaselines(n.baselines,{transaction:t}),this.ctx.log("debug","Inserted baselines (if any)"),e?.abort?.aborted)throw new Error("Aborted");n.operations&&(n.isLocal?(this.ctx.log("debug","Inserting local operations"),await this.insertLocalOperations(n.operations,{transaction:t})):(this.ctx.log("debug","Inserting remote operations"),await this.insertRemoteOperations(n.operations,{transaction:t}))),this.ctx.log("debug","End insert data transaction")});this.updateLastSynced=async n=>{if(!this.ctx.closing)return this.updateLocalReplica({lastSyncedLogicalTime:n})};this.setGlobalAck=async n=>{this.ctx.closing||(await this.db.setGlobalAck(n),this.ctx.config.persistence?.disableRebasing||await this.rebaser.scheduleRebase(n))};this._cachedLocalReplica=null;this._creatingLocalReplica=void 0;this.getLocalReplica=async n=>{if(this._cachedLocalReplica)return this._cachedLocalReplica;let e=await this.db.getLocalReplica(n);return e?(this.ctx.log("debug","Read local replica",e),this._cachedLocalReplica=e,e):this._creatingLocalReplica?this._creatingLocalReplica:(this._creatingLocalReplica=(async()=>{let r={id:(0,eo.default)(),userId:null,ackedLogicalTime:null,lastSyncedLogicalTime:null};return await this.db.updateLocalReplica(r),this._cachedLocalReplica=r,r})(),this._creatingLocalReplica)};this.updateLocalReplica=async(n,e)=>{let t=await this.getLocalReplica(e);N(!!t,"Local replica must exist"),Object.assign(t,n),this._cachedLocalReplica=t,await this.db.updateLocalReplica(t,e)};this.iterateLocalOperations=this.db.iterateLocalOperations;this.iterateAllOperations=this.db.iterateAllOperations;this.iterateAllBaselines=this.db.iterateAllBaselines;this.reset=async()=>{this.ctx.closing||await this.db.reset()};this.stats=this.db.stats;this.export=async()=>{let n=new Array,e=new Array;return this.db.transaction({storeNames:["baselines","operations"],mode:"readwrite"},async t=>{await this.iterateAllOperations(s=>{e.push(s)},{transaction:t}),await this.iterateAllBaselines(s=>{n.push(s)},{transaction:t});let r=await this.getLocalReplica();return{operations:e,baselines:n,localReplica:r,schemaVersion:this.ctx.schema.version}})};this.resetFrom=async n=>{this._cachedLocalReplica=null,await this.db.reset({clearReplica:!0}),n.localReplica&&await this.updateLocalReplica({ackedLogicalTime:n.localReplica.ackedLogicalTime,lastSyncedLogicalTime:n.localReplica.lastSyncedLogicalTime}),this.ctx.log("debug","Resetting metadata from export",n),await this.insertData({operations:n.operations,baselines:n.baselines,isLocal:!0})};this.manualRebase=async()=>{if(this.ctx.closing||this.ctx.config.persistence?.disableRebasing)return;let n=await this.db.getAckInfo();n.globalAckTimestamp&&await this.rebaser.scheduleRebase(n.globalAckTimestamp)};this.ack=async n=>{let e=await this.getLocalReplica();n>this.ctx.time.now||(this.events.emit("syncMessage",{type:"ack",replicaId:e.id,timestamp:n}),!this.ctx.closing&&(!e.ackedLogicalTime||n>e.ackedLogicalTime)&&this.updateLocalReplica({ackedLogicalTime:n}))};this.rebaser=new Dn(n,this,e),this.messageCreator=new Cn(n,this,e)}};var An=class{constructor(n,e){this.db=n;this.ctx=e;this.reset=this.db.reset.bind(this.db);this.close=this.db.close.bind(this.db);this.saveEntities=async(n,e)=>{if(n.length===0)return;let t=new Set(Object.keys(this.ctx.schema.collections)),r=[],s=n.filter(o=>{let{collection:a}=le(o.oid);return t.has(a)?(r.includes(a)||r.push(a),!0):(this.ctx.log("warn",`Entity ${o.oid} is in a collection that no longer exists in the schema. It will not be saved.`),!1)});if(r.length!==0){this.ctx.log("debug","Saving",s.length,"entities"),await this.db.saveEntities(s,{abort:e?.abort,collections:r}),this.ctx.log("debug","Saved",s.length,"entities"),this.ctx.entityEvents.emit("collectionsChanged",r);for(let o of n)this.ctx.entityEvents.emit("documentChanged",o.oid)}};this.findOneOid=this.db.findOneOid.bind(this.db);this.findAllOids=this.db.findAllOids.bind(this.db);this.stats=this.db.stats.bind(this.db)}};async function kt(i){let n=i;if(i.schema.wip&&(n.namespace=Js(i.originalNamespace,i.schema),n.log("info","Switched to WIP namespace",n.namespace),!(await n.persistence.getNamespaces()).includes(n.namespace))){let r=await n.persistence.getNamespaceVersion(n.originalNamespace);if(r===0)n.log("debug","No existing data to copy to WIP namespace");else{let s=i.oldSchemas?.find(o=>o.version===r);if(!s)throw new H(H.Code.MigrationPathNotFound,void 0,`Trying to open WIP database for version ${i.schema.version}, but the current local data is version ${r} and a historical schema for that version is not available.`);n.log("info",`Copying data from ${n.originalNamespace} to ${n.namespace}`),await n.persistence.copyNamespace(n.originalNamespace,n.namespace,{...n,schema:s})}}let e=await i.persistence.openNamespace(n.namespace,n);if(n.log("info","Opening persistence metadata"),n.meta=new Pn(await e.openMetadata(i),i),n.log("info","Opening persistence files"),n.files=new En(await e.openFiles(n),n),n.log("info","Migrating document database"),await Zs({context:n,version:i.schema.version}),n.log("info","Opening persistence documents"),n.documents=new An(await e.openDocuments(n),n),!i.schema.wip){let t=await i.persistence.getNamespaces();for(let r of t)r.startsWith("@@wip_")&&(i.log("debug","Cleaning up old WIP namespace",r),await i.persistence.deleteNamespace(r,i))}return n}async function to(i,n){i.log("info","Importing data from export");let e=i.oldSchemas?.find(a=>a.version===n.data.schemaVersion);if(!e)throw new Error(`Could not find schema for version ${n.data.schemaVersion}`);let t=`@@import_${Date.now()}`,r=await kt({...i,schema:e,namespace:t,originalNamespace:t,entityEvents:new V,internalEvents:new V,globalEvents:new V,config:{...i.config,persistence:{...i.config.persistence,disableRebasing:!0}},persistenceShutdownHandler:new Pe(i.log)});await r.meta.resetFrom(n.data);let s=new Set;for(let a of n.data.baselines)s.add(z(a.oid));for(let a of n.data.operations)s.add(z(a.oid));let o=await Promise.all(Array.from(s).map(async a=>{let f=await r.meta.getDocumentSnapshot(a);return{oid:a,getSnapshot:()=>f}}));if(await r.documents.saveEntities(o),await r.files.import(n),i.log("debug","Imported data into temporary namespace",t),await r.persistenceShutdownHandler.shutdown(),e.version!==i.schema.version){let a=i.schema,f=await kt({...r,persistenceShutdownHandler:new Pe(i.log),schema:a});i.log("debug","Upgraded imported data to current schema"),await f.persistenceShutdownHandler.shutdown(),i.log("debug","Shut down upgraded databases")}if(await i.persistenceShutdownHandler.shutdown(),await i.persistence.copyNamespace(t,i.namespace,i),await kt(i),n.data.schemaVersion===i.schema.version){let a=await i.meta.stats();if(a.operationsSize.count!==n.data.operations.length)throw i.log("critical","Imported operations count mismatch","expected",n.data.operations.length,"actual",a.operationsSize.count),new H(H.Code.ImportFailed,void 0,"Imported operations count mismatch");if(a.baselinesSize.count!==n.data.baselines.length)throw i.log("critical","Imported documents count mismatch","expected",n.data.baselines.length,"actual",a.baselinesSize.count),new H(H.Code.ImportFailed,void 0,"Imported documents count mismatch")}i.log("debug","Data copied to primary namespace"),await i.persistence.deleteNamespace(t,i),i.log("debug","Deleted temporary namespace"),i.internalEvents.emit("persistenceReset"),i.log("info","Data imported successfully"),i.persistenceShutdownHandler.reset()}function Ua(i){return i!==null}function Ki(i){return Array.isArray(i)?i.map(Ki).filter(Ua):i instanceof de&&i.deleted?null:i}function je(i,n){return!i&&!n||i&&n&&Ve(i)===Ve(n)}var qi=Symbol("ON_ALL_UNSUBSCRIBED"),ue=Symbol("UPDATE"),Va,pe=class extends re{constructor({initial:e,context:t,collection:r,key:s,shouldUpdate:o}){super();this._internalUnsubscribes=[];this._status="initial";this._executionPromise=null;this.setValue=e=>{this._rawValue=e,this.subscribeToDeleteAndRestore(this._rawValue);let t=Ki(e),r=!0;this.status==="initializing"||this.status==="initial"?r=!0:this.isListQuery?this._value.length===t.length&&this._value.every((s,o)=>s===t[o])&&(r=!1):this._value===t&&(r=!1),this._value=t,r&&(this.context.log("debug","Query value changed",this.key),this._events.emit("change",this._value)),this.status="ready"};this.refreshValue=()=>{this.setValue(this._rawValue)};this.subscribeToDeleteAndRestore=e=>{for(;this._internalUnsubscribes.length;)this._internalUnsubscribes.pop()?.();Array.isArray(e)?e.forEach(t=>{t instanceof de&&(this._internalUnsubscribes.push(t.subscribe("delete",this.refreshValue)),this._internalUnsubscribes.push(t.subscribe("restore",this.refreshValue)))}):e instanceof de&&(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[Va]=e=>{this._allUnsubscribedHandler=e};this._rawValue=e,this._value=e,this.isListQuery=Array.isArray(e),this._events=new V(f=>{f==="change"&&this._allUnsubscribedHandler?.(this)}),this.context=t,this.key=s,this.collection=r;let a=o||(f=>f.includes(r));this.addDispose(this.context.entityEvents.subscribe("collectionsChanged",f=>{a(f)&&(this.context.log("info","Updating query",this.key),this.execute())}))}static{Va=qi}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}set status(e){this._status!==e&&(this._status=e,this._events.emit("statusChange",this._status))}get hasDeleted(){return this.isListQuery?this._rawValue.length!==this._value.length:!!this._rawValue&&!this._value}subscribe(e,t){if(t===void 0&&typeof e=="function")return this.resolved,this._events.subscribe("change",e);if(e==="change"&&t!==void 0)return this.resolved,this._events.subscribe("change",t);if(e==="statusChange"&&typeof t=="function")return this._events.subscribe(e,t);throw new Error("Invalid invocation of Query.subscribe")}get __rawValue(){return this._rawValue}};var Rn=class extends pe{constructor({id:e,hydrate:t,...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=t}};var Na,Fn=class extends pe{constructor({index:e,hydrate:t,...r}){super({initial:null,...r});this.run=async()=>{let e=await this.context.documents.findOneOid({collection:this.collection,index:this.index});this.setValue(e?await this.hydrate(e):null)};this[Na]=e=>{je(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=t}static{Na=ue}};var za,Tn=class extends pe{constructor({index:e,hydrate:t,pageSize:r,page:s,...o}){super({initial:[],...o});this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:t}=await this.context.documents.findAllOids({collection:this.collection,index:this.index,limit:this._pageSize,offset:this._page*this._pageSize});this._hasNextPage=t,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[za]=e=>{je(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=t,this._pageSize=r,this._page=s}static{za=ue}get pageSize(){return this._pageSize}get page(){return this._page}get hasNextPage(){return this._hasNextPage}get hasPreviousPage(){return this._page>0}};var $a,kn=class extends pe{constructor({hydrate:e,pageSize:t,index:r,...s}){super({initial:[],...s});this._upToPage=1;this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:t}=await this.context.documents.findAllOids({collection:this.collection,limit:this._pageSize*this._upToPage,offset:0,index:this.index});this._hasNextPage=t,this.setValue(await Promise.all(e.map(this.hydrate)))};this.loadMore=async()=>{let{result:e,hasNextPage:t}=await this.context.documents.findAllOids({collection:this.collection,limit:this._pageSize,offset:this._pageSize*this._upToPage,index:this.index});this._hasNextPage=t,this._upToPage++,this.setValue([...this.current,...await Promise.all(e.map(this.hydrate))])};this[$a]=e=>{je(this.index,e)||(this.index=e,this.execute())};this.index=r,this.hydrate=e,this._pageSize=t}static{$a=ue}get pageSize(){return this._pageSize}get hasMore(){return this._hasNextPage}};var Ka,Bn=class extends pe{constructor({index:e,hydrate:t,...r}){super({initial:[],...r});this.run=async()=>{let{result:e}=await this.context.documents.findAllOids({collection:this.collection,index:this.index});this.context.log("debug",`FindAllQuery: ${e.length} oids found: ${e}`),this.setValue(await Promise.all(e.map(this.hydrate)))};this[Ka]=e=>{je(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=t}static{Ka=ue}};var Ln=class{constructor({collection:n,cache:e,entities:t,context:r,documentManager:s}){this.serializeIndex=n=>n?Ve(n):"";this.get=n=>{let e=`get:${this.collection}:${n}`;return this.cache.getOrSet(e,()=>new Rn({id:n,collection:this.collection,hydrate:this.hydrate,context:this.context,key:e}))};this.findOne=({index:n,key:e}={})=>{let t=e||`findOne:${this.collection}:${this.serializeIndex(n)}`;return this.cache.getOrSet(t,()=>new Fn({index:n,collection:this.collection,hydrate:this.hydrate,context:this.context,key:t}),r=>{r[ue](n)})};this.findAll=({index:n,key:e}={})=>{let t=e||`findAll:${this.collection}:${this.serializeIndex(n)}`;return this.cache.getOrSet(t,()=>new Bn({index:n,collection:this.collection,hydrate:this.hydrate,context:this.context,key:t}),r=>{r[ue](n)})};this.findPage=({index:n,pageSize:e,page:t,key:r})=>{let s=r||`findPage:${this.collection}:${this.serializeIndex(n)}:${e}`;return this.cache.getOrSet(s,()=>new Tn({index:n,collection:this.collection,hydrate:this.hydrate,context:this.context,key:s,pageSize:e,page:t}),o=>{o[ue](n)})};this.findAllInfinite=({index:n,pageSize:e,key:t})=>{let r=t||`findAllInfinite:${this.collection}:${this.serializeIndex(n)}:${e}`;return this.cache.getOrSet(r,()=>new kn({index:n,collection:this.collection,hydrate:this.hydrate,context:this.context,key:r,pageSize:e}),s=>{s[ue](n)})};this.cache=e,this.collection=n,this.hydrate=t.hydrate,this.context=r,this.documentManager=s,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),this.clone=this.documentManager.clone.bind(this.documentManager,this.collection)}};var jn=class extends re{constructor({evictionTime:e=5*1e3,context:t}){super();this._cache=new Map;this._holds=new Set;this.enqueueQueryEviction=e=>{setTimeout(()=>{if(!e.subscribed){if(this._holds.has(e.key)){this.context.log("debug","QueryCache: keepAlive hold on query preserves after unsubscribe",e.key);return}this._cache.get(e.key)===e&&(this._cache.delete(e.key),this.context.log("debug","QueryCache: evicted query",e.key))}},this._evictionTime)};this.dropAll=()=>{this.context.log("debug","QueryCache: drop all",this._cache.size,"queries"),this._cache.forEach(e=>e.dispose()),this._cache.clear()};this.forceRefreshAll=()=>{this.context.log("debug","QueryCache: force refresh all",this._cache.size,"queries"),this._cache.forEach(e=>e.execute())};this._evictionTime=e,this.context=t,this.addDispose(this.context.internalEvents.subscribe("persistenceReset",this.forceRefreshAll))}get activeKeys(){return Array.from(this._cache.keys())}get(e){return this._cache.get(e)||null}set(e){return this._cache.set(e.key,e),e[qi](this.enqueueQueryEviction),this.enqueueQueryEviction(e),e}getOrSet(e,t,r){let s=this.get(e);return s?(r?.(s),s):(this.context.log("debug","QueryCache: creating new query",e),this.set(t()))}keepAlive(e){this._holds.add(e),this.context.log("debug","QueryCache: keepAlive",e)}dropKeepAlive(e){this._holds.delete(e);let t=this.get(e);t&&(t.subscribed||(this.context.log("debug","QueryCache: dropKeepAlive on unsubscribed query; queuing eviction",e),this.enqueueQueryEviction(t)))}get keepAlives(){return this._holds}};var Hi=Symbol("handleMessage"),qa,Bt=class extends V{constructor({initialPresence:e,updateBatchTimeout:t=200,defaultProfile:r,ctx:s}){super();this._peers={};this._self={profile:{}};this._selfReplicaIds=new Set;this._peerIds=new Array;this.isSelf=(e,t)=>e.id===t.replicaId||this._selfReplicaIds.has(t.replicaId)||this._self.id===t.id;this[qa]=async(e,t)=>{let r=!1,s=!1,o=new Set(this.peerIds);if(t.type==="presence-changed")this.isSelf(e,t.userInfo)?(this._self=t.userInfo,this._selfReplicaIds.add(t.userInfo.replicaId),s=!0,this.emit("selfChanged",t.userInfo)):(o.add(t.userInfo.id),this._peers[t.userInfo.id]=t.userInfo,r=!0,this.emit("peerChanged",t.userInfo.id,t.userInfo));else if(t.type==="sync-resp"){this._peers={},o.clear();for(let[a,f]of Object.entries(t.peerPresence))this.isSelf(e,f)?(this._self=f,this._selfReplicaIds.add(f.replicaId),s=!0,this.emit("selfChanged",f)):(r=!0,o.add(a),this._peers[a]=f,this.emit("peerChanged",a,f))}else if(t.type==="presence-offline"){o.delete(t.userId),this._selfReplicaIds.delete(t.replicaId);let a=this._peers[t.userId];delete this._peers[t.userId],r=!0,this.emit("peerLeft",t.userId,a)}r&&(this._peerIds=Array.from(o).sort(),this.emit("peersChanged",this._peers)),(r||s)&&this.emit("change")};this.update=async e=>{this._updateBatch.update({items:[{presence:e}]}),this.self.presence={...this.self.presence,...e},this.emit("selfChanged",this.self),this.emit("change")};this.flushPresenceUpdates=e=>{let t={presence:this.self.presence,internal:this.self.internal};for(let r of e)r.presence&&Object.assign(t.presence,r.presence),r.internal&&Object.assign(t.internal,r.internal);this.emit("update",t)};this.setViewId=e=>{this._updateBatch.update({items:[{internal:{viewId:e}}]}),this.self.internal.viewId=e,this.emit("selfChanged",this.self),this.emit("change")};this.setFieldId=(e,t=Date.now())=>{this._updateBatch.update({items:[{internal:{lastFieldId:e,lastFieldTimestamp:t}}]}),this.self.internal.lastFieldId=e,this.emit("selfChanged",this.self),this.emit("change")};this.getViewPeers=()=>this._peerIds.map(e=>this._peers[e]).filter(e=>this.self.internal.viewId===void 0||e.internal.viewId===this.self.internal.viewId);this.getFieldPeers=(e,t=60*1e3)=>this._peerIds.map(r=>this._peers[r]).filter(r=>r.internal.lastFieldId===e&&Date.now()-r.internal.lastFieldTimestamp<t);this.self.presence=e,this.self.profile=r,this.self.internal=fi,this.self.id="",this.self.replicaId="",s.meta.getLocalReplica().then(o=>{this.self.replicaId=o.id}),this._updateBatcher=new Ye(this.flushPresenceUpdates),this._updateBatch=this._updateBatcher.add({max:25,timeout:t,items:[],key:"default"})}static{qa=Hi}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 Mn=class extends re{constructor({endpointProvider:e,ctx:t}){super();this.onFileAdded=async e=>{if(!e.remote){this.ctx.log("debug","Uploading file",e.id,e.name);try{await this.uploadFile(e)}catch(t){this.ctx.log("error","File upload failed",t)}}};this.uploadFile=async(e,t={current:0,max:3})=>{let r=e.file;if(!r)throw new Error("Cannot upload a non-local file");let{files:s,token:o}=await this.endpointProvider.getEndpoints(),a=new FormData;a.append("file",r);try{let f=await this.ctx.environment.fetch(s+`/${e.id}`,{method:"POST",body:a,credentials:"include",headers:{Authorization:`Bearer ${o}`}});if(f.ok)return this.ctx.internalEvents.emit(`fileUploaded:${e.id}`,e),this.ctx.internalEvents.emit("fileUploaded",e),this.ctx.log("info","File upload successful"),{success:!0};{let p=await f.text();return this.ctx.log("error","File upload failed",f.status,p),f.status<500||t.current>=t.max?{success:!1,error:`Failed to upload file: ${f.status} ${p}`}:(await new Promise(y=>setTimeout(y,1e3)),this.uploadFile(e,{max:t.max,current:t.current+1}))}}catch(f){return this.ctx.log("error","File upload failed",f),t.current>=t.max?{success:!1,error:f.message}:(await new Promise(p=>setTimeout(p,1e3)),this.uploadFile(e,{max:t.max,current:t.current+1}))}};this.getFile=async(e,t={current:0,max:3})=>{let{files:r,token:s}=await this.endpointProvider.getEndpoints();try{let o=await this.ctx.environment.fetch(r+`/${e}`,{method:"GET",credentials:"include",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`}});return o.ok?{success:!0,data:await o.json()}:(this.ctx.log("error","File information fetch failed",o.status,await o.text()),o.status<500&&o.status!==404||t.current>=t.max?{success:!1,error:`Failed to fetch file: ${o.status}`}:(await new Promise(a=>setTimeout(a,1e3)),this.getFile(e,{current:t.current+1,max:t.max})))}catch(o){return this.ctx.log("error","File information fetch failed",o),t.current>=t.max?{success:!1,error:o.message}:(await new Promise(a=>setTimeout(a,1e3)),this.getFile(e,{current:t.current+1,max:t.max}))}};this.endpointProvider=e,this.ctx=t,this.addDispose(t.internalEvents.subscribe("fileAdded",this.onFileAdded))}};var lt=class extends V{constructor({interval:e=15*1e3,deadlineLength:t=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=t,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 Un=class extends V{constructor({endpointProvider:e,presence:t,interval:r=15*1e3,ctx: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.ctx.log("debug","Sending sync request",e);try{let{http:t,token:r}=await this.endpointProvider.getEndpoints(),s=await this.fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({messages:e}),credentials:"include"});if(s.ok){this.heartbeat.keepAlive();let o=await s.json(),a=Promise.all(o.messages.map(this.handleServerMessage));this._isConnected||(this._isConnected=!0,this.emit("onlineChange",!0)),await a}else{this.ctx.log("error","Sync request failed",s.status,await s.text()),this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1));let o=await s.json();lr(o)&&o.code===pt.TokenExpired&&(this.endpointProvider.clearCache(),this.heartbeat.keepAlive()),s.status>=500&&this.heartbeat.keepAlive()}}catch(t){this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1)),this.ctx.log("error",t),this.heartbeat.keepAlive()}};this.handleServerMessage=async e=>{e.type==="sync-resp"&&(this._hasSynced=!0,e.ackThisNonce&&(this.ctx.log("debug","Sending sync ack",e.ackThisNonce),await this.sendRequest([await this.ctx.meta.messageCreator.createAck(e.ackThisNonce)]))),this.emit("message",e)};this.throttledPresenceUpdate=wr(e=>{this.sendRequest([e])},3e3);this.send=e=>{switch(e.type){case"presence-update":return this.throttledPresenceUpdate(e);case"sync":case"heartbeat":return this.sendRequest([e]);case"op":if(this._hasSynced)return this.sendRequest([e]);break}};this.start=async()=>{this.status!=="active"&&(await this.endpointProvider.getEndpoints(),this.heartbeat.start(!0),this._status="active")};this.destroy=()=>{this.dispose(),this.stop()};this.onHeartbeat=async()=>{this.sendRequest([await this.ctx.meta.messageCreator.createPresenceUpdate(this.presence.self),await this.ctx.meta.messageCreator.createSyncStep1()])};this.onHeartbeatMissed=async()=>{this.emit("onlineChange",!1),this.ctx.log("warn","Missed heartbeat"),this._isConnected=!1};this.syncOnce=async()=>{await this.sendRequest([await this.ctx.meta.messageCreator.createSyncStep1()])};this.ctx=s,this.presence=t,this.endpointProvider=e,this.heartbeat=new lt({interval:r}),this.heartbeat.subscribe("beat",this.onHeartbeat),this.heartbeat.subscribe("missed",this.onHeartbeatMissed)}get fetch(){return this.ctx.environment.fetch}get interval(){return this.heartbeat.interval}get hasSynced(){return this._hasSynced}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 Qi(i){this.message=i}Qi.prototype=new Error,Qi.prototype.name="InvalidCharacterError";var no=typeof window<"u"&&window.atob&&window.atob.bind(window)||function(i){var n=String(i).replace(/=+$/,"");if(n.length%4==1)throw new Qi("'atob' failed: The string to be decoded is not correctly encoded.");for(var e,t,r=0,s=0,o="";t=n.charAt(s++);~t&&(e=r%4?64*e+t:t,r++%4)?o+=String.fromCharCode(255&e>>(-2*r&6)):0)t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(t);return o};function Ha(i){var n=i.replace(/-/g,"+").replace(/_/g,"/");switch(n.length%4){case 0:break;case 2:n+="==";break;case 3:n+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(no(e).replace(/(.)/g,function(t,r){var s=r.charCodeAt(0).toString(16).toUpperCase();return s.length<2&&(s="0"+s),"%"+s}))}(n)}catch{return no(n)}}function Vn(i){this.message=i}function Qa(i,n){if(typeof i!="string")throw new Vn("Invalid token specified");var e=(n=n||{}).header===!0?0:1;try{return JSON.parse(Ha(i.split(".")[e]))}catch(t){throw new Vn("Invalid token specified: "+t.message)}}Vn.prototype=new Error,Vn.prototype.name="InvalidTokenError";var io=Qa;var Nn=class{constructor(n,e){this.config=n;this.ctx=e;this.cached=null;this.tokenInfo=null;this.getEndpoints=async()=>{if(this.cached)return this.cached;let n;if(this.config.fetchAuth)n=await this.config.fetchAuth();else{let a=this.ctx.environment.fetch;n=await a(this.config.authEndpoint,{credentials:"include"}).then(f=>{if(f.ok)return f.json();throw new Error(`Auth endpoint returned non-200 response: ${f.status}`)})}N(n.accessToken,"No access token provided from auth endpoint");let e=io(n.accessToken);N(e.url,"No sync endpoint provided from auth endpoint"),N(e.type!==void 0,"No replica type provided from auth endpoint"),this.tokenInfo={userId:e.sub,libraryId:e.lib,url:e.url,fileUrl:e.file,role:e.role,type:parseInt(e.type+"")};let t=new URL(e.url);t.protocol=t.protocol.replace("ws","http");let r=t.toString();t.protocol=t.protocol.replace("http","ws");let s=t.toString(),o=e.file;if(!o){let a=new URL(r);a.pathname=a.pathname+"/files",o=a.toString()}return this.cached={http:r,websocket:s,files:o,token:n.accessToken},this.cached};this.clearCache=()=>{this.cached=null};if(!n.authEndpoint&&!n.fetchAuth)throw new Error("Either authEndpoint or fetchAuth must be provided to ServerSyncEndpointProvider")}get type(){return this.tokenInfo?.type??Be.Realtime}};var zn=class extends V{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}},$n=class{constructor(n,e){this.current=0;this.next=()=>{this.current=Math.min(this.max,this.current*this.factor)};this.reset=()=>{this.current=0};this.max=n,this.factor=e}};var Kn=class extends V{constructor({endpointProvider:e,ctx:t,presence:r}){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.heartbeat=new lt;this.reconnectScheduler=new zn(new $n(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.ctx.log("debug","Sending queued message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e));this.connectQueue=[]}this.ctx.log("debug","Sync connected"),this.onOnlineChange(!0),this.reconnectScheduler.reset()};this.onOnlineChange=async e=>{this.ctx.log("info","Socket online change",e),!this.disposed&&(this.ctx.closing||(e?(this.ctx.log("debug","Starting sync"),this.hasStartedSync=!0,this.synced=!1,this.send(await this.ctx.meta.messageCreator.createPresenceUpdate(this.presence.self)),this.send(await this.ctx.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.ctx.log("warn","Ignoring incoming message (ignore incoming flag set)",e.data);return}let t=JSON.parse(e.data);switch(t.type){case"sync-resp":if(t.ackThisNonce&&this.send(await this.ctx.meta.messageCreator.createAck(t.ackThisNonce)),this.hasStartedSync=!0,this.synced=!0,this.syncQueue.length)if(t.overwriteLocalData)this.ctx.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",t),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",t);break;case"op-re":if(!this.synced){this.ctx.log("debug","Enqueueing op-re message because sync hasn't finished yet",t),this.incomingQueue.push(t);break}this.emit("message",t);break;case"heartbeat-response":this.heartbeat.keepAlive(),this.emit("message",t);break;default:this.synced&&this.emit("message",t);break}};this.onError=e=>{this.ctx.log("error",e),this.reconnectScheduler.next(),this.ctx.log("info","Attempting reconnect to websocket sync")};this.onClose=e=>{this.ctx.log("info","Sync disconnected"),this.onOnlineChange(!1),this.onError(e)};this.initializeSocket=async()=>{let e=await this.endpointProvider.getEndpoints();return this.socket=new this.ctx.environment.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.ctx.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===Wi?(this.ctx.log("debug","Sending message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e))):(this.ctx.log("debug","Enqueueing message until socket is open",JSON.stringify(e,null,2)),this.connectQueue.push(e)):this.synced?this.socket?.readyState===Wi&&(this.ctx.log("debug","Sending message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e))):this.hasStartedSync&&(this.ctx.log("debug","Enqueueing message until synced",JSON.stringify(e,null,2)),this.syncQueue.push(e))))};this.destroy=()=>{this.dispose(),this.stop()};this.start=async()=>{this.socket||(await 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.ctx=t,this.endpointProvider=e,this.presence=r,this.reconnectScheduler.subscribe("trigger",this.initializeSocket),this.heartbeat.subscribe("beat",this.sendHeartbeat)}get hasSynced(){return this.synced}ignoreIncoming(){this.incomingQueue=[],this._ignoreIncoming=!0}get isConnected(){return this.socket?.readyState===Wi}get status(){return this._status}},Wi=1;async function ro(){try{let i=await navigator.permissions.query({name:"periodic-background-sync"});if(i.state==="granted"){let n=await navigator.serviceWorker.ready;if("periodicSync"in n)try{await n.periodicSync.register("verdant-sync",{minInterval:24*60*60*1e3})}catch(e){console.warn("Failed to register background sync:",e)}}else console.debug("Background sync permission is not granted:",i)}catch(i){console.error("Failed to initiate background sync:",i)}}var qn=class extends V{constructor(e){super();this.mode="pull";this.hasSynced=!1;this.destroy=()=>{};this.isConnected=!1;this.status="paused";this.pullInterval=0;this.uploadFile=async()=>({success:!1,retry:!1});this.getFile=async()=>({success:!1,error:"Sync is not active"});this.syncOnce=async()=>{};this.presence=new Bt({initialPresence:null,defaultProfile:null,ctx:e})}send(){}async start(){}stop(){}ignoreIncoming(){}reconnect(){}setMode(){}setPullInterval(){}},dt=class extends V{constructor({authEndpoint:e,fetchAuth:t,initialPresence:r,automaticTransportSelection:s=!0,autoStart:o,initialTransport:a,pullInterval:f,presenceUpdateBatchTimeout:p,defaultProfile:y,useBroadcastChannel:D,onOutgoingMessage:w,EXPERIMENTAL_backgroundSync:A},{ctx:g,onData:I}){super();this.broadcastChannel=null;this._activelySyncing=!1;this._hasSynced=!1;this.handleBroadcastChannelMessage=e=>{e.data.type==="sync"&&this.handleMessage(e.data.message,{source:"broadcastChannel"})};this.handleMessage=async(e,{source:t}={source:"network"})=>{if(!this.ctx.closing){if(e.type==="op-re"||e.type==="sync-resp")for(let r of e.operations)this.ctx.time.update(r.timestamp);switch(this.ctx.log("debug","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.ctx.meta.setGlobalAck(e.globalAckTimestamp);break;case"global-ack":await this.ctx.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.ctx.meta.setGlobalAck(e.globalAckTimestamp),await this.ctx.meta.updateLastSynced(e.ackedTimestamp),this._activelySyncing=!1,this.emit("syncingChange",!1),this._hasSynced=!0,this.emit("synced");break;case"need-since":this.emit("serverReset",e.since),this.ctx.files.onServerReset(e.since),this.activeSync.send(await this.ctx.meta.messageCreator.createSyncStep1(e.since));break;case"server-ack":await this.ctx.meta.updateLastSynced(e.timestamp)}t==="network"&&this.broadcastChannel?.postMessage({type:"sync",message:e}),this.presence[Hi](await this.ctx.meta.getLocalReplica(),e)}};this.handleOnlineChange=async e=>{if(this.emit("onlineChange",e),e){let t=await this.ctx.files.listUnsynced(),r=await Promise.allSettled(t.map(s=>this.fileSync.uploadFile(s)));r.some(s=>s.status==="rejected")&&this.ctx.log("error","Failed to upload unsynced files",r.filter(s=>s.status==="rejected").map(s=>s.reason))}};this.handlePresenceUpdate=async e=>{this.send(await this.ctx.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 t;e==="realtime"?t=this.webSocketSync:t=this.pushPullSync,t!==this.activeSync&&(this.ctx.log("debug","switching to",e,"mode"),this.activeSync.status==="active"&&t.start(),this.activeSync.stop(),this.activeSync=t)};this.setPullInterval=e=>{this.pushPullSync.setInterval(e)};this.send=async e=>{if(this.activeSync.status==="active"){let t=this.endpointProvider.tokenInfo?.userId;if(!t)throw new H(H.Code.Unexpected,void 0,"Active sync has invalid token info");(e.type==="sync"||e.type==="op")&&cr(e,t),await this.activeSync.send(e),this.onOutgoingMessage?.(e)}};this.uploadFile=async e=>(this.ctx.log("info","Uploading file",{name:e.name,type:e.type,id:e.id,size:e.file?.size}),this.activeSync.status==="active"?this.fileSync.uploadFile(e):{success:!1,retry:!1,error:"Sync is not active"});this.getFile=async e=>{if(this.activeSync.status==="active")return this.fileSync.getFile(e);if(await this.getSyncStartPromise(),this.activeSync.status==="paused")throw new H(H.Code.Offline,void 0,"Sync is not active");return this.fileSync.getFile(e)};this.getSyncStartPromise=(e=5e3)=>new Promise((t,r)=>{let s=setTimeout(()=>{r(new Error("Sync did not start in time")),o()},e),o=this.subscribe("onlineChange",a=>{a&&(clearTimeout(s),o(),t())})});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();this.syncOnce=()=>this.pushPullSync.syncOnce();if(this.onData=I,this.ctx=g,this.onOutgoingMessage=w,this.presence=new Bt({initialPresence:r,defaultProfile:y,updateBatchTimeout:p,ctx:g}),this.endpointProvider=new Nn({authEndpoint:e,fetchAuth:t},g),this.webSocketSync=new Kn({endpointProvider:this.endpointProvider,presence:this.presence,ctx:g}),this.pushPullSync=new Un({endpointProvider:this.endpointProvider,presence:this.presence,interval:f,ctx:g}),this.fileSync=new Mn({endpointProvider:this.endpointProvider,ctx:g}),D&&"BroadcastChannel"in window&&(this.broadcastChannel=new BroadcastChannel(`verdant-${g.namespace}`),this.broadcastChannel.addEventListener("message",this.handleBroadcastChannelMessage)),a==="realtime"?this.activeSync=this.webSocketSync:this.activeSync=this.pushPullSync,this.presence.subscribe("update",this.handlePresenceUpdate),g.meta.events.subscribe("syncMessage",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 E=()=>{O&&clearTimeout(O);let k=this.presence.getViewPeers().length>0||s!=="peers-only"&&this.presence.selfReplicaIds.size>1;k&&this.mode==="pull"?this.setMode("realtime"):!k&&this.mode==="realtime"&&(O=setTimeout(()=>{this.presence.getViewPeers().length===0&&this.setMode("pull")},1e3))},O;this.presence.subscribe("peersChanged",E),s!=="peers-only"&&this.presence.subscribe("selfChanged",E)}o&&this.start(),A&&ro()}get canDoRealtime(){return this.endpointProvider.type===Be.Realtime||this.endpointProvider.type===Be.PassiveRealtime||this.endpointProvider.type===Be.ReadOnlyRealtime}get syncing(){return this._activelySyncing}get hasSynced(){return this._hasSynced}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 so(i){return i.operations.map(t=>t.timestamp).concat(i.baselines?.map(t=>t.timestamp)??[]).reduce((t,r)=>{let s=on(r);return s>t?s:t},0)}var ut=class extends V{constructor(e){super();this.context=e;this.importingPromise=Promise.resolve();this.addData=async e=>{await this.importingPromise;try{let t=e.reset?so(e):this.schema.version;return t<this.schema.version?(this.context.log("warn","Incoming reset sync data is from an old schema version",t,`(current ${this.schema.version})`),await this.import({data:{operations:e.operations,baselines:e.baselines??[],localReplica:void 0,schemaVersion:t},fileData:[],files:[]})):await this._entities.addData(e)}catch(t){throw this.context.log("critical","Sync failed",t),this.emit("developerError",new Error("Sync failed, see logs or cause",{cause:t})),t}};this.stats=async()=>{if(this.disposed)return{};let e=await this.context.documents.stats(),t=await this.context.meta.stats(),r=typeof navigator<"u"&&typeof navigator.storage<"u"&&"estimate"in navigator.storage?await navigator.storage.estimate():void 0,s=await this.context.files.stats(),o=Object.values(e).reduce((p,{size:y})=>p+y,0),a=t.baselinesSize.size+t.operationsSize.size,f=a/o;return{collections:e,meta:t,storage:r,totalMetaSize:a,totalCollectionsSize:o,metaToDataRatio:f,files:s,quotaUsage:r?.usage&&r?.quota?r.usage/r.quota:void 0}};this.close=async()=>{this.sync.ignoreIncoming(),await this._entities.flushAllBatches(),this.context.closing=!0,this.context.closeLock&&await this.context.closeLock,this.sync.stop(),this.sync.destroy(),await this._entities.destroy(),this.context.persistenceShutdownHandler.shutdown(),this.context.internalEvents.disable(),this.context.entityEvents.disable(),await new Promise(e=>{e()}),this.context.log?.("info","Client closed")};this.__dangerous__resetLocal=async()=>{this.sync.stop(),await In(this.namespace,indexedDB)};this.export=async({downloadRemoteFiles:e}={downloadRemoteFiles:!0})=>{this.context.log("info","Exporting data...");let t=await this.context.meta.export(),{fileData:r,files:s}=await this.context.files.export(e);return{data:t,fileData:r,files:s}};this.import=async({data:e,fileData:t,files:r})=>{let s=()=>{};this.importingPromise=new Promise(o=>{s=o}),this.context.log("info","Importing data..."),await to(this.context,{data:e,files:r,fileData:t}),s()};this.__dangerous__hardReset=async()=>{let e=await this.export();await this.import(e)};this.__cleanupFilesImmediately=()=>this.context.files.cleanupDeletedFiles();this.__manualRebase=()=>(this.context.meta.manualRebase(),new Promise(e=>{let t=this.subscribe("rebase",()=>{t(),e()})}));e.getClient=()=>this,this.collectionNames=Object.keys(e.schema.collections),this._sync=this.context.config.sync&&!e.schema.wip?new dt(this.context.config.sync,{onData:this.addData,ctx:this.context}):new qn(this.context),e.schema.wip&&this.context.config.sync&&e.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 On({sync:this.sync,context:this.context}),this._entities=new xn({ctx:this.context,files:this._fileManager}),this._queryCache=new jn({context:e,evictionTime:e.config.queries?.evictionTime}),this._documentManager=new cn(this.schema,this._entities);let t=vr(()=>{this.emit("futureSeen")},300);this.context.globalEvents.subscribe("futureSeen",t),this.context.globalEvents.subscribe("resetToServer",()=>{this.emit("resetToServer")}),this.context.globalEvents.subscribe("operation",r=>{this.emit("operation",r)}),this.context.globalEvents.subscribe("rebase",()=>{this.emit("rebase")}),this.context.globalEvents.subscribe("fileSaved",r=>{this.emit("fileSaved",r)});for(let[r,s]of Object.entries(e.schema.collections)){let o=r;this[o]=new Ln({collection:o,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 schema(){return this.context.schema}get namespace(){return this.context.namespace}get undoHistory(){return this.context.undoHistory}get queries(){return this._queryCache}get batch(){return this.entities.batch}get __persistence(){return{meta:this.context.meta,queries:this.context.documents,files:this.context.files}}};var Hn=class{constructor(n,e){this.base=n;this.version=e;this.withMigrationTime=async(n,e)=>{this.overrideNow=()=>this.base.zero(n),await e(),this.overrideNow=void 0};this.update=this.base.update.bind(this.base);this.nowWithVersion=n=>this.base.now(n);this.zeroWithVersion=n=>this.base.zero(n)}get now(){return this.overrideNow?this.overrideNow():this.base.now(this.version)}get zero(){return this.base.zero(this.version)}};var Qn=class{constructor(n){this.value=n}deref(){return this.value}};var Me=class extends re{constructor(e,{log:t}={}){super();this.db=e;this.createTransaction=(e,t)=>{try{if(this.globalAbortController.signal.aborted)throw new Error("Global abort signal is already aborted");let r=Hs(this.db,e,t?.mode||"readonly",t?.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}catch(r){throw this.log?.("error","Failed to create abortable transaction for store names",e,r),r}};this.run=async(e,t,r)=>{if(this.disposed||r?.transaction?.error)return Promise.resolve(void 0);let o=(r?.transaction||this.createTransaction([e],r)).objectStore(e),a=t(o);return at(a)};this.runAll=async(e,t,r)=>{if(this.disposed||r?.transaction?.error)return Promise.resolve([]);let o=(r?.transaction||this.createTransaction([e],r)).objectStore(e),a=t(o);return Promise.all(a.map(at))};this.iterate=async(e,t,r,s)=>{let a=(s?.transaction||this.createTransaction([e],s)).objectStore(e),f=t(a);return Array.isArray(f)?Promise.all(f.map(p=>new Promise((y,D)=>{p.onsuccess=()=>{let w=p.result;w?r(w.value,a,w)?y():w.continue():y()},p.onerror=()=>{p.error&&Qe(p.error)?y():D(p.error)}}))).then(()=>{}):new Promise((p,y)=>{f.onsuccess=()=>{let D=f.result;D?r(D.value,a,D)?p():D.continue():p()},f.onerror=()=>{f.error&&Qe(f.error)?p():y(f.error)}})};this.clear=(e,t)=>this.run(e,r=>r.clear(),{mode:"readwrite",transaction:t});this.onVersionChange=e=>{if(this.log?.("warn",`Another tab has requested a version change for ${this.db.name}`),this.db.close(),typeof window<"u")try{window.location.reload()}catch(t){this.log?.("error","Failed to reload the page",t)}};this.log=t;let r=new AbortController,s=r.abort.bind(r);this.globalAbortController=r,this.db.addEventListener("versionchange",this.onVersionChange),this.addDispose(()=>{this.db.removeEventListener("versionchange",this.onVersionChange)})}};var Wn=class extends Me{constructor(){super(...arguments);this.add=async e=>{let t=e.file?await Ja(e.file):void 0;await this.run("files",r=>r.put({id:e.id,remote:e.remote?"true":"false",deletedAt:null,name:e.name,type:e.type,url:e.url,buffer:t,timestamp:e.timestamp}),{mode:"readwrite"})};this.markUploaded=async e=>{if(this.disposed)return;let t=await this.getFileRaw(e);if(!t)throw new Error("File is not in local database");await this.run("files",r=>r.put({...t,remote:"true"}),{mode:"readwrite"})};this.get=async e=>{let t=await this.getFileRaw(e);return t?this.hydrateFileData(t):null};this.delete=e=>this.run("files",t=>t.delete(e),{mode:"readwrite"});this.markPendingDelete=async e=>{let t=await this.getFileRaw(e);if(!t)throw new Error("File is not in local database");await this.run("files",r=>r.put({...t,deletedAt:Date.now()}),{mode:"readwrite"})};this.listUnsynced=async()=>(await this.run("files",t=>t.index("remote").getAll("false"),{mode:"readonly"})).map(this.hydrateFileData);this.resetSyncedStatusSince=async e=>{let t=this.createTransaction(["files"],{mode:"readwrite"}),s=(await this.run("files",o=>o.index("remote").getAll("true"),{transaction:t})).filter(o=>!o.timestamp||!e||o.timestamp>e);await Promise.all(s.map(o=>this.run("files",a=>a.put({...o,remote:"false"}),{transaction:t})))};this.iterateOverPendingDelete=e=>this.iterate("files",t=>t.index("deletedAt").openCursor(IDBKeyRange.lowerBound(0,!0)),(t,r)=>{e(this.hydrateFileData(t),r)},{mode:"readwrite"});this.getAll=async e=>{let[t]=await zi(this.db,["files"]);return t.map(this.hydrateFileData)};this.stats=async()=>({size:await We(this.db,"files")});this.loadFileContents=async(e,t)=>{if(e.file)return e.file;if(e.localPath)throw new Error("Local file paths are not supported in browser");if(e.url){let r=await t.environment.fetch(e.url);if(!r.ok)throw new Error(`Failed to download file ${e.url}: ${r.statusText}`);return r.blob()}throw new Error("File is missing url, file, and localPath")};this.hydrateFileData=e=>{e.remote=e.remote==="true";let t=e.buffer;return delete e.buffer,e.file=t?Wa(t,e.type,e.name):void 0,e};this.getFileRaw=async(e,{transaction:t}={})=>{if(this.disposed)return;let r=await this.run("files",s=>s.get(e),{mode:"readonly",transaction:t});if(r)return r}}};function Wa(i,n,e){return new File([new Blob([i],{type:n})],e??"blob",{type:n})}function Ja(i){return"__testReadBuffer"in i?Promise.resolve(i.__testReadBuffer):new Promise((n,e)=>{let t=new FileReader;t.onload=()=>{n(t.result)},t.onerror=e,t.readAsArrayBuffer(i)})}var Jn=class extends Me{constructor(e,t){super(e,t);this.ctx=t;this.transaction=async(e,t)=>{let r=this.createTransaction(e.storeNames,{mode:e.mode,abort:e.abort});return await t(r)};this.getAckInfo=async()=>{let e=await this.run("info",t=>t.get("ack"));return e||{globalAckTimestamp:null}};this.setGlobalAck=async e=>{await this.run("info",t=>t.put({type:"ack",globalAckTimestamp:e}),{mode:"readwrite"})};this.getLocalReplica=async e=>this.run("info",t=>t.get("localReplicaInfo"),e);this.updateLocalReplica=async(e,t)=>{try{await this.run("info",r=>r.put({...e,type:"localReplicaInfo"}),{mode:"readwrite",transaction:t?.transaction})}catch(r){throw this.ctx.log("critical","Error updating local replica",e,r),r}};this.iterateDocumentBaselines=async(e,t,r)=>{await this.iterate("baselines",s=>{let o=z(e),[a,f]=Rr(e),[p,y]=Fr(e);return[s.openCursor(IDBKeyRange.only(o)),s.openCursor(IDBKeyRange.bound(a,f,!1,!1)),s.openCursor(IDBKeyRange.bound(p,y,!1,!1))]},t,r)};this.iterateCollectionBaselines=async(e,t,r)=>{await this.iterate("baselines",s=>[s.openCursor(IDBKeyRange.bound(e,e+"\uFFFF",!1,!1))],t,r)};this.iterateAllBaselines=async(e,t)=>{await this.iterate("baselines",r=>r.index("timestamp").openCursor(),e,t)};this.getBaseline=(e,t)=>this.run("baselines",r=>r.get(e),t);this.setBaselines=async(e,t=Ji)=>{await this.runAll("baselines",r=>e.map(s=>r.put(s)),t)};this.deleteBaseline=async(e,t=Ji)=>{await this.run("baselines",r=>r.delete(e),t)};this.iterateDocumentOperations=(e,t,r)=>this.iterate("operations",s=>{let o=s.index("d_t"),a=xe(e),f=r?.to?fe(e,r.to):Ee(e),p=IDBKeyRange.bound(a,f,!1,!1);return o.openCursor(p)},t,r);this.iterateEntityOperations=(e,t,r)=>this.iterate("operations",s=>{let o=xe(e),a=r?.to?fe(e,r.to):Ee(e),f=IDBKeyRange.bound(o,a,!1,!1);return s.openCursor(f)},t,r);this.deleteEntityOperations=(e,t)=>this.iterate("operations",r=>{let s=xe(e),o=t?.to?fe(e,t.to):Ee(e),a=IDBKeyRange.bound(s,o,!1,!1);return r.openCursor(a)},(r,s)=>{s.delete(r.oid_timestamp)},t);this.iterateCollectionOperations=(e,t,r)=>this.iterate("operations",s=>s.openCursor(IDBKeyRange.bound(e,e+"\uFFFF",!1,!1),"next"),t,r);this.iterateLocalOperations=(e,t)=>this.iterate("operations",r=>{let s=t?.after?fe(!0,t.after):xe(!0),o=Ee(!0);return r.index("l_t").openCursor(IDBKeyRange.bound(s,o,!!t?.after,!1),"next")},e);this.iterateAllOperations=(e,t)=>this.iterate("operations",r=>{let s=t?.from?xe(t.from):void 0,o=t?.before?Ee(t.before):xe(!0),a=s&&o?IDBKeyRange.bound(s,o,!1,!0):s?IDBKeyRange.lowerBound(s,!1):o?IDBKeyRange.upperBound(o,!0):void 0;return r.index("timestamp").openCursor(a,"next")},e,t);this.addOperations=async(e,t=Ji)=>{let r=new Set;return await this.runAll("operations",s=>e.map(o=>(r.add(z(o.oid)),s.put(this.addOperationIndexes(o)))),t),Array.from(r)};this.reset=async({clearReplica:e,transaction:t}={})=>{let r=t||this.createTransaction(["info","operations","baselines"],{mode:"readwrite"});await Promise.all([this.resetLocalReplica(r,e),this.resetBaselines(r),this.resetOperations(r)])};this.stats=async()=>{let e=await We(this.db,"operations"),t=await We(this.db,"baselines");return{operationsSize:e,baselinesSize:t}};this.resetLocalReplica=async(e,t=!1)=>{if(t)return this.run("info",r=>r.delete("localReplicaInfo"),{mode:"readwrite",transaction:e});{let r=await this.getLocalReplica({transaction:e});r&&(r.ackedLogicalTime=null,r.lastSyncedLogicalTime=null,await this.run("info",s=>s.put({...r,type:"localReplicaInfo"}),{mode:"readwrite",transaction:e}))}};this.resetBaselines=async e=>this.clear("baselines",e);this.resetOperations=async e=>this.clear("operations",e);this.addOperationIndexes=e=>({...e,oid_timestamp:fe(e.oid,e.timestamp),l_t:fe(e.isLocal,e.timestamp),d_t:fe(z(e.oid),e.timestamp)});this.addDispose(()=>(this.ctx.log("info","Closing metadata DB for",this.ctx.namespace),he(e)))}},Ji={mode:"readwrite"};var oo=[Ya,Xa,Za,ec,tc,nc],Ga=oo.length;function Gi({indexedDB:i=window.indexedDB,namespace:n,log:e}){return new Promise((t,r)=>{let s=i.open(Tt(n),Ga),o=!1;s.onupgradeneeded=async a=>{let f=s.result,p=s.transaction,y=oo.slice(a.oldVersion);for(let D of y)await D(f,p);await new Promise((D,w)=>{p.addEventListener("complete",D),p.addEventListener("error",w)}),a.oldVersion||(o=!0)},s.onerror=()=>{console.error("Error opening database",s.error),r(s.error)},s.onsuccess=()=>{t({db:s.result,wasInitialized:o})}})}async function Ya(i,n){let e=i.createObjectStore("baselines",{keyPath:"oid"}),t=i.createObjectStore("operations",{keyPath:"oid_timestamp"}),r=i.createObjectStore("info",{keyPath:"type"});e.createIndex("timestamp","timestamp"),t.createIndex("isLocal_timestamp","isLocal_timestamp"),t.createIndex("documentOid_timestamp","documentOid_timestamp")}async function Xa(i,n){let e=n.objectStore("operations");await new Promise((t,r)=>{let s=e.openCursor();s.onsuccess=()=>{let o=s.result;if(o){let{isLocal_timestamp:a,documentOid_timestamp:f,...p}=o.value;o.update({...p,l_t:a,d_t:f}),o.continue()}else t()},s.onerror=o=>{r(s.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 Za(i,n){n.objectStore("operations").createIndex("timestamp","timestamp")}async function ec(i,n){let e=i.createObjectStore("files",{keyPath:"id"});e.createIndex("remote","remote"),e.createIndex("deletedAt","deletedAt")}async function tc(i,n){let e=n.objectStore("operations");await new Promise((r,s)=>{let o=e.openCursor();o.onsuccess=()=>{let a=o.result;if(a){let f=oi(a.value);f.oid_timestamp!==a.primaryKey?(a.delete(),e.put(f)):a.update(f),a.continue()}else r()},o.onerror=a=>{s(o.error)}});let t=n.objectStore("baselines");await new Promise((r,s)=>{let o=t.openCursor();o.onsuccess=()=>{let a=o.result;if(a){let f=oi(a.value);f.oid!==a.primaryKey?(a.delete(),t.put(f)):a.update(f),a.continue()}else r()},o.onerror=a=>{s(o.error)}})}async function nc(i,n){n.objectStore("files").createIndex("timestamp","timestamp")}var ic=i=>IDBKeyRange.only(be(i.equals)),rc=i=>{},sc=i=>{let n=i.gte||i.gt,e=i.lte||i.lt;return n===e?IDBKeyRange.only(be(n)):n?e?IDBKeyRange.bound(be(n),be(e),!!i.gt,!!i.lt):IDBKeyRange.lowerBound(be(n),!!i.gt):IDBKeyRange.upperBound(be(e),!!i.lt)},oc=(i,n,e)=>{let t=i.collections[n].compounds[e.where];N(t,`Index ${e.where} does not exist on collection ${n}`);let r=Object.keys(e.match).sort((f,p)=>t.of.indexOf(f)-t.of.indexOf(p));for(let f of r)if(t.of.indexOf(f)!==r.indexOf(f))throw new Error(`Compound index ${e.where} does not have ${f} at the start of its order`);let s=r.map(f=>e.match[f]);if(r.length===t.of.length)return IDBKeyRange.only(fe(...s));let o=xe(...s),a=Ee(...s);return IDBKeyRange.bound(o,a)};function ac(i){let n=i.startsWith,e=i.startsWith+"\uFFFF";return IDBKeyRange.bound(n,e)}function Yi(i,n,e){if(e)return Xt(e)?sc(e):Yt(e)?ic(e):bi(e)?rc(e):Zt(e)?ac(e):oc(i,n,e)}var Gn=class extends Me{constructor(e,t){super(e,{log:t.log});this.close=async()=>{await this.dispose()};this.stats=async()=>{let e=Object.keys(this.ctx.schema.collections),t={};return await Promise.all(e.map(async r=>{let s=await We(this.db,r);t[r]=s})),t};this.findOneOid=async e=>{let t=await this.run(e.collection,r=>{let s=e.index?.where?r.index(e.index.where):r,o=e.index?.order==="desc"?"prev":"next",a=Yi(this.ctx.schema,e.collection,e.index);return s.openCursor(a,o)},{mode:"readonly"});return t?Z(e.collection,t.primaryKey.toString()):null};this.findAllOids=async({collection:e,index:t,offset:r,limit:s})=>{let a=this.createTransaction([e],{mode:"readonly"}).objectStore(e),f=t?.where?a.index(t.where):a,p=t?.order==="desc"?"prev":"next",y=Yi(this.ctx.schema,e,t),D=f.openCursor(y,p),w=!1;return{result:await new Promise((g,I)=>{let E=!r,O=0,_=new Set;D.onsuccess=()=>{O++;let k=D.result;if(!k){g(Array.from(_));return}r&&!E?(k.advance(r),E=!0):((!s||_.size<s)&&_.add(Z(e,k.primaryKey.toString())),s&&O>s?(w=!0,g(Array.from(_))):k.continue())},D.onerror=()=>{D.error?.name==="InvalidStateError"?(this.ctx.log("error","find query failed with InvalidStateError",D.error),g([])):D.error&&Qe(D.error)?g([]):I(D.error)}}),hasNextPage:w}};this.saveEntities=async(e,t)=>{let r={transaction:this.createTransaction(t.collections,{mode:"readwrite",abort:t.abort})},s=await Promise.allSettled(e.map(async a=>{let f=a.getSnapshot();try{await this.saveDocument(a.oid,f,r)}catch(p){throw this.ctx.log("error",`Error saving document ${a.oid} (${JSON.stringify(f)})`,p),p instanceof Error?p:new Error("Unknown error saving document")}})),o=s.filter(a=>a.status==="rejected");if(o.length){if(o.length===s.length)throw new Error("Failed to save any documents. Something must be quite wrong.");this.ctx.log("error","Failed to save documents:",o,". See logs above. This only affects querying these documents. Let's hope a future attempt will correct them...")}r.transaction.commit()};this.reset=async()=>{let e=Object.keys(this.ctx.schema.collections),t=this.createTransaction(e,{mode:"readwrite"});await Promise.all(e.map(r=>this.run(r,s=>s.clear(),{transaction:t}))),this.ctx.entityEvents.emit("collectionsChanged",e),this.ctx.log("info","\u{1F4A8} Reset queryable storage")};this.saveDocument=async(e,t,{transaction:r})=>{this.ctx.log("debug",`Saving document indexes for querying ${e}`);let{collection:s,id:o}=le(e);try{if(!t)await this.run(s,a=>a.delete(o),{mode:"readwrite",transaction:r}),this.ctx.log("debug",`Deleted document indexes for querying ${e}`);else{let a=this.ctx.schema.collections[s],f=li(a,t);f["@@@snapshot"]=JSON.stringify(t),await this.run(s,p=>p.put(f),{mode:"readwrite",transaction:r}),this.ctx.log("debug",`Save complete for ${e}`,f)}}catch(a){throw this.ctx.log("error",`Error saving document ${e}`,a),a}};this.ctx=t,this.addDispose(()=>(this.ctx.log("info","Closing document database for",this.ctx.namespace),he(this.db)))}};async function ao(i,n,e,t,r){r?.("debug","Upgrading database",n,"to version",e);function s(o,a){let f=i.open(ct(n),e),p=!1;f.onupgradeneeded=y=>{let D=f.transaction;t(D,f.result,y),p=!0},f.onsuccess=async y=>{p?(await he(f.result),o(f.result)):a(new Error("Database was not upgraded when a version change was expected"))},f.onerror=y=>{a(f.error||new Error("Unknown error"))},f.onblocked=y=>{r?.("Database upgrade blocked!")}}return new Promise(s)}async function Xi({indexedDB:i=Ni,namespace:n,version:e,log:t}){t?.("debug","Opening database",n,"at version",e);let r=await Qs(ct(n),e,i);return r.addEventListener("versionchange",s=>{r.close()}),r.addEventListener("close",()=>{t?.("warn","Database closed",n)}),r}var ft=class{constructor(n=window.indexedDB){this.indexedDB=n;this.name="IdbPersistence";this.getNamespaces=async()=>{let n=await this.indexedDB.databases();return Array.from(new Set(n.map(Ws).filter(e=>!!e)))};this.getNamespaceVersion=async n=>{let e=ct(n),r=(await this.indexedDB.databases()).find(s=>s.name===e);return r?r.version??0:0};this.deleteNamespace=async(n,e)=>{await Promise.all([_n(Tt(n),this.indexedDB),_n([n,"collections"].join("_"),this.indexedDB)])};this.openNamespace=async n=>new Zi(this.indexedDB,n);this.copyNamespace=async(n,e,t)=>{let r={...t,namespace:n},s={...t,namespace:e},{db:o}=await Gi({indexedDB:this.indexedDB,log:r.log,namespace:r.namespace}),a=await Xi({indexedDB:this.indexedDB,namespace:r.namespace,version:r.schema.version,log:r.log});r.log("info",`Copying data from ${r.namespace} to ${s.namespace}`),await $i(o,Tt(s.namespace),s,this.indexedDB),await $i(a,ct(s.namespace),s,this.indexedDB),await he(o),await he(a)}}},Zi=class{constructor(n,e){this.indexedDB=n;this.namespace=e;this.openMetadata=async n=>{let{db:e}=await Gi({indexedDB:this.indexedDB,log:n.log,namespace:this.namespace});return this.metadataDb=e,n.persistenceShutdownHandler.register(()=>he(e)),new Jn(e,n)};this.openDocuments=async n=>{let e=await Xi({version:n.schema.version,indexedDB:this.indexedDB,log:n.log,namespace:this.namespace});return n.persistenceShutdownHandler.register(()=>he(e)),new Gn(e,n)};this.applyMigration=async(n,e)=>{n.log("debug","Applying migration",e.newSchema.version,e),await ao(this.indexedDB,this.namespace,e.newSchema.version,(t,r)=>{for(let s of e.addedCollections)r.createObjectStore(s,{keyPath:e.newSchema.collections[s].primaryKey,autoIncrement:!1});for(let s of e.allCollections){let o=t.objectStore(s);for(let a of e.addedIndexes[s]||[])o.createIndex(a.name,a.name,{multiEntry:a.multiEntry});for(let a of e.removedIndexes[s]||[])o.deleteIndex(a.name)}for(let s of e.removedCollections)t.objectStore(s).clear()},n.log)}}openFiles(n){if(!this.metadataDb)throw new Error("Metadata database must be opened first. This is a bug in Verdant.");return Promise.resolve(new Wn(this.metadataDb,n))}};var ht=class extends V{constructor(){super(...arguments);this._undoable=[];this._undone=[];this.undo=async()=>{let e=this._undoable.pop();if(e){let t=await e();return t&&this._undone.push(t),this.emit("change"),!0}return!1};this.redo=async()=>{let e=this._undone.pop();if(e){let t=await e();return t&&this._undoable.push(t),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}get undoLength(){return this._undoable.length}get redoLength(){return this._undone.length}};var Yn=class{constructor(n){this.init=n;this._initializing=!1;this.initialize=async n=>{if(typeof window>"u"&&!n.environment)throw new Error("A Verdant client was initialized in an environment without a global Window or `environment` configuration. 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 the environment to the ClientDescriptor options.");if(this._initializing||this._resolvedValue)return this._readyPromise;this._initializing=!0;try{let e=new Hn(new tn,n.schema.version),t=n.environment||cc,r={closing:!1,entityEvents:new V,globalEvents:new V,internalEvents:new V,log:n.log||xr,migrations:n.migrations,namespace:n.namespace,originalNamespace:n.namespace,schema:n.schema,oldSchemas:n.oldSchemas,time:e,undoHistory:n.undoHistory||new ht,weakRef:a=>n.EXPERIMENTAL_weakRefs?new WeakRef(a):new Qn(a),patchCreator:new nt(()=>e.now),config:{files:n.files,sync:n.sync,persistence:{disableRebasing:n.disableRebasing,rebaseTimeout:n.rebaseTimeout},queries:n.queries},persistence:n.persistence||new ft(t.indexedDB),environment:t,persistenceShutdownHandler:new Pe(n.log),pauseRebasing:!1,getClient(){throw new H(H.Code.Unexpected,void 0,"Client not yet initialized. This is a Verdant bug, please report it.")}};r.log("info","Initializing client",{namespace:r.namespace,version:n.schema.version,persistence:r.persistence.name});let s=await kt(r),o=new ut(s);return this.resolveReady(o),this._resolvedValue=o,o}catch(e){throw e instanceof Error?(this.rejectReady(e),e):new Error("Unknown error initializing storage")}finally{this._initializing=!1}};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 In(this.namespace)};this._readyPromise=new Promise((e,t)=>{this.resolveReady=e,this.rejectReady=t}),this._namespace=n.namespace}get namespace(){return this._namespace}get current(){return this._resolvedValue}get readyPromise(){return this._readyPromise}get schema(){return this.init.schema}},cc={WebSocket:typeof WebSocket<"u"?WebSocket:void 0,fetch:typeof window<"u"?window.fetch.bind(window):fetch,indexedDB:typeof indexedDB<"u"?indexedDB:void 0};var lc={private:Ue.onlyMe(),public:void 0};function dc(i,{port:n=3242,initialPresence:e={}}={}){let t=localStorage.getItem("verdant-userId");return t||(t=`user-${Math.random().toString(36).slice(2)}`,localStorage.setItem("verdant-userId",t)),{defaultProfile:{id:t},initialPresence:e,authEndpoint:`http://localhost:${n}/auth/${i}?userId=${t}`}}var er=Ae($e(),1);function uc(i){return i?er.default.slug():(0,er.default)()}window.Verdant=tr;
13
+ - New indexes: ${Object.keys(t.addedIndexes).map(a=>t.addedIndexes[a].map(d=>`${a}.${d.name}`)).flatMap(a=>a).join(", ")}
14
+ - Removed indexes: ${Object.keys(t.removedIndexes).map(a=>t.removedIndexes[a].map(d=>`${a}.${d.name}`)).flatMap(a=>a).join(", ")}
15
+ `)}i.pauseRebasing=!1}var Cn=class{constructor(n,e){this.db=n;this.context=e;this.onServerReset=n=>this.db.resetSyncedStatusSince(n);this.add=async n=>{if(n.url&&!(n.localPath||n.file)){this.context.log("debug","Remote file added to an entity. This usually means an entity was cloned. Downloading remote file...",n.id);let e=await this.loadFileContents(n,0,3);n.file=new File([e],n.name,{type:n.type}),delete n.url,this.context.log("debug","Downloaded remote file",n.id,n.name,". Cleared its remote URL.")}else!n.url&&!n.file&&!n.localPath&&this.context.log("warn","File added without a file or URL. This file will not be available for use.",n.id);return n.remote=!1,await this.db.add(n),this.context.internalEvents.emit("fileAdded",n),this.context.globalEvents.emit("fileSaved",n),this.context.log("debug","File added",n.id,n.name,n.type,n.file?"with binary file":n.url?"with url":n.localPath?"with local path":"with no data"),n};this.onUploaded=this.db.markUploaded.bind(this.db);this.get=this.db.get.bind(this.db);this.getAll=this.db.getAll.bind(this.db);this.listUnsynced=this.db.listUnsynced.bind(this.db);this.iterateOverPendingDelete=this.db.iterateOverPendingDelete.bind(this.db);this.stats=this.db.stats.bind(this.db);this.getFileExportName=(n,e)=>`${e}___${n}`;this.export=async(n=!0)=>{let e=await this.getAll();if(n)for(let s of e)if(!s.file&&(s.url||s.localPath))try{let o=await this.loadFileContents(s);s.file=o}catch(o){this.context.log("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,o)}else s.file||this.context.log("warn",`File ${s.id} has no file or URL. It will be missing in the export.`,s);let t=[],r=[];for(let s of e){let o=s.file;if(delete s.file,t.push(s),o){let a=new File([o],this.getFileExportName(s.name,s.id),{type:s.type});r.push(a)}else this.context.log("warn",`File ${s.id} was could not be loaded locally or from the server. It will be missing in the export.`)}return{fileData:t,files:r}};this.import=async({fileData:n,files:e})=>{let t=new Map(e.map(s=>{let{id:o}=this.parseFileExportname(s.name);return[o,s]})),r=n.map(s=>{let o=t.get(s.id);return o?{...s,file:o}:(this.context.log("warn",`File ${s.id} was not found in import`),s)});await Promise.all(r.map(s=>this.add(s)))};this.parseFileExportname=n=>{let[e,t]=n.split("___");return{id:e,originalFileName:t}};this.loadFileContents=async(n,e=0,t=0)=>{try{return await this.db.loadFileContents(n,this.context)}catch(r){if(e<t)return new Promise((s,o)=>{setTimeout(()=>{this.loadFileContents(n,e+1,t).then(s,o)},1e3)});throw this.context.log("error",`Failed to download file after ${t} retries`,r),new Error(`Failed to download file after ${t} retries`,{cause:r})}};this.cleanupDeletedFiles=async()=>{let n=0,e=0,t=[];await this.iterateOverPendingDelete(r=>{this.config.canCleanupDeletedFile(r)?(n++,t.push(r.id)):e++});for(let r of t)await this.db.delete(r);this.context.log("info",`Cleaned up ${n} files, skipped ${e} files`)};this.onFileRefsDeleted=async n=>{await Promise.all(n.map(async e=>{try{await this.db.markPendingDelete(e.id)}catch(t){this.context.log("error","Failed to mark file for deletion",t)}})),this.context.log("info",`Marked ${n.length} files as pending delete`)};e.internalEvents.subscribe("filesDeleted",this.onFileRefsDeleted),this.cleanupDeletedFiles()}get config(){return{canCleanupDeletedFile(n){return n.deletedAt!==null&&n.deletedAt<Date.now()-1e3*60*24*3},...this.context.config.files}}};var An=class{constructor(n,e,t){this.db=n;this.meta=e;this.ctx=t;this.tryAutonomousRebase=async()=>{(await this.meta.getLocalReplica()).lastSyncedLogicalTime||this.ctx.closing||this.ctx.persistenceShutdownHandler.isShuttingDown||(this.ctx.log("debug","Running autonomous library rebase"),await this.runRebase(this.ctx.time.now))};this.runRebase=async n=>{this.ctx.closing||this.ctx.persistenceShutdownHandler.isShuttingDown||(await this.db.transaction({storeNames:["baselines","operations"],mode:"readwrite"},async e=>{let t=new Set,r,s=0;if(await this.db.iterateAllOperations(a=>{t.add(a.oid),r=a.timestamp,s++},{before:n,transaction:e}),!t.size||this.ctx.closing||this.ctx.persistenceShutdownHandler.isShuttingDown)return;let o=[];for(let a of t)o.push(await this.rebase(a,r||n,e))}),this.ctx.globalEvents.emit("rebase"))};this.scheduleRebase=async n=>{this.rebaseTimeout&&clearTimeout(this.rebaseTimeout),this.rebaseTimeout=setTimeout(this.runRebase,this.ctx.config.persistence?.rebaseTimeout??1e4,n),this.ctx.log("debug","Scheduled rebase up to global ack",n)};this.rebaseTimeout=null;this.rebase=async(n,e,t)=>{if(this.ctx.closing||this.ctx.persistenceShutdownHandler.isShuttingDown)return;let r=await this.db.getBaseline(n,{transaction:t}),s=r?.snapshot||void 0,o=0,a=r?.authz,d=[];if(this.ctx.closing||this.ctx.persistenceShutdownHandler.isShuttingDown)return;await this.db.iterateEntityOperations(n,h=>{(!r||h.timestamp>r.timestamp)&&(s=Be(s,h.data,d),h.data.op==="initialize"&&(a=h.authz)),o++},{to:e,transaction:t}),s&&z(s,n);let m={oid:n,snapshot:s,timestamp:e,authz:a};if(!(this.ctx.closing||this.ctx.persistenceShutdownHandler.isShuttingDown))return this.ctx.closeLock=(async()=>{if(m.snapshot?await this.db.setBaselines([m],{transaction:t}):await this.db.deleteBaseline(n,{transaction:t}),await this.db.deleteEntityOperations(n,{to:e,transaction:t}),this.ctx.log("debug","rebased",n,"up to",e,":",s,"and deleted",o,"operations"),d.length){let h=d.filter(he);h.length&&this.ctx.internalEvents.emit("filesDeleted",h)}})(),m}}};var Rn=class{constructor(n,e,t){this.db=n;this.meta=e;this.ctx=t;this.createOperation=async n=>{let e=await this.meta.getLocalReplica();return this.ctx.log("debug","Creating operation message",n.operations.length),{type:"op",timestamp:this.ctx.time.now,replicaId:e.id,operations:n.operations.map(Kt)}};this.createSyncStep1=async n=>{let e=await this.meta.getLocalReplica(),t=n===null?null:e.lastSyncedLogicalTime,r=[],s=new Set;return this.db.transaction({mode:"readwrite",storeNames:["operations","baselines"]},async o=>{t?(this.ctx.log("debug","Syncing local operations since",t),await this.db.iterateLocalOperations(d=>{r.push(Kt(d)),s.add(K(d.oid))},{after:t,transaction:o})):(this.ctx.log("debug","Syncing all operations"),await this.db.iterateAllOperations(d=>{r.push(Kt(d)),s.add(K(d.oid))},{transaction:o}));let a=[];return t||await this.db.iterateAllBaselines(d=>{a.push(d)},{transaction:o}),r.length>0&&this.ctx.log("debug",`Syncing ${r.length} operations since ${t}`),{type:"sync",schemaVersion:this.ctx.schema.version,timestamp:this.ctx.time.now,replicaId:e.id,resyncAll:!e.lastSyncedLogicalTime,operations:r,baselines:a,since:t}})};this.createPresenceUpdate=async n=>{let e=await this.meta.getLocalReplica();return{type:"presence-update",presence:n.presence,replicaId:e.id,internal:n.internal}};this.createHeartbeat=async()=>{let n=await this.meta.getLocalReplica();return{type:"heartbeat",timestamp:this.ctx.time.now,replicaId:n.id}};this.createAck=async n=>{let e=await this.meta.getLocalReplica();return{type:"ack",timestamp:this.ctx.time.now,replicaId:e.id,nonce:n}}}};var ro=Te(He(),1),Fn=class{constructor(n,e){this.db=n;this.ctx=e;this.events=new N;this.insertOperations=async(n,e)=>{this.ctx.log("debug",`Inserting ${n.length} operations`,n);let t=await this.db.addOperations(n,e);for(let r of n)this.ctx.globalEvents.emit("operation",r);return!this.ctx.config.persistence?.disableRebasing&&!this.ctx.pauseRebasing&&this.rebaser.tryAutonomousRebase(),t};this.insertLocalOperations=async(n,e)=>{if(n.length===0)return;for(let r of n)r.isLocal=!0;await this.insertOperations(n,e),this.ctx.log("debug",`Inserted ${n.length} local operations; sending sync message`);let t=await this.messageCreator.createOperation({operations:n});this.events.emit("syncMessage",t)};this.insertRemoteOperations=async(n,e)=>{if(n.length===0)return[];for(let t of n)t.isLocal=!1;await this.insertOperations(n,e),this.ack(n[n.length-1].timestamp)};this.insertRemoteBaselines=async(n,e)=>{if(n.length===0)return[];this.ctx.log("debug",`Inserting ${n.length} remote baselines`),await this.db.setBaselines(n,e);let t=new Set;return n.forEach(r=>{t.add(K(r.oid))}),Array.from(t)};this.deleteDocument=async n=>{let e=new Set,t=K(n);return L(t===n,"Must be root document OID"),e.add(t),this.db.transaction({storeNames:["baselines","operations"]},async r=>{await Promise.all([this.db.iterateDocumentBaselines(t,a=>{e.add(a.oid)},{transaction:r}),this.db.iterateDocumentOperations(t,a=>{e.add(a.oid)},{transaction:r})]);let s=await this.getDocumentAuthz(t),o=new Array;for(let a of e)o.push({oid:a,timestamp:this.ctx.time.now,data:{op:"delete"},authz:s});return this.insertLocalOperations(o,{transaction:r})})};this.deleteCollection=async n=>{let e=new Set;return this.db.transaction({storeNames:["baselines","operations"],mode:"readwrite"},async t=>{await Promise.all([this.db.iterateCollectionBaselines(n,s=>{e.add(s.oid)},{transaction:t}),this.db.iterateCollectionOperations(n,s=>{e.add(s.oid)},{transaction:t})]);let r=new Array;for(let s of e)r.push({oid:s,timestamp:this.ctx.time.now,data:{op:"delete"},authz:void 0});return this.insertLocalOperations(r,{transaction:t})})};this.getDocumentSnapshot=async(n,e={})=>{let t=K(n);return L(t===n,"Must be root document OID"),this.db.transaction({storeNames:["baselines","operations"],mode:"readwrite"},async r=>{let s=[];await this.db.iterateDocumentBaselines(t,d=>{s.push(d)},{transaction:r});let o=new Map;for(let d of s)d.snapshot&&z(d.snapshot,d.oid),o.set(d.oid,d.snapshot);await this.db.iterateDocumentOperations(t,d=>{let m=o.get(d.oid)||void 0,h=Be(m,d.data);h&&z(h,d.oid),o.set(d.oid,h)},{transaction:r,to:e.to||this.ctx.time.now});let a=o.get(t);return a&&$t(a,o),a})};this.getDocumentData=async(n,e)=>this.db.transaction({storeNames:["baselines","operations"],abort:e?.abort},async t=>{let r=[],s={};return await Promise.all([this.db.iterateDocumentBaselines(n,o=>{r.push(o)},{transaction:t}),this.db.iterateDocumentOperations(n,o=>{s[o.oid]??=[],s[o.oid].push(o)},{transaction:t})]),{baselines:r,operations:s}});this.getDocumentAuthz=async n=>{let e;return await this.db.iterateEntityOperations(n,t=>{if(t.data.op==="initialize")return e=t.authz,!0}),e};this.insertData=async(n,e)=>this.db.transaction({storeNames:["baselines","operations"],abort:e?.abort,mode:"readwrite"},async t=>{if(this.ctx.log("debug","Begin insert data transaction"),n.baselines&&await this.insertRemoteBaselines(n.baselines,{transaction:t}),this.ctx.log("debug","Inserted baselines (if any)"),e?.abort?.aborted)throw new Error("Aborted");n.operations&&(n.isLocal?(this.ctx.log("debug","Inserting local operations"),await this.insertLocalOperations(n.operations,{transaction:t})):(this.ctx.log("debug","Inserting remote operations"),await this.insertRemoteOperations(n.operations,{transaction:t}))),this.ctx.log("debug","End insert data transaction")});this.updateLastSynced=async n=>{if(!this.ctx.closing)return this.updateLocalReplica({lastSyncedLogicalTime:n})};this.setGlobalAck=async n=>{this.ctx.closing||(await this.db.setGlobalAck(n),this.ctx.config.persistence?.disableRebasing||await this.rebaser.scheduleRebase(n))};this._cachedLocalReplica=null;this._creatingLocalReplica=void 0;this.getLocalReplica=async n=>{if(this._cachedLocalReplica)return this._cachedLocalReplica;let e=await this.db.getLocalReplica(n);return e?(this.ctx.log("debug","Read local replica",e),this._cachedLocalReplica=e,e):this._creatingLocalReplica?this._creatingLocalReplica:(this._creatingLocalReplica=(async()=>{let r={id:(0,ro.default)(),userId:null,ackedLogicalTime:null,lastSyncedLogicalTime:null};return await this.db.updateLocalReplica(r),this._cachedLocalReplica=r,r})(),this._creatingLocalReplica)};this.updateLocalReplica=async(n,e)=>{let t=await this.getLocalReplica(e);L(!!t,"Local replica must exist"),Object.assign(t,n),this._cachedLocalReplica=t,await this.db.updateLocalReplica(t,e)};this.iterateLocalOperations=this.db.iterateLocalOperations;this.iterateAllOperations=this.db.iterateAllOperations;this.iterateAllBaselines=this.db.iterateAllBaselines;this.reset=async()=>{this.ctx.closing||await this.db.reset()};this.stats=this.db.stats;this.export=async()=>{let n=new Array,e=new Array;return this.db.transaction({storeNames:["baselines","operations"],mode:"readwrite"},async t=>{await this.iterateAllOperations(s=>{e.push(s)},{transaction:t}),await this.iterateAllBaselines(s=>{n.push(s)},{transaction:t});let r=await this.getLocalReplica();return{operations:e,baselines:n,localReplica:r,schemaVersion:this.ctx.schema.version}})};this.resetFrom=async n=>{this._cachedLocalReplica=null,await this.db.reset({clearReplica:!0}),n.localReplica&&await this.updateLocalReplica({ackedLogicalTime:n.localReplica.ackedLogicalTime,lastSyncedLogicalTime:n.localReplica.lastSyncedLogicalTime}),this.ctx.log("debug","Resetting metadata from export",n),await this.insertData({operations:n.operations,baselines:n.baselines,isLocal:!0})};this.manualRebase=async()=>{if(this.ctx.closing||this.ctx.config.persistence?.disableRebasing)return;let n=await this.db.getAckInfo();n.globalAckTimestamp&&await this.rebaser.scheduleRebase(n.globalAckTimestamp)};this.ack=async n=>{let e=await this.getLocalReplica();n>this.ctx.time.now||(this.events.emit("syncMessage",{type:"ack",replicaId:e.id,timestamp:n}),!this.ctx.closing&&(!e.ackedLogicalTime||n>e.ackedLogicalTime)&&this.updateLocalReplica({ackedLogicalTime:n}))};this.rebaser=new An(n,this,e),this.messageCreator=new Rn(n,this,e)}};var Tn=class{constructor(n,e){this.db=n;this.ctx=e;this.reset=this.db.reset.bind(this.db);this.close=this.db.close.bind(this.db);this.saveEntities=async(n,e)=>{if(n.length===0)return;let t=new Set(Object.keys(this.ctx.schema.collections)),r=[],s=n.filter(o=>{let{collection:a}=ue(o.oid);return t.has(a)?(r.includes(a)||r.push(a),!0):(this.ctx.log("warn",`Entity ${o.oid} is in a collection that no longer exists in the schema. It will not be saved.`),!1)});if(r.length!==0){this.ctx.log("debug","Saving",s.length,"entities"),await this.db.saveEntities(s,{abort:e?.abort,collections:r}),this.ctx.log("debug","Saved",s.length,"entities"),this.ctx.entityEvents.emit("collectionsChanged",r);for(let o of n)this.ctx.entityEvents.emit("documentChanged",o.oid)}};this.findOneOid=this.db.findOneOid.bind(this.db);this.findAllOids=this.db.findAllOids.bind(this.db);this.stats=this.db.stats.bind(this.db)}};async function Lt(i){let n=i;if(i.schema.wip&&(n.namespace=Zs(i.originalNamespace,i.schema),n.log("info","Switched to WIP namespace",n.namespace),!(await n.persistence.getNamespaces()).includes(n.namespace))){let r=await n.persistence.getNamespaceVersion(n.originalNamespace);if(r===0)n.log("debug","No existing data to copy to WIP namespace");else{let s=i.oldSchemas?.find(o=>o.version===r);if(!s)throw new Q(Q.Code.MigrationPathNotFound,void 0,`Trying to open WIP database for version ${i.schema.version}, but the current local data is version ${r} and a historical schema for that version is not available.`);n.log("info",`Copying data from ${n.originalNamespace} to ${n.namespace}`),await n.persistence.copyNamespace(n.originalNamespace,n.namespace,{...n,schema:s})}}let e=await i.persistence.openNamespace(n.namespace,n);if(n.log("info","Opening persistence metadata"),n.meta=new Fn(await e.openMetadata(i),i),n.log("info","Opening persistence files"),n.files=new Cn(await e.openFiles(n),n),n.log("info","Migrating document database"),await io({context:n,version:i.schema.version}),n.log("info","Opening persistence documents"),n.documents=new Tn(await e.openDocuments(n),n),!i.schema.wip){let t=await i.persistence.getNamespaces();for(let r of t)r.startsWith("@@wip_")&&(i.log("debug","Cleaning up old WIP namespace",r),await i.persistence.deleteNamespace(r,i))}return n}async function so(i,n){i.log("info","Importing data from export");let e=i.oldSchemas?.find(a=>a.version===n.data.schemaVersion);if(!e)throw new Error(`Could not find schema for version ${n.data.schemaVersion}`);let t=`@@import_${Date.now()}`,r=await Lt({...i,schema:e,namespace:t,originalNamespace:t,entityEvents:new N,internalEvents:new N,globalEvents:new N,config:{...i.config,persistence:{...i.config.persistence,disableRebasing:!0}},persistenceShutdownHandler:new Fe(i.log)});await r.meta.resetFrom(n.data);let s=new Set;for(let a of n.data.baselines)s.add(K(a.oid));for(let a of n.data.operations)s.add(K(a.oid));let o=await Promise.all(Array.from(s).map(async a=>{let d=await r.meta.getDocumentSnapshot(a);return{oid:a,getSnapshot:()=>d}}));if(await r.documents.saveEntities(o),await r.files.import(n),i.log("debug","Imported data into temporary namespace",t),await r.persistenceShutdownHandler.shutdown(),e.version!==i.schema.version){let a=i.schema,d=await Lt({...r,persistenceShutdownHandler:new Fe(i.log),schema:a});i.log("debug","Upgraded imported data to current schema"),await d.persistenceShutdownHandler.shutdown(),i.log("debug","Shut down upgraded databases")}if(await i.persistenceShutdownHandler.shutdown(),await i.persistence.copyNamespace(t,i.namespace,i),await Lt(i),n.data.schemaVersion===i.schema.version){let a=await i.meta.stats();if(a.operationsSize.count!==n.data.operations.length)throw i.log("critical","Imported operations count mismatch","expected",n.data.operations.length,"actual",a.operationsSize.count),new Q(Q.Code.ImportFailed,void 0,"Imported operations count mismatch");if(a.baselinesSize.count!==n.data.baselines.length)throw i.log("critical","Imported documents count mismatch","expected",n.data.baselines.length,"actual",a.baselinesSize.count),new Q(Q.Code.ImportFailed,void 0,"Imported documents count mismatch")}i.log("debug","Data copied to primary namespace"),await i.persistence.deleteNamespace(t,i),i.log("debug","Deleted temporary namespace"),i.internalEvents.emit("persistenceReset"),i.log("info","Data imported successfully"),i.persistenceShutdownHandler.reset()}function za(i){return i!==null}function Hi(i){return Array.isArray(i)?i.map(Hi).filter(za):i instanceof pe&&i.deleted?null:i}function Ue(i,n){return!i&&!n||i&&n&&$e(i)===$e(n)}var Qi=Symbol("ON_ALL_UNSUBSCRIBED"),me=Symbol("UPDATE"),$a,ve=class extends oe{constructor({initial:e,context:t,collection:r,key:s,shouldUpdate:o}){super();this._internalUnsubscribes=[];this._status="initial";this._executionPromise=null;this.setValue=e=>{this._rawValue=e,this.subscribeToDeleteAndRestore(this._rawValue);let t=Hi(e),r=!0;this.status==="initializing"||this.status==="initial"?r=!0:this.isListQuery?this._value.length===t.length&&this._value.every((s,o)=>s===t[o])&&(r=!1):this._value===t&&(r=!1),this._value=t,r&&(this.context.log("debug","Query value changed",this.key),this._events.emit("change",this._value)),this.status="ready"};this.refreshValue=()=>{this.setValue(this._rawValue)};this.subscribeToDeleteAndRestore=e=>{for(;this._internalUnsubscribes.length;)this._internalUnsubscribes.pop()?.();Array.isArray(e)?e.forEach(t=>{t instanceof pe&&(this._internalUnsubscribes.push(t.subscribe("delete",this.refreshValue)),this._internalUnsubscribes.push(t.subscribe("restore",this.refreshValue)))}):e instanceof pe&&(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[$a]=e=>{this._allUnsubscribedHandler=e};this._rawValue=e,this._value=e,this.isListQuery=Array.isArray(e),this._events=new N(d=>{d==="change"&&this._allUnsubscribedHandler?.(this)}),this.context=t,this.key=s,this.collection=r;let a=o||(d=>d.includes(r));this.addDispose(this.context.entityEvents.subscribe("collectionsChanged",d=>{a(d)&&(this.context.log("info","Updating query",this.key),this.execute())}))}static{$a=Qi}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}set status(e){this._status!==e&&(this._status=e,this._events.emit("statusChange",this._status))}get hasDeleted(){return this.isListQuery?this._rawValue.length!==this._value.length:!!this._rawValue&&!this._value}subscribe(e,t){if(t===void 0&&typeof e=="function")return this.resolved,this._events.subscribe("change",e);if(e==="change"&&t!==void 0)return this.resolved,this._events.subscribe("change",t);if(e==="statusChange"&&typeof t=="function")return this._events.subscribe(e,t);throw new Error("Invalid invocation of Query.subscribe")}get __rawValue(){return this._rawValue}};var kn=class extends ve{constructor({id:e,hydrate:t,...r}){super({initial:null,...r});this.run=async()=>{let e=await this.hydrate(this.oid);this.setValue(e)};this.oid=ee(r.collection,e),this.hydrate=t}};var Ka,Bn=class extends ve{constructor({index:e,hydrate:t,...r}){super({initial:null,...r});this.run=async()=>{let e=await this.context.documents.findOneOid({collection:this.collection,index:this.index});this.setValue(e?await this.hydrate(e):null)};this[Ka]=e=>{Ue(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=t}static{Ka=me}};var qa,Ln=class extends ve{constructor({index:e,hydrate:t,pageSize:r,page:s,...o}){super({initial:[],...o});this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:t}=await this.context.documents.findAllOids({collection:this.collection,index:this.index,limit:this._pageSize,offset:this._page*this._pageSize});this._hasNextPage=t,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[qa]=e=>{Ue(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=t,this._pageSize=r,this._page=s}static{qa=me}get pageSize(){return this._pageSize}get page(){return this._page}get hasNextPage(){return this._hasNextPage}get hasPreviousPage(){return this._page>0}};var Ha,jn=class extends ve{constructor({hydrate:e,pageSize:t,index:r,...s}){super({initial:[],...s});this._upToPage=1;this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:t}=await this.context.documents.findAllOids({collection:this.collection,limit:this._pageSize*this._upToPage,offset:0,index:this.index});this._hasNextPage=t,this.setValue(await Promise.all(e.map(this.hydrate)))};this.loadMore=async()=>{let{result:e,hasNextPage:t}=await this.context.documents.findAllOids({collection:this.collection,limit:this._pageSize,offset:this._pageSize*this._upToPage,index:this.index});this._hasNextPage=t,this._upToPage++,this.setValue([...this.current,...await Promise.all(e.map(this.hydrate))])};this[Ha]=e=>{Ue(this.index,e)||(this.index=e,this.execute())};this.index=r,this.hydrate=e,this._pageSize=t}static{Ha=me}get pageSize(){return this._pageSize}get hasMore(){return this._hasNextPage}};var Qa,Mn=class extends ve{constructor({index:e,hydrate:t,...r}){super({initial:[],...r});this.run=async()=>{let{result:e}=await this.context.documents.findAllOids({collection:this.collection,index:this.index});this.context.log("debug",`FindAllQuery: ${e.length} oids found: ${e}`),this.setValue(await Promise.all(e.map(this.hydrate)))};this[Qa]=e=>{Ue(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=t}static{Qa=me}};var Vn=class{constructor({collection:n,cache:e,entities:t,context:r,documentManager:s}){this.serializeIndex=n=>n?$e(n):"";this.get=n=>{let e=`get:${this.collection}:${n}`;return this.cache.getOrSet(e,()=>new kn({id:n,collection:this.collection,hydrate:this.hydrate,context:this.context,key:e}))};this.findOne=({index:n,key:e}={})=>{let t=e||`findOne:${this.collection}:${this.serializeIndex(n)}`;return this.cache.getOrSet(t,()=>new Bn({index:n,collection:this.collection,hydrate:this.hydrate,context:this.context,key:t}),r=>{r[me](n)})};this.findAll=({index:n,key:e}={})=>{let t=e||`findAll:${this.collection}:${this.serializeIndex(n)}`;return this.cache.getOrSet(t,()=>new Mn({index:n,collection:this.collection,hydrate:this.hydrate,context:this.context,key:t}),r=>{r[me](n)})};this.findPage=({index:n,pageSize:e,page:t,key:r})=>{let s=r||`findPage:${this.collection}:${this.serializeIndex(n)}:${e}`;return this.cache.getOrSet(s,()=>new Ln({index:n,collection:this.collection,hydrate:this.hydrate,context:this.context,key:s,pageSize:e,page:t}),o=>{o[me](n)})};this.findAllInfinite=({index:n,pageSize:e,key:t})=>{let r=t||`findAllInfinite:${this.collection}:${this.serializeIndex(n)}:${e}`;return this.cache.getOrSet(r,()=>new jn({index:n,collection:this.collection,hydrate:this.hydrate,context:this.context,key:r,pageSize:e}),s=>{s[me](n)})};this.cache=e,this.collection=n,this.hydrate=t.hydrate,this.context=r,this.documentManager=s,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),this.clone=this.documentManager.clone.bind(this.documentManager,this.collection)}};var Un=class extends oe{constructor({evictionTime:e=5*1e3,context:t}){super();this._cache=new Map;this._holds=new Set;this.enqueueQueryEviction=e=>{setTimeout(()=>{if(!e.subscribed){if(this._holds.has(e.key)){this.context.log("debug","QueryCache: keepAlive hold on query preserves after unsubscribe",e.key);return}this._cache.get(e.key)===e&&(this._cache.delete(e.key),this.context.log("debug","QueryCache: evicted query",e.key))}},this._evictionTime)};this.dropAll=()=>{this.context.log("debug","QueryCache: drop all",this._cache.size,"queries"),this._cache.forEach(e=>e.dispose()),this._cache.clear()};this.forceRefreshAll=()=>{this.context.log("debug","QueryCache: force refresh all",this._cache.size,"queries"),this._cache.forEach(e=>e.execute())};this._evictionTime=e,this.context=t,this.addDispose(this.context.internalEvents.subscribe("persistenceReset",this.forceRefreshAll))}get activeKeys(){return Array.from(this._cache.keys())}get(e){return this._cache.get(e)||null}set(e){return this._cache.set(e.key,e),e[Qi](this.enqueueQueryEviction),this.enqueueQueryEviction(e),e}getOrSet(e,t,r){let s=this.get(e);return s?(r?.(s),s):(this.context.log("debug","QueryCache: creating new query",e),this.set(t()))}keepAlive(e){this._holds.add(e),this.context.log("debug","QueryCache: keepAlive",e)}dropKeepAlive(e){this._holds.delete(e);let t=this.get(e);t&&(t.subscribed||(this.context.log("debug","QueryCache: dropKeepAlive on unsubscribed query; queuing eviction",e),this.enqueueQueryEviction(t)))}get keepAlives(){return this._holds}};var Wi=Symbol("handleMessage"),Wa,jt=class extends N{constructor({initialPresence:e,updateBatchTimeout:t=200,defaultProfile:r,ctx:s}){super();this._peers={};this._self={profile:{}};this._selfReplicaIds=new Set;this._peerIds=new Array;this.isSelf=(e,t)=>e.id===t.replicaId||this._selfReplicaIds.has(t.replicaId)||this._self.id===t.id;this[Wa]=async(e,t)=>{let r=!1,s=!1,o=new Set(this.peerIds);if(t.type==="presence-changed")this.isSelf(e,t.userInfo)?(this._self=t.userInfo,this._selfReplicaIds.add(t.userInfo.replicaId),s=!0,this.emit("selfChanged",t.userInfo)):(o.add(t.userInfo.id),this._peers[t.userInfo.id]=t.userInfo,r=!0,this.emit("peerChanged",t.userInfo.id,t.userInfo));else if(t.type==="sync-resp"){this._peers={},o.clear();for(let[a,d]of Object.entries(t.peerPresence))this.isSelf(e,d)?(this._self=d,this._selfReplicaIds.add(d.replicaId),s=!0,this.emit("selfChanged",d)):(r=!0,o.add(a),this._peers[a]=d,this.emit("peerChanged",a,d))}else if(t.type==="presence-offline"){o.delete(t.userId),this._selfReplicaIds.delete(t.replicaId);let a=this._peers[t.userId];delete this._peers[t.userId],r=!0,this.emit("peerLeft",t.userId,a)}r&&(this._peerIds=Array.from(o).sort(),this.emit("peersChanged",this._peers)),(r||s)&&this.emit("change")};this.update=async e=>{this._updateBatch.update({items:[{presence:e}]}),this.self.presence={...this.self.presence,...e},this.emit("selfChanged",this.self),this.emit("change")};this.flushPresenceUpdates=e=>{let t={presence:this.self.presence,internal:this.self.internal};for(let r of e)r.presence&&Object.assign(t.presence,r.presence),r.internal&&Object.assign(t.internal,r.internal);this.emit("update",t)};this.setViewId=e=>{this._updateBatch.update({items:[{internal:{viewId:e}}]}),this.self.internal.viewId=e,this.emit("selfChanged",this.self),this.emit("change")};this.setFieldId=(e,t=Date.now())=>{this._updateBatch.update({items:[{internal:{lastFieldId:e,lastFieldTimestamp:t}}]}),this.self.internal.lastFieldId=e,this.emit("selfChanged",this.self),this.emit("change")};this.getViewPeers=()=>this._peerIds.map(e=>this._peers[e]).filter(e=>this.self.internal.viewId===void 0||e.internal.viewId===this.self.internal.viewId);this.getFieldPeers=(e,t=60*1e3)=>this._peerIds.map(r=>this._peers[r]).filter(r=>r.internal.lastFieldId===e&&Date.now()-r.internal.lastFieldTimestamp<t);this.self.presence=e,this.self.profile=r,this.self.internal=pi,this.self.id="",this.self.replicaId="",s.meta.getLocalReplica().then(o=>{this.self.replicaId=o.id}),this._updateBatcher=new et(this.flushPresenceUpdates),this._updateBatch=this._updateBatcher.add({max:25,timeout:t,items:[],key:"default"})}static{Wa=Wi}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 Nn=class extends oe{constructor({endpointProvider:e,ctx:t}){super();this.onFileAdded=async e=>{if(!e.remote){this.ctx.log("debug","Uploading file",e.id,e.name);try{await this.uploadFile(e)}catch(t){this.ctx.log("error","File upload failed",t)}}};this.uploadFile=async(e,t={current:0,max:3})=>{let r=e.file;if(!r)throw new Error("Cannot upload a non-local file");let{files:s,token:o}=await this.endpointProvider.getEndpoints(),a=new FormData;a.append("file",r);try{let d=await this.ctx.environment.fetch(s+`/${e.id}`,{method:"POST",body:a,credentials:"include",headers:{Authorization:`Bearer ${o}`}});if(d.ok)return this.ctx.internalEvents.emit(`fileUploaded:${e.id}`,e),this.ctx.internalEvents.emit("fileUploaded",e),this.ctx.log("info","File upload successful"),{success:!0};{let m=await d.text();return this.ctx.log("error","File upload failed",d.status,m),d.status<500||t.current>=t.max?{success:!1,error:`Failed to upload file: ${d.status} ${m}`}:(await new Promise(h=>setTimeout(h,1e3)),this.uploadFile(e,{max:t.max,current:t.current+1}))}}catch(d){return this.ctx.log("error","File upload failed",d),t.current>=t.max?{success:!1,error:d.message}:(await new Promise(m=>setTimeout(m,1e3)),this.uploadFile(e,{max:t.max,current:t.current+1}))}};this.getFile=async(e,t={current:0,max:3})=>{let{files:r,token:s}=await this.endpointProvider.getEndpoints();try{let o=await this.ctx.environment.fetch(r+`/${e}`,{method:"GET",credentials:"include",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`}});return o.ok?{success:!0,data:await o.json()}:(this.ctx.log("error","File information fetch failed",o.status,await o.text()),o.status<500&&o.status!==404||t.current>=t.max?{success:!1,error:`Failed to fetch file: ${o.status}`}:(await new Promise(a=>setTimeout(a,1e3)),this.getFile(e,{current:t.current+1,max:t.max})))}catch(o){return this.ctx.log("error","File information fetch failed",o),t.current>=t.max?{success:!1,error:o.message}:(await new Promise(a=>setTimeout(a,1e3)),this.getFile(e,{current:t.current+1,max:t.max}))}};this.endpointProvider=e,this.ctx=t,this.addDispose(t.internalEvents.subscribe("fileAdded",this.onFileAdded))}};var ft=class extends N{constructor({interval:e=15*1e3,deadlineLength:t=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=t,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 zn=class extends N{constructor({endpointProvider:e,presence:t,interval:r=15*1e3,ctx: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.ctx.log("debug","Sending sync request",e);try{let{http:t,token:r}=await this.endpointProvider.getEndpoints(),s=await this.fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({messages:e}),credentials:"include"});if(s.ok){this.heartbeat.keepAlive();let o=await s.json(),a=Promise.all(o.messages.map(this.handleServerMessage));this._isConnected||(this._isConnected=!0,this.emit("onlineChange",!0)),await a}else{this.ctx.log("error","Sync request failed",s.status,await s.text()),this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1));let o=await s.json();ur(o)&&o.code===yt.TokenExpired&&(this.endpointProvider.clearCache(),this.heartbeat.keepAlive()),s.status>=500&&this.heartbeat.keepAlive()}}catch(t){this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1)),this.ctx.log("error",t),this.heartbeat.keepAlive()}};this.handleServerMessage=async e=>{e.type==="sync-resp"&&(this._hasSynced=!0,e.ackThisNonce&&(this.ctx.log("debug","Sending sync ack",e.ackThisNonce),await this.sendRequest([await this.ctx.meta.messageCreator.createAck(e.ackThisNonce)]))),this.emit("message",e)};this.throttledPresenceUpdate=Sr(e=>{this.sendRequest([e])},3e3);this.send=e=>{switch(e.type){case"presence-update":return this.throttledPresenceUpdate(e);case"sync":case"heartbeat":return this.sendRequest([e]);case"op":if(this._hasSynced)return this.sendRequest([e]);break}};this.start=async()=>{this.status!=="active"&&(await this.endpointProvider.getEndpoints(),this.heartbeat.start(!0),this._status="active")};this.destroy=()=>{this.dispose(),this.stop()};this.onHeartbeat=async()=>{this.sendRequest([await this.ctx.meta.messageCreator.createPresenceUpdate(this.presence.self),await this.ctx.meta.messageCreator.createSyncStep1()])};this.onHeartbeatMissed=async()=>{this.emit("onlineChange",!1),this.ctx.log("warn","Missed heartbeat"),this._isConnected=!1};this.syncOnce=async()=>{await this.sendRequest([await this.ctx.meta.messageCreator.createSyncStep1()])};this.ctx=s,this.presence=t,this.endpointProvider=e,this.heartbeat=new ft({interval:r}),this.heartbeat.subscribe("beat",this.onHeartbeat),this.heartbeat.subscribe("missed",this.onHeartbeatMissed)}get fetch(){return this.ctx.environment.fetch}get interval(){return this.heartbeat.interval}get hasSynced(){return this._hasSynced}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 Ji(i){this.message=i}Ji.prototype=new Error,Ji.prototype.name="InvalidCharacterError";var oo=typeof window<"u"&&window.atob&&window.atob.bind(window)||function(i){var n=String(i).replace(/=+$/,"");if(n.length%4==1)throw new Ji("'atob' failed: The string to be decoded is not correctly encoded.");for(var e,t,r=0,s=0,o="";t=n.charAt(s++);~t&&(e=r%4?64*e+t:t,r++%4)?o+=String.fromCharCode(255&e>>(-2*r&6)):0)t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(t);return o};function Ja(i){var n=i.replace(/-/g,"+").replace(/_/g,"/");switch(n.length%4){case 0:break;case 2:n+="==";break;case 3:n+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(oo(e).replace(/(.)/g,function(t,r){var s=r.charCodeAt(0).toString(16).toUpperCase();return s.length<2&&(s="0"+s),"%"+s}))}(n)}catch{return oo(n)}}function $n(i){this.message=i}function Ga(i,n){if(typeof i!="string")throw new $n("Invalid token specified");var e=(n=n||{}).header===!0?0:1;try{return JSON.parse(Ja(i.split(".")[e]))}catch(t){throw new $n("Invalid token specified: "+t.message)}}$n.prototype=new Error,$n.prototype.name="InvalidTokenError";var ao=Ga;var Kn=class{constructor(n,e){this.config=n;this.ctx=e;this.cached=null;this.tokenInfo=null;this.getEndpoints=async()=>{if(this.cached)return this.cached;let n;if(this.config.fetchAuth)n=await this.config.fetchAuth();else{let a=this.ctx.environment.fetch;n=await a(this.config.authEndpoint,{credentials:"include"}).then(d=>{if(d.ok)return d.json();throw new Error(`Auth endpoint returned non-200 response: ${d.status}`)})}L(n.accessToken,"No access token provided from auth endpoint");let e=ao(n.accessToken);L(e.url,"No sync endpoint provided from auth endpoint"),L(e.type!==void 0,"No replica type provided from auth endpoint"),this.tokenInfo={userId:e.sub,libraryId:e.lib,url:e.url,fileUrl:e.file,role:e.role,type:parseInt(e.type+"")};let t=new URL(e.url);t.protocol=t.protocol.replace("ws","http");let r=t.toString();t.protocol=t.protocol.replace("http","ws");let s=t.toString(),o=e.file;if(!o){let a=new URL(r);a.pathname=a.pathname+"/files",o=a.toString()}return this.cached={http:r,websocket:s,files:o,token:n.accessToken},this.cached};this.clearCache=()=>{this.cached=null};if(!n.authEndpoint&&!n.fetchAuth)throw new Error("Either authEndpoint or fetchAuth must be provided to ServerSyncEndpointProvider")}get type(){return this.tokenInfo?.type??Me.Realtime}};var qn=class extends N{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}},Hn=class{constructor(n,e){this.current=0;this.next=()=>{this.current=Math.min(this.max,this.current*this.factor)};this.reset=()=>{this.current=0};this.max=n,this.factor=e}};var Qn=class extends N{constructor({endpointProvider:e,ctx:t,presence:r}){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.heartbeat=new ft;this.reconnectScheduler=new qn(new Hn(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.ctx.log("debug","Sending queued message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e));this.connectQueue=[]}this.ctx.log("debug","Sync connected"),this.onOnlineChange(!0),this.reconnectScheduler.reset()};this.onOnlineChange=async e=>{this.ctx.log("info","Socket online change",e),!this.disposed&&(this.ctx.closing||(e?(this.ctx.log("debug","Starting sync"),this.hasStartedSync=!0,this.synced=!1,this.send(await this.ctx.meta.messageCreator.createPresenceUpdate(this.presence.self)),this.send(await this.ctx.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.ctx.log("warn","Ignoring incoming message (ignore incoming flag set)",e.data);return}let t=JSON.parse(e.data);switch(t.type){case"sync-resp":if(t.ackThisNonce&&this.send(await this.ctx.meta.messageCreator.createAck(t.ackThisNonce)),this.hasStartedSync=!0,this.synced=!0,this.syncQueue.length)if(t.overwriteLocalData)this.ctx.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",t),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",t);break;case"op-re":if(!this.synced){this.ctx.log("debug","Enqueueing op-re message because sync hasn't finished yet",t),this.incomingQueue.push(t);break}this.emit("message",t);break;case"heartbeat-response":this.heartbeat.keepAlive(),this.emit("message",t);break;default:this.synced&&this.emit("message",t);break}};this.onError=e=>{this.ctx.log("error",e),this.reconnectScheduler.next(),this.ctx.log("info","Attempting reconnect to websocket sync")};this.onClose=e=>{this.ctx.log("info","Sync disconnected"),this.onOnlineChange(!1),this.onError(e)};this.initializeSocket=async()=>{let e=await this.endpointProvider.getEndpoints();return this.socket=new this.ctx.environment.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.ctx.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===Gi?(this.ctx.log("debug","Sending message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e))):(this.ctx.log("debug","Enqueueing message until socket is open",JSON.stringify(e,null,2)),this.connectQueue.push(e)):this.synced?this.socket?.readyState===Gi&&(this.ctx.log("debug","Sending message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e))):this.hasStartedSync&&(this.ctx.log("debug","Enqueueing message until synced",JSON.stringify(e,null,2)),this.syncQueue.push(e))))};this.destroy=()=>{this.dispose(),this.stop()};this.start=async()=>{this.socket||(await 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.ctx=t,this.endpointProvider=e,this.presence=r,this.reconnectScheduler.subscribe("trigger",this.initializeSocket),this.heartbeat.subscribe("beat",this.sendHeartbeat)}get hasSynced(){return this.synced}ignoreIncoming(){this.incomingQueue=[],this._ignoreIncoming=!0}get isConnected(){return this.socket?.readyState===Gi}get status(){return this._status}},Gi=1;async function co(){try{let i=await navigator.permissions.query({name:"periodic-background-sync"});if(i.state==="granted"){let n=await navigator.serviceWorker.ready;if("periodicSync"in n)try{await n.periodicSync.register("verdant-sync",{minInterval:24*60*60*1e3})}catch(e){console.warn("Failed to register background sync:",e)}}else console.debug("Background sync permission is not granted:",i)}catch(i){console.error("Failed to initiate background sync:",i)}}var Wn=class extends N{constructor(e){super();this.mode="pull";this.hasSynced=!1;this.destroy=()=>{};this.isConnected=!1;this.status="paused";this.pullInterval=0;this.uploadFile=async()=>({success:!1,retry:!1});this.getFile=async()=>({success:!1,error:"Sync is not active"});this.syncOnce=async()=>{};this.presence=new jt({initialPresence:null,defaultProfile:null,ctx:e})}send(){}async start(){}stop(){}ignoreIncoming(){}reconnect(){}setMode(){}setPullInterval(){}},ht=class extends N{constructor({authEndpoint:e,fetchAuth:t,initialPresence:r,automaticTransportSelection:s=!0,autoStart:o,initialTransport:a,pullInterval:d,presenceUpdateBatchTimeout:m,defaultProfile:h,useBroadcastChannel:O,onOutgoingMessage:w,EXPERIMENTAL_backgroundSync:C},{ctx:y,onData:I}){super();this.broadcastChannel=null;this._activelySyncing=!1;this._hasSynced=!1;this.handleBroadcastChannelMessage=e=>{e.data.type==="sync"&&this.handleMessage(e.data.message,{source:"broadcastChannel"})};this.handleMessage=async(e,{source:t}={source:"network"})=>{if(!this.ctx.closing){if(e.type==="op-re"||e.type==="sync-resp")for(let r of e.operations)this.ctx.time.update(r.timestamp);switch(this.ctx.log("debug","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.ctx.meta.setGlobalAck(e.globalAckTimestamp);break;case"global-ack":await this.ctx.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.ctx.meta.setGlobalAck(e.globalAckTimestamp),await this.ctx.meta.updateLastSynced(e.ackedTimestamp),this._activelySyncing=!1,this.emit("syncingChange",!1),this._hasSynced=!0,this.emit("synced");break;case"need-since":this.emit("serverReset",e.since),this.ctx.files.onServerReset(e.since),this.activeSync.send(await this.ctx.meta.messageCreator.createSyncStep1(e.since));break;case"server-ack":await this.ctx.meta.updateLastSynced(e.timestamp)}t==="network"&&this.broadcastChannel?.postMessage({type:"sync",message:e}),this.presence[Wi](await this.ctx.meta.getLocalReplica(),e)}};this.handleOnlineChange=async e=>{if(this.emit("onlineChange",e),e){let t=await this.ctx.files.listUnsynced(),r=await Promise.allSettled(t.map(s=>this.fileSync.uploadFile(s)));r.some(s=>s.status==="rejected")&&this.ctx.log("error","Failed to upload unsynced files",r.filter(s=>s.status==="rejected").map(s=>s.reason))}};this.handlePresenceUpdate=async e=>{this.send(await this.ctx.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 t;e==="realtime"?t=this.webSocketSync:t=this.pushPullSync,t!==this.activeSync&&(this.ctx.log("debug","switching to",e,"mode"),this.activeSync.status==="active"&&t.start(),this.activeSync.stop(),this.activeSync=t)};this.setPullInterval=e=>{this.pushPullSync.setInterval(e)};this.send=async e=>{if(this.activeSync.status==="active"){let t=this.endpointProvider.tokenInfo?.userId;if(!t)throw new Q(Q.Code.Unexpected,void 0,"Active sync has invalid token info");(e.type==="sync"||e.type==="op")&&dr(e,t),await this.activeSync.send(e),this.onOutgoingMessage?.(e)}};this.uploadFile=async e=>(this.ctx.log("info","Uploading file",{name:e.name,type:e.type,id:e.id,size:e.file?.size}),this.activeSync.status==="active"?this.fileSync.uploadFile(e):{success:!1,retry:!1,error:"Sync is not active"});this.getFile=async e=>{if(this.activeSync.status==="active")return this.fileSync.getFile(e);if(await this.getSyncStartPromise(),this.activeSync.status==="paused")throw new Q(Q.Code.Offline,void 0,"Sync is not active");return this.fileSync.getFile(e)};this.getSyncStartPromise=(e=5e3)=>new Promise((t,r)=>{let s=setTimeout(()=>{r(new Error("Sync did not start in time")),o()},e),o=this.subscribe("onlineChange",a=>{a&&(clearTimeout(s),o(),t())})});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();this.syncOnce=()=>this.pushPullSync.syncOnce();if(this.onData=I,this.ctx=y,this.onOutgoingMessage=w,this.presence=new jt({initialPresence:r,defaultProfile:h,updateBatchTimeout:m,ctx:y}),this.endpointProvider=new Kn({authEndpoint:e,fetchAuth:t},y),this.webSocketSync=new Qn({endpointProvider:this.endpointProvider,presence:this.presence,ctx:y}),this.pushPullSync=new zn({endpointProvider:this.endpointProvider,presence:this.presence,interval:d,ctx:y}),this.fileSync=new Nn({endpointProvider:this.endpointProvider,ctx:y}),O&&"BroadcastChannel"in window&&(this.broadcastChannel=new BroadcastChannel(`verdant-${y.namespace}`),this.broadcastChannel.addEventListener("message",this.handleBroadcastChannelMessage)),a==="realtime"?this.activeSync=this.webSocketSync:this.activeSync=this.pushPullSync,this.presence.subscribe("update",this.handlePresenceUpdate),y.meta.events.subscribe("syncMessage",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 E=()=>{_&&clearTimeout(_);let k=this.presence.getViewPeers().length>0||s!=="peers-only"&&this.presence.selfReplicaIds.size>1;k&&this.mode==="pull"?this.setMode("realtime"):!k&&this.mode==="realtime"&&(_=setTimeout(()=>{this.presence.getViewPeers().length===0&&this.setMode("pull")},1e3))},_;this.presence.subscribe("peersChanged",E),s!=="peers-only"&&this.presence.subscribe("selfChanged",E)}o&&this.start(),C&&co()}get canDoRealtime(){return this.endpointProvider.type===Me.Realtime||this.endpointProvider.type===Me.PassiveRealtime||this.endpointProvider.type===Me.ReadOnlyRealtime}get syncing(){return this._activelySyncing}get hasSynced(){return this._hasSynced}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 lo(i){return i.operations.map(t=>t.timestamp).concat(i.baselines?.map(t=>t.timestamp)??[]).reduce((t,r)=>{let s=ln(r);return s>t?s:t},0)}var pt=class extends N{constructor(e){super();this.context=e;this.importingPromise=Promise.resolve();this.addData=async e=>{await this.importingPromise;try{let t=e.reset?lo(e):this.schema.version;return t<this.schema.version?(this.context.log("warn","Incoming reset sync data is from an old schema version",t,`(current ${this.schema.version})`),await this.import({data:{operations:e.operations,baselines:e.baselines??[],localReplica:void 0,schemaVersion:t},fileData:[],files:[]})):await this._entities.addData(e)}catch(t){throw this.context.log("critical","Sync failed",t),this.emit("developerError",new Error("Sync failed, see logs or cause",{cause:t})),t}};this.stats=async()=>{if(this.disposed)return{};let e=await this.context.documents.stats(),t=await this.context.meta.stats(),r=typeof navigator<"u"&&typeof navigator.storage<"u"&&"estimate"in navigator.storage?await navigator.storage.estimate():void 0,s=await this.context.files.stats(),o=Object.values(e).reduce((m,{size:h})=>m+h,0),a=t.baselinesSize.size+t.operationsSize.size,d=a/o;return{collections:e,meta:t,storage:r,totalMetaSize:a,totalCollectionsSize:o,metaToDataRatio:d,files:s,quotaUsage:r?.usage&&r?.quota?r.usage/r.quota:void 0}};this.close=async()=>{this.sync.ignoreIncoming(),await this._entities.flushAllBatches(),this.context.closing=!0,this.context.closeLock&&await this.context.closeLock,this.sync.stop(),this.sync.destroy(),await this._entities.destroy(),this.context.persistenceShutdownHandler.shutdown(),this.context.internalEvents.disable(),this.context.entityEvents.disable(),await new Promise(e=>{e()}),this.context.log?.("info","Client closed")};this.__dangerous__resetLocal=async()=>{this.sync.stop(),await Dn(this.namespace,indexedDB)};this.export=async({downloadRemoteFiles:e}={downloadRemoteFiles:!0})=>{this.context.log("info","Exporting data...");let t=await this.context.meta.export(),{fileData:r,files:s}=await this.context.files.export(e);return{data:t,fileData:r,files:s}};this.import=async({data:e,fileData:t,files:r})=>{let s=()=>{};this.importingPromise=new Promise(o=>{s=o}),this.context.log("info","Importing data..."),await so(this.context,{data:e,files:r,fileData:t}),s()};this.__dangerous__hardReset=async()=>{let e=await this.export();await this.import(e)};this.__cleanupFilesImmediately=()=>this.context.files.cleanupDeletedFiles();this.__manualRebase=()=>(this.context.meta.manualRebase(),new Promise(e=>{let t=this.subscribe("rebase",()=>{t(),e()})}));e.getClient=()=>this,this.collectionNames=Object.keys(e.schema.collections),this._sync=this.context.config.sync&&!e.schema.wip?new ht(this.context.config.sync,{onData:this.addData,ctx:this.context}):new Wn(this.context),e.schema.wip&&this.context.config.sync&&e.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 En({sync:this.sync,context:this.context}),this._entities=new In({ctx:this.context,files:this._fileManager}),this._queryCache=new Un({context:e,evictionTime:e.config.queries?.evictionTime}),this._documentManager=new un(this.schema,this._entities);let t=xr(()=>{this.emit("futureSeen")},300);this.context.globalEvents.subscribe("futureSeen",t),this.context.globalEvents.subscribe("resetToServer",()=>{this.emit("resetToServer")}),this.context.globalEvents.subscribe("operation",r=>{this.emit("operation",r)}),this.context.globalEvents.subscribe("rebase",()=>{this.emit("rebase")}),this.context.globalEvents.subscribe("fileSaved",r=>{this.emit("fileSaved",r)});for(let[r,s]of Object.entries(e.schema.collections)){let o=r;this[o]=new Vn({collection:o,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 schema(){return this.context.schema}get namespace(){return this.context.namespace}get undoHistory(){return this.context.undoHistory}get queries(){return this._queryCache}get batch(){return this.entities.batch}get __persistence(){return{meta:this.context.meta,queries:this.context.documents,files:this.context.files}}};var Jn=class{constructor(n,e){this.base=n;this.version=e;this.withMigrationTime=async(n,e)=>{this.overrideNow=()=>this.base.zero(n),await e(),this.overrideNow=void 0};this.update=this.base.update.bind(this.base);this.nowWithVersion=n=>this.base.now(n);this.zeroWithVersion=n=>this.base.zero(n)}get now(){return this.overrideNow?this.overrideNow():this.base.now(this.version)}get zero(){return this.base.zero(this.version)}};var Gn=class{constructor(n){this.value=n}deref(){return this.value}};var Ne=class extends oe{constructor(e,{log:t}={}){super();this.db=e;this.createTransaction=(e,t)=>{try{if(this.globalAbortController.signal.aborted)throw new Error("Global abort signal is already aborted");let r=Gs(this.db,e,t?.mode||"readonly",t?.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}catch(r){throw this.log?.("error","Failed to create abortable transaction for store names",e,r),r}};this.run=async(e,t,r)=>{if(this.disposed||r?.transaction?.error)return Promise.resolve(void 0);let o=(r?.transaction||this.createTransaction([e],r)).objectStore(e),a=t(o);return dt(a)};this.runAll=async(e,t,r)=>{if(this.disposed||r?.transaction?.error)return Promise.resolve([]);let o=(r?.transaction||this.createTransaction([e],r)).objectStore(e),a=t(o);return Promise.all(a.map(dt))};this.iterate=async(e,t,r,s)=>{let a=(s?.transaction||this.createTransaction([e],s)).objectStore(e),d=t(a);return Array.isArray(d)?Promise.all(d.map(m=>new Promise((h,O)=>{m.onsuccess=()=>{let w=m.result;w?r(w.value,a,w)?h():w.continue():h()},m.onerror=()=>{m.error&&Ge(m.error)?h():O(m.error)}}))).then(()=>{}):new Promise((m,h)=>{d.onsuccess=()=>{let O=d.result;O?r(O.value,a,O)?m():O.continue():m()},d.onerror=()=>{d.error&&Ge(d.error)?m():h(d.error)}})};this.clear=(e,t)=>this.run(e,r=>r.clear(),{mode:"readwrite",transaction:t});this.onVersionChange=e=>{if(this.log?.("warn",`Another tab has requested a version change for ${this.db.name}`),this.db.close(),typeof window<"u")try{window.location.reload()}catch(t){this.log?.("error","Failed to reload the page",t)}};this.log=t;let r=new AbortController,s=r.abort.bind(r);this.globalAbortController=r,this.db.addEventListener("versionchange",this.onVersionChange),this.addDispose(()=>{this.db.removeEventListener("versionchange",this.onVersionChange)})}};var Yn=class extends Ne{constructor(){super(...arguments);this.add=async e=>{let t=e.file?await Xa(e.file):void 0;await this.run("files",r=>r.put({id:e.id,remote:e.remote?"true":"false",deletedAt:null,name:e.name,type:e.type,url:e.url,buffer:t,timestamp:e.timestamp}),{mode:"readwrite"})};this.markUploaded=async e=>{if(this.disposed)return;let t=await this.getFileRaw(e);if(!t)throw new Error("File is not in local database");await this.run("files",r=>r.put({...t,remote:"true"}),{mode:"readwrite"})};this.get=async e=>{let t=await this.getFileRaw(e);return t?this.hydrateFileData(t):null};this.delete=e=>this.run("files",t=>t.delete(e),{mode:"readwrite"});this.markPendingDelete=async e=>{let t=await this.getFileRaw(e);if(!t)throw new Error("File is not in local database");await this.run("files",r=>r.put({...t,deletedAt:Date.now()}),{mode:"readwrite"})};this.listUnsynced=async()=>(await this.run("files",t=>t.index("remote").getAll("false"),{mode:"readonly"})).map(this.hydrateFileData);this.resetSyncedStatusSince=async e=>{let t=this.createTransaction(["files"],{mode:"readwrite"}),s=(await this.run("files",o=>o.index("remote").getAll("true"),{transaction:t})).filter(o=>!o.timestamp||!e||o.timestamp>e);await Promise.all(s.map(o=>this.run("files",a=>a.put({...o,remote:"false"}),{transaction:t})))};this.iterateOverPendingDelete=e=>this.iterate("files",t=>t.index("deletedAt").openCursor(IDBKeyRange.lowerBound(0,!0)),(t,r)=>{e(this.hydrateFileData(t),r)},{mode:"readwrite"});this.getAll=async e=>{let[t]=await Ki(this.db,["files"]);return t.map(this.hydrateFileData)};this.stats=async()=>({size:await Ye(this.db,"files")});this.loadFileContents=async(e,t)=>{if(e.file)return e.file;if(e.localPath)throw new Error("Local file paths are not supported in browser");if(e.url){let r=await t.environment.fetch(e.url);if(!r.ok)throw new Error(`Failed to download file ${e.url}: ${r.statusText}`);return r.blob()}throw new Error("File is missing url, file, and localPath")};this.hydrateFileData=e=>{e.remote=e.remote==="true";let t=e.buffer;return delete e.buffer,e.file=t?Ya(t,e.type,e.name):void 0,e};this.getFileRaw=async(e,{transaction:t}={})=>{if(this.disposed)return;let r=await this.run("files",s=>s.get(e),{mode:"readonly",transaction:t});if(r)return r}}};function Ya(i,n,e){return new File([new Blob([i],{type:n})],e??"blob",{type:n})}function Xa(i){return"__testReadBuffer"in i?Promise.resolve(i.__testReadBuffer):new Promise((n,e)=>{let t=new FileReader;t.onload=()=>{n(t.result)},t.onerror=e,t.readAsArrayBuffer(i)})}var Xn=class extends Ne{constructor(e,t){super(e,t);this.ctx=t;this.transaction=async(e,t)=>{let r=this.createTransaction(e.storeNames,{mode:e.mode,abort:e.abort});return await t(r)};this.getAckInfo=async()=>{let e=await this.run("info",t=>t.get("ack"));return e||{globalAckTimestamp:null}};this.setGlobalAck=async e=>{await this.run("info",t=>t.put({type:"ack",globalAckTimestamp:e}),{mode:"readwrite"})};this.getLocalReplica=async e=>this.run("info",t=>t.get("localReplicaInfo"),e);this.updateLocalReplica=async(e,t)=>{try{await this.run("info",r=>r.put({...e,type:"localReplicaInfo"}),{mode:"readwrite",transaction:t?.transaction})}catch(r){throw this.ctx.log("critical","Error updating local replica",e,r),r}};this.iterateDocumentBaselines=async(e,t,r)=>{await this.iterate("baselines",s=>{let o=K(e),[a,d]=Br(e),[m,h]=Lr(e);return[s.openCursor(IDBKeyRange.only(o)),s.openCursor(IDBKeyRange.bound(a,d,!1,!1)),s.openCursor(IDBKeyRange.bound(m,h,!1,!1))]},t,r)};this.iterateCollectionBaselines=async(e,t,r)=>{await this.iterate("baselines",s=>[s.openCursor(IDBKeyRange.bound(e,e+"\uFFFF",!1,!1))],t,r)};this.iterateAllBaselines=async(e,t)=>{await this.iterate("baselines",r=>r.index("timestamp").openCursor(),e,t)};this.getBaseline=(e,t)=>this.run("baselines",r=>r.get(e),t);this.setBaselines=async(e,t=Yi)=>{await this.runAll("baselines",r=>e.map(s=>r.put(s)),t)};this.deleteBaseline=async(e,t=Yi)=>{await this.run("baselines",r=>r.delete(e),t)};this.iterateDocumentOperations=(e,t,r)=>this.iterate("operations",s=>{let o=s.index("d_t"),a=Oe(e),d=r?.to?ge(e,r.to):Ae(e),m=IDBKeyRange.bound(a,d,!1,!1);return o.openCursor(m)},t,r);this.iterateEntityOperations=(e,t,r)=>this.iterate("operations",s=>{let o=Oe(e),a=r?.to?ge(e,r.to):Ae(e),d=IDBKeyRange.bound(o,a,!1,!1);return s.openCursor(d)},t,r);this.deleteEntityOperations=(e,t)=>this.iterate("operations",r=>{let s=Oe(e),o=t?.to?ge(e,t.to):Ae(e),a=IDBKeyRange.bound(s,o,!1,!1);return r.openCursor(a)},(r,s)=>{s.delete(r.oid_timestamp)},t);this.iterateCollectionOperations=(e,t,r)=>this.iterate("operations",s=>s.openCursor(IDBKeyRange.bound(e,e+"\uFFFF",!1,!1),"next"),t,r);this.iterateLocalOperations=(e,t)=>this.iterate("operations",r=>{let s=t?.after?ge(!0,t.after):Oe(!0),o=Ae(!0);return r.index("l_t").openCursor(IDBKeyRange.bound(s,o,!!t?.after,!1),"next")},e);this.iterateAllOperations=(e,t)=>this.iterate("operations",r=>{let s=t?.from?Oe(t.from):void 0,o=t?.before?Ae(t.before):Oe(!0),a=s&&o?IDBKeyRange.bound(s,o,!1,!0):s?IDBKeyRange.lowerBound(s,!1):o?IDBKeyRange.upperBound(o,!0):void 0;return r.index("timestamp").openCursor(a,"next")},e,t);this.addOperations=async(e,t=Yi)=>{let r=new Set;return await this.runAll("operations",s=>e.map(o=>(r.add(K(o.oid)),s.put(this.addOperationIndexes(o)))),t),Array.from(r)};this.reset=async({clearReplica:e,transaction:t}={})=>{let r=t||this.createTransaction(["info","operations","baselines"],{mode:"readwrite"});await Promise.all([this.resetLocalReplica(r,e),this.resetBaselines(r),this.resetOperations(r)])};this.stats=async()=>{let e=await Ye(this.db,"operations"),t=await Ye(this.db,"baselines");return{operationsSize:e,baselinesSize:t}};this.resetLocalReplica=async(e,t=!1)=>{if(t)return this.run("info",r=>r.delete("localReplicaInfo"),{mode:"readwrite",transaction:e});{let r=await this.getLocalReplica({transaction:e});r&&(r.ackedLogicalTime=null,r.lastSyncedLogicalTime=null,await this.run("info",s=>s.put({...r,type:"localReplicaInfo"}),{mode:"readwrite",transaction:e}))}};this.resetBaselines=async e=>this.clear("baselines",e);this.resetOperations=async e=>this.clear("operations",e);this.addOperationIndexes=e=>({...e,oid_timestamp:ge(e.oid,e.timestamp),l_t:ge(e.isLocal,e.timestamp),d_t:ge(K(e.oid),e.timestamp)});this.addDispose(()=>(this.ctx.log("info","Closing metadata DB for",this.ctx.namespace),we(e)))}},Yi={mode:"readwrite"};var uo=[ec,tc,nc,ic,rc,sc],Za=uo.length;function Xi({indexedDB:i=window.indexedDB,namespace:n,log:e}){return new Promise((t,r)=>{let s=i.open(Bt(n),Za),o=!1;s.onupgradeneeded=async a=>{let d=s.result,m=s.transaction,h=uo.slice(a.oldVersion);for(let O of h)await O(d,m);await new Promise((O,w)=>{m.addEventListener("complete",O),m.addEventListener("error",w)}),a.oldVersion||(o=!0)},s.onerror=()=>{console.error("Error opening database",s.error),r(s.error)},s.onsuccess=()=>{t({db:s.result,wasInitialized:o})}})}async function ec(i,n){let e=i.createObjectStore("baselines",{keyPath:"oid"}),t=i.createObjectStore("operations",{keyPath:"oid_timestamp"}),r=i.createObjectStore("info",{keyPath:"type"});e.createIndex("timestamp","timestamp"),t.createIndex("isLocal_timestamp","isLocal_timestamp"),t.createIndex("documentOid_timestamp","documentOid_timestamp")}async function tc(i,n){let e=n.objectStore("operations");await new Promise((t,r)=>{let s=e.openCursor();s.onsuccess=()=>{let o=s.result;if(o){let{isLocal_timestamp:a,documentOid_timestamp:d,...m}=o.value;o.update({...m,l_t:a,d_t:d}),o.continue()}else t()},s.onerror=o=>{r(s.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 nc(i,n){n.objectStore("operations").createIndex("timestamp","timestamp")}async function ic(i,n){let e=i.createObjectStore("files",{keyPath:"id"});e.createIndex("remote","remote"),e.createIndex("deletedAt","deletedAt")}async function rc(i,n){let e=n.objectStore("operations");await new Promise((r,s)=>{let o=e.openCursor();o.onsuccess=()=>{let a=o.result;if(a){let d=li(a.value);d.oid_timestamp!==a.primaryKey?(a.delete(),e.put(d)):a.update(d),a.continue()}else r()},o.onerror=a=>{s(o.error)}});let t=n.objectStore("baselines");await new Promise((r,s)=>{let o=t.openCursor();o.onsuccess=()=>{let a=o.result;if(a){let d=li(a.value);d.oid!==a.primaryKey?(a.delete(),t.put(d)):a.update(d),a.continue()}else r()},o.onerror=a=>{s(o.error)}})}async function sc(i,n){n.objectStore("files").createIndex("timestamp","timestamp")}var oc=i=>IDBKeyRange.only(Se(i.equals)),ac=i=>{},cc=i=>{let n=i.gte||i.gt,e=i.lte||i.lt;return n===e?IDBKeyRange.only(Se(n)):n?e?IDBKeyRange.bound(Se(n),Se(e),!!i.gt,!!i.lt):IDBKeyRange.lowerBound(Se(n),!!i.gt):IDBKeyRange.upperBound(Se(e),!!i.lt)},lc=(i,n,e)=>{let t=i.collections[n].compounds[e.where];L(t,`Index ${e.where} does not exist on collection ${n}`);let r=Object.keys(e.match).sort((d,m)=>t.of.indexOf(d)-t.of.indexOf(m));for(let d of r)if(t.of.indexOf(d)!==r.indexOf(d))throw new Error(`Compound index ${e.where} does not have ${d} at the start of its order`);let s=r.map(d=>e.match[d]);if(r.length===t.of.length)return IDBKeyRange.only(ge(...s));let o=Oe(...s),a=Ae(...s);return IDBKeyRange.bound(o,a)};function dc(i){let n=i.startsWith,e=i.startsWith+"\uFFFF";return IDBKeyRange.bound(n,e)}function Zi(i,n,e){if(e)return tn(e)?cc(e):en(e)?oc(e):vi(e)?ac(e):nn(e)?dc(e):lc(i,n,e)}var Zn=class extends Ne{constructor(e,t){super(e,{log:t.log});this.close=async()=>{await this.dispose()};this.stats=async()=>{let e=Object.keys(this.ctx.schema.collections),t={};return await Promise.all(e.map(async r=>{let s=await Ye(this.db,r);t[r]=s})),t};this.findOneOid=async e=>{let t=await this.run(e.collection,r=>{let s=e.index?.where?r.index(e.index.where):r,o=e.index?.order==="desc"?"prev":"next",a=Zi(this.ctx.schema,e.collection,e.index);return s.openCursor(a,o)},{mode:"readonly"});return t?ee(e.collection,t.primaryKey.toString()):null};this.findAllOids=async({collection:e,index:t,offset:r,limit:s})=>{let a=this.createTransaction([e],{mode:"readonly"}).objectStore(e),d=t?.where?a.index(t.where):a,m=t?.order==="desc"?"prev":"next",h=Zi(this.ctx.schema,e,t),O=d.openCursor(h,m),w=!1;return{result:await new Promise((y,I)=>{let E=!r,_=0,D=new Set;O.onsuccess=()=>{_++;let k=O.result;if(!k){y(Array.from(D));return}r&&!E?(k.advance(r),E=!0):((!s||D.size<s)&&D.add(ee(e,k.primaryKey.toString())),s&&_>s?(w=!0,y(Array.from(D))):k.continue())},O.onerror=()=>{O.error?.name==="InvalidStateError"?(this.ctx.log("error","find query failed with InvalidStateError",O.error),y([])):O.error&&Ge(O.error)?y([]):I(O.error)}}),hasNextPage:w}};this.saveEntities=async(e,t)=>{let r={transaction:this.createTransaction(t.collections,{mode:"readwrite",abort:t.abort})},s=await Promise.allSettled(e.map(async a=>{let d=a.getSnapshot();try{await this.saveDocument(a.oid,d,r)}catch(m){throw this.ctx.log("error",`Error saving document ${a.oid} (${JSON.stringify(d)})`,m),m instanceof Error?m:new Error("Unknown error saving document")}})),o=s.filter(a=>a.status==="rejected");if(o.length){if(o.length===s.length)throw new Error("Failed to save any documents. Something must be quite wrong.");this.ctx.log("error","Failed to save documents:",o,". See logs above. This only affects querying these documents. Let's hope a future attempt will correct them...")}r.transaction.commit()};this.reset=async()=>{let e=Object.keys(this.ctx.schema.collections),t=this.createTransaction(e,{mode:"readwrite"});await Promise.all(e.map(r=>this.run(r,s=>s.clear(),{transaction:t}))),this.ctx.entityEvents.emit("collectionsChanged",e),this.ctx.log("info","\u{1F4A8} Reset queryable storage")};this.saveDocument=async(e,t,{transaction:r})=>{this.ctx.log("debug",`Saving document indexes for querying ${e}`);let{collection:s,id:o}=ue(e);try{if(!t)await this.run(s,a=>a.delete(o),{mode:"readwrite",transaction:r}),this.ctx.log("debug",`Deleted document indexes for querying ${e}`);else{let a=this.ctx.schema.collections[s],d=ui(a,t);d["@@@snapshot"]=JSON.stringify(t),await this.run(s,m=>m.put(d),{mode:"readwrite",transaction:r}),this.ctx.log("debug",`Save complete for ${e}`,d)}}catch(a){throw this.ctx.log("error",`Error saving document ${e}`,a),a}};this.ctx=t,this.addDispose(()=>(this.ctx.log("info","Closing document database for",this.ctx.namespace),we(this.db)))}};async function fo(i,n,e,t,r){r?.("debug","Upgrading database",n,"to version",e);function s(o,a){let d=i.open(ut(n),e),m=!1;d.onupgradeneeded=h=>{let O=d.transaction;t(O,d.result,h),m=!0},d.onsuccess=async h=>{m?(await we(d.result),o(d.result)):a(new Error("Database was not upgraded when a version change was expected"))},d.onerror=h=>{a(d.error||new Error("Unknown error"))},d.onblocked=h=>{r?.("Database upgrade blocked!")}}return new Promise(s)}async function er({indexedDB:i=$i,namespace:n,version:e,log:t}){t?.("debug","Opening database",n,"at version",e);let r=await Ys(ut(n),e,i);return r.addEventListener("versionchange",s=>{r.close()}),r.addEventListener("close",()=>{t?.("warn","Database closed",n)}),r}var mt=class{constructor(n=window.indexedDB){this.indexedDB=n;this.name="IdbPersistence";this.getNamespaces=async()=>{let n=await this.indexedDB.databases();return Array.from(new Set(n.map(Xs).filter(e=>!!e)))};this.getNamespaceVersion=async n=>{let e=ut(n),r=(await this.indexedDB.databases()).find(s=>s.name===e);return r?r.version??0:0};this.deleteNamespace=async(n,e)=>{await Promise.all([Pn(Bt(n),this.indexedDB),Pn([n,"collections"].join("_"),this.indexedDB)])};this.openNamespace=async n=>new tr(this.indexedDB,n);this.copyNamespace=async(n,e,t)=>{let r={...t,namespace:n},s={...t,namespace:e},{db:o}=await Xi({indexedDB:this.indexedDB,log:r.log,namespace:r.namespace}),a=await er({indexedDB:this.indexedDB,namespace:r.namespace,version:r.schema.version,log:r.log});r.log("info",`Copying data from ${r.namespace} to ${s.namespace}`),await qi(o,Bt(s.namespace),s,this.indexedDB),await qi(a,ut(s.namespace),s,this.indexedDB),await we(o),await we(a)}}},tr=class{constructor(n,e){this.indexedDB=n;this.namespace=e;this.openMetadata=async n=>{let{db:e}=await Xi({indexedDB:this.indexedDB,log:n.log,namespace:this.namespace});return this.metadataDb=e,n.persistenceShutdownHandler.register(()=>we(e)),new Xn(e,n)};this.openDocuments=async n=>{let e=await er({version:n.schema.version,indexedDB:this.indexedDB,log:n.log,namespace:this.namespace});return n.persistenceShutdownHandler.register(()=>we(e)),new Zn(e,n)};this.applyMigration=async(n,e)=>{n.log("debug","Applying migration",e.newSchema.version,e),await fo(this.indexedDB,this.namespace,e.newSchema.version,(t,r)=>{for(let s of e.addedCollections)r.createObjectStore(s,{keyPath:e.newSchema.collections[s].primaryKey,autoIncrement:!1});for(let s of e.allCollections){let o=t.objectStore(s);for(let a of e.addedIndexes[s]||[])o.createIndex(a.name,a.name,{multiEntry:a.multiEntry});for(let a of e.removedIndexes[s]||[])o.deleteIndex(a.name)}for(let s of e.removedCollections)t.objectStore(s).clear()},n.log)}}openFiles(n){if(!this.metadataDb)throw new Error("Metadata database must be opened first. This is a bug in Verdant.");return Promise.resolve(new Yn(this.metadataDb,n))}};var gt=class extends N{constructor(){super(...arguments);this._undoable=[];this._undone=[];this.undo=async()=>{let e=this._undoable.pop();if(e){let t=await e();return t&&this._undone.push(t),this.emit("change"),!0}return!1};this.redo=async()=>{let e=this._undone.pop();if(e){let t=await e();return t&&this._undoable.push(t),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}get undoLength(){return this._undoable.length}get redoLength(){return this._undone.length}};var ei=class{constructor(n){this.init=n;this._initializing=!1;this.initialize=async n=>{if(typeof window>"u"&&!n.environment)throw new Error("A Verdant client was initialized in an environment without a global Window or `environment` configuration. 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 the environment to the ClientDescriptor options.");if(this._initializing||this._resolvedValue)return this._readyPromise;this._initializing=!0;try{let e=new Jn(new sn,n.schema.version),t=n.environment||uc,r={closing:!1,entityEvents:new N,globalEvents:new N,internalEvents:new N,log:n.log||Or,migrations:n.migrations,namespace:n.namespace,originalNamespace:n.namespace,schema:n.schema,oldSchemas:n.oldSchemas,time:e,undoHistory:n.undoHistory||new gt,weakRef:a=>n.EXPERIMENTAL_weakRefs?new WeakRef(a):new Gn(a),patchCreator:new je(()=>e.now),config:{files:n.files,sync:n.sync,persistence:{disableRebasing:n.disableRebasing,rebaseTimeout:n.rebaseTimeout},queries:n.queries},persistence:n.persistence||new mt(t.indexedDB),environment:t,persistenceShutdownHandler:new Fe(n.log),pauseRebasing:!1,getClient(){throw new Q(Q.Code.Unexpected,void 0,"Client not yet initialized. This is a Verdant bug, please report it.")}};r.log("info","Initializing client",{namespace:r.namespace,version:n.schema.version,persistence:r.persistence.name});let s=await Lt(r),o=new pt(s);return this.resolveReady(o),this._resolvedValue=o,o}catch(e){throw e instanceof Error?(this.rejectReady(e),e):new Error("Unknown error initializing storage")}finally{this._initializing=!1}};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 Dn(this.namespace)};this._readyPromise=new Promise((e,t)=>{this.resolveReady=e,this.rejectReady=t}),this._namespace=n.namespace}get namespace(){return this._namespace}get current(){return this._resolvedValue}get readyPromise(){return this._readyPromise}get schema(){return this.init.schema}},uc={WebSocket:typeof WebSocket<"u"?WebSocket:void 0,fetch:typeof window<"u"?window.fetch.bind(window):fetch,indexedDB:typeof indexedDB<"u"?indexedDB:void 0};var fc={private:ze.onlyMe(),public:void 0};function hc(i,{port:n=3242,initialPresence:e={}}={}){let t=localStorage.getItem("verdant-userId");return t||(t=`user-${Math.random().toString(36).slice(2)}`,localStorage.setItem("verdant-userId",t)),{defaultProfile:{id:t},initialPresence:e,authEndpoint:`http://localhost:${n}/auth/${i}?userId=${t}`}}var nr=Te(He(),1);function pc(i){return i?nr.default.slug():(0,nr.default)()}window.Verdant=ir;
14
16
  //# sourceMappingURL=index.js.map