@verdant-web/store 4.0.0-next.0 → 4.0.0-next.1

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,14 @@
1
1
  "use strict";var oo=Object.create;var Rt=Object.defineProperty;var ao=Object.getOwnPropertyDescriptor;var co=Object.getOwnPropertyNames;var lo=Object.getPrototypeOf,uo=Object.prototype.hasOwnProperty;var fo=(n,i)=>()=>(n&&(i=n(n=0)),i);var oe=(n,i)=>()=>(i||n((i={exports:{}}).exports,i),i.exports),or=(n,i)=>{for(var e in i)Rt(n,e,{get:i[e],enumerable:!0})},ar=(n,i,e,t)=>{if(i&&typeof i=="object"||typeof i=="function")for(let r of co(i))!uo.call(n,r)&&r!==e&&Rt(n,r,{get:()=>i[r],enumerable:!(t=ao(i,r))||t.enumerable});return n};var Te=(n,i,e)=>(e=n!=null?oo(lo(n)):{},ar(i||!n||!n.__esModule?Rt(e,"default",{value:n,enumerable:!0}):e,n)),Xe=n=>ar(Rt({},"__esModule",{value:!0}),n);var Gn=oe((oc,cr)=>{cr.exports=function(i,e){var t="000000000"+i;return t.substr(t.length-e)}});var dr=oe((ac,lr)=>{var ho=Gn(),po=typeof window=="object"?window:self,mo=Object.keys(po).length,go=navigator.mimeTypes?navigator.mimeTypes.length:0,yo=ho((go+navigator.userAgent.length).toString(36)+mo.toString(36),4);lr.exports=function(){return yo}});var pr=oe((cc,hr)=>{var Xn,ur=typeof window<"u"&&(window.crypto||window.msCrypto)||typeof self<"u"&&self.crypto;ur?(fr=Math.pow(2,32)-1,Xn=function(){return Math.abs(ur.getRandomValues(new Uint32Array(1))[0]/fr)}):Xn=Math.random;var fr;hr.exports=Xn});var ze=oe((lc,br)=>{var Tt=dr(),mr=Gn(),bo=pr(),ht=0,ei=4,Ft=36,gr=Math.pow(Ft,ei);function Zn(){return mr((bo()*gr<<0).toString(Ft),ei)}function yr(){return ht=ht<gr?ht:0,ht++,ht-1}function pt(){var n="c",i=new Date().getTime().toString(Ft),e=mr(yr().toString(Ft),ei),t=Tt(),r=Zn()+Zn();return n+i+e+t+r}pt.slug=function(){var i=new Date().getTime().toString(36),e=yr().toString(36).slice(-4),t=Tt().slice(0,1)+Tt().slice(-1),r=Zn().slice(-2);return i.slice(-2)+e+t+r};pt.isCuid=function(i){return typeof i!="string"?!1:!!i.startsWith("c")};pt.isSlug=function(i){if(typeof i!="string")return!1;var e=i.length;return e>=7&&e<=10};pt.fingerprint=Tt;br.exports=pt});var Fr=oe((Rr,Tr)=>{(function(n){var i;typeof Rr=="object"?Tr.exports=n():typeof define=="function"&&define.amd?define(n):(typeof window<"u"?i=window:typeof global<"u"?i=global:typeof self<"u"&&(i=self),i.objectHash=n())})(function(){return function n(i,e,t){function r(a,d){if(!e[a]){if(!i[a]){var p=typeof require=="function"&&require;if(!d&&p)return p(a,!0);if(s)return s(a,!0);throw new Error("Cannot find module '"+a+"'")}d=e[a]={exports:{}},i[a][0].call(d.exports,function(m){var D=i[a][1][m];return r(D||m)},d,d.exports,n,i,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(n,i,e){(function(t,r,s,o,a,d,p,m,D){"use strict";var v=n("crypto");function P(y,I){I=E(y,I);var u;return(u=I.algorithm!=="passthrough"?v.createHash(I.algorithm):new F).write===void 0&&(u.write=u.update,u.end=u.update),_(I,u).dispatch(y),u.update||u.end(""),u.digest?u.digest(I.encoding==="buffer"?void 0:I.encoding):(y=u.read(),I.encoding!=="buffer"?y.toString(I.encoding):y)}(e=i.exports=P).sha1=function(y){return P(y)},e.keys=function(y){return P(y,{excludeValues:!0,algorithm:"sha1",encoding:"hex"})},e.MD5=function(y){return P(y,{algorithm:"md5",encoding:"hex"})},e.keysMD5=function(y){return P(y,{algorithm:"md5",encoding:"hex",excludeValues:!0})};var b=v.getHashes?v.getHashes().slice():["sha1","md5"],x=(b.push("passthrough"),["buffer","hex","binary","base64"]);function E(y,I){var u={};if(u.algorithm=(I=I||{}).algorithm||"sha1",u.encoding=I.encoding||"hex",u.excludeValues=!!I.excludeValues,u.algorithm=u.algorithm.toLowerCase(),u.encoding=u.encoding.toLowerCase(),u.ignoreUnknown=I.ignoreUnknown===!0,u.respectType=I.respectType!==!1,u.respectFunctionNames=I.respectFunctionNames!==!1,u.respectFunctionProperties=I.respectFunctionProperties!==!1,u.unorderedArrays=I.unorderedArrays===!0,u.unorderedSets=I.unorderedSets!==!1,u.unorderedObjects=I.unorderedObjects!==!1,u.replacer=I.replacer||void 0,u.excludeKeys=I.excludeKeys||void 0,y===void 0)throw new Error("Object argument required.");for(var h=0;h<b.length;++h)b[h].toLowerCase()===u.algorithm.toLowerCase()&&(u.algorithm=b[h]);if(b.indexOf(u.algorithm)===-1)throw new Error('Algorithm "'+u.algorithm+'" not supported. supported values: '+b.join(", "));if(x.indexOf(u.encoding)===-1&&u.algorithm!=="passthrough")throw new Error('Encoding "'+u.encoding+'" not supported. supported values: '+x.join(", "));return u}function S(y){if(typeof y=="function")return/^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i.exec(Function.prototype.toString.call(y))!=null}function _(y,I,u){u=u||[];function h(l){return I.update?I.update(l,"utf8"):I.write(l,"utf8")}return{dispatch:function(l){return this["_"+((l=y.replacer?y.replacer(l):l)===null?"null":typeof l)](l)},_object:function(l){var w,O=Object.prototype.toString.call(l),j=/\[object (.*)\]/i.exec(O);if(j=(j=j?j[1]:"unknown:["+O+"]").toLowerCase(),0<=(O=u.indexOf(l)))return this.dispatch("[CIRCULAR:"+O+"]");if(u.push(l),s!==void 0&&s.isBuffer&&s.isBuffer(l))return h("buffer:"),h(l);if(j==="object"||j==="function"||j==="asyncfunction")return O=Object.keys(l),y.unorderedObjects&&(O=O.sort()),y.respectType===!1||S(l)||O.splice(0,0,"prototype","__proto__","constructor"),y.excludeKeys&&(O=O.filter(function(k){return!y.excludeKeys(k)})),h("object:"+O.length+":"),w=this,O.forEach(function(k){w.dispatch(k),h(":"),y.excludeValues||w.dispatch(l[k]),h(",")});if(!this["_"+j]){if(y.ignoreUnknown)return h("["+j+"]");throw new Error('Unknown object type "'+j+'"')}this["_"+j](l)},_array:function(l,k){k=k!==void 0?k:y.unorderedArrays!==!1;var O=this;if(h("array:"+l.length+":"),!k||l.length<=1)return l.forEach(function(M){return O.dispatch(M)});var j=[],k=l.map(function(M){var B=new F,q=u.slice();return _(y,B,q).dispatch(M),j=j.concat(q.slice(u.length)),B.read().toString()});return u=u.concat(j),k.sort(),this._array(k,!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:"),S(l)?this.dispatch("[native]"):this.dispatch(l.toString()),y.respectFunctionNames!==!1&&this.dispatch("function-name:"+String(l.name)),y.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,y.unorderedSets!==!1)},_set:function(l){return h("set:"),l=Array.from(l),this._array(l,y.unorderedSets!==!1)},_file:function(l){return h("file:"),this.dispatch([l.name,l.size,l.type,l.lastModfied])},_blob:function(){if(y.ignoreUnknown)return h("[blob]");throw Error(`Hashing Blob objects is currently not supported
2
2
  (see https://github.com/puleos/object-hash/issues/26)
3
3
  Use "options.replacer" or "options.ignoreUnknown"
4
- `)},_domwindow:function(){return h("domwindow")},_bigint:function(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 F(){return{buf:"",write:function(y){this.buf+=y},end:function(y){this.buf+=y},read:function(){return this.buf}}}e.writeToStream=function(y,I,u){return u===void 0&&(u=I,I={}),_(I=E(y,I),u).dispatch(y)}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/fake_9a5aa49d.js","/")},{buffer:3,crypto:5,lYpoI2:11}],2:[function(n,i,e){(function(t,r,s,o,a,d,p,m,D){(function(v){"use strict";var P=typeof Uint8Array<"u"?Uint8Array:Array,b="+".charCodeAt(0),x="/".charCodeAt(0),E="0".charCodeAt(0),S="a".charCodeAt(0),_="A".charCodeAt(0),F="-".charCodeAt(0),y="_".charCodeAt(0);function I(u){return u=u.charCodeAt(0),u===b||u===F?62:u===x||u===y?63:u<E?-1:u<E+10?u-E+26+26:u<_+26?u-_:u<S+26?u-S+26:void 0}v.toByteArray=function(u){var h,l;if(0<u.length%4)throw new Error("Invalid string. Length must be a multiple of 4");var w=u.length,w=u.charAt(w-2)==="="?2:u.charAt(w-1)==="="?1:0,O=new P(3*u.length/4-w),j=0<w?u.length-4:u.length,k=0;function M(B){O[k++]=B}for(h=0;h<j;h+=4,0)M((16711680&(l=I(u.charAt(h))<<18|I(u.charAt(h+1))<<12|I(u.charAt(h+2))<<6|I(u.charAt(h+3))))>>16),M((65280&l)>>8),M(255&l);return w==2?M(255&(l=I(u.charAt(h))<<2|I(u.charAt(h+1))>>4)):w==1&&(M((l=I(u.charAt(h))<<10|I(u.charAt(h+1))<<4|I(u.charAt(h+2))>>2)>>8&255),M(255&l)),O},v.fromByteArray=function(u){var h,l,w,O,j=u.length%3,k="";function M(B){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(B)}for(h=0,w=u.length-j;h<w;h+=3)l=(u[h]<<16)+(u[h+1]<<8)+u[h+2],k+=M((O=l)>>18&63)+M(O>>12&63)+M(O>>6&63)+M(63&O);switch(j){case 1:k=(k+=M((l=u[u.length-1])>>2))+M(l<<4&63)+"==";break;case 2:k=(k=(k+=M((l=(u[u.length-2]<<8)+u[u.length-1])>>10))+M(l>>4&63))+M(l<<2&63)+"="}return k}})(e===void 0?this.base64js={}:e)}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("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(n,i,e){(function(t,r,b,o,a,d,p,m,D){var v=n("base64-js"),P=n("ieee754");function b(c,f,g){if(!(this instanceof b))return new b(c,f,g);var A,C,T,L,H=typeof c;if(f==="base64"&&H=="string")for(c=(L=c).trim?L.trim():L.replace(/^\s+|\s+$/g,"");c.length%4!=0;)c+="=";if(H=="number")A=te(c);else if(H=="string")A=b.byteLength(c,f);else{if(H!="object")throw new Error("First argument needs to be a number, array or string.");A=te(c.length)}if(b._useTypedArrays?C=b._augment(new Uint8Array(A)):((C=this).length=A,C._isBuffer=!0),b._useTypedArrays&&typeof c.byteLength=="number")C._set(c);else if(Q(L=c)||b.isBuffer(L)||L&&typeof L=="object"&&typeof L.length=="number")for(T=0;T<A;T++)b.isBuffer(c)?C[T]=c.readUInt8(T):C[T]=c[T];else if(H=="string")C.write(c,0,f);else if(H=="number"&&!b._useTypedArrays&&!g)for(T=0;T<A;T++)C[T]=0;return C}function x(c,f,g,A){return b._charsWritten=At(function(C){for(var T=[],L=0;L<C.length;L++)T.push(255&C.charCodeAt(L));return T}(f),c,g,A)}function E(c,f,g,A){return b._charsWritten=At(function(C){for(var T,L,H=[],G=0;G<C.length;G++)L=C.charCodeAt(G),T=L>>8,L=L%256,H.push(L),H.push(T);return H}(f),c,g,A)}function S(c,f,g){var A="";g=Math.min(c.length,g);for(var C=f;C<g;C++)A+=String.fromCharCode(c[C]);return A}function _(c,f,g,T){T||(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 C,T=c.length;if(!(T<=f))return g?(C=c[f],f+1<T&&(C|=c[f+1]<<8)):(C=c[f]<<8,f+1<T&&(C|=c[f+1])),C}function F(c,f,g,T){T||(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 C,T=c.length;if(!(T<=f))return g?(f+2<T&&(C=c[f+2]<<16),f+1<T&&(C|=c[f+1]<<8),C|=c[f],f+3<T&&(C+=c[f+3]<<24>>>0)):(f+1<T&&(C=c[f+1]<<16),f+2<T&&(C|=c[f+2]<<8),f+3<T&&(C|=c[f+3]),C+=c[f]<<24>>>0),C}function y(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=_(c,f,g,!0),32768&A?-1*(65535-A+1):A}function I(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=F(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")),P.read(c,f,g,23,4)}function h(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")),P.read(c,f,g,52,8)}function l(c,f,g,A,C){if(C||(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"),Jn(f,65535)),C=c.length,!(C<=g))for(var T=0,L=Math.min(C-g,2);T<L;T++)c[g+T]=(f&255<<8*(A?T:1-T))>>>8*(A?T:1-T)}function w(c,f,g,A,C){if(C||(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"),Jn(f,4294967295)),C=c.length,!(C<=g))for(var T=0,L=Math.min(C-g,4);T<L;T++)c[g+T]=f>>>8*(A?T:3-T)&255}function O(c,f,g,A,C){C||(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"),Yn(f,32767,-32768)),c.length<=g||l(c,0<=f?f:65535+f+1,g,A,C)}function j(c,f,g,A,C){C||(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"),Yn(f,2147483647,-2147483648)),c.length<=g||w(c,0<=f?f:4294967295+f+1,g,A,C)}function k(c,f,g,A,C){C||(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"),rr(f,34028234663852886e22,-34028234663852886e22)),c.length<=g||P.write(c,f,g,A,23,4)}function M(c,f,g,A,C){C||(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"),rr(f,17976931348623157e292,-17976931348623157e292)),c.length<=g||P.write(c,f,g,A,52,8)}e.Buffer=b,e.SlowBuffer=b,e.INSPECT_MAX_BYTES=50,b.poolSize=8192,b._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}}(),b.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}},b.isBuffer=function(c){return!(c==null||!c._isBuffer)},b.byteLength=function(c,f){var g;switch(c+="",f||"utf8"){case"hex":g=c.length/2;break;case"utf8":case"utf-8":g=_e(c).length;break;case"ascii":case"binary":case"raw":g=c.length;break;case"base64":g=nr(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},b.concat=function(c,f){if(R(Q(c),`Usage: Buffer.concat(list, [totalLength])
5
- list should be an Array.`),c.length===0)return new b(0);if(c.length===1)return c[0];if(typeof f!="number")for(C=f=0;C<c.length;C++)f+=c[C].length;for(var g=new b(f),A=0,C=0;C<c.length;C++){var T=c[C];T.copy(g,A),A+=T.length}return g},b.prototype.write=function(c,f,g,A){isFinite(f)?isFinite(g)||(A=g,g=void 0):(G=A,A=f,f=g,g=G),f=Number(f)||0;var C,T,L,H,G=this.length-f;switch((!g||G<(g=Number(g)))&&(g=G),A=String(A||"utf8").toLowerCase()){case"hex":C=function(pe,re,se,X){se=Number(se)||0;var J=pe.length-se;(!X||J<(X=Number(X)))&&(X=J),R((J=re.length)%2==0,"Invalid hex string"),J/2<X&&(X=J/2);for(var Ge=0;Ge<X;Ge++){var sr=parseInt(re.substr(2*Ge,2),16);R(!isNaN(sr),"Invalid hex string"),pe[se+Ge]=sr}return b._charsWritten=2*Ge,Ge}(this,c,f,g);break;case"utf8":case"utf-8":T=this,L=f,H=g,C=b._charsWritten=At(_e(c),T,L,H);break;case"ascii":case"binary":C=x(this,c,f,g);break;case"base64":T=this,L=f,H=g,C=b._charsWritten=At(nr(c),T,L,H);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":C=E(this,c,f,g);break;default:throw new Error("Unknown encoding")}return C},b.prototype.toString=function(c,f,g){var A,C,T,L,H=this;if(c=String(c||"utf8").toLowerCase(),f=Number(f)||0,(g=g!==void 0?Number(g):H.length)===f)return"";switch(c){case"hex":A=function(G,pe,re){var se=G.length;(!pe||pe<0)&&(pe=0),(!re||re<0||se<re)&&(re=se);for(var X="",J=pe;J<re;J++)X+=K(G[J]);return X}(H,f,g);break;case"utf8":case"utf-8":A=function(G,pe,re){var se="",X="";re=Math.min(G.length,re);for(var J=pe;J<re;J++)G[J]<=127?(se+=ir(X)+String.fromCharCode(G[J]),X=""):X+="%"+G[J].toString(16);return se+ir(X)}(H,f,g);break;case"ascii":case"binary":A=S(H,f,g);break;case"base64":C=H,L=g,A=(T=f)===0&&L===C.length?v.fromByteArray(C):v.fromByteArray(C.slice(T,L));break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":A=function(G,pe,re){for(var se=G.slice(pe,re),X="",J=0;J<se.length;J+=2)X+=String.fromCharCode(se[J]+256*se[J+1]);return X}(H,f,g);break;default:throw new Error("Unknown encoding")}return A},b.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},b.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 C=(A=c.length-f<A-g?c.length-f+g:A)-g;if(C<100||!b._useTypedArrays)for(var T=0;T<C;T++)c[T+f]=this[T+g];else c._set(this.subarray(g,g+C),f)}},b.prototype.slice=function(c,f){var g=this.length;if(c=q(c,g,0),f=q(f,g,g),b._useTypedArrays)return b._augment(this.subarray(c,f));for(var A=f-c,C=new b(A,void 0,!0),T=0;T<A;T++)C[T]=this[T+c];return C},b.prototype.get=function(c){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(c)},b.prototype.set=function(c,f){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(c,f)},b.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]},b.prototype.readUInt16LE=function(c,f){return _(this,c,!0,f)},b.prototype.readUInt16BE=function(c,f){return _(this,c,!1,f)},b.prototype.readUInt32LE=function(c,f){return F(this,c,!0,f)},b.prototype.readUInt32BE=function(c,f){return F(this,c,!1,f)},b.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]},b.prototype.readInt16LE=function(c,f){return y(this,c,!0,f)},b.prototype.readInt16BE=function(c,f){return y(this,c,!1,f)},b.prototype.readInt32LE=function(c,f){return I(this,c,!0,f)},b.prototype.readInt32BE=function(c,f){return I(this,c,!1,f)},b.prototype.readFloatLE=function(c,f){return u(this,c,!0,f)},b.prototype.readFloatBE=function(c,f){return u(this,c,!1,f)},b.prototype.readDoubleLE=function(c,f){return h(this,c,!0,f)},b.prototype.readDoubleBE=function(c,f){return h(this,c,!1,f)},b.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"),Jn(c,255)),f>=this.length||(this[f]=c)},b.prototype.writeUInt16LE=function(c,f,g){l(this,c,f,!0,g)},b.prototype.writeUInt16BE=function(c,f,g){l(this,c,f,!1,g)},b.prototype.writeUInt32LE=function(c,f,g){w(this,c,f,!0,g)},b.prototype.writeUInt32BE=function(c,f,g){w(this,c,f,!1,g)},b.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"),Yn(c,127,-128)),f>=this.length||(0<=c?this.writeUInt8(c,f,g):this.writeUInt8(255+c+1,f,g))},b.prototype.writeInt16LE=function(c,f,g){O(this,c,f,!0,g)},b.prototype.writeInt16BE=function(c,f,g){O(this,c,f,!1,g)},b.prototype.writeInt32LE=function(c,f,g){j(this,c,f,!0,g)},b.prototype.writeInt32BE=function(c,f,g){j(this,c,f,!1,g)},b.prototype.writeFloatLE=function(c,f,g){k(this,c,f,!0,g)},b.prototype.writeFloatBE=function(c,f,g){k(this,c,f,!1,g)},b.prototype.writeDoubleLE=function(c,f,g){M(this,c,f,!0,g)},b.prototype.writeDoubleBE=function(c,f,g){M(this,c,f,!1,g)},b.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}},b.prototype.inspect=function(){for(var c=[],f=this.length,g=0;g<f;g++)if(c[g]=K(this[g]),g===e.INSPECT_MAX_BYTES){c[g+1]="...";break}return"<Buffer "+c.join(" ")+">"},b.prototype.toArrayBuffer=function(){if(typeof Uint8Array>"u")throw new Error("Buffer.toArrayBuffer not supported in this browser");if(b._useTypedArrays)return new b(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 B=b.prototype;function q(c,f,g){return typeof c!="number"?g:f<=(c=~~c)?f:0<=c||0<=(c+=f)?c:0}function te(c){return(c=~~Math.ceil(+c))<0?0:c}function Q(c){return(Array.isArray||function(f){return Object.prototype.toString.call(f)==="[object Array]"})(c)}function K(c){return c<16?"0"+c.toString(16):c.toString(16)}function _e(c){for(var f=[],g=0;g<c.length;g++){var A=c.charCodeAt(g);if(A<=127)f.push(c.charCodeAt(g));else for(var C=g,T=(55296<=A&&A<=57343&&g++,encodeURIComponent(c.slice(C,g+1)).substr(1).split("%")),L=0;L<T.length;L++)f.push(parseInt(T[L],16))}return f}function nr(c){return v.toByteArray(c)}function At(c,f,g,A){for(var C=0;C<A&&!(C+g>=f.length||C>=c.length);C++)f[C+g]=c[C];return C}function ir(c){try{return decodeURIComponent(c)}catch{return String.fromCharCode(65533)}}function Jn(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 Yn(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 rr(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")}b._augment=function(c){return c._isBuffer=!0,c._get=c.get,c._set=c.set,c.get=B.get,c.set=B.set,c.write=B.write,c.toString=B.toString,c.toLocaleString=B.toString,c.toJSON=B.toJSON,c.copy=B.copy,c.slice=B.slice,c.readUInt8=B.readUInt8,c.readUInt16LE=B.readUInt16LE,c.readUInt16BE=B.readUInt16BE,c.readUInt32LE=B.readUInt32LE,c.readUInt32BE=B.readUInt32BE,c.readInt8=B.readInt8,c.readInt16LE=B.readInt16LE,c.readInt16BE=B.readInt16BE,c.readInt32LE=B.readInt32LE,c.readInt32BE=B.readInt32BE,c.readFloatLE=B.readFloatLE,c.readFloatBE=B.readFloatBE,c.readDoubleLE=B.readDoubleLE,c.readDoubleBE=B.readDoubleBE,c.writeUInt8=B.writeUInt8,c.writeUInt16LE=B.writeUInt16LE,c.writeUInt16BE=B.writeUInt16BE,c.writeUInt32LE=B.writeUInt32LE,c.writeUInt32BE=B.writeUInt32BE,c.writeInt8=B.writeInt8,c.writeInt16LE=B.writeInt16LE,c.writeInt16BE=B.writeInt16BE,c.writeInt32LE=B.writeInt32LE,c.writeInt32BE=B.writeInt32BE,c.writeFloatLE=B.writeFloatLE,c.writeFloatBE=B.writeFloatBE,c.writeDoubleLE=B.writeDoubleLE,c.writeDoubleBE=B.writeDoubleBE,c.fill=B.fill,c.inspect=B.inspect,c.toArrayBuffer=B.toArrayBuffer,c}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("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(n,i,e){(function(t,r,v,o,a,d,p,m,D){var v=n("buffer").Buffer,P=4,b=new v(P);b.fill(0),i.exports={hash:function(x,E,S,_){for(var F=E(function(l,w){l.length%P!=0&&(O=l.length+(P-l.length%P),l=v.concat([l,b],O));for(var O,j=[],k=w?l.readInt32BE:l.readInt32LE,M=0;M<l.length;M+=P)j.push(k.call(l,M));return j}(x=v.isBuffer(x)?x:new v(x),_),8*x.length),E=_,y=new v(S),I=E?y.writeInt32BE:y.writeInt32LE,u=0;u<F.length;u++)I.call(y,F[u],4*u,!0);return y}}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("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(n,i,e){(function(t,r,v,o,a,d,p,m,D){var v=n("buffer").Buffer,P=n("./sha"),b=n("./sha256"),x=n("./rng"),E={sha1:P,sha256:b,md5:n("./md5")},S=64,_=new v(S);function F(l,w){var O=E[l=l||"sha1"],j=[];return O||y("algorithm:",l,"is not yet supported"),{update:function(k){return v.isBuffer(k)||(k=new v(k)),j.push(k),k.length,this},digest:function(k){var M=v.concat(j),M=w?function(B,q,te){v.isBuffer(q)||(q=new v(q)),v.isBuffer(te)||(te=new v(te)),q.length>S?q=B(q):q.length<S&&(q=v.concat([q,_],S));for(var Q=new v(S),K=new v(S),_e=0;_e<S;_e++)Q[_e]=54^q[_e],K[_e]=92^q[_e];return te=B(v.concat([Q,te])),B(v.concat([K,te]))}(O,w,M):O(M);return j=null,k?M.toString(k):M}}}function y(){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 F(l)},e.createHmac=F,e.randomBytes=function(l,w){if(!w||!w.call)return new v(x(l));try{w.call(this,void 0,new v(x(l)))}catch(O){w(O)}};var I,u=["createCredentials","createCipher","createCipheriv","createDecipher","createDecipheriv","createSign","createVerify","createDiffieHellman","pbkdf2"],h=function(l){e[l]=function(){y("sorry,",l,"is not implemented yet")}};for(I in u)h(u[I],I)}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("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(n,i,e){(function(t,r,s,o,a,d,p,m,D){var v=n("./helpers");function P(y,I){y[I>>5]|=128<<I%32,y[14+(I+64>>>9<<4)]=I;for(var u=1732584193,h=-271733879,l=-1732584194,w=271733878,O=0;O<y.length;O+=16){var j=u,k=h,M=l,B=w,u=x(u,h,l,w,y[O+0],7,-680876936),w=x(w,u,h,l,y[O+1],12,-389564586),l=x(l,w,u,h,y[O+2],17,606105819),h=x(h,l,w,u,y[O+3],22,-1044525330);u=x(u,h,l,w,y[O+4],7,-176418897),w=x(w,u,h,l,y[O+5],12,1200080426),l=x(l,w,u,h,y[O+6],17,-1473231341),h=x(h,l,w,u,y[O+7],22,-45705983),u=x(u,h,l,w,y[O+8],7,1770035416),w=x(w,u,h,l,y[O+9],12,-1958414417),l=x(l,w,u,h,y[O+10],17,-42063),h=x(h,l,w,u,y[O+11],22,-1990404162),u=x(u,h,l,w,y[O+12],7,1804603682),w=x(w,u,h,l,y[O+13],12,-40341101),l=x(l,w,u,h,y[O+14],17,-1502002290),u=E(u,h=x(h,l,w,u,y[O+15],22,1236535329),l,w,y[O+1],5,-165796510),w=E(w,u,h,l,y[O+6],9,-1069501632),l=E(l,w,u,h,y[O+11],14,643717713),h=E(h,l,w,u,y[O+0],20,-373897302),u=E(u,h,l,w,y[O+5],5,-701558691),w=E(w,u,h,l,y[O+10],9,38016083),l=E(l,w,u,h,y[O+15],14,-660478335),h=E(h,l,w,u,y[O+4],20,-405537848),u=E(u,h,l,w,y[O+9],5,568446438),w=E(w,u,h,l,y[O+14],9,-1019803690),l=E(l,w,u,h,y[O+3],14,-187363961),h=E(h,l,w,u,y[O+8],20,1163531501),u=E(u,h,l,w,y[O+13],5,-1444681467),w=E(w,u,h,l,y[O+2],9,-51403784),l=E(l,w,u,h,y[O+7],14,1735328473),u=S(u,h=E(h,l,w,u,y[O+12],20,-1926607734),l,w,y[O+5],4,-378558),w=S(w,u,h,l,y[O+8],11,-2022574463),l=S(l,w,u,h,y[O+11],16,1839030562),h=S(h,l,w,u,y[O+14],23,-35309556),u=S(u,h,l,w,y[O+1],4,-1530992060),w=S(w,u,h,l,y[O+4],11,1272893353),l=S(l,w,u,h,y[O+7],16,-155497632),h=S(h,l,w,u,y[O+10],23,-1094730640),u=S(u,h,l,w,y[O+13],4,681279174),w=S(w,u,h,l,y[O+0],11,-358537222),l=S(l,w,u,h,y[O+3],16,-722521979),h=S(h,l,w,u,y[O+6],23,76029189),u=S(u,h,l,w,y[O+9],4,-640364487),w=S(w,u,h,l,y[O+12],11,-421815835),l=S(l,w,u,h,y[O+15],16,530742520),u=_(u,h=S(h,l,w,u,y[O+2],23,-995338651),l,w,y[O+0],6,-198630844),w=_(w,u,h,l,y[O+7],10,1126891415),l=_(l,w,u,h,y[O+14],15,-1416354905),h=_(h,l,w,u,y[O+5],21,-57434055),u=_(u,h,l,w,y[O+12],6,1700485571),w=_(w,u,h,l,y[O+3],10,-1894986606),l=_(l,w,u,h,y[O+10],15,-1051523),h=_(h,l,w,u,y[O+1],21,-2054922799),u=_(u,h,l,w,y[O+8],6,1873313359),w=_(w,u,h,l,y[O+15],10,-30611744),l=_(l,w,u,h,y[O+6],15,-1560198380),h=_(h,l,w,u,y[O+13],21,1309151649),u=_(u,h,l,w,y[O+4],6,-145523070),w=_(w,u,h,l,y[O+11],10,-1120210379),l=_(l,w,u,h,y[O+2],15,718787259),h=_(h,l,w,u,y[O+9],21,-343485551),u=F(u,j),h=F(h,k),l=F(l,M),w=F(w,B)}return Array(u,h,l,w)}function b(y,I,u,h,l,w){return F((I=F(F(I,y),F(h,w)))<<l|I>>>32-l,u)}function x(y,I,u,h,l,w,O){return b(I&u|~I&h,y,I,l,w,O)}function E(y,I,u,h,l,w,O){return b(I&h|u&~h,y,I,l,w,O)}function S(y,I,u,h,l,w,O){return b(I^u^h,y,I,l,w,O)}function _(y,I,u,h,l,w,O){return b(u^(I|~h),y,I,l,w,O)}function F(y,I){var u=(65535&y)+(65535&I);return(y>>16)+(I>>16)+(u>>16)<<16|65535&u}i.exports=function(y){return v.hash(y,P,16)}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("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(n,i,e){(function(t,r,s,o,a,d,p,m,D){var v;i.exports=v||function(P){for(var b,x=new Array(P),E=0;E<P;E++)!(3&E)&&(b=4294967296*Math.random()),x[E]=b>>>((3&E)<<3)&255;return x}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("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(n,i,e){(function(t,r,s,o,a,d,p,m,D){var v=n("./helpers");function P(E,S){E[S>>5]|=128<<24-S%32,E[15+(S+64>>9<<4)]=S;for(var _,F,y,I=Array(80),u=1732584193,h=-271733879,l=-1732584194,w=271733878,O=-1009589776,j=0;j<E.length;j+=16){for(var k=u,M=h,B=l,q=w,te=O,Q=0;Q<80;Q++){I[Q]=Q<16?E[j+Q]:x(I[Q-3]^I[Q-8]^I[Q-14]^I[Q-16],1);var K=b(b(x(u,5),(K=h,F=l,y=w,(_=Q)<20?K&F|~K&y:!(_<40)&&_<60?K&F|K&y|F&y:K^F^y)),b(b(O,I[Q]),(_=Q)<20?1518500249:_<40?1859775393:_<60?-1894007588:-899497514)),O=w,w=l,l=x(h,30),h=u,u=K}u=b(u,k),h=b(h,M),l=b(l,B),w=b(w,q),O=b(O,te)}return Array(u,h,l,w,O)}function b(E,S){var _=(65535&E)+(65535&S);return(E>>16)+(S>>16)+(_>>16)<<16|65535&_}function x(E,S){return E<<S|E>>>32-S}i.exports=function(E){return v.hash(E,P,20,!0)}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("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(n,i,e){(function(t,r,s,o,a,d,p,m,D){function v(S,_){var F=(65535&S)+(65535&_);return(S>>16)+(_>>16)+(F>>16)<<16|65535&F}function P(S,_){var F,y=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),I=new Array(1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225),u=new Array(64);S[_>>5]|=128<<24-_%32,S[15+(_+64>>9<<4)]=_;for(var h,l,w=0;w<S.length;w+=16){for(var O=I[0],j=I[1],k=I[2],M=I[3],B=I[4],q=I[5],te=I[6],Q=I[7],K=0;K<64;K++)u[K]=K<16?S[K+w]:v(v(v((l=u[K-2],x(l,17)^x(l,19)^E(l,10)),u[K-7]),(l=u[K-15],x(l,7)^x(l,18)^E(l,3))),u[K-16]),F=v(v(v(v(Q,x(l=B,6)^x(l,11)^x(l,25)),B&q^~B&te),y[K]),u[K]),h=v(x(h=O,2)^x(h,13)^x(h,22),O&j^O&k^j&k),Q=te,te=q,q=B,B=v(M,F),M=k,k=j,j=O,O=v(F,h);I[0]=v(O,I[0]),I[1]=v(j,I[1]),I[2]=v(k,I[2]),I[3]=v(M,I[3]),I[4]=v(B,I[4]),I[5]=v(q,I[5]),I[6]=v(te,I[6]),I[7]=v(Q,I[7])}return I}var b=n("./helpers"),x=function(S,_){return S>>>_|S<<32-_},E=function(S,_){return S>>>_};i.exports=function(S){return b.hash(S,P,32,!0)}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("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(n,i,e){(function(t,r,s,o,a,d,p,m,D){e.read=function(v,P,b,x,w){var S,_,F=8*w-x-1,y=(1<<F)-1,I=y>>1,u=-7,h=b?w-1:0,l=b?-1:1,w=v[P+h];for(h+=l,S=w&(1<<-u)-1,w>>=-u,u+=F;0<u;S=256*S+v[P+h],h+=l,u-=8);for(_=S&(1<<-u)-1,S>>=-u,u+=x;0<u;_=256*_+v[P+h],h+=l,u-=8);if(S===0)S=1-I;else{if(S===y)return _?NaN:1/0*(w?-1:1);_+=Math.pow(2,x),S-=I}return(w?-1:1)*_*Math.pow(2,S-x)},e.write=function(v,P,b,x,E,O){var _,F,y=8*O-E-1,I=(1<<y)-1,u=I>>1,h=E===23?Math.pow(2,-24)-Math.pow(2,-77):0,l=x?0:O-1,w=x?1:-1,O=P<0||P===0&&1/P<0?1:0;for(P=Math.abs(P),isNaN(P)||P===1/0?(F=isNaN(P)?1:0,_=I):(_=Math.floor(Math.log(P)/Math.LN2),P*(x=Math.pow(2,-_))<1&&(_--,x*=2),2<=(P+=1<=_+u?h/x:h*Math.pow(2,1-u))*x&&(_++,x/=2),I<=_+u?(F=0,_=I):1<=_+u?(F=(P*x-1)*Math.pow(2,E),_+=u):(F=P*Math.pow(2,u-1)*Math.pow(2,E),_=0));8<=E;v[b+l]=255&F,l+=w,F/=256,E-=8);for(_=_<<E|F,y+=E;0<y;v[b+l]=255&_,l+=w,_/=256,y-=8);v[b+l-w]|=128*O}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("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(n,i,e){(function(t,r,s,o,a,d,p,m,D){var v,P,b;function x(){}(t=i.exports={}).nextTick=(P=typeof window<"u"&&window.setImmediate,b=typeof window<"u"&&window.postMessage&&window.addEventListener,P?function(E){return window.setImmediate(E)}:b?(v=[],window.addEventListener("message",function(E){var S=E.source;S!==window&&S!==null||E.data!=="process-tick"||(E.stopPropagation(),0<v.length&&v.shift()())},!0),function(E){v.push(E),window.postMessage("process-tick","*")}):function(E){setTimeout(E,0)}),t.title="browser",t.browser=!0,t.env={},t.argv=[],t.on=x,t.addListener=x,t.once=x,t.off=x,t.removeListener=x,t.removeAllListeners=x,t.emit=x,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,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("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 He={};or(He,{__addDisposableResource:()=>Is,__assign:()=>an,__asyncDelegator:()=>gs,__asyncGenerator:()=>ms,__asyncValues:()=>ys,__await:()=>ot,__awaiter:()=>ls,__classPrivateFieldGet:()=>xs,__classPrivateFieldIn:()=>Os,__classPrivateFieldSet:()=>Ss,__createBinding:()=>ln,__decorate:()=>os,__disposeResources:()=>_s,__esDecorate:()=>ca,__exportStar:()=>us,__extends:()=>rs,__generator:()=>ds,__importDefault:()=>vs,__importStar:()=>ws,__makeTemplateObject:()=>bs,__metadata:()=>cs,__param:()=>as,__propKey:()=>da,__read:()=>Ai,__rest:()=>ss,__runInitializers:()=>la,__setFunctionName:()=>ua,__spread:()=>fs,__spreadArray:()=>ps,__spreadArrays:()=>hs,__values:()=>cn,default:()=>pa});function rs(n,i){if(typeof i!="function"&&i!==null)throw new TypeError("Class extends value "+String(i)+" is not a constructor or null");Ci(n,i);function e(){this.constructor=n}n.prototype=i===null?Object.create(i):(e.prototype=i.prototype,new e)}function ss(n,i){var e={};for(var t in n)Object.prototype.hasOwnProperty.call(n,t)&&i.indexOf(t)<0&&(e[t]=n[t]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,t=Object.getOwnPropertySymbols(n);r<t.length;r++)i.indexOf(t[r])<0&&Object.prototype.propertyIsEnumerable.call(n,t[r])&&(e[t[r]]=n[t[r]]);return e}function os(n,i,e,t){var r=arguments.length,s=r<3?i:t===null?t=Object.getOwnPropertyDescriptor(i,e):t,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(n,i,e,t);else for(var a=n.length-1;a>=0;a--)(o=n[a])&&(s=(r<3?o(s):r>3?o(i,e,s):o(i,e))||s);return r>3&&s&&Object.defineProperty(i,e,s),s}function as(n,i){return function(e,t){i(e,t,n)}}function ca(n,i,e,t,r,s){function o(S){if(S!==void 0&&typeof S!="function")throw new TypeError("Function expected");return S}for(var a=t.kind,d=a==="getter"?"get":a==="setter"?"set":"value",p=!i&&n?t.static?n:n.prototype:null,m=i||(p?Object.getOwnPropertyDescriptor(p,t.name):{}),D,v=!1,P=e.length-1;P>=0;P--){var b={};for(var x in t)b[x]=x==="access"?{}:t[x];for(var x in t.access)b.access[x]=t.access[x];b.addInitializer=function(S){if(v)throw new TypeError("Cannot add initializers after decoration has completed");s.push(o(S||null))};var E=(0,e[P])(a==="accessor"?{get:m.get,set:m.set}:m[d],b);if(a==="accessor"){if(E===void 0)continue;if(E===null||typeof E!="object")throw new TypeError("Object expected");(D=o(E.get))&&(m.get=D),(D=o(E.set))&&(m.set=D),(D=o(E.init))&&r.unshift(D)}else(D=o(E))&&(a==="field"?r.unshift(D):m[d]=D)}p&&Object.defineProperty(p,t.name,m),v=!0}function la(n,i,e){for(var t=arguments.length>2,r=0;r<i.length;r++)e=t?i[r].call(n,e):i[r].call(n);return t?e:void 0}function da(n){return typeof n=="symbol"?n:"".concat(n)}function ua(n,i,e){return typeof i=="symbol"&&(i=i.description?"[".concat(i.description,"]"):""),Object.defineProperty(n,"name",{configurable:!0,value:e?"".concat(e," ",i):i})}function cs(n,i){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,i)}function ls(n,i,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(m){try{p(t.next(m))}catch(D){o(D)}}function d(m){try{p(t.throw(m))}catch(D){o(D)}}function p(m){m.done?s(m.value):r(m.value).then(a,d)}p((t=t.apply(n,i||[])).next())})}function ds(n,i){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(m){return d([p,m])}}function d(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=i.call(n,e)}catch(m){p=[6,m],r=0}finally{t=s=0}if(p[0]&5)throw p[1];return{value:p[0]?p[1]:void 0,done:!0}}}function us(n,i){for(var e in n)e!=="default"&&!Object.prototype.hasOwnProperty.call(i,e)&&ln(i,n,e)}function cn(n){var i=typeof Symbol=="function"&&Symbol.iterator,e=i&&n[i],t=0;if(e)return e.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&t>=n.length&&(n=void 0),{value:n&&n[t++],done:!n}}};throw new TypeError(i?"Object is not iterable.":"Symbol.iterator is not defined.")}function Ai(n,i){var e=typeof Symbol=="function"&&n[Symbol.iterator];if(!e)return n;var t=e.call(n),r,s=[],o;try{for(;(i===void 0||i-- >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 fs(){for(var n=[],i=0;i<arguments.length;i++)n=n.concat(Ai(arguments[i]));return n}function hs(){for(var n=0,i=0,e=arguments.length;i<e;i++)n+=arguments[i].length;for(var t=Array(n),r=0,i=0;i<e;i++)for(var s=arguments[i],o=0,a=s.length;o<a;o++,r++)t[r]=s[o];return t}function ps(n,i,e){if(e||arguments.length===2)for(var t=0,r=i.length,s;t<r;t++)(s||!(t in i))&&(s||(s=Array.prototype.slice.call(i,0,t)),s[t]=i[t]);return n.concat(s||Array.prototype.slice.call(i))}function ot(n){return this instanceof ot?(this.v=n,this):new ot(n)}function ms(n,i,e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=e.apply(n,i||[]),r,s=[];return r={},o("next"),o("throw"),o("return"),r[Symbol.asyncIterator]=function(){return this},r;function o(v){t[v]&&(r[v]=function(P){return new Promise(function(b,x){s.push([v,P,b,x])>1||a(v,P)})})}function a(v,P){try{d(t[v](P))}catch(b){D(s[0][3],b)}}function d(v){v.value instanceof ot?Promise.resolve(v.value.v).then(p,m):D(s[0][2],v)}function p(v){a("next",v)}function m(v){a("throw",v)}function D(v,P){v(P),s.shift(),s.length&&a(s[0][0],s[0][1])}}function gs(n){var i,e;return i={},t("next"),t("throw",function(r){throw r}),t("return"),i[Symbol.iterator]=function(){return this},i;function t(r,s){i[r]=n[r]?function(o){return(e=!e)?{value:ot(n[r](o)),done:!1}:s?s(o):o}:s}}function ys(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=n[Symbol.asyncIterator],e;return i?i.call(n):(n=typeof cn=="function"?cn(n):n[Symbol.iterator](),e={},t("next"),t("throw"),t("return"),e[Symbol.asyncIterator]=function(){return this},e);function t(s){e[s]=n[s]&&function(o){return new Promise(function(a,d){o=n[s](o),r(a,d,o.done,o.value)})}}function r(s,o,a,d){Promise.resolve(d).then(function(p){s({value:p,done:a})},o)}}function bs(n,i){return Object.defineProperty?Object.defineProperty(n,"raw",{value:i}):n.raw=i,n}function ws(n){if(n&&n.__esModule)return n;var i={};if(n!=null)for(var e in n)e!=="default"&&Object.prototype.hasOwnProperty.call(n,e)&&ln(i,n,e);return fa(i,n),i}function vs(n){return n&&n.__esModule?n:{default:n}}function xs(n,i,e,t){if(e==="a"&&!t)throw new TypeError("Private accessor was defined without a getter");if(typeof i=="function"?n!==i||!t:!i.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e==="m"?t:e==="a"?t.call(n):t?t.value:i.get(n)}function Ss(n,i,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 i=="function"?n!==i||!r:!i.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t==="a"?r.call(n,e):r?r.value=e:i.set(n,e),e}function Os(n,i){if(i===null||typeof i!="object"&&typeof i!="function")throw new TypeError("Cannot use 'in' operator on non-object");return typeof n=="function"?i===n:n.has(i)}function Is(n,i,e){if(i!=null){if(typeof i!="object"&&typeof i!="function")throw new TypeError("Object expected.");var t;if(e){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");t=i[Symbol.asyncDispose]}if(t===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");t=i[Symbol.dispose]}if(typeof t!="function")throw new TypeError("Object not disposable.");n.stack.push({value:i,dispose:t,async:e})}else e&&n.stack.push({async:!0});return i}function _s(n){function i(t){n.error=n.hasError?new ha(t,n.error,"An error was suppressed during disposal."):t,n.hasError=!0}function e(){for(;n.stack.length;){var t=n.stack.pop();try{var r=t.dispose&&t.dispose.call(t.value);if(t.async)return Promise.resolve(r).then(e,function(s){return i(s),e()})}catch(s){i(s)}}if(n.hasError)throw n.error}return e()}var Ci,an,ln,fa,ha,pa,We=fo(()=>{Ci=function(n,i){return Ci=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])},Ci(n,i)};an=function(){return an=Object.assign||function(i){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)&&(i[s]=e[s])}return i},an.apply(this,arguments)};ln=Object.create?function(n,i,e,t){t===void 0&&(t=e);var r=Object.getOwnPropertyDescriptor(i,e);(!r||("get"in r?!i.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return i[e]}}),Object.defineProperty(n,t,r)}:function(n,i,e,t){t===void 0&&(t=e),n[t]=i[e]};fa=Object.create?function(n,i){Object.defineProperty(n,"default",{enumerable:!0,value:i})}:function(n,i){n.default=i};ha=typeof SuppressedError=="function"?SuppressedError:function(n,i,e){var t=new Error(e);return t.name="SuppressedError",t.error=n,t.suppressed=i,t};pa={__extends:rs,__assign:an,__rest:ss,__decorate:os,__param:as,__metadata:cs,__awaiter:ls,__generator:ds,__createBinding:ln,__exportStar:us,__values:cn,__read:Ai,__spread:fs,__spreadArrays:hs,__spreadArray:ps,__await:ot,__asyncGenerator:ms,__asyncDelegator:gs,__asyncValues:ys,__makeTemplateObject:bs,__importStar:ws,__importDefault:vs,__classPrivateFieldGet:xs,__classPrivateFieldSet:Ss,__classPrivateFieldIn:Os,__addDisposableResource:Is,__disposeResources:_s}});var Ds=oe(Es=>{"use strict";Object.defineProperty(Es,"__esModule",{value:!0})});var Ti=oe(Ie=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.invokeEventHandlersAsync=Ie.invokeEventHandlers=Ie.eventHandlerSafeInvokeAsync=Ie.eventHandlerSafeInvoke=void 0;var Ps=(We(),Xe(He));function Cs(n,i,e){try{return n(i,e),{succeeded:!0}}catch(t){return{error:t,succeeded:!1}}}Ie.eventHandlerSafeInvoke=Cs;function Ri(n,i,e){return(0,Ps.__awaiter)(this,void 0,void 0,function*(){try{return yield n(i,e),{succeeded:!0}}catch(t){return{error:t,succeeded:!1}}})}Ie.eventHandlerSafeInvokeAsync=Ri;function ma(n,i,e,t){for(let r of n){let{succeeded:s,error:o}=Cs(r,i,e);if(!s&&t?.swallowExceptions!==!0)throw o}}Ie.invokeEventHandlers=ma;function ga(n,i,e,t){return(0,Ps.__awaiter)(this,void 0,void 0,function*(){if(t?.parallelize===!1)for(let r of n){let{succeeded:s,error:o}=yield Ri(r,i,e);if(!s&&t?.swallowExceptions!==!0)throw o}else{let r=[];for(let s of n)r.push(Ri(s,i,e).then(({succeeded:o,error:a})=>{if(!o&&t?.swallowExceptions!==!0)throw a}));yield Promise.all(r)}})}Ie.invokeEventHandlersAsync=ga});var Ts=oe(dn=>{"use strict";Object.defineProperty(dn,"__esModule",{value:!0});dn.TypedEvent=void 0;var ya=(We(),Xe(He)),As=Ti(),Rs={swallowExceptions:!1,parallelize:!0},Fi=class{constructor(){this._handlers=[]}attach(i){this._handlers.push(i)}detach(i){this.tryRemoveHandler(i)}invoke(i,e,t=Rs){(0,As.invokeEventHandlers)(this._handlers,i,e,t)}invokeAsync(i,e,t=Rs){return(0,ya.__awaiter)(this,void 0,void 0,function*(){yield(0,As.invokeEventHandlersAsync)(this._handlers,i,e,t)})}tryRemoveHandler(i){let e=this._handlers.findIndex(t=>t===i);e>=0&&this._handlers.splice(e,1)}};dn.TypedEvent=Fi});var ki=oe(Bi=>{"use strict";Object.defineProperty(Bi,"__esModule",{value:!0});var ba=(We(),Xe(He));(0,ba.__exportStar)(Ts(),Bi)});var Fs=oe(un=>{"use strict";Object.defineProperty(un,"__esModule",{value:!0});un.FinalizationRegistryMissingError=void 0;var ji=class extends Error{};un.FinalizationRegistryMissingError=ji});var Li=oe(fn=>{"use strict";Object.defineProperty(fn,"__esModule",{value:!0});fn.WeakHandlerHolder=void 0;var wa=Fs(),Mi=class{constructor(i){this._refs=[];try{this._finalizationRegistry=new FinalizationRegistry(i)}catch(e){throw e.name==="FinalizationRegistry"?new wa.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(i,e){let t=new WeakRef(e);return this._finalizationRegistry.register(e,{eventSource:i,handlerRef:t},t),this._refs.push(t),t}releaseWeakHandler(i){let t=this._refs.find(r=>r?.deref()===i)||new WeakRef(i);return this._finalizationRegistry.unregister(t),t}unregisterRef(i){this._finalizationRegistry.unregister(i)}};fn.WeakHandlerHolder=Mi});var Bs=oe(hn=>{"use strict";Object.defineProperty(hn,"__esModule",{value:!0});hn.WeakEvent=void 0;var Vi=(We(),Xe(He)),va=ki(),xa=Li(),Ui=Ti(),Sa={swallowExceptions:!1,parallelize:!0},Ni=class{constructor(){this._handlers=[],this._handlerFinalizedEvent=new va.TypedEvent,this.handlerFinalizedEvent=this._handlerFinalizedEvent,this._refHolder=new xa.WeakHandlerHolder(i=>{this.onHandlerFinalizer(i)})}invoke(i,e,t){for(let r of this._handlers){let s=r?.deref();if(s){let{succeeded:o,error:a}=(0,Ui.eventHandlerSafeInvoke)(s,i,e);if(!o&&t?.swallowExceptions!==!0)throw a}else this.releaseHandler(r)}}invokeAsync(i,e,t=Sa){return(0,Vi.__awaiter)(this,void 0,void 0,function*(){t?.parallelize===!1?yield this.sequentialInvokeAsync(i,e,t):yield this.parallelInvokeAsync(i,e,t)})}sequentialInvokeAsync(i,e,t){return(0,Vi.__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,Ui.eventHandlerSafeInvokeAsync)(s,i,e);if(!o&&t.swallowExceptions!==!0)throw a}else this.releaseHandler(r)}})}parallelInvokeAsync(i,e,t){return(0,Vi.__awaiter)(this,void 0,void 0,function*(){let r=[];for(let s of this._handlers){let o=s?.deref();o?r.push((0,Ui.eventHandlerSafeInvokeAsync)(o,i,e).then(({succeeded:a,error:d})=>{if(!a&&t.swallowExceptions!==!0)throw d})):this.releaseHandler(s)}yield Promise.all(r)})}attach(i){this._handlers.push(this._refHolder.getWeakHandler(this,i))}detach(i){let e=this._refHolder.releaseWeakHandler(i);this.tryRemoveHandlerRef(e)}onHandlerFinalizer(i){this.tryRemoveHandlerRef(i?.handlerRef),this._handlerFinalizedEvent.invokeAsync(this,i,{swallowExceptions:!0})}tryRemoveHandlerRef(i){let e=this._handlers.findIndex(t=>t===i);e>=0&&this._handlers.splice(e,1)}releaseHandler(i){this._refHolder.unregisterRef(i),this.tryRemoveHandlerRef(i)}};hn.WeakEvent=Ni});var js=oe(pn=>{"use strict";Object.defineProperty(pn,"__esModule",{value:!0});var ks=(We(),Xe(He));(0,ks.__exportStar)(Li(),pn);(0,ks.__exportStar)(Bs(),pn)});var Ms=oe(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});var zi=(We(),Xe(He));(0,zi.__exportStar)(Ds(),Dt);(0,zi.__exportStar)(ki(),Dt);(0,zi.__exportStar)(js(),Dt)});var tr={};or(tr,{Client:()=>ut,ClientDescriptor:()=>Wn,Entity:()=>de,EntityFile:()=>ve,ServerSync:()=>lt,Storage:()=>ut,StorageDescriptor:()=>Wn,UndoHistory:()=>rt,authorization:()=>ic,cliSync:()=>rc,collection:()=>vi,createDefaultMigration:()=>xi,createMigration:()=>Si,id:()=>nc,migrate:()=>en,schema:()=>It});var Sr=Te(ze(),1),Vt=4,gt=36;function wr(n){return n.toString(gt).padStart(Vt,"0")}function wo(n){return n.toString().padStart(6,"0")}var Bt=class{constructor(){this.latest={time:Date.now(),counter:0,node:vo()},this.zeroCounter=0,this.now=i=>(this.latest=xr(this.latest),this.get(i,this.latest)),this.OLD_now=i=>(this.latest=xr(this.latest),wo(i)+So(this.latest)),this.timerState=()=>this.latest,this.update=i=>{let e=i.slice(Vt);this.latest=xo(this.latest,Or(e))},this.get=(i,e)=>wr(i)+vr(e),this.zero=i=>wr(i)+vr({time:0,counter:this.zeroCounter++,node:this.latest.node}),this.getWallClockTime=ri}},kt=class extends Error{constructor(...i){super(),this.type="ClockDriftError",this.message=["maximum clock drift exceeded"].concat(i).join(" ")}},jt=class extends Error{constructor(){super(),this.type="OverflowError",this.message="timestamp counter overflow"}},ti=4,ni=7,Mt=60*1e3,mt=9;function vo(){return Sr.default.slug().padStart(ni,"0").slice(0,ni)}function vr(n){let i=new Date(n.time).getTime().toString(gt).padStart(mt,"0"),e=n.counter.toString(gt).padStart(ti,"0"),t=n.node.padStart(ni,"0");return`${i}${e}${t}`}function xr(n){let i=Date.now(),e=Math.max(n.time,i),t=n.time===e?n.counter+1:0;if(e-i>Mt)throw new kt(e,i,Mt);if(t>65535)throw new jt;return{time:e,counter:t,node:n.node}}function xo(n,i){let e=Date.now(),t=Math.max(e,Math.max(n.time,i.time)),r=Math.max(n.counter,i.counter),s;if(n.time===t&&i.time===t?s=r+1:n.time===t?s=n.counter+1:i.time===t?s=i.counter+1:s=0,t-e>Mt)throw new kt(t,e,Mt);if(s>65535)throw new jt;return{time:t,counter:s,node:n.node}}function Or(n){let i=n.slice(0,mt),e=n.slice(mt,mt+ti),t=n.slice(mt+ti),r=parseInt(i,gt),s=parseInt(e,gt);if(isNaN(r)||isNaN(s))throw new Error("invalid clock format");return{time:r,counter:s,node:t}}function So(n){let i=new Date(n.time).toISOString(),e=n.counter.toString(16).toUpperCase().padStart(4,"0"),t=n.node.padStart(16,"0");return`${i}-${e}-${t}`}function Lt(n){return parseInt(n.slice(0,Vt),36)}function ii(n,i){return Lt(n)-Lt(i)}function ri(n){return Or(n.slice(Vt)).time}var Ut,Oo=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(Oo)}var Ir=/^(?:[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 Io(n){return typeof n=="string"&&Ir.test(n)}var _r=Io;var ee=[];for(Nt=0;Nt<256;++Nt)ee.push((Nt+256).toString(16).substr(1));var Nt;function _o(n){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=(ee[n[i+0]]+ee[n[i+1]]+ee[n[i+2]]+ee[n[i+3]]+"-"+ee[n[i+4]]+ee[n[i+5]]+"-"+ee[n[i+6]]+ee[n[i+7]]+"-"+ee[n[i+8]]+ee[n[i+9]]+"-"+ee[n[i+10]]+ee[n[i+11]]+ee[n[i+12]]+ee[n[i+13]]+ee[n[i+14]]+ee[n[i+15]]).toLowerCase();if(!_r(e))throw TypeError("Stringified UUID is invalid");return e}var Er=_o;function Eo(n,i,e){n=n||{};var t=n.random||(n.rng||si)();if(t[6]=t[6]&15|64,t[8]=t[8]&63|128,i){e=e||0;for(var r=0;r<16;++r)i[e+r]=t[r];return i}return Er(t)}var yt=Eo;function W(n){return Se(n)||me(n)}function Ze(n,i){return n===i?!0:!(!W(n)||!W(i)||n["@@type"]!==i["@@type"]||n.id!==i.id)}var Do="/",bt=":",ai=new WeakMap;function ie(n){let i=fe(n);return N(!!i,`Object ${JSON.stringify(n)} does not have an OID assigned to it`),i}function fe(n){if(V(n))return ai.get(n)}function z(n,i){return N(V(n),`Only objects can be assigned OIDs, received ${JSON.stringify(n)}`),ci(n)&&Kt(n),ai.set(n,i),n}function ci(n){return!!fe(n)}function Kt(n){return ai.delete(n),n}function li(n,i,e){if(ci(n))return ie(n);{let t=ge(i,e);return z(n,t),t}}function Dr(n,i,e){if(ci(n)){let t=ie(n);if(Ee(t,i))return ie(n);{let r=ge(i,e);return z(n,r),r}}else{let t=ge(i,e);return z(n,t),t}}var oi={".":"&dot;","/":"&slash;",":":"&colon;"};function Pr(n){return n.replace(/[/]/g,oi["/"]).replace(/[:]/g,oi[":"]).replace(/[.]/g,oi["."])}function Cr(n){return n.replace(/&slash;/g,"/").replace(/&colon;/g,":").replace(/&dot;/g,".")}function Y(n,i,e){let t=Pr(n)+Do+Pr(i);return e&&(t+=bt+e),t}function ge(n,i=Po){let{collection:e,id:t}=ce(n);return Y(e,t,i())}function ce(n){let[i,e,...t]=n.split("/");t.length&&(console.error(`OID ${n} has more than 3 segments. Attempting to parse it anyway.`),e+="/"+t.join("/"));let[r,s]=e.split(bt),o;return r.includes(".")?o=r.slice(0,r.indexOf(".")):o=r,{collection:Cr(i),id:Cr(o),subId:s}}function et(n,i){let e=ie(n);if(Array.isArray(n)){let t;for(let r=0;r<n.length;r++)t=n[r],V(t)&&!W(t)&&(Dr(t,e,i),et(t,i))}else if(V(n)&&!W(n))for(let t of Object.keys(n))V(n[t])&&!W(n[t])&&(Dr(n[t],e,i),et(n[t],i))}function zt(n){if(Kt(n),Array.isArray(n))for(let i=0;i<n.length;i++)zt(n[i]);else if(V(n))for(let i of Object.keys(n))zt(n[i])}function Po(){return yt().slice(0,8)}function ae(n){return{"@@type":"ref",id:n}}function $t(n,i=new Map){if(Array.isArray(n)){let e=ie(n),t=z([],e);for(let r=0;r<n.length;r++){let s=n[r];if(V(s)){if(Se(s))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(me(s)){t[r]=s;continue}else{let o=ie(s);t[r]=ae(o),$t(s,i)}}else t[r]=s}i.set(e,t)}else if(V(n)&&!W(n)){let e=ie(n),t=z({},e);for(let r of Object.keys(n)){let s=n[r];if(V(s)){if(Se(s))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(me(s))t[r]=s;else{let o=ie(s);t[r]=ae(o),$t(s,i)}}else t[r]=s}i.set(e,t)}else W(n);return i}function $(n){return n.split(".")[0].split(bt)[0]}function Ar(n){let i=$(n),e=ge(i,()=>"\uFFFF");return[`${i}${bt}`,e]}function Ee(n,i){return $(n)===$(i)}function qt(n){return!n.includes(bt)}var Br=Te(Fr(),1);function Co(n,i){return typeof i!="object"||i===null||Array.isArray(i)?i:Object.fromEntries(Object.entries(i).sort(([e],[t])=>e<t?-1:e>t?1:0))}function wt(n){return JSON.stringify(n,Co)}function le(n,i=!0){if(!i&&typeof structuredClone=="function")return structuredClone(n);if(V(n)||Array.isArray(n)){let e=fe(n),t;if(Array.isArray(n))t=n.map(r=>le(r,i));else{t={};for(let[r,s]of Object.entries(n))t[r]=le(s,i)}return i&&e&&z(t,e),t}return n}function $e(n){return(0,Br.default)(n)}function V(n){return n&&typeof n=="object"}function kr(n){for(var i=[],e=[n],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"&&i.indexOf(r)===-1){i.push(r);for(var s in r)e.push(r[s])}}return t}function N(n,i="assertion failed"){if(!n)throw new Error(i)}function Qt(n=16){return yt().replace("-","").slice(0,n)}function jr(n,i){for(let e=n.length-1;e>=0;e--)if(i(n[e]))return e;return-1}function Mr(n,i){let e;return function(...t){let r=this;clearTimeout(e),e=setTimeout(()=>n.apply(r,t),i)}}function Lr(n,i){let e=0,t;return function(...r){let s=this,o=Date.now();o-e>=i?(e=o,n.apply(s,r),clearTimeout(t)):(clearTimeout(t),t=setTimeout(()=>{e=o,n.apply(s,r)},i))}}function Vr(){}function me(n){return n&&n["@@type"]==="file"}function vt(n){return{"@@type":"file",id:n}}function tt(n){return typeof File<"u"&&n instanceof File||typeof Blob<"u"&&n instanceof Blob}function Ht(n){return n&&V(n)&&typeof n.id=="string"&&typeof n.remote=="boolean"&&typeof n.name=="string"&&typeof n.type=="string"}var nt="__@@oid_do_not_use",De="@@id";function Ao(n){if(V(n))return n[De]||n[nt]}function Ro(n){return V(n)&&(delete n[nt],delete n[De]),n}function To(n){let i=Ao(n);i&&z(n,i)}function xt(n){if(To(n),Ro(n),Array.isArray(n))for(let i=0;i<n.length;i++)xt(n[i]);else if(V(n))for(let i of Object.keys(n))xt(n[i])}function Fo(n){let{collection:i,id:e,subId:t}=ce(n);return Y(i,e,t)}var Bo=/"\w+\/[^"]+?(\.[^"]+)+\:[\S]+?"/g;function ko(n){return n.replaceAll(Bo,i=>{let e=i.slice(1,i.length-1);return`"${Fo(e)}"`})}function di(n){return JSON.parse(ko(JSON.stringify(n)))}function Ur(n){let i=$(n);return[`${i}.`,`${i}.\uFFFF`]}function ui(n){return n===De||n===nt}function Se(n){return n&&typeof n=="object"&&n["@@type"]==="ref"}function fi(n){return V(n)&&!W(n)}function jo(n,i){return n===i?!0:W(n)&&W(i)?Ze(n,i):!1}function St(n,i,e,t,r=[],s){let o=s?.authz,a=ie(n);function d(p,m,D,v){if(!fi(m))jo(m,D)||(v?r.push(Be({oid:a,timestamp:e(),data:{op:"list-set",index:p,value:m}},o)):r.push(Be({oid:a,timestamp:e(),data:{op:"set",name:p,value:m}},o)));else{let P=fe(D),b=fe(m);b&&!Ee(a,b)?(m=le(m,!1),b=ge(a,t),z(m,b)):s?.mergeUnknownObjects?!b&&P?(z(m,P),b=P):b=li(m,a,t):b=li(m,a,t),N(!!b,"Error: no value OID was resolved during diff. This is a bug in Verdant."),N(Ee(a,b),`Error: value OID ${b} is not related to parent OID ${a}. This is a bug in Verdant.`),D===void 0||b!==P?(Ke(m,b,e,t,r),r.push(Be({oid:a,timestamp:e(),data:{op:"set",name:p,value:ae(b)}},o)),P!==void 0&&r.push(Be({oid:P,timestamp:e(),data:{op:"delete"}},o))):St(D,m,e,t,r,s)}}if(Array.isArray(n)&&Array.isArray(i)){for(let m=0;m<i.length;m++){let D=i[m],v=n[m];d(m,D,v,!0)}let p=n.length-i.length;if(p>0){for(let m=i.length;m<n.length;m++){let D=n[m],v=fe(D);v&&r.push(Be({oid:v,timestamp:e(),data:{op:"delete"}},o))}r.push(Be({oid:a,timestamp:e(),data:{op:"list-delete",index:i.length,count:p}},o))}}else{if(Array.isArray(n)||Array.isArray(i))throw new Error("Cannot diff an array with an object");if(fi(n)&&fi(i)){let p=new Set(Object.keys(n));for(let[m,D]of Object.entries(i)){if(D===void 0&&s?.defaultUndefined||(p.delete(m),ui(m)))continue;let v=n[m];d(m,D,v,!1)}if(!s?.defaultUndefined)for(let m of p)ui(m)||r.push(Be({oid:a,timestamp:e(),data:{op:"remove",name:m}},o))}}return r}function Ke(n,i,e,t,r=[],s){z(n,i),et(n,t);let o=$t(n);for(let a of o.keys()){let d=o.get(a),p={oid:a,timestamp:e(),data:{op:"initialize",value:Kt(d)}};r.push(Be(p,s?.authz))}return r}function Be(n,i){return i&&(n.authz=i),n}function Ot(n){let i={};for(let e of n)e.oid in i?i[e.oid].push(e):i[e.oid]=[e];return i}function zr(n){let i={};for(let e of n){let t=$(e.oid);t in i?i[t].push(e):i[t]=[e]}return i}function $r(n){let i={};for(let e of n){let t=$(e.oid);t in i?i[t].push(e):i[t]=[e]}return i}function Fe(n){return Array.isArray(n)?!0:(console.error(`Cannot apply list patch; expected array, received ${JSON.stringify(n)}. This suggests your data is changing from a list to an object over time. (OID: ${fe(n)})`),!1)}function ke(n,i,e){if(n==null&&i.op!=="initialize")return n;let t=n,r,s;function o(a){e&&W(a)&&e.push(a)}switch(i.op){case"set":o(t[i.name]),t[i.name]=i.value;break;case"remove":o(t[i.name]),delete t[i.name];break;case"list-set":Fe(n)&&(o(n[i.index]),n[i.index]=i.value);break;case"list-push":Fe(n)&&n.push(i.value);break;case"list-delete":Fe(n)&&(o(n[i.index]),n.splice(i.index,i.count));break;case"list-move-by-index":Fe(n)&&(s=n.splice(i.from,1),n.splice(i.to,0,s[0]));break;case"list-remove":if(Fe(n))do{let a=i.value;i.only==="last"?Se(a)?r=jr(n,d=>d.id===a.id):r=n.lastIndexOf(a):Se(a)?r=n.findIndex(d=>d.id===a.id):r=n.indexOf(a),r!==-1&&(o(n[r]),n.splice(r,1))}while(!i.only&&r!==-1);break;case"list-add":Fe(n)&&(n.some(d=>Se(d)&&Se(i.value)?d.id===i.value.id:d===i.value)||n.push(i.value));break;case"list-move-by-ref":Fe(n)&&(r=n.findIndex(a=>Ze(a,i.value)),s=n.splice(r,1),n.splice(i.index,0,s[0]));break;case"list-insert":if(Fe(n)){if(!i.value&&!i.values)throw new Error(`Cannot apply list insert patch; expected value or values, received ${JSON.stringify(i)}`);i.value?n.splice(i.index,0,i.value):n.splice(i.index,0,...i.values)}break;case"delete":Array.isArray(n)?n.forEach(o):V(n)&&Object.values(n||{}).forEach(o);return;case"initialize":return le(i.value);case"touch":return n;default:throw new Error(`Unsupported patch operation: ${i.op}`)}return n}function Wt(n,i,e=[]){if(Array.isArray(n))for(let t=0;t<n.length;t++){let r=n[t];n[t]=Nr(r,i,e),V(n[t])&&Wt(n[t],i,e)}else if(!me(n)){if(V(n)){N(fe(n),`Object ${JSON.stringify(n)} must have an oid`);for(let t of Object.keys(n))n[t]=Nr(n[t],i,e),V(n[t])&&Wt(n[t],i,e)}}return e}function Nr(n,i,e){if(Se(n)){e.push(n.id);let t=i.get(n.id);return N(!!t,`No value was found in object map for ${n.id}`),z(t,n.id)}else return n}function Kr(n){return n.data.op==="set"?n.data.name:!1}function qr(n,i){return i.has(!0)?!0:n.data.op==="set"||n.data.op==="remove"?i.has(n.data.name):!1}function Jt(n){return{oid:n.oid,timestamp:n.timestamp,data:n.data,authz:n.authz}}var je;(function(n){n[n.Realtime=0]="Realtime",n[n.Push=1]="Push",n[n.PassiveRealtime=2]="PassiveRealtime",n[n.PassivePush=3]="PassivePush",n[n.ReadOnlyPull=4]="ReadOnlyPull",n[n.ReadOnlyRealtime=5]="ReadOnlyRealtime"})(je||(je={}));var Qr=Te(ze(),1),Mo=n=>Object.assign({type:"object"},n),Lo=n=>Object.assign({type:"array"},n),Vo=n=>Object.assign({type:"string"},n),Uo=n=>Object.assign({type:"number"},n),No=n=>Object.assign({type:"boolean"},n),zo=n=>Object.assign({type:"any"},n),$o=n=>Object.assign({type:"map"},n),Ko=n=>Object.assign({type:"file"},n),qo=()=>({type:"string",default:Qr.default}),Hr={object:Mo,array:Lo,string:Vo,number:Uo,boolean:No,any:zo,map:$o,file:Ko,id:qo};var Gr=Te(ze(),1);function hi(n){return n.equals!==void 0}function pi(n){return n.gte!==void 0||n.lte!==void 0||n.gt!==void 0||n.lt!==void 0}function Qo(n){return!!n.match}function mi(n){return n.startsWith!==void 0}function Wr(n){return!pi(n)&&!hi(n)&&!Qo(n)&&!mi(n)&&n.order}function ye(n){return n.type==="any"?!0:n.type==="map"?!1:n.nullable}function Pe(n){return n?n.type==="map"||n.type==="array"?!0:n.type==="file"?!1:n.default!==void 0:!1}function yi(n){if(!(!n||!Pe(n)))return n.type==="file"?ye(n)?null:void 0:n.type==="map"?{}:n.type==="array"?ye(n)?null:[]:n.type==="object"?ye(n)?null:void 0:typeof n.default=="function"?n.default():n.default}function Ce(n,i){for(let[e,t]of Object.entries(n.fields)){let r=bi(t);(r!==void 0&&i[e]===void 0||!ye(t)&&i[e]===null)&&(i[e]=r),i[e]&&qe(i[e],t)}return i}function qe(n,i){if(n==null)return n;if(i.type==="object")for(let[e,t]of Object.entries(i.properties)){if(n[e]===void 0){let r=bi(t);r!==void 0&&(n[e]=r)}qe(n[e],t)}else if(i.type==="array")for(let e of n)qe(e,i.items);else if(i.type==="map")for(let[e,t]of Object.entries(n))e===De||e===nt||qe(t,i.values)}function bi(n){if(n.type==="string"||n.type==="number"||n.type==="boolean"||n.type==="any"){if(n.default&&typeof n.default=="function")return n.default();if(n.default!==void 0)return JSON.parse(JSON.stringify(n.default))}if(n.type==="array")return[];if(n.type==="map")return{};if(n.type!=="any"&&n.nullable)return null;if(n.type==="object"&&n.default){let i=typeof n.default=="function"?n.default():JSON.parse(JSON.stringify(n.default));for(let[e,t]of Object.entries(n.properties))i[e]===void 0&&(i[e]=bi(t));return i}}function wi(n,i){for(let[e,t]of Object.entries(i))e===De||e===nt||(n.fields[e]?gi(t,n.fields[e]):delete i[e]);return i}function gi(n,i){if(V(n)&&i.type==="object")for(let[e,t]of Object.entries(n))i.properties[e]?gi(t,i.properties[e]):delete n[e];else if(Array.isArray(n)&&i.type==="array")for(let e of n)gi(e,i.items)}function Jr(n,i){for(let[e,t]of Object.entries(i))if(e!==De){if(!n[e])return{type:"invalid-key",fieldPath:[e],message:`Invalid field "${e}"`};if(t){let r=Ae({field:n[e],value:t,fieldPath:[e]});if(r)return r}}}function Ae({field:n,value:i,fieldPath:e=[],depth:t,requireDefaults:r}){if(!(t!==void 0&&t<=0)&&!(ye(n)&&i===null)){if(i===null&&(r||!Pe(n)))return{type:"no-default",fieldPath:e,message:`Invalid null value for field ${Oe(e)}`};if(n.type==="object"){if(!V(i))return{type:"invalid-type",fieldPath:e,message:`Expected object ${n.nullable?"or null ":""}for field ${Oe(e)}, got ${i}`};for(let[s,o]of Object.entries(n.properties))s!==De&&i[s]&&Ae({field:o,value:i[s],fieldPath:[...e,s],depth:t!==void 0?t-1:void 0});for(let s of Object.keys(i))if(!n.properties[s])return{type:"invalid-key",fieldPath:[...e,s],message:`Invalid unexpected field "${s}" on value ${Oe(e)}`}}else if(n.type==="array"){if(!Array.isArray(i))return i===null&&n.nullable?void 0:{type:"invalid-value",fieldPath:e,message:`Expected array ${n.nullable?"or null ":""}for field ${Oe(e)}, got ${i}`};for(let s of i)Ae({field:n.items,value:s,fieldPath:[...e,"[]"],depth:t!==void 0?t-1:void 0})}else if(n.type==="map"){if(!V(i))return{type:"invalid-type",fieldPath:e,message:`Expected map for field ${Oe(e)}, got ${i}`};for(let[s,o]of Object.entries(i))Ae({field:n.values,value:o,fieldPath:[...e,s],depth:t!==void 0?t-1:void 0})}else if(n.type==="string"){if(typeof i!="string")return{type:"invalid-type",fieldPath:e,message:`Expected string ${n.nullable?"or null ":""}for field ${Oe(e)}, got ${i}`};if(n.options&&!n.options.includes(i))return{type:"invalid-value",fieldPath:e,message:`Expected one of ${n.options.join(", ")} for field ${Oe(e)}, got ${i}`}}else if(n.type==="boolean"){if(typeof i!="boolean")return{type:"invalid-type",fieldPath:e,message:`Expected boolean ${n.nullable?"or null ":""}for field ${Oe(e)}, got ${i}`}}else if(n.type==="number"){if(typeof i!="number")return{type:"invalid-type",fieldPath:e,message:`Expected number ${n.nullable?"or null ":""}for field ${Oe(e)}, got ${i}`}}else if(n.type==="file"&&!tt(i)&&!Ht(i))return{type:"invalid-type",fieldPath:e,message:`Expected file ${n.nullable?"or null ":""}for field ${Oe(e)}, got ${i}`}}}function Oe(n){return n.length===0?"root":n.join(".")}function Yr(n,i){let e={};for(let[t,r]of Object.entries(i))n[t]&&(e[t]=Yt({field:n[t],value:r,fieldPath:[t]}));return e}function Yt({field:n,value:i,fieldPath:e=[],depth:t}){let r=Ae({field:n,value:i,fieldPath:e,depth:t,requireDefaults:!0});if(r)throw new Error(`Validation error: ${r.message}`);if(n.type==="object"){if(!V(i))return i;let s={};for(let[o,a]of Object.entries(n.properties))s[o]=Yt({field:a,value:i[o],fieldPath:[...e,o],depth:t!==void 0?t-1:void 0});return s}else{if(n.type==="array")return Array.isArray(i)?i.map(s=>Yt({field:n.items,value:s,fieldPath:[...e,"[]"],depth:t!==void 0?t-1:void 0})):i;if(n.type==="map"){if(!V(i))return i;let s={};for(let[o,a]of Object.entries(i))s[o]=Yt({field:n.values,value:a,fieldPath:[...e,o],depth:t!==void 0?t-1:void 0});return s}else return i}}function Me(n,i){var e;return n.type==="object"?n.properties[i]:n.type==="array"?n.items:n.type==="map"?n.values:n.type==="any"?n:"type"in n?null:(e=n[i])!==null&&e!==void 0?e:null}var Ho=function(n,i){var e={};for(var t in n)Object.prototype.hasOwnProperty.call(n,t)&&i.indexOf(t)<0&&(e[t]=n[t]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,t=Object.getOwnPropertySymbols(n);r<t.length;r++)i.indexOf(t[r])<0&&Object.prototype.propertyIsEnumerable.call(n,t[r])&&(e[t[r]]=n[t[r]]);return e};function vi(n){var{synthetics:i,indexes:e}=n,t=Ho(n,["synthetics","indexes"]);let r=Object.assign(Object.assign({},i),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 It(n){return n}It.collection=vi;It.fields=Hr;It.generated={id:Gr.default};var Gt="\uFFFFFE",Wo="\0",Jo="\uFFFFFF";function we(...n){let i=Yo(n);return i.length===1?i[0]:i}function Le(...n){return n.join(Gt)+`${Jo}`}function Re(...n){return n.join(Gt)+`${Gt}${Wo}`}function Yo(n){let i=[[]];for(let e of n)if(Array.isArray(e)){let t=[];for(let r of i)for(let s of e)t.push(r.concat(s));i=t}else for(let t of i)t.push(`${e}`);return Array.from(new Set(i.map(e=>e.join(Gt))))}function Go(n){return!!n.field}function Xo(n,i){let e={};for(let[t,r]of Object.entries(n.indexes||{})){let s=r;Go(s)?e[t]=be(i[s.field]):e[t]=be(s.compute(i))}return e}function Zo(n,i){return Object.entries(n.compounds||{}).reduce((e,[t,r])=>(e[t]=we(...r.of.map(s=>i[s])),e),{})}function ea(n,i){return Object.entries(n.fields).reduce((e,[t,r])=>("indexed"in r&&(e[t]=be(i[t])),e),{})}function Xt(n,i){let e=Object.assign(Object.assign({[n.primaryKey]:i[n.primaryKey]},ea(n,i)),Xo(n,i));return Object.assign(e,Zo(n,Object.assign(Object.assign({},i),e))),e["@@@snapshot"]=JSON.stringify(i),e}var ta="null";function be(n){if(n===null)return ta;if(typeof n=="string"||typeof n=="number")return n;if(typeof n=="boolean"||n===null)return`${n}`;if(n===void 0)return"undefined";if(Array.isArray(n))return n.map(be);throw new Error(`Unsupported index value: ${n}`)}var Xr={version:0,collections:{}};function en(n,i,e){let t=typeof i=="function",r=t?Xr:n,s=t?n:i,o=t?i:e,a=Object.keys(s.collections).filter(x=>r.collections[x]&&wt(r.collections[x])!==wt(s.collections[x])),d=Object.keys(r.collections).filter(x=>!s.collections[x]),p=Object.keys(s.collections).filter(x=>!r.collections[x]),m=new Set;for(let x of a){let E=r.collections[x].fields,S=s.collections[x].fields;Object.keys(S).some(_=>{var F,y;return!(!((F=E[_])===null||F===void 0)&&F.default)&&((y=S[_])===null||y===void 0?void 0:y.default)})&&m.add(x),Object.keys(E).some(_=>!S[_])&&m.add(x)}let D={},v={};for(let x of[...a,...p]){let E=Zt(r.collections[x]),S=Zt(s.collections[x]),_=S.filter(y=>!E.find(I=>I.name===y.name)),F=E.filter(y=>!S.find(I=>I.name===y.name));_.length>0&&(D[x]=_,a.includes(x)&&m.add(x)),F.length>0&&(v[x]=F,a.includes(x)&&m.add(x))}let P=(x,E)=>Ce(s.collections[x],E),b=x=>E=>{let S=s.collections[x];return Ce(S,wi(S,E))};return{version:s.version,migrate:async x=>{let E=[];if(await o({migrate:async(S,_)=>{let F=b(S),y=async I=>{let u=await _(I);return z(u,ie(I)),F(u)};await x.migrate(S,y),E.push(S),m.delete(S)},identity:S=>S,withDefaults:P,info:{changedCollections:a,addedCollections:p,removedCollections:d},queries:x.queries,mutations:x.mutations}),s.version>1){x.log("debug","auto-migrating collections with new defaults",m);for(let _ of m)await x.migrate(_,b(_)),E.push(_);let S=a.filter(_=>!E.includes(_));S.length>0&&console.error(`Unmigrated changed collections from version ${r.version} to version ${s.version}:`,S)}},removedCollections:d,addedIndexes:D,removedIndexes:v,allCollections:Object.keys(s.collections),changedCollections:a,addedCollections:p,oldCollections:Object.keys(r.collections),oldSchema:r,newSchema:s}}function Zt(n){return n?[...Object.keys(n.indexes||{}).map(i=>({name:i,multiEntry:["array","string[]","number[]","boolean[]"].includes(n.indexes[i].type),synthetic:!0,compound:!1})),...Object.keys(n.compounds||{}).map(i=>({name:i,multiEntry:n.compounds[i].of.some(e=>(n.fields[e]||n.indexes[e]).type==="array"),synthetic:!1,compound:!0}))]:[]}function xi(n,i){return en(i?n:{version:0,collections:{}},i||n,async({migrate:t,info:r})=>{if((i||n).version!==1)for(let s of r.changedCollections)await t(s,o=>o)})}function Si(n,i,e){let t=typeof i=="function"||i===void 0,r=t?Xr:n,s=t?n:i,o=t?i:e;N(r,"Invalid arguments to createMigration"),N(s,"Invalid arguments to createMigration");let{changedCollections:a,addedCollections:d,removedCollections:p,addedIndexes:m,removedIndexes:D,autoMigratedCollections:v,autoMigration:P}=na(r,s);return{version:s.version,migrate:async b=>{let x=[];if(await o?.({migrate:async(S,_)=>{let F=P(S),y=async I=>{let u=await _(I);z(u,ie(I));let h=F(u),l=Jr(s.collections[S].fields,h);return h};await b.migrate(S,y),x.push(S),v.delete(S)},info:{changedCollections:a,addedCollections:d,removedCollections:p},queries:b.queries,mutations:b.mutations}),s.version>1){b.log("debug","auto-migrating collections with new defaults",v);for(let _ of v)await b.migrate(_,P(_)),x.push(_);for(let _ of p)await b.deleteCollection(_);let S=a.filter(_=>!x.includes(_));S.length>0&&console.error(`Unmigrated changed collections from version ${r.version} to version ${s.version}:`,S)}},removedCollections:p,addedIndexes:m,removedIndexes:D,allCollections:Object.keys(s.collections),changedCollections:a,addedCollections:d,oldCollections:Object.keys(r.collections),oldSchema:r,newSchema:s}}function na(n,i){let e=Object.keys(i.collections).filter(m=>n.collections[m]&&wt(n.collections[m])!==wt(i.collections[m])),t=Object.keys(n.collections).filter(m=>!i.collections[m]),r=Object.keys(i.collections).filter(m=>!n.collections[m]),s=new Set;for(let m of e){let D=n.collections[m].fields,v=i.collections[m].fields;Object.keys(v).some(P=>!Pe(D[P])&&Pe(v[P]))&&s.add(m),Object.keys(D).some(P=>!v[P])&&s.add(m)}let o={},a={};for(let m of[...e,...r]){let D=Zt(n.collections[m]),v=Zt(i.collections[m]),P=v.filter(x=>!D.find(E=>E.name===x.name)),b=D.filter(x=>!v.find(E=>E.name===x.name));P.length>0&&(o[m]=P,e.includes(m)&&s.add(m)),b.length>0&&(a[m]=b,e.includes(m)&&s.add(m))}return{changedCollections:e,addedCollections:r,removedCollections:t,addedIndexes:o,removedIndexes:a,autoMigratedCollections:s,withDefaults:(m,D)=>Ce(i.collections[m],D),autoMigration:m=>D=>{let v=i.collections[m];return Ce(v,wi(v,D))}}}var Oi={};var tn=class{constructor(i,e){this.getNow=i,this.createSubId=e,this.isPrimitive=t=>!V(t)||W(t),this.createDiff=(t,r,s={})=>St(t,r,this.getNow,this.createSubId,[],s),this.createInitialize=(t,r,s)=>Ke(t,r,this.getNow,this.createSubId,void 0,s?{authz:s}:void 0),this.createSet=(t,r,s)=>{if(this.isPrimitive(s))return[{oid:t,timestamp:this.getNow(),data:{op:"set",name:r,value:s}}];{let o=ge(t,this.createSubId);return[...Ke(s,o,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"set",value:ae(o),name:r}}]}},this.createRemove=(t,r)=>[{oid:t,timestamp:this.getNow(),data:{op:"remove",name:r}}],this.createListSet=(t,r,s)=>{if(this.isPrimitive(s))return[{oid:t,timestamp:this.getNow(),data:{op:"list-set",index:r,value:s}}];{let o=ge(t,this.createSubId);return[...Ke(s,o,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-set",index:r,value:ae(o)}}]}},this.createListPush=(t,r)=>{if(this.isPrimitive(r))return[{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:r}}];{let s=ge(t,this.createSubId);return[...Ke(r,s,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:ae(s)}}]}},this.createListAdd=(t,r)=>this.isPrimitive(r)?[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:r}}]:[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:ae(r)}}],this.createListInsert=(t,r,s)=>{if(this.isPrimitive(s))return[{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:s,index:r}}];{let o=ge(t,this.createSubId);return[...Ke(s,o,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:ae(o),index:r}}]}},this.createListRemove=(t,r,s)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-remove",value:r,only:s}}],this.createListDelete=(t,r,s=1)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-delete",index:r,count:s}}],this.createListMoveByRef=(t,r,s)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-move-by-ref",value:r,index:s}}],this.createListMoveByIndex=(t,r,s)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-move-by-index",from:r,to:s}}],this.createDelete=t=>[{oid:t,timestamp:this.getNow(),data:{op:"delete"}}],this.createDeleteAll=(t,r)=>t.map(s=>({oid:s,timestamp:this.getNow(),data:{op:"delete"},authz:r}))}};var U=class{constructor(i){this._onAllUnsubscribed=i,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=Qt(),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}};function Zr(n,i,e,t){if(i==null)return[{oid:n,timestamp:t(),data:{op:"delete"}}];let r=le(i),s=[];for(let o of e){let a=ia(n,r,o,t);s.unshift(...a),ke(r,o.data)}return s}function ia(n,i,e,t){let r=e.data;switch(r.op){case"set":case"remove":return[{oid:n,timestamp:t(),data:{op:"set",name:r.name,value:i[r.name]}}];case"list-insert":return[{oid:n,timestamp:t(),data:{op:"list-delete",index:r.index,count:1}}];case"list-delete":return[{oid:n,timestamp:t(),data:{op:"list-insert",index:r.index,values:i.slice(r.index,r.count)}}];case"list-move-by-ref":return[{oid:n,timestamp:t(),data:{op:"list-move-by-ref",value:r.value,index:i.indexOf(r.value)}}];case"list-move-by-index":return[{oid:n,timestamp:t(),data:{op:"list-move-by-index",from:r.to,to:r.from}}];case"delete":return[{oid:n,timestamp:t(),data:{op:"initialize",value:i}}];case"list-push":return[{oid:n,timestamp:t(),data:{op:"list-remove",value:r.value,only:"last"}}];case"list-remove":if(r.only==="last"){let s=i.lastIndexOf(r.value);return[{oid:n,timestamp:t(),data:{op:"list-insert",index:s,values:[r.value]}}]}else if(r.only==="first"){let s=i.indexOf(r.value);return[{oid:n,timestamp:t(),data:{op:"list-insert",index:s,values:[r.value]}}]}else{let s=[],o=i.indexOf(r.value);for(;o!==-1;)s.push(o),o=i.indexOf(r.value,o+1);return s.map(a=>({oid:n,timestamp:t(),data:{op:"list-insert",index:a,value:r.value}}))}case"list-add":return[{oid:n,timestamp:t(),data:{op:"list-remove",value:r.value,only:"last"}}];case"list-set":return[{oid:n,timestamp:t(),data:{op:"list-set",index:r.index,value:i[r.index]}}];case"initialize":return[{oid:n,timestamp:t(),data:{op:"delete"}}];case"touch":return[];default:throw new Error(`Cannot undo operation type: ${r.op}`)}}var it=class{constructor(i){this.flusher=i,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:i,userData:e,items:t,max:r,timeout:s}){let o=this.batches.get(i);return o||(o=new Ii({max:r||null,startedAt:Date.now(),userData:e,timeout:s||null,flusher:this.flusher,key:i}),this.batches.set(i,o)),o.update({items:t,max:r,timeout:s,userData:e}),o}},Ii=class{constructor({max:i,startedAt:e,timeout:t,userData:r,flusher:s,key:o}){this.items=[],this.update=({items:a,max:d,timeout:p,userData:m})=>{this.items.push(...a),d!==void 0&&(this.max=d),p!==void 0&&(this.timeout=p),m&&(this.userData=m);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=i,this.startedAt=e,this.timeout=t,this.userData=r,this.flusher=s,this.key=o}};function es(n,i){let e,t;return(...r)=>{let s=i();return e&&e.length===s.length&&e.every((o,a)=>o===s[a])||(e=[...s],t=n(...r)),t}}var _t;(function(n){n[n.InvalidRequest=4e3]="InvalidRequest",n[n.BodyRequired=4001]="BodyRequired",n[n.NoToken=4010]="NoToken",n[n.InvalidToken=4011]="InvalidToken",n[n.TokenExpired=4012]="TokenExpired",n[n.Forbidden=4030]="Forbidden",n[n.NotFound=4040]="NotFound",n[n.Unexpected=5e3]="Unexpected",n[n.ConfigurationError=5010]="ConfigurationError",n[n.NoFileStorage=5011]="NoFileStorage",n[n.MigrationPathNotFound=7001]="MigrationPathNotFound",n[n.ImportFailed=7002]="ImportFailed"})(_t||(_t={}));var ne=class extends Error{constructor(i,e,t){super(t??`Verdant error: ${i}`,{cause:e}),this.code=i,this.toResponse=()=>JSON.stringify({code:this.code})}get httpStatus(){let i=Math.floor(this.code/10);return i<600?i:500}};ne.Code=_t;function ts(n){return typeof n=="object"&&"code"in n&&typeof n.code=="number"}function ra(n){return typeof Buffer<"u"?Buffer.from(n).toString("base64"):btoa(n)}function sa(n){return typeof Buffer<"u"?Buffer.from(n,"base64").toString():atob(n)}var Qe={onlyUser:n=>ra(`u:${n}:*`),onlyMe:()=>Qe.onlyUser(_i),decode:n=>{let e=sa(n).split(":");if(e.length!==3)throw new Error("Invalid authz string");return{scope:e[0],subject:e[1],action:e[2]}}},_i="$$_originator_$$";function ns(n,i){let{operations:e,baselines:t}=n;if(e)for(let r of e)r.authz&&Qe.decode(r.authz).subject===_i&&(r.authz=Qe.onlyUser(i));if(t)for(let r of t)r.authz&&Qe.decode(r.authz).subject===_i&&(r.authz=Qe.onlyUser(i))}var rt=class extends U{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}};var nn=class{constructor(i,e){this.schema=i;this.entities=e;this.getOid=(i,e)=>{let t=this.schema.collections[i].primaryKey,r=e[t];return N(r,`Document must have a primary key: ${t.toString()} (got: ${JSON.stringify(e)})`),Y(i,r)};this.addDefaults=(i,e)=>{let t=this.schema.collections[i];return Ce(t,e)};this.validate=(i,e)=>{let t=this.schema.collections[i];return Yr(t.fields,e)};this.create=async(i,e,t={})=>{let r=t,s=this.addDefaults(i,e),o=this.validate(i,s),a=this.getOid(i,o);if(t.access){let d=this.schema.collections[i];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(i,e,t={})=>{let r=Y(i,e);return this.entities.delete(r,t)};this.deleteAll=async(i,e={})=>this.entities.deleteAll(i.map(([t,r])=>Y(t,r)),e);this.deleteAllFromCollection=async(i,e,t={})=>this.entities.deleteAll(e.map(r=>Y(i,r)),t);this.clone=async(i,e,t={})=>{if(!qt(e.uid))throw new Error("Cannot clone non-root documents");let r=e.getSnapshot(),s=this.schema.collections[i];if(delete r[s.primaryKey],!s.fields[s.primaryKey].default){if(!t.primaryKey)throw new Error(`Error cloning document from collection ${i}: 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(i,r,t)}}};var Ei=Te(ze(),1);function oa(n){return{id:(0,Ei.default)(),file:n,url:void 0,remote:!1,name:n.name,type:n.type}}function st(n,i){if(typeof window<"u"&&tt(n)){let e=oa(n);return i(e),vt(e.id)}if(Ht(n)){let e={...n,id:(0,Ei.default)()};return i(e),vt(e.id)}if(Array.isArray(n)){for(let e=0;e<n.length;e++)n[e]=st(n[e],i);return n}if(typeof n=="object"){for(let e in n)n[e]=st(n[e],i);return n}return n}var rn=class{constructor({initial:i}={}){this.cache=new Map;this.get=i=>{if(this.cache.has(i.oid))return this.cache.get(i.oid);let e=new de(i);return this.cache.set(i.oid,e),e};this.has=i=>this.cache.has(i);this.getCached=i=>this.cache.get(i);if(i)for(let e of i)this.cache.set(e.oid,e)}};function is(n,i,e){let t={previousValue:n.get(i),isLocal:!1};function r(s){if(n.deleted)return;let o=n.get(i);o!==this.previousValue&&(this.isLocal=s.isLocal,e(o,this),this.previousValue=o)}return n.subscribe("change",r.bind(t))}var de=class n extends U{constructor({oid:e,schema:t,entityFamily:r,parent:s,ctx:o,metadataFamily:a,readonlyKeys:d,files:p,storeEvents:m,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 n){let t=e.view;return t==null}return e==null};this.getFieldSchema=e=>{let t=Me(this.schema,e);return N(t,`No schema for key ${e}`),t};this.validate=es(()=>(this.validationError=Ae({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 n||s instanceof ve?e(s):s);return z(r,this.oid),r}else{let r=Object.entries(t).reduce((s,[o,a])=>(a instanceof n||a instanceof ve?s[o]=e(a):s[o]=a,s),{});return z(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 n&&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=Me(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)=>is(this,e,r);this.get=e=>{Di(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=Me(this.schema,e);if(!s)throw new Error(`No schema for key ${String(e)} in ${JSON.stringify(this.schema)}`);if(W(r))if(me(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:Ae({field:s,value:r,fieldPath:[...this.fieldPath,e],depth:1,requireDefaults:!0})?Pe(s)?yi(s):ye(s)?null:void 0:r};this.getOrSet=(e,t)=>{Di(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=le(e,!1));let r=Me(this.schema,t);if(r){qe(e,r);let s=Ae({field:r,value:e,fieldPath:[...this.fieldPath,t]});if(s)throw new Error(`Validation error: ${s.message}`,{cause:s})}return st(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 n)return ae(e.oid);if(e instanceof ve)return vt(e.id);if(typeof e=="object"){let t=fe(e);if(!t||!this.entityFamily.has(t))throw new Error(`Cannot move object ${JSON.stringify(e)} which does not exist in this list`);return ae(t)}else return e};this.set=(e,t,r)=>{Di(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)aa(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}={})=>{if(!t&&this.schema.type!=="any"&&this.schema.type!=="map")throw new Error('Cannot use .update without merge if the field has a strict schema type. merge: false is only available on "any" or "map" types.');let o={};z(o,this.oid);for(let[a,d]of Object.entries(e)){if(this.readonlyKeys.includes(a))throw new Error(`Cannot set readonly key ${a.toString()}`);if(d===void 0&&!s)continue;let p=Me(this.schema,a);p&&qe(d,p),o[a]=this.processInputValue(d,a)}this.addPendingOperations(this.patchCreator.createDiff(this.getSnapshot(),o,{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(W(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 W(t)?this.view.some(r=>{if(W(r))return Ze(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=d||[],this.ctx=o,this.files=p,this.schema=t,this.entityFamily=r||new rn({initial:[this]}),this.metadataFamily=a,this.storeEvents=m,this.parent=s,this._deleteSelf=D,this.parent||(m.add.attach(this.onAdd),m.replace.attach(this.onReplace),m.resetAll.attach(this.onResetAll))}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&&!ye(this.schema)||this.schema.type==="array"&&!Array.isArray(e)||(this.schema.type==="object"||this.schema.type==="map")&&!V(e))return Pe(this.schema)?yi(this.schema):null;if(this.cachedView=this.isList?[]:{},z(this.cachedView,this.oid),Array.isArray(e)){let r=Me(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)&&!ye(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=Me(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)&&!ye(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 n){let r=t.deepUpdatedAt;r&&(!e||r>e)&&(e=r)}}):this.values().forEach(t=>{if(t instanceof n){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 Di(n){if(typeof n=="symbol")throw new Error("Symbol keys aren't supported")}function aa(n){if(typeof n!="number")throw new Error("Only number keys are supported in list entities")}var Z=class{constructor(){this._disposes=[];this.disposed=!1;this.dispose=async()=>{this.disposed=!0,await Promise.all(this._disposes.map(i=>i())),this._disposes=[]};this.compose=i=>this.addDispose(i.dispose.bind(i));this.addDispose=i=>{this._disposes.push(i)}}};var Pi=class{constructor({oid:i,ctx:e,confirmedOperations:t,pendingOperations:r,baseline:s}){this.baseline=null;this.confirmedOperations=[];this.pendingOperations=[];this.computeView=(i=!1)=>{let e=le(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=i?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 p=o.latestTimestamp??s.latestTimestamp??t,m=p?ri(p):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:m,latestTimestamp:p,authz:r}};this.addBaseline=i=>{if(!(this.baseline&&this.baseline.timestamp>=i.timestamp))for(this.baseline=i;this.confirmedOperations[0]?.timestamp<i.timestamp;)this.confirmedOperations.shift()};this.addConfirmedOperations=i=>{let e=0;for(let t of i){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=i=>{this.pendingOperations.push(i)};this.discardPendingOperation=i=>{this.pendingOperations=this.pendingOperations.filter(e=>e.timestamp!==i.timestamp)};this.applyOperations=(i,e,t,r,s)=>{let o,a,d=this.ctx.time.now;for(let p of t)if(!(s&&p.timestamp<=s)){if(ii(p.timestamp,d)>0){o=p.timestamp;continue}p.data.op==="delete"?e=!0:(i=ke(i,p.data),p.data.op==="initialize"&&(e=!1,p.authz&&(a=p.authz))),(!r||p.timestamp>r)&&(r=p.timestamp)}return{view:i,latestTimestamp:r??null,deleted:e,futureSeen:o,authz:a}};N(i,"oid is required"),this.ctx=e,this.oid=i,t&&(this.confirmedOperations=t),r&&(this.pendingOperations=r),s&&(this.baseline=s)}},sn=class{constructor({ctx:i,onPendingOperations:e,rootOid:t}){this.entities=new Map;this.get=i=>(N(i,"oid is required"),this.entities.has(i)||this.entities.set(i,new Pi({oid:i,ctx:this.ctx})),this.entities.get(i));this.getAllOids=()=>Array.from(this.entities.keys());this.addConfirmedData=({baselines:i=[],operations:e={},isLocal:t=!1})=>{let r={};for(let s of i){if(!Ee(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(!Ee(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=i=>{let e={};for(let t of i)this.get(t.oid).addPendingOperation(t),e[t.oid]??={oid:t.oid,isLocal:!0};return this.onPendingOperations(i),Object.values(e)};this.replaceAllData=({operations:i={},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(!Ee(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(i)){if(!Ee(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=i=>{this.entities.get(i.oid)?.discardPendingOperation(i)};this.ctx=i,this.rootOid=t,this.onPendingOperations=e}};var Et="@@default",on=class{constructor({batchTimeout:i=200,ctx:e,entities:t}){this.currentBatchKey=Et;this.flushOperations=async(i,e,t)=>{if(!i.length)return;this.ctx.log("debug","Flushing",i.length,"operations from batch",e,"to storage / sync");let r=[],s={};for(let o=i.length-1;o>=0;o--){let a=i[o],d=s[a.oid];if(d&&qr(a,d)){this.entities.discardPendingOperation(a);continue}let p=Kr(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(i,e)=>{if(i.length){if(e.undoable){let t=await this.createUndo({ops:i,source:e.source});t&&this.ctx.undoHistory.addUndo(t)}await this.entities.addData({operations:i,baselines:[],isLocal:!0})}};this.addOperations=i=>{i.length&&(this.batcher.add({key:this.currentBatchKey,items:i}),this.ctx.log("debug","added",i.length,"ops to batch",this.currentBatchKey,", size = ",this.batcher.getSize(this.currentBatchKey)))};this.batch=({undoable:i=!0,batchName:e=Qt(),max:t=null,timeout:r=this.defaultBatchTimeout}={})=>{let s=this.batcher.add({key:e,max:t,timeout:r,items:[],userData:{undoable:i}}),o={run:a=>(this.currentBatchKey=e,a(),this.currentBatchKey=Et,o),commit:async()=>(await this.batcher.flush(Et),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 i=>{let e=await this.getInverseOperations(i);return e.length?async()=>{let t=await this.createUndo({ops:e,source:i.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:i,source:e})=>{let t=Ot(i),r=[],s=()=>this.ctx.time.now;return await Promise.all(Object.entries(t).map(async([o,a])=>{let p=(e??await this.entities.hydrate($(o)))?.__getViewData__(o,"confirmed");if(!p){this.ctx.log("warn","could not find entity",o,"for undo operation",i);return}let m=Zr(o,p.view,a,s);r.unshift(...m)})),r};this.ctx=e,this.entities=t,this.defaultBatchTimeout=i,this.batcher=new it(this.flushOperations),this.batcher.add({key:Et,items:[],max:100,timeout:i,userData:{undoable:!0}})}get isDefaultBatch(){return this.currentBatchKey===Et}};var mn=Te(Ms(),1);var gn=class extends Z{constructor({ctx:e,files:t}){super();this.events={add:new mn.WeakEvent,replace:new mn.WeakEvent,resetAll:new mn.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.queries.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.queries.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(m=>$(m.oid)).concat(r.map(m=>$(m.oid))))),o=$r(t),a=zr(r);this.ctx.log("debug","Applying data to live entities");for(let m of s){let D=o[m],v=a[m]??[],P=Ot(v),b=e.reset?this.events.replace:this.events.add,x=this.pendingEntityPromises.get(m);x?(this.ctx.log("debug","Waiting for ongoing entity hydration",m),x.then(()=>{b.invoke(this,{oid:m,baselines:D,operations:P,isLocal:!1})})):(this.ctx.log("debug","Applying data to entity",m),b.invoke(this,{oid:m,baselines:D,operations:P,isLocal:!1}))}let d={abort:this.abortDataQueueController.signal};await this.ctx.meta.insertData(e,d);let p=await Promise.all(s.map(async m=>await this.hydrate(m,d)??{oid:m,getSnapshot(){return null}}));try{await this.ctx.queries.saveEntities(p,d)}catch(m){this.disposed?this.ctx.log("warn","Error saving entities to queryable storage - EntityStore is disposed",m):this.ctx.log("error","Error saving entities to queryable storage",m)}};this.hydrate=async(e,t)=>{if(!qt(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}=ce(t);zt(e);let a=st(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 p=this.ctx.patchCreator.createInitialize(a,t);s&&p.forEach(D=>{D.authz=s}),await this.batcher.commitOperations(p,{undoable:!!r,source:d});let m=Ot(p);return this.events.add.invoke(this,{operations:m,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),N(e.every(o=>o===$(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 p of d)p.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=>{let{collection:t}=ce(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 sn({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=$(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 on({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}};var at=Symbol("entity-file-update"),yn=Symbol("entity-file-mark-failed"),Oa,Ia,ve=class extends U{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.unsubscribes=[];this[Oa]=e=>{this.ctx.log("debug","EntityFile updated",this.id,e),this._loading=!1,this._failed=!1,this._fileData=e,e.file&&(this._objectUrl&&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[Ia]=()=>{this._failed=!0,this._loading=!1,this.emit("change")};this.onUploaded=()=>{this._fileData&&(this._fileData.remote=!0,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{Oa=at,Ia=yn}get downloadRemote(){return this._downloadRemote}get isFile(){return!0}get isUploaded(){return 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:!1,type:this.type??"",file:this._fileData?.file}}};var bn=class{constructor({sync:i,context:e}){this.cache=new Map;this.add=async(i,e)=>{if(this.cache.has(i.id))this.cache.get(i.id)[at](i);else{let t=new ve(i.id,{ctx:this.context});t[at](i),this.cache.set(i.id,t)}await this.context.files.add(i,e)};this.get=(i,e)=>{if(this.cache.has(i))return this.cache.get(i);let t=new ve(i,e);return this.cache.set(i,t),this.load(t),t};this.load=async i=>{let e=await this.context.files.get(i.id);if(e)i[at](e);else try{let t=await this.sync.getFile(i.id);t.success?(i[at](t.data),await this.context.files.add(t.data,{downloadRemote:i.downloadRemote})):(this.context.log("error","Failed to load file",t),i[yn]())}catch(t){this.context.log("error","Failed to load file",t),i[yn]()}};this.sync=i,this.context=e}};var $i=typeof window<"u"?window.indexedDB:void 0;function Je(n){return n instanceof Error&&n.name==="AbortError"}function Ye(n){return new Promise((i,e)=>{n.onsuccess=()=>{i(n.result)},n.onerror=()=>{n.error&&Je(n.error)?i(n.result):e(n.error)}})}function Ve(n,i){return new Promise((e,t)=>{let r=n.transaction([i],"readonly"),o=r.objectStore(i).openCursor(),a=0,d=0;o.onsuccess=function(p){let m=o.result;m&&(a++,d=d+kr(m.value),m.continue())},o.onerror=function(p){o.error&&Je(o.error)?e({count:a,size:d}):t(o.error)},r.oncomplete=function(p){e({count:a,size:d})},r.onabort=function(p){t(p)},r.onerror=function(p){t(p)}})}async function Ls(n){let e=Array.from(n.objectStoreNames).map(async r=>{let s=await Ve(n,r);return{[r]:s}});return(await Promise.all(e)).reduce((r,s)=>({...r,...s}),{})}function Ki(n,i){let e=n.transaction(i,"readonly"),t=i.map(r=>{let s=e.objectStore(r);return Ye(s.getAll())});return Promise.all(t)}async function xe(n){n.close(),await new Promise((i,e)=>{i()})}async function wn(n,i=$i){let e=i.deleteDatabase([n,"meta"].join("_")),t=i.deleteDatabase([n,"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 qi(n,i=window.indexedDB){return Ye(i.deleteDatabase(n))}function Vs(n,i,e,t,r){let s=n.transaction(i,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}function _a(n){let i=Array.from(n.objectStoreNames),e=n.transaction(i,"readwrite");for(let t of i)e.objectStore(t).clear();return new Promise((t,r)=>{e.oncomplete=()=>t(),e.onerror=()=>r(e.error)})}async function Us(n,i){await _a(i);let e=await Ki(n,Array.from(n.objectStoreNames)),t=i.transaction(Array.from(i.objectStoreNames),"readwrite");for(let r=0;r<e.length;r++){let s=t.objectStore(n.objectStoreNames[r]);for(let o of e[r])s.add(o)}return new Promise((r,s)=>{t.oncomplete=()=>r(),t.onerror=()=>s(t.error)})}function Ns(n,i,e=window.indexedDB){return new Promise((t,r)=>{let s=e.open(n,i);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!==i&&(a.close(),r(new Error(`Migration error: database version changed unexpectedly when reading current data. Expected ${i}, got ${a.version}`)))}})}function vn(n){return[n,"meta"].join("_")}function Qi(n){return[n,"collections"].join("_")}function zs(n){return n.name?.split("_")[0]}function Ea(n){return n!==null}function Hi(n){return Array.isArray(n)?n.map(Hi).filter(Ea):n instanceof de&&n.deleted?null:n}function Ue(n,i){return!n&&!i||n&&i&&$e(n)===$e(i)}var Wi=Symbol("ON_ALL_UNSUBSCRIBED"),ue=Symbol("UPDATE"),Da,he=class extends Z{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 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[Da]=e=>{this._allUnsubscribedHandler=e};this._rawValue=e,this._value=e,this.isListQuery=Array.isArray(e),this._events=new U(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{Da=Wi}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 xn=class extends he{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=Y(r.collection,e),this.hydrate=t}};var Pa,Sn=class extends he{constructor({index:e,hydrate:t,...r}){super({initial:null,...r});this.run=async()=>{let e=await this.context.queries.findOneOid({collection:this.collection,index:this.index});this.setValue(e?await this.hydrate(e):null)};this[Pa]=e=>{Ue(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=t}static{Pa=ue}};var Ca,On=class extends he{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.queries.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[Ca]=e=>{Ue(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=t,this._pageSize=r,this._page=s}static{Ca=ue}get pageSize(){return this._pageSize}get page(){return this._page}get hasNextPage(){return this._hasNextPage}get hasPreviousPage(){return this._page>0}};var Aa,In=class extends he{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.queries.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.queries.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[Aa]=e=>{Ue(this.index,e)||(this.index=e,this.execute())};this.index=r,this.hydrate=e,this._pageSize=t}static{Aa=ue}get pageSize(){return this._pageSize}get hasMore(){return this._hasNextPage}};var Ra,_n=class extends he{constructor({index:e,hydrate:t,...r}){super({initial:[],...r});this.run=async()=>{let{result:e}=await this.context.queries.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[Ra]=e=>{Ue(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=t}static{Ra=ue}};var En=class{constructor({collection:i,cache:e,entities:t,context:r,documentManager:s}){this.serializeIndex=i=>i?$e(i):"";this.get=i=>{let e=`get:${this.collection}:${i}`;return this.cache.getOrSet(e,()=>new xn({id:i,collection:this.collection,hydrate:this.hydrate,context:this.context,key:e}))};this.findOne=({index:i,key:e}={})=>{let t=e||`findOne:${this.collection}:${this.serializeIndex(i)}`;return this.cache.getOrSet(t,()=>new Sn({index:i,collection:this.collection,hydrate:this.hydrate,context:this.context,key:t}),r=>{r[ue](i)})};this.findAll=({index:i,key:e}={})=>{let t=e||`findAll:${this.collection}:${this.serializeIndex(i)}`;return this.cache.getOrSet(t,()=>new _n({index:i,collection:this.collection,hydrate:this.hydrate,context:this.context,key:t}),r=>{r[ue](i)})};this.findPage=({index:i,pageSize:e,page:t,key:r})=>{let s=r||`findPage:${this.collection}:${this.serializeIndex(i)}:${e}`;return this.cache.getOrSet(s,()=>new On({index:i,collection:this.collection,hydrate:this.hydrate,context:this.context,key:s,pageSize:e,page:t}),o=>{o[ue](i)})};this.findAllInfinite=({index:i,pageSize:e,key:t})=>{let r=t||`findAllInfinite:${this.collection}:${this.serializeIndex(i)}:${e}`;return this.cache.getOrSet(r,()=>new In({index:i,collection:this.collection,hydrate:this.hydrate,context:this.context,key:r,pageSize:e}),s=>{s[ue](i)})};this.cache=e,this.collection=i,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 Dn=class extends Z{constructor({evictionTime:e=5*1e3,context:t}){super();this._cache=new Map;this.onQueryUnsubscribed=e=>{setTimeout(()=>{e.subscribed||this._cache.get(e.key)===e&&this._cache.delete(e.key)},this._evictionTime)};this.dropAll=()=>{this.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(e){return this._cache.get(e)||null}set(e){return this._cache.set(e.key,e),e[Wi](this.onQueryUnsubscribed),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()))}};var Ji=Symbol("handleMessage"),Ta,Pt=class extends U{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[Ta]=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=Oi,this.self.id="",this.self.replicaId="",s.meta.getLocalReplica().then(o=>{this.self.replicaId=o.id}),this._updateBatcher=new it(this.flushPresenceUpdates),this._updateBatch=this._updateBatcher.add({max:25,timeout:t,items:[],key:"default"})}static{Ta=Ji}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 Pn=class extends Z{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),this.ctx.internalEvents.emit(`fileUploaded:${e.id}`)}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 fetch(s+`/${e.id}`,{method:"POST",body:a,credentials:"include",headers:{Authorization:`Bearer ${o}`}});if(d.ok)return this.ctx.log("info","File upload successful"),{success:!0};{let p=await d.text();return this.ctx.log("error","File upload failed",d.status,p),d.status<500||t.current>=t.max?{success:!1,error:`Failed to upload file: ${d.status} ${p}`}:(await new Promise(m=>setTimeout(m,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(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 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 ct=class extends U{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 Cn=class extends U{constructor({endpointProvider:e,presence:t,interval:r=15*1e3,fetch:s=window.fetch.bind(window),ctx:o}){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();ts(o)&&o.code===_t.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=Lr(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=o,this.presence=t,this.endpointProvider=e,this.fetch=s,this.heartbeat=new ct({interval:r}),this.heartbeat.subscribe("beat",this.onHeartbeat),this.heartbeat.subscribe("missed",this.onHeartbeatMissed)}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 Yi(n){this.message=n}Yi.prototype=new Error,Yi.prototype.name="InvalidCharacterError";var $s=typeof window<"u"&&window.atob&&window.atob.bind(window)||function(n){var i=String(n).replace(/=+$/,"");if(i.length%4==1)throw new Yi("'atob' failed: The string to be decoded is not correctly encoded.");for(var e,t,r=0,s=0,o="";t=i.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 Fa(n){var i=n.replace(/-/g,"+").replace(/_/g,"/");switch(i.length%4){case 0:break;case 2:i+="==";break;case 3:i+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent($s(e).replace(/(.)/g,function(t,r){var s=r.charCodeAt(0).toString(16).toUpperCase();return s.length<2&&(s="0"+s),"%"+s}))}(i)}catch{return $s(i)}}function An(n){this.message=n}function Ba(n,i){if(typeof n!="string")throw new An("Invalid token specified");var e=(i=i||{}).header===!0?0:1;try{return JSON.parse(Fa(n.split(".")[e]))}catch(t){throw new An("Invalid token specified: "+t.message)}}An.prototype=new Error,An.prototype.name="InvalidTokenError";var Ks=Ba;var Rn=class{constructor(i){this.config=i;this.cached=null;this.tokenInfo=null;this.getEndpoints=async()=>{if(this.cached)return this.cached;let i;this.config.fetchAuth?i=await this.config.fetchAuth():i=await(this.config.fetch||fetch.bind(window))(this.config.authEndpoint,{credentials:"include"}).then(d=>{if(d.ok)return d.json();throw new Error(`Auth endpoint returned non-200 response: ${d.status}`)}),N(i.accessToken,"No access token provided from auth endpoint");let e=Ks(i.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:i.accessToken},this.cached};this.clearCache=()=>{this.cached=null};if(!i.authEndpoint&&!i.fetchAuth)throw new Error("Either authEndpoint or fetchAuth must be provided to ServerSyncEndpointProvider")}get type(){return this.tokenInfo?.type??je.Realtime}};var Tn=class extends U{constructor(e){super();this.timer=null;this.isScheduled=!1;this.next=()=>{this.isScheduled||(this.isScheduled=!0,this.timer=setTimeout(()=>{this.emit("trigger"),this.isScheduled=!1,this.backoff.next()},this.backoff.current))};this.reset=()=>{this.backoff.reset(),this.timer&&(clearTimeout(this.timer),this.timer=null)};this.backoff=e}},Fn=class{constructor(i,e){this.current=0;this.next=()=>{this.current=Math.min(this.max,this.current*this.factor)};this.reset=()=>{this.current=0};this.max=i,this.factor=e}};var Bn=class extends U{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 ct;this.reconnectScheduler=new Tn(new Fn(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&&(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 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===WebSocket.OPEN?(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===WebSocket.OPEN&&(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===WebSocket.OPEN}get status(){return this._status}};async function qs(){try{let n=await navigator.permissions.query({name:"periodic-background-sync"});if(n.state==="granted"){let i=await navigator.serviceWorker.ready;if("periodicSync"in i)try{await i.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:",n)}catch(n){console.error("Failed to initiate background sync:",n)}}var kn=class extends U{constructor(e){super();this.mode="pull";this.destroy=()=>{};this.isConnected=!1;this.status="paused";this.pullInterval=0;this.uploadFile=async()=>({success:!1,retry:!1});this.getFile=async()=>({success:!1,error:"Sync is not active"});this.syncOnce=async()=>{};this.presence=new Pt({initialPresence:null,defaultProfile:null,ctx:e})}send(){}async start(){}stop(){}ignoreIncoming(){}reconnect(){}setMode(){}setPullInterval(){}},lt=class extends U{constructor({authEndpoint:e,fetchAuth:t,fetch:r,initialPresence:s,automaticTransportSelection:o=!0,autoStart:a,initialTransport:d,pullInterval:p,presenceUpdateBatchTimeout:m,defaultProfile:D,useBroadcastChannel:v,onOutgoingMessage:P,EXPERIMENTAL_backgroundSync:b},{ctx:x,onData:E}){super();this.broadcastChannel=null;this._activelySyncing=!1;this.handleBroadcastChannelMessage=e=>{e.data.type==="sync"&&this.handleMessage(e.data.message,{source:"broadcastChannel"})};this.handleMessage=async(e,{source:t}={source:"network"})=>{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);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[Ji](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 ne(ne.Code.Unexpected,void 0,"Active sync has invalid token info");(e.type==="sync"||e.type==="op")&&ns(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);throw new Error("Offline, cannot retrieve remote file details")};this.start=()=>this.activeSync.start();this.stop=()=>this.activeSync.stop();this.destroy=()=>{this.dispose(),this.webSocketSync.destroy(),this.pushPullSync.destroy()};this.reconnect=()=>this.activeSync.reconnect();this.syncOnce=()=>this.pushPullSync.syncOnce();if(this.onData=E,this.ctx=x,this.onOutgoingMessage=P,this.presence=new Pt({initialPresence:s,defaultProfile:D,updateBatchTimeout:m,ctx:x}),this.endpointProvider=new Rn({authEndpoint:e,fetchAuth:t,fetch:r}),this.webSocketSync=new Bn({endpointProvider:this.endpointProvider,presence:this.presence,ctx:x}),this.pushPullSync=new Cn({endpointProvider:this.endpointProvider,presence:this.presence,interval:p,fetch:r,ctx:x}),this.fileSync=new Pn({endpointProvider:this.endpointProvider,ctx:x}),v&&"BroadcastChannel"in window&&(this.broadcastChannel=new BroadcastChannel(`verdant-${x.namespace}`),this.broadcastChannel.addEventListener("message",this.handleBroadcastChannelMessage)),d==="realtime"?this.activeSync=this.webSocketSync:this.activeSync=this.pushPullSync,this.presence.subscribe("update",this.handlePresenceUpdate),x.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),o&&this.canDoRealtime){let S=()=>{_&&clearTimeout(_);let y=this.presence.getViewPeers().length>0||o!=="peers-only"&&this.presence.selfReplicaIds.size>1;y&&this.mode==="pull"?this.setMode("realtime"):!y&&this.mode==="realtime"&&(_=setTimeout(()=>{this.presence.getViewPeers().length===0&&this.setMode("pull")},1e3))},_;this.presence.subscribe("peersChanged",S),o!=="peers-only"&&this.presence.subscribe("selfChanged",S)}a&&this.start(),b&&qs()}get canDoRealtime(){return this.endpointProvider.type===je.Realtime||this.endpointProvider.type===je.PassiveRealtime||this.endpointProvider.type===je.ReadOnlyRealtime}get syncing(){return this._activelySyncing}get pullInterval(){return this.pushPullSync.interval}ignoreIncoming(){this.activeSync.ignoreIncoming()}get isConnected(){return this.activeSync.isConnected}get status(){return this.activeSync.status}get mode(){return this.activeSync.mode}};function Qs(n){return n.operations.map(t=>t.timestamp).concat(n.baselines?.map(t=>t.timestamp)??[]).reduce((t,r)=>{let s=Lt(r);return s>t?s:t},0)}function Hs(n,i){return`@@wip_${n}_${$e(i)}`}var jn=class extends Z{constructor(e,t){super();this.db=e;this.context=t;this.onServerReset=e=>this.db.resetSyncedStatusSince(e);this.add=async(e,t)=>{if(e.url&&!e.file){this.context.log("debug","Remote file added to an entity. This usually means an entity was cloned. Downloading remote file...",e.id);let r=await this.context.files.downloadRemoteFile(e.url,0,3);e.file=new File([r],e.name,{type:e.type})}else e.file||this.context.log("warn","File added without a file or URL. This file will not be available for use.",e.id);e.remote=!1,this.context.internalEvents.emit("fileAdded",e),await this.db.add(e,t),this.context.log("debug","File added",e.id,e.name,e.type,e.file?"with binary file":e.url?"with url":"with no data")};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=(e,t)=>`${t}___${e}`;this.export=async(e=!1)=>{let t=await this.getAll();if(e){for(let o of t)if(!o.file&&o.url)try{let a=await this.downloadRemoteFile(o.url);o.file=a}catch(a){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.",a)}}let r=[],s=[];for(let o of t){let a=o.file;if(delete o.file,r.push(o),a){let d=new File([a],this.getFileExportName(o.name,o.id),{type:o.type});s.push(d)}else this.context.log("warn",`File ${o.id} was could not be loaded locally or from the server. It will be missing in the export.`)}return{fileData:r,files:s}};this.import=async({fileData:e,files:t})=>{let r=new Map(t.map(o=>{let{id:a}=this.parseFileExportname(o.name);return[a,o]})),s=e.map(o=>{let a=r.get(o.id);return a?{...o,file:a}:(this.context.log("warn",`File ${o.id} was not found in import`),o)});await Promise.all(s.map(o=>this.add(o)))};this.parseFileExportname=e=>{let[t,r]=e.split("___");return{id:t,originalFileName:r}};this.downloadRemoteFile=async(e,t=0,r=0)=>{let s=await fetch(e,{method:"GET",credentials:"include"});if(!s.ok){if(t<r)return new Promise((o,a)=>{setTimeout(()=>{this.downloadRemoteFile(e,t+1,r).then(o,a)},1e3)});throw new Error(`Failed to download file after ${r} retries (status: ${s.status})`)}return await s.blob()};this.cleanupDeletedFiles=async()=>{let e=0,t=0;await this.iterateOverPendingDelete((r,s)=>{this.config.canCleanupDeletedFile(r)?(e++,s.delete(r.id)):t++}),this.context.log("info",`Cleaned up ${e} files, skipped ${t} files`)};this.onFileRefsDeleted=async e=>{let t=this.db.transaction({mode:"readwrite",storeNames:["files"]});await Promise.all(e.map(async r=>{try{await this.db.markPendingDelete(r.id,{transaction:t})}catch(s){this.context.log("error","Failed to mark file for deletion",s)}})),this.context.log("info",`Marked ${e.length} files as pending delete`)};t.internalEvents.subscribe("filesDeleted",this.onFileRefsDeleted),this.compose(this.db),this.cleanupDeletedFiles()}get config(){return{canCleanupDeletedFile(e){return e.deletedAt!==null&&e.deletedAt<Date.now()-1e3*60*24*3},...this.context.config.files}}};var Mn=class{constructor(i,e){this.db=i;this.ctx=e;this.tryAutonomousRebase=async()=>{(await this.db.getLocalReplica()).lastSyncedLogicalTime||await this.runRebase(this.ctx.time.now)};this.runRebase=async i=>{if(this.ctx.closing)return;let e,t=new Set,r=this.db.transaction({storeNames:["baselines","operations"],mode:"readwrite"}),s=0;if(await this.db.iterateAllOperations(a=>{t.add(a.oid),e=a.timestamp,s++},{before:i,transaction:r}),!t.size||this.ctx.closing)return;let o=[];for(let a of t)o.push(await this.rebase(a,e||i,r));this.ctx.globalEvents.emit("rebase")};this.scheduleRebase=async i=>{this.rebaseTimeout&&clearTimeout(this.rebaseTimeout),this.rebaseTimeout=setTimeout(this.runRebase,this.ctx.config.persistence?.rebaseTimeout??1e4,i)};this.rebaseTimeout=null;this.rebase=async(i,e,t)=>{let r=t||this.db.transaction({storeNames:["operations","baselines"],mode:"readwrite"}),s=await this.db.getBaseline(i,{transaction:r}),o=s?.snapshot||void 0,a=0,d=s?.authz,p=[];await this.db.consumeEntityOperations(i,D=>{(!s||D.timestamp>s.timestamp)&&(o=ke(o,D.data,p),D.data.op==="initialize"&&(d=D.authz)),a++},{to:e,transaction:r}),o&&z(o,i);let m={oid:i,snapshot:o,timestamp:e,authz:d};if(m.snapshot?await this.db.setBaselines([m],{transaction:r}):await this.db.deleteBaseline(i,{transaction:r}),this.ctx.log("debug","rebased",i,"up to",e,":",o,"and deleted",a,"operations"),p.length){let D=p.filter(me);D.length&&this.ctx.internalEvents.emit("filesDeleted",D)}return m}}};var Ln=class{constructor(i,e){this.db=i;this.ctx=e;this.createOperation=async i=>{let e=await this.db.getLocalReplica();return{type:"op",timestamp:this.ctx.time.now,replicaId:e.id,operations:i.operations.map(Jt)}};this.createSyncStep1=async i=>{let e=await this.db.getLocalReplica(),t=i===null?null:e.lastSyncedLogicalTime,r=[],s=new Set,o=await this.db.transaction({mode:"readwrite",storeNames:["operations","baselines"]});t?(this.ctx.log("debug","Syncing local operations since",t),await this.db.iterateLocalOperations(d=>{r.push(Jt(d)),s.add($(d.oid))},{after:t,transaction:o})):(this.ctx.log("debug","Syncing all operations"),await this.db.iterateAllOperations(d=>{r.push(Jt(d)),s.add($(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 i=>{let e=await this.db.getLocalReplica();return{type:"presence-update",presence:i.presence,replicaId:e.id,internal:i.internal}};this.createHeartbeat=async()=>{let i=await this.db.getLocalReplica();return{type:"heartbeat",timestamp:this.ctx.time.now,replicaId:i.id}};this.createAck=async i=>{let e=await this.db.getLocalReplica();return{type:"ack",timestamp:this.ctx.time.now,replicaId:e.id,nonce:i}}}};var dt=class extends Z{constructor(e,t){super();this.db=e;this.ctx=t;this.events=new U;this.insertOperations=async(e,t)=>{this.ctx.log("debug",`Inserting ${e.length} operations`,e);let r=await this.db.addOperations(e,t);for(let s of e)this.ctx.globalEvents.emit("operation",s);return this.ctx.config.persistence?.disableRebasing||this.rebaser.tryAutonomousRebase(),r};this.insertLocalOperations=async(e,t)=>{if(e.length===0)return;for(let s of e)s.isLocal=!0;await this.insertOperations(e,t);let r=await this.messageCreator.createOperation({operations:e});this.events.emit("syncMessage",r)};this.insertRemoteOperations=async(e,t)=>{if(e.length===0)return[];for(let r of e)r.isLocal=!1;await this.insertOperations(e,t),this.ack(e[e.length-1].timestamp)};this.insertRemoteBaselines=async(e,t)=>{if(e.length===0)return[];this.ctx.log("debug",`Inserting ${e.length} remote baselines`),await this.db.setBaselines(e,t);let r=new Set;return e.forEach(s=>{r.add($(s.oid))}),Array.from(r)};this.deleteDocument=async e=>{let t=new Set,r=$(e);N(r===e,"Must be root document OID"),t.add(r);let s=this.db.transaction({storeNames:["baselines","operations"]});await Promise.all([this.db.iterateDocumentBaselines(r,d=>{t.add(d.oid)},{transaction:s}),this.db.iterateDocumentOperations(r,d=>{t.add(d.oid)},{transaction:s})]);let o=await this.getDocumentAuthz(r),a=new Array;for(let d of t)a.push({oid:d,timestamp:this.ctx.time.now,data:{op:"delete"},authz:o});return this.insertLocalOperations(a)};this.deleteCollection=async e=>{let t=new Set,r=this.db.transaction({storeNames:["baselines","operations"],mode:"readwrite"});await Promise.all([this.db.iterateCollectionBaselines(e,o=>{t.add(o.oid)},{transaction:r}),this.db.iterateCollectionOperations(e,o=>{t.add(o.oid)},{transaction:r})]);let s=new Array;for(let o of t)s.push({oid:o,timestamp:this.ctx.time.now,data:{op:"delete"},authz:void 0});return this.insertLocalOperations(s)};this.getDocumentSnapshot=async(e,t={})=>{let r=$(e);N(r===e,"Must be root document OID");let s=this.db.transaction({storeNames:["baselines","operations"],mode:"readwrite"}),o=[];await this.db.iterateDocumentBaselines(r,p=>{o.push(p)},{transaction:s});let a=new Map;for(let p of o)p.snapshot&&z(p.snapshot,p.oid),a.set(p.oid,p.snapshot);await this.db.iterateDocumentOperations(r,p=>{let m=a.get(p.oid)||void 0,D=ke(m,p.data);D&&z(D,p.oid),a.set(p.oid,D)},{transaction:s,to:t.to||this.ctx.time.now});let d=a.get(r);return d&&Wt(d,a),d};this.getDocumentData=async(e,t)=>{let r=this.db.transaction({storeNames:["baselines","operations"],abort:t?.abort}),s=[],o={};return await Promise.all([this.db.iterateDocumentBaselines(e,a=>{s.push(a)},{transaction:r}),this.db.iterateDocumentOperations(e,a=>{o[a.oid]??=[],o[a.oid].push(a)},{transaction:r})]),{baselines:s,operations:o}};this.getDocumentAuthz=async e=>{let t;return await this.db.iterateEntityOperations(e,r=>{if(r.data.op==="initialize")return t=r.authz,!0}),t};this.insertData=async(e,t)=>{let r=this.db.transaction({storeNames:["baselines","operations"],abort:t?.abort,mode:"readwrite"});e.baselines&&await this.insertRemoteBaselines(e.baselines,{transaction:r}),!t?.abort?.aborted&&e.operations&&(e.isLocal?await this.insertLocalOperations(e.operations,{transaction:r}):await this.insertRemoteOperations(e.operations,{transaction:r}))};this.updateLastSynced=async e=>{if(!this.ctx.closing)return this.db.updateLocalReplica({lastSyncedLogicalTime:e})};this.setGlobalAck=async e=>{this.ctx.closing||(await this.db.setGlobalAck(e),this.ctx.config.persistence?.disableRebasing||await this.rebaser.scheduleRebase(e))};this.getLocalReplica=async e=>this.db.getLocalReplica(e);this.iterateLocalOperations=this.db.iterateLocalOperations;this.iterateAllOperations=this.db.iterateAllOperations;this.iterateAllBaselines=this.db.iterateAllBaselines;this.reset=this.db.reset;this.stats=this.db.stats;this.export=async()=>{let e=this.db,t=new Array,r=new Array,s=e.transaction({storeNames:["baselines","operations"],mode:"readwrite"});await this.iterateAllOperations(a=>{r.push(a)},{transaction:s}),await this.iterateAllBaselines(a=>{t.push(a)},{transaction:s});let o=await this.db.getLocalReplica();return{operations:r,baselines:t,localReplica:o,schemaVersion:this.ctx.schema.version}};this.resetFrom=async e=>{let r=this.db.transaction({storeNames:["baselines","operations","info"],mode:"readwrite"});await this.db.reset({clearReplica:!0,transaction:r}),e.localReplica&&await this.db.updateLocalReplica({ackedLogicalTime:e.localReplica.ackedLogicalTime,lastSyncedLogicalTime:e.localReplica.lastSyncedLogicalTime},{transaction:r}),this.ctx.log("debug","Resetting metadata from export",e),await this.insertData({operations:e.operations,baselines:e.baselines,isLocal:!0})};this.manualRebase=async()=>{if(this.ctx.closing||this.ctx.config.persistence?.disableRebasing)return;let e=await this.db.getAckInfo();e.globalAckTimestamp&&await this.rebaser.scheduleRebase(e.globalAckTimestamp)};this.ack=async e=>{let t=await this.db.getLocalReplica();e>this.ctx.time.now||(this.events.emit("syncMessage",{type:"ack",replicaId:t.id,timestamp:e}),!this.ctx.closing&&(!t.ackedLogicalTime||e>t.ackedLogicalTime)&&this.db.updateLocalReplica({ackedLogicalTime:e}))};this.rebaser=new Mn(e,t),this.messageCreator=new Ln(e,t),this.compose(this.db)}};var Vn=class extends Z{constructor(e,t){super();this.db=e;this.ctx=t;this.reset=this.db.reset.bind(this.db);this.saveEntities=this.db.saveEntities;this.findOneOid=this.db.findOneOid.bind(this.db);this.findAllOids=this.db.findAllOids.bind(this.db);this.stats=this.db.stats.bind(this.db);this.compose(this.db)}};async function Un(n){let i=n;if(n.schema.wip&&(i.namespace=Hs(n.originalNamespace,n.schema),i.log("info","Switched to WIP namespace",i.namespace),!(await i.persistence.getNamespaces()).includes(i.namespace))){let t=await i.persistence.getNamespaceVersion(i.originalNamespace);if(t!==0){let r=n.oldSchemas?.find(s=>s.version===t);if(!r)throw new ne(ne.Code.MigrationPathNotFound,void 0,`Trying to open WIP database for version ${n.schema.version}, but the current local data is version ${t} and a historical schema for that version is not available.`);i.log("info",`Copying data from ${i.originalNamespace} to ${i.namespace}`),await i.persistence.copyNamespace(i.originalNamespace,i.namespace,{...i,schema:r})}}if(i.log("info","Opening persistence metadata"),i.meta=new dt(await n.persistence.openMetadata(n),n),i.log("info","Opening persistence files"),i.files=new jn(await n.persistence.openFiles(i),i),i.log("info","Opening persistence queries"),i.queries=new Vn(await n.persistence.openQueries(i),i),!n.schema.wip){let e=await n.persistence.getNamespaces();for(let t of e)t.startsWith("@@wip_")&&(n.log("debug","Cleaning up old WIP namespace",t),await n.persistence.deleteNamespace(t,n))}return i}async function Ws(n,i){n.log("info","Importing data from export");let e=n.oldSchemas?.find(a=>a.version===i.data.schemaVersion);if(!e)throw new Error(`Could not find schema for version ${i.data.schemaVersion}`);let t=`@@import_${Date.now()}`,r=await Un({...n,schema:e,namespace:t,originalNamespace:t,entityEvents:new U,config:{...n.config,persistence:{...n.config.persistence,disableRebasing:!0}}});await r.meta.resetFrom(i.data);let s=new Set;for(let a of i.data.baselines)s.add($(a.oid));for(let a of i.data.operations)s.add($(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.queries.saveEntities(o),await r.files.import(i),n.log("debug","Imported data into temporary namespace",t),await r.queries.dispose(),await r.meta.dispose(),await r.files.dispose(),e.version!==n.schema.version){n.log("debug","Shut down imported databases");let a=n.schema,d=await Un({...r,schema:a});n.log("debug","Upgraded imported data to current schema"),await d.queries.dispose(),await d.meta.dispose(),await d.files.dispose(),n.log("debug","Shut down upgraded databases")}if(await n.persistence.copyNamespace(t,n.namespace,n),i.data.schemaVersion===n.schema.version){let a=await n.meta.stats();if(a.operationsSize.count!==i.data.operations.length)throw n.log("critical","Imported operations count mismatch","expected",i.data.operations.length,"actual",a.operationsSize.count),new ne(ne.Code.ImportFailed,void 0,"Imported operations count mismatch");if(a.baselinesSize.count!==i.data.baselines.length)throw n.log("critical","Imported documents count mismatch","expected",i.data.baselines.length,"actual",a.baselinesSize.count),new ne(ne.Code.ImportFailed,void 0,"Imported documents count mismatch")}n.log("debug","Data copied to primary namespace"),await n.persistence.deleteNamespace(t,n),n.log("debug","Deleted temporary namespace"),n.internalEvents.emit("persistenceReset"),n.log("info","Data imported successfully")}var ut=class extends U{constructor(e){super();this.context=e;this.importingPromise=Promise.resolve();this.addData=async e=>{await this.importingPromise;try{let t=e.reset?Qs(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.queries.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:m})=>p+m,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.files.dispose(),this.sync.stop(),this.sync.destroy(),await this._entities.destroy(),this.context.queries.dispose(),this.context.meta.dispose(),await new Promise(e=>{e()}),this.context.log?.("info","Client closed")};this.__dangerous__resetLocal=async()=>{this.sync.stop(),await wn(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 Ws(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();this.collectionNames=Object.keys(e.schema.collections),this._sync=this.context.config.sync&&!e.schema.wip?new lt(this.context.config.sync,{onData:this.addData,ctx:this.context}):new kn(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 bn({sync:this.sync,context:this.context}),this._entities=new gn({ctx:this.context,files:this._fileManager}),this._queryCache=new Dn({context:e}),this._documentManager=new nn(this.schema,this._entities);let t=Mr(()=>{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")});for(let[r,s]of Object.entries(e.schema.collections)){let o=r;this[o]=new En({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 batch(){return this.entities.batch}get __persistence(){return{meta:this.context.meta,queries:this.context.queries,files:this.context.files}}};var Nn=class{constructor(i){this.value=i}deref(){return this.value}};var zn=class{constructor(i,e){this.base=i;this.version=e;this.withMigrationTime=async(i,e)=>{this.overrideNow=()=>this.base.zero(i),await e(),this.overrideNow=void 0};this.update=this.base.update.bind(this.base);this.nowWithVersion=i=>this.base.now(i);this.zeroWithVersion=i=>this.base.zero(i)}get now(){return this.overrideNow?this.overrideNow():this.base.now(this.version)}get zero(){return this.base.zero(this.version)}};var Ne=class extends Z{constructor(e,{log:t}={}){super();this.db=e;this.globalAbortController=new AbortController;this.createTransaction=(e,t)=>{let r=Vs(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};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 Ye(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(Ye))};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(p=>new Promise((m,D)=>{p.onsuccess=()=>{let v=p.result;v?r(v.value,a,v)?m():v.continue():m()},p.onerror=()=>{p.error&&Je(p.error)?m():D(p.error)}}))).then(()=>{}):new Promise((p,m)=>{d.onsuccess=()=>{let D=d.result;D?r(D.value,a,D)?p():D.continue():p()},d.onerror=()=>{d.error&&Je(d.error)?p():m(d.error)}})};this.clear=(e,t)=>this.run(e,r=>r.clear(),{mode:"readwrite",transaction:t});this.cloneTo=async e=>{await Us(this.db,e)};this.onVersionChange=()=>{this.log?.("warn",`Another tab has requested a version change for ${this.db.name}`),this.db.close(),typeof window<"u"&&window.location.reload()};this.log=t,this.addDispose(()=>{this.globalAbortController.abort()}),this.db.addEventListener("versionchange",this.onVersionChange),this.addDispose(()=>{this.db.removeEventListener("versionchange",this.onVersionChange)})}};var $n=class extends Ne{constructor(){super(...arguments);this.transaction=e=>this.createTransaction(e.storeNames,{mode:e.mode,abort:e.abort});this.add=async(e,t)=>{let r=e.file?await ja(e.file):void 0;if(!r&&t?.downloadRemote&&e.url)try{r=await fetch(e.url,{method:"GET",credentials:"include"}).then(s=>s.arrayBuffer())}catch(s){console.error("Failed to download file to cache it locally. The file will still be available using its URL. Check the file server's CORS configuration.",s)}await this.run("files",s=>s.put({id:e.id,remote:e.remote?"true":"false",deletedAt:null,name:e.name,type:e.type,url:e.url,buffer:r}),{mode:"readwrite",transaction:t?.transaction})};this.markUploaded=async(e,t)=>{let r=await this.getFileRaw(e,t);if(!r)throw new Error("File is not in local database");await this.run("files",s=>s.put({...r,remote:"true"}),{mode:"readwrite",transaction:t?.transaction})};this.get=async(e,t)=>{let r=await this.getFileRaw(e,t);return r?this.hydrateFileData(r):null};this.delete=(e,t)=>this.run("files",r=>r.delete(e),{mode:"readwrite",transaction:t?.transaction});this.markPendingDelete=async(e,t)=>{let r=await this.getFileRaw(e,t);if(!r)throw new Error("File is not in local database");await this.run("files",s=>s.put({...r,deletedAt:Date.now()}),{mode:"readwrite",transaction:t?.transaction})};this.listUnsynced=async e=>(await this.run("files",r=>r.index("remote").getAll("false"),{mode:"readonly",transaction:e?.transaction})).map(this.hydrateFileData);this.resetSyncedStatusSince=async(e,t)=>{let r=t?.transaction??this.createTransaction(["files"],{mode:"readwrite"}),o=(await this.run("files",a=>a.index("remote").getAll("true"),{transaction:r})).filter(a=>!a.timestamp||!e||a.timestamp>e);await Promise.all(o.map(a=>this.run("files",d=>d.put({...a,remote:"false"}),{transaction:r})))};this.iterateOverPendingDelete=(e,t)=>this.iterate("files",r=>r.index("deletedAt").openCursor(IDBKeyRange.lowerBound(0,!0)),(r,s)=>{e(this.hydrateFileData(r),s)},{mode:"readwrite",transaction:t?.transaction});this.getAll=async e=>{let[t]=await Ki(this.db,["files"]);return t.map(this.hydrateFileData)};this.stats=async()=>({size:await Ve(this.db,"files")});this.hydrateFileData=e=>{e.remote=e.remote==="true";let t=e.buffer;return delete e.buffer,e.file=t?ka(t,e.type):void 0,e};this.getFileRaw=async(e,{transaction:t}={})=>{let r=await this.run("files",s=>s.get(e),{mode:"readonly",transaction:t});if(r)return r}}};function ka(n,i){return new Blob([n],{type:i})}function ja(n){return"__testReadBuffer"in n?Promise.resolve(n.__testReadBuffer):new Promise((i,e)=>{let t=new FileReader;t.onload=()=>{i(t.result)},t.onerror=e,t.readAsArrayBuffer(n)})}var Js=Te(ze(),1);var Kn=class extends Ne{constructor(e,t){super(e,t);this.ctx=t;this.transaction=e=>this.createTransaction(e.storeNames,{mode:e.mode,abort:e.abort});this.getAckInfo=async()=>{let e=await this.run("info",t=>t.get("ack"));return e||{globalAckTimestamp:null,type:"ack"}};this.setGlobalAck=async e=>{await this.run("info",t=>t.put({type:"ack",globalAckTimestamp:e}),{mode:"readwrite"})};this.getLocalReplica=async e=>{if(this.cachedLocalReplica)return this.cachedLocalReplica;let t=await this.run("info",r=>r.get("localReplicaInfo"),this.convertOpts(e));return t?(this.cachedLocalReplica=t,t):(this._creatingLocalReplica||(this._creatingLocalReplica=(async()=>{let s={type:"localReplicaInfo",id:(0,Js.default)(),userId:void 0,ackedLogicalTime:null,lastSyncedLogicalTime:null};await this.run("info",o=>o.put(s),{mode:"readwrite"}),this.cachedLocalReplica=s})()),await this._creatingLocalReplica,this.getLocalReplica(e))};this.updateLocalReplica=async(e,t=Ct)=>{let r=await this.getLocalReplica(t);Object.assign(r,e),await this.run("info",s=>s.put(r),{mode:"readwrite"}),this.cachedLocalReplica=r};this.iterateDocumentBaselines=async(e,t,r)=>{await this.iterate("baselines",s=>{let o=$(e),[a,d]=Ar(e),[p,m]=Ur(e);return[s.openCursor(IDBKeyRange.only(o)),s.openCursor(IDBKeyRange.bound(a,d,!1,!1)),s.openCursor(IDBKeyRange.bound(p,m,!1,!1))]},t,this.convertOpts(r))};this.iterateCollectionBaselines=async(e,t,r)=>{await this.iterate("baselines",s=>[s.openCursor(IDBKeyRange.bound(e,e+"\uFFFF",!1,!1))],t,this.convertOpts(r))};this.iterateAllBaselines=async(e,t)=>{await this.iterate("baselines",r=>r.index("timestamp").openCursor(),e,this.convertOpts(t))};this.getBaseline=(e,t)=>this.run("baselines",r=>r.get(e),this.convertOpts(t));this.setBaselines=async(e,t=Ct)=>{await this.runAll("baselines",r=>e.map(s=>r.put(s)),this.convertOpts(t))};this.deleteBaseline=async(e,t=Ct)=>{await this.run("baselines",r=>r.delete(e),this.convertOpts(t))};this.iterateDocumentOperations=(e,t,r)=>this.iterate("operations",s=>{let o=s.index("d_t"),a=Re(e),d=r?.to?we(e,r.to):Le(e),p=IDBKeyRange.bound(a,d,!1,!1);return o.openCursor(p)},t,this.convertOpts(r));this.iterateEntityOperations=(e,t,r)=>this.iterate("operations",s=>{let o=Re(e),a=r?.to?we(e,r.to):Le(e),d=IDBKeyRange.bound(o,a,!1,!1);return s.openCursor(d)},t,this.convertOpts(r));this.consumeEntityOperations=(e,t,r=Ct)=>this.iterate("operations",s=>{let o=Re(e),a=r?.to?we(e,r.to):Le(e),d=IDBKeyRange.bound(o,a,!1,!1);return s.openCursor(d)},(s,o)=>{t(s),o.delete(s.oid_timestamp)},this.convertOpts(r));this.iterateCollectionOperations=(e,t,r)=>this.iterate("operations",s=>s.openCursor(IDBKeyRange.bound(e,e+"\uFFFF",!1,!1),"next"),t,this.convertOpts(r));this.iterateLocalOperations=(e,t)=>this.iterate("operations",r=>{let s=t?.after?we(!0,t.after):Re(!0),o=Le(!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?Re(t.from):void 0,o=t?.before?Le(t.before):Re(!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,this.convertOpts(t));this.addOperations=async(e,t=Ct)=>{let r=new Set;return await this.runAll("operations",s=>e.map(o=>(r.add($(o.oid)),s.put(this.addOperationIndexes(o)))),this.convertOpts(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 Ve(this.db,"operations"),t=await Ve(this.db,"baselines");return{operationsSize:e,baselinesSize:t}};this.resetLocalReplica=async(e,t=!1)=>{if(t)return this.run("info",s=>s.delete("localReplicaInfo"),{mode:"readwrite",transaction:e});let r=await this.getLocalReplica();r.ackedLogicalTime=null,r.lastSyncedLogicalTime=null,await this.run("info",s=>s.put(r),{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:we(e.oid,e.timestamp),l_t:we(e.isLocal,e.timestamp),d_t:we($(e.oid),e.timestamp)});this.convertOpts=e=>{if(e?.transaction&&!(e.transaction instanceof IDBTransaction))throw new Error(`Invalid IndexedDB transaction. You cannot mix persistence providers. ${typeof e.transaction}`);return{mode:e?.mode,transaction:e?.transaction}};this.addDispose(()=>xe(e))}},Ct={mode:"readwrite"};var Ys=[La,Va,Ua,Na,za,$a],Ma=Ys.length;function Gi({indexedDB:n=window.indexedDB,namespace:i,log:e,metadataVersion:t=Ma}){return new Promise((r,s)=>{let o=n.open(vn(i),t),a=!1;o.onupgradeneeded=async d=>{let p=o.result,m=o.transaction,D=Ys.slice(d.oldVersion);for(let v of D)await v(p,m);await new Promise((v,P)=>{m.addEventListener("complete",v),m.addEventListener("error",P)}),d.oldVersion||(a=!0)},o.onerror=()=>{console.error("Error opening database",o.error),s(o.error)},o.onsuccess=()=>{r({db:o.result,wasInitialized:a})}})}async function La(n,i){let e=n.createObjectStore("baselines",{keyPath:"oid"}),t=n.createObjectStore("operations",{keyPath:"oid_timestamp"}),r=n.createObjectStore("info",{keyPath:"type"});e.createIndex("timestamp","timestamp"),t.createIndex("isLocal_timestamp","isLocal_timestamp"),t.createIndex("documentOid_timestamp","documentOid_timestamp")}async function Va(n,i){let e=i.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,...p}=o.value;o.update({...p,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 Ua(n,i){i.objectStore("operations").createIndex("timestamp","timestamp")}async function Na(n,i){let e=n.createObjectStore("files",{keyPath:"id"});e.createIndex("remote","remote"),e.createIndex("deletedAt","deletedAt")}async function za(n,i){let e=i.objectStore("operations");await new Promise((r,s)=>{let o=e.openCursor();o.onsuccess=()=>{let a=o.result;if(a){let d=di(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=i.objectStore("baselines");await new Promise((r,s)=>{let o=t.openCursor();o.onsuccess=()=>{let a=o.result;if(a){let d=di(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 $a(n,i){i.objectStore("files").createIndex("timestamp","timestamp")}var Ka=n=>IDBKeyRange.only(be(n.equals)),qa=n=>{},Qa=n=>{let i=n.gte||n.gt,e=n.lte||n.lt;return i===e?IDBKeyRange.only(be(i)):i?e?IDBKeyRange.bound(be(i),be(e),!!n.gt,!!n.lt):IDBKeyRange.lowerBound(be(i),!!n.gt):IDBKeyRange.upperBound(be(e),!!n.lt)},Ha=(n,i,e)=>{let t=n.collections[i].compounds[e.where];N(t,`Index ${e.where} does not exist on collection ${i}`);let r=Object.keys(e.match).sort((d,p)=>t.of.indexOf(d)-t.of.indexOf(p));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(we(...s));let o=Re(...s),a=Le(...s);return IDBKeyRange.bound(o,a)};function Wa(n){let i=n.startsWith,e=n.startsWith+"\uFFFF";return IDBKeyRange.bound(i,e)}function Xi(n,i,e){if(e)return pi(e)?Qa(e):hi(e)?Ka(e):Wr(e)?qa(e):mi(e)?Wa(e):Ha(n,i,e)}var ft=class extends Ne{constructor(e,t){super(e,{log:t.log});this.stats=async()=>{let e=Object.keys(this.ctx.schema.collections),t={};return await Promise.all(e.map(async r=>{let s=await Ve(this.db,r);t[r]=s})),t};this.transaction=e=>this.createTransaction(e.storeNames,{mode:e.mode,abort:e.abort});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=Xi(this.ctx.schema,e.collection,e.index);return s.openCursor(a,o)},{mode:"readonly"});return t?Y(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,p=t?.order==="desc"?"prev":"next",m=Xi(this.ctx.schema,e,t),D=d.openCursor(m,p),v=!1;return{result:await new Promise((b,x)=>{let E=!r,S=0,_=new Set;D.onsuccess=()=>{S++;let F=D.result;if(!F){b(Array.from(_));return}r&&!E?(F.advance(r),E=!0):((!s||_.size<s)&&_.add(Y(e,F.primaryKey.toString())),s&&S>s?(v=!0,b(Array.from(_))):F.continue())},D.onerror=()=>{D.error?.name==="InvalidStateError"?(this.ctx.log("error","find query failed with InvalidStateError",D.error),b([])):D.error&&Je(D.error)?b([]):x(D.error)}}),hasNextPage:v}};this.saveEntities=async(e,t)=>{if(e.length===0)return;let r=Array.from(new Set(e.map(d=>ce(d.oid).collection))),s=r.filter(d=>!this.ctx.schema.collections[d]);s.length>0&&this.ctx.log("warn",`Ignoring entities from collections that no longer exist: ${s.join(", ")}`);let o=new Set(r);s.forEach(d=>o.delete(d)),r=Array.from(o);let a={transaction:this.createTransaction(r,{mode:"readwrite",abort:t?.abort})};await Promise.all(e.map(async d=>{let p=d.getSnapshot();try{await this.saveDocument(d.oid,p,a)}catch(m){throw this.ctx.log("error",`Error saving document ${d.oid} (${JSON.stringify(p)})`,m),m instanceof Error?m:new Error("Unknown error saving document")}})),a.transaction.commit(),this.ctx.entityEvents.emit("collectionsChanged",r);for(let d of e)this.ctx.entityEvents.emit("documentChanged",d.oid)};this.reset=async e=>{let t=Object.keys(this.ctx.schema.collections),r=e?.transaction||this.createTransaction(t,{mode:"readwrite"});await Promise.all(t.map(s=>this.run(s,o=>o.clear(),{transaction:r}))),this.ctx.entityEvents.emit("collectionsChanged",t),this.ctx.log("info","\u{1F4A8} Reset queryable storage")};this.dispose=()=>xe(this.db);this.saveDocument=async(e,t,{transaction:r})=>{this.ctx.log("debug",`Saving document indexes for querying ${e}`);let{collection:s,id:o}=ce(e);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=Xt(a,t);await this.run(s,p=>p.put(d),{mode:"readwrite",transaction:r}),this.ctx.log("debug",`Save complete for ${e}`,d)}};this.ctx=t}};async function qn(n,i){let e=Qi(i),r=(await n.databases()).find(s=>s.name===e);return r?r.version??0:0}async function Gs(n,i,e,t,r){function s(o,a){let d=n.open([i,"collections"].join("_"),e),p=!1;d.onupgradeneeded=m=>{let D=d.transaction;t(D,d.result,m),p=!0},d.onsuccess=m=>{p?o(d.result):a(new Error("Database was not upgraded when a version change was expected"))},d.onerror=m=>{a(d.error||new Error("Unknown error"))},d.onblocked=m=>{r?.("Database upgrade blocked, waiting...")}}return new Promise(s)}async function Xs(n,i){typeof navigator<"u"&&navigator.locks?await navigator.locks.request(`verdant_migration_${n}`,i):await i()}async function Qn({indexedDB:n=$i,namespace:i,version:e,context:t}){t.log("debug","Opening database",i,"at version",e);let r=await Ns(Qi(i),e,n);return r.addEventListener("versionchange",s=>{r.close()}),r}function Zs({migration:n,newOids:i,ctx:e}){return n.allCollections.reduce((t,r)=>(t[r]={put:async(s,o)=>{Ce(n.newSchema.collections[r],s);let a=s[n.newSchema.collections[r].primaryKey],d=Y(r,a);return i.push(d),await e.time.withMigrationTime(n.version,()=>e.meta.insertData({operations:e.patchCreator.createInitialize(s,d,o?.access),isLocal:!0})),s},delete:async s=>{let o=Y(r,s);await e.time.withMigrationTime(n.version,()=>e.meta.deleteDocument(o))}},t),{})}function Ja({migration:n,context:i,queryDb:e}){let t=new ft(e,i);return n.oldCollections.reduce((r,s)=>(r[s]={get:async o=>{let a=Y(s,o);return await i.meta.getDocumentSnapshot(a,{to:i.time.nowWithVersion(n.oldSchema.version)})},findOne:async o=>{let a=await t.findOneOid({collection:s,index:o});return a?await i.meta.getDocumentSnapshot(a,{to:i.time.nowWithVersion(n.oldSchema.version)}):null},findAll:async o=>{let{result:a}=await t.findAllOids({collection:s,index:o});return await Promise.all(a.map(p=>i.meta.getDocumentSnapshot(p,{to:i.time.nowWithVersion(n.oldSchema.version)})))}},r),{})}function eo({migration:n,context:i,queryDb:e}){let t=new Array,r=Ja({migration:n,context:i,queryDb:e}),s=Zs({migration:n,newOids:t,ctx:i}),o=async p=>{await i.meta.deleteCollection(p)},a=new Array;return{log:i.log,newOids:t,deleteCollection:o,migrate:async(p,m)=>{let D=await r[p].findAll();await Promise.all(D.filter(Boolean).map(async v=>{let P=ie(v);N(!!P,`Document is missing an OID: ${JSON.stringify(v)}`);let b=await i.meta.getDocumentAuthz(P),x=le(v),E=await m(v);if(E){xt(x),xt(E),et(E);let S=St(x,E,()=>i.time.zeroWithVersion(n.version),void 0,[],{mergeUnknownObjects:!0,authz:b});S.length>0&&await i.meta.insertData({operations:S,isLocal:!0})}}))},queries:r,mutations:s,awaitables:a}}function to({migration:n,context:i}){let e=new Array,t=new Proxy({},{get(){throw new Error("Queries are not available in initial migrations; there is no database yet!")}}),r=Zs({migration:n,newOids:e,ctx:i});return{log:i.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:[]}}var no=typeof window<"u"?window.indexedDB:void 0;async function io({context:n,toRun:i,indexedDB:e=no,namespace:t=n.namespace}){await Xs(t,async()=>{for(let r of i){let s;if(r.oldSchema.version===0)s=to({migration:r,context:n}),await r.migrate(s);else{let d=await Qn({indexedDB:e,namespace:t,version:r.oldSchema.version,context:n});s=eo({migration:r,context:n,queryDb:d});try{await r.migrate(s),await Promise.all(s.awaitables)}catch(p){throw n.log("critical",`Migration failed (${r.oldSchema.version} -> ${r.newSchema.version})`,p),p instanceof Error?p:new Error("Unknown error during migration")}await xe(d)}n.log("debug","Upgrading database",t,"to version",r.newSchema.version);let o=await ec({migration:r,indexedDB:e,namespace:t,context:n}),a=await Za({currentVersion:r.oldSchema.version,newVersion:r.newSchema.version,ctx:n});for(let d of r.allCollections){let m=o.transaction(d,"readwrite").objectStore(d),v=(await Ya(m)).map(S=>Y(d,`${S}`));v.push(...s.newOids.filter(S=>ce(S).collection===d),...a.filter(S=>ce(S).collection===d));let b=(await Promise.all(v.map(async S=>{try{let _=await n.meta.getDocumentSnapshot(S);return[S,_]}catch(_){return n.log("error","Could not regenerate snapshot during migration for oid",S,"this document will not be preserved",_),null}}))).filter(S=>!!S).map(([S,_])=>{if(!_)return[S,void 0];let F=Xt(r.newSchema.collections[d],_);return[S,F]}),E=o.transaction(d,"readwrite").objectStore(d);await Promise.all(b.map(([S,_])=>{if(_)return Xa(E,_);{let{id:F}=ce(S);return Ga(E,F)}}))}await xe(o),n.log("debug",`Migration of ${t} complete.`),n.log("info",`
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 F(){return{buf:"",write:function(y){this.buf+=y},end:function(y){this.buf+=y},read:function(){return this.buf}}}e.writeToStream=function(y,I,u){return u===void 0&&(u=I,I={}),_(I=E(y,I),u).dispatch(y)}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/fake_9a5aa49d.js","/")},{buffer:3,crypto:5,lYpoI2:11}],2:[function(n,i,e){(function(t,r,s,o,a,d,p,m,D){(function(v){"use strict";var P=typeof Uint8Array<"u"?Uint8Array:Array,b="+".charCodeAt(0),x="/".charCodeAt(0),E="0".charCodeAt(0),S="a".charCodeAt(0),_="A".charCodeAt(0),F="-".charCodeAt(0),y="_".charCodeAt(0);function I(u){return u=u.charCodeAt(0),u===b||u===F?62:u===x||u===y?63:u<E?-1:u<E+10?u-E+26+26:u<_+26?u-_:u<S+26?u-S+26:void 0}v.toByteArray=function(u){var h,l;if(0<u.length%4)throw new Error("Invalid string. Length must be a multiple of 4");var w=u.length,w=u.charAt(w-2)==="="?2:u.charAt(w-1)==="="?1:0,O=new P(3*u.length/4-w),j=0<w?u.length-4:u.length,k=0;function M(B){O[k++]=B}for(h=0;h<j;h+=4,0)M((16711680&(l=I(u.charAt(h))<<18|I(u.charAt(h+1))<<12|I(u.charAt(h+2))<<6|I(u.charAt(h+3))))>>16),M((65280&l)>>8),M(255&l);return w==2?M(255&(l=I(u.charAt(h))<<2|I(u.charAt(h+1))>>4)):w==1&&(M((l=I(u.charAt(h))<<10|I(u.charAt(h+1))<<4|I(u.charAt(h+2))>>2)>>8&255),M(255&l)),O},v.fromByteArray=function(u){var h,l,w,O,j=u.length%3,k="";function M(B){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(B)}for(h=0,w=u.length-j;h<w;h+=3)l=(u[h]<<16)+(u[h+1]<<8)+u[h+2],k+=M((O=l)>>18&63)+M(O>>12&63)+M(O>>6&63)+M(63&O);switch(j){case 1:k=(k+=M((l=u[u.length-1])>>2))+M(l<<4&63)+"==";break;case 2:k=(k=(k+=M((l=(u[u.length-2]<<8)+u[u.length-1])>>10))+M(l>>4&63))+M(l<<2&63)+"="}return k}})(e===void 0?this.base64js={}:e)}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("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(n,i,e){(function(t,r,b,o,a,d,p,m,D){var v=n("base64-js"),P=n("ieee754");function b(c,f,g){if(!(this instanceof b))return new b(c,f,g);var A,C,T,L,H=typeof c;if(f==="base64"&&H=="string")for(c=(L=c).trim?L.trim():L.replace(/^\s+|\s+$/g,"");c.length%4!=0;)c+="=";if(H=="number")A=ne(c);else if(H=="string")A=b.byteLength(c,f);else{if(H!="object")throw new Error("First argument needs to be a number, array or string.");A=ne(c.length)}if(b._useTypedArrays?C=b._augment(new Uint8Array(A)):((C=this).length=A,C._isBuffer=!0),b._useTypedArrays&&typeof c.byteLength=="number")C._set(c);else if(Q(L=c)||b.isBuffer(L)||L&&typeof L=="object"&&typeof L.length=="number")for(T=0;T<A;T++)b.isBuffer(c)?C[T]=c.readUInt8(T):C[T]=c[T];else if(H=="string")C.write(c,0,f);else if(H=="number"&&!b._useTypedArrays&&!g)for(T=0;T<A;T++)C[T]=0;return C}function x(c,f,g,A){return b._charsWritten=At(function(C){for(var T=[],L=0;L<C.length;L++)T.push(255&C.charCodeAt(L));return T}(f),c,g,A)}function E(c,f,g,A){return b._charsWritten=At(function(C){for(var T,L,H=[],G=0;G<C.length;G++)L=C.charCodeAt(G),T=L>>8,L=L%256,H.push(L),H.push(T);return H}(f),c,g,A)}function S(c,f,g){var A="";g=Math.min(c.length,g);for(var C=f;C<g;C++)A+=String.fromCharCode(c[C]);return A}function _(c,f,g,T){T||(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 C,T=c.length;if(!(T<=f))return g?(C=c[f],f+1<T&&(C|=c[f+1]<<8)):(C=c[f]<<8,f+1<T&&(C|=c[f+1])),C}function F(c,f,g,T){T||(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 C,T=c.length;if(!(T<=f))return g?(f+2<T&&(C=c[f+2]<<16),f+1<T&&(C|=c[f+1]<<8),C|=c[f],f+3<T&&(C+=c[f+3]<<24>>>0)):(f+1<T&&(C=c[f+1]<<16),f+2<T&&(C|=c[f+2]<<8),f+3<T&&(C|=c[f+3]),C+=c[f]<<24>>>0),C}function y(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=_(c,f,g,!0),32768&A?-1*(65535-A+1):A}function I(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=F(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")),P.read(c,f,g,23,4)}function h(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")),P.read(c,f,g,52,8)}function l(c,f,g,A,C){if(C||(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"),Jn(f,65535)),C=c.length,!(C<=g))for(var T=0,L=Math.min(C-g,2);T<L;T++)c[g+T]=(f&255<<8*(A?T:1-T))>>>8*(A?T:1-T)}function w(c,f,g,A,C){if(C||(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"),Jn(f,4294967295)),C=c.length,!(C<=g))for(var T=0,L=Math.min(C-g,4);T<L;T++)c[g+T]=f>>>8*(A?T:3-T)&255}function O(c,f,g,A,C){C||(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"),Yn(f,32767,-32768)),c.length<=g||l(c,0<=f?f:65535+f+1,g,A,C)}function j(c,f,g,A,C){C||(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"),Yn(f,2147483647,-2147483648)),c.length<=g||w(c,0<=f?f:4294967295+f+1,g,A,C)}function k(c,f,g,A,C){C||(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"),rr(f,34028234663852886e22,-34028234663852886e22)),c.length<=g||P.write(c,f,g,A,23,4)}function M(c,f,g,A,C){C||(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"),rr(f,17976931348623157e292,-17976931348623157e292)),c.length<=g||P.write(c,f,g,A,52,8)}e.Buffer=b,e.SlowBuffer=b,e.INSPECT_MAX_BYTES=50,b.poolSize=8192,b._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}}(),b.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}},b.isBuffer=function(c){return!(c==null||!c._isBuffer)},b.byteLength=function(c,f){var g;switch(c+="",f||"utf8"){case"hex":g=c.length/2;break;case"utf8":case"utf-8":g=_e(c).length;break;case"ascii":case"binary":case"raw":g=c.length;break;case"base64":g=nr(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},b.concat=function(c,f){if(R(Q(c),`Usage: Buffer.concat(list, [totalLength])
5
+ list should be an Array.`),c.length===0)return new b(0);if(c.length===1)return c[0];if(typeof f!="number")for(C=f=0;C<c.length;C++)f+=c[C].length;for(var g=new b(f),A=0,C=0;C<c.length;C++){var T=c[C];T.copy(g,A),A+=T.length}return g},b.prototype.write=function(c,f,g,A){isFinite(f)?isFinite(g)||(A=g,g=void 0):(G=A,A=f,f=g,g=G),f=Number(f)||0;var C,T,L,H,G=this.length-f;switch((!g||G<(g=Number(g)))&&(g=G),A=String(A||"utf8").toLowerCase()){case"hex":C=function(pe,re,se,X){se=Number(se)||0;var J=pe.length-se;(!X||J<(X=Number(X)))&&(X=J),R((J=re.length)%2==0,"Invalid hex string"),J/2<X&&(X=J/2);for(var Ge=0;Ge<X;Ge++){var sr=parseInt(re.substr(2*Ge,2),16);R(!isNaN(sr),"Invalid hex string"),pe[se+Ge]=sr}return b._charsWritten=2*Ge,Ge}(this,c,f,g);break;case"utf8":case"utf-8":T=this,L=f,H=g,C=b._charsWritten=At(_e(c),T,L,H);break;case"ascii":case"binary":C=x(this,c,f,g);break;case"base64":T=this,L=f,H=g,C=b._charsWritten=At(nr(c),T,L,H);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":C=E(this,c,f,g);break;default:throw new Error("Unknown encoding")}return C},b.prototype.toString=function(c,f,g){var A,C,T,L,H=this;if(c=String(c||"utf8").toLowerCase(),f=Number(f)||0,(g=g!==void 0?Number(g):H.length)===f)return"";switch(c){case"hex":A=function(G,pe,re){var se=G.length;(!pe||pe<0)&&(pe=0),(!re||re<0||se<re)&&(re=se);for(var X="",J=pe;J<re;J++)X+=K(G[J]);return X}(H,f,g);break;case"utf8":case"utf-8":A=function(G,pe,re){var se="",X="";re=Math.min(G.length,re);for(var J=pe;J<re;J++)G[J]<=127?(se+=ir(X)+String.fromCharCode(G[J]),X=""):X+="%"+G[J].toString(16);return se+ir(X)}(H,f,g);break;case"ascii":case"binary":A=S(H,f,g);break;case"base64":C=H,L=g,A=(T=f)===0&&L===C.length?v.fromByteArray(C):v.fromByteArray(C.slice(T,L));break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":A=function(G,pe,re){for(var se=G.slice(pe,re),X="",J=0;J<se.length;J+=2)X+=String.fromCharCode(se[J]+256*se[J+1]);return X}(H,f,g);break;default:throw new Error("Unknown encoding")}return A},b.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},b.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 C=(A=c.length-f<A-g?c.length-f+g:A)-g;if(C<100||!b._useTypedArrays)for(var T=0;T<C;T++)c[T+f]=this[T+g];else c._set(this.subarray(g,g+C),f)}},b.prototype.slice=function(c,f){var g=this.length;if(c=q(c,g,0),f=q(f,g,g),b._useTypedArrays)return b._augment(this.subarray(c,f));for(var A=f-c,C=new b(A,void 0,!0),T=0;T<A;T++)C[T]=this[T+c];return C},b.prototype.get=function(c){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(c)},b.prototype.set=function(c,f){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(c,f)},b.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]},b.prototype.readUInt16LE=function(c,f){return _(this,c,!0,f)},b.prototype.readUInt16BE=function(c,f){return _(this,c,!1,f)},b.prototype.readUInt32LE=function(c,f){return F(this,c,!0,f)},b.prototype.readUInt32BE=function(c,f){return F(this,c,!1,f)},b.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]},b.prototype.readInt16LE=function(c,f){return y(this,c,!0,f)},b.prototype.readInt16BE=function(c,f){return y(this,c,!1,f)},b.prototype.readInt32LE=function(c,f){return I(this,c,!0,f)},b.prototype.readInt32BE=function(c,f){return I(this,c,!1,f)},b.prototype.readFloatLE=function(c,f){return u(this,c,!0,f)},b.prototype.readFloatBE=function(c,f){return u(this,c,!1,f)},b.prototype.readDoubleLE=function(c,f){return h(this,c,!0,f)},b.prototype.readDoubleBE=function(c,f){return h(this,c,!1,f)},b.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"),Jn(c,255)),f>=this.length||(this[f]=c)},b.prototype.writeUInt16LE=function(c,f,g){l(this,c,f,!0,g)},b.prototype.writeUInt16BE=function(c,f,g){l(this,c,f,!1,g)},b.prototype.writeUInt32LE=function(c,f,g){w(this,c,f,!0,g)},b.prototype.writeUInt32BE=function(c,f,g){w(this,c,f,!1,g)},b.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"),Yn(c,127,-128)),f>=this.length||(0<=c?this.writeUInt8(c,f,g):this.writeUInt8(255+c+1,f,g))},b.prototype.writeInt16LE=function(c,f,g){O(this,c,f,!0,g)},b.prototype.writeInt16BE=function(c,f,g){O(this,c,f,!1,g)},b.prototype.writeInt32LE=function(c,f,g){j(this,c,f,!0,g)},b.prototype.writeInt32BE=function(c,f,g){j(this,c,f,!1,g)},b.prototype.writeFloatLE=function(c,f,g){k(this,c,f,!0,g)},b.prototype.writeFloatBE=function(c,f,g){k(this,c,f,!1,g)},b.prototype.writeDoubleLE=function(c,f,g){M(this,c,f,!0,g)},b.prototype.writeDoubleBE=function(c,f,g){M(this,c,f,!1,g)},b.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}},b.prototype.inspect=function(){for(var c=[],f=this.length,g=0;g<f;g++)if(c[g]=K(this[g]),g===e.INSPECT_MAX_BYTES){c[g+1]="...";break}return"<Buffer "+c.join(" ")+">"},b.prototype.toArrayBuffer=function(){if(typeof Uint8Array>"u")throw new Error("Buffer.toArrayBuffer not supported in this browser");if(b._useTypedArrays)return new b(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 B=b.prototype;function q(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 Q(c){return(Array.isArray||function(f){return Object.prototype.toString.call(f)==="[object Array]"})(c)}function K(c){return c<16?"0"+c.toString(16):c.toString(16)}function _e(c){for(var f=[],g=0;g<c.length;g++){var A=c.charCodeAt(g);if(A<=127)f.push(c.charCodeAt(g));else for(var C=g,T=(55296<=A&&A<=57343&&g++,encodeURIComponent(c.slice(C,g+1)).substr(1).split("%")),L=0;L<T.length;L++)f.push(parseInt(T[L],16))}return f}function nr(c){return v.toByteArray(c)}function At(c,f,g,A){for(var C=0;C<A&&!(C+g>=f.length||C>=c.length);C++)f[C+g]=c[C];return C}function ir(c){try{return decodeURIComponent(c)}catch{return String.fromCharCode(65533)}}function Jn(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 Yn(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 rr(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")}b._augment=function(c){return c._isBuffer=!0,c._get=c.get,c._set=c.set,c.get=B.get,c.set=B.set,c.write=B.write,c.toString=B.toString,c.toLocaleString=B.toString,c.toJSON=B.toJSON,c.copy=B.copy,c.slice=B.slice,c.readUInt8=B.readUInt8,c.readUInt16LE=B.readUInt16LE,c.readUInt16BE=B.readUInt16BE,c.readUInt32LE=B.readUInt32LE,c.readUInt32BE=B.readUInt32BE,c.readInt8=B.readInt8,c.readInt16LE=B.readInt16LE,c.readInt16BE=B.readInt16BE,c.readInt32LE=B.readInt32LE,c.readInt32BE=B.readInt32BE,c.readFloatLE=B.readFloatLE,c.readFloatBE=B.readFloatBE,c.readDoubleLE=B.readDoubleLE,c.readDoubleBE=B.readDoubleBE,c.writeUInt8=B.writeUInt8,c.writeUInt16LE=B.writeUInt16LE,c.writeUInt16BE=B.writeUInt16BE,c.writeUInt32LE=B.writeUInt32LE,c.writeUInt32BE=B.writeUInt32BE,c.writeInt8=B.writeInt8,c.writeInt16LE=B.writeInt16LE,c.writeInt16BE=B.writeInt16BE,c.writeInt32LE=B.writeInt32LE,c.writeInt32BE=B.writeInt32BE,c.writeFloatLE=B.writeFloatLE,c.writeFloatBE=B.writeFloatBE,c.writeDoubleLE=B.writeDoubleLE,c.writeDoubleBE=B.writeDoubleBE,c.fill=B.fill,c.inspect=B.inspect,c.toArrayBuffer=B.toArrayBuffer,c}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("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(n,i,e){(function(t,r,v,o,a,d,p,m,D){var v=n("buffer").Buffer,P=4,b=new v(P);b.fill(0),i.exports={hash:function(x,E,S,_){for(var F=E(function(l,w){l.length%P!=0&&(O=l.length+(P-l.length%P),l=v.concat([l,b],O));for(var O,j=[],k=w?l.readInt32BE:l.readInt32LE,M=0;M<l.length;M+=P)j.push(k.call(l,M));return j}(x=v.isBuffer(x)?x:new v(x),_),8*x.length),E=_,y=new v(S),I=E?y.writeInt32BE:y.writeInt32LE,u=0;u<F.length;u++)I.call(y,F[u],4*u,!0);return y}}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("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(n,i,e){(function(t,r,v,o,a,d,p,m,D){var v=n("buffer").Buffer,P=n("./sha"),b=n("./sha256"),x=n("./rng"),E={sha1:P,sha256:b,md5:n("./md5")},S=64,_=new v(S);function F(l,w){var O=E[l=l||"sha1"],j=[];return O||y("algorithm:",l,"is not yet supported"),{update:function(k){return v.isBuffer(k)||(k=new v(k)),j.push(k),k.length,this},digest:function(k){var M=v.concat(j),M=w?function(B,q,ne){v.isBuffer(q)||(q=new v(q)),v.isBuffer(ne)||(ne=new v(ne)),q.length>S?q=B(q):q.length<S&&(q=v.concat([q,_],S));for(var Q=new v(S),K=new v(S),_e=0;_e<S;_e++)Q[_e]=54^q[_e],K[_e]=92^q[_e];return ne=B(v.concat([Q,ne])),B(v.concat([K,ne]))}(O,w,M):O(M);return j=null,k?M.toString(k):M}}}function y(){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 F(l)},e.createHmac=F,e.randomBytes=function(l,w){if(!w||!w.call)return new v(x(l));try{w.call(this,void 0,new v(x(l)))}catch(O){w(O)}};var I,u=["createCredentials","createCipher","createCipheriv","createDecipher","createDecipheriv","createSign","createVerify","createDiffieHellman","pbkdf2"],h=function(l){e[l]=function(){y("sorry,",l,"is not implemented yet")}};for(I in u)h(u[I],I)}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("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(n,i,e){(function(t,r,s,o,a,d,p,m,D){var v=n("./helpers");function P(y,I){y[I>>5]|=128<<I%32,y[14+(I+64>>>9<<4)]=I;for(var u=1732584193,h=-271733879,l=-1732584194,w=271733878,O=0;O<y.length;O+=16){var j=u,k=h,M=l,B=w,u=x(u,h,l,w,y[O+0],7,-680876936),w=x(w,u,h,l,y[O+1],12,-389564586),l=x(l,w,u,h,y[O+2],17,606105819),h=x(h,l,w,u,y[O+3],22,-1044525330);u=x(u,h,l,w,y[O+4],7,-176418897),w=x(w,u,h,l,y[O+5],12,1200080426),l=x(l,w,u,h,y[O+6],17,-1473231341),h=x(h,l,w,u,y[O+7],22,-45705983),u=x(u,h,l,w,y[O+8],7,1770035416),w=x(w,u,h,l,y[O+9],12,-1958414417),l=x(l,w,u,h,y[O+10],17,-42063),h=x(h,l,w,u,y[O+11],22,-1990404162),u=x(u,h,l,w,y[O+12],7,1804603682),w=x(w,u,h,l,y[O+13],12,-40341101),l=x(l,w,u,h,y[O+14],17,-1502002290),u=E(u,h=x(h,l,w,u,y[O+15],22,1236535329),l,w,y[O+1],5,-165796510),w=E(w,u,h,l,y[O+6],9,-1069501632),l=E(l,w,u,h,y[O+11],14,643717713),h=E(h,l,w,u,y[O+0],20,-373897302),u=E(u,h,l,w,y[O+5],5,-701558691),w=E(w,u,h,l,y[O+10],9,38016083),l=E(l,w,u,h,y[O+15],14,-660478335),h=E(h,l,w,u,y[O+4],20,-405537848),u=E(u,h,l,w,y[O+9],5,568446438),w=E(w,u,h,l,y[O+14],9,-1019803690),l=E(l,w,u,h,y[O+3],14,-187363961),h=E(h,l,w,u,y[O+8],20,1163531501),u=E(u,h,l,w,y[O+13],5,-1444681467),w=E(w,u,h,l,y[O+2],9,-51403784),l=E(l,w,u,h,y[O+7],14,1735328473),u=S(u,h=E(h,l,w,u,y[O+12],20,-1926607734),l,w,y[O+5],4,-378558),w=S(w,u,h,l,y[O+8],11,-2022574463),l=S(l,w,u,h,y[O+11],16,1839030562),h=S(h,l,w,u,y[O+14],23,-35309556),u=S(u,h,l,w,y[O+1],4,-1530992060),w=S(w,u,h,l,y[O+4],11,1272893353),l=S(l,w,u,h,y[O+7],16,-155497632),h=S(h,l,w,u,y[O+10],23,-1094730640),u=S(u,h,l,w,y[O+13],4,681279174),w=S(w,u,h,l,y[O+0],11,-358537222),l=S(l,w,u,h,y[O+3],16,-722521979),h=S(h,l,w,u,y[O+6],23,76029189),u=S(u,h,l,w,y[O+9],4,-640364487),w=S(w,u,h,l,y[O+12],11,-421815835),l=S(l,w,u,h,y[O+15],16,530742520),u=_(u,h=S(h,l,w,u,y[O+2],23,-995338651),l,w,y[O+0],6,-198630844),w=_(w,u,h,l,y[O+7],10,1126891415),l=_(l,w,u,h,y[O+14],15,-1416354905),h=_(h,l,w,u,y[O+5],21,-57434055),u=_(u,h,l,w,y[O+12],6,1700485571),w=_(w,u,h,l,y[O+3],10,-1894986606),l=_(l,w,u,h,y[O+10],15,-1051523),h=_(h,l,w,u,y[O+1],21,-2054922799),u=_(u,h,l,w,y[O+8],6,1873313359),w=_(w,u,h,l,y[O+15],10,-30611744),l=_(l,w,u,h,y[O+6],15,-1560198380),h=_(h,l,w,u,y[O+13],21,1309151649),u=_(u,h,l,w,y[O+4],6,-145523070),w=_(w,u,h,l,y[O+11],10,-1120210379),l=_(l,w,u,h,y[O+2],15,718787259),h=_(h,l,w,u,y[O+9],21,-343485551),u=F(u,j),h=F(h,k),l=F(l,M),w=F(w,B)}return Array(u,h,l,w)}function b(y,I,u,h,l,w){return F((I=F(F(I,y),F(h,w)))<<l|I>>>32-l,u)}function x(y,I,u,h,l,w,O){return b(I&u|~I&h,y,I,l,w,O)}function E(y,I,u,h,l,w,O){return b(I&h|u&~h,y,I,l,w,O)}function S(y,I,u,h,l,w,O){return b(I^u^h,y,I,l,w,O)}function _(y,I,u,h,l,w,O){return b(u^(I|~h),y,I,l,w,O)}function F(y,I){var u=(65535&y)+(65535&I);return(y>>16)+(I>>16)+(u>>16)<<16|65535&u}i.exports=function(y){return v.hash(y,P,16)}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("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(n,i,e){(function(t,r,s,o,a,d,p,m,D){var v;i.exports=v||function(P){for(var b,x=new Array(P),E=0;E<P;E++)!(3&E)&&(b=4294967296*Math.random()),x[E]=b>>>((3&E)<<3)&255;return x}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("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(n,i,e){(function(t,r,s,o,a,d,p,m,D){var v=n("./helpers");function P(E,S){E[S>>5]|=128<<24-S%32,E[15+(S+64>>9<<4)]=S;for(var _,F,y,I=Array(80),u=1732584193,h=-271733879,l=-1732584194,w=271733878,O=-1009589776,j=0;j<E.length;j+=16){for(var k=u,M=h,B=l,q=w,ne=O,Q=0;Q<80;Q++){I[Q]=Q<16?E[j+Q]:x(I[Q-3]^I[Q-8]^I[Q-14]^I[Q-16],1);var K=b(b(x(u,5),(K=h,F=l,y=w,(_=Q)<20?K&F|~K&y:!(_<40)&&_<60?K&F|K&y|F&y:K^F^y)),b(b(O,I[Q]),(_=Q)<20?1518500249:_<40?1859775393:_<60?-1894007588:-899497514)),O=w,w=l,l=x(h,30),h=u,u=K}u=b(u,k),h=b(h,M),l=b(l,B),w=b(w,q),O=b(O,ne)}return Array(u,h,l,w,O)}function b(E,S){var _=(65535&E)+(65535&S);return(E>>16)+(S>>16)+(_>>16)<<16|65535&_}function x(E,S){return E<<S|E>>>32-S}i.exports=function(E){return v.hash(E,P,20,!0)}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("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(n,i,e){(function(t,r,s,o,a,d,p,m,D){function v(S,_){var F=(65535&S)+(65535&_);return(S>>16)+(_>>16)+(F>>16)<<16|65535&F}function P(S,_){var F,y=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),I=new Array(1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225),u=new Array(64);S[_>>5]|=128<<24-_%32,S[15+(_+64>>9<<4)]=_;for(var h,l,w=0;w<S.length;w+=16){for(var O=I[0],j=I[1],k=I[2],M=I[3],B=I[4],q=I[5],ne=I[6],Q=I[7],K=0;K<64;K++)u[K]=K<16?S[K+w]:v(v(v((l=u[K-2],x(l,17)^x(l,19)^E(l,10)),u[K-7]),(l=u[K-15],x(l,7)^x(l,18)^E(l,3))),u[K-16]),F=v(v(v(v(Q,x(l=B,6)^x(l,11)^x(l,25)),B&q^~B&ne),y[K]),u[K]),h=v(x(h=O,2)^x(h,13)^x(h,22),O&j^O&k^j&k),Q=ne,ne=q,q=B,B=v(M,F),M=k,k=j,j=O,O=v(F,h);I[0]=v(O,I[0]),I[1]=v(j,I[1]),I[2]=v(k,I[2]),I[3]=v(M,I[3]),I[4]=v(B,I[4]),I[5]=v(q,I[5]),I[6]=v(ne,I[6]),I[7]=v(Q,I[7])}return I}var b=n("./helpers"),x=function(S,_){return S>>>_|S<<32-_},E=function(S,_){return S>>>_};i.exports=function(S){return b.hash(S,P,32,!0)}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("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(n,i,e){(function(t,r,s,o,a,d,p,m,D){e.read=function(v,P,b,x,w){var S,_,F=8*w-x-1,y=(1<<F)-1,I=y>>1,u=-7,h=b?w-1:0,l=b?-1:1,w=v[P+h];for(h+=l,S=w&(1<<-u)-1,w>>=-u,u+=F;0<u;S=256*S+v[P+h],h+=l,u-=8);for(_=S&(1<<-u)-1,S>>=-u,u+=x;0<u;_=256*_+v[P+h],h+=l,u-=8);if(S===0)S=1-I;else{if(S===y)return _?NaN:1/0*(w?-1:1);_+=Math.pow(2,x),S-=I}return(w?-1:1)*_*Math.pow(2,S-x)},e.write=function(v,P,b,x,E,O){var _,F,y=8*O-E-1,I=(1<<y)-1,u=I>>1,h=E===23?Math.pow(2,-24)-Math.pow(2,-77):0,l=x?0:O-1,w=x?1:-1,O=P<0||P===0&&1/P<0?1:0;for(P=Math.abs(P),isNaN(P)||P===1/0?(F=isNaN(P)?1:0,_=I):(_=Math.floor(Math.log(P)/Math.LN2),P*(x=Math.pow(2,-_))<1&&(_--,x*=2),2<=(P+=1<=_+u?h/x:h*Math.pow(2,1-u))*x&&(_++,x/=2),I<=_+u?(F=0,_=I):1<=_+u?(F=(P*x-1)*Math.pow(2,E),_+=u):(F=P*Math.pow(2,u-1)*Math.pow(2,E),_=0));8<=E;v[b+l]=255&F,l+=w,F/=256,E-=8);for(_=_<<E|F,y+=E;0<y;v[b+l]=255&_,l+=w,_/=256,y-=8);v[b+l-w]|=128*O}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("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(n,i,e){(function(t,r,s,o,a,d,p,m,D){var v,P,b;function x(){}(t=i.exports={}).nextTick=(P=typeof window<"u"&&window.setImmediate,b=typeof window<"u"&&window.postMessage&&window.addEventListener,P?function(E){return window.setImmediate(E)}:b?(v=[],window.addEventListener("message",function(E){var S=E.source;S!==window&&S!==null||E.data!=="process-tick"||(E.stopPropagation(),0<v.length&&v.shift()())},!0),function(E){v.push(E),window.postMessage("process-tick","*")}):function(E){setTimeout(E,0)}),t.title="browser",t.browser=!0,t.env={},t.argv=[],t.on=x,t.addListener=x,t.once=x,t.off=x,t.removeListener=x,t.removeAllListeners=x,t.emit=x,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,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("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 He={};or(He,{__addDisposableResource:()=>Is,__assign:()=>an,__asyncDelegator:()=>gs,__asyncGenerator:()=>ms,__asyncValues:()=>ys,__await:()=>ot,__awaiter:()=>ls,__classPrivateFieldGet:()=>xs,__classPrivateFieldIn:()=>Os,__classPrivateFieldSet:()=>Ss,__createBinding:()=>ln,__decorate:()=>os,__disposeResources:()=>_s,__esDecorate:()=>ca,__exportStar:()=>us,__extends:()=>rs,__generator:()=>ds,__importDefault:()=>vs,__importStar:()=>ws,__makeTemplateObject:()=>bs,__metadata:()=>cs,__param:()=>as,__propKey:()=>da,__read:()=>Ai,__rest:()=>ss,__runInitializers:()=>la,__setFunctionName:()=>ua,__spread:()=>fs,__spreadArray:()=>ps,__spreadArrays:()=>hs,__values:()=>cn,default:()=>pa});function rs(n,i){if(typeof i!="function"&&i!==null)throw new TypeError("Class extends value "+String(i)+" is not a constructor or null");Ci(n,i);function e(){this.constructor=n}n.prototype=i===null?Object.create(i):(e.prototype=i.prototype,new e)}function ss(n,i){var e={};for(var t in n)Object.prototype.hasOwnProperty.call(n,t)&&i.indexOf(t)<0&&(e[t]=n[t]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,t=Object.getOwnPropertySymbols(n);r<t.length;r++)i.indexOf(t[r])<0&&Object.prototype.propertyIsEnumerable.call(n,t[r])&&(e[t[r]]=n[t[r]]);return e}function os(n,i,e,t){var r=arguments.length,s=r<3?i:t===null?t=Object.getOwnPropertyDescriptor(i,e):t,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(n,i,e,t);else for(var a=n.length-1;a>=0;a--)(o=n[a])&&(s=(r<3?o(s):r>3?o(i,e,s):o(i,e))||s);return r>3&&s&&Object.defineProperty(i,e,s),s}function as(n,i){return function(e,t){i(e,t,n)}}function ca(n,i,e,t,r,s){function o(S){if(S!==void 0&&typeof S!="function")throw new TypeError("Function expected");return S}for(var a=t.kind,d=a==="getter"?"get":a==="setter"?"set":"value",p=!i&&n?t.static?n:n.prototype:null,m=i||(p?Object.getOwnPropertyDescriptor(p,t.name):{}),D,v=!1,P=e.length-1;P>=0;P--){var b={};for(var x in t)b[x]=x==="access"?{}:t[x];for(var x in t.access)b.access[x]=t.access[x];b.addInitializer=function(S){if(v)throw new TypeError("Cannot add initializers after decoration has completed");s.push(o(S||null))};var E=(0,e[P])(a==="accessor"?{get:m.get,set:m.set}:m[d],b);if(a==="accessor"){if(E===void 0)continue;if(E===null||typeof E!="object")throw new TypeError("Object expected");(D=o(E.get))&&(m.get=D),(D=o(E.set))&&(m.set=D),(D=o(E.init))&&r.unshift(D)}else(D=o(E))&&(a==="field"?r.unshift(D):m[d]=D)}p&&Object.defineProperty(p,t.name,m),v=!0}function la(n,i,e){for(var t=arguments.length>2,r=0;r<i.length;r++)e=t?i[r].call(n,e):i[r].call(n);return t?e:void 0}function da(n){return typeof n=="symbol"?n:"".concat(n)}function ua(n,i,e){return typeof i=="symbol"&&(i=i.description?"[".concat(i.description,"]"):""),Object.defineProperty(n,"name",{configurable:!0,value:e?"".concat(e," ",i):i})}function cs(n,i){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,i)}function ls(n,i,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(m){try{p(t.next(m))}catch(D){o(D)}}function d(m){try{p(t.throw(m))}catch(D){o(D)}}function p(m){m.done?s(m.value):r(m.value).then(a,d)}p((t=t.apply(n,i||[])).next())})}function ds(n,i){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(m){return d([p,m])}}function d(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=i.call(n,e)}catch(m){p=[6,m],r=0}finally{t=s=0}if(p[0]&5)throw p[1];return{value:p[0]?p[1]:void 0,done:!0}}}function us(n,i){for(var e in n)e!=="default"&&!Object.prototype.hasOwnProperty.call(i,e)&&ln(i,n,e)}function cn(n){var i=typeof Symbol=="function"&&Symbol.iterator,e=i&&n[i],t=0;if(e)return e.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&t>=n.length&&(n=void 0),{value:n&&n[t++],done:!n}}};throw new TypeError(i?"Object is not iterable.":"Symbol.iterator is not defined.")}function Ai(n,i){var e=typeof Symbol=="function"&&n[Symbol.iterator];if(!e)return n;var t=e.call(n),r,s=[],o;try{for(;(i===void 0||i-- >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 fs(){for(var n=[],i=0;i<arguments.length;i++)n=n.concat(Ai(arguments[i]));return n}function hs(){for(var n=0,i=0,e=arguments.length;i<e;i++)n+=arguments[i].length;for(var t=Array(n),r=0,i=0;i<e;i++)for(var s=arguments[i],o=0,a=s.length;o<a;o++,r++)t[r]=s[o];return t}function ps(n,i,e){if(e||arguments.length===2)for(var t=0,r=i.length,s;t<r;t++)(s||!(t in i))&&(s||(s=Array.prototype.slice.call(i,0,t)),s[t]=i[t]);return n.concat(s||Array.prototype.slice.call(i))}function ot(n){return this instanceof ot?(this.v=n,this):new ot(n)}function ms(n,i,e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=e.apply(n,i||[]),r,s=[];return r={},o("next"),o("throw"),o("return"),r[Symbol.asyncIterator]=function(){return this},r;function o(v){t[v]&&(r[v]=function(P){return new Promise(function(b,x){s.push([v,P,b,x])>1||a(v,P)})})}function a(v,P){try{d(t[v](P))}catch(b){D(s[0][3],b)}}function d(v){v.value instanceof ot?Promise.resolve(v.value.v).then(p,m):D(s[0][2],v)}function p(v){a("next",v)}function m(v){a("throw",v)}function D(v,P){v(P),s.shift(),s.length&&a(s[0][0],s[0][1])}}function gs(n){var i,e;return i={},t("next"),t("throw",function(r){throw r}),t("return"),i[Symbol.iterator]=function(){return this},i;function t(r,s){i[r]=n[r]?function(o){return(e=!e)?{value:ot(n[r](o)),done:!1}:s?s(o):o}:s}}function ys(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=n[Symbol.asyncIterator],e;return i?i.call(n):(n=typeof cn=="function"?cn(n):n[Symbol.iterator](),e={},t("next"),t("throw"),t("return"),e[Symbol.asyncIterator]=function(){return this},e);function t(s){e[s]=n[s]&&function(o){return new Promise(function(a,d){o=n[s](o),r(a,d,o.done,o.value)})}}function r(s,o,a,d){Promise.resolve(d).then(function(p){s({value:p,done:a})},o)}}function bs(n,i){return Object.defineProperty?Object.defineProperty(n,"raw",{value:i}):n.raw=i,n}function ws(n){if(n&&n.__esModule)return n;var i={};if(n!=null)for(var e in n)e!=="default"&&Object.prototype.hasOwnProperty.call(n,e)&&ln(i,n,e);return fa(i,n),i}function vs(n){return n&&n.__esModule?n:{default:n}}function xs(n,i,e,t){if(e==="a"&&!t)throw new TypeError("Private accessor was defined without a getter");if(typeof i=="function"?n!==i||!t:!i.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e==="m"?t:e==="a"?t.call(n):t?t.value:i.get(n)}function Ss(n,i,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 i=="function"?n!==i||!r:!i.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t==="a"?r.call(n,e):r?r.value=e:i.set(n,e),e}function Os(n,i){if(i===null||typeof i!="object"&&typeof i!="function")throw new TypeError("Cannot use 'in' operator on non-object");return typeof n=="function"?i===n:n.has(i)}function Is(n,i,e){if(i!=null){if(typeof i!="object"&&typeof i!="function")throw new TypeError("Object expected.");var t;if(e){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");t=i[Symbol.asyncDispose]}if(t===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");t=i[Symbol.dispose]}if(typeof t!="function")throw new TypeError("Object not disposable.");n.stack.push({value:i,dispose:t,async:e})}else e&&n.stack.push({async:!0});return i}function _s(n){function i(t){n.error=n.hasError?new ha(t,n.error,"An error was suppressed during disposal."):t,n.hasError=!0}function e(){for(;n.stack.length;){var t=n.stack.pop();try{var r=t.dispose&&t.dispose.call(t.value);if(t.async)return Promise.resolve(r).then(e,function(s){return i(s),e()})}catch(s){i(s)}}if(n.hasError)throw n.error}return e()}var Ci,an,ln,fa,ha,pa,We=fo(()=>{Ci=function(n,i){return Ci=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])},Ci(n,i)};an=function(){return an=Object.assign||function(i){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)&&(i[s]=e[s])}return i},an.apply(this,arguments)};ln=Object.create?function(n,i,e,t){t===void 0&&(t=e);var r=Object.getOwnPropertyDescriptor(i,e);(!r||("get"in r?!i.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return i[e]}}),Object.defineProperty(n,t,r)}:function(n,i,e,t){t===void 0&&(t=e),n[t]=i[e]};fa=Object.create?function(n,i){Object.defineProperty(n,"default",{enumerable:!0,value:i})}:function(n,i){n.default=i};ha=typeof SuppressedError=="function"?SuppressedError:function(n,i,e){var t=new Error(e);return t.name="SuppressedError",t.error=n,t.suppressed=i,t};pa={__extends:rs,__assign:an,__rest:ss,__decorate:os,__param:as,__metadata:cs,__awaiter:ls,__generator:ds,__createBinding:ln,__exportStar:us,__values:cn,__read:Ai,__spread:fs,__spreadArrays:hs,__spreadArray:ps,__await:ot,__asyncGenerator:ms,__asyncDelegator:gs,__asyncValues:ys,__makeTemplateObject:bs,__importStar:ws,__importDefault:vs,__classPrivateFieldGet:xs,__classPrivateFieldSet:Ss,__classPrivateFieldIn:Os,__addDisposableResource:Is,__disposeResources:_s}});var Ds=oe(Es=>{"use strict";Object.defineProperty(Es,"__esModule",{value:!0})});var Ti=oe(Ie=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.invokeEventHandlersAsync=Ie.invokeEventHandlers=Ie.eventHandlerSafeInvokeAsync=Ie.eventHandlerSafeInvoke=void 0;var Ps=(We(),Xe(He));function Cs(n,i,e){try{return n(i,e),{succeeded:!0}}catch(t){return{error:t,succeeded:!1}}}Ie.eventHandlerSafeInvoke=Cs;function Ri(n,i,e){return(0,Ps.__awaiter)(this,void 0,void 0,function*(){try{return yield n(i,e),{succeeded:!0}}catch(t){return{error:t,succeeded:!1}}})}Ie.eventHandlerSafeInvokeAsync=Ri;function ma(n,i,e,t){for(let r of n){let{succeeded:s,error:o}=Cs(r,i,e);if(!s&&t?.swallowExceptions!==!0)throw o}}Ie.invokeEventHandlers=ma;function ga(n,i,e,t){return(0,Ps.__awaiter)(this,void 0,void 0,function*(){if(t?.parallelize===!1)for(let r of n){let{succeeded:s,error:o}=yield Ri(r,i,e);if(!s&&t?.swallowExceptions!==!0)throw o}else{let r=[];for(let s of n)r.push(Ri(s,i,e).then(({succeeded:o,error:a})=>{if(!o&&t?.swallowExceptions!==!0)throw a}));yield Promise.all(r)}})}Ie.invokeEventHandlersAsync=ga});var Ts=oe(dn=>{"use strict";Object.defineProperty(dn,"__esModule",{value:!0});dn.TypedEvent=void 0;var ya=(We(),Xe(He)),As=Ti(),Rs={swallowExceptions:!1,parallelize:!0},Fi=class{constructor(){this._handlers=[]}attach(i){this._handlers.push(i)}detach(i){this.tryRemoveHandler(i)}invoke(i,e,t=Rs){(0,As.invokeEventHandlers)(this._handlers,i,e,t)}invokeAsync(i,e,t=Rs){return(0,ya.__awaiter)(this,void 0,void 0,function*(){yield(0,As.invokeEventHandlersAsync)(this._handlers,i,e,t)})}tryRemoveHandler(i){let e=this._handlers.findIndex(t=>t===i);e>=0&&this._handlers.splice(e,1)}};dn.TypedEvent=Fi});var ki=oe(Bi=>{"use strict";Object.defineProperty(Bi,"__esModule",{value:!0});var ba=(We(),Xe(He));(0,ba.__exportStar)(Ts(),Bi)});var Fs=oe(un=>{"use strict";Object.defineProperty(un,"__esModule",{value:!0});un.FinalizationRegistryMissingError=void 0;var ji=class extends Error{};un.FinalizationRegistryMissingError=ji});var Li=oe(fn=>{"use strict";Object.defineProperty(fn,"__esModule",{value:!0});fn.WeakHandlerHolder=void 0;var wa=Fs(),Mi=class{constructor(i){this._refs=[];try{this._finalizationRegistry=new FinalizationRegistry(i)}catch(e){throw e.name==="FinalizationRegistry"?new wa.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(i,e){let t=new WeakRef(e);return this._finalizationRegistry.register(e,{eventSource:i,handlerRef:t},t),this._refs.push(t),t}releaseWeakHandler(i){let t=this._refs.find(r=>r?.deref()===i)||new WeakRef(i);return this._finalizationRegistry.unregister(t),t}unregisterRef(i){this._finalizationRegistry.unregister(i)}};fn.WeakHandlerHolder=Mi});var Bs=oe(hn=>{"use strict";Object.defineProperty(hn,"__esModule",{value:!0});hn.WeakEvent=void 0;var Vi=(We(),Xe(He)),va=ki(),xa=Li(),Ui=Ti(),Sa={swallowExceptions:!1,parallelize:!0},Ni=class{constructor(){this._handlers=[],this._handlerFinalizedEvent=new va.TypedEvent,this.handlerFinalizedEvent=this._handlerFinalizedEvent,this._refHolder=new xa.WeakHandlerHolder(i=>{this.onHandlerFinalizer(i)})}invoke(i,e,t){for(let r of this._handlers){let s=r?.deref();if(s){let{succeeded:o,error:a}=(0,Ui.eventHandlerSafeInvoke)(s,i,e);if(!o&&t?.swallowExceptions!==!0)throw a}else this.releaseHandler(r)}}invokeAsync(i,e,t=Sa){return(0,Vi.__awaiter)(this,void 0,void 0,function*(){t?.parallelize===!1?yield this.sequentialInvokeAsync(i,e,t):yield this.parallelInvokeAsync(i,e,t)})}sequentialInvokeAsync(i,e,t){return(0,Vi.__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,Ui.eventHandlerSafeInvokeAsync)(s,i,e);if(!o&&t.swallowExceptions!==!0)throw a}else this.releaseHandler(r)}})}parallelInvokeAsync(i,e,t){return(0,Vi.__awaiter)(this,void 0,void 0,function*(){let r=[];for(let s of this._handlers){let o=s?.deref();o?r.push((0,Ui.eventHandlerSafeInvokeAsync)(o,i,e).then(({succeeded:a,error:d})=>{if(!a&&t.swallowExceptions!==!0)throw d})):this.releaseHandler(s)}yield Promise.all(r)})}attach(i){this._handlers.push(this._refHolder.getWeakHandler(this,i))}detach(i){let e=this._refHolder.releaseWeakHandler(i);this.tryRemoveHandlerRef(e)}onHandlerFinalizer(i){this.tryRemoveHandlerRef(i?.handlerRef),this._handlerFinalizedEvent.invokeAsync(this,i,{swallowExceptions:!0})}tryRemoveHandlerRef(i){let e=this._handlers.findIndex(t=>t===i);e>=0&&this._handlers.splice(e,1)}releaseHandler(i){this._refHolder.unregisterRef(i),this.tryRemoveHandlerRef(i)}};hn.WeakEvent=Ni});var js=oe(pn=>{"use strict";Object.defineProperty(pn,"__esModule",{value:!0});var ks=(We(),Xe(He));(0,ks.__exportStar)(Li(),pn);(0,ks.__exportStar)(Bs(),pn)});var Ms=oe(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});var zi=(We(),Xe(He));(0,zi.__exportStar)(Ds(),Dt);(0,zi.__exportStar)(ki(),Dt);(0,zi.__exportStar)(js(),Dt)});var tr={};or(tr,{Client:()=>ut,ClientDescriptor:()=>Wn,Entity:()=>de,EntityFile:()=>ve,ServerSync:()=>lt,Storage:()=>ut,StorageDescriptor:()=>Wn,UndoHistory:()=>rt,authorization:()=>ic,cliSync:()=>rc,collection:()=>vi,createDefaultMigration:()=>xi,createMigration:()=>Si,id:()=>nc,migrate:()=>en,schema:()=>It});var Sr=Te(ze(),1),Vt=4,gt=36;function wr(n){return n.toString(gt).padStart(Vt,"0")}function wo(n){return n.toString().padStart(6,"0")}var Bt=class{constructor(){this.latest={time:Date.now(),counter:0,node:vo()},this.zeroCounter=0,this.now=i=>(this.latest=xr(this.latest),this.get(i,this.latest)),this.OLD_now=i=>(this.latest=xr(this.latest),wo(i)+So(this.latest)),this.timerState=()=>this.latest,this.update=i=>{let e=i.slice(Vt);this.latest=xo(this.latest,Or(e))},this.get=(i,e)=>wr(i)+vr(e),this.zero=i=>wr(i)+vr({time:0,counter:this.zeroCounter++,node:this.latest.node}),this.getWallClockTime=ri}},kt=class extends Error{constructor(...i){super(),this.type="ClockDriftError",this.message=["maximum clock drift exceeded"].concat(i).join(" ")}},jt=class extends Error{constructor(){super(),this.type="OverflowError",this.message="timestamp counter overflow"}},ti=4,ni=7,Mt=60*1e3,mt=9;function vo(){return Sr.default.slug().padStart(ni,"0").slice(0,ni)}function vr(n){let i=new Date(n.time).getTime().toString(gt).padStart(mt,"0"),e=n.counter.toString(gt).padStart(ti,"0"),t=n.node.padStart(ni,"0");return`${i}${e}${t}`}function xr(n){let i=Date.now(),e=Math.max(n.time,i),t=n.time===e?n.counter+1:0;if(e-i>Mt)throw new kt(e,i,Mt);if(t>65535)throw new jt;return{time:e,counter:t,node:n.node}}function xo(n,i){let e=Date.now(),t=Math.max(e,Math.max(n.time,i.time)),r=Math.max(n.counter,i.counter),s;if(n.time===t&&i.time===t?s=r+1:n.time===t?s=n.counter+1:i.time===t?s=i.counter+1:s=0,t-e>Mt)throw new kt(t,e,Mt);if(s>65535)throw new jt;return{time:t,counter:s,node:n.node}}function Or(n){let i=n.slice(0,mt),e=n.slice(mt,mt+ti),t=n.slice(mt+ti),r=parseInt(i,gt),s=parseInt(e,gt);if(isNaN(r)||isNaN(s))throw new Error("invalid clock format");return{time:r,counter:s,node:t}}function So(n){let i=new Date(n.time).toISOString(),e=n.counter.toString(16).toUpperCase().padStart(4,"0"),t=n.node.padStart(16,"0");return`${i}-${e}-${t}`}function Lt(n){return parseInt(n.slice(0,Vt),36)}function ii(n,i){return Lt(n)-Lt(i)}function ri(n){return Or(n.slice(Vt)).time}var Ut,Oo=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(Oo)}var Ir=/^(?:[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 Io(n){return typeof n=="string"&&Ir.test(n)}var _r=Io;var te=[];for(Nt=0;Nt<256;++Nt)te.push((Nt+256).toString(16).substr(1));var Nt;function _o(n){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=(te[n[i+0]]+te[n[i+1]]+te[n[i+2]]+te[n[i+3]]+"-"+te[n[i+4]]+te[n[i+5]]+"-"+te[n[i+6]]+te[n[i+7]]+"-"+te[n[i+8]]+te[n[i+9]]+"-"+te[n[i+10]]+te[n[i+11]]+te[n[i+12]]+te[n[i+13]]+te[n[i+14]]+te[n[i+15]]).toLowerCase();if(!_r(e))throw TypeError("Stringified UUID is invalid");return e}var Er=_o;function Eo(n,i,e){n=n||{};var t=n.random||(n.rng||si)();if(t[6]=t[6]&15|64,t[8]=t[8]&63|128,i){e=e||0;for(var r=0;r<16;++r)i[e+r]=t[r];return i}return Er(t)}var yt=Eo;function W(n){return Se(n)||me(n)}function Ze(n,i){return n===i?!0:!(!W(n)||!W(i)||n["@@type"]!==i["@@type"]||n.id!==i.id)}var Do="/",bt=":",ai=new WeakMap;function ie(n){let i=fe(n);return N(!!i,`Object ${JSON.stringify(n)} does not have an OID assigned to it`),i}function fe(n){if(V(n))return ai.get(n)}function z(n,i){return N(V(n),`Only objects can be assigned OIDs, received ${JSON.stringify(n)}`),ci(n)&&Kt(n),ai.set(n,i),n}function ci(n){return!!fe(n)}function Kt(n){return ai.delete(n),n}function li(n,i,e){if(ci(n))return ie(n);{let t=ge(i,e);return z(n,t),t}}function Dr(n,i,e){if(ci(n)){let t=ie(n);if(Ee(t,i))return ie(n);{let r=ge(i,e);return z(n,r),r}}else{let t=ge(i,e);return z(n,t),t}}var oi={".":"&dot;","/":"&slash;",":":"&colon;"};function Pr(n){return n.replace(/[/]/g,oi["/"]).replace(/[:]/g,oi[":"]).replace(/[.]/g,oi["."])}function Cr(n){return n.replace(/&slash;/g,"/").replace(/&colon;/g,":").replace(/&dot;/g,".")}function Y(n,i,e){let t=Pr(n)+Do+Pr(i);return e&&(t+=bt+e),t}function ge(n,i=Po){let{collection:e,id:t}=ce(n);return Y(e,t,i())}function ce(n){let[i,e,...t]=n.split("/");t.length&&(console.error(`OID ${n} has more than 3 segments. Attempting to parse it anyway.`),e+="/"+t.join("/"));let[r,s]=e.split(bt),o;return r.includes(".")?o=r.slice(0,r.indexOf(".")):o=r,{collection:Cr(i),id:Cr(o),subId:s}}function et(n,i){let e=ie(n);if(Array.isArray(n)){let t;for(let r=0;r<n.length;r++)t=n[r],V(t)&&!W(t)&&(Dr(t,e,i),et(t,i))}else if(V(n)&&!W(n))for(let t of Object.keys(n))V(n[t])&&!W(n[t])&&(Dr(n[t],e,i),et(n[t],i))}function zt(n){if(Kt(n),Array.isArray(n))for(let i=0;i<n.length;i++)zt(n[i]);else if(V(n))for(let i of Object.keys(n))zt(n[i])}function Po(){return yt().slice(0,8)}function ae(n){return{"@@type":"ref",id:n}}function $t(n,i=new Map){if(Array.isArray(n)){let e=ie(n),t=z([],e);for(let r=0;r<n.length;r++){let s=n[r];if(V(s)){if(Se(s))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(me(s)){t[r]=s;continue}else{let o=ie(s);t[r]=ae(o),$t(s,i)}}else t[r]=s}i.set(e,t)}else if(V(n)&&!W(n)){let e=ie(n),t=z({},e);for(let r of Object.keys(n)){let s=n[r];if(V(s)){if(Se(s))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(me(s))t[r]=s;else{let o=ie(s);t[r]=ae(o),$t(s,i)}}else t[r]=s}i.set(e,t)}else W(n);return i}function $(n){return n.split(".")[0].split(bt)[0]}function Ar(n){let i=$(n),e=ge(i,()=>"\uFFFF");return[`${i}${bt}`,e]}function Ee(n,i){return $(n)===$(i)}function qt(n){return!n.includes(bt)}var Br=Te(Fr(),1);function Co(n,i){return typeof i!="object"||i===null||Array.isArray(i)?i:Object.fromEntries(Object.entries(i).sort(([e],[t])=>e<t?-1:e>t?1:0))}function wt(n){return JSON.stringify(n,Co)}function le(n,i=!0){if(!i&&typeof structuredClone=="function")return structuredClone(n);if(V(n)||Array.isArray(n)){let e=fe(n),t;if(Array.isArray(n))t=n.map(r=>le(r,i));else{t={};for(let[r,s]of Object.entries(n))t[r]=le(s,i)}return i&&e&&z(t,e),t}return n}function $e(n){return(0,Br.default)(n)}function V(n){return n&&typeof n=="object"}function kr(n){for(var i=[],e=[n],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"&&i.indexOf(r)===-1){i.push(r);for(var s in r)e.push(r[s])}}return t}function N(n,i="assertion failed"){if(!n)throw new Error(i)}function Qt(n=16){return yt().replace("-","").slice(0,n)}function jr(n,i){for(let e=n.length-1;e>=0;e--)if(i(n[e]))return e;return-1}function Mr(n,i){let e;return function(...t){let r=this;clearTimeout(e),e=setTimeout(()=>n.apply(r,t),i)}}function Lr(n,i){let e=0,t;return function(...r){let s=this,o=Date.now();o-e>=i?(e=o,n.apply(s,r),clearTimeout(t)):(clearTimeout(t),t=setTimeout(()=>{e=o,n.apply(s,r)},i))}}function Vr(){}function me(n){return n&&n["@@type"]==="file"}function vt(n){return{"@@type":"file",id:n}}function tt(n){return typeof File<"u"&&n instanceof File||typeof Blob<"u"&&n instanceof Blob}function Ht(n){return n&&V(n)&&typeof n.id=="string"&&typeof n.remote=="boolean"&&typeof n.name=="string"&&typeof n.type=="string"}var nt="__@@oid_do_not_use",De="@@id";function Ao(n){if(V(n))return n[De]||n[nt]}function Ro(n){return V(n)&&(delete n[nt],delete n[De]),n}function To(n){let i=Ao(n);i&&z(n,i)}function xt(n){if(To(n),Ro(n),Array.isArray(n))for(let i=0;i<n.length;i++)xt(n[i]);else if(V(n))for(let i of Object.keys(n))xt(n[i])}function Fo(n){let{collection:i,id:e,subId:t}=ce(n);return Y(i,e,t)}var Bo=/"\w+\/[^"]+?(\.[^"]+)+\:[\S]+?"/g;function ko(n){return n.replaceAll(Bo,i=>{let e=i.slice(1,i.length-1);return`"${Fo(e)}"`})}function di(n){return JSON.parse(ko(JSON.stringify(n)))}function Ur(n){let i=$(n);return[`${i}.`,`${i}.\uFFFF`]}function ui(n){return n===De||n===nt}function Se(n){return n&&typeof n=="object"&&n["@@type"]==="ref"}function fi(n){return V(n)&&!W(n)}function jo(n,i){return n===i?!0:W(n)&&W(i)?Ze(n,i):!1}function St(n,i,e,t,r=[],s){let o=s?.authz,a=ie(n);function d(p,m,D,v){if(!fi(m))jo(m,D)||(v?r.push(Be({oid:a,timestamp:e(),data:{op:"list-set",index:p,value:m}},o)):r.push(Be({oid:a,timestamp:e(),data:{op:"set",name:p,value:m}},o)));else{let P=fe(D),b=fe(m);b&&!Ee(a,b)?(m=le(m,!1),b=ge(a,t),z(m,b)):s?.mergeUnknownObjects?!b&&P?(z(m,P),b=P):b=li(m,a,t):b=li(m,a,t),N(!!b,"Error: no value OID was resolved during diff. This is a bug in Verdant."),N(Ee(a,b),`Error: value OID ${b} is not related to parent OID ${a}. This is a bug in Verdant.`),D===void 0||b!==P?(Ke(m,b,e,t,r),r.push(Be({oid:a,timestamp:e(),data:{op:"set",name:p,value:ae(b)}},o)),P!==void 0&&r.push(Be({oid:P,timestamp:e(),data:{op:"delete"}},o))):St(D,m,e,t,r,s)}}if(Array.isArray(n)&&Array.isArray(i)){for(let m=0;m<i.length;m++){let D=i[m],v=n[m];d(m,D,v,!0)}let p=n.length-i.length;if(p>0){for(let m=i.length;m<n.length;m++){let D=n[m],v=fe(D);v&&r.push(Be({oid:v,timestamp:e(),data:{op:"delete"}},o))}r.push(Be({oid:a,timestamp:e(),data:{op:"list-delete",index:i.length,count:p}},o))}}else{if(Array.isArray(n)||Array.isArray(i))throw new Error("Cannot diff an array with an object");if(fi(n)&&fi(i)){let p=new Set(Object.keys(n));for(let[m,D]of Object.entries(i)){if(D===void 0&&s?.defaultUndefined||(p.delete(m),ui(m)))continue;let v=n[m];d(m,D,v,!1)}if(!s?.defaultUndefined)for(let m of p)ui(m)||r.push(Be({oid:a,timestamp:e(),data:{op:"remove",name:m}},o))}}return r}function Ke(n,i,e,t,r=[],s){z(n,i),et(n,t);let o=$t(n);for(let a of o.keys()){let d=o.get(a),p={oid:a,timestamp:e(),data:{op:"initialize",value:Kt(d)}};r.push(Be(p,s?.authz))}return r}function Be(n,i){return i&&(n.authz=i),n}function Ot(n){let i={};for(let e of n)e.oid in i?i[e.oid].push(e):i[e.oid]=[e];return i}function zr(n){let i={};for(let e of n){let t=$(e.oid);t in i?i[t].push(e):i[t]=[e]}return i}function $r(n){let i={};for(let e of n){let t=$(e.oid);t in i?i[t].push(e):i[t]=[e]}return i}function Fe(n){return Array.isArray(n)?!0:(console.error(`Cannot apply list patch; expected array, received ${JSON.stringify(n)}. This suggests your data is changing from a list to an object over time. (OID: ${fe(n)})`),!1)}function ke(n,i,e){if(n==null&&i.op!=="initialize")return n;let t=n,r,s;function o(a){e&&W(a)&&e.push(a)}switch(i.op){case"set":o(t[i.name]),t[i.name]=i.value;break;case"remove":o(t[i.name]),delete t[i.name];break;case"list-set":Fe(n)&&(o(n[i.index]),n[i.index]=i.value);break;case"list-push":Fe(n)&&n.push(i.value);break;case"list-delete":Fe(n)&&(o(n[i.index]),n.splice(i.index,i.count));break;case"list-move-by-index":Fe(n)&&(s=n.splice(i.from,1),n.splice(i.to,0,s[0]));break;case"list-remove":if(Fe(n))do{let a=i.value;i.only==="last"?Se(a)?r=jr(n,d=>d.id===a.id):r=n.lastIndexOf(a):Se(a)?r=n.findIndex(d=>d.id===a.id):r=n.indexOf(a),r!==-1&&(o(n[r]),n.splice(r,1))}while(!i.only&&r!==-1);break;case"list-add":Fe(n)&&(n.some(d=>Se(d)&&Se(i.value)?d.id===i.value.id:d===i.value)||n.push(i.value));break;case"list-move-by-ref":Fe(n)&&(r=n.findIndex(a=>Ze(a,i.value)),s=n.splice(r,1),n.splice(i.index,0,s[0]));break;case"list-insert":if(Fe(n)){if(!i.value&&!i.values)throw new Error(`Cannot apply list insert patch; expected value or values, received ${JSON.stringify(i)}`);i.value?n.splice(i.index,0,i.value):n.splice(i.index,0,...i.values)}break;case"delete":Array.isArray(n)?n.forEach(o):V(n)&&Object.values(n||{}).forEach(o);return;case"initialize":return le(i.value);case"touch":return n;default:throw new Error(`Unsupported patch operation: ${i.op}`)}return n}function Wt(n,i,e=[]){if(Array.isArray(n))for(let t=0;t<n.length;t++){let r=n[t];n[t]=Nr(r,i,e),V(n[t])&&Wt(n[t],i,e)}else if(!me(n)){if(V(n)){N(fe(n),`Object ${JSON.stringify(n)} must have an oid`);for(let t of Object.keys(n))n[t]=Nr(n[t],i,e),V(n[t])&&Wt(n[t],i,e)}}return e}function Nr(n,i,e){if(Se(n)){e.push(n.id);let t=i.get(n.id);return N(!!t,`No value was found in object map for ${n.id}`),z(t,n.id)}else return n}function Kr(n){return n.data.op==="set"?n.data.name:!1}function qr(n,i){return i.has(!0)?!0:n.data.op==="set"||n.data.op==="remove"?i.has(n.data.name):!1}function Jt(n){return{oid:n.oid,timestamp:n.timestamp,data:n.data,authz:n.authz}}var je;(function(n){n[n.Realtime=0]="Realtime",n[n.Push=1]="Push",n[n.PassiveRealtime=2]="PassiveRealtime",n[n.PassivePush=3]="PassivePush",n[n.ReadOnlyPull=4]="ReadOnlyPull",n[n.ReadOnlyRealtime=5]="ReadOnlyRealtime"})(je||(je={}));var Qr=Te(ze(),1),Mo=n=>Object.assign({type:"object"},n),Lo=n=>Object.assign({type:"array"},n),Vo=n=>Object.assign({type:"string"},n),Uo=n=>Object.assign({type:"number"},n),No=n=>Object.assign({type:"boolean"},n),zo=n=>Object.assign({type:"any"},n),$o=n=>Object.assign({type:"map"},n),Ko=n=>Object.assign({type:"file"},n),qo=()=>({type:"string",default:Qr.default}),Hr={object:Mo,array:Lo,string:Vo,number:Uo,boolean:No,any:zo,map:$o,file:Ko,id:qo};var Gr=Te(ze(),1);function hi(n){return n.equals!==void 0}function pi(n){return n.gte!==void 0||n.lte!==void 0||n.gt!==void 0||n.lt!==void 0}function Qo(n){return!!n.match}function mi(n){return n.startsWith!==void 0}function Wr(n){return!pi(n)&&!hi(n)&&!Qo(n)&&!mi(n)&&n.order}function ye(n){return n.type==="any"?!0:n.type==="map"?!1:n.nullable}function Pe(n){return n?n.type==="map"||n.type==="array"?!0:n.type==="file"?!1:n.default!==void 0:!1}function yi(n){if(!(!n||!Pe(n)))return n.type==="file"?ye(n)?null:void 0:n.type==="map"?{}:n.type==="array"?ye(n)?null:[]:n.type==="object"?ye(n)?null:void 0:typeof n.default=="function"?n.default():n.default}function Ce(n,i){for(let[e,t]of Object.entries(n.fields)){let r=bi(t);(r!==void 0&&i[e]===void 0||!ye(t)&&i[e]===null)&&(i[e]=r),i[e]&&qe(i[e],t)}return i}function qe(n,i){if(n==null)return n;if(i.type==="object")for(let[e,t]of Object.entries(i.properties)){if(n[e]===void 0){let r=bi(t);r!==void 0&&(n[e]=r)}qe(n[e],t)}else if(i.type==="array")for(let e of n)qe(e,i.items);else if(i.type==="map")for(let[e,t]of Object.entries(n))e===De||e===nt||qe(t,i.values)}function bi(n){if(n.type==="string"||n.type==="number"||n.type==="boolean"||n.type==="any"){if(n.default&&typeof n.default=="function")return n.default();if(n.default!==void 0)return JSON.parse(JSON.stringify(n.default))}if(n.type==="array")return[];if(n.type==="map")return{};if(n.type!=="any"&&n.nullable)return null;if(n.type==="object"&&n.default){let i=typeof n.default=="function"?n.default():JSON.parse(JSON.stringify(n.default));for(let[e,t]of Object.entries(n.properties))i[e]===void 0&&(i[e]=bi(t));return i}}function wi(n,i){for(let[e,t]of Object.entries(i))e===De||e===nt||(n.fields[e]?gi(t,n.fields[e]):delete i[e]);return i}function gi(n,i){if(V(n)&&i.type==="object")for(let[e,t]of Object.entries(n))i.properties[e]?gi(t,i.properties[e]):delete n[e];else if(Array.isArray(n)&&i.type==="array")for(let e of n)gi(e,i.items)}function Jr(n,i){for(let[e,t]of Object.entries(i))if(e!==De){if(!n[e])return{type:"invalid-key",fieldPath:[e],message:`Invalid field "${e}"`};if(t){let r=Ae({field:n[e],value:t,fieldPath:[e]});if(r)return r}}}function Ae({field:n,value:i,fieldPath:e=[],depth:t,requireDefaults:r}){if(!(t!==void 0&&t<=0)&&!(ye(n)&&i===null)){if(i===null&&(r||!Pe(n)))return{type:"no-default",fieldPath:e,message:`Invalid null value for field ${Oe(e)}`};if(n.type==="object"){if(!V(i))return{type:"invalid-type",fieldPath:e,message:`Expected object ${n.nullable?"or null ":""}for field ${Oe(e)}, got ${i}`};for(let[s,o]of Object.entries(n.properties))s!==De&&i[s]&&Ae({field:o,value:i[s],fieldPath:[...e,s],depth:t!==void 0?t-1:void 0});for(let s of Object.keys(i))if(!n.properties[s])return{type:"invalid-key",fieldPath:[...e,s],message:`Invalid unexpected field "${s}" on value ${Oe(e)}`}}else if(n.type==="array"){if(!Array.isArray(i))return i===null&&n.nullable?void 0:{type:"invalid-value",fieldPath:e,message:`Expected array ${n.nullable?"or null ":""}for field ${Oe(e)}, got ${i}`};for(let s of i)Ae({field:n.items,value:s,fieldPath:[...e,"[]"],depth:t!==void 0?t-1:void 0})}else if(n.type==="map"){if(!V(i))return{type:"invalid-type",fieldPath:e,message:`Expected map for field ${Oe(e)}, got ${i}`};for(let[s,o]of Object.entries(i))Ae({field:n.values,value:o,fieldPath:[...e,s],depth:t!==void 0?t-1:void 0})}else if(n.type==="string"){if(typeof i!="string")return{type:"invalid-type",fieldPath:e,message:`Expected string ${n.nullable?"or null ":""}for field ${Oe(e)}, got ${i}`};if(n.options&&!n.options.includes(i))return{type:"invalid-value",fieldPath:e,message:`Expected one of ${n.options.join(", ")} for field ${Oe(e)}, got ${i}`}}else if(n.type==="boolean"){if(typeof i!="boolean")return{type:"invalid-type",fieldPath:e,message:`Expected boolean ${n.nullable?"or null ":""}for field ${Oe(e)}, got ${i}`}}else if(n.type==="number"){if(typeof i!="number")return{type:"invalid-type",fieldPath:e,message:`Expected number ${n.nullable?"or null ":""}for field ${Oe(e)}, got ${i}`}}else if(n.type==="file"&&!tt(i)&&!Ht(i))return{type:"invalid-type",fieldPath:e,message:`Expected file ${n.nullable?"or null ":""}for field ${Oe(e)}, got ${i}`}}}function Oe(n){return n.length===0?"root":n.join(".")}function Yr(n,i){let e={};for(let[t,r]of Object.entries(i))n[t]&&(e[t]=Yt({field:n[t],value:r,fieldPath:[t]}));return e}function Yt({field:n,value:i,fieldPath:e=[],depth:t}){let r=Ae({field:n,value:i,fieldPath:e,depth:t,requireDefaults:!0});if(r)throw new Error(`Validation error: ${r.message}`);if(n.type==="object"){if(!V(i))return i;let s={};for(let[o,a]of Object.entries(n.properties))s[o]=Yt({field:a,value:i[o],fieldPath:[...e,o],depth:t!==void 0?t-1:void 0});return s}else{if(n.type==="array")return Array.isArray(i)?i.map(s=>Yt({field:n.items,value:s,fieldPath:[...e,"[]"],depth:t!==void 0?t-1:void 0})):i;if(n.type==="map"){if(!V(i))return i;let s={};for(let[o,a]of Object.entries(i))s[o]=Yt({field:n.values,value:a,fieldPath:[...e,o],depth:t!==void 0?t-1:void 0});return s}else return i}}function Me(n,i){var e;return n.type==="object"?n.properties[i]:n.type==="array"?n.items:n.type==="map"?n.values:n.type==="any"?n:"type"in n?null:(e=n[i])!==null&&e!==void 0?e:null}var Ho=function(n,i){var e={};for(var t in n)Object.prototype.hasOwnProperty.call(n,t)&&i.indexOf(t)<0&&(e[t]=n[t]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,t=Object.getOwnPropertySymbols(n);r<t.length;r++)i.indexOf(t[r])<0&&Object.prototype.propertyIsEnumerable.call(n,t[r])&&(e[t[r]]=n[t[r]]);return e};function vi(n){var{synthetics:i,indexes:e}=n,t=Ho(n,["synthetics","indexes"]);let r=Object.assign(Object.assign({},i),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 It(n){return n}It.collection=vi;It.fields=Hr;It.generated={id:Gr.default};var Gt="\uFFFFFE",Wo="\0",Jo="\uFFFFFF";function we(...n){let i=Yo(n);return i.length===1?i[0]:i}function Le(...n){return n.join(Gt)+`${Jo}`}function Re(...n){return n.join(Gt)+`${Gt}${Wo}`}function Yo(n){let i=[[]];for(let e of n)if(Array.isArray(e)){let t=[];for(let r of i)for(let s of e)t.push(r.concat(s));i=t}else for(let t of i)t.push(`${e}`);return Array.from(new Set(i.map(e=>e.join(Gt))))}function Go(n){return!!n.field}function Xo(n,i){let e={};for(let[t,r]of Object.entries(n.indexes||{})){let s=r;Go(s)?e[t]=be(i[s.field]):e[t]=be(s.compute(i))}return e}function Zo(n,i){return Object.entries(n.compounds||{}).reduce((e,[t,r])=>(e[t]=we(...r.of.map(s=>i[s])),e),{})}function ea(n,i){return Object.entries(n.fields).reduce((e,[t,r])=>("indexed"in r&&(e[t]=be(i[t])),e),{})}function Xt(n,i){let e=Object.assign(Object.assign({[n.primaryKey]:i[n.primaryKey]},ea(n,i)),Xo(n,i));return Object.assign(e,Zo(n,Object.assign(Object.assign({},i),e))),e["@@@snapshot"]=JSON.stringify(i),e}var ta="null";function be(n){if(n===null)return ta;if(typeof n=="string"||typeof n=="number")return n;if(typeof n=="boolean"||n===null)return`${n}`;if(n===void 0)return"undefined";if(Array.isArray(n))return n.map(be);throw new Error(`Unsupported index value: ${n}`)}var Xr={version:0,collections:{}};function en(n,i,e){let t=typeof i=="function",r=t?Xr:n,s=t?n:i,o=t?i:e,a=Object.keys(s.collections).filter(x=>r.collections[x]&&wt(r.collections[x])!==wt(s.collections[x])),d=Object.keys(r.collections).filter(x=>!s.collections[x]),p=Object.keys(s.collections).filter(x=>!r.collections[x]),m=new Set;for(let x of a){let E=r.collections[x].fields,S=s.collections[x].fields;Object.keys(S).some(_=>{var F,y;return!(!((F=E[_])===null||F===void 0)&&F.default)&&((y=S[_])===null||y===void 0?void 0:y.default)})&&m.add(x),Object.keys(E).some(_=>!S[_])&&m.add(x)}let D={},v={};for(let x of[...a,...p]){let E=Zt(r.collections[x]),S=Zt(s.collections[x]),_=S.filter(y=>!E.find(I=>I.name===y.name)),F=E.filter(y=>!S.find(I=>I.name===y.name));_.length>0&&(D[x]=_,a.includes(x)&&m.add(x)),F.length>0&&(v[x]=F,a.includes(x)&&m.add(x))}let P=(x,E)=>Ce(s.collections[x],E),b=x=>E=>{let S=s.collections[x];return Ce(S,wi(S,E))};return{version:s.version,migrate:async x=>{let E=[];if(await o({migrate:async(S,_)=>{let F=b(S),y=async I=>{let u=await _(I);return z(u,ie(I)),F(u)};await x.migrate(S,y),E.push(S),m.delete(S)},identity:S=>S,withDefaults:P,info:{changedCollections:a,addedCollections:p,removedCollections:d},queries:x.queries,mutations:x.mutations}),s.version>1){x.log("debug","auto-migrating collections with new defaults",m);for(let _ of m)await x.migrate(_,b(_)),E.push(_);let S=a.filter(_=>!E.includes(_));S.length>0&&console.error(`Unmigrated changed collections from version ${r.version} to version ${s.version}:`,S)}},removedCollections:d,addedIndexes:D,removedIndexes:v,allCollections:Object.keys(s.collections),changedCollections:a,addedCollections:p,oldCollections:Object.keys(r.collections),oldSchema:r,newSchema:s}}function Zt(n){return n?[...Object.keys(n.indexes||{}).map(i=>({name:i,multiEntry:["array","string[]","number[]","boolean[]"].includes(n.indexes[i].type),synthetic:!0,compound:!1})),...Object.keys(n.compounds||{}).map(i=>({name:i,multiEntry:n.compounds[i].of.some(e=>(n.fields[e]||n.indexes[e]).type==="array"),synthetic:!1,compound:!0}))]:[]}function xi(n,i){return en(i?n:{version:0,collections:{}},i||n,async({migrate:t,info:r})=>{if((i||n).version!==1)for(let s of r.changedCollections)await t(s,o=>o)})}function Si(n,i,e){let t=typeof i=="function"||i===void 0,r=t?Xr:n,s=t?n:i,o=t?i:e;N(r,"Invalid arguments to createMigration"),N(s,"Invalid arguments to createMigration");let{changedCollections:a,addedCollections:d,removedCollections:p,addedIndexes:m,removedIndexes:D,autoMigratedCollections:v,autoMigration:P}=na(r,s);return{version:s.version,migrate:async b=>{let x=[];if(await o?.({migrate:async(S,_)=>{let F=P(S),y=async I=>{let u=await _(I);z(u,ie(I));let h=F(u),l=Jr(s.collections[S].fields,h);return h};await b.migrate(S,y),x.push(S),v.delete(S)},info:{changedCollections:a,addedCollections:d,removedCollections:p},queries:b.queries,mutations:b.mutations}),s.version>1){b.log("debug","auto-migrating collections with new defaults",v);for(let _ of v)await b.migrate(_,P(_)),x.push(_);for(let _ of p)await b.deleteCollection(_);let S=a.filter(_=>!x.includes(_));S.length>0&&console.error(`Unmigrated changed collections from version ${r.version} to version ${s.version}:`,S)}},removedCollections:p,addedIndexes:m,removedIndexes:D,allCollections:Object.keys(s.collections),changedCollections:a,addedCollections:d,oldCollections:Object.keys(r.collections),oldSchema:r,newSchema:s}}function na(n,i){let e=Object.keys(i.collections).filter(m=>n.collections[m]&&wt(n.collections[m])!==wt(i.collections[m])),t=Object.keys(n.collections).filter(m=>!i.collections[m]),r=Object.keys(i.collections).filter(m=>!n.collections[m]),s=new Set;for(let m of e){let D=n.collections[m].fields,v=i.collections[m].fields;Object.keys(v).some(P=>!Pe(D[P])&&Pe(v[P]))&&s.add(m),Object.keys(D).some(P=>!v[P])&&s.add(m)}let o={},a={};for(let m of[...e,...r]){let D=Zt(n.collections[m]),v=Zt(i.collections[m]),P=v.filter(x=>!D.find(E=>E.name===x.name)),b=D.filter(x=>!v.find(E=>E.name===x.name));P.length>0&&(o[m]=P,e.includes(m)&&s.add(m)),b.length>0&&(a[m]=b,e.includes(m)&&s.add(m))}return{changedCollections:e,addedCollections:r,removedCollections:t,addedIndexes:o,removedIndexes:a,autoMigratedCollections:s,withDefaults:(m,D)=>Ce(i.collections[m],D),autoMigration:m=>D=>{let v=i.collections[m];return Ce(v,wi(v,D))}}}var Oi={};var tn=class{constructor(i,e){this.getNow=i,this.createSubId=e,this.isPrimitive=t=>!V(t)||W(t),this.createDiff=(t,r,s={})=>St(t,r,this.getNow,this.createSubId,[],s),this.createInitialize=(t,r,s)=>Ke(t,r,this.getNow,this.createSubId,void 0,s?{authz:s}:void 0),this.createSet=(t,r,s)=>{if(this.isPrimitive(s))return[{oid:t,timestamp:this.getNow(),data:{op:"set",name:r,value:s}}];{let o=ge(t,this.createSubId);return[...Ke(s,o,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"set",value:ae(o),name:r}}]}},this.createRemove=(t,r)=>[{oid:t,timestamp:this.getNow(),data:{op:"remove",name:r}}],this.createListSet=(t,r,s)=>{if(this.isPrimitive(s))return[{oid:t,timestamp:this.getNow(),data:{op:"list-set",index:r,value:s}}];{let o=ge(t,this.createSubId);return[...Ke(s,o,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-set",index:r,value:ae(o)}}]}},this.createListPush=(t,r)=>{if(this.isPrimitive(r))return[{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:r}}];{let s=ge(t,this.createSubId);return[...Ke(r,s,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:ae(s)}}]}},this.createListAdd=(t,r)=>this.isPrimitive(r)?[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:r}}]:[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:ae(r)}}],this.createListInsert=(t,r,s)=>{if(this.isPrimitive(s))return[{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:s,index:r}}];{let o=ge(t,this.createSubId);return[...Ke(s,o,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:ae(o),index:r}}]}},this.createListRemove=(t,r,s)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-remove",value:r,only:s}}],this.createListDelete=(t,r,s=1)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-delete",index:r,count:s}}],this.createListMoveByRef=(t,r,s)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-move-by-ref",value:r,index:s}}],this.createListMoveByIndex=(t,r,s)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-move-by-index",from:r,to:s}}],this.createDelete=t=>[{oid:t,timestamp:this.getNow(),data:{op:"delete"}}],this.createDeleteAll=(t,r)=>t.map(s=>({oid:s,timestamp:this.getNow(),data:{op:"delete"},authz:r}))}};var U=class{constructor(i){this._onAllUnsubscribed=i,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=Qt(),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}};function Zr(n,i,e,t){if(i==null)return[{oid:n,timestamp:t(),data:{op:"delete"}}];let r=le(i),s=[];for(let o of e){let a=ia(n,r,o,t);s.unshift(...a),ke(r,o.data)}return s}function ia(n,i,e,t){let r=e.data;switch(r.op){case"set":case"remove":return[{oid:n,timestamp:t(),data:{op:"set",name:r.name,value:i[r.name]}}];case"list-insert":return[{oid:n,timestamp:t(),data:{op:"list-delete",index:r.index,count:1}}];case"list-delete":return[{oid:n,timestamp:t(),data:{op:"list-insert",index:r.index,values:i.slice(r.index,r.count)}}];case"list-move-by-ref":return[{oid:n,timestamp:t(),data:{op:"list-move-by-ref",value:r.value,index:i.indexOf(r.value)}}];case"list-move-by-index":return[{oid:n,timestamp:t(),data:{op:"list-move-by-index",from:r.to,to:r.from}}];case"delete":return[{oid:n,timestamp:t(),data:{op:"initialize",value:i}}];case"list-push":return[{oid:n,timestamp:t(),data:{op:"list-remove",value:r.value,only:"last"}}];case"list-remove":if(r.only==="last"){let s=i.lastIndexOf(r.value);return[{oid:n,timestamp:t(),data:{op:"list-insert",index:s,values:[r.value]}}]}else if(r.only==="first"){let s=i.indexOf(r.value);return[{oid:n,timestamp:t(),data:{op:"list-insert",index:s,values:[r.value]}}]}else{let s=[],o=i.indexOf(r.value);for(;o!==-1;)s.push(o),o=i.indexOf(r.value,o+1);return s.map(a=>({oid:n,timestamp:t(),data:{op:"list-insert",index:a,value:r.value}}))}case"list-add":return[{oid:n,timestamp:t(),data:{op:"list-remove",value:r.value,only:"last"}}];case"list-set":return[{oid:n,timestamp:t(),data:{op:"list-set",index:r.index,value:i[r.index]}}];case"initialize":return[{oid:n,timestamp:t(),data:{op:"delete"}}];case"touch":return[];default:throw new Error(`Cannot undo operation type: ${r.op}`)}}var it=class{constructor(i){this.flusher=i,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:i,userData:e,items:t,max:r,timeout:s}){let o=this.batches.get(i);return o||(o=new Ii({max:r||null,startedAt:Date.now(),userData:e,timeout:s||null,flusher:this.flusher,key:i}),this.batches.set(i,o)),o.update({items:t,max:r,timeout:s,userData:e}),o}},Ii=class{constructor({max:i,startedAt:e,timeout:t,userData:r,flusher:s,key:o}){this.items=[],this.update=({items:a,max:d,timeout:p,userData:m})=>{this.items.push(...a),d!==void 0&&(this.max=d),p!==void 0&&(this.timeout=p),m&&(this.userData=m);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=i,this.startedAt=e,this.timeout=t,this.userData=r,this.flusher=s,this.key=o}};function es(n,i){let e,t;return(...r)=>{let s=i();return e&&e.length===s.length&&e.every((o,a)=>o===s[a])||(e=[...s],t=n(...r)),t}}var _t;(function(n){n[n.InvalidRequest=4e3]="InvalidRequest",n[n.BodyRequired=4001]="BodyRequired",n[n.NoToken=4010]="NoToken",n[n.InvalidToken=4011]="InvalidToken",n[n.TokenExpired=4012]="TokenExpired",n[n.Forbidden=4030]="Forbidden",n[n.NotFound=4040]="NotFound",n[n.Unexpected=5e3]="Unexpected",n[n.ConfigurationError=5010]="ConfigurationError",n[n.NoFileStorage=5011]="NoFileStorage",n[n.MigrationPathNotFound=7001]="MigrationPathNotFound",n[n.ImportFailed=7002]="ImportFailed",n[n.Offline=7003]="Offline"})(_t||(_t={}));var Z=class extends Error{constructor(i,e,t){super(t??`Verdant error: ${i}`,{cause:e}),this.code=i,this.toResponse=()=>JSON.stringify({code:this.code})}get httpStatus(){let i=Math.floor(this.code/10);return i<600?i:500}};Z.Code=_t;function ts(n){return typeof n=="object"&&"code"in n&&typeof n.code=="number"}function ra(n){return typeof Buffer<"u"?Buffer.from(n).toString("base64"):btoa(n)}function sa(n){return typeof Buffer<"u"?Buffer.from(n,"base64").toString():atob(n)}var Qe={onlyUser:n=>ra(`u:${n}:*`),onlyMe:()=>Qe.onlyUser(_i),decode:n=>{let e=sa(n).split(":");if(e.length!==3)throw new Error("Invalid authz string");return{scope:e[0],subject:e[1],action:e[2]}}},_i="$$_originator_$$";function ns(n,i){let{operations:e,baselines:t}=n;if(e)for(let r of e)r.authz&&Qe.decode(r.authz).subject===_i&&(r.authz=Qe.onlyUser(i));if(t)for(let r of t)r.authz&&Qe.decode(r.authz).subject===_i&&(r.authz=Qe.onlyUser(i))}var rt=class extends U{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}};var nn=class{constructor(i,e){this.schema=i;this.entities=e;this.getOid=(i,e)=>{let t=this.schema.collections[i].primaryKey,r=e[t];return N(r,`Document must have a primary key: ${t.toString()} (got: ${JSON.stringify(e)})`),Y(i,r)};this.addDefaults=(i,e)=>{let t=this.schema.collections[i];return Ce(t,e)};this.validate=(i,e)=>{let t=this.schema.collections[i];return Yr(t.fields,e)};this.create=async(i,e,t={})=>{let r=t,s=this.addDefaults(i,e),o=this.validate(i,s),a=this.getOid(i,o);if(t.access){let d=this.schema.collections[i];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(i,e,t={})=>{let r=Y(i,e);return this.entities.delete(r,t)};this.deleteAll=async(i,e={})=>this.entities.deleteAll(i.map(([t,r])=>Y(t,r)),e);this.deleteAllFromCollection=async(i,e,t={})=>this.entities.deleteAll(e.map(r=>Y(i,r)),t);this.clone=async(i,e,t={})=>{if(!qt(e.uid))throw new Error("Cannot clone non-root documents");let r=e.getSnapshot(),s=this.schema.collections[i];if(delete r[s.primaryKey],!s.fields[s.primaryKey].default){if(!t.primaryKey)throw new Error(`Error cloning document from collection ${i}: 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(i,r,t)}}};var Ei=Te(ze(),1);function oa(n){return{id:(0,Ei.default)(),file:n,url:void 0,remote:!1,name:n.name,type:n.type}}function st(n,i){if(typeof window<"u"&&tt(n)){let e=oa(n);return i(e),vt(e.id)}if(Ht(n)){let e={...n,id:(0,Ei.default)()};return i(e),vt(e.id)}if(Array.isArray(n)){for(let e=0;e<n.length;e++)n[e]=st(n[e],i);return n}if(typeof n=="object"){for(let e in n)n[e]=st(n[e],i);return n}return n}var rn=class{constructor({initial:i}={}){this.cache=new Map;this.get=i=>{if(this.cache.has(i.oid))return this.cache.get(i.oid);let e=new de(i);return this.cache.set(i.oid,e),e};this.has=i=>this.cache.has(i);this.getCached=i=>this.cache.get(i);if(i)for(let e of i)this.cache.set(e.oid,e)}};function is(n,i,e){let t={previousValue:n.get(i),isLocal:!1};function r(s){if(n.deleted)return;let o=n.get(i);o!==this.previousValue&&(this.isLocal=s.isLocal,e(o,this),this.previousValue=o)}return n.subscribe("change",r.bind(t))}var de=class n extends U{constructor({oid:e,schema:t,entityFamily:r,parent:s,ctx:o,metadataFamily:a,readonlyKeys:d,files:p,storeEvents:m,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 n){let t=e.view;return t==null}return e==null};this.getFieldSchema=e=>{let t=Me(this.schema,e);return N(t,`No schema for key ${e}`),t};this.validate=es(()=>(this.validationError=Ae({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 n||s instanceof ve?e(s):s);return z(r,this.oid),r}else{let r=Object.entries(t).reduce((s,[o,a])=>(a instanceof n||a instanceof ve?s[o]=e(a):s[o]=a,s),{});return z(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 n&&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=Me(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)=>is(this,e,r);this.get=e=>{Di(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=Me(this.schema,e);if(!s)throw new Error(`No schema for key ${String(e)} in ${JSON.stringify(this.schema)}`);if(W(r))if(me(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:Ae({field:s,value:r,fieldPath:[...this.fieldPath,e],depth:1,requireDefaults:!0})?Pe(s)?yi(s):ye(s)?null:void 0:r};this.getOrSet=(e,t)=>{Di(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=le(e,!1));let r=Me(this.schema,t);if(r){qe(e,r);let s=Ae({field:r,value:e,fieldPath:[...this.fieldPath,t]});if(s)throw new Error(`Validation error: ${s.message}`,{cause:s})}return st(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 n)return ae(e.oid);if(e instanceof ve)return vt(e.id);if(typeof e=="object"){let t=fe(e);if(!t||!this.entityFamily.has(t))throw new Error(`Cannot move object ${JSON.stringify(e)} which does not exist in this list`);return ae(t)}else return e};this.set=(e,t,r)=>{Di(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)aa(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}={})=>{if(!t&&this.schema.type!=="any"&&this.schema.type!=="map")throw new Error('Cannot use .update without merge if the field has a strict schema type. merge: false is only available on "any" or "map" types.');let o={};z(o,this.oid);for(let[a,d]of Object.entries(e)){if(this.readonlyKeys.includes(a))throw new Error(`Cannot set readonly key ${a.toString()}`);if(d===void 0&&!s)continue;let p=Me(this.schema,a);p&&qe(d,p),o[a]=this.processInputValue(d,a)}this.addPendingOperations(this.patchCreator.createDiff(this.getSnapshot(),o,{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(W(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 W(t)?this.view.some(r=>{if(W(r))return Ze(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=d||[],this.ctx=o,this.files=p,this.schema=t,this.entityFamily=r||new rn({initial:[this]}),this.metadataFamily=a,this.storeEvents=m,this.parent=s,this._deleteSelf=D,this.parent||(m.add.attach(this.onAdd),m.replace.attach(this.onReplace),m.resetAll.attach(this.onResetAll))}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&&!ye(this.schema)||this.schema.type==="array"&&!Array.isArray(e)||(this.schema.type==="object"||this.schema.type==="map")&&!V(e))return Pe(this.schema)?yi(this.schema):null;if(this.cachedView=this.isList?[]:{},z(this.cachedView,this.oid),Array.isArray(e)){let r=Me(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)&&!ye(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=Me(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)&&!ye(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 n){let r=t.deepUpdatedAt;r&&(!e||r>e)&&(e=r)}}):this.values().forEach(t=>{if(t instanceof n){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 Di(n){if(typeof n=="symbol")throw new Error("Symbol keys aren't supported")}function aa(n){if(typeof n!="number")throw new Error("Only number keys are supported in list entities")}var ee=class{constructor(){this._disposes=[];this.disposed=!1;this.dispose=async()=>{this.disposed=!0,await Promise.all(this._disposes.map(i=>i())),this._disposes=[]};this.compose=i=>this.addDispose(i.dispose.bind(i));this.addDispose=i=>{this._disposes.push(i)}}};var Pi=class{constructor({oid:i,ctx:e,confirmedOperations:t,pendingOperations:r,baseline:s}){this.baseline=null;this.confirmedOperations=[];this.pendingOperations=[];this.computeView=(i=!1)=>{let e=le(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=i?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 p=o.latestTimestamp??s.latestTimestamp??t,m=p?ri(p):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:m,latestTimestamp:p,authz:r}};this.addBaseline=i=>{if(!(this.baseline&&this.baseline.timestamp>=i.timestamp))for(this.baseline=i;this.confirmedOperations[0]?.timestamp<i.timestamp;)this.confirmedOperations.shift()};this.addConfirmedOperations=i=>{let e=0;for(let t of i){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=i=>{this.pendingOperations.push(i)};this.discardPendingOperation=i=>{this.pendingOperations=this.pendingOperations.filter(e=>e.timestamp!==i.timestamp)};this.applyOperations=(i,e,t,r,s)=>{let o,a,d=this.ctx.time.now;for(let p of t)if(!(s&&p.timestamp<=s)){if(ii(p.timestamp,d)>0){o=p.timestamp;continue}p.data.op==="delete"?e=!0:(i=ke(i,p.data),p.data.op==="initialize"&&(e=!1,p.authz&&(a=p.authz))),(!r||p.timestamp>r)&&(r=p.timestamp)}return{view:i,latestTimestamp:r??null,deleted:e,futureSeen:o,authz:a}};N(i,"oid is required"),this.ctx=e,this.oid=i,t&&(this.confirmedOperations=t),r&&(this.pendingOperations=r),s&&(this.baseline=s)}},sn=class{constructor({ctx:i,onPendingOperations:e,rootOid:t}){this.entities=new Map;this.get=i=>(N(i,"oid is required"),this.entities.has(i)||this.entities.set(i,new Pi({oid:i,ctx:this.ctx})),this.entities.get(i));this.getAllOids=()=>Array.from(this.entities.keys());this.addConfirmedData=({baselines:i=[],operations:e={},isLocal:t=!1})=>{let r={};for(let s of i){if(!Ee(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(!Ee(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=i=>{let e={};for(let t of i)this.get(t.oid).addPendingOperation(t),e[t.oid]??={oid:t.oid,isLocal:!0};return this.onPendingOperations(i),Object.values(e)};this.replaceAllData=({operations:i={},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(!Ee(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(i)){if(!Ee(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=i=>{this.entities.get(i.oid)?.discardPendingOperation(i)};this.ctx=i,this.rootOid=t,this.onPendingOperations=e}};var Et="@@default",on=class{constructor({batchTimeout:i=200,ctx:e,entities:t}){this.currentBatchKey=Et;this.flushOperations=async(i,e,t)=>{if(!i.length)return;this.ctx.log("debug","Flushing",i.length,"operations from batch",e,"to storage / sync");let r=[],s={};for(let o=i.length-1;o>=0;o--){let a=i[o],d=s[a.oid];if(d&&qr(a,d)){this.entities.discardPendingOperation(a);continue}let p=Kr(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(i,e)=>{if(i.length){if(e.undoable){let t=await this.createUndo({ops:i,source:e.source});t&&this.ctx.undoHistory.addUndo(t)}await this.entities.addData({operations:i,baselines:[],isLocal:!0})}};this.addOperations=i=>{i.length&&(this.batcher.add({key:this.currentBatchKey,items:i}),this.ctx.log("debug","added",i.length,"ops to batch",this.currentBatchKey,", size = ",this.batcher.getSize(this.currentBatchKey)))};this.batch=({undoable:i=!0,batchName:e=Qt(),max:t=null,timeout:r=this.defaultBatchTimeout}={})=>{let s=this.batcher.add({key:e,max:t,timeout:r,items:[],userData:{undoable:i}}),o={run:a=>(this.currentBatchKey=e,a(),this.currentBatchKey=Et,o),commit:async()=>(await this.batcher.flush(Et),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 i=>{let e=await this.getInverseOperations(i);return e.length?async()=>{let t=await this.createUndo({ops:e,source:i.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:i,source:e})=>{let t=Ot(i),r=[],s=()=>this.ctx.time.now;return await Promise.all(Object.entries(t).map(async([o,a])=>{let p=(e??await this.entities.hydrate($(o)))?.__getViewData__(o,"confirmed");if(!p){this.ctx.log("warn","could not find entity",o,"for undo operation",i);return}let m=Zr(o,p.view,a,s);r.unshift(...m)})),r};this.ctx=e,this.entities=t,this.defaultBatchTimeout=i,this.batcher=new it(this.flushOperations),this.batcher.add({key:Et,items:[],max:100,timeout:i,userData:{undoable:!0}})}get isDefaultBatch(){return this.currentBatchKey===Et}};var mn=Te(Ms(),1);var gn=class extends ee{constructor({ctx:e,files:t}){super();this.events={add:new mn.WeakEvent,replace:new mn.WeakEvent,resetAll:new mn.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.queries.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.queries.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(m=>$(m.oid)).concat(r.map(m=>$(m.oid))))),o=$r(t),a=zr(r);this.ctx.log("debug","Applying data to live entities");for(let m of s){let D=o[m],v=a[m]??[],P=Ot(v),b=e.reset?this.events.replace:this.events.add,x=this.pendingEntityPromises.get(m);x?(this.ctx.log("debug","Waiting for ongoing entity hydration",m),x.then(()=>{b.invoke(this,{oid:m,baselines:D,operations:P,isLocal:!1})})):(this.ctx.log("debug","Applying data to entity",m),b.invoke(this,{oid:m,baselines:D,operations:P,isLocal:!1}))}let d={abort:this.abortDataQueueController.signal};await this.ctx.meta.insertData(e,d);let p=await Promise.all(s.map(async m=>await this.hydrate(m,d)??{oid:m,getSnapshot(){return null}}));try{await this.ctx.queries.saveEntities(p,d)}catch(m){this.disposed?this.ctx.log("warn","Error saving entities to queryable storage - EntityStore is disposed",m):this.ctx.log("error","Error saving entities to queryable storage",m)}};this.hydrate=async(e,t)=>{if(!qt(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}=ce(t);zt(e);let a=st(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 p=this.ctx.patchCreator.createInitialize(a,t);s&&p.forEach(D=>{D.authz=s}),await this.batcher.commitOperations(p,{undoable:!!r,source:d});let m=Ot(p);return this.events.add.invoke(this,{operations:m,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),N(e.every(o=>o===$(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 p of d)p.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=>{let{collection:t}=ce(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 sn({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=$(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 on({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}};var at=Symbol("entity-file-update"),yn=Symbol("entity-file-mark-failed"),Oa,Ia,ve=class extends U{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.unsubscribes=[];this[Oa]=e=>{this.ctx.log("debug","EntityFile updated",this.id,e),this._loading=!1,this._failed=!1,this._fileData=e,e.file&&(this._objectUrl&&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[Ia]=()=>{this._failed=!0,this._loading=!1,this.emit("change")};this.onUploaded=()=>{this._fileData&&(this._fileData.remote=!0,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{Oa=at,Ia=yn}get downloadRemote(){return this._downloadRemote}get isFile(){return!0}get isUploaded(){return 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:!1,type:this.type??"",file:this._fileData?.file}}};var bn=class{constructor({sync:i,context:e}){this.cache=new Map;this.add=async(i,e)=>{if(this.cache.has(i.id))this.cache.get(i.id)[at](i);else{let t=new ve(i.id,{ctx:this.context});t[at](i),this.cache.set(i.id,t)}await this.context.files.add(i,e)};this.get=(i,e)=>{if(this.cache.has(i))return this.cache.get(i);let t=new ve(i,e);return this.cache.set(i,t),this.load(t),t};this.load=async i=>{let e=await this.context.files.get(i.id);if(e)i[at](e);else try{if(this.sync.status!=="active"){this.context.log("info","Sync is not active, waiting for online to load file",i.id,i.name);let r=this.sync.subscribe("onlineChange",s=>{s&&(r(),this.load(i))});return}let t=await this.sync.getFile(i.id);t.success?(i[at](t.data),await this.context.files.add(t.data,{downloadRemote:i.downloadRemote})):(this.context.log("error","Failed to load file",t),i[yn]())}catch(t){this.context.log("error","Failed to load file",t),i[yn]()}};this.sync=i,this.context=e}};var $i=typeof window<"u"?window.indexedDB:void 0;function Je(n){return n instanceof Error&&n.name==="AbortError"}function Ye(n){return new Promise((i,e)=>{n.onsuccess=()=>{i(n.result)},n.onerror=()=>{n.error&&Je(n.error)?i(n.result):e(n.error)}})}function Ve(n,i){return new Promise((e,t)=>{let r=n.transaction([i],"readonly"),o=r.objectStore(i).openCursor(),a=0,d=0;o.onsuccess=function(p){let m=o.result;m&&(a++,d=d+kr(m.value),m.continue())},o.onerror=function(p){o.error&&Je(o.error)?e({count:a,size:d}):t(o.error)},r.oncomplete=function(p){e({count:a,size:d})},r.onabort=function(p){t(p)},r.onerror=function(p){t(p)}})}async function Ls(n){let e=Array.from(n.objectStoreNames).map(async r=>{let s=await Ve(n,r);return{[r]:s}});return(await Promise.all(e)).reduce((r,s)=>({...r,...s}),{})}function Ki(n,i){let e=n.transaction(i,"readonly"),t=i.map(r=>{let s=e.objectStore(r);return Ye(s.getAll())});return Promise.all(t)}async function xe(n){n.close(),await new Promise((i,e)=>{i()})}async function wn(n,i=$i){let e=i.deleteDatabase([n,"meta"].join("_")),t=i.deleteDatabase([n,"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 qi(n,i=window.indexedDB){return Ye(i.deleteDatabase(n))}function Vs(n,i,e,t,r){let s=n.transaction(i,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}function _a(n){let i=Array.from(n.objectStoreNames),e=n.transaction(i,"readwrite");for(let t of i)e.objectStore(t).clear();return new Promise((t,r)=>{e.oncomplete=()=>t(),e.onerror=()=>r(e.error)})}async function Us(n,i){await _a(i);let e=await Ki(n,Array.from(n.objectStoreNames)),t=i.transaction(Array.from(i.objectStoreNames),"readwrite");for(let r=0;r<e.length;r++){let s=t.objectStore(n.objectStoreNames[r]);for(let o of e[r])s.add(o)}return new Promise((r,s)=>{t.oncomplete=()=>r(),t.onerror=()=>s(t.error)})}function Ns(n,i,e=window.indexedDB){return new Promise((t,r)=>{let s=e.open(n,i);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!==i&&(a.close(),r(new Error(`Migration error: database version changed unexpectedly when reading current data. Expected ${i}, got ${a.version}`)))}})}function vn(n){return[n,"meta"].join("_")}function Qi(n){return[n,"collections"].join("_")}function zs(n){return n.name?.split("_")[0]}function Ea(n){return n!==null}function Hi(n){return Array.isArray(n)?n.map(Hi).filter(Ea):n instanceof de&&n.deleted?null:n}function Ue(n,i){return!n&&!i||n&&i&&$e(n)===$e(i)}var Wi=Symbol("ON_ALL_UNSUBSCRIBED"),ue=Symbol("UPDATE"),Da,he=class extends ee{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 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[Da]=e=>{this._allUnsubscribedHandler=e};this._rawValue=e,this._value=e,this.isListQuery=Array.isArray(e),this._events=new U(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{Da=Wi}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 xn=class extends he{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=Y(r.collection,e),this.hydrate=t}};var Pa,Sn=class extends he{constructor({index:e,hydrate:t,...r}){super({initial:null,...r});this.run=async()=>{let e=await this.context.queries.findOneOid({collection:this.collection,index:this.index});this.setValue(e?await this.hydrate(e):null)};this[Pa]=e=>{Ue(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=t}static{Pa=ue}};var Ca,On=class extends he{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.queries.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[Ca]=e=>{Ue(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=t,this._pageSize=r,this._page=s}static{Ca=ue}get pageSize(){return this._pageSize}get page(){return this._page}get hasNextPage(){return this._hasNextPage}get hasPreviousPage(){return this._page>0}};var Aa,In=class extends he{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.queries.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.queries.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[Aa]=e=>{Ue(this.index,e)||(this.index=e,this.execute())};this.index=r,this.hydrate=e,this._pageSize=t}static{Aa=ue}get pageSize(){return this._pageSize}get hasMore(){return this._hasNextPage}};var Ra,_n=class extends he{constructor({index:e,hydrate:t,...r}){super({initial:[],...r});this.run=async()=>{let{result:e}=await this.context.queries.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[Ra]=e=>{Ue(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=t}static{Ra=ue}};var En=class{constructor({collection:i,cache:e,entities:t,context:r,documentManager:s}){this.serializeIndex=i=>i?$e(i):"";this.get=i=>{let e=`get:${this.collection}:${i}`;return this.cache.getOrSet(e,()=>new xn({id:i,collection:this.collection,hydrate:this.hydrate,context:this.context,key:e}))};this.findOne=({index:i,key:e}={})=>{let t=e||`findOne:${this.collection}:${this.serializeIndex(i)}`;return this.cache.getOrSet(t,()=>new Sn({index:i,collection:this.collection,hydrate:this.hydrate,context:this.context,key:t}),r=>{r[ue](i)})};this.findAll=({index:i,key:e}={})=>{let t=e||`findAll:${this.collection}:${this.serializeIndex(i)}`;return this.cache.getOrSet(t,()=>new _n({index:i,collection:this.collection,hydrate:this.hydrate,context:this.context,key:t}),r=>{r[ue](i)})};this.findPage=({index:i,pageSize:e,page:t,key:r})=>{let s=r||`findPage:${this.collection}:${this.serializeIndex(i)}:${e}`;return this.cache.getOrSet(s,()=>new On({index:i,collection:this.collection,hydrate:this.hydrate,context:this.context,key:s,pageSize:e,page:t}),o=>{o[ue](i)})};this.findAllInfinite=({index:i,pageSize:e,key:t})=>{let r=t||`findAllInfinite:${this.collection}:${this.serializeIndex(i)}:${e}`;return this.cache.getOrSet(r,()=>new In({index:i,collection:this.collection,hydrate:this.hydrate,context:this.context,key:r,pageSize:e}),s=>{s[ue](i)})};this.cache=e,this.collection=i,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 Dn=class extends ee{constructor({evictionTime:e=5*1e3,context:t}){super();this._cache=new Map;this.onQueryUnsubscribed=e=>{setTimeout(()=>{e.subscribed||this._cache.get(e.key)===e&&this._cache.delete(e.key)},this._evictionTime)};this.dropAll=()=>{this.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(e){return this._cache.get(e)||null}set(e){return this._cache.set(e.key,e),e[Wi](this.onQueryUnsubscribed),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()))}};var Ji=Symbol("handleMessage"),Ta,Pt=class extends U{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[Ta]=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=Oi,this.self.id="",this.self.replicaId="",s.meta.getLocalReplica().then(o=>{this.self.replicaId=o.id}),this._updateBatcher=new it(this.flushPresenceUpdates),this._updateBatch=this._updateBatcher.add({max:25,timeout:t,items:[],key:"default"})}static{Ta=Ji}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 Pn=class extends ee{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),this.ctx.internalEvents.emit(`fileUploaded:${e.id}`)}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 fetch(s+`/${e.id}`,{method:"POST",body:a,credentials:"include",headers:{Authorization:`Bearer ${o}`}});if(d.ok)return this.ctx.log("info","File upload successful"),{success:!0};{let p=await d.text();return this.ctx.log("error","File upload failed",d.status,p),d.status<500||t.current>=t.max?{success:!1,error:`Failed to upload file: ${d.status} ${p}`}:(await new Promise(m=>setTimeout(m,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(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 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 ct=class extends U{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 Cn=class extends U{constructor({endpointProvider:e,presence:t,interval:r=15*1e3,fetch:s=window.fetch.bind(window),ctx:o}){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();ts(o)&&o.code===_t.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=Lr(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=o,this.presence=t,this.endpointProvider=e,this.fetch=s,this.heartbeat=new ct({interval:r}),this.heartbeat.subscribe("beat",this.onHeartbeat),this.heartbeat.subscribe("missed",this.onHeartbeatMissed)}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 Yi(n){this.message=n}Yi.prototype=new Error,Yi.prototype.name="InvalidCharacterError";var $s=typeof window<"u"&&window.atob&&window.atob.bind(window)||function(n){var i=String(n).replace(/=+$/,"");if(i.length%4==1)throw new Yi("'atob' failed: The string to be decoded is not correctly encoded.");for(var e,t,r=0,s=0,o="";t=i.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 Fa(n){var i=n.replace(/-/g,"+").replace(/_/g,"/");switch(i.length%4){case 0:break;case 2:i+="==";break;case 3:i+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent($s(e).replace(/(.)/g,function(t,r){var s=r.charCodeAt(0).toString(16).toUpperCase();return s.length<2&&(s="0"+s),"%"+s}))}(i)}catch{return $s(i)}}function An(n){this.message=n}function Ba(n,i){if(typeof n!="string")throw new An("Invalid token specified");var e=(i=i||{}).header===!0?0:1;try{return JSON.parse(Fa(n.split(".")[e]))}catch(t){throw new An("Invalid token specified: "+t.message)}}An.prototype=new Error,An.prototype.name="InvalidTokenError";var Ks=Ba;var Rn=class{constructor(i){this.config=i;this.cached=null;this.tokenInfo=null;this.getEndpoints=async()=>{if(this.cached)return this.cached;let i;this.config.fetchAuth?i=await this.config.fetchAuth():i=await(this.config.fetch||fetch.bind(window))(this.config.authEndpoint,{credentials:"include"}).then(d=>{if(d.ok)return d.json();throw new Error(`Auth endpoint returned non-200 response: ${d.status}`)}),N(i.accessToken,"No access token provided from auth endpoint");let e=Ks(i.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:i.accessToken},this.cached};this.clearCache=()=>{this.cached=null};if(!i.authEndpoint&&!i.fetchAuth)throw new Error("Either authEndpoint or fetchAuth must be provided to ServerSyncEndpointProvider")}get type(){return this.tokenInfo?.type??je.Realtime}};var Tn=class extends U{constructor(e){super();this.timer=null;this.isScheduled=!1;this.next=()=>{this.isScheduled||(this.isScheduled=!0,this.timer=setTimeout(()=>{this.emit("trigger"),this.isScheduled=!1,this.backoff.next()},this.backoff.current))};this.reset=()=>{this.backoff.reset(),this.timer&&(clearTimeout(this.timer),this.timer=null)};this.backoff=e}},Fn=class{constructor(i,e){this.current=0;this.next=()=>{this.current=Math.min(this.max,this.current*this.factor)};this.reset=()=>{this.current=0};this.max=i,this.factor=e}};var Bn=class extends U{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 ct;this.reconnectScheduler=new Tn(new Fn(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&&(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 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===WebSocket.OPEN?(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===WebSocket.OPEN&&(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===WebSocket.OPEN}get status(){return this._status}};async function qs(){try{let n=await navigator.permissions.query({name:"periodic-background-sync"});if(n.state==="granted"){let i=await navigator.serviceWorker.ready;if("periodicSync"in i)try{await i.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:",n)}catch(n){console.error("Failed to initiate background sync:",n)}}var kn=class extends U{constructor(e){super();this.mode="pull";this.destroy=()=>{};this.isConnected=!1;this.status="paused";this.pullInterval=0;this.uploadFile=async()=>({success:!1,retry:!1});this.getFile=async()=>({success:!1,error:"Sync is not active"});this.syncOnce=async()=>{};this.presence=new Pt({initialPresence:null,defaultProfile:null,ctx:e})}send(){}async start(){}stop(){}ignoreIncoming(){}reconnect(){}setMode(){}setPullInterval(){}},lt=class extends U{constructor({authEndpoint:e,fetchAuth:t,fetch:r,initialPresence:s,automaticTransportSelection:o=!0,autoStart:a,initialTransport:d,pullInterval:p,presenceUpdateBatchTimeout:m,defaultProfile:D,useBroadcastChannel:v,onOutgoingMessage:P,EXPERIMENTAL_backgroundSync:b},{ctx:x,onData:E}){super();this.broadcastChannel=null;this._activelySyncing=!1;this.handleBroadcastChannelMessage=e=>{e.data.type==="sync"&&this.handleMessage(e.data.message,{source:"broadcastChannel"})};this.handleMessage=async(e,{source:t}={source:"network"})=>{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);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[Ji](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 Z(Z.Code.Unexpected,void 0,"Active sync has invalid token info");(e.type==="sync"||e.type==="op")&&ns(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 Z(Z.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=E,this.ctx=x,this.onOutgoingMessage=P,this.presence=new Pt({initialPresence:s,defaultProfile:D,updateBatchTimeout:m,ctx:x}),this.endpointProvider=new Rn({authEndpoint:e,fetchAuth:t,fetch:r}),this.webSocketSync=new Bn({endpointProvider:this.endpointProvider,presence:this.presence,ctx:x}),this.pushPullSync=new Cn({endpointProvider:this.endpointProvider,presence:this.presence,interval:p,fetch:r,ctx:x}),this.fileSync=new Pn({endpointProvider:this.endpointProvider,ctx:x}),v&&"BroadcastChannel"in window&&(this.broadcastChannel=new BroadcastChannel(`verdant-${x.namespace}`),this.broadcastChannel.addEventListener("message",this.handleBroadcastChannelMessage)),d==="realtime"?this.activeSync=this.webSocketSync:this.activeSync=this.pushPullSync,this.presence.subscribe("update",this.handlePresenceUpdate),x.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),o&&this.canDoRealtime){let S=()=>{_&&clearTimeout(_);let y=this.presence.getViewPeers().length>0||o!=="peers-only"&&this.presence.selfReplicaIds.size>1;y&&this.mode==="pull"?this.setMode("realtime"):!y&&this.mode==="realtime"&&(_=setTimeout(()=>{this.presence.getViewPeers().length===0&&this.setMode("pull")},1e3))},_;this.presence.subscribe("peersChanged",S),o!=="peers-only"&&this.presence.subscribe("selfChanged",S)}a&&this.start(),b&&qs()}get canDoRealtime(){return this.endpointProvider.type===je.Realtime||this.endpointProvider.type===je.PassiveRealtime||this.endpointProvider.type===je.ReadOnlyRealtime}get syncing(){return this._activelySyncing}get pullInterval(){return this.pushPullSync.interval}ignoreIncoming(){this.activeSync.ignoreIncoming()}get isConnected(){return this.activeSync.isConnected}get status(){return this.activeSync.status}get mode(){return this.activeSync.mode}};function Qs(n){return n.operations.map(t=>t.timestamp).concat(n.baselines?.map(t=>t.timestamp)??[]).reduce((t,r)=>{let s=Lt(r);return s>t?s:t},0)}function Hs(n,i){return`@@wip_${n}_${$e(i)}`}var jn=class extends ee{constructor(e,t){super();this.db=e;this.context=t;this.onServerReset=e=>this.db.resetSyncedStatusSince(e);this.add=async(e,t)=>{if(e.url&&!e.file){this.context.log("debug","Remote file added to an entity. This usually means an entity was cloned. Downloading remote file...",e.id);let r=await this.context.files.downloadRemoteFile(e.url,0,3);e.file=new File([r],e.name,{type:e.type})}else e.file||this.context.log("warn","File added without a file or URL. This file will not be available for use.",e.id);e.remote=!1,this.context.internalEvents.emit("fileAdded",e),await this.db.add(e,t),this.context.log("debug","File added",e.id,e.name,e.type,e.file?"with binary file":e.url?"with url":"with no data")};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=(e,t)=>`${t}___${e}`;this.export=async(e=!1)=>{let t=await this.getAll();if(e){for(let o of t)if(!o.file&&o.url)try{let a=await this.downloadRemoteFile(o.url);o.file=a}catch(a){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.",a)}}let r=[],s=[];for(let o of t){let a=o.file;if(delete o.file,r.push(o),a){let d=new File([a],this.getFileExportName(o.name,o.id),{type:o.type});s.push(d)}else this.context.log("warn",`File ${o.id} was could not be loaded locally or from the server. It will be missing in the export.`)}return{fileData:r,files:s}};this.import=async({fileData:e,files:t})=>{let r=new Map(t.map(o=>{let{id:a}=this.parseFileExportname(o.name);return[a,o]})),s=e.map(o=>{let a=r.get(o.id);return a?{...o,file:a}:(this.context.log("warn",`File ${o.id} was not found in import`),o)});await Promise.all(s.map(o=>this.add(o)))};this.parseFileExportname=e=>{let[t,r]=e.split("___");return{id:t,originalFileName:r}};this.downloadRemoteFile=async(e,t=0,r=0)=>{let s=await fetch(e,{method:"GET",credentials:"include"});if(!s.ok){if(t<r)return new Promise((o,a)=>{setTimeout(()=>{this.downloadRemoteFile(e,t+1,r).then(o,a)},1e3)});throw new Error(`Failed to download file after ${r} retries (status: ${s.status})`)}return await s.blob()};this.cleanupDeletedFiles=async()=>{let e=0,t=0;await this.iterateOverPendingDelete((r,s)=>{this.config.canCleanupDeletedFile(r)?(e++,s.delete(r.id)):t++}),this.context.log("info",`Cleaned up ${e} files, skipped ${t} files`)};this.onFileRefsDeleted=async e=>{let t=this.db.transaction({mode:"readwrite",storeNames:["files"]});await Promise.all(e.map(async r=>{try{await this.db.markPendingDelete(r.id,{transaction:t})}catch(s){this.context.log("error","Failed to mark file for deletion",s)}})),this.context.log("info",`Marked ${e.length} files as pending delete`)};t.internalEvents.subscribe("filesDeleted",this.onFileRefsDeleted),this.compose(this.db),this.cleanupDeletedFiles()}get config(){return{canCleanupDeletedFile(e){return e.deletedAt!==null&&e.deletedAt<Date.now()-1e3*60*24*3},...this.context.config.files}}};var Mn=class{constructor(i,e){this.db=i;this.ctx=e;this.tryAutonomousRebase=async()=>{(await this.db.getLocalReplica()).lastSyncedLogicalTime||await this.runRebase(this.ctx.time.now)};this.runRebase=async i=>{if(this.ctx.closing)return;let e,t=new Set,r=this.db.transaction({storeNames:["baselines","operations"],mode:"readwrite"}),s=0;if(await this.db.iterateAllOperations(a=>{t.add(a.oid),e=a.timestamp,s++},{before:i,transaction:r}),!t.size||this.ctx.closing)return;let o=[];for(let a of t)o.push(await this.rebase(a,e||i,r));this.ctx.globalEvents.emit("rebase")};this.scheduleRebase=async i=>{this.rebaseTimeout&&clearTimeout(this.rebaseTimeout),this.rebaseTimeout=setTimeout(this.runRebase,this.ctx.config.persistence?.rebaseTimeout??1e4,i)};this.rebaseTimeout=null;this.rebase=async(i,e,t)=>{let r=t||this.db.transaction({storeNames:["operations","baselines"],mode:"readwrite"}),s=await this.db.getBaseline(i,{transaction:r}),o=s?.snapshot||void 0,a=0,d=s?.authz,p=[];await this.db.consumeEntityOperations(i,D=>{(!s||D.timestamp>s.timestamp)&&(o=ke(o,D.data,p),D.data.op==="initialize"&&(d=D.authz)),a++},{to:e,transaction:r}),o&&z(o,i);let m={oid:i,snapshot:o,timestamp:e,authz:d};if(m.snapshot?await this.db.setBaselines([m],{transaction:r}):await this.db.deleteBaseline(i,{transaction:r}),this.ctx.log("debug","rebased",i,"up to",e,":",o,"and deleted",a,"operations"),p.length){let D=p.filter(me);D.length&&this.ctx.internalEvents.emit("filesDeleted",D)}return m}}};var Ln=class{constructor(i,e){this.db=i;this.ctx=e;this.createOperation=async i=>{let e=await this.db.getLocalReplica();return{type:"op",timestamp:this.ctx.time.now,replicaId:e.id,operations:i.operations.map(Jt)}};this.createSyncStep1=async i=>{let e=await this.db.getLocalReplica(),t=i===null?null:e.lastSyncedLogicalTime,r=[],s=new Set,o=await this.db.transaction({mode:"readwrite",storeNames:["operations","baselines"]});t?(this.ctx.log("debug","Syncing local operations since",t),await this.db.iterateLocalOperations(d=>{r.push(Jt(d)),s.add($(d.oid))},{after:t,transaction:o})):(this.ctx.log("debug","Syncing all operations"),await this.db.iterateAllOperations(d=>{r.push(Jt(d)),s.add($(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 i=>{let e=await this.db.getLocalReplica();return{type:"presence-update",presence:i.presence,replicaId:e.id,internal:i.internal}};this.createHeartbeat=async()=>{let i=await this.db.getLocalReplica();return{type:"heartbeat",timestamp:this.ctx.time.now,replicaId:i.id}};this.createAck=async i=>{let e=await this.db.getLocalReplica();return{type:"ack",timestamp:this.ctx.time.now,replicaId:e.id,nonce:i}}}};var dt=class extends ee{constructor(e,t){super();this.db=e;this.ctx=t;this.events=new U;this.insertOperations=async(e,t)=>{this.ctx.log("debug",`Inserting ${e.length} operations`,e);let r=await this.db.addOperations(e,t);for(let s of e)this.ctx.globalEvents.emit("operation",s);return this.ctx.config.persistence?.disableRebasing||this.rebaser.tryAutonomousRebase(),r};this.insertLocalOperations=async(e,t)=>{if(e.length===0)return;for(let s of e)s.isLocal=!0;await this.insertOperations(e,t);let r=await this.messageCreator.createOperation({operations:e});this.events.emit("syncMessage",r)};this.insertRemoteOperations=async(e,t)=>{if(e.length===0)return[];for(let r of e)r.isLocal=!1;await this.insertOperations(e,t),this.ack(e[e.length-1].timestamp)};this.insertRemoteBaselines=async(e,t)=>{if(e.length===0)return[];this.ctx.log("debug",`Inserting ${e.length} remote baselines`),await this.db.setBaselines(e,t);let r=new Set;return e.forEach(s=>{r.add($(s.oid))}),Array.from(r)};this.deleteDocument=async e=>{let t=new Set,r=$(e);N(r===e,"Must be root document OID"),t.add(r);let s=this.db.transaction({storeNames:["baselines","operations"]});await Promise.all([this.db.iterateDocumentBaselines(r,d=>{t.add(d.oid)},{transaction:s}),this.db.iterateDocumentOperations(r,d=>{t.add(d.oid)},{transaction:s})]);let o=await this.getDocumentAuthz(r),a=new Array;for(let d of t)a.push({oid:d,timestamp:this.ctx.time.now,data:{op:"delete"},authz:o});return this.insertLocalOperations(a)};this.deleteCollection=async e=>{let t=new Set,r=this.db.transaction({storeNames:["baselines","operations"],mode:"readwrite"});await Promise.all([this.db.iterateCollectionBaselines(e,o=>{t.add(o.oid)},{transaction:r}),this.db.iterateCollectionOperations(e,o=>{t.add(o.oid)},{transaction:r})]);let s=new Array;for(let o of t)s.push({oid:o,timestamp:this.ctx.time.now,data:{op:"delete"},authz:void 0});return this.insertLocalOperations(s)};this.getDocumentSnapshot=async(e,t={})=>{let r=$(e);N(r===e,"Must be root document OID");let s=this.db.transaction({storeNames:["baselines","operations"],mode:"readwrite"}),o=[];await this.db.iterateDocumentBaselines(r,p=>{o.push(p)},{transaction:s});let a=new Map;for(let p of o)p.snapshot&&z(p.snapshot,p.oid),a.set(p.oid,p.snapshot);await this.db.iterateDocumentOperations(r,p=>{let m=a.get(p.oid)||void 0,D=ke(m,p.data);D&&z(D,p.oid),a.set(p.oid,D)},{transaction:s,to:t.to||this.ctx.time.now});let d=a.get(r);return d&&Wt(d,a),d};this.getDocumentData=async(e,t)=>{let r=this.db.transaction({storeNames:["baselines","operations"],abort:t?.abort}),s=[],o={};return await Promise.all([this.db.iterateDocumentBaselines(e,a=>{s.push(a)},{transaction:r}),this.db.iterateDocumentOperations(e,a=>{o[a.oid]??=[],o[a.oid].push(a)},{transaction:r})]),{baselines:s,operations:o}};this.getDocumentAuthz=async e=>{let t;return await this.db.iterateEntityOperations(e,r=>{if(r.data.op==="initialize")return t=r.authz,!0}),t};this.insertData=async(e,t)=>{let r=this.db.transaction({storeNames:["baselines","operations"],abort:t?.abort,mode:"readwrite"});e.baselines&&await this.insertRemoteBaselines(e.baselines,{transaction:r}),!t?.abort?.aborted&&e.operations&&(e.isLocal?await this.insertLocalOperations(e.operations,{transaction:r}):await this.insertRemoteOperations(e.operations,{transaction:r}))};this.updateLastSynced=async e=>{if(!this.ctx.closing)return this.db.updateLocalReplica({lastSyncedLogicalTime:e})};this.setGlobalAck=async e=>{this.ctx.closing||(await this.db.setGlobalAck(e),this.ctx.config.persistence?.disableRebasing||await this.rebaser.scheduleRebase(e))};this.getLocalReplica=async e=>this.db.getLocalReplica(e);this.iterateLocalOperations=this.db.iterateLocalOperations;this.iterateAllOperations=this.db.iterateAllOperations;this.iterateAllBaselines=this.db.iterateAllBaselines;this.reset=this.db.reset;this.stats=this.db.stats;this.export=async()=>{let e=this.db,t=new Array,r=new Array,s=e.transaction({storeNames:["baselines","operations"],mode:"readwrite"});await this.iterateAllOperations(a=>{r.push(a)},{transaction:s}),await this.iterateAllBaselines(a=>{t.push(a)},{transaction:s});let o=await this.db.getLocalReplica();return{operations:r,baselines:t,localReplica:o,schemaVersion:this.ctx.schema.version}};this.resetFrom=async e=>{let r=this.db.transaction({storeNames:["baselines","operations","info"],mode:"readwrite"});await this.db.reset({clearReplica:!0,transaction:r}),e.localReplica&&await this.db.updateLocalReplica({ackedLogicalTime:e.localReplica.ackedLogicalTime,lastSyncedLogicalTime:e.localReplica.lastSyncedLogicalTime},{transaction:r}),this.ctx.log("debug","Resetting metadata from export",e),await this.insertData({operations:e.operations,baselines:e.baselines,isLocal:!0})};this.manualRebase=async()=>{if(this.ctx.closing||this.ctx.config.persistence?.disableRebasing)return;let e=await this.db.getAckInfo();e.globalAckTimestamp&&await this.rebaser.scheduleRebase(e.globalAckTimestamp)};this.ack=async e=>{let t=await this.db.getLocalReplica();e>this.ctx.time.now||(this.events.emit("syncMessage",{type:"ack",replicaId:t.id,timestamp:e}),!this.ctx.closing&&(!t.ackedLogicalTime||e>t.ackedLogicalTime)&&this.db.updateLocalReplica({ackedLogicalTime:e}))};this.rebaser=new Mn(e,t),this.messageCreator=new Ln(e,t),this.compose(this.db)}};var Vn=class extends ee{constructor(e,t){super();this.db=e;this.ctx=t;this.reset=this.db.reset.bind(this.db);this.saveEntities=this.db.saveEntities;this.findOneOid=this.db.findOneOid.bind(this.db);this.findAllOids=this.db.findAllOids.bind(this.db);this.stats=this.db.stats.bind(this.db);this.compose(this.db)}};async function Un(n){let i=n;if(n.schema.wip&&(i.namespace=Hs(n.originalNamespace,n.schema),i.log("info","Switched to WIP namespace",i.namespace),!(await i.persistence.getNamespaces()).includes(i.namespace))){let t=await i.persistence.getNamespaceVersion(i.originalNamespace);if(t!==0){let r=n.oldSchemas?.find(s=>s.version===t);if(!r)throw new Z(Z.Code.MigrationPathNotFound,void 0,`Trying to open WIP database for version ${n.schema.version}, but the current local data is version ${t} and a historical schema for that version is not available.`);i.log("info",`Copying data from ${i.originalNamespace} to ${i.namespace}`),await i.persistence.copyNamespace(i.originalNamespace,i.namespace,{...i,schema:r})}}if(i.log("info","Opening persistence metadata"),i.meta=new dt(await n.persistence.openMetadata(n),n),i.log("info","Opening persistence files"),i.files=new jn(await n.persistence.openFiles(i),i),i.log("info","Opening persistence queries"),i.queries=new Vn(await n.persistence.openQueries(i),i),!n.schema.wip){let e=await n.persistence.getNamespaces();for(let t of e)t.startsWith("@@wip_")&&(n.log("debug","Cleaning up old WIP namespace",t),await n.persistence.deleteNamespace(t,n))}return i}async function Ws(n,i){n.log("info","Importing data from export");let e=n.oldSchemas?.find(a=>a.version===i.data.schemaVersion);if(!e)throw new Error(`Could not find schema for version ${i.data.schemaVersion}`);let t=`@@import_${Date.now()}`,r=await Un({...n,schema:e,namespace:t,originalNamespace:t,entityEvents:new U,config:{...n.config,persistence:{...n.config.persistence,disableRebasing:!0}}});await r.meta.resetFrom(i.data);let s=new Set;for(let a of i.data.baselines)s.add($(a.oid));for(let a of i.data.operations)s.add($(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.queries.saveEntities(o),await r.files.import(i),n.log("debug","Imported data into temporary namespace",t),await r.queries.dispose(),await r.meta.dispose(),await r.files.dispose(),e.version!==n.schema.version){n.log("debug","Shut down imported databases");let a=n.schema,d=await Un({...r,schema:a});n.log("debug","Upgraded imported data to current schema"),await d.queries.dispose(),await d.meta.dispose(),await d.files.dispose(),n.log("debug","Shut down upgraded databases")}if(await n.persistence.copyNamespace(t,n.namespace,n),i.data.schemaVersion===n.schema.version){let a=await n.meta.stats();if(a.operationsSize.count!==i.data.operations.length)throw n.log("critical","Imported operations count mismatch","expected",i.data.operations.length,"actual",a.operationsSize.count),new Z(Z.Code.ImportFailed,void 0,"Imported operations count mismatch");if(a.baselinesSize.count!==i.data.baselines.length)throw n.log("critical","Imported documents count mismatch","expected",i.data.baselines.length,"actual",a.baselinesSize.count),new Z(Z.Code.ImportFailed,void 0,"Imported documents count mismatch")}n.log("debug","Data copied to primary namespace"),await n.persistence.deleteNamespace(t,n),n.log("debug","Deleted temporary namespace"),n.internalEvents.emit("persistenceReset"),n.log("info","Data imported successfully")}var ut=class extends U{constructor(e){super();this.context=e;this.importingPromise=Promise.resolve();this.addData=async e=>{await this.importingPromise;try{let t=e.reset?Qs(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.queries.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:m})=>p+m,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.files.dispose(),this.sync.stop(),this.sync.destroy(),await this._entities.destroy(),this.context.queries.dispose(),this.context.meta.dispose(),await new Promise(e=>{e()}),this.context.log?.("info","Client closed")};this.__dangerous__resetLocal=async()=>{this.sync.stop(),await wn(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 Ws(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();this.collectionNames=Object.keys(e.schema.collections),this._sync=this.context.config.sync&&!e.schema.wip?new lt(this.context.config.sync,{onData:this.addData,ctx:this.context}):new kn(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 bn({sync:this.sync,context:this.context}),this._entities=new gn({ctx:this.context,files:this._fileManager}),this._queryCache=new Dn({context:e}),this._documentManager=new nn(this.schema,this._entities);let t=Mr(()=>{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")});for(let[r,s]of Object.entries(e.schema.collections)){let o=r;this[o]=new En({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 batch(){return this.entities.batch}get __persistence(){return{meta:this.context.meta,queries:this.context.queries,files:this.context.files}}};var Nn=class{constructor(i){this.value=i}deref(){return this.value}};var zn=class{constructor(i,e){this.base=i;this.version=e;this.withMigrationTime=async(i,e)=>{this.overrideNow=()=>this.base.zero(i),await e(),this.overrideNow=void 0};this.update=this.base.update.bind(this.base);this.nowWithVersion=i=>this.base.now(i);this.zeroWithVersion=i=>this.base.zero(i)}get now(){return this.overrideNow?this.overrideNow():this.base.now(this.version)}get zero(){return this.base.zero(this.version)}};var Ne=class extends ee{constructor(e,{log:t}={}){super();this.db=e;this.globalAbortController=new AbortController;this.createTransaction=(e,t)=>{let r=Vs(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};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 Ye(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(Ye))};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(p=>new Promise((m,D)=>{p.onsuccess=()=>{let v=p.result;v?r(v.value,a,v)?m():v.continue():m()},p.onerror=()=>{p.error&&Je(p.error)?m():D(p.error)}}))).then(()=>{}):new Promise((p,m)=>{d.onsuccess=()=>{let D=d.result;D?r(D.value,a,D)?p():D.continue():p()},d.onerror=()=>{d.error&&Je(d.error)?p():m(d.error)}})};this.clear=(e,t)=>this.run(e,r=>r.clear(),{mode:"readwrite",transaction:t});this.cloneTo=async e=>{await Us(this.db,e)};this.onVersionChange=()=>{this.log?.("warn",`Another tab has requested a version change for ${this.db.name}`),this.db.close(),typeof window<"u"&&window.location.reload()};this.log=t,this.addDispose(()=>{this.globalAbortController.abort()}),this.db.addEventListener("versionchange",this.onVersionChange),this.addDispose(()=>{this.db.removeEventListener("versionchange",this.onVersionChange)})}};var $n=class extends Ne{constructor(){super(...arguments);this.transaction=e=>this.createTransaction(e.storeNames,{mode:e.mode,abort:e.abort});this.add=async(e,t)=>{let r=e.file?await ja(e.file):void 0;if(!r&&t?.downloadRemote&&e.url)try{r=await fetch(e.url,{method:"GET",credentials:"include"}).then(s=>s.arrayBuffer())}catch(s){console.error("Failed to download file to cache it locally. The file will still be available using its URL. Check the file server's CORS configuration.",s)}await this.run("files",s=>s.put({id:e.id,remote:e.remote?"true":"false",deletedAt:null,name:e.name,type:e.type,url:e.url,buffer:r}),{mode:"readwrite",transaction:t?.transaction})};this.markUploaded=async(e,t)=>{let r=await this.getFileRaw(e,t);if(!r)throw new Error("File is not in local database");await this.run("files",s=>s.put({...r,remote:"true"}),{mode:"readwrite",transaction:t?.transaction})};this.get=async(e,t)=>{let r=await this.getFileRaw(e,t);return r?this.hydrateFileData(r):null};this.delete=(e,t)=>this.run("files",r=>r.delete(e),{mode:"readwrite",transaction:t?.transaction});this.markPendingDelete=async(e,t)=>{let r=await this.getFileRaw(e,t);if(!r)throw new Error("File is not in local database");await this.run("files",s=>s.put({...r,deletedAt:Date.now()}),{mode:"readwrite",transaction:t?.transaction})};this.listUnsynced=async e=>(await this.run("files",r=>r.index("remote").getAll("false"),{mode:"readonly",transaction:e?.transaction})).map(this.hydrateFileData);this.resetSyncedStatusSince=async(e,t)=>{let r=t?.transaction??this.createTransaction(["files"],{mode:"readwrite"}),o=(await this.run("files",a=>a.index("remote").getAll("true"),{transaction:r})).filter(a=>!a.timestamp||!e||a.timestamp>e);await Promise.all(o.map(a=>this.run("files",d=>d.put({...a,remote:"false"}),{transaction:r})))};this.iterateOverPendingDelete=(e,t)=>this.iterate("files",r=>r.index("deletedAt").openCursor(IDBKeyRange.lowerBound(0,!0)),(r,s)=>{e(this.hydrateFileData(r),s)},{mode:"readwrite",transaction:t?.transaction});this.getAll=async e=>{let[t]=await Ki(this.db,["files"]);return t.map(this.hydrateFileData)};this.stats=async()=>({size:await Ve(this.db,"files")});this.hydrateFileData=e=>{e.remote=e.remote==="true";let t=e.buffer;return delete e.buffer,e.file=t?ka(t,e.type):void 0,e};this.getFileRaw=async(e,{transaction:t}={})=>{let r=await this.run("files",s=>s.get(e),{mode:"readonly",transaction:t});if(r)return r}}};function ka(n,i){return new Blob([n],{type:i})}function ja(n){return"__testReadBuffer"in n?Promise.resolve(n.__testReadBuffer):new Promise((i,e)=>{let t=new FileReader;t.onload=()=>{i(t.result)},t.onerror=e,t.readAsArrayBuffer(n)})}var Js=Te(ze(),1);var Kn=class extends Ne{constructor(e,t){super(e,t);this.ctx=t;this.transaction=e=>this.createTransaction(e.storeNames,{mode:e.mode,abort:e.abort});this.getAckInfo=async()=>{let e=await this.run("info",t=>t.get("ack"));return e||{globalAckTimestamp:null,type:"ack"}};this.setGlobalAck=async e=>{await this.run("info",t=>t.put({type:"ack",globalAckTimestamp:e}),{mode:"readwrite"})};this.getLocalReplica=async e=>{if(this.cachedLocalReplica)return this.cachedLocalReplica;let t=await this.run("info",r=>r.get("localReplicaInfo"),this.convertOpts(e));return t?(this.cachedLocalReplica=t,t):(this._creatingLocalReplica||(this._creatingLocalReplica=(async()=>{let s={type:"localReplicaInfo",id:(0,Js.default)(),userId:void 0,ackedLogicalTime:null,lastSyncedLogicalTime:null};await this.run("info",o=>o.put(s),{mode:"readwrite"}),this.cachedLocalReplica=s})()),await this._creatingLocalReplica,this.getLocalReplica(e))};this.updateLocalReplica=async(e,t=Ct)=>{let r=await this.getLocalReplica(t);Object.assign(r,e),await this.run("info",s=>s.put(r),{mode:"readwrite"}),this.cachedLocalReplica=r};this.iterateDocumentBaselines=async(e,t,r)=>{await this.iterate("baselines",s=>{let o=$(e),[a,d]=Ar(e),[p,m]=Ur(e);return[s.openCursor(IDBKeyRange.only(o)),s.openCursor(IDBKeyRange.bound(a,d,!1,!1)),s.openCursor(IDBKeyRange.bound(p,m,!1,!1))]},t,this.convertOpts(r))};this.iterateCollectionBaselines=async(e,t,r)=>{await this.iterate("baselines",s=>[s.openCursor(IDBKeyRange.bound(e,e+"\uFFFF",!1,!1))],t,this.convertOpts(r))};this.iterateAllBaselines=async(e,t)=>{await this.iterate("baselines",r=>r.index("timestamp").openCursor(),e,this.convertOpts(t))};this.getBaseline=(e,t)=>this.run("baselines",r=>r.get(e),this.convertOpts(t));this.setBaselines=async(e,t=Ct)=>{await this.runAll("baselines",r=>e.map(s=>r.put(s)),this.convertOpts(t))};this.deleteBaseline=async(e,t=Ct)=>{await this.run("baselines",r=>r.delete(e),this.convertOpts(t))};this.iterateDocumentOperations=(e,t,r)=>this.iterate("operations",s=>{let o=s.index("d_t"),a=Re(e),d=r?.to?we(e,r.to):Le(e),p=IDBKeyRange.bound(a,d,!1,!1);return o.openCursor(p)},t,this.convertOpts(r));this.iterateEntityOperations=(e,t,r)=>this.iterate("operations",s=>{let o=Re(e),a=r?.to?we(e,r.to):Le(e),d=IDBKeyRange.bound(o,a,!1,!1);return s.openCursor(d)},t,this.convertOpts(r));this.consumeEntityOperations=(e,t,r=Ct)=>this.iterate("operations",s=>{let o=Re(e),a=r?.to?we(e,r.to):Le(e),d=IDBKeyRange.bound(o,a,!1,!1);return s.openCursor(d)},(s,o)=>{t(s),o.delete(s.oid_timestamp)},this.convertOpts(r));this.iterateCollectionOperations=(e,t,r)=>this.iterate("operations",s=>s.openCursor(IDBKeyRange.bound(e,e+"\uFFFF",!1,!1),"next"),t,this.convertOpts(r));this.iterateLocalOperations=(e,t)=>this.iterate("operations",r=>{let s=t?.after?we(!0,t.after):Re(!0),o=Le(!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?Re(t.from):void 0,o=t?.before?Le(t.before):Re(!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,this.convertOpts(t));this.addOperations=async(e,t=Ct)=>{let r=new Set;return await this.runAll("operations",s=>e.map(o=>(r.add($(o.oid)),s.put(this.addOperationIndexes(o)))),this.convertOpts(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 Ve(this.db,"operations"),t=await Ve(this.db,"baselines");return{operationsSize:e,baselinesSize:t}};this.resetLocalReplica=async(e,t=!1)=>{if(t)return this.run("info",s=>s.delete("localReplicaInfo"),{mode:"readwrite",transaction:e});let r=await this.getLocalReplica();r.ackedLogicalTime=null,r.lastSyncedLogicalTime=null,await this.run("info",s=>s.put(r),{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:we(e.oid,e.timestamp),l_t:we(e.isLocal,e.timestamp),d_t:we($(e.oid),e.timestamp)});this.convertOpts=e=>{if(e?.transaction&&!(e.transaction instanceof IDBTransaction))throw new Error(`Invalid IndexedDB transaction. You cannot mix persistence providers. ${typeof e.transaction}`);return{mode:e?.mode,transaction:e?.transaction}};this.addDispose(()=>xe(e))}},Ct={mode:"readwrite"};var Ys=[La,Va,Ua,Na,za,$a],Ma=Ys.length;function Gi({indexedDB:n=window.indexedDB,namespace:i,log:e,metadataVersion:t=Ma}){return new Promise((r,s)=>{let o=n.open(vn(i),t),a=!1;o.onupgradeneeded=async d=>{let p=o.result,m=o.transaction,D=Ys.slice(d.oldVersion);for(let v of D)await v(p,m);await new Promise((v,P)=>{m.addEventListener("complete",v),m.addEventListener("error",P)}),d.oldVersion||(a=!0)},o.onerror=()=>{console.error("Error opening database",o.error),s(o.error)},o.onsuccess=()=>{r({db:o.result,wasInitialized:a})}})}async function La(n,i){let e=n.createObjectStore("baselines",{keyPath:"oid"}),t=n.createObjectStore("operations",{keyPath:"oid_timestamp"}),r=n.createObjectStore("info",{keyPath:"type"});e.createIndex("timestamp","timestamp"),t.createIndex("isLocal_timestamp","isLocal_timestamp"),t.createIndex("documentOid_timestamp","documentOid_timestamp")}async function Va(n,i){let e=i.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,...p}=o.value;o.update({...p,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 Ua(n,i){i.objectStore("operations").createIndex("timestamp","timestamp")}async function Na(n,i){let e=n.createObjectStore("files",{keyPath:"id"});e.createIndex("remote","remote"),e.createIndex("deletedAt","deletedAt")}async function za(n,i){let e=i.objectStore("operations");await new Promise((r,s)=>{let o=e.openCursor();o.onsuccess=()=>{let a=o.result;if(a){let d=di(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=i.objectStore("baselines");await new Promise((r,s)=>{let o=t.openCursor();o.onsuccess=()=>{let a=o.result;if(a){let d=di(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 $a(n,i){i.objectStore("files").createIndex("timestamp","timestamp")}var Ka=n=>IDBKeyRange.only(be(n.equals)),qa=n=>{},Qa=n=>{let i=n.gte||n.gt,e=n.lte||n.lt;return i===e?IDBKeyRange.only(be(i)):i?e?IDBKeyRange.bound(be(i),be(e),!!n.gt,!!n.lt):IDBKeyRange.lowerBound(be(i),!!n.gt):IDBKeyRange.upperBound(be(e),!!n.lt)},Ha=(n,i,e)=>{let t=n.collections[i].compounds[e.where];N(t,`Index ${e.where} does not exist on collection ${i}`);let r=Object.keys(e.match).sort((d,p)=>t.of.indexOf(d)-t.of.indexOf(p));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(we(...s));let o=Re(...s),a=Le(...s);return IDBKeyRange.bound(o,a)};function Wa(n){let i=n.startsWith,e=n.startsWith+"\uFFFF";return IDBKeyRange.bound(i,e)}function Xi(n,i,e){if(e)return pi(e)?Qa(e):hi(e)?Ka(e):Wr(e)?qa(e):mi(e)?Wa(e):Ha(n,i,e)}var ft=class extends Ne{constructor(e,t){super(e,{log:t.log});this.stats=async()=>{let e=Object.keys(this.ctx.schema.collections),t={};return await Promise.all(e.map(async r=>{let s=await Ve(this.db,r);t[r]=s})),t};this.transaction=e=>this.createTransaction(e.storeNames,{mode:e.mode,abort:e.abort});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=Xi(this.ctx.schema,e.collection,e.index);return s.openCursor(a,o)},{mode:"readonly"});return t?Y(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,p=t?.order==="desc"?"prev":"next",m=Xi(this.ctx.schema,e,t),D=d.openCursor(m,p),v=!1;return{result:await new Promise((b,x)=>{let E=!r,S=0,_=new Set;D.onsuccess=()=>{S++;let F=D.result;if(!F){b(Array.from(_));return}r&&!E?(F.advance(r),E=!0):((!s||_.size<s)&&_.add(Y(e,F.primaryKey.toString())),s&&S>s?(v=!0,b(Array.from(_))):F.continue())},D.onerror=()=>{D.error?.name==="InvalidStateError"?(this.ctx.log("error","find query failed with InvalidStateError",D.error),b([])):D.error&&Je(D.error)?b([]):x(D.error)}}),hasNextPage:v}};this.saveEntities=async(e,t)=>{if(e.length===0)return;let r=Array.from(new Set(e.map(d=>ce(d.oid).collection))),s=r.filter(d=>!this.ctx.schema.collections[d]);s.length>0&&this.ctx.log("warn",`Ignoring entities from collections that no longer exist: ${s.join(", ")}`);let o=new Set(r);s.forEach(d=>o.delete(d)),r=Array.from(o);let a={transaction:this.createTransaction(r,{mode:"readwrite",abort:t?.abort})};await Promise.all(e.map(async d=>{let p=d.getSnapshot();try{await this.saveDocument(d.oid,p,a)}catch(m){throw this.ctx.log("error",`Error saving document ${d.oid} (${JSON.stringify(p)})`,m),m instanceof Error?m:new Error("Unknown error saving document")}})),a.transaction.commit(),this.ctx.entityEvents.emit("collectionsChanged",r);for(let d of e)this.ctx.entityEvents.emit("documentChanged",d.oid)};this.reset=async e=>{let t=Object.keys(this.ctx.schema.collections),r=e?.transaction||this.createTransaction(t,{mode:"readwrite"});await Promise.all(t.map(s=>this.run(s,o=>o.clear(),{transaction:r}))),this.ctx.entityEvents.emit("collectionsChanged",t),this.ctx.log("info","\u{1F4A8} Reset queryable storage")};this.dispose=()=>xe(this.db);this.saveDocument=async(e,t,{transaction:r})=>{this.ctx.log("debug",`Saving document indexes for querying ${e}`);let{collection:s,id:o}=ce(e);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=Xt(a,t);await this.run(s,p=>p.put(d),{mode:"readwrite",transaction:r}),this.ctx.log("debug",`Save complete for ${e}`,d)}};this.ctx=t}};async function qn(n,i){let e=Qi(i),r=(await n.databases()).find(s=>s.name===e);return r?r.version??0:0}async function Gs(n,i,e,t,r){function s(o,a){let d=n.open([i,"collections"].join("_"),e),p=!1;d.onupgradeneeded=m=>{let D=d.transaction;t(D,d.result,m),p=!0},d.onsuccess=m=>{p?o(d.result):a(new Error("Database was not upgraded when a version change was expected"))},d.onerror=m=>{a(d.error||new Error("Unknown error"))},d.onblocked=m=>{r?.("Database upgrade blocked, waiting...")}}return new Promise(s)}async function Xs(n,i){typeof navigator<"u"&&navigator.locks?await navigator.locks.request(`verdant_migration_${n}`,i):await i()}async function Qn({indexedDB:n=$i,namespace:i,version:e,context:t}){t.log("debug","Opening database",i,"at version",e);let r=await Ns(Qi(i),e,n);return r.addEventListener("versionchange",s=>{r.close()}),r}function Zs({migration:n,newOids:i,ctx:e}){return n.allCollections.reduce((t,r)=>(t[r]={put:async(s,o)=>{Ce(n.newSchema.collections[r],s);let a=s[n.newSchema.collections[r].primaryKey],d=Y(r,a);return i.push(d),await e.time.withMigrationTime(n.version,()=>e.meta.insertData({operations:e.patchCreator.createInitialize(s,d,o?.access),isLocal:!0})),s},delete:async s=>{let o=Y(r,s);await e.time.withMigrationTime(n.version,()=>e.meta.deleteDocument(o))}},t),{})}function Ja({migration:n,context:i,queryDb:e}){let t=new ft(e,i);return n.oldCollections.reduce((r,s)=>(r[s]={get:async o=>{let a=Y(s,o);return await i.meta.getDocumentSnapshot(a,{to:i.time.nowWithVersion(n.oldSchema.version)})},findOne:async o=>{let a=await t.findOneOid({collection:s,index:o});return a?await i.meta.getDocumentSnapshot(a,{to:i.time.nowWithVersion(n.oldSchema.version)}):null},findAll:async o=>{let{result:a}=await t.findAllOids({collection:s,index:o});return await Promise.all(a.map(p=>i.meta.getDocumentSnapshot(p,{to:i.time.nowWithVersion(n.oldSchema.version)})))}},r),{})}function eo({migration:n,context:i,queryDb:e}){let t=new Array,r=Ja({migration:n,context:i,queryDb:e}),s=Zs({migration:n,newOids:t,ctx:i}),o=async p=>{await i.meta.deleteCollection(p)},a=new Array;return{log:i.log,newOids:t,deleteCollection:o,migrate:async(p,m)=>{let D=await r[p].findAll();await Promise.all(D.filter(Boolean).map(async v=>{let P=ie(v);N(!!P,`Document is missing an OID: ${JSON.stringify(v)}`);let b=await i.meta.getDocumentAuthz(P),x=le(v),E=await m(v);if(E){xt(x),xt(E),et(E);let S=St(x,E,()=>i.time.zeroWithVersion(n.version),void 0,[],{mergeUnknownObjects:!0,authz:b});S.length>0&&await i.meta.insertData({operations:S,isLocal:!0})}}))},queries:r,mutations:s,awaitables:a}}function to({migration:n,context:i}){let e=new Array,t=new Proxy({},{get(){throw new Error("Queries are not available in initial migrations; there is no database yet!")}}),r=Zs({migration:n,newOids:e,ctx:i});return{log:i.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:[]}}var no=typeof window<"u"?window.indexedDB:void 0;async function io({context:n,toRun:i,indexedDB:e=no,namespace:t=n.namespace}){await Xs(t,async()=>{for(let r of i){let s;if(r.oldSchema.version===0)s=to({migration:r,context:n}),await r.migrate(s);else{let d=await Qn({indexedDB:e,namespace:t,version:r.oldSchema.version,context:n});s=eo({migration:r,context:n,queryDb:d});try{await r.migrate(s),await Promise.all(s.awaitables)}catch(p){throw n.log("critical",`Migration failed (${r.oldSchema.version} -> ${r.newSchema.version})`,p),p instanceof Error?p:new Error("Unknown error during migration")}await xe(d)}n.log("debug","Upgrading database",t,"to version",r.newSchema.version);let o=await ec({migration:r,indexedDB:e,namespace:t,context:n}),a=await Za({currentVersion:r.oldSchema.version,newVersion:r.newSchema.version,ctx:n});for(let d of r.allCollections){let m=o.transaction(d,"readwrite").objectStore(d),v=(await Ya(m)).map(S=>Y(d,`${S}`));v.push(...s.newOids.filter(S=>ce(S).collection===d),...a.filter(S=>ce(S).collection===d));let b=(await Promise.all(v.map(async S=>{try{let _=await n.meta.getDocumentSnapshot(S);return[S,_]}catch(_){return n.log("error","Could not regenerate snapshot during migration for oid",S,"this document will not be preserved",_),null}}))).filter(S=>!!S).map(([S,_])=>{if(!_)return[S,void 0];let F=Xt(r.newSchema.collections[d],_);return[S,F]}),E=o.transaction(d,"readwrite").objectStore(d);await Promise.all(b.map(([S,_])=>{if(_)return Xa(E,_);{let{id:F}=ce(S);return Ga(E,F)}}))}await xe(o),n.log("debug",`Migration of ${t} complete.`),n.log("info",`
7
7
  \u2B06\uFE0F v${r.newSchema.version} Migration complete. Here's the rundown:
8
8
  - Added collections: ${r.addedCollections.join(", ")}
9
9
  - Removed collections: ${r.removedCollections.join(", ")}
10
10
  - Changed collections: ${r.changedCollections.join(", ")}
11
11
  - New indexes: ${Object.keys(r.addedIndexes).map(d=>r.addedIndexes[d].map(p=>`${d}.${p.name}`)).flatMap(d=>d).join(", ")}
12
12
  - Removed indexes: ${Object.keys(r.removedIndexes).map(d=>r.removedIndexes[d].map(p=>`${d}.${p.name}`)).flatMap(d=>d).join(", ")}
13
- `)}})}async function Ya(n){return new Promise((i,e)=>{let t=n.getAllKeys();t.onsuccess=r=>{i(t.result)},t.onerror=r=>{e(t.error)}})}async function Ga(n,i){let e=n.delete(i);return new Promise((t,r)=>{e.onsuccess=s=>{t()},e.onerror=s=>{r(e.error)}})}async function Xa(n,i){let e=n.put(i);return new Promise((t,r)=>{e.onsuccess=s=>{t()},e.onerror=s=>{r(e.error)}})}async function Za({currentVersion:n,newVersion:i,ctx:e}){let t=[];return await e.meta.iterateAllOperations(r=>{t.push(r)},{from:e.time.zeroWithVersion(n+1)}),Array.from(new Set(t.map(r=>$(r.oid))))}function ec({migration:n,indexedDB:i=no,namespace:e,context:t}){return Gs(i,e,n.newSchema.version,(r,s)=>{for(let o of n.addedCollections)s.createObjectStore(o,{keyPath:n.newSchema.collections[o].primaryKey,autoIncrement:!1});for(let o of n.allCollections){let a=r.objectStore(o);for(let d of n.addedIndexes[o]||[])a.createIndex(d.name,d.name,{multiEntry:d.multiEntry});for(let d of n.removedIndexes[o]||[])a.deleteIndex(d.name)}for(let o of n.removedCollections)r.objectStore(o).clear()},t.log)}function ro({currentVersion:n,targetVersion:i,migrations:e}){let t=so({currentVersion:n,targetVersion:i,migrations:e});if(!t)throw new ne(ne.Code.MigrationPathNotFound,void 0,`No migration path found from ${n} to ${i}! 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 so({currentVersion:n,targetVersion:i,migrations:e}){if(n===i)return[];let t=e.filter(r=>r.oldSchema.version===n).sort((r,s)=>s.newSchema.version-r.newSchema.version);for(;t.length>0;){let r=t.shift();if(r.newSchema.version>i)return null;if(r.newSchema.version===i)return[r];let s=so({currentVersion:r.newSchema.version,targetVersion:i,migrations:e});if(s)return[r,...s]}return null}var tc=typeof window<"u"?window.indexedDB:void 0;async function Zi({version:n,indexedDB:i=tc,migrations:e,context:t}){let r=await qn(i,t.namespace);t.log("debug","Opening index database",t.namespace,"Current database version:",r,"target version:",n,t.schema.wip?"(wip)":"");let s=ro({currentVersion:r,targetVersion:n,migrations:e});return s.length>0&&(t.log("debug","Migrations to run:",s.map(o=>o.version)),await io({context:t,toRun:s,indexedDB:i})),Qn({indexedDB:i,namespace:t.namespace,version:n,context:t})}var Hn=class{constructor(i=window.indexedDB){this.indexedDB=i;this.getNamespaces=async()=>{let i=await this.indexedDB.databases();return Array.from(new Set(i.map(zs).filter(e=>!!e)))};this.getNamespaceVersion=async i=>qn(this.indexedDB,i);this.deleteNamespace=async(i,e)=>{await Promise.all([qi(vn(i),this.indexedDB),qi([i,"collections"].join("_"),this.indexedDB)])};this.openMetadata=async i=>{let{db:e}=await Gi({indexedDB:this.indexedDB,log:i.log,namespace:i.namespace});return this.metadataDb=e,new Kn(e,i)};this.openQueries=async i=>{let e=await Zi({version:i.schema.version,indexedDB:this.indexedDB,migrations:i.migrations,context:i});return new ft(e,i)};this.copyNamespace=async(i,e,t)=>{let r={...t,namespace:i,originalNamespace:i},s=await this.openMetadata(r),o=new dt(s,r),a=await this.openQueries({...r,meta:o});t.log("info",`Copying data from ${i} to ${e}`);let{db:d}=await Gi({indexedDB:this.indexedDB,log:t.log,namespace:e});t.log("debug","Metadata database opened"),await s.cloneTo(d),t.log("debug","Metadata copied");let p=await Zi({version:t.schema.version,indexedDB:this.indexedDB,migrations:t.migrations,context:{...t,namespace:e,originalNamespace:e,meta:o}});await a.cloneTo(p),t.log("debug","Indexes copied"),t.log("debug","New document store stats:",await Ls(p)),await s.dispose(),await xe(d),await a.dispose(),await xe(p)}}openFiles(i){if(!this.metadataDb)throw new Error("Metadata database must be opened first. This is a bug in Verdant.");return Promise.resolve(new $n(this.metadataDb,i))}};var Wn=class{constructor(i){this.init=i;this._initializing=!1;this.initialize=async i=>{if(typeof window>"u"&&!i.indexedDb)throw new Error("A Verdant client was initialized in an environment without IndexedDB. If you are using verdant in a server-rendered framework, you must enforce that all clients are initialized on the client-side, or you must provide some mock interface of IDBFactory to the ClientDescriptor options.");if(this._initializing||this._resolvedValue)return this._readyPromise;this._initializing=!0;try{let e=new zn(new Bt,i.schema.version),t={closing:!1,entityEvents:new U,globalEvents:new U,internalEvents:new U,log:i.log||Vr,migrations:i.migrations,namespace:i.namespace,originalNamespace:i.namespace,schema:i.schema,oldSchemas:i.oldSchemas,time:e,undoHistory:i.undoHistory||new rt,weakRef:o=>i.EXPERIMENTAL_weakRefs?new WeakRef(o):new Nn(o),patchCreator:new tn(()=>e.now),config:{files:i.files,sync:i.sync,persistence:{disableRebasing:i.disableRebasing,rebaseTimeout:i.rebaseTimeout}},persistence:i.persistence||new Hn(i.indexedDb)},r=await Un(t),s=new ut(r);return this.resolveReady(s),this._resolvedValue=s,s}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 wn(this.namespace)};this._readyPromise=new Promise((e,t)=>{this.resolveReady=e,this.rejectReady=t}),this._namespace=i.namespace}get namespace(){return this._namespace}get current(){return this._resolvedValue}get readyPromise(){return this._readyPromise}get schema(){return this.init.schema}};var er=Te(ze(),1);function nc(n){return n?er.default.slug():(0,er.default)()}var ic={private:Qe.onlyMe(),public:void 0};function rc(n,{port:i=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:${i}/auth/${n}?userId=${t}`}}window.Verdant=tr;
13
+ `)}})}async function Ya(n){return new Promise((i,e)=>{let t=n.getAllKeys();t.onsuccess=r=>{i(t.result)},t.onerror=r=>{e(t.error)}})}async function Ga(n,i){let e=n.delete(i);return new Promise((t,r)=>{e.onsuccess=s=>{t()},e.onerror=s=>{r(e.error)}})}async function Xa(n,i){let e=n.put(i);return new Promise((t,r)=>{e.onsuccess=s=>{t()},e.onerror=s=>{r(e.error)}})}async function Za({currentVersion:n,newVersion:i,ctx:e}){let t=[];return await e.meta.iterateAllOperations(r=>{t.push(r)},{from:e.time.zeroWithVersion(n+1)}),Array.from(new Set(t.map(r=>$(r.oid))))}function ec({migration:n,indexedDB:i=no,namespace:e,context:t}){return Gs(i,e,n.newSchema.version,(r,s)=>{for(let o of n.addedCollections)s.createObjectStore(o,{keyPath:n.newSchema.collections[o].primaryKey,autoIncrement:!1});for(let o of n.allCollections){let a=r.objectStore(o);for(let d of n.addedIndexes[o]||[])a.createIndex(d.name,d.name,{multiEntry:d.multiEntry});for(let d of n.removedIndexes[o]||[])a.deleteIndex(d.name)}for(let o of n.removedCollections)r.objectStore(o).clear()},t.log)}function ro({currentVersion:n,targetVersion:i,migrations:e}){let t=so({currentVersion:n,targetVersion:i,migrations:e});if(!t)throw new Z(Z.Code.MigrationPathNotFound,void 0,`No migration path found from ${n} to ${i}! 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 so({currentVersion:n,targetVersion:i,migrations:e}){if(n===i)return[];let t=e.filter(r=>r.oldSchema.version===n).sort((r,s)=>s.newSchema.version-r.newSchema.version);for(;t.length>0;){let r=t.shift();if(r.newSchema.version>i)return null;if(r.newSchema.version===i)return[r];let s=so({currentVersion:r.newSchema.version,targetVersion:i,migrations:e});if(s)return[r,...s]}return null}var tc=typeof window<"u"?window.indexedDB:void 0;async function Zi({version:n,indexedDB:i=tc,migrations:e,context:t}){let r=await qn(i,t.namespace);t.log("debug","Opening index database",t.namespace,"Current database version:",r,"target version:",n,t.schema.wip?"(wip)":"");let s=ro({currentVersion:r,targetVersion:n,migrations:e});return s.length>0&&(t.log("debug","Migrations to run:",s.map(o=>o.version)),await io({context:t,toRun:s,indexedDB:i})),Qn({indexedDB:i,namespace:t.namespace,version:n,context:t})}var Hn=class{constructor(i=window.indexedDB){this.indexedDB=i;this.getNamespaces=async()=>{let i=await this.indexedDB.databases();return Array.from(new Set(i.map(zs).filter(e=>!!e)))};this.getNamespaceVersion=async i=>qn(this.indexedDB,i);this.deleteNamespace=async(i,e)=>{await Promise.all([qi(vn(i),this.indexedDB),qi([i,"collections"].join("_"),this.indexedDB)])};this.openMetadata=async i=>{let{db:e}=await Gi({indexedDB:this.indexedDB,log:i.log,namespace:i.namespace});return this.metadataDb=e,new Kn(e,i)};this.openQueries=async i=>{let e=await Zi({version:i.schema.version,indexedDB:this.indexedDB,migrations:i.migrations,context:i});return new ft(e,i)};this.copyNamespace=async(i,e,t)=>{let r={...t,namespace:i,originalNamespace:i},s=await this.openMetadata(r),o=new dt(s,r),a=await this.openQueries({...r,meta:o});t.log("info",`Copying data from ${i} to ${e}`);let{db:d}=await Gi({indexedDB:this.indexedDB,log:t.log,namespace:e});t.log("debug","Metadata database opened"),await s.cloneTo(d),t.log("debug","Metadata copied");let p=await Zi({version:t.schema.version,indexedDB:this.indexedDB,migrations:t.migrations,context:{...t,namespace:e,originalNamespace:e,meta:o}});await a.cloneTo(p),t.log("debug","Indexes copied"),t.log("debug","New document store stats:",await Ls(p)),await s.dispose(),await xe(d),await a.dispose(),await xe(p)}}openFiles(i){if(!this.metadataDb)throw new Error("Metadata database must be opened first. This is a bug in Verdant.");return Promise.resolve(new $n(this.metadataDb,i))}};var Wn=class{constructor(i){this.init=i;this._initializing=!1;this.initialize=async i=>{if(typeof window>"u"&&!i.indexedDb)throw new Error("A Verdant client was initialized in an environment without IndexedDB. If you are using verdant in a server-rendered framework, you must enforce that all clients are initialized on the client-side, or you must provide some mock interface of IDBFactory to the ClientDescriptor options.");if(this._initializing||this._resolvedValue)return this._readyPromise;this._initializing=!0;try{let e=new zn(new Bt,i.schema.version),t={closing:!1,entityEvents:new U,globalEvents:new U,internalEvents:new U,log:i.log||Vr,migrations:i.migrations,namespace:i.namespace,originalNamespace:i.namespace,schema:i.schema,oldSchemas:i.oldSchemas,time:e,undoHistory:i.undoHistory||new rt,weakRef:o=>i.EXPERIMENTAL_weakRefs?new WeakRef(o):new Nn(o),patchCreator:new tn(()=>e.now),config:{files:i.files,sync:i.sync,persistence:{disableRebasing:i.disableRebasing,rebaseTimeout:i.rebaseTimeout}},persistence:i.persistence||new Hn(i.indexedDb)},r=await Un(t),s=new ut(r);return this.resolveReady(s),this._resolvedValue=s,s}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 wn(this.namespace)};this._readyPromise=new Promise((e,t)=>{this.resolveReady=e,this.rejectReady=t}),this._namespace=i.namespace}get namespace(){return this._namespace}get current(){return this._resolvedValue}get readyPromise(){return this._readyPromise}get schema(){return this.init.schema}};var er=Te(ze(),1);function nc(n){return n?er.default.slug():(0,er.default)()}var ic={private:Qe.onlyMe(),public:void 0};function rc(n,{port:i=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:${i}/auth/${n}?userId=${t}`}}window.Verdant=tr;
14
14
  //# sourceMappingURL=index.js.map