@verdant-web/store 3.7.0 → 3.8.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.
- package/LICENSE +650 -21
- package/dist/bundle/index.js +12 -12
- package/dist/bundle/index.js.map +4 -4
- package/dist/esm/DocumentManager.d.ts +1 -0
- package/dist/esm/DocumentManager.js +8 -3
- package/dist/esm/DocumentManager.js.map +1 -1
- package/dist/esm/__tests__/documents.test.js +16 -0
- package/dist/esm/__tests__/documents.test.js.map +1 -1
- package/dist/esm/client/Client.d.ts +3 -3
- package/dist/esm/client/Client.js +5 -5
- package/dist/esm/client/Client.js.map +1 -1
- package/dist/esm/client/ClientDescriptor.d.ts +1 -0
- package/dist/esm/client/ClientDescriptor.js +6 -3
- package/dist/esm/client/ClientDescriptor.js.map +1 -1
- package/dist/esm/context.d.ts +1 -0
- package/dist/esm/entities/EntityStore.d.ts +3 -3
- package/dist/esm/entities/EntityStore.js +5 -0
- package/dist/esm/entities/EntityStore.js.map +1 -1
- package/dist/esm/idb.d.ts +6 -0
- package/dist/esm/idb.js +17 -1
- package/dist/esm/idb.js.map +1 -1
- package/dist/esm/migration/db.d.ts +9 -3
- package/dist/esm/migration/db.js +23 -11
- package/dist/esm/migration/db.js.map +1 -1
- package/dist/esm/migration/engine.d.ts +15 -0
- package/dist/esm/migration/engine.js +159 -0
- package/dist/esm/migration/engine.js.map +1 -0
- package/dist/esm/migration/migrations.d.ts +17 -0
- package/dist/esm/migration/migrations.js +242 -0
- package/dist/esm/migration/migrations.js.map +1 -0
- package/dist/esm/migration/openQueryDatabase.d.ts +10 -0
- package/dist/esm/migration/openQueryDatabase.js +27 -0
- package/dist/esm/migration/openQueryDatabase.js.map +1 -0
- package/dist/esm/migration/openWIPDatabase.d.ts +11 -0
- package/dist/esm/migration/openWIPDatabase.js +65 -0
- package/dist/esm/migration/openWIPDatabase.js.map +1 -0
- package/dist/esm/migration/types.d.ts +3 -0
- package/dist/esm/migration/types.js +2 -0
- package/dist/esm/migration/types.js.map +1 -0
- package/dist/esm/queries/QueryableStorage.js +1 -1
- package/dist/esm/queries/QueryableStorage.js.map +1 -1
- package/dist/esm/sync/PushPullSync.d.ts +3 -2
- package/dist/esm/sync/PushPullSync.js +7 -1
- package/dist/esm/sync/PushPullSync.js.map +1 -1
- package/package.json +4 -3
- package/src/DocumentManager.ts +11 -2
- package/src/__tests__/documents.test.ts +19 -0
- package/src/client/Client.ts +6 -8
- package/src/client/ClientDescriptor.ts +7 -6
- package/src/context.ts +1 -0
- package/src/entities/EntityStore.ts +8 -2
- package/src/idb.ts +20 -1
- package/src/migration/db.ts +62 -20
- package/src/migration/engine.ts +248 -0
- package/src/migration/migrations.ts +347 -0
- package/src/migration/openQueryDatabase.ts +63 -0
- package/src/migration/openWIPDatabase.ts +97 -0
- package/src/migration/types.ts +4 -0
- package/src/queries/QueryableStorage.ts +1 -1
- package/src/sync/PushPullSync.ts +10 -0
- package/dist/esm/migration/openDatabase.d.ts +0 -20
- package/dist/esm/migration/openDatabase.js +0 -463
- package/dist/esm/migration/openDatabase.js.map +0 -1
- package/src/migration/openDatabase.ts +0 -749
package/dist/bundle/index.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var Qo=Object.create;var Ft=Object.defineProperty;var Jo=Object.getOwnPropertyDescriptor;var Go=Object.getOwnPropertyNames;var Yo=Object.getPrototypeOf,Xo=Object.prototype.hasOwnProperty;var Zo=(n,i)=>()=>(n&&(i=n(n=0)),i);var oe=(n,i)=>()=>(i||n((i={exports:{}}).exports,i),i.exports),tr=(n,i)=>{for(var e in i)Ft(n,e,{get:i[e],enumerable:!0})},nr=(n,i,e,t)=>{if(i&&typeof i=="object"||typeof i=="function")for(let r of Go(i))!Xo.call(n,r)&&r!==e&&Ft(n,r,{get:()=>i[r],enumerable:!(t=Jo(i,r))||t.enumerable});return n};var Ue=(n,i,e)=>(e=n!=null?Qo(Yo(n)):{},nr(i||!n||!n.__esModule?Ft(e,"default",{value:n,enumerable:!0}):e,n)),Ye=n=>nr(Ft({},"__esModule",{value:!0}),n);var Gn=oe((Na,ir)=>{ir.exports=function(i,e){var t="000000000"+i;return t.substr(t.length-e)}});var or=oe(($a,rr)=>{var es=Gn(),ts=typeof window=="object"?window:self,ns=Object.keys(ts).length,is=navigator.mimeTypes?navigator.mimeTypes.length:0,rs=es((is+navigator.userAgent.length).toString(36)+ns.toString(36),4);rr.exports=function(){return rs}});var lr=oe((za,cr)=>{var Yn,sr=typeof window<"u"&&(window.crypto||window.msCrypto)||typeof self<"u"&&self.crypto;sr?(ar=Math.pow(2,32)-1,Yn=function(){return Math.abs(sr.getRandomValues(new Uint32Array(1))[0]/ar)}):Yn=Math.random;var ar;cr.exports=Yn});var Xe=oe((Ka,hr)=>{var Tt=or(),dr=Gn(),os=lr(),ct=0,Zn=4,Bt=36,ur=Math.pow(Bt,Zn);function Xn(){return dr((os()*ur<<0).toString(Bt),Zn)}function fr(){return ct=ct<ur?ct:0,ct++,ct-1}function lt(){var n="c",i=new Date().getTime().toString(Bt),e=dr(fr().toString(Bt),Zn),t=Tt(),r=Xn()+Xn();return n+i+e+t+r}lt.slug=function(){var i=new Date().getTime().toString(36),e=fr().toString(36).slice(-4),t=Tt().slice(0,1)+Tt().slice(-1),r=Xn().slice(-2);return i.slice(-2)+e+t+r};lt.isCuid=function(i){return typeof i!="string"?!1:!!i.startsWith("c")};lt.isSlug=function(i){if(typeof i!="string")return!1;var e=i.length;return e>=7&&e<=10};lt.fingerprint=Tt;hr.exports=lt});var _r=oe((Sr,Ir)=>{(function(n){var i;typeof Sr=="object"?Ir.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,u){if(!e[a]){if(!i[a]){var d=typeof require=="function"&&require;if(!u&&d)return d(a,!0);if(o)return o(a,!0);throw new Error("Cannot find module '"+a+"'")}u=e[a]={exports:{}},i[a][0].call(u.exports,function(m){var S=i[a][1][m];return r(S||m)},u,u.exports,n,i,e,t)}return e[a].exports}for(var o=typeof require=="function"&&require,s=0;s<t.length;s++)r(t[s]);return r}({1:[function(n,i,e){(function(t,r,o,s,a,u,d,m,S){"use strict";var b=n("crypto");function C(y,D){D=_(y,D);var f;return(f=D.algorithm!=="passthrough"?b.createHash(D.algorithm):new R).write===void 0&&(f.write=f.update,f.end=f.update),O(D,f).dispatch(y),f.update||f.end(""),f.digest?f.digest(D.encoding==="buffer"?void 0:D.encoding):(y=f.read(),D.encoding!=="buffer"?y.toString(D.encoding):y)}(e=i.exports=C).sha1=function(y){return C(y)},e.keys=function(y){return C(y,{excludeValues:!0,algorithm:"sha1",encoding:"hex"})},e.MD5=function(y){return C(y,{algorithm:"md5",encoding:"hex"})},e.keysMD5=function(y){return C(y,{algorithm:"md5",encoding:"hex",excludeValues:!0})};var w=b.getHashes?b.getHashes().slice():["sha1","md5"],v=(w.push("passthrough"),["buffer","hex","binary","base64"]);function _(y,D){var f={};if(f.algorithm=(D=D||{}).algorithm||"sha1",f.encoding=D.encoding||"hex",f.excludeValues=!!D.excludeValues,f.algorithm=f.algorithm.toLowerCase(),f.encoding=f.encoding.toLowerCase(),f.ignoreUnknown=D.ignoreUnknown===!0,f.respectType=D.respectType!==!1,f.respectFunctionNames=D.respectFunctionNames!==!1,f.respectFunctionProperties=D.respectFunctionProperties!==!1,f.unorderedArrays=D.unorderedArrays===!0,f.unorderedSets=D.unorderedSets!==!1,f.unorderedObjects=D.unorderedObjects!==!1,f.replacer=D.replacer||void 0,f.excludeKeys=D.excludeKeys||void 0,y===void 0)throw new Error("Object argument required.");for(var p=0;p<w.length;++p)w[p].toLowerCase()===f.algorithm.toLowerCase()&&(f.algorithm=w[p]);if(w.indexOf(f.algorithm)===-1)throw new Error('Algorithm "'+f.algorithm+'" not supported. supported values: '+w.join(", "));if(v.indexOf(f.encoding)===-1&&f.algorithm!=="passthrough")throw new Error('Encoding "'+f.encoding+'" not supported. supported values: '+v.join(", "));return f}function I(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 O(y,D,f){f=f||[];function p(l){return D.update?D.update(l,"utf8"):D.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 x,E=Object.prototype.toString.call(l),M=/\[object (.*)\]/i.exec(E);if(M=(M=M?M[1]:"unknown:["+E+"]").toLowerCase(),0<=(E=f.indexOf(l)))return this.dispatch("[CIRCULAR:"+E+"]");if(f.push(l),o!==void 0&&o.isBuffer&&o.isBuffer(l))return p("buffer:"),p(l);if(M==="object"||M==="function"||M==="asyncfunction")return E=Object.keys(l),y.unorderedObjects&&(E=E.sort()),y.respectType===!1||I(l)||E.splice(0,0,"prototype","__proto__","constructor"),y.excludeKeys&&(E=E.filter(function(k){return!y.excludeKeys(k)})),p("object:"+E.length+":"),x=this,E.forEach(function(k){x.dispatch(k),p(":"),y.excludeValues||x.dispatch(l[k]),p(",")});if(!this["_"+M]){if(y.ignoreUnknown)return p("["+M+"]");throw new Error('Unknown object type "'+M+'"')}this["_"+M](l)},_array:function(l,k){k=k!==void 0?k:y.unorderedArrays!==!1;var E=this;if(p("array:"+l.length+":"),!k||l.length<=1)return l.forEach(function(j){return E.dispatch(j)});var M=[],k=l.map(function(j){var B=new R,q=f.slice();return O(y,B,q).dispatch(j),M=M.concat(q.slice(f.length)),B.read().toString()});return f=f.concat(M),k.sort(),this._array(k,!1)},_date:function(l){return p("date:"+l.toJSON())},_symbol:function(l){return p("symbol:"+l.toString())},_error:function(l){return p("error:"+l.toString())},_boolean:function(l){return p("bool:"+l.toString())},_string:function(l){p("string:"+l.length+":"),p(l.toString())},_function:function(l){p("fn:"),I(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 p("number:"+l.toString())},_xml:function(l){return p("xml:"+l.toString())},_null:function(){return p("Null")},_undefined:function(){return p("Undefined")},_regexp:function(l){return p("regex:"+l.toString())},_uint8array:function(l){return p("uint8array:"),this.dispatch(Array.prototype.slice.call(l))},_uint8clampedarray:function(l){return p("uint8clampedarray:"),this.dispatch(Array.prototype.slice.call(l))},_int8array:function(l){return p("int8array:"),this.dispatch(Array.prototype.slice.call(l))},_uint16array:function(l){return p("uint16array:"),this.dispatch(Array.prototype.slice.call(l))},_int16array:function(l){return p("int16array:"),this.dispatch(Array.prototype.slice.call(l))},_uint32array:function(l){return p("uint32array:"),this.dispatch(Array.prototype.slice.call(l))},_int32array:function(l){return p("int32array:"),this.dispatch(Array.prototype.slice.call(l))},_float32array:function(l){return p("float32array:"),this.dispatch(Array.prototype.slice.call(l))},_float64array:function(l){return p("float64array:"),this.dispatch(Array.prototype.slice.call(l))},_arraybuffer:function(l){return p("arraybuffer:"),this.dispatch(new Uint8Array(l))},_url:function(l){return p("url:"+l.toString())},_map:function(l){return p("map:"),l=Array.from(l),this._array(l,y.unorderedSets!==!1)},_set:function(l){return p("set:"),l=Array.from(l),this._array(l,y.unorderedSets!==!1)},_file:function(l){return p("file:"),this.dispatch([l.name,l.size,l.type,l.lastModfied])},_blob:function(){if(y.ignoreUnknown)return p("[blob]");throw Error(`Hashing Blob objects is currently not supported
|
|
2
2
|
(see https://github.com/puleos/object-hash/issues/26)
|
|
3
3
|
Use "options.replacer" or "options.ignoreUnknown"
|
|
4
|
-
`)},_domwindow:function(){return p("domwindow")},_bigint:function(l){return p("bigint:"+l.toString())},_process:function(){return p("process")},_timer:function(){return p("timer")},_pipe:function(){return p("pipe")},_tcp:function(){return p("tcp")},_udp:function(){return p("udp")},_tty:function(){return p("tty")},_statwatcher:function(){return p("statwatcher")},_securecontext:function(){return p("securecontext")},_connection:function(){return p("connection")},_zlib:function(){return p("zlib")},_context:function(){return p("context")},_nodescript:function(){return p("nodescript")},_httpparser:function(){return p("httpparser")},_dataview:function(){return p("dataview")},_signal:function(){return p("signal")},_fsevent:function(){return p("fsevent")},_tlswrap:function(){return p("tlswrap")}}}function R(){return{buf:"",write:function(y){this.buf+=y},end:function(y){this.buf+=y},read:function(){return this.buf}}}e.writeToStream=function(y,
|
|
5
|
-
list should be an Array.`),c.length===0)return new w(0);if(c.length===1)return c[0];if(typeof f!="number")for(P=f=0;P<c.length;P++)f+=c[P].length;for(var g=new w(f),A=0,P=0;P<c.length;P++){var T=c[P];T.copy(g,A),A+=T.length}return g},w.prototype.write=function(c,f,g,A){isFinite(f)?isFinite(g)||(A=g,g=void 0):(Y=A,A=f,f=g,g=Y),f=Number(f)||0;var P,T,U,W,Y=this.length-f;switch((!g||Y<(g=Number(g)))&&(g=Y),A=String(A||"utf8").toLowerCase()){case"hex":P=function(ye,ie,re,X){re=Number(re)||0;var G=ye.length-re;(!X||G<(X=Number(X)))&&(X=G),F((G=ie.length)%2==0,"Invalid hex string"),G/2<X&&(X=G/2);for(var Ge=0;Ge<X;Ge++){var er=parseInt(ie.substr(2*Ge,2),16);F(!isNaN(er),"Invalid hex string"),ye[re+Ge]=er}return w._charsWritten=2*Ge,Ge}(this,c,f,g);break;case"utf8":case"utf-8":T=this,U=f,W=g,P=w._charsWritten=Pt(De(c),T,U,W);break;case"ascii":case"binary":P=x(this,c,f,g);break;case"base64":T=this,U=f,W=g,P=w._charsWritten=Pt(Yi(c),T,U,W);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":P=_(this,c,f,g);break;default:throw new Error("Unknown encoding")}return P},w.prototype.toString=function(c,f,g){var A,P,T,U,W=this;if(c=String(c||"utf8").toLowerCase(),f=Number(f)||0,(g=g!==void 0?Number(g):W.length)===f)return"";switch(c){case"hex":A=function(Y,ye,ie){var re=Y.length;(!ye||ye<0)&&(ye=0),(!ie||ie<0||re<ie)&&(ie=re);for(var X="",G=ye;G<ie;G++)X+=K(Y[G]);return X}(W,f,g);break;case"utf8":case"utf-8":A=function(Y,ye,ie){var re="",X="";ie=Math.min(Y.length,ie);for(var G=ye;G<ie;G++)Y[G]<=127?(re+=Xi(X)+String.fromCharCode(Y[G]),X=""):X+="%"+Y[G].toString(16);return re+Xi(X)}(W,f,g);break;case"ascii":case"binary":A=O(W,f,g);break;case"base64":P=W,U=g,A=(T=f)===0&&U===P.length?b.fromByteArray(P):b.fromByteArray(P.slice(T,U));break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":A=function(Y,ye,ie){for(var re=Y.slice(ye,ie),X="",G=0;G<re.length;G+=2)X+=String.fromCharCode(re[G]+256*re[G+1]);return X}(W,f,g);break;default:throw new Error("Unknown encoding")}return A},w.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},w.prototype.copy=function(c,f,g,A){if(f=f||0,(A=A||A===0?A:this.length)!==(g=g||0)&&c.length!==0&&this.length!==0){F(g<=A,"sourceEnd < sourceStart"),F(0<=f&&f<c.length,"targetStart out of bounds"),F(0<=g&&g<this.length,"sourceStart out of bounds"),F(0<=A&&A<=this.length,"sourceEnd out of bounds"),A>this.length&&(A=this.length);var P=(A=c.length-f<A-g?c.length-f+g:A)-g;if(P<100||!w._useTypedArrays)for(var T=0;T<P;T++)c[T+f]=this[T+g];else c._set(this.subarray(g,g+P),f)}},w.prototype.slice=function(c,f){var g=this.length;if(c=q(c,g,0),f=q(f,g,g),w._useTypedArrays)return w._augment(this.subarray(c,f));for(var A=f-c,P=new w(A,void 0,!0),T=0;T<A;T++)P[T]=this[T+c];return P},w.prototype.get=function(c){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(c)},w.prototype.set=function(c,f){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(c,f)},w.prototype.readUInt8=function(c,f){if(f||(F(c!=null,"missing offset"),F(c<this.length,"Trying to read beyond buffer length")),!(c>=this.length))return this[c]},w.prototype.readUInt16LE=function(c,f){return I(this,c,!0,f)},w.prototype.readUInt16BE=function(c,f){return I(this,c,!1,f)},w.prototype.readUInt32LE=function(c,f){return R(this,c,!0,f)},w.prototype.readUInt32BE=function(c,f){return R(this,c,!1,f)},w.prototype.readInt8=function(c,f){if(f||(F(c!=null,"missing offset"),F(c<this.length,"Trying to read beyond buffer length")),!(c>=this.length))return 128&this[c]?-1*(255-this[c]+1):this[c]},w.prototype.readInt16LE=function(c,f){return y(this,c,!0,f)},w.prototype.readInt16BE=function(c,f){return y(this,c,!1,f)},w.prototype.readInt32LE=function(c,f){return E(this,c,!0,f)},w.prototype.readInt32BE=function(c,f){return E(this,c,!1,f)},w.prototype.readFloatLE=function(c,f){return u(this,c,!0,f)},w.prototype.readFloatBE=function(c,f){return u(this,c,!1,f)},w.prototype.readDoubleLE=function(c,f){return p(this,c,!0,f)},w.prototype.readDoubleBE=function(c,f){return p(this,c,!1,f)},w.prototype.writeUInt8=function(c,f,g){g||(F(c!=null,"missing value"),F(f!=null,"missing offset"),F(f<this.length,"trying to write beyond buffer length"),Hn(c,255)),f>=this.length||(this[f]=c)},w.prototype.writeUInt16LE=function(c,f,g){l(this,c,f,!0,g)},w.prototype.writeUInt16BE=function(c,f,g){l(this,c,f,!1,g)},w.prototype.writeUInt32LE=function(c,f,g){S(this,c,f,!0,g)},w.prototype.writeUInt32BE=function(c,f,g){S(this,c,f,!1,g)},w.prototype.writeInt8=function(c,f,g){g||(F(c!=null,"missing value"),F(f!=null,"missing offset"),F(f<this.length,"Trying to write beyond buffer length"),Wn(c,127,-128)),f>=this.length||(0<=c?this.writeUInt8(c,f,g):this.writeUInt8(255+c+1,f,g))},w.prototype.writeInt16LE=function(c,f,g){C(this,c,f,!0,g)},w.prototype.writeInt16BE=function(c,f,g){C(this,c,f,!1,g)},w.prototype.writeInt32LE=function(c,f,g){j(this,c,f,!0,g)},w.prototype.writeInt32BE=function(c,f,g){j(this,c,f,!1,g)},w.prototype.writeFloatLE=function(c,f,g){B(this,c,f,!0,g)},w.prototype.writeFloatBE=function(c,f,g){B(this,c,f,!1,g)},w.prototype.writeDoubleLE=function(c,f,g){M(this,c,f,!0,g)},w.prototype.writeDoubleBE=function(c,f,g){M(this,c,f,!1,g)},w.prototype.fill=function(c,f,g){if(f=f||0,g=g||this.length,F(typeof(c=typeof(c=c||0)=="string"?c.charCodeAt(0):c)=="number"&&!isNaN(c),"value is not a number"),F(f<=g,"end < start"),g!==f&&this.length!==0){F(0<=f&&f<this.length,"start out of bounds"),F(0<=g&&g<=this.length,"end out of bounds");for(var A=f;A<g;A++)this[A]=c}},w.prototype.inspect=function(){for(var c=[],f=this.length,g=0;g<f;g++)if(c[g]=K(this[g]),g===e.INSPECT_MAX_BYTES){c[g+1]="...";break}return"<Buffer "+c.join(" ")+">"},w.prototype.toArrayBuffer=function(){if(typeof Uint8Array>"u")throw new Error("Buffer.toArrayBuffer not supported in this browser");if(w._useTypedArrays)return new w(this).buffer;for(var c=new Uint8Array(this.length),f=0,g=c.length;f<g;f+=1)c[f]=this[f];return c.buffer};var k=w.prototype;function q(c,f,g){return typeof c!="number"?g:f<=(c=~~c)?f:0<=c||0<=(c+=f)?c:0}function te(c){return(c=~~Math.ceil(+c))<0?0:c}function H(c){return(Array.isArray||function(f){return Object.prototype.toString.call(f)==="[object Array]"})(c)}function K(c){return c<16?"0"+c.toString(16):c.toString(16)}function De(c){for(var f=[],g=0;g<c.length;g++){var A=c.charCodeAt(g);if(A<=127)f.push(c.charCodeAt(g));else for(var P=g,T=(55296<=A&&A<=57343&&g++,encodeURIComponent(c.slice(P,g+1)).substr(1).split("%")),U=0;U<T.length;U++)f.push(parseInt(T[U],16))}return f}function Yi(c){return b.toByteArray(c)}function Pt(c,f,g,A){for(var P=0;P<A&&!(P+g>=f.length||P>=c.length);P++)f[P+g]=c[P];return P}function Xi(c){try{return decodeURIComponent(c)}catch{return String.fromCharCode(65533)}}function Hn(c,f){F(typeof c=="number","cannot write a non-number as a number"),F(0<=c,"specified a negative value for writing an unsigned value"),F(c<=f,"value is larger than maximum value for type"),F(Math.floor(c)===c,"value has a fractional component")}function Wn(c,f,g){F(typeof c=="number","cannot write a non-number as a number"),F(c<=f,"value larger than maximum allowed value"),F(g<=c,"value smaller than minimum allowed value"),F(Math.floor(c)===c,"value has a fractional component")}function Zi(c,f,g){F(typeof c=="number","cannot write a non-number as a number"),F(c<=f,"value larger than maximum allowed value"),F(g<=c,"value smaller than minimum allowed value")}function F(c,f){if(!c)throw new Error(f||"Failed assertion")}w._augment=function(c){return c._isBuffer=!0,c._get=c.get,c._set=c.set,c.get=k.get,c.set=k.set,c.write=k.write,c.toString=k.toString,c.toLocaleString=k.toString,c.toJSON=k.toJSON,c.copy=k.copy,c.slice=k.slice,c.readUInt8=k.readUInt8,c.readUInt16LE=k.readUInt16LE,c.readUInt16BE=k.readUInt16BE,c.readUInt32LE=k.readUInt32LE,c.readUInt32BE=k.readUInt32BE,c.readInt8=k.readInt8,c.readInt16LE=k.readInt16LE,c.readInt16BE=k.readInt16BE,c.readInt32LE=k.readInt32LE,c.readInt32BE=k.readInt32BE,c.readFloatLE=k.readFloatLE,c.readFloatBE=k.readFloatBE,c.readDoubleLE=k.readDoubleLE,c.readDoubleBE=k.readDoubleBE,c.writeUInt8=k.writeUInt8,c.writeUInt16LE=k.writeUInt16LE,c.writeUInt16BE=k.writeUInt16BE,c.writeUInt32LE=k.writeUInt32LE,c.writeUInt32BE=k.writeUInt32BE,c.writeInt8=k.writeInt8,c.writeInt16LE=k.writeInt16LE,c.writeInt16BE=k.writeInt16BE,c.writeInt32LE=k.writeInt32LE,c.writeInt32BE=k.writeInt32BE,c.writeFloatLE=k.writeFloatLE,c.writeFloatBE=k.writeFloatBE,c.writeDoubleLE=k.writeDoubleLE,c.writeDoubleBE=k.writeDoubleBE,c.fill=k.fill,c.inspect=k.inspect,c.toArrayBuffer=k.toArrayBuffer,c}}).call(this,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,b,o,a,h,d,m,v){var b=n("buffer").Buffer,D=4,w=new b(D);w.fill(0),i.exports={hash:function(x,_,O,I){for(var R=_(function(l,S){l.length%D!=0&&(C=l.length+(D-l.length%D),l=b.concat([l,w],C));for(var C,j=[],B=S?l.readInt32BE:l.readInt32LE,M=0;M<l.length;M+=D)j.push(B.call(l,M));return j}(x=b.isBuffer(x)?x:new b(x),I),8*x.length),_=I,y=new b(O),E=_?y.writeInt32BE:y.writeInt32LE,u=0;u<R.length;u++)E.call(y,R[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,b,o,a,h,d,m,v){var b=n("buffer").Buffer,D=n("./sha"),w=n("./sha256"),x=n("./rng"),_={sha1:D,sha256:w,md5:n("./md5")},O=64,I=new b(O);function R(l,S){var C=_[l=l||"sha1"],j=[];return C||y("algorithm:",l,"is not yet supported"),{update:function(B){return b.isBuffer(B)||(B=new b(B)),j.push(B),B.length,this},digest:function(B){var M=b.concat(j),M=S?function(k,q,te){b.isBuffer(q)||(q=new b(q)),b.isBuffer(te)||(te=new b(te)),q.length>O?q=k(q):q.length<O&&(q=b.concat([q,I],O));for(var H=new b(O),K=new b(O),De=0;De<O;De++)H[De]=54^q[De],K[De]=92^q[De];return te=k(b.concat([H,te])),k(b.concat([K,te]))}(C,S,M):C(M);return j=null,B?M.toString(B):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
|
-
`))}I.fill(0),e.createHash=function(l){return R(l)},e.createHmac=R,e.randomBytes=function(l,S){if(!S||!S.call)return new b(x(l));try{S.call(this,void 0,new b(x(l)))}catch(C){S(C)}};var E,u=["createCredentials","createCipher","createCipheriv","createDecipher","createDecipheriv","createSign","createVerify","createDiffieHellman","pbkdf2"],p=function(l){e[l]=function(){y("sorry,",l,"is not implemented yet")}};for(E in u)p(u[E],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/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,h,d,m,v){var b=n("./helpers");function D(y,E){y[E>>5]|=128<<E%32,y[14+(E+64>>>9<<4)]=E;for(var u=1732584193,p=-271733879,l=-1732584194,S=271733878,C=0;C<y.length;C+=16){var j=u,B=p,M=l,k=S,u=x(u,p,l,S,y[C+0],7,-680876936),S=x(S,u,p,l,y[C+1],12,-389564586),l=x(l,S,u,p,y[C+2],17,606105819),p=x(p,l,S,u,y[C+3],22,-1044525330);u=x(u,p,l,S,y[C+4],7,-176418897),S=x(S,u,p,l,y[C+5],12,1200080426),l=x(l,S,u,p,y[C+6],17,-1473231341),p=x(p,l,S,u,y[C+7],22,-45705983),u=x(u,p,l,S,y[C+8],7,1770035416),S=x(S,u,p,l,y[C+9],12,-1958414417),l=x(l,S,u,p,y[C+10],17,-42063),p=x(p,l,S,u,y[C+11],22,-1990404162),u=x(u,p,l,S,y[C+12],7,1804603682),S=x(S,u,p,l,y[C+13],12,-40341101),l=x(l,S,u,p,y[C+14],17,-1502002290),u=_(u,p=x(p,l,S,u,y[C+15],22,1236535329),l,S,y[C+1],5,-165796510),S=_(S,u,p,l,y[C+6],9,-1069501632),l=_(l,S,u,p,y[C+11],14,643717713),p=_(p,l,S,u,y[C+0],20,-373897302),u=_(u,p,l,S,y[C+5],5,-701558691),S=_(S,u,p,l,y[C+10],9,38016083),l=_(l,S,u,p,y[C+15],14,-660478335),p=_(p,l,S,u,y[C+4],20,-405537848),u=_(u,p,l,S,y[C+9],5,568446438),S=_(S,u,p,l,y[C+14],9,-1019803690),l=_(l,S,u,p,y[C+3],14,-187363961),p=_(p,l,S,u,y[C+8],20,1163531501),u=_(u,p,l,S,y[C+13],5,-1444681467),S=_(S,u,p,l,y[C+2],9,-51403784),l=_(l,S,u,p,y[C+7],14,1735328473),u=O(u,p=_(p,l,S,u,y[C+12],20,-1926607734),l,S,y[C+5],4,-378558),S=O(S,u,p,l,y[C+8],11,-2022574463),l=O(l,S,u,p,y[C+11],16,1839030562),p=O(p,l,S,u,y[C+14],23,-35309556),u=O(u,p,l,S,y[C+1],4,-1530992060),S=O(S,u,p,l,y[C+4],11,1272893353),l=O(l,S,u,p,y[C+7],16,-155497632),p=O(p,l,S,u,y[C+10],23,-1094730640),u=O(u,p,l,S,y[C+13],4,681279174),S=O(S,u,p,l,y[C+0],11,-358537222),l=O(l,S,u,p,y[C+3],16,-722521979),p=O(p,l,S,u,y[C+6],23,76029189),u=O(u,p,l,S,y[C+9],4,-640364487),S=O(S,u,p,l,y[C+12],11,-421815835),l=O(l,S,u,p,y[C+15],16,530742520),u=I(u,p=O(p,l,S,u,y[C+2],23,-995338651),l,S,y[C+0],6,-198630844),S=I(S,u,p,l,y[C+7],10,1126891415),l=I(l,S,u,p,y[C+14],15,-1416354905),p=I(p,l,S,u,y[C+5],21,-57434055),u=I(u,p,l,S,y[C+12],6,1700485571),S=I(S,u,p,l,y[C+3],10,-1894986606),l=I(l,S,u,p,y[C+10],15,-1051523),p=I(p,l,S,u,y[C+1],21,-2054922799),u=I(u,p,l,S,y[C+8],6,1873313359),S=I(S,u,p,l,y[C+15],10,-30611744),l=I(l,S,u,p,y[C+6],15,-1560198380),p=I(p,l,S,u,y[C+13],21,1309151649),u=I(u,p,l,S,y[C+4],6,-145523070),S=I(S,u,p,l,y[C+11],10,-1120210379),l=I(l,S,u,p,y[C+2],15,718787259),p=I(p,l,S,u,y[C+9],21,-343485551),u=R(u,j),p=R(p,B),l=R(l,M),S=R(S,k)}return Array(u,p,l,S)}function w(y,E,u,p,l,S){return R((E=R(R(E,y),R(p,S)))<<l|E>>>32-l,u)}function x(y,E,u,p,l,S,C){return w(E&u|~E&p,y,E,l,S,C)}function _(y,E,u,p,l,S,C){return w(E&p|u&~p,y,E,l,S,C)}function O(y,E,u,p,l,S,C){return w(E^u^p,y,E,l,S,C)}function I(y,E,u,p,l,S,C){return w(u^(E|~p),y,E,l,S,C)}function R(y,E){var u=(65535&y)+(65535&E);return(y>>16)+(E>>16)+(u>>16)<<16|65535&u}i.exports=function(y){return b.hash(y,D,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,h,d,m,v){var b;i.exports=b||function(D){for(var w,x=new Array(D),_=0;_<D;_++)!(3&_)&&(w=4294967296*Math.random()),x[_]=w>>>((3&_)<<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,h,d,m,v){var b=n("./helpers");function D(_,O){_[O>>5]|=128<<24-O%32,_[15+(O+64>>9<<4)]=O;for(var I,R,y,E=Array(80),u=1732584193,p=-271733879,l=-1732584194,S=271733878,C=-1009589776,j=0;j<_.length;j+=16){for(var B=u,M=p,k=l,q=S,te=C,H=0;H<80;H++){E[H]=H<16?_[j+H]:x(E[H-3]^E[H-8]^E[H-14]^E[H-16],1);var K=w(w(x(u,5),(K=p,R=l,y=S,(I=H)<20?K&R|~K&y:!(I<40)&&I<60?K&R|K&y|R&y:K^R^y)),w(w(C,E[H]),(I=H)<20?1518500249:I<40?1859775393:I<60?-1894007588:-899497514)),C=S,S=l,l=x(p,30),p=u,u=K}u=w(u,B),p=w(p,M),l=w(l,k),S=w(S,q),C=w(C,te)}return Array(u,p,l,S,C)}function w(_,O){var I=(65535&_)+(65535&O);return(_>>16)+(O>>16)+(I>>16)<<16|65535&I}function x(_,O){return _<<O|_>>>32-O}i.exports=function(_){return b.hash(_,D,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,h,d,m,v){function b(O,I){var R=(65535&O)+(65535&I);return(O>>16)+(I>>16)+(R>>16)<<16|65535&R}function D(O,I){var R,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),E=new Array(1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225),u=new Array(64);O[I>>5]|=128<<24-I%32,O[15+(I+64>>9<<4)]=I;for(var p,l,S=0;S<O.length;S+=16){for(var C=E[0],j=E[1],B=E[2],M=E[3],k=E[4],q=E[5],te=E[6],H=E[7],K=0;K<64;K++)u[K]=K<16?O[K+S]:b(b(b((l=u[K-2],x(l,17)^x(l,19)^_(l,10)),u[K-7]),(l=u[K-15],x(l,7)^x(l,18)^_(l,3))),u[K-16]),R=b(b(b(b(H,x(l=k,6)^x(l,11)^x(l,25)),k&q^~k&te),y[K]),u[K]),p=b(x(p=C,2)^x(p,13)^x(p,22),C&j^C&B^j&B),H=te,te=q,q=k,k=b(M,R),M=B,B=j,j=C,C=b(R,p);E[0]=b(C,E[0]),E[1]=b(j,E[1]),E[2]=b(B,E[2]),E[3]=b(M,E[3]),E[4]=b(k,E[4]),E[5]=b(q,E[5]),E[6]=b(te,E[6]),E[7]=b(H,E[7])}return E}var w=n("./helpers"),x=function(O,I){return O>>>I|O<<32-I},_=function(O,I){return O>>>I};i.exports=function(O){return w.hash(O,D,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,h,d,m,v){e.read=function(b,D,w,x,S){var O,I,R=8*S-x-1,y=(1<<R)-1,E=y>>1,u=-7,p=w?S-1:0,l=w?-1:1,S=b[D+p];for(p+=l,O=S&(1<<-u)-1,S>>=-u,u+=R;0<u;O=256*O+b[D+p],p+=l,u-=8);for(I=O&(1<<-u)-1,O>>=-u,u+=x;0<u;I=256*I+b[D+p],p+=l,u-=8);if(O===0)O=1-E;else{if(O===y)return I?NaN:1/0*(S?-1:1);I+=Math.pow(2,x),O-=E}return(S?-1:1)*I*Math.pow(2,O-x)},e.write=function(b,D,w,x,_,C){var I,R,y=8*C-_-1,E=(1<<y)-1,u=E>>1,p=_===23?Math.pow(2,-24)-Math.pow(2,-77):0,l=x?0:C-1,S=x?1:-1,C=D<0||D===0&&1/D<0?1:0;for(D=Math.abs(D),isNaN(D)||D===1/0?(R=isNaN(D)?1:0,I=E):(I=Math.floor(Math.log(D)/Math.LN2),D*(x=Math.pow(2,-I))<1&&(I--,x*=2),2<=(D+=1<=I+u?p/x:p*Math.pow(2,1-u))*x&&(I++,x/=2),E<=I+u?(R=0,I=E):1<=I+u?(R=(D*x-1)*Math.pow(2,_),I+=u):(R=D*Math.pow(2,u-1)*Math.pow(2,_),I=0));8<=_;b[w+l]=255&R,l+=S,R/=256,_-=8);for(I=I<<_|R,y+=_;0<y;b[w+l]=255&I,l+=S,I/=256,y-=8);b[w+l-S]|=128*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/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,h,d,m,v){var b,D,w;function x(){}(t=i.exports={}).nextTick=(D=typeof window<"u"&&window.setImmediate,w=typeof window<"u"&&window.postMessage&&window.addEventListener,D?function(_){return window.setImmediate(_)}:w?(b=[],window.addEventListener("message",function(_){var O=_.source;O!==window&&O!==null||_.data!=="process-tick"||(_.stopPropagation(),0<b.length&&b.shift()())},!0),function(_){b.push(_),window.postMessage("process-tick","*")}):function(_){setTimeout(_,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(_){throw new Error("process.binding is not supported")},t.cwd=function(){return"/"},t.chdir=function(_){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 We={};tr(We,{__addDisposableResource:()=>Is,__assign:()=>vn,__asyncDelegator:()=>gs,__asyncGenerator:()=>ms,__asyncValues:()=>ys,__await:()=>st,__awaiter:()=>ls,__classPrivateFieldGet:()=>xs,__classPrivateFieldIn:()=>Ss,__classPrivateFieldSet:()=>Os,__createBinding:()=>On,__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:()=>Fi,__rest:()=>ss,__runInitializers:()=>la,__setFunctionName:()=>ua,__spread:()=>fs,__spreadArray:()=>ps,__spreadArrays:()=>hs,__values:()=>xn,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");Ri(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(O){if(O!==void 0&&typeof O!="function")throw new TypeError("Function expected");return O}for(var a=t.kind,h=a==="getter"?"get":a==="setter"?"set":"value",d=!i&&n?t.static?n:n.prototype:null,m=i||(d?Object.getOwnPropertyDescriptor(d,t.name):{}),v,b=!1,D=e.length-1;D>=0;D--){var w={};for(var x in t)w[x]=x==="access"?{}:t[x];for(var x in t.access)w.access[x]=t.access[x];w.addInitializer=function(O){if(b)throw new TypeError("Cannot add initializers after decoration has completed");s.push(o(O||null))};var _=(0,e[D])(a==="accessor"?{get:m.get,set:m.set}:m[h],w);if(a==="accessor"){if(_===void 0)continue;if(_===null||typeof _!="object")throw new TypeError("Object expected");(v=o(_.get))&&(m.get=v),(v=o(_.set))&&(m.set=v),(v=o(_.init))&&r.unshift(v)}else(v=o(_))&&(a==="field"?r.unshift(v):m[h]=v)}d&&Object.defineProperty(d,t.name,m),b=!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{d(t.next(m))}catch(v){o(v)}}function h(m){try{d(t.throw(m))}catch(v){o(v)}}function d(m){m.done?s(m.value):r(m.value).then(a,h)}d((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(d){return function(m){return h([d,m])}}function h(d){if(t)throw new TypeError("Generator is already executing.");for(;o&&(o=0,d[0]&&(e=0)),e;)try{if(t=1,r&&(s=d[0]&2?r.return:d[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,d[1])).done)return s;switch(r=0,s&&(d=[d[0]&2,s.value]),d[0]){case 0:case 1:s=d;break;case 4:return e.label++,{value:d[1],done:!1};case 5:e.label++,r=d[1],d=[0];continue;case 7:d=e.ops.pop(),e.trys.pop();continue;default:if(s=e.trys,!(s=s.length>0&&s[s.length-1])&&(d[0]===6||d[0]===2)){e=0;continue}if(d[0]===3&&(!s||d[1]>s[0]&&d[1]<s[3])){e.label=d[1];break}if(d[0]===6&&e.label<s[1]){e.label=s[1],s=d;break}if(s&&e.label<s[2]){e.label=s[2],e.ops.push(d);break}s[2]&&e.ops.pop(),e.trys.pop();continue}d=i.call(n,e)}catch(m){d=[6,m],r=0}finally{t=s=0}if(d[0]&5)throw d[1];return{value:d[0]?d[1]:void 0,done:!0}}}function us(n,i){for(var e in n)e!=="default"&&!Object.prototype.hasOwnProperty.call(i,e)&&On(i,n,e)}function xn(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 Fi(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(Fi(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 st(n){return this instanceof st?(this.v=n,this):new st(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(b){t[b]&&(r[b]=function(D){return new Promise(function(w,x){s.push([b,D,w,x])>1||a(b,D)})})}function a(b,D){try{h(t[b](D))}catch(w){v(s[0][3],w)}}function h(b){b.value instanceof st?Promise.resolve(b.value.v).then(d,m):v(s[0][2],b)}function d(b){a("next",b)}function m(b){a("throw",b)}function v(b,D){b(D),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:st(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 xn=="function"?xn(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,h){o=n[s](o),r(a,h,o.done,o.value)})}}function r(s,o,a,h){Promise.resolve(h).then(function(d){s({value:d,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)&&On(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 Os(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 Ss(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 Ri,vn,On,fa,ha,pa,Qe=Hs(()=>{Ri=function(n,i){return Ri=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])},Ri(n,i)};vn=function(){return vn=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},vn.apply(this,arguments)};On=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:vn,__rest:ss,__decorate:os,__param:as,__metadata:cs,__awaiter:ls,__generator:ds,__createBinding:On,__exportStar:us,__values:xn,__read:Fi,__spread:fs,__spreadArrays:hs,__spreadArray:ps,__await:st,__asyncGenerator:ms,__asyncDelegator:gs,__asyncValues:ys,__makeTemplateObject:bs,__importStar:ws,__importDefault:vs,__classPrivateFieldGet:xs,__classPrivateFieldSet:Os,__classPrivateFieldIn:Ss,__addDisposableResource:Is,__disposeResources:_s}});var Es=se(Ds=>{"use strict";Object.defineProperty(Ds,"__esModule",{value:!0})});var ki=se(_e=>{"use strict";Object.defineProperty(_e,"__esModule",{value:!0});_e.invokeEventHandlersAsync=_e.invokeEventHandlers=_e.eventHandlerSafeInvokeAsync=_e.eventHandlerSafeInvoke=void 0;var Cs=(Qe(),Ye(We));function Ps(n,i,e){try{return n(i,e),{succeeded:!0}}catch(t){return{error:t,succeeded:!1}}}_e.eventHandlerSafeInvoke=Ps;function Ti(n,i,e){return(0,Cs.__awaiter)(this,void 0,void 0,function*(){try{return yield n(i,e),{succeeded:!0}}catch(t){return{error:t,succeeded:!1}}})}_e.eventHandlerSafeInvokeAsync=Ti;function ma(n,i,e,t){for(let r of n){let{succeeded:s,error:o}=Ps(r,i,e);if(!s&&t?.swallowExceptions!==!0)throw o}}_e.invokeEventHandlers=ma;function ga(n,i,e,t){return(0,Cs.__awaiter)(this,void 0,void 0,function*(){if(t?.parallelize===!1)for(let r of n){let{succeeded:s,error:o}=yield Ti(r,i,e);if(!s&&t?.swallowExceptions!==!0)throw o}else{let r=[];for(let s of n)r.push(Ti(s,i,e).then(({succeeded:o,error:a})=>{if(!o&&t?.swallowExceptions!==!0)throw a}));yield Promise.all(r)}})}_e.invokeEventHandlersAsync=ga});var Fs=se(Sn=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});Sn.TypedEvent=void 0;var ya=(Qe(),Ye(We)),As=ki(),Rs={swallowExceptions:!1,parallelize:!0},Bi=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)}};Sn.TypedEvent=Bi});var Mi=se(ji=>{"use strict";Object.defineProperty(ji,"__esModule",{value:!0});var ba=(Qe(),Ye(We));(0,ba.__exportStar)(Fs(),ji)});var Ts=se(In=>{"use strict";Object.defineProperty(In,"__esModule",{value:!0});In.FinalizationRegistryMissingError=void 0;var Li=class extends Error{};In.FinalizationRegistryMissingError=Li});var Vi=se(_n=>{"use strict";Object.defineProperty(_n,"__esModule",{value:!0});_n.WeakHandlerHolder=void 0;var wa=Ts(),Ui=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)}};_n.WeakHandlerHolder=Ui});var ks=se(Dn=>{"use strict";Object.defineProperty(Dn,"__esModule",{value:!0});Dn.WeakEvent=void 0;var Ni=(Qe(),Ye(We)),va=Mi(),xa=Vi(),$i=ki(),Oa={swallowExceptions:!1,parallelize:!0},zi=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,$i.eventHandlerSafeInvoke)(s,i,e);if(!o&&t?.swallowExceptions!==!0)throw a}else this.releaseHandler(r)}}invokeAsync(i,e,t=Oa){return(0,Ni.__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,Ni.__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,$i.eventHandlerSafeInvokeAsync)(s,i,e);if(!o&&t.swallowExceptions!==!0)throw a}else this.releaseHandler(r)}})}parallelInvokeAsync(i,e,t){return(0,Ni.__awaiter)(this,void 0,void 0,function*(){let r=[];for(let s of this._handlers){let o=s?.deref();o?r.push((0,$i.eventHandlerSafeInvokeAsync)(o,i,e).then(({succeeded:a,error:h})=>{if(!a&&t.swallowExceptions!==!0)throw h})):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)}};Dn.WeakEvent=zi});var js=se(En=>{"use strict";Object.defineProperty(En,"__esModule",{value:!0});var Bs=(Qe(),Ye(We));(0,Bs.__exportStar)(Vi(),En);(0,Bs.__exportStar)(ks(),En)});var Ms=se(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});var Ki=(Qe(),Ye(We));(0,Ki.__exportStar)(Es(),Dt);(0,Ki.__exportStar)(Mi(),Dt);(0,Ki.__exportStar)(js(),Dt)});var Gi={};tr(Gi,{Client:()=>Je,ClientDescriptor:()=>qn,Entity:()=>fe,EntityFile:()=>ue,MigrationPathError:()=>nt,ServerSync:()=>at,Storage:()=>Je,StorageDescriptor:()=>qn,UndoHistory:()=>He,collection:()=>wi,createDefaultMigration:()=>vi,createMigration:()=>xi,id:()=>Fa,migrate:()=>Jt,schema:()=>bt});var br=Me(Xe(),1),Mt=4,ut=36;function pr(n){return n.toString(ut).padStart(Mt,"0")}function Zs(n){return n.toString().padStart(6,"0")}var Tt=class{constructor(){this.latest={time:Date.now(),counter:0,node:eo()},this.zeroCounter=0,this.now=i=>(this.latest=gr(this.latest),this.get(i,this.latest)),this.OLD_now=i=>(this.latest=gr(this.latest),Zs(i)+no(this.latest)),this.timerState=()=>this.latest,this.update=i=>{let e=i.slice(Mt);this.latest=to(this.latest,wr(e))},this.get=(i,e)=>pr(i)+mr(e),this.zero=i=>pr(i)+mr({time:0,counter:this.zeroCounter++,node:this.latest.node}),this.getWallClockTime=ti}},kt=class extends Error{constructor(...i){super(),this.type="ClockDriftError",this.message=["maximum clock drift exceeded"].concat(i).join(" ")}},Bt=class extends Error{constructor(){super(),this.type="OverflowError",this.message="timestamp counter overflow"}},Xn=4,Zn=7,jt=60*1e3,dt=9;function eo(){return br.default.slug().padStart(Zn,"0").slice(0,Zn)}function mr(n){let i=new Date(n.time).getTime().toString(ut).padStart(dt,"0"),e=n.counter.toString(ut).padStart(Xn,"0"),t=n.node.padStart(Zn,"0");return`${i}${e}${t}`}function gr(n){let i=Date.now(),e=Math.max(n.time,i),t=n.time===e?n.counter+1:0;if(e-i>jt)throw new kt(e,i,jt);if(t>65535)throw new Bt;return{time:e,counter:t,node:n.node}}function to(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>jt)throw new kt(t,e,jt);if(s>65535)throw new Bt;return{time:t,counter:s,node:n.node}}function wr(n){let i=n.slice(0,dt),e=n.slice(dt,dt+Xn),t=n.slice(dt+Xn),r=parseInt(i,ut),s=parseInt(e,ut);if(isNaN(r)||isNaN(s))throw new Error("invalid clock format");return{time:r,counter:s,node:t}}function no(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 yr(n){return parseInt(n.slice(0,Mt),36)}function ei(n,i){return yr(n)-yr(i)}function ti(n){return wr(n.slice(Mt)).time}function be(n){return n&&n["@@type"]==="file"}function Lt(n){return{"@@type":"file",id:n}}var Ut,io=new Uint8Array(16);function ni(){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(io)}var vr=/^(?:[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 ro(n){return typeof n=="string"&&vr.test(n)}var xr=ro;var ee=[];for(Vt=0;Vt<256;++Vt)ee.push((Vt+256).toString(16).substr(1));var Vt;function so(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(!xr(e))throw TypeError("Stringified UUID is invalid");return e}var Or=so;function oo(n,i,e){n=n||{};var t=n.random||(n.rng||ni)();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 Or(t)}var ft=oo;function Q(n){return Oe(n)||be(n)}function Ze(n,i){return n===i?!0:!(!Q(n)||!Q(i)||n["@@type"]!==i["@@type"]||n.id!==i.id)}var Dr=Me(_r(),1);function ao(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 ht(n){return JSON.stringify(n,ao)}function ae(n,i=!0){if(N(n)||Array.isArray(n)){let e=pe(n),t;if(Array.isArray(n))t=n.map(r=>ae(r,i));else{t={};for(let[r,s]of Object.entries(n))t[r]=ae(s,i)}return i&&e&&$(t,e),t}return n}function Fe(n){return(0,Dr.default)(n)}function N(n){return n&&typeof n=="object"}function Er(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 L(n,i="assertion failed"){if(!n)throw new Error(i)}function Nt(n=16){return ft().replace("-","").slice(0,n)}function Cr(n,i){for(let e=n.length-1;e>=0;e--)if(i(n[e]))return e;return-1}function Pr(n,i){let e;return function(...t){let r=this;clearTimeout(e),e=setTimeout(()=>n.apply(r,t),i)}}var Le="__@@oid_do_not_use",Se="@@id",co="/",mt=":",ri=new WeakMap;function ne(n){let i=pe(n);return L(!!i,`Object ${JSON.stringify(n)} does not have an OID assigned to it`),i}function pe(n){var i,e;if(N(n))return(e=(i=ri.get(n))!==null&&i!==void 0?i:n[Se])!==null&&e!==void 0?e:n[Le]}function $(n,i){return L(N(n),`Only objects can be assigned OIDs, received ${JSON.stringify(n)}`),si(n)&&Kt(n),ri.set(n,i),n}function si(n){return!!pe(n)}function Kt(n){return ri.delete(n),n}function oi(n){return n===Se||n===Le}function ai(n,i,e){if(si(n))return ne(n);{let t=we(i,e);return $(n,t),t}}function Ar(n,i,e){if(si(n)){let t=ne(n);if(Ee(t,i))return ne(n);{let r=we(i,e);return $(n,r),r}}else{let t=we(i,e);return $(n,t),t}}var ii={".":"˙","/":"&slash;",":":":"};function Rr(n){return n.replace(/[/]/g,ii["/"]).replace(/[:]/g,ii[":"]).replace(/[.]/g,ii["."])}function Fr(n){return n.replace(/&slash;/g,"/").replace(/:/g,":").replace(/˙/g,".")}function Z(n,i,e){let t=Rr(n)+co+Rr(i);return e&&(t+=mt+e),t}function we(n,i=ho){let{collection:e,id:t}=me(n);return Z(e,t,i())}function me(n){let[i,e]=n.split(mt),[t,r,...s]=i.split("/");s.length&&(r+="/"+s.join("/"));let o;return r.includes(".")?o=r.slice(0,r.indexOf(".")):o=r,{collection:Fr(t),id:Fr(o),subId:e}}function et(n,i){let e=ne(n);if(Array.isArray(n)){let t;for(let r=0;r<n.length;r++)t=n[r],N(t)&&!Q(t)&&(Ar(t,e,i),et(t,i))}else if(N(n)&&!Q(n))for(let t of Object.keys(n))N(n[t])&&!Q(n[t])&&(Ar(n[t],e,i),et(n[t],i))}function lo(n){if(N(n))return n[Se]||n[Le]}function uo(n){return N(n)&&(delete n[Le],delete n[Se]),n}function fo(n){let i=lo(n);i&&$(n,i)}function pt(n){if(fo(n),uo(n),Array.isArray(n))for(let i=0;i<n.length;i++)pt(n[i]);else if(N(n))for(let i of Object.keys(n))pt(n[i])}function $t(n){if(Kt(n),Array.isArray(n))for(let i=0;i<n.length;i++)$t(n[i]);else if(N(n))for(let i of Object.keys(n))$t(n[i])}function ho(){return ft().slice(0,8)}function ce(n){return{"@@type":"ref",id:n}}function zt(n,i=new Map){if(Array.isArray(n)){let e=ne(n),t=$([],e);for(let r=0;r<n.length;r++){let s=n[r];if(N(s)){if(Oe(s))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(be(s)){t[r]=s;continue}else{let o=ne(s);t[r]=ce(o),zt(s,i)}}else t[r]=s}i.set(e,t)}else if(N(n)&&!Q(n)){let e=ne(n),t=$({},e);for(let r of Object.keys(n)){let s=n[r];if(N(s)){if(Oe(s))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(be(s))t[r]=s;else{let o=ne(s);t[r]=ce(o),zt(s,i)}}else t[r]=s}i.set(e,t)}else Q(n);return i}function z(n){return n.split(".")[0].split(mt)[0]}function ci(n){let i=z(n),e=we(i,()=>"\uFFFF");return[`${i}${mt}`,e]}function li(n){let i=z(n);return[`${i}.`,`${i}.\uFFFF`]}function Ee(n,i){return z(n)===z(i)}function po(n){let{collection:i,id:e,subId:t}=me(n);return Z(i,e,t)}var mo=/"\w+\/[^"]+?(\.[^"]+)+\:[\S]+?"/g;function go(n){return n.replaceAll(mo,i=>{let e=i.slice(1,i.length-1);return`"${po(e)}"`})}function di(n){return JSON.parse(go(JSON.stringify(n)))}function Tr(n){return!n.includes(mt)}function Oe(n){return n&&typeof n=="object"&&n["@@type"]==="ref"}function ui(n){return N(n)&&!Q(n)}function yo(n,i){return n===i?!0:Q(n)&&Q(i)?Ze(n,i):!1}function gt(n,i,e,t,r=[],s={}){let o=ne(n);function a(h,d,m,v){if(!ui(d))yo(d,m)||(v?r.push({oid:o,timestamp:e(),data:{op:"list-set",index:h,value:d}}):r.push({oid:o,timestamp:e(),data:{op:"set",name:h,value:d}}));else{let b=pe(m),D=pe(d);D&&!Ee(o,D)?(d=ae(d,!1),D=we(o,t),$(d,D)):s.mergeUnknownObjects?!D&&b?($(d,b),D=b):D=ai(d,o,t):D=ai(d,o,t),L(!!D,"Error: no value OID was resolved during diff. This is a bug in Verdant."),L(Ee(o,D),`Error: value OID ${D} is not related to parent OID ${o}. This is a bug in Verdant.`),m===void 0||D!==b?(Ce(d,D,e,t,r),r.push({oid:o,timestamp:e(),data:{op:"set",name:h,value:ce(D)}}),b!==void 0&&r.push({oid:b,timestamp:e(),data:{op:"delete"}})):gt(m,d,e,t,r,s)}}if(Array.isArray(n)&&Array.isArray(i)){for(let d=0;d<i.length;d++){let m=i[d],v=n[d];a(d,m,v,!0)}let h=n.length-i.length;if(h>0){for(let d=i.length;d<n.length;d++){let m=n[d],v=pe(m);v&&r.push({oid:v,timestamp:e(),data:{op:"delete"}})}r.push({oid:o,timestamp:e(),data:{op:"list-delete",index:i.length,count:h}})}}else{if(Array.isArray(n)||Array.isArray(i))throw new Error("Cannot diff an array with an object");if(ui(n)&&ui(i)){let h=new Set(Object.keys(n));for(let[d,m]of Object.entries(i)){if(m===void 0&&s.defaultUndefined||(h.delete(d),oi(d)))continue;let v=n[d];a(d,m,v,!1)}if(!s.defaultUndefined)for(let d of h)oi(d)||r.push({oid:o,timestamp:e(),data:{op:"remove",name:d}})}}return r}function Ce(n,i,e,t,r=[]){$(n,i),et(n,t);let s=zt(n);for(let o of s.keys()){let a=s.get(o);r.push({oid:o,timestamp:e(),data:{op:"initialize",value:Kt(a)}})}return r}function yt(n){let i={};for(let e of n)e.oid in i?i[e.oid].push(e):i[e.oid]=[e];return i}function Br(n){let i={};for(let e of n){let t=z(e.oid);t in i?i[t].push(e):i[t]=[e]}return i}function jr(n){let i={};for(let e of n){let t=z(e.oid);t in i?i[t].push(e):i[t]=[e]}return i}function Te(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: ${pe(n)})`),!1)}function Ue(n,i,e){if(n==null&&i.op!=="initialize")return n;let t=n,r,s;function o(a){e&&Q(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":Te(n)&&(o(n[i.index]),n[i.index]=i.value);break;case"list-push":Te(n)&&n.push(i.value);break;case"list-delete":Te(n)&&(o(n[i.index]),n.splice(i.index,i.count));break;case"list-move-by-index":Te(n)&&(s=n.splice(i.from,1),n.splice(i.to,0,s[0]));break;case"list-remove":if(Te(n))do{let a=i.value;i.only==="last"?Oe(a)?r=Cr(n,h=>h.id===a.id):r=n.lastIndexOf(a):Oe(a)?r=n.findIndex(h=>h.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":Te(n)&&(n.some(h=>Oe(h)&&Oe(i.value)?h.id===i.value.id:h===i.value)||n.push(i.value));break;case"list-move-by-ref":Te(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(Te(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):N(n)&&Object.values(n||{}).forEach(o);return;case"initialize":return ae(i.value);case"touch":return n;default:throw new Error(`Unsupported patch operation: ${i.op}`)}return n}function qt(n,i,e=[]){if(Array.isArray(n))for(let t=0;t<n.length;t++){let r=n[t];n[t]=kr(r,i,e),N(n[t])&&qt(n[t],i,e)}else if(!be(n)){if(N(n)){L(pe(n),`Object ${JSON.stringify(n)} must have an oid`);for(let t of Object.keys(n))n[t]=kr(n[t],i,e),N(n[t])&&qt(n[t],i,e)}}return e}function kr(n,i,e){if(Oe(n)){e.push(n.id);let t=i.get(n.id);return L(!!t,`No value was found in object map for ${n.id}`),$(t,n.id)}else return n}function Mr(n){return n.data.op==="set"?n.data.name:!1}function Lr(n,i){return i.has(!0)?!0:n.data.op==="set"||n.data.op==="remove"?i.has(n.data.name):!1}var ke;(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"})(ke||(ke={}));var bo=n=>Object.assign({type:"object"},n),wo=n=>Object.assign({type:"array"},n),vo=n=>Object.assign({type:"string"},n),xo=n=>Object.assign({type:"number"},n),Oo=n=>Object.assign({type:"boolean"},n),So=n=>Object.assign({type:"any"},n),Io=n=>Object.assign({type:"map"},n),_o=n=>Object.assign({type:"file"},n),Ur={object:bo,array:wo,string:vo,number:xo,boolean:Oo,any:So,map:Io,file:_o};var $r=Me(Xe(),1);function fi(n){return n.equals!==void 0}function hi(n){return n.gte!==void 0||n.lte!==void 0||n.gt!==void 0||n.lt!==void 0}function Do(n){return!!n.match}function pi(n){return n.startsWith!==void 0}function Vr(n){return!hi(n)&&!fi(n)&&!Do(n)&&!pi(n)&&n.order}function ve(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 gi(n){if(!(!n||!Pe(n)))return n.type==="file"?ve(n)?null:void 0:n.type==="map"?{}:n.type==="array"?ve(n)?null:[]:n.type==="object"?ve(n)?null:void 0:typeof n.default=="function"?n.default():n.default}function Ae(n,i){for(let[e,t]of Object.entries(n.fields)){let r=yi(t);(r!==void 0&&i[e]===void 0||!ve(t)&&i[e]===null)&&(i[e]=r),i[e]&&Ve(i[e],t)}return i}function Ve(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=yi(t);r!==void 0&&(n[e]=r)}Ve(n[e],t)}else if(i.type==="array")for(let e of n)Ve(e,i.items);else if(i.type==="map")for(let[e,t]of Object.entries(n))e===Se||e===Le||Ve(t,i.values)}function yi(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]=yi(t));return i}}function bi(n,i){for(let[e,t]of Object.entries(i))e===Se||e===Le||(n.fields[e]?mi(t,n.fields[e]):delete i[e]);return i}function mi(n,i){if(N(n)&&i.type==="object")for(let[e,t]of Object.entries(n))i.properties[e]?mi(t,i.properties[e]):delete n[e];else if(Array.isArray(n)&&i.type==="array")for(let e of n)mi(e,i.items)}function Nr(n,i){for(let[e,t]of Object.entries(i))if(e!==Se){if(!n[e])return{type:"invalid-key",fieldPath:[e],message:`Invalid field "${e}"`};if(t){let r=Be({field:n[e],value:t,fieldPath:[e]});if(r)return r}}}function Be({field:n,value:i,fieldPath:e=[],depth:t,requireDefaults:r}){if(!(t!==void 0&&t<=0)&&!(ve(n)&&i===null)){if(i===null&&(r||!Pe(n)))return{type:"no-default",fieldPath:e,message:`Invalid null value for field ${Re(e)}`};if(n.type==="object"){if(!N(i))return{type:"invalid-type",fieldPath:e,message:`Expected object${n.nullable?" or null":""} for field ${Re(e)}, got ${i}`};for(let[s,o]of Object.entries(n.properties))s!==Se&&i[s]&&Be({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 ${Re(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 ${Re(e)}, got ${i}`};for(let s of i)Be({field:n.items,value:s,fieldPath:[...e,"[]"],depth:t!==void 0?t-1:void 0})}else if(n.type==="map"){if(!N(i))return{type:"invalid-type",fieldPath:e,message:`Expected map for field ${Re(e)}, got ${i}`};for(let[s,o]of Object.entries(i))Be({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 ${Re(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 ${Re(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 ${Re(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 ${Re(e)}, got ${i}`}}else n.type}}function Re(n){return n.length===0?"root":n.join(".")}function Ne(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 Eo=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 wi(n){var{synthetics:i,indexes:e}=n,t=Eo(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 bt(n){return n}bt.collection=wi;bt.fields=Ur;bt.generated={id:$r.default};var Ht="\uFFFFFE",Co="\0",Po="\uFFFFFF";function le(...n){let i=Ao(n);return i.length===1?i[0]:i}function $e(...n){return n.join(Ht)+`${Po}`}function ze(...n){return n.join(Ht)+`${Ht}${Co}`}function Ao(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(Ht))))}function Ro(n){return!!n.field}function Fo(n,i){let e={};for(let[t,r]of Object.entries(n.indexes||{})){let s=r;Ro(s)?e[t]=xe(i[s.field]):e[t]=xe(s.compute(i))}return e}function To(n,i){return Object.entries(n.compounds||{}).reduce((e,[t,r])=>(e[t]=le(...r.of.map(s=>i[s])),e),{})}function ko(n,i){return Object.entries(n.fields).reduce((e,[t,r])=>("indexed"in r&&(e[t]=xe(i[t])),e),{})}function Wt(n,i){let e=Object.assign(Object.assign({[n.primaryKey]:i[n.primaryKey]},ko(n,i)),Fo(n,i));return Object.assign(e,To(n,Object.assign(Object.assign({},i),e))),e["@@@snapshot"]=i,e}var Bo="null";function xe(n){if(n===null)return Bo;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(xe);throw new Error(`Unsupported index value: ${n}`)}var zr={version:0,collections:{}};function Jt(n,i,e){let t=typeof i=="function",r=t?zr:n,s=t?n:i,o=t?i:e,a=Object.keys(s.collections).filter(x=>r.collections[x]&&ht(r.collections[x])!==ht(s.collections[x])),h=Object.keys(r.collections).filter(x=>!s.collections[x]),d=Object.keys(s.collections).filter(x=>!r.collections[x]),m=new Set;for(let x of a){let _=r.collections[x].fields,O=s.collections[x].fields;Object.keys(O).some(I=>{var R,y;return!(!((R=_[I])===null||R===void 0)&&R.default)&&((y=O[I])===null||y===void 0?void 0:y.default)})&&m.add(x),Object.keys(_).some(I=>!O[I])&&m.add(x)}let v={},b={};for(let x of[...a,...d]){let _=Qt(r.collections[x]),O=Qt(s.collections[x]),I=O.filter(y=>!_.find(E=>E.name===y.name)),R=_.filter(y=>!O.find(E=>E.name===y.name));I.length>0&&(v[x]=I,a.includes(x)&&m.add(x)),R.length>0&&(b[x]=R,a.includes(x)&&m.add(x))}let D=(x,_)=>Ae(s.collections[x],_),w=x=>_=>{let O=s.collections[x];return Ae(O,bi(O,_))};return{version:s.version,migrate:async x=>{let _=[];if(await o({migrate:async(O,I)=>{let R=w(O),y=async E=>{let u=await I(E);return $(u,ne(E)),R(u)};await x.migrate(O,y),_.push(O),m.delete(O)},identity:O=>O,withDefaults:D,info:{changedCollections:a,addedCollections:d,removedCollections:h},queries:x.queries,mutations:x.mutations}),s.version>1){x.log("debug","auto-migrating collections with new defaults",m);for(let I of m)await x.migrate(I,w(I)),_.push(I);let O=a.filter(I=>!_.includes(I));O.length>0&&console.error(`Unmigrated changed collections from version ${r.version} to version ${s.version}:`,O)}},removedCollections:h,addedIndexes:v,removedIndexes:b,allCollections:Object.keys(s.collections),changedCollections:a,addedCollections:d,oldCollections:Object.keys(r.collections),oldSchema:r,newSchema:s}}function Qt(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 vi(n,i){return Jt(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 xi(n,i,e){let t=typeof i=="function"||i===void 0,r=t?zr:n,s=t?n:i,o=t?i:e;L(r,"Invalid arguments to createMigration"),L(s,"Invalid arguments to createMigration");let{changedCollections:a,addedCollections:h,removedCollections:d,addedIndexes:m,removedIndexes:v,autoMigratedCollections:b,autoMigration:D}=jo(r,s);return{version:s.version,migrate:async w=>{let x=[];if(await o?.({migrate:async(O,I)=>{let R=D(O),y=async E=>{let u=await I(E);$(u,ne(E));let p=R(u),l=Nr(s.collections[O].fields,p);return p};await w.migrate(O,y),x.push(O),b.delete(O)},info:{changedCollections:a,addedCollections:h,removedCollections:d},queries:w.queries,mutations:w.mutations}),s.version>1){w.log("debug","auto-migrating collections with new defaults",b);for(let I of b)await w.migrate(I,D(I)),x.push(I);for(let I of d)await w.deleteCollection(I);let O=a.filter(I=>!x.includes(I));O.length>0&&console.error(`Unmigrated changed collections from version ${r.version} to version ${s.version}:`,O)}},removedCollections:d,addedIndexes:m,removedIndexes:v,allCollections:Object.keys(s.collections),changedCollections:a,addedCollections:h,oldCollections:Object.keys(r.collections),oldSchema:r,newSchema:s}}function jo(n,i){let e=Object.keys(i.collections).filter(m=>n.collections[m]&&ht(n.collections[m])!==ht(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 v=n.collections[m].fields,b=i.collections[m].fields;Object.keys(b).some(D=>!Pe(v[D])&&Pe(b[D]))&&s.add(m),Object.keys(v).some(D=>!b[D])&&s.add(m)}let o={},a={};for(let m of[...e,...r]){let v=Qt(n.collections[m]),b=Qt(i.collections[m]),D=b.filter(x=>!v.find(_=>_.name===x.name)),w=v.filter(x=>!b.find(_=>_.name===x.name));D.length>0&&(o[m]=D,e.includes(m)&&s.add(m)),w.length>0&&(a[m]=w,e.includes(m)&&s.add(m))}return{changedCollections:e,addedCollections:r,removedCollections:t,addedIndexes:o,removedIndexes:a,autoMigratedCollections:s,withDefaults:(m,v)=>Ae(i.collections[m],v),autoMigration:m=>v=>{let b=i.collections[m];return Ae(b,bi(b,v))}}}var Gt=class{constructor(i,e){this.getNow=i,this.createSubId=e,this.isPrimitive=t=>!N(t)||Q(t),this.createDiff=(t,r,s={})=>gt(t,r,this.getNow,this.createSubId,[],s),this.createInitialize=(t,r)=>Ce(t,r,this.getNow,this.createSubId),this.createSet=(t,r,s)=>{if(this.isPrimitive(s))return[{oid:t,timestamp:this.getNow(),data:{op:"set",name:r,value:s}}];{let o=we(t,this.createSubId);return[...Ce(s,o,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"set",value:ce(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=we(t,this.createSubId);return[...Ce(s,o,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-set",index:r,value:ce(o)}}]}},this.createListPush=(t,r)=>{if(this.isPrimitive(r))return[{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:r}}];{let s=we(t,this.createSubId);return[...Ce(r,s,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:ce(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:ce(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=we(t,this.createSubId);return[...Ce(s,o,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:ce(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=>t.map(r=>({oid:r,timestamp:this.getNow(),data:{op:"delete"}}))}};var V=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=Nt(),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 Kr(n,i,e,t){if(i==null)return[{oid:n,timestamp:t(),data:{op:"delete"}}];let r=ae(i),s=[];for(let o of e){let a=Mo(n,r,o,t);s.unshift(...a),Ue(r,o.data)}return s}function Mo(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 tt=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 Oi({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}},Oi=class{constructor({max:i,startedAt:e,timeout:t,userData:r,flusher:s,key:o}){this.items=[],this.update=({items:a,max:h,timeout:d,userData:m})=>{this.items.push(...a),h!==void 0&&(this.max=h),d!==void 0&&(this.timeout=d),m&&(this.userData=m);let v=this.items.length!==0&&this.timeout!==null&&!this.flushTimeout;this.max!==null&&this.items.length>=this.max?this.flush():v&&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 qr(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 wt;(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"})(wt||(wt={}));var Si=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}};Si.Code=wt;function Hr(n){return typeof n=="object"&&"code"in n&&typeof n.code=="number"}function de(n){return n instanceof Error&&n.name==="AbortError"}function J(n){return new Promise((i,e)=>{n.onsuccess=()=>{i(n.result)},n.onerror=()=>{n.error&&de(n.error)?i(n.result):e(n.error)}})}function vt(n,i){return new Promise((e,t)=>{let r=n.transaction([i],"readonly"),o=r.objectStore(i).openCursor(),a=0,h=0;o.onsuccess=function(d){let m=o.result;m&&(a++,h=h+Er(m.value),m.continue())},o.onerror=function(d){o.error&&de(o.error)?e({count:a,size:h}):t(o.error)},r.oncomplete=function(d){e({count:a,size:h})},r.onabort=function(d){t(d)},r.onerror=function(d){t(d)}})}function Yt(n,i){let e=n.transaction(i,"readonly"),t=i.map(r=>{let s=e.objectStore(r);return J(s.getAll())});return Promise.all(t)}async function Ke(n){n.close(),await new Promise((i,e)=>{i()})}async function Xt(n,i=window.indexedDB){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 Wr(n,i=window.indexedDB){return J(i.deleteDatabase(n))}async function Qr(n=window.indexedDB){return n.databases()}function Zt(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}var Ie=class{constructor(){this._disposes=[];this.disposed=!1;this.dispose=()=>{this.disposed=!0,this._disposes.forEach(i=>i()),this._disposes=[]};this.addDispose=i=>{this._disposes.push(i)}}};var oe=class extends Ie{constructor(e,{log:t}={}){super();this.db=e;this.globalAbortController=new AbortController;this.createTransaction=(e,t)=>{let r=Zt(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 J(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(J))};this.iterate=async(e,t,r,s)=>{let a=(s?.transaction||this.createTransaction([e],s)).objectStore(e),h=t(a);return Array.isArray(h)?Promise.all(h.map(d=>new Promise((m,v)=>{d.onsuccess=()=>{let b=d.result;b?(r(b.value,a),b.continue()):m()},d.onerror=()=>{d.error&&de(d.error)?m():v(d.error)}}))).then(()=>{}):new Promise((d,m)=>{h.onsuccess=()=>{let v=h.result;v?(r(v.value,a),v.continue()):d()},h.onerror=()=>{h.error&&de(h.error)?d():m(h.error)}})};this.clear=e=>this.run(e,t=>t.clear(),{mode:"readwrite"});this.log=t,this.addDispose(()=>{this.globalAbortController.abort()})}};var en=class extends oe{constructor(){super(...arguments);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"})}}};var tn=class extends oe{constructor(e,t){super(e,t);this.getAllForDocument=async(e,{mode:t="readonly",transaction:r}={})=>{let s=[];return await this.iterateOverAllForDocument(e,o=>{s.push(o)},{mode:t,transaction:r}),s};this.iterateOverAllForDocument=async(e,t,{mode:r="readonly",transaction:s}={})=>this.iterate("baselines",o=>{let a=z(e),[h,d]=ci(e),[m,v]=li(e);return[o.openCursor(IDBKeyRange.only(a)),o.openCursor(IDBKeyRange.bound(h,d,!1,!1)),o.openCursor(IDBKeyRange.bound(m,v,!1,!1))]},t,{mode:r,transaction:s});this.iterateOverAllForCollection=async(e,t,{mode:r="readonly",transaction:s}={})=>this.iterate("baselines",o=>[o.openCursor(IDBKeyRange.bound(e,e+"\uFFFF",!1,!1))],t,{mode:r,transaction:s});this.getAllForMultipleDocuments=async(e,{mode:t="readonly"}={})=>(await this.runAll("baselines",s=>e.flatMap(o=>{let a=z(o),[h,d]=ci(o),[m,v]=li(o);return[s.get(a),s.getAll(IDBKeyRange.bound(h,d,!1,!1)),s.getAll(IDBKeyRange.bound(m,v,!1,!1))]}),{mode:t})).flat();this.getAllSince=async(e,{mode:t="readonly"}={})=>this.run("baselines",r=>{let s=e?IDBKeyRange.lowerBound(e,!0):void 0;return r.index("timestamp").getAll(s)},{mode:t});this.get=async(e,{transaction:t,mode:r="readonly"}={})=>this.run("baselines",s=>s.get(e),{mode:r,transaction:t});this.set=async(e,{transaction:t}={})=>{await this.run("baselines",r=>r.put(e),{mode:"readwrite",transaction:t})};this.setAll=async(e,{transaction:t}={})=>{await this.runAll("baselines",r=>e.map(s=>r.put(s)),{mode:"readwrite",transaction:t})};this.reset=()=>this.clear("baselines");this.delete=async(e,{transaction:t})=>{await this.run("baselines",r=>r.delete(e),{mode:"readwrite",transaction:t})}}};var Jr=Me(Xe(),1);var nn=class extends oe{constructor(){super(...arguments);this.get=async({transaction:e}={})=>{if(this.cached)return this.cached;let t=await this.run("info",r=>r.get("localReplicaInfo"),{transaction:e});return t?(this.cached=t,t):(this._creating||(this._creating=(async()=>{let s={type:"localReplicaInfo",id:(0,Jr.default)(),ackedLogicalTime:null,lastSyncedLogicalTime:null};await this.run("info",o=>o.put(s),{mode:"readwrite"}),this.cached=s})()),await this._creating,this.get({transaction:e}))};this.update=async(e,{transaction:t}={})=>{let r=await this.get({transaction:t});Object.assign(r,e),await this.run("info",s=>s.put(r),{mode:"readwrite"}),this.cached=r};this.reset=async()=>{let e=await this.get();e.ackedLogicalTime=null,e.lastSyncedLogicalTime=null,await this.run("info",t=>t.put(e),{mode:"readwrite"})}}};var rn=class{constructor(i){this.meta=i;this.createOperation=async i=>{let e=await this.meta.localReplica.get();return{type:"op",timestamp:this.meta.now,replicaId:e.id,operations:i.operations.map(t=>({data:t.data,oid:t.oid,timestamp:t.timestamp}))}};this.createMigrationOperation=async({targetVersion:i,...e})=>{let t=await this.meta.localReplica.get();return{type:"op",operations:e.operations.map(r=>({...r,timestamp:this.meta.time.zero(i)})),timestamp:this.meta.time.zero(i),replicaId:t.id}};this.createSyncStep1=async i=>{let e=await this.meta.localReplica.get(),t=i===null?null:e.lastSyncedLogicalTime,r=[],s=new Set;t?await this.meta.operations.iterateOverAllLocalOperations(a=>{r.push({data:a.data,oid:a.oid,timestamp:a.timestamp}),s.add(z(a.oid))},{after:t,mode:"readwrite"}):await this.meta.operations.iterateOverAllOperations(a=>{r.push({data:a.data,oid:a.oid,timestamp:a.timestamp}),s.add(z(a.oid))},{mode:"readwrite"});let o=[];return t||(o=await this.meta.baselines.getAllSince("")),{type:"sync",schemaVersion:this.meta.schema.currentVersion,timestamp:this.meta.now,replicaId:e.id,resyncAll:!e.lastSyncedLogicalTime,operations:r,baselines:o,since:t}};this.createPresenceUpdate=async i=>{let e=await this.meta.localReplica.get();return{type:"presence-update",presence:i,replicaId:e.id}};this.createHeartbeat=async()=>{let i=await this.meta.localReplica.get();return{type:"heartbeat",timestamp:this.meta.now,replicaId:i.id}};this.createAck=async i=>{let e=await this.meta.localReplica.get();return{type:"ack",timestamp:this.meta.now,replicaId:e.id,nonce:i}}}};var sn=class extends oe{constructor(e,t){super(e,t);this.iterateOverAllOperationsForDocument=async(e,t,{to:r,from:s,after:o,mode:a="readonly",transaction:h}={})=>{let m=(h||this.createTransaction(["operations"],{mode:a})).objectStore("operations"),v=m.index("d_t"),b=s||o,D=b?le(e,b):ze(e),w=r?le(e,r):$e(e),x=IDBKeyRange.bound(D,w,!!o,!1),_=v.openCursor(x,"next");return new Promise((O,I)=>{let R;_.onsuccess=y=>{let E=_.result;if(E){let u=E.value;L(u.oid.startsWith(e)),L(R===void 0||R<=u.timestamp,`expected ${R} <= ${u.timestamp}`),t(u,m),R=u.timestamp,E.continue()}else O()},_.onerror=y=>{if(de(_.error)){O();return}else I(_.error)}})};this.iterateOverAllOperationsForEntity=async(e,t,{after:r,to:s,mode:o,transaction:a})=>{let d=(a||this.createTransaction(["operations"],{mode:o})).objectStore("operations"),m=r?le(e,r):ze(e),v=s?le(e,s):$e(e),b=IDBKeyRange.bound(m,v,!!r,!1),D=d.openCursor(b,"next");return new Promise((w,x)=>{let _;D.onsuccess=O=>{let I=D.result;if(I){let R=I.value;L(R.oid.startsWith(e)),L(_===void 0||_<=R.timestamp,`expected ${_} <= ${R.timestamp}`),t(R,d),_=R.timestamp,I.continue()}else w()},D.onerror=O=>{de(D.error)?w():x(D.error)}})};this.iterateOverAllOperationsForCollection=async(e,t,{after:r,to:s,mode:o,transaction:a})=>{let h=a||this.createTransaction(["operations"],{mode:o});return this.iterate("operations",d=>d.openCursor(IDBKeyRange.bound(e,e+"\uFFFF",!1,!1),"next"),t,{mode:o,transaction:h})};this.iterateOverAllLocalOperations=async(e,{before:t,after:r,mode:s="readonly",transaction:o})=>{let h=(o||this.createTransaction(["operations"],{mode:s})).objectStore("operations"),d=h.index("l_t"),m=r?le(!0,r):ze(!0),v=t?le(!0,t):$e(!0),b=IDBKeyRange.bound(m,v,!!r,!0),D=d.openCursor(b,"next");return new Promise((w,x)=>{let _;D.onsuccess=O=>{let I=D.result;if(I){let R=I.value;L(_===void 0||_<=R.timestamp,`expected ${_} <= ${R.timestamp}`),e(R,h),_=R.timestamp,I.continue()}else w()},D.onerror=O=>{de(D.error)?w():x(D.error)}})};this.iterateOverAllOperations=async(e,{before:t,transaction:r,mode:s,from:o})=>{await this.iterate("operations",a=>{let h=o?ze(o):void 0,d=t?$e(t):void 0,m=h&&d?window.IDBKeyRange.bound(h,d,!1,!0):h?window.IDBKeyRange.lowerBound(h,!1):d?window.IDBKeyRange.upperBound(d,!0):void 0;return a.index("timestamp").openCursor(m,"next")},e,{mode:s,transaction:r})};this.addOperations=async(e,{transaction:t}={})=>this.insert(e.map(this.addCompoundIndexes),{transaction:t});this.addCompoundIndexes=e=>({...e,oid_timestamp:le(e.oid,e.timestamp),l_t:le(e.isLocal,e.timestamp),d_t:le(z(e.oid),e.timestamp)});this.insert=async(e,{transaction:t})=>{let r=new Set;return await this.runAll("operations",s=>e.map(o=>(r.add(z(o.oid)),s.put(o))),{mode:"readwrite",transaction:t}),Array.from(r)};this.reset=()=>this.clear("operations")}};var on=class{constructor(i,e){this.db=i;this.currentVersion=e;this.cached=null;this.get=async()=>{if(this.cached)return this.cached;let r=this.db.transaction("info","readonly").objectStore("info").get("schema"),s=await J(r);return s?(this.cached=JSON.parse(s.schema),this.cached):null};this.set=async i=>{let s=this.db.transaction("info","readwrite").objectStore("info").put({type:"schema",schema:JSON.stringify(i)});this.cached=i,await J(s)}}};var xt=class extends V{constructor({disableRebasing:e,context:t,onOperation:r}){super();this.time=new Tt;this.disableRebasing=!1;this._closing=!1;this.setContext=e=>{this.context=e};this.close=()=>{this._closing=!0};this.createTransaction=(e,t={})=>Zt(this.db,e,t.write?"readwrite":"readonly",t.abort,this.context.log);this.getAllDocumentRelatedOids=async e=>{let t=new Set,r=z(e);L(r===e,"Must be root document OID"),t.add(r);let s=this.createTransaction(["baselines","operations"]);return await Promise.all([this.baselines.iterateOverAllForDocument(r,o=>{t.add(o.oid)},{transaction:s}),this.operations.iterateOverAllOperationsForDocument(r,o=>{t.add(o.oid)},{transaction:s})]),Array.from(t)};this.getAllCollectionRelatedOids=async e=>{let t=new Set,r=this.db.transaction(["baselines","operations"],"readwrite");return await Promise.all([this.baselines.iterateOverAllForCollection(e,s=>{t.add(s.oid)},{transaction:r}),this.operations.iterateOverAllOperationsForCollection(e,s=>{t.add(s.oid)},{transaction:r})]),Array.from(t)};this.getDocumentSnapshot=async(e,t={})=>{let r=z(e);L(r===e,"Must be root document OID");let s=this.db.transaction(["baselines","operations"],"readwrite"),o=await this.baselines.getAllForDocument(r,{transaction:s}),a=new Map;for(let d of o)d.snapshot&&$(d.snapshot,d.oid),a.set(d.oid,d.snapshot);await this.operations.iterateOverAllOperationsForDocument(r,d=>{let m=a.get(d.oid)||void 0,v=Ue(m,d.data);v&&$(v,d.oid),a.set(d.oid,v)},{transaction:s,to:t.to||this.now});let h=a.get(r);return h&&qt(h,a),h};this.getDocumentData=async(e,t)=>{let r=this.createTransaction(["baselines","operations"],t),s=[],o={};return await Promise.all([this.baselines.iterateOverAllForDocument(e,a=>{s.push(a)},{transaction:r}),this.operations.iterateOverAllOperationsForDocument(e,a=>{o[a.oid]??=[],o[a.oid].push(a)},{transaction:r})]),{baselines:s,operations:o}};this.ack=async e=>{let t=await this.localReplica.get();e>this.now||(this.emit("message",{type:"ack",replicaId:t.id,timestamp:e}),!this._closing&&(!t.ackedLogicalTime||e>t.ackedLogicalTime)&&this.localReplica.update({ackedLogicalTime:e}))};this.insertLocalOperations=async(e,t)=>{if(e.length===0)return;this.log("debug",`Inserting ${e.length} local operations`,e);for(let s of e)s.isLocal=!0;await this.operations.addOperations(e,t);let r=await this.messageCreator.createOperation({operations:e});this.emit("message",r),this.tryAutonomousRebase(),this.onOperation&&e.forEach(s=>this.onOperation(s))};this.insertRemoteOperations=async(e,t)=>{if(e.length===0)return[];this.log("debug",`Inserting ${e.length} remote operations`,e);let r=await this.operations.addOperations(e.map(s=>({...s,isLocal:!1})),t);return this.ack(e[e.length-1].timestamp),this.onOperation&&e.forEach(s=>this.onOperation(s)),r};this.insertRemoteBaselines=async(e,t)=>{if(e.length===0)return[];this.log(`Inserting ${e.length} remote baselines`),await this.baselines.setAll(e,t);let r=new Set;return e.forEach(s=>{r.add(z(s.oid))}),Array.from(r)};this.insertData=async(e,t)=>{let r=this.createTransaction(["baselines","operations"],{...t,write:!0});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._closing)return this.localReplica.update({lastSyncedLogicalTime:e})};this.lastSyncedTimestamp=async()=>(await this.localReplica.get()).lastSyncedLogicalTime;this.tryAutonomousRebase=async()=>{this.disableRebasing||(await this.localReplica.get()).lastSyncedLogicalTime||await this.runRebase(this.now)};this.runRebase=async e=>{if(this._closing)return;let t,r=new Set,s=this.createTransaction(["baselines","operations"],{write:!0}),o=0;if(await this.operations.iterateOverAllOperations(h=>{r.add(h.oid),t=h.timestamp,o++},{before:e,transaction:s}),!r.size||this._closing)return;let a=[];for(let h of r)a.push(await this.rebase(h,t||e,s));this.emit("rebase",a)};this.rebase=async(e,t,r)=>{let s=(await this.localReplica.get()).id;this.log("[",s,"]","Rebasing",e,"up to",t);let o=r||this.createTransaction(["operations","baselines"],{write:!0}),a=await this.baselines.get(e,{transaction:o}),h=a?.snapshot||void 0,d=0,m=[];await this.operations.iterateOverAllOperationsForEntity(e,(b,D)=>{(!a||b.timestamp>a.timestamp)&&(h=Ue(h,b.data,m)),d++,D.delete(b.oid_timestamp)},{to:t,transaction:o}),h&&$(h,e);let v={oid:e,snapshot:h,timestamp:t};if(v.snapshot?await this.baselines.set(v,{transaction:o}):await this.baselines.delete(e,{transaction:o}),this.log("debug","successfully rebased",e,"up to",t,":",h,"and deleted",d,"operations"),m.length){let b=m.filter(be);b.length&&this.emit("filesDeleted",b)}return v};this.reset=async()=>{await this.operations.reset(),await this.baselines.reset(),await this.localReplica.reset()};this.updateSchema=async(e,t)=>{let r=await this.schema.get();if(r&&t===r.version&&r.version===e.version&&JSON.stringify(r)!==JSON.stringify(e))throw console.error(`Schema mismatch for version ${e.version}
|
|
4
|
+
`)},_domwindow:function(){return p("domwindow")},_bigint:function(l){return p("bigint:"+l.toString())},_process:function(){return p("process")},_timer:function(){return p("timer")},_pipe:function(){return p("pipe")},_tcp:function(){return p("tcp")},_udp:function(){return p("udp")},_tty:function(){return p("tty")},_statwatcher:function(){return p("statwatcher")},_securecontext:function(){return p("securecontext")},_connection:function(){return p("connection")},_zlib:function(){return p("zlib")},_context:function(){return p("context")},_nodescript:function(){return p("nodescript")},_httpparser:function(){return p("httpparser")},_dataview:function(){return p("dataview")},_signal:function(){return p("signal")},_fsevent:function(){return p("fsevent")},_tlswrap:function(){return p("tlswrap")}}}function R(){return{buf:"",write:function(y){this.buf+=y},end:function(y){this.buf+=y},read:function(){return this.buf}}}e.writeToStream=function(y,D,f){return f===void 0&&(f=D,D={}),O(D=_(y,D),f).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,o,s,a,u,d,m,S){(function(b){"use strict";var C=typeof Uint8Array<"u"?Uint8Array:Array,w="+".charCodeAt(0),v="/".charCodeAt(0),_="0".charCodeAt(0),I="a".charCodeAt(0),O="A".charCodeAt(0),R="-".charCodeAt(0),y="_".charCodeAt(0);function D(f){return f=f.charCodeAt(0),f===w||f===R?62:f===v||f===y?63:f<_?-1:f<_+10?f-_+26+26:f<O+26?f-O:f<I+26?f-I+26:void 0}b.toByteArray=function(f){var p,l;if(0<f.length%4)throw new Error("Invalid string. Length must be a multiple of 4");var x=f.length,x=f.charAt(x-2)==="="?2:f.charAt(x-1)==="="?1:0,E=new C(3*f.length/4-x),M=0<x?f.length-4:f.length,k=0;function j(B){E[k++]=B}for(p=0;p<M;p+=4,0)j((16711680&(l=D(f.charAt(p))<<18|D(f.charAt(p+1))<<12|D(f.charAt(p+2))<<6|D(f.charAt(p+3))))>>16),j((65280&l)>>8),j(255&l);return x==2?j(255&(l=D(f.charAt(p))<<2|D(f.charAt(p+1))>>4)):x==1&&(j((l=D(f.charAt(p))<<10|D(f.charAt(p+1))<<4|D(f.charAt(p+2))>>2)>>8&255),j(255&l)),E},b.fromByteArray=function(f){var p,l,x,E,M=f.length%3,k="";function j(B){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(B)}for(p=0,x=f.length-M;p<x;p+=3)l=(f[p]<<16)+(f[p+1]<<8)+f[p+2],k+=j((E=l)>>18&63)+j(E>>12&63)+j(E>>6&63)+j(63&E);switch(M){case 1:k=(k+=j((l=f[f.length-1])>>2))+j(l<<4&63)+"==";break;case 2:k=(k=(k+=j((l=(f[f.length-2]<<8)+f[f.length-1])>>10))+j(l>>4&63))+j(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,w,s,a,u,d,m,S){var b=n("base64-js"),C=n("ieee754");function w(c,h,g){if(!(this instanceof w))return new w(c,h,g);var A,P,T,U,W=typeof c;if(h==="base64"&&W=="string")for(c=(U=c).trim?U.trim():U.replace(/^\s+|\s+$/g,"");c.length%4!=0;)c+="=";if(W=="number")A=te(c);else if(W=="string")A=w.byteLength(c,h);else{if(W!="object")throw new Error("First argument needs to be a number, array or string.");A=te(c.length)}if(w._useTypedArrays?P=w._augment(new Uint8Array(A)):((P=this).length=A,P._isBuffer=!0),w._useTypedArrays&&typeof c.byteLength=="number")P._set(c);else if(H(U=c)||w.isBuffer(U)||U&&typeof U=="object"&&typeof U.length=="number")for(T=0;T<A;T++)w.isBuffer(c)?P[T]=c.readUInt8(T):P[T]=c[T];else if(W=="string")P.write(c,0,h);else if(W=="number"&&!w._useTypedArrays&&!g)for(T=0;T<A;T++)P[T]=0;return P}function v(c,h,g,A){return w._charsWritten=Rt(function(P){for(var T=[],U=0;U<P.length;U++)T.push(255&P.charCodeAt(U));return T}(h),c,g,A)}function _(c,h,g,A){return w._charsWritten=Rt(function(P){for(var T,U,W=[],X=0;X<P.length;X++)U=P.charCodeAt(X),T=U>>8,U=U%256,W.push(U),W.push(T);return W}(h),c,g,A)}function I(c,h,g){var A="";g=Math.min(c.length,g);for(var P=h;P<g;P++)A+=String.fromCharCode(c[P]);return A}function O(c,h,g,T){T||(F(typeof g=="boolean","missing or invalid endian"),F(h!=null,"missing offset"),F(h+1<c.length,"Trying to read beyond buffer length"));var P,T=c.length;if(!(T<=h))return g?(P=c[h],h+1<T&&(P|=c[h+1]<<8)):(P=c[h]<<8,h+1<T&&(P|=c[h+1])),P}function R(c,h,g,T){T||(F(typeof g=="boolean","missing or invalid endian"),F(h!=null,"missing offset"),F(h+3<c.length,"Trying to read beyond buffer length"));var P,T=c.length;if(!(T<=h))return g?(h+2<T&&(P=c[h+2]<<16),h+1<T&&(P|=c[h+1]<<8),P|=c[h],h+3<T&&(P+=c[h+3]<<24>>>0)):(h+1<T&&(P=c[h+1]<<16),h+2<T&&(P|=c[h+2]<<8),h+3<T&&(P|=c[h+3]),P+=c[h]<<24>>>0),P}function y(c,h,g,A){if(A||(F(typeof g=="boolean","missing or invalid endian"),F(h!=null,"missing offset"),F(h+1<c.length,"Trying to read beyond buffer length")),!(c.length<=h))return A=O(c,h,g,!0),32768&A?-1*(65535-A+1):A}function D(c,h,g,A){if(A||(F(typeof g=="boolean","missing or invalid endian"),F(h!=null,"missing offset"),F(h+3<c.length,"Trying to read beyond buffer length")),!(c.length<=h))return A=R(c,h,g,!0),2147483648&A?-1*(4294967295-A+1):A}function f(c,h,g,A){return A||(F(typeof g=="boolean","missing or invalid endian"),F(h+3<c.length,"Trying to read beyond buffer length")),C.read(c,h,g,23,4)}function p(c,h,g,A){return A||(F(typeof g=="boolean","missing or invalid endian"),F(h+7<c.length,"Trying to read beyond buffer length")),C.read(c,h,g,52,8)}function l(c,h,g,A,P){if(P||(F(h!=null,"missing value"),F(typeof A=="boolean","missing or invalid endian"),F(g!=null,"missing offset"),F(g+1<c.length,"trying to write beyond buffer length"),Qn(h,65535)),P=c.length,!(P<=g))for(var T=0,U=Math.min(P-g,2);T<U;T++)c[g+T]=(h&255<<8*(A?T:1-T))>>>8*(A?T:1-T)}function x(c,h,g,A,P){if(P||(F(h!=null,"missing value"),F(typeof A=="boolean","missing or invalid endian"),F(g!=null,"missing offset"),F(g+3<c.length,"trying to write beyond buffer length"),Qn(h,4294967295)),P=c.length,!(P<=g))for(var T=0,U=Math.min(P-g,4);T<U;T++)c[g+T]=h>>>8*(A?T:3-T)&255}function E(c,h,g,A,P){P||(F(h!=null,"missing value"),F(typeof A=="boolean","missing or invalid endian"),F(g!=null,"missing offset"),F(g+1<c.length,"Trying to write beyond buffer length"),Jn(h,32767,-32768)),c.length<=g||l(c,0<=h?h:65535+h+1,g,A,P)}function M(c,h,g,A,P){P||(F(h!=null,"missing value"),F(typeof A=="boolean","missing or invalid endian"),F(g!=null,"missing offset"),F(g+3<c.length,"Trying to write beyond buffer length"),Jn(h,2147483647,-2147483648)),c.length<=g||x(c,0<=h?h:4294967295+h+1,g,A,P)}function k(c,h,g,A,P){P||(F(h!=null,"missing value"),F(typeof A=="boolean","missing or invalid endian"),F(g!=null,"missing offset"),F(g+3<c.length,"Trying to write beyond buffer length"),Zi(h,34028234663852886e22,-34028234663852886e22)),c.length<=g||C.write(c,h,g,A,23,4)}function j(c,h,g,A,P){P||(F(h!=null,"missing value"),F(typeof A=="boolean","missing or invalid endian"),F(g!=null,"missing offset"),F(g+7<c.length,"Trying to write beyond buffer length"),Zi(h,17976931348623157e292,-17976931348623157e292)),c.length<=g||C.write(c,h,g,A,52,8)}e.Buffer=w,e.SlowBuffer=w,e.INSPECT_MAX_BYTES=50,w.poolSize=8192,w._useTypedArrays=function(){try{var c=new ArrayBuffer(0),h=new Uint8Array(c);return h.foo=function(){return 42},h.foo()===42&&typeof h.subarray=="function"}catch{return!1}}(),w.isEncoding=function(c){switch(String(c).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},w.isBuffer=function(c){return!(c==null||!c._isBuffer)},w.byteLength=function(c,h){var g;switch(c+="",h||"utf8"){case"hex":g=c.length/2;break;case"utf8":case"utf-8":g=Ee(c).length;break;case"ascii":case"binary":case"raw":g=c.length;break;case"base64":g=Yi(c).length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":g=2*c.length;break;default:throw new Error("Unknown encoding")}return g},w.concat=function(c,h){if(F(H(c),`Usage: Buffer.concat(list, [totalLength])
|
|
5
|
+
list should be an Array.`),c.length===0)return new w(0);if(c.length===1)return c[0];if(typeof h!="number")for(P=h=0;P<c.length;P++)h+=c[P].length;for(var g=new w(h),A=0,P=0;P<c.length;P++){var T=c[P];T.copy(g,A),A+=T.length}return g},w.prototype.write=function(c,h,g,A){isFinite(h)?isFinite(g)||(A=g,g=void 0):(X=A,A=h,h=g,g=X),h=Number(h)||0;var P,T,U,W,X=this.length-h;switch((!g||X<(g=Number(g)))&&(g=X),A=String(A||"utf8").toLowerCase()){case"hex":P=function(be,ie,re,Z){re=Number(re)||0;var G=be.length-re;(!Z||G<(Z=Number(Z)))&&(Z=G),F((G=ie.length)%2==0,"Invalid hex string"),G/2<Z&&(Z=G/2);for(var Ge=0;Ge<Z;Ge++){var er=parseInt(ie.substr(2*Ge,2),16);F(!isNaN(er),"Invalid hex string"),be[re+Ge]=er}return w._charsWritten=2*Ge,Ge}(this,c,h,g);break;case"utf8":case"utf-8":T=this,U=h,W=g,P=w._charsWritten=Rt(Ee(c),T,U,W);break;case"ascii":case"binary":P=v(this,c,h,g);break;case"base64":T=this,U=h,W=g,P=w._charsWritten=Rt(Yi(c),T,U,W);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":P=_(this,c,h,g);break;default:throw new Error("Unknown encoding")}return P},w.prototype.toString=function(c,h,g){var A,P,T,U,W=this;if(c=String(c||"utf8").toLowerCase(),h=Number(h)||0,(g=g!==void 0?Number(g):W.length)===h)return"";switch(c){case"hex":A=function(X,be,ie){var re=X.length;(!be||be<0)&&(be=0),(!ie||ie<0||re<ie)&&(ie=re);for(var Z="",G=be;G<ie;G++)Z+=K(X[G]);return Z}(W,h,g);break;case"utf8":case"utf-8":A=function(X,be,ie){var re="",Z="";ie=Math.min(X.length,ie);for(var G=be;G<ie;G++)X[G]<=127?(re+=Xi(Z)+String.fromCharCode(X[G]),Z=""):Z+="%"+X[G].toString(16);return re+Xi(Z)}(W,h,g);break;case"ascii":case"binary":A=I(W,h,g);break;case"base64":P=W,U=g,A=(T=h)===0&&U===P.length?b.fromByteArray(P):b.fromByteArray(P.slice(T,U));break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":A=function(X,be,ie){for(var re=X.slice(be,ie),Z="",G=0;G<re.length;G+=2)Z+=String.fromCharCode(re[G]+256*re[G+1]);return Z}(W,h,g);break;default:throw new Error("Unknown encoding")}return A},w.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},w.prototype.copy=function(c,h,g,A){if(h=h||0,(A=A||A===0?A:this.length)!==(g=g||0)&&c.length!==0&&this.length!==0){F(g<=A,"sourceEnd < sourceStart"),F(0<=h&&h<c.length,"targetStart out of bounds"),F(0<=g&&g<this.length,"sourceStart out of bounds"),F(0<=A&&A<=this.length,"sourceEnd out of bounds"),A>this.length&&(A=this.length);var P=(A=c.length-h<A-g?c.length-h+g:A)-g;if(P<100||!w._useTypedArrays)for(var T=0;T<P;T++)c[T+h]=this[T+g];else c._set(this.subarray(g,g+P),h)}},w.prototype.slice=function(c,h){var g=this.length;if(c=q(c,g,0),h=q(h,g,g),w._useTypedArrays)return w._augment(this.subarray(c,h));for(var A=h-c,P=new w(A,void 0,!0),T=0;T<A;T++)P[T]=this[T+c];return P},w.prototype.get=function(c){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(c)},w.prototype.set=function(c,h){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(c,h)},w.prototype.readUInt8=function(c,h){if(h||(F(c!=null,"missing offset"),F(c<this.length,"Trying to read beyond buffer length")),!(c>=this.length))return this[c]},w.prototype.readUInt16LE=function(c,h){return O(this,c,!0,h)},w.prototype.readUInt16BE=function(c,h){return O(this,c,!1,h)},w.prototype.readUInt32LE=function(c,h){return R(this,c,!0,h)},w.prototype.readUInt32BE=function(c,h){return R(this,c,!1,h)},w.prototype.readInt8=function(c,h){if(h||(F(c!=null,"missing offset"),F(c<this.length,"Trying to read beyond buffer length")),!(c>=this.length))return 128&this[c]?-1*(255-this[c]+1):this[c]},w.prototype.readInt16LE=function(c,h){return y(this,c,!0,h)},w.prototype.readInt16BE=function(c,h){return y(this,c,!1,h)},w.prototype.readInt32LE=function(c,h){return D(this,c,!0,h)},w.prototype.readInt32BE=function(c,h){return D(this,c,!1,h)},w.prototype.readFloatLE=function(c,h){return f(this,c,!0,h)},w.prototype.readFloatBE=function(c,h){return f(this,c,!1,h)},w.prototype.readDoubleLE=function(c,h){return p(this,c,!0,h)},w.prototype.readDoubleBE=function(c,h){return p(this,c,!1,h)},w.prototype.writeUInt8=function(c,h,g){g||(F(c!=null,"missing value"),F(h!=null,"missing offset"),F(h<this.length,"trying to write beyond buffer length"),Qn(c,255)),h>=this.length||(this[h]=c)},w.prototype.writeUInt16LE=function(c,h,g){l(this,c,h,!0,g)},w.prototype.writeUInt16BE=function(c,h,g){l(this,c,h,!1,g)},w.prototype.writeUInt32LE=function(c,h,g){x(this,c,h,!0,g)},w.prototype.writeUInt32BE=function(c,h,g){x(this,c,h,!1,g)},w.prototype.writeInt8=function(c,h,g){g||(F(c!=null,"missing value"),F(h!=null,"missing offset"),F(h<this.length,"Trying to write beyond buffer length"),Jn(c,127,-128)),h>=this.length||(0<=c?this.writeUInt8(c,h,g):this.writeUInt8(255+c+1,h,g))},w.prototype.writeInt16LE=function(c,h,g){E(this,c,h,!0,g)},w.prototype.writeInt16BE=function(c,h,g){E(this,c,h,!1,g)},w.prototype.writeInt32LE=function(c,h,g){M(this,c,h,!0,g)},w.prototype.writeInt32BE=function(c,h,g){M(this,c,h,!1,g)},w.prototype.writeFloatLE=function(c,h,g){k(this,c,h,!0,g)},w.prototype.writeFloatBE=function(c,h,g){k(this,c,h,!1,g)},w.prototype.writeDoubleLE=function(c,h,g){j(this,c,h,!0,g)},w.prototype.writeDoubleBE=function(c,h,g){j(this,c,h,!1,g)},w.prototype.fill=function(c,h,g){if(h=h||0,g=g||this.length,F(typeof(c=typeof(c=c||0)=="string"?c.charCodeAt(0):c)=="number"&&!isNaN(c),"value is not a number"),F(h<=g,"end < start"),g!==h&&this.length!==0){F(0<=h&&h<this.length,"start out of bounds"),F(0<=g&&g<=this.length,"end out of bounds");for(var A=h;A<g;A++)this[A]=c}},w.prototype.inspect=function(){for(var c=[],h=this.length,g=0;g<h;g++)if(c[g]=K(this[g]),g===e.INSPECT_MAX_BYTES){c[g+1]="...";break}return"<Buffer "+c.join(" ")+">"},w.prototype.toArrayBuffer=function(){if(typeof Uint8Array>"u")throw new Error("Buffer.toArrayBuffer not supported in this browser");if(w._useTypedArrays)return new w(this).buffer;for(var c=new Uint8Array(this.length),h=0,g=c.length;h<g;h+=1)c[h]=this[h];return c.buffer};var B=w.prototype;function q(c,h,g){return typeof c!="number"?g:h<=(c=~~c)?h:0<=c||0<=(c+=h)?c:0}function te(c){return(c=~~Math.ceil(+c))<0?0:c}function H(c){return(Array.isArray||function(h){return Object.prototype.toString.call(h)==="[object Array]"})(c)}function K(c){return c<16?"0"+c.toString(16):c.toString(16)}function Ee(c){for(var h=[],g=0;g<c.length;g++){var A=c.charCodeAt(g);if(A<=127)h.push(c.charCodeAt(g));else for(var P=g,T=(55296<=A&&A<=57343&&g++,encodeURIComponent(c.slice(P,g+1)).substr(1).split("%")),U=0;U<T.length;U++)h.push(parseInt(T[U],16))}return h}function Yi(c){return b.toByteArray(c)}function Rt(c,h,g,A){for(var P=0;P<A&&!(P+g>=h.length||P>=c.length);P++)h[P+g]=c[P];return P}function Xi(c){try{return decodeURIComponent(c)}catch{return String.fromCharCode(65533)}}function Qn(c,h){F(typeof c=="number","cannot write a non-number as a number"),F(0<=c,"specified a negative value for writing an unsigned value"),F(c<=h,"value is larger than maximum value for type"),F(Math.floor(c)===c,"value has a fractional component")}function Jn(c,h,g){F(typeof c=="number","cannot write a non-number as a number"),F(c<=h,"value larger than maximum allowed value"),F(g<=c,"value smaller than minimum allowed value"),F(Math.floor(c)===c,"value has a fractional component")}function Zi(c,h,g){F(typeof c=="number","cannot write a non-number as a number"),F(c<=h,"value larger than maximum allowed value"),F(g<=c,"value smaller than minimum allowed value")}function F(c,h){if(!c)throw new Error(h||"Failed assertion")}w._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,b,s,a,u,d,m,S){var b=n("buffer").Buffer,C=4,w=new b(C);w.fill(0),i.exports={hash:function(v,_,I,O){for(var R=_(function(l,x){l.length%C!=0&&(E=l.length+(C-l.length%C),l=b.concat([l,w],E));for(var E,M=[],k=x?l.readInt32BE:l.readInt32LE,j=0;j<l.length;j+=C)M.push(k.call(l,j));return M}(v=b.isBuffer(v)?v:new b(v),O),8*v.length),_=O,y=new b(I),D=_?y.writeInt32BE:y.writeInt32LE,f=0;f<R.length;f++)D.call(y,R[f],4*f,!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,b,s,a,u,d,m,S){var b=n("buffer").Buffer,C=n("./sha"),w=n("./sha256"),v=n("./rng"),_={sha1:C,sha256:w,md5:n("./md5")},I=64,O=new b(I);function R(l,x){var E=_[l=l||"sha1"],M=[];return E||y("algorithm:",l,"is not yet supported"),{update:function(k){return b.isBuffer(k)||(k=new b(k)),M.push(k),k.length,this},digest:function(k){var j=b.concat(M),j=x?function(B,q,te){b.isBuffer(q)||(q=new b(q)),b.isBuffer(te)||(te=new b(te)),q.length>I?q=B(q):q.length<I&&(q=b.concat([q,O],I));for(var H=new b(I),K=new b(I),Ee=0;Ee<I;Ee++)H[Ee]=54^q[Ee],K[Ee]=92^q[Ee];return te=B(b.concat([H,te])),B(b.concat([K,te]))}(E,x,j):E(j);return M=null,k?j.toString(k):j}}}function y(){var l=[].slice.call(arguments).join(" ");throw new Error([l,"we accept pull requests","http://github.com/dominictarr/crypto-browserify"].join(`
|
|
6
|
+
`))}O.fill(0),e.createHash=function(l){return R(l)},e.createHmac=R,e.randomBytes=function(l,x){if(!x||!x.call)return new b(v(l));try{x.call(this,void 0,new b(v(l)))}catch(E){x(E)}};var D,f=["createCredentials","createCipher","createCipheriv","createDecipher","createDecipheriv","createSign","createVerify","createDiffieHellman","pbkdf2"],p=function(l){e[l]=function(){y("sorry,",l,"is not implemented yet")}};for(D in f)p(f[D],D)}).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,o,s,a,u,d,m,S){var b=n("./helpers");function C(y,D){y[D>>5]|=128<<D%32,y[14+(D+64>>>9<<4)]=D;for(var f=1732584193,p=-271733879,l=-1732584194,x=271733878,E=0;E<y.length;E+=16){var M=f,k=p,j=l,B=x,f=v(f,p,l,x,y[E+0],7,-680876936),x=v(x,f,p,l,y[E+1],12,-389564586),l=v(l,x,f,p,y[E+2],17,606105819),p=v(p,l,x,f,y[E+3],22,-1044525330);f=v(f,p,l,x,y[E+4],7,-176418897),x=v(x,f,p,l,y[E+5],12,1200080426),l=v(l,x,f,p,y[E+6],17,-1473231341),p=v(p,l,x,f,y[E+7],22,-45705983),f=v(f,p,l,x,y[E+8],7,1770035416),x=v(x,f,p,l,y[E+9],12,-1958414417),l=v(l,x,f,p,y[E+10],17,-42063),p=v(p,l,x,f,y[E+11],22,-1990404162),f=v(f,p,l,x,y[E+12],7,1804603682),x=v(x,f,p,l,y[E+13],12,-40341101),l=v(l,x,f,p,y[E+14],17,-1502002290),f=_(f,p=v(p,l,x,f,y[E+15],22,1236535329),l,x,y[E+1],5,-165796510),x=_(x,f,p,l,y[E+6],9,-1069501632),l=_(l,x,f,p,y[E+11],14,643717713),p=_(p,l,x,f,y[E+0],20,-373897302),f=_(f,p,l,x,y[E+5],5,-701558691),x=_(x,f,p,l,y[E+10],9,38016083),l=_(l,x,f,p,y[E+15],14,-660478335),p=_(p,l,x,f,y[E+4],20,-405537848),f=_(f,p,l,x,y[E+9],5,568446438),x=_(x,f,p,l,y[E+14],9,-1019803690),l=_(l,x,f,p,y[E+3],14,-187363961),p=_(p,l,x,f,y[E+8],20,1163531501),f=_(f,p,l,x,y[E+13],5,-1444681467),x=_(x,f,p,l,y[E+2],9,-51403784),l=_(l,x,f,p,y[E+7],14,1735328473),f=I(f,p=_(p,l,x,f,y[E+12],20,-1926607734),l,x,y[E+5],4,-378558),x=I(x,f,p,l,y[E+8],11,-2022574463),l=I(l,x,f,p,y[E+11],16,1839030562),p=I(p,l,x,f,y[E+14],23,-35309556),f=I(f,p,l,x,y[E+1],4,-1530992060),x=I(x,f,p,l,y[E+4],11,1272893353),l=I(l,x,f,p,y[E+7],16,-155497632),p=I(p,l,x,f,y[E+10],23,-1094730640),f=I(f,p,l,x,y[E+13],4,681279174),x=I(x,f,p,l,y[E+0],11,-358537222),l=I(l,x,f,p,y[E+3],16,-722521979),p=I(p,l,x,f,y[E+6],23,76029189),f=I(f,p,l,x,y[E+9],4,-640364487),x=I(x,f,p,l,y[E+12],11,-421815835),l=I(l,x,f,p,y[E+15],16,530742520),f=O(f,p=I(p,l,x,f,y[E+2],23,-995338651),l,x,y[E+0],6,-198630844),x=O(x,f,p,l,y[E+7],10,1126891415),l=O(l,x,f,p,y[E+14],15,-1416354905),p=O(p,l,x,f,y[E+5],21,-57434055),f=O(f,p,l,x,y[E+12],6,1700485571),x=O(x,f,p,l,y[E+3],10,-1894986606),l=O(l,x,f,p,y[E+10],15,-1051523),p=O(p,l,x,f,y[E+1],21,-2054922799),f=O(f,p,l,x,y[E+8],6,1873313359),x=O(x,f,p,l,y[E+15],10,-30611744),l=O(l,x,f,p,y[E+6],15,-1560198380),p=O(p,l,x,f,y[E+13],21,1309151649),f=O(f,p,l,x,y[E+4],6,-145523070),x=O(x,f,p,l,y[E+11],10,-1120210379),l=O(l,x,f,p,y[E+2],15,718787259),p=O(p,l,x,f,y[E+9],21,-343485551),f=R(f,M),p=R(p,k),l=R(l,j),x=R(x,B)}return Array(f,p,l,x)}function w(y,D,f,p,l,x){return R((D=R(R(D,y),R(p,x)))<<l|D>>>32-l,f)}function v(y,D,f,p,l,x,E){return w(D&f|~D&p,y,D,l,x,E)}function _(y,D,f,p,l,x,E){return w(D&p|f&~p,y,D,l,x,E)}function I(y,D,f,p,l,x,E){return w(D^f^p,y,D,l,x,E)}function O(y,D,f,p,l,x,E){return w(f^(D|~p),y,D,l,x,E)}function R(y,D){var f=(65535&y)+(65535&D);return(y>>16)+(D>>16)+(f>>16)<<16|65535&f}i.exports=function(y){return b.hash(y,C,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,o,s,a,u,d,m,S){var b;i.exports=b||function(C){for(var w,v=new Array(C),_=0;_<C;_++)!(3&_)&&(w=4294967296*Math.random()),v[_]=w>>>((3&_)<<3)&255;return v}}).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,o,s,a,u,d,m,S){var b=n("./helpers");function C(_,I){_[I>>5]|=128<<24-I%32,_[15+(I+64>>9<<4)]=I;for(var O,R,y,D=Array(80),f=1732584193,p=-271733879,l=-1732584194,x=271733878,E=-1009589776,M=0;M<_.length;M+=16){for(var k=f,j=p,B=l,q=x,te=E,H=0;H<80;H++){D[H]=H<16?_[M+H]:v(D[H-3]^D[H-8]^D[H-14]^D[H-16],1);var K=w(w(v(f,5),(K=p,R=l,y=x,(O=H)<20?K&R|~K&y:!(O<40)&&O<60?K&R|K&y|R&y:K^R^y)),w(w(E,D[H]),(O=H)<20?1518500249:O<40?1859775393:O<60?-1894007588:-899497514)),E=x,x=l,l=v(p,30),p=f,f=K}f=w(f,k),p=w(p,j),l=w(l,B),x=w(x,q),E=w(E,te)}return Array(f,p,l,x,E)}function w(_,I){var O=(65535&_)+(65535&I);return(_>>16)+(I>>16)+(O>>16)<<16|65535&O}function v(_,I){return _<<I|_>>>32-I}i.exports=function(_){return b.hash(_,C,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,o,s,a,u,d,m,S){function b(I,O){var R=(65535&I)+(65535&O);return(I>>16)+(O>>16)+(R>>16)<<16|65535&R}function C(I,O){var R,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),D=new Array(1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225),f=new Array(64);I[O>>5]|=128<<24-O%32,I[15+(O+64>>9<<4)]=O;for(var p,l,x=0;x<I.length;x+=16){for(var E=D[0],M=D[1],k=D[2],j=D[3],B=D[4],q=D[5],te=D[6],H=D[7],K=0;K<64;K++)f[K]=K<16?I[K+x]:b(b(b((l=f[K-2],v(l,17)^v(l,19)^_(l,10)),f[K-7]),(l=f[K-15],v(l,7)^v(l,18)^_(l,3))),f[K-16]),R=b(b(b(b(H,v(l=B,6)^v(l,11)^v(l,25)),B&q^~B&te),y[K]),f[K]),p=b(v(p=E,2)^v(p,13)^v(p,22),E&M^E&k^M&k),H=te,te=q,q=B,B=b(j,R),j=k,k=M,M=E,E=b(R,p);D[0]=b(E,D[0]),D[1]=b(M,D[1]),D[2]=b(k,D[2]),D[3]=b(j,D[3]),D[4]=b(B,D[4]),D[5]=b(q,D[5]),D[6]=b(te,D[6]),D[7]=b(H,D[7])}return D}var w=n("./helpers"),v=function(I,O){return I>>>O|I<<32-O},_=function(I,O){return I>>>O};i.exports=function(I){return w.hash(I,C,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,o,s,a,u,d,m,S){e.read=function(b,C,w,v,x){var I,O,R=8*x-v-1,y=(1<<R)-1,D=y>>1,f=-7,p=w?x-1:0,l=w?-1:1,x=b[C+p];for(p+=l,I=x&(1<<-f)-1,x>>=-f,f+=R;0<f;I=256*I+b[C+p],p+=l,f-=8);for(O=I&(1<<-f)-1,I>>=-f,f+=v;0<f;O=256*O+b[C+p],p+=l,f-=8);if(I===0)I=1-D;else{if(I===y)return O?NaN:1/0*(x?-1:1);O+=Math.pow(2,v),I-=D}return(x?-1:1)*O*Math.pow(2,I-v)},e.write=function(b,C,w,v,_,E){var O,R,y=8*E-_-1,D=(1<<y)-1,f=D>>1,p=_===23?Math.pow(2,-24)-Math.pow(2,-77):0,l=v?0:E-1,x=v?1:-1,E=C<0||C===0&&1/C<0?1:0;for(C=Math.abs(C),isNaN(C)||C===1/0?(R=isNaN(C)?1:0,O=D):(O=Math.floor(Math.log(C)/Math.LN2),C*(v=Math.pow(2,-O))<1&&(O--,v*=2),2<=(C+=1<=O+f?p/v:p*Math.pow(2,1-f))*v&&(O++,v/=2),D<=O+f?(R=0,O=D):1<=O+f?(R=(C*v-1)*Math.pow(2,_),O+=f):(R=C*Math.pow(2,f-1)*Math.pow(2,_),O=0));8<=_;b[w+l]=255&R,l+=x,R/=256,_-=8);for(O=O<<_|R,y+=_;0<y;b[w+l]=255&O,l+=x,O/=256,y-=8);b[w+l-x]|=128*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/ieee754/index.js","/node_modules/gulp-browserify/node_modules/ieee754")},{buffer:3,lYpoI2:11}],11:[function(n,i,e){(function(t,r,o,s,a,u,d,m,S){var b,C,w;function v(){}(t=i.exports={}).nextTick=(C=typeof window<"u"&&window.setImmediate,w=typeof window<"u"&&window.postMessage&&window.addEventListener,C?function(_){return window.setImmediate(_)}:w?(b=[],window.addEventListener("message",function(_){var I=_.source;I!==window&&I!==null||_.data!=="process-tick"||(_.stopPropagation(),0<b.length&&b.shift()())},!0),function(_){b.push(_),window.postMessage("process-tick","*")}):function(_){setTimeout(_,0)}),t.title="browser",t.browser=!0,t.env={},t.argv=[],t.on=v,t.addListener=v,t.once=v,t.off=v,t.removeListener=v,t.removeAllListeners=v,t.emit=v,t.binding=function(_){throw new Error("process.binding is not supported")},t.cwd=function(){return"/"},t.chdir=function(_){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 We={};tr(We,{__addDisposableResource:()=>Ro,__assign:()=>vn,__asyncDelegator:()=>So,__asyncGenerator:()=>Oo,__asyncValues:()=>Io,__await:()=>ot,__awaiter:()=>go,__classPrivateFieldGet:()=>Co,__classPrivateFieldIn:()=>Ao,__classPrivateFieldSet:()=>Po,__createBinding:()=>On,__decorate:()=>ho,__disposeResources:()=>Fo,__esDecorate:()=>fa,__exportStar:()=>bo,__extends:()=>uo,__generator:()=>yo,__importDefault:()=>Eo,__importStar:()=>Do,__makeTemplateObject:()=>_o,__metadata:()=>mo,__param:()=>po,__propKey:()=>pa,__read:()=>Fi,__rest:()=>fo,__runInitializers:()=>ha,__setFunctionName:()=>ma,__spread:()=>wo,__spreadArray:()=>xo,__spreadArrays:()=>vo,__values:()=>xn,default:()=>ba});function uo(n,i){if(typeof i!="function"&&i!==null)throw new TypeError("Class extends value "+String(i)+" is not a constructor or null");Ri(n,i);function e(){this.constructor=n}n.prototype=i===null?Object.create(i):(e.prototype=i.prototype,new e)}function fo(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 ho(n,i,e,t){var r=arguments.length,o=r<3?i:t===null?t=Object.getOwnPropertyDescriptor(i,e):t,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(n,i,e,t);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(o=(r<3?s(o):r>3?s(i,e,o):s(i,e))||o);return r>3&&o&&Object.defineProperty(i,e,o),o}function po(n,i){return function(e,t){i(e,t,n)}}function fa(n,i,e,t,r,o){function s(I){if(I!==void 0&&typeof I!="function")throw new TypeError("Function expected");return I}for(var a=t.kind,u=a==="getter"?"get":a==="setter"?"set":"value",d=!i&&n?t.static?n:n.prototype:null,m=i||(d?Object.getOwnPropertyDescriptor(d,t.name):{}),S,b=!1,C=e.length-1;C>=0;C--){var w={};for(var v in t)w[v]=v==="access"?{}:t[v];for(var v in t.access)w.access[v]=t.access[v];w.addInitializer=function(I){if(b)throw new TypeError("Cannot add initializers after decoration has completed");o.push(s(I||null))};var _=(0,e[C])(a==="accessor"?{get:m.get,set:m.set}:m[u],w);if(a==="accessor"){if(_===void 0)continue;if(_===null||typeof _!="object")throw new TypeError("Object expected");(S=s(_.get))&&(m.get=S),(S=s(_.set))&&(m.set=S),(S=s(_.init))&&r.unshift(S)}else(S=s(_))&&(a==="field"?r.unshift(S):m[u]=S)}d&&Object.defineProperty(d,t.name,m),b=!0}function ha(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 pa(n){return typeof n=="symbol"?n:"".concat(n)}function ma(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 mo(n,i){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,i)}function go(n,i,e,t){function r(o){return o instanceof e?o:new e(function(s){s(o)})}return new(e||(e=Promise))(function(o,s){function a(m){try{d(t.next(m))}catch(S){s(S)}}function u(m){try{d(t.throw(m))}catch(S){s(S)}}function d(m){m.done?o(m.value):r(m.value).then(a,u)}d((t=t.apply(n,i||[])).next())})}function yo(n,i){var e={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},t,r,o,s;return s={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function a(d){return function(m){return u([d,m])}}function u(d){if(t)throw new TypeError("Generator is already executing.");for(;s&&(s=0,d[0]&&(e=0)),e;)try{if(t=1,r&&(o=d[0]&2?r.return:d[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,d[1])).done)return o;switch(r=0,o&&(d=[d[0]&2,o.value]),d[0]){case 0:case 1:o=d;break;case 4:return e.label++,{value:d[1],done:!1};case 5:e.label++,r=d[1],d=[0];continue;case 7:d=e.ops.pop(),e.trys.pop();continue;default:if(o=e.trys,!(o=o.length>0&&o[o.length-1])&&(d[0]===6||d[0]===2)){e=0;continue}if(d[0]===3&&(!o||d[1]>o[0]&&d[1]<o[3])){e.label=d[1];break}if(d[0]===6&&e.label<o[1]){e.label=o[1],o=d;break}if(o&&e.label<o[2]){e.label=o[2],e.ops.push(d);break}o[2]&&e.ops.pop(),e.trys.pop();continue}d=i.call(n,e)}catch(m){d=[6,m],r=0}finally{t=o=0}if(d[0]&5)throw d[1];return{value:d[0]?d[1]:void 0,done:!0}}}function bo(n,i){for(var e in n)e!=="default"&&!Object.prototype.hasOwnProperty.call(i,e)&&On(i,n,e)}function xn(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 Fi(n,i){var e=typeof Symbol=="function"&&n[Symbol.iterator];if(!e)return n;var t=e.call(n),r,o=[],s;try{for(;(i===void 0||i-- >0)&&!(r=t.next()).done;)o.push(r.value)}catch(a){s={error:a}}finally{try{r&&!r.done&&(e=t.return)&&e.call(t)}finally{if(s)throw s.error}}return o}function wo(){for(var n=[],i=0;i<arguments.length;i++)n=n.concat(Fi(arguments[i]));return n}function vo(){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 o=arguments[i],s=0,a=o.length;s<a;s++,r++)t[r]=o[s];return t}function xo(n,i,e){if(e||arguments.length===2)for(var t=0,r=i.length,o;t<r;t++)(o||!(t in i))&&(o||(o=Array.prototype.slice.call(i,0,t)),o[t]=i[t]);return n.concat(o||Array.prototype.slice.call(i))}function ot(n){return this instanceof ot?(this.v=n,this):new ot(n)}function Oo(n,i,e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=e.apply(n,i||[]),r,o=[];return r={},s("next"),s("throw"),s("return"),r[Symbol.asyncIterator]=function(){return this},r;function s(b){t[b]&&(r[b]=function(C){return new Promise(function(w,v){o.push([b,C,w,v])>1||a(b,C)})})}function a(b,C){try{u(t[b](C))}catch(w){S(o[0][3],w)}}function u(b){b.value instanceof ot?Promise.resolve(b.value.v).then(d,m):S(o[0][2],b)}function d(b){a("next",b)}function m(b){a("throw",b)}function S(b,C){b(C),o.shift(),o.length&&a(o[0][0],o[0][1])}}function So(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,o){i[r]=n[r]?function(s){return(e=!e)?{value:ot(n[r](s)),done:!1}:o?o(s):s}:o}}function Io(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 xn=="function"?xn(n):n[Symbol.iterator](),e={},t("next"),t("throw"),t("return"),e[Symbol.asyncIterator]=function(){return this},e);function t(o){e[o]=n[o]&&function(s){return new Promise(function(a,u){s=n[o](s),r(a,u,s.done,s.value)})}}function r(o,s,a,u){Promise.resolve(u).then(function(d){o({value:d,done:a})},s)}}function _o(n,i){return Object.defineProperty?Object.defineProperty(n,"raw",{value:i}):n.raw=i,n}function Do(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)&&On(i,n,e);return ga(i,n),i}function Eo(n){return n&&n.__esModule?n:{default:n}}function Co(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 Po(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 Ao(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 Ro(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 Fo(n){function i(t){n.error=n.hasError?new ya(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(o){return i(o),e()})}catch(o){i(o)}}if(n.hasError)throw n.error}return e()}var Ri,vn,On,ga,ya,ba,Qe=Zo(()=>{Ri=function(n,i){return Ri=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])},Ri(n,i)};vn=function(){return vn=Object.assign||function(i){for(var e,t=1,r=arguments.length;t<r;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(i[o]=e[o])}return i},vn.apply(this,arguments)};On=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]};ga=Object.create?function(n,i){Object.defineProperty(n,"default",{enumerable:!0,value:i})}:function(n,i){n.default=i};ya=typeof SuppressedError=="function"?SuppressedError:function(n,i,e){var t=new Error(e);return t.name="SuppressedError",t.error=n,t.suppressed=i,t};ba={__extends:uo,__assign:vn,__rest:fo,__decorate:ho,__param:po,__metadata:mo,__awaiter:go,__generator:yo,__createBinding:On,__exportStar:bo,__values:xn,__read:Fi,__spread:wo,__spreadArrays:vo,__spreadArray:xo,__await:ot,__asyncGenerator:Oo,__asyncDelegator:So,__asyncValues:Io,__makeTemplateObject:_o,__importStar:Do,__importDefault:Eo,__classPrivateFieldGet:Co,__classPrivateFieldSet:Po,__classPrivateFieldIn:Ao,__addDisposableResource:Ro,__disposeResources:Fo}});var Bo=oe(To=>{"use strict";Object.defineProperty(To,"__esModule",{value:!0})});var Bi=oe(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.invokeEventHandlersAsync=De.invokeEventHandlers=De.eventHandlerSafeInvokeAsync=De.eventHandlerSafeInvoke=void 0;var ko=(Qe(),Ye(We));function Mo(n,i,e){try{return n(i,e),{succeeded:!0}}catch(t){return{error:t,succeeded:!1}}}De.eventHandlerSafeInvoke=Mo;function Ti(n,i,e){return(0,ko.__awaiter)(this,void 0,void 0,function*(){try{return yield n(i,e),{succeeded:!0}}catch(t){return{error:t,succeeded:!1}}})}De.eventHandlerSafeInvokeAsync=Ti;function wa(n,i,e,t){for(let r of n){let{succeeded:o,error:s}=Mo(r,i,e);if(!o&&t?.swallowExceptions!==!0)throw s}}De.invokeEventHandlers=wa;function va(n,i,e,t){return(0,ko.__awaiter)(this,void 0,void 0,function*(){if(t?.parallelize===!1)for(let r of n){let{succeeded:o,error:s}=yield Ti(r,i,e);if(!o&&t?.swallowExceptions!==!0)throw s}else{let r=[];for(let o of n)r.push(Ti(o,i,e).then(({succeeded:s,error:a})=>{if(!s&&t?.swallowExceptions!==!0)throw a}));yield Promise.all(r)}})}De.invokeEventHandlersAsync=va});var Uo=oe(Sn=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});Sn.TypedEvent=void 0;var xa=(Qe(),Ye(We)),jo=Bi(),Lo={swallowExceptions:!1,parallelize:!0},ki=class{constructor(){this._handlers=[]}attach(i){this._handlers.push(i)}detach(i){this.tryRemoveHandler(i)}invoke(i,e,t=Lo){(0,jo.invokeEventHandlers)(this._handlers,i,e,t)}invokeAsync(i,e,t=Lo){return(0,xa.__awaiter)(this,void 0,void 0,function*(){yield(0,jo.invokeEventHandlersAsync)(this._handlers,i,e,t)})}tryRemoveHandler(i){let e=this._handlers.findIndex(t=>t===i);e>=0&&this._handlers.splice(e,1)}};Sn.TypedEvent=ki});var ji=oe(Mi=>{"use strict";Object.defineProperty(Mi,"__esModule",{value:!0});var Oa=(Qe(),Ye(We));(0,Oa.__exportStar)(Uo(),Mi)});var Vo=oe(In=>{"use strict";Object.defineProperty(In,"__esModule",{value:!0});In.FinalizationRegistryMissingError=void 0;var Li=class extends Error{};In.FinalizationRegistryMissingError=Li});var Vi=oe(_n=>{"use strict";Object.defineProperty(_n,"__esModule",{value:!0});_n.WeakHandlerHolder=void 0;var Sa=Vo(),Ui=class{constructor(i){this._refs=[];try{this._finalizationRegistry=new FinalizationRegistry(i)}catch(e){throw e.name==="FinalizationRegistry"?new Sa.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)}};_n.WeakHandlerHolder=Ui});var No=oe(Dn=>{"use strict";Object.defineProperty(Dn,"__esModule",{value:!0});Dn.WeakEvent=void 0;var Ni=(Qe(),Ye(We)),Ia=ji(),_a=Vi(),$i=Bi(),Da={swallowExceptions:!1,parallelize:!0},zi=class{constructor(){this._handlers=[],this._handlerFinalizedEvent=new Ia.TypedEvent,this.handlerFinalizedEvent=this._handlerFinalizedEvent,this._refHolder=new _a.WeakHandlerHolder(i=>{this.onHandlerFinalizer(i)})}invoke(i,e,t){for(let r of this._handlers){let o=r?.deref();if(o){let{succeeded:s,error:a}=(0,$i.eventHandlerSafeInvoke)(o,i,e);if(!s&&t?.swallowExceptions!==!0)throw a}else this.releaseHandler(r)}}invokeAsync(i,e,t=Da){return(0,Ni.__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,Ni.__awaiter)(this,void 0,void 0,function*(){for(let r of this._handlers){let o=r?.deref();if(o){let{succeeded:s,error:a}=yield(0,$i.eventHandlerSafeInvokeAsync)(o,i,e);if(!s&&t.swallowExceptions!==!0)throw a}else this.releaseHandler(r)}})}parallelInvokeAsync(i,e,t){return(0,Ni.__awaiter)(this,void 0,void 0,function*(){let r=[];for(let o of this._handlers){let s=o?.deref();s?r.push((0,$i.eventHandlerSafeInvokeAsync)(s,i,e).then(({succeeded:a,error:u})=>{if(!a&&t.swallowExceptions!==!0)throw u})):this.releaseHandler(o)}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)}};Dn.WeakEvent=zi});var zo=oe(En=>{"use strict";Object.defineProperty(En,"__esModule",{value:!0});var $o=(Qe(),Ye(We));(0,$o.__exportStar)(Vi(),En);(0,$o.__exportStar)(No(),En)});var Ko=oe(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});var Ki=(Qe(),Ye(We));(0,Ki.__exportStar)(Bo(),Et);(0,Ki.__exportStar)(ji(),Et);(0,Ki.__exportStar)(zo(),Et)});var Gi={};tr(Gi,{Client:()=>Je,ClientDescriptor:()=>Wn,Entity:()=>fe,EntityFile:()=>ue,MigrationPathError:()=>nt,ServerSync:()=>at,Storage:()=>Je,StorageDescriptor:()=>Wn,UndoHistory:()=>He,collection:()=>xi,createDefaultMigration:()=>Oi,createMigration:()=>Si,id:()=>Ua,migrate:()=>Xt,schema:()=>bt});var br=Ue(Xe(),1),Ut=4,ut=36;function pr(n){return n.toString(ut).padStart(Ut,"0")}function ss(n){return n.toString().padStart(6,"0")}var kt=class{constructor(){this.latest={time:Date.now(),counter:0,node:as()},this.zeroCounter=0,this.now=i=>(this.latest=gr(this.latest),this.get(i,this.latest)),this.OLD_now=i=>(this.latest=gr(this.latest),ss(i)+ls(this.latest)),this.timerState=()=>this.latest,this.update=i=>{let e=i.slice(Ut);this.latest=cs(this.latest,wr(e))},this.get=(i,e)=>pr(i)+mr(e),this.zero=i=>pr(i)+mr({time:0,counter:this.zeroCounter++,node:this.latest.node}),this.getWallClockTime=ii}},Mt=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"}},ei=4,ti=7,Lt=60*1e3,dt=9;function as(){return br.default.slug().padStart(ti,"0").slice(0,ti)}function mr(n){let i=new Date(n.time).getTime().toString(ut).padStart(dt,"0"),e=n.counter.toString(ut).padStart(ei,"0"),t=n.node.padStart(ti,"0");return`${i}${e}${t}`}function gr(n){let i=Date.now(),e=Math.max(n.time,i),t=n.time===e?n.counter+1:0;if(e-i>Lt)throw new Mt(e,i,Lt);if(t>65535)throw new jt;return{time:e,counter:t,node:n.node}}function cs(n,i){let e=Date.now(),t=Math.max(e,Math.max(n.time,i.time)),r=Math.max(n.counter,i.counter),o;if(n.time===t&&i.time===t?o=r+1:n.time===t?o=n.counter+1:i.time===t?o=i.counter+1:o=0,t-e>Lt)throw new Mt(t,e,Lt);if(o>65535)throw new jt;return{time:t,counter:o,node:n.node}}function wr(n){let i=n.slice(0,dt),e=n.slice(dt,dt+ei),t=n.slice(dt+ei),r=parseInt(i,ut),o=parseInt(e,ut);if(isNaN(r)||isNaN(o))throw new Error("invalid clock format");return{time:r,counter:o,node:t}}function ls(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 yr(n){return parseInt(n.slice(0,Ut),36)}function ni(n,i){return yr(n)-yr(i)}function ii(n){return wr(n.slice(Ut)).time}function we(n){return n&&n["@@type"]==="file"}function Vt(n){return{"@@type":"file",id:n}}var Nt,ds=new Uint8Array(16);function ri(){if(!Nt&&(Nt=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!Nt))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Nt(ds)}var vr=/^(?:[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 us(n){return typeof n=="string"&&vr.test(n)}var xr=us;var ee=[];for($t=0;$t<256;++$t)ee.push(($t+256).toString(16).substr(1));var $t;function fs(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(!xr(e))throw TypeError("Stringified UUID is invalid");return e}var Or=fs;function hs(n,i,e){n=n||{};var t=n.random||(n.rng||ri)();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 Or(t)}var ft=hs;function Q(n){return Se(n)||we(n)}function Ze(n,i){return n===i?!0:!(!Q(n)||!Q(i)||n["@@type"]!==i["@@type"]||n.id!==i.id)}var Dr=Ue(_r(),1);function ps(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 ht(n){return JSON.stringify(n,ps)}function ae(n,i=!0){if(N(n)||Array.isArray(n)){let e=pe(n),t;if(Array.isArray(n))t=n.map(r=>ae(r,i));else{t={};for(let[r,o]of Object.entries(n))t[r]=ae(o,i)}return i&&e&&$(t,e),t}return n}function Be(n){return(0,Dr.default)(n)}function N(n){return n&&typeof n=="object"}function Er(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 o in r)e.push(r[o])}}return t}function L(n,i="assertion failed"){if(!n)throw new Error(i)}function zt(n=16){return ft().replace("-","").slice(0,n)}function Cr(n,i){for(let e=n.length-1;e>=0;e--)if(i(n[e]))return e;return-1}function Pr(n,i){let e;return function(...t){let r=this;clearTimeout(e),e=setTimeout(()=>n.apply(r,t),i)}}function Ar(n,i){let e=0,t;return function(...r){let o=this,s=Date.now();s-e>=i?(e=s,n.apply(o,r),clearTimeout(t)):(clearTimeout(t),t=setTimeout(()=>{e=s,n.apply(o,r)},i))}}var Ve="__@@oid_do_not_use",Ie="@@id",ms="/",mt=":",si=new WeakMap;function ne(n){let i=pe(n);return L(!!i,`Object ${JSON.stringify(n)} does not have an OID assigned to it`),i}function pe(n){var i,e;if(N(n))return(e=(i=si.get(n))!==null&&i!==void 0?i:n[Ie])!==null&&e!==void 0?e:n[Ve]}function $(n,i){return L(N(n),`Only objects can be assigned OIDs, received ${JSON.stringify(n)}`),ai(n)&&Ht(n),si.set(n,i),n}function ai(n){return!!pe(n)}function Ht(n){return si.delete(n),n}function ci(n){return n===Ie||n===Ve}function li(n,i,e){if(ai(n))return ne(n);{let t=ve(i,e);return $(n,t),t}}function Rr(n,i,e){if(ai(n)){let t=ne(n);if(Ce(t,i))return ne(n);{let r=ve(i,e);return $(n,r),r}}else{let t=ve(i,e);return $(n,t),t}}var oi={".":"˙","/":"&slash;",":":":"};function Fr(n){return n.replace(/[/]/g,oi["/"]).replace(/[:]/g,oi[":"]).replace(/[.]/g,oi["."])}function Tr(n){return n.replace(/&slash;/g,"/").replace(/:/g,":").replace(/˙/g,".")}function Y(n,i,e){let t=Fr(n)+ms+Fr(i);return e&&(t+=mt+e),t}function ve(n,i=ws){let{collection:e,id:t}=me(n);return Y(e,t,i())}function me(n){let[i,e]=n.split(mt),[t,r,...o]=i.split("/");o.length&&(r+="/"+o.join("/"));let s;return r.includes(".")?s=r.slice(0,r.indexOf(".")):s=r,{collection:Tr(t),id:Tr(s),subId:e}}function et(n,i){let e=ne(n);if(Array.isArray(n)){let t;for(let r=0;r<n.length;r++)t=n[r],N(t)&&!Q(t)&&(Rr(t,e,i),et(t,i))}else if(N(n)&&!Q(n))for(let t of Object.keys(n))N(n[t])&&!Q(n[t])&&(Rr(n[t],e,i),et(n[t],i))}function gs(n){if(N(n))return n[Ie]||n[Ve]}function ys(n){return N(n)&&(delete n[Ve],delete n[Ie]),n}function bs(n){let i=gs(n);i&&$(n,i)}function pt(n){if(bs(n),ys(n),Array.isArray(n))for(let i=0;i<n.length;i++)pt(n[i]);else if(N(n))for(let i of Object.keys(n))pt(n[i])}function Kt(n){if(Ht(n),Array.isArray(n))for(let i=0;i<n.length;i++)Kt(n[i]);else if(N(n))for(let i of Object.keys(n))Kt(n[i])}function ws(){return ft().slice(0,8)}function ce(n){return{"@@type":"ref",id:n}}function qt(n,i=new Map){if(Array.isArray(n)){let e=ne(n),t=$([],e);for(let r=0;r<n.length;r++){let o=n[r];if(N(o)){if(Se(o))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(we(o)){t[r]=o;continue}else{let s=ne(o);t[r]=ce(s),qt(o,i)}}else t[r]=o}i.set(e,t)}else if(N(n)&&!Q(n)){let e=ne(n),t=$({},e);for(let r of Object.keys(n)){let o=n[r];if(N(o)){if(Se(o))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(we(o))t[r]=o;else{let s=ne(o);t[r]=ce(s),qt(o,i)}}else t[r]=o}i.set(e,t)}else Q(n);return i}function z(n){return n.split(".")[0].split(mt)[0]}function di(n){let i=z(n),e=ve(i,()=>"\uFFFF");return[`${i}${mt}`,e]}function ui(n){let i=z(n);return[`${i}.`,`${i}.\uFFFF`]}function Ce(n,i){return z(n)===z(i)}function vs(n){let{collection:i,id:e,subId:t}=me(n);return Y(i,e,t)}var xs=/"\w+\/[^"]+?(\.[^"]+)+\:[\S]+?"/g;function Os(n){return n.replaceAll(xs,i=>{let e=i.slice(1,i.length-1);return`"${vs(e)}"`})}function fi(n){return JSON.parse(Os(JSON.stringify(n)))}function Br(n){return!n.includes(mt)}function Se(n){return n&&typeof n=="object"&&n["@@type"]==="ref"}function hi(n){return N(n)&&!Q(n)}function Ss(n,i){return n===i?!0:Q(n)&&Q(i)?Ze(n,i):!1}function gt(n,i,e,t,r=[],o={}){let s=ne(n);function a(u,d,m,S){if(!hi(d))Ss(d,m)||(S?r.push({oid:s,timestamp:e(),data:{op:"list-set",index:u,value:d}}):r.push({oid:s,timestamp:e(),data:{op:"set",name:u,value:d}}));else{let b=pe(m),C=pe(d);C&&!Ce(s,C)?(d=ae(d,!1),C=ve(s,t),$(d,C)):o.mergeUnknownObjects?!C&&b?($(d,b),C=b):C=li(d,s,t):C=li(d,s,t),L(!!C,"Error: no value OID was resolved during diff. This is a bug in Verdant."),L(Ce(s,C),`Error: value OID ${C} is not related to parent OID ${s}. This is a bug in Verdant.`),m===void 0||C!==b?(Pe(d,C,e,t,r),r.push({oid:s,timestamp:e(),data:{op:"set",name:u,value:ce(C)}}),b!==void 0&&r.push({oid:b,timestamp:e(),data:{op:"delete"}})):gt(m,d,e,t,r,o)}}if(Array.isArray(n)&&Array.isArray(i)){for(let d=0;d<i.length;d++){let m=i[d],S=n[d];a(d,m,S,!0)}let u=n.length-i.length;if(u>0){for(let d=i.length;d<n.length;d++){let m=n[d],S=pe(m);S&&r.push({oid:S,timestamp:e(),data:{op:"delete"}})}r.push({oid:s,timestamp:e(),data:{op:"list-delete",index:i.length,count:u}})}}else{if(Array.isArray(n)||Array.isArray(i))throw new Error("Cannot diff an array with an object");if(hi(n)&&hi(i)){let u=new Set(Object.keys(n));for(let[d,m]of Object.entries(i)){if(m===void 0&&o.defaultUndefined||(u.delete(d),ci(d)))continue;let S=n[d];a(d,m,S,!1)}if(!o.defaultUndefined)for(let d of u)ci(d)||r.push({oid:s,timestamp:e(),data:{op:"remove",name:d}})}}return r}function Pe(n,i,e,t,r=[]){$(n,i),et(n,t);let o=qt(n);for(let s of o.keys()){let a=o.get(s);r.push({oid:s,timestamp:e(),data:{op:"initialize",value:Ht(a)}})}return r}function yt(n){let i={};for(let e of n)e.oid in i?i[e.oid].push(e):i[e.oid]=[e];return i}function Mr(n){let i={};for(let e of n){let t=z(e.oid);t in i?i[t].push(e):i[t]=[e]}return i}function jr(n){let i={};for(let e of n){let t=z(e.oid);t in i?i[t].push(e):i[t]=[e]}return i}function ke(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: ${pe(n)})`),!1)}function Ne(n,i,e){if(n==null&&i.op!=="initialize")return n;let t=n,r,o;function s(a){e&&Q(a)&&e.push(a)}switch(i.op){case"set":s(t[i.name]),t[i.name]=i.value;break;case"remove":s(t[i.name]),delete t[i.name];break;case"list-set":ke(n)&&(s(n[i.index]),n[i.index]=i.value);break;case"list-push":ke(n)&&n.push(i.value);break;case"list-delete":ke(n)&&(s(n[i.index]),n.splice(i.index,i.count));break;case"list-move-by-index":ke(n)&&(o=n.splice(i.from,1),n.splice(i.to,0,o[0]));break;case"list-remove":if(ke(n))do{let a=i.value;i.only==="last"?Se(a)?r=Cr(n,u=>u.id===a.id):r=n.lastIndexOf(a):Se(a)?r=n.findIndex(u=>u.id===a.id):r=n.indexOf(a),r!==-1&&(s(n[r]),n.splice(r,1))}while(!i.only&&r!==-1);break;case"list-add":ke(n)&&(n.some(u=>Se(u)&&Se(i.value)?u.id===i.value.id:u===i.value)||n.push(i.value));break;case"list-move-by-ref":ke(n)&&(r=n.findIndex(a=>Ze(a,i.value)),o=n.splice(r,1),n.splice(i.index,0,o[0]));break;case"list-insert":if(ke(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(s):N(n)&&Object.values(n||{}).forEach(s);return;case"initialize":return ae(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]=kr(r,i,e),N(n[t])&&Wt(n[t],i,e)}else if(!we(n)){if(N(n)){L(pe(n),`Object ${JSON.stringify(n)} must have an oid`);for(let t of Object.keys(n))n[t]=kr(n[t],i,e),N(n[t])&&Wt(n[t],i,e)}}return e}function kr(n,i,e){if(Se(n)){e.push(n.id);let t=i.get(n.id);return L(!!t,`No value was found in object map for ${n.id}`),$(t,n.id)}else return n}function Lr(n){return n.data.op==="set"?n.data.name:!1}function Ur(n,i){return i.has(!0)?!0:n.data.op==="set"||n.data.op==="remove"?i.has(n.data.name):!1}var Me;(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"})(Me||(Me={}));var Is=n=>Object.assign({type:"object"},n),_s=n=>Object.assign({type:"array"},n),Ds=n=>Object.assign({type:"string"},n),Es=n=>Object.assign({type:"number"},n),Cs=n=>Object.assign({type:"boolean"},n),Ps=n=>Object.assign({type:"any"},n),As=n=>Object.assign({type:"map"},n),Rs=n=>Object.assign({type:"file"},n),Vr={object:Is,array:_s,string:Ds,number:Es,boolean:Cs,any:Ps,map:As,file:Rs};var Kr=Ue(Xe(),1);function pi(n){return n.equals!==void 0}function mi(n){return n.gte!==void 0||n.lte!==void 0||n.gt!==void 0||n.lt!==void 0}function Fs(n){return!!n.match}function gi(n){return n.startsWith!==void 0}function Nr(n){return!mi(n)&&!pi(n)&&!Fs(n)&&!gi(n)&&n.order}function xe(n){return n.type==="any"?!0:n.type==="map"?!1:n.nullable}function Ae(n){return n?n.type==="map"||n.type==="array"?!0:n.type==="file"?!1:n.default!==void 0:!1}function bi(n){if(!(!n||!Ae(n)))return n.type==="file"?xe(n)?null:void 0:n.type==="map"?{}:n.type==="array"?xe(n)?null:[]:n.type==="object"?xe(n)?null:void 0:typeof n.default=="function"?n.default():n.default}function Re(n,i){for(let[e,t]of Object.entries(n.fields)){let r=wi(t);(r!==void 0&&i[e]===void 0||!xe(t)&&i[e]===null)&&(i[e]=r),i[e]&&$e(i[e],t)}return i}function $e(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=wi(t);r!==void 0&&(n[e]=r)}$e(n[e],t)}else if(i.type==="array")for(let e of n)$e(e,i.items);else if(i.type==="map")for(let[e,t]of Object.entries(n))e===Ie||e===Ve||$e(t,i.values)}function wi(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]=wi(t));return i}}function vi(n,i){for(let[e,t]of Object.entries(i))e===Ie||e===Ve||(n.fields[e]?yi(t,n.fields[e]):delete i[e]);return i}function yi(n,i){if(N(n)&&i.type==="object")for(let[e,t]of Object.entries(n))i.properties[e]?yi(t,i.properties[e]):delete n[e];else if(Array.isArray(n)&&i.type==="array")for(let e of n)yi(e,i.items)}function $r(n,i){for(let[e,t]of Object.entries(i))if(e!==Ie){if(!n[e])return{type:"invalid-key",fieldPath:[e],message:`Invalid field "${e}"`};if(t){let r=Te({field:n[e],value:t,fieldPath:[e]});if(r)return r}}}function Te({field:n,value:i,fieldPath:e=[],depth:t,requireDefaults:r}){if(!(t!==void 0&&t<=0)&&!(xe(n)&&i===null)){if(i===null&&(r||!Ae(n)))return{type:"no-default",fieldPath:e,message:`Invalid null value for field ${Fe(e)}`};if(n.type==="object"){if(!N(i))return{type:"invalid-type",fieldPath:e,message:`Expected object${n.nullable?" or null":""} for field ${Fe(e)}, got ${i}`};for(let[o,s]of Object.entries(n.properties))o!==Ie&&i[o]&&Te({field:s,value:i[o],fieldPath:[...e,o],depth:t!==void 0?t-1:void 0});for(let o of Object.keys(i))if(!n.properties[o])return{type:"invalid-key",fieldPath:[...e,o],message:`Invalid unexpected field "${o}" on value ${Fe(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 ${Fe(e)}, got ${i}`};for(let o of i)Te({field:n.items,value:o,fieldPath:[...e,"[]"],depth:t!==void 0?t-1:void 0})}else if(n.type==="map"){if(!N(i))return{type:"invalid-type",fieldPath:e,message:`Expected map for field ${Fe(e)}, got ${i}`};for(let[o,s]of Object.entries(i))Te({field:n.values,value:s,fieldPath:[...e,o],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 ${Fe(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 ${Fe(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 ${Fe(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 ${Fe(e)}, got ${i}`}}else n.type}}function Fe(n){return n.length===0?"root":n.join(".")}function zr(n,i){let e={};for(let[t,r]of Object.entries(i))n[t]&&(e[t]=Qt({field:n[t],value:r,fieldPath:[t]}));return e}function Qt({field:n,value:i,fieldPath:e=[],depth:t}){let r=Te({field:n,value:i,fieldPath:e,depth:t,requireDefaults:!0});if(r)throw new Error(`Validation error: ${r.message}`);if(n.type==="object"){if(!N(i))return i;let o={};for(let[s,a]of Object.entries(n.properties))o[s]=Qt({field:a,value:i[s],fieldPath:[...e,s],depth:t!==void 0?t-1:void 0});return o}else{if(n.type==="array")return Array.isArray(i)?i.map(o=>Qt({field:n.items,value:o,fieldPath:[...e,"[]"],depth:t!==void 0?t-1:void 0})):i;if(n.type==="map"){if(!N(i))return i;let o={};for(let[s,a]of Object.entries(i))o[s]=Qt({field:n.values,value:a,fieldPath:[...e,s],depth:t!==void 0?t-1:void 0});return o}else return i}}function ze(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 Ts=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 xi(n){var{synthetics:i,indexes:e}=n,t=Ts(n,["synthetics","indexes"]);let r=Object.assign(Object.assign({},i),e);for(let[o,s]of Object.entries(t.fields))"indexed"in s&&(r[o]={field:o});return Object.assign(Object.assign({},t),{indexes:r})}function bt(n){return n}bt.collection=xi;bt.fields=Vr;bt.generated={id:Kr.default};var Jt="\uFFFFFE",Bs="\0",ks="\uFFFFFF";function le(...n){let i=Ms(n);return i.length===1?i[0]:i}function Ke(...n){return n.join(Jt)+`${ks}`}function qe(...n){return n.join(Jt)+`${Jt}${Bs}`}function Ms(n){let i=[[]];for(let e of n)if(Array.isArray(e)){let t=[];for(let r of i)for(let o of e)t.push(r.concat(o));i=t}else for(let t of i)t.push(`${e}`);return Array.from(new Set(i.map(e=>e.join(Jt))))}function js(n){return!!n.field}function Ls(n,i){let e={};for(let[t,r]of Object.entries(n.indexes||{})){let o=r;js(o)?e[t]=Oe(i[o.field]):e[t]=Oe(o.compute(i))}return e}function Us(n,i){return Object.entries(n.compounds||{}).reduce((e,[t,r])=>(e[t]=le(...r.of.map(o=>i[o])),e),{})}function Vs(n,i){return Object.entries(n.fields).reduce((e,[t,r])=>("indexed"in r&&(e[t]=Oe(i[t])),e),{})}function Gt(n,i){let e=Object.assign(Object.assign({[n.primaryKey]:i[n.primaryKey]},Vs(n,i)),Ls(n,i));return Object.assign(e,Us(n,Object.assign(Object.assign({},i),e))),e["@@@snapshot"]=i,e}var Ns="null";function Oe(n){if(n===null)return Ns;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(Oe);throw new Error(`Unsupported index value: ${n}`)}var qr={version:0,collections:{}};function Xt(n,i,e){let t=typeof i=="function",r=t?qr:n,o=t?n:i,s=t?i:e,a=Object.keys(o.collections).filter(v=>r.collections[v]&&ht(r.collections[v])!==ht(o.collections[v])),u=Object.keys(r.collections).filter(v=>!o.collections[v]),d=Object.keys(o.collections).filter(v=>!r.collections[v]),m=new Set;for(let v of a){let _=r.collections[v].fields,I=o.collections[v].fields;Object.keys(I).some(O=>{var R,y;return!(!((R=_[O])===null||R===void 0)&&R.default)&&((y=I[O])===null||y===void 0?void 0:y.default)})&&m.add(v),Object.keys(_).some(O=>!I[O])&&m.add(v)}let S={},b={};for(let v of[...a,...d]){let _=Yt(r.collections[v]),I=Yt(o.collections[v]),O=I.filter(y=>!_.find(D=>D.name===y.name)),R=_.filter(y=>!I.find(D=>D.name===y.name));O.length>0&&(S[v]=O,a.includes(v)&&m.add(v)),R.length>0&&(b[v]=R,a.includes(v)&&m.add(v))}let C=(v,_)=>Re(o.collections[v],_),w=v=>_=>{let I=o.collections[v];return Re(I,vi(I,_))};return{version:o.version,migrate:async v=>{let _=[];if(await s({migrate:async(I,O)=>{let R=w(I),y=async D=>{let f=await O(D);return $(f,ne(D)),R(f)};await v.migrate(I,y),_.push(I),m.delete(I)},identity:I=>I,withDefaults:C,info:{changedCollections:a,addedCollections:d,removedCollections:u},queries:v.queries,mutations:v.mutations}),o.version>1){v.log("debug","auto-migrating collections with new defaults",m);for(let O of m)await v.migrate(O,w(O)),_.push(O);let I=a.filter(O=>!_.includes(O));I.length>0&&console.error(`Unmigrated changed collections from version ${r.version} to version ${o.version}:`,I)}},removedCollections:u,addedIndexes:S,removedIndexes:b,allCollections:Object.keys(o.collections),changedCollections:a,addedCollections:d,oldCollections:Object.keys(r.collections),oldSchema:r,newSchema:o}}function Yt(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 Oi(n,i){return Xt(i?n:{version:0,collections:{}},i||n,async({migrate:t,info:r})=>{if((i||n).version!==1)for(let o of r.changedCollections)await t(o,s=>s)})}function Si(n,i,e){let t=typeof i=="function"||i===void 0,r=t?qr:n,o=t?n:i,s=t?i:e;L(r,"Invalid arguments to createMigration"),L(o,"Invalid arguments to createMigration");let{changedCollections:a,addedCollections:u,removedCollections:d,addedIndexes:m,removedIndexes:S,autoMigratedCollections:b,autoMigration:C}=$s(r,o);return{version:o.version,migrate:async w=>{let v=[];if(await s?.({migrate:async(I,O)=>{let R=C(I),y=async D=>{let f=await O(D);$(f,ne(D));let p=R(f),l=$r(o.collections[I].fields,p);return p};await w.migrate(I,y),v.push(I),b.delete(I)},info:{changedCollections:a,addedCollections:u,removedCollections:d},queries:w.queries,mutations:w.mutations}),o.version>1){w.log("debug","auto-migrating collections with new defaults",b);for(let O of b)await w.migrate(O,C(O)),v.push(O);for(let O of d)await w.deleteCollection(O);let I=a.filter(O=>!v.includes(O));I.length>0&&console.error(`Unmigrated changed collections from version ${r.version} to version ${o.version}:`,I)}},removedCollections:d,addedIndexes:m,removedIndexes:S,allCollections:Object.keys(o.collections),changedCollections:a,addedCollections:u,oldCollections:Object.keys(r.collections),oldSchema:r,newSchema:o}}function $s(n,i){let e=Object.keys(i.collections).filter(m=>n.collections[m]&&ht(n.collections[m])!==ht(i.collections[m])),t=Object.keys(n.collections).filter(m=>!i.collections[m]),r=Object.keys(i.collections).filter(m=>!n.collections[m]),o=new Set;for(let m of e){let S=n.collections[m].fields,b=i.collections[m].fields;Object.keys(b).some(C=>!Ae(S[C])&&Ae(b[C]))&&o.add(m),Object.keys(S).some(C=>!b[C])&&o.add(m)}let s={},a={};for(let m of[...e,...r]){let S=Yt(n.collections[m]),b=Yt(i.collections[m]),C=b.filter(v=>!S.find(_=>_.name===v.name)),w=S.filter(v=>!b.find(_=>_.name===v.name));C.length>0&&(s[m]=C,e.includes(m)&&o.add(m)),w.length>0&&(a[m]=w,e.includes(m)&&o.add(m))}return{changedCollections:e,addedCollections:r,removedCollections:t,addedIndexes:s,removedIndexes:a,autoMigratedCollections:o,withDefaults:(m,S)=>Re(i.collections[m],S),autoMigration:m=>S=>{let b=i.collections[m];return Re(b,vi(b,S))}}}var Zt=class{constructor(i,e){this.getNow=i,this.createSubId=e,this.isPrimitive=t=>!N(t)||Q(t),this.createDiff=(t,r,o={})=>gt(t,r,this.getNow,this.createSubId,[],o),this.createInitialize=(t,r)=>Pe(t,r,this.getNow,this.createSubId),this.createSet=(t,r,o)=>{if(this.isPrimitive(o))return[{oid:t,timestamp:this.getNow(),data:{op:"set",name:r,value:o}}];{let s=ve(t,this.createSubId);return[...Pe(o,s,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"set",value:ce(s),name:r}}]}},this.createRemove=(t,r)=>[{oid:t,timestamp:this.getNow(),data:{op:"remove",name:r}}],this.createListSet=(t,r,o)=>{if(this.isPrimitive(o))return[{oid:t,timestamp:this.getNow(),data:{op:"list-set",index:r,value:o}}];{let s=ve(t,this.createSubId);return[...Pe(o,s,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-set",index:r,value:ce(s)}}]}},this.createListPush=(t,r)=>{if(this.isPrimitive(r))return[{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:r}}];{let o=ve(t,this.createSubId);return[...Pe(r,o,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:ce(o)}}]}},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:ce(r)}}],this.createListInsert=(t,r,o)=>{if(this.isPrimitive(o))return[{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:o,index:r}}];{let s=ve(t,this.createSubId);return[...Pe(o,s,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:ce(s),index:r}}]}},this.createListRemove=(t,r,o)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-remove",value:r,only:o}}],this.createListDelete=(t,r,o=1)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-delete",index:r,count:o}}],this.createListMoveByRef=(t,r,o)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-move-by-ref",value:r,index:o}}],this.createListMoveByIndex=(t,r,o)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-move-by-index",from:r,to:o}}],this.createDelete=t=>[{oid:t,timestamp:this.getNow(),data:{op:"delete"}}],this.createDeleteAll=t=>t.map(r=>({oid:r,timestamp:this.getNow(),data:{op:"delete"}}))}};var V=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=zt(),o=this.subscribers[e];return o||(o=this.subscribers[e]={}),o[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 Hr(n,i,e,t){if(i==null)return[{oid:n,timestamp:t(),data:{op:"delete"}}];let r=ae(i),o=[];for(let s of e){let a=zs(n,r,s,t);o.unshift(...a),Ne(r,s.data)}return o}function zs(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 o=i.lastIndexOf(r.value);return[{oid:n,timestamp:t(),data:{op:"list-insert",index:o,values:[r.value]}}]}else if(r.only==="first"){let o=i.indexOf(r.value);return[{oid:n,timestamp:t(),data:{op:"list-insert",index:o,values:[r.value]}}]}else{let o=[],s=i.indexOf(r.value);for(;s!==-1;)o.push(s),s=i.indexOf(r.value,s+1);return o.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 tt=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:o}){let s=this.batches.get(i);return s||(s=new Ii({max:r||null,startedAt:Date.now(),userData:e,timeout:o||null,flusher:this.flusher,key:i}),this.batches.set(i,s)),s.update({items:t,max:r,timeout:o,userData:e}),s}},Ii=class{constructor({max:i,startedAt:e,timeout:t,userData:r,flusher:o,key:s}){this.items=[],this.update=({items:a,max:u,timeout:d,userData:m})=>{this.items.push(...a),u!==void 0&&(this.max=u),d!==void 0&&(this.timeout=d),m&&(this.userData=m);let S=this.items.length!==0&&this.timeout!==null&&!this.flushTimeout;this.max!==null&&this.items.length>=this.max?this.flush():S&&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=o,this.key=s}};function Wr(n,i){let e,t;return(...r)=>{let o=i();return e&&e.length===o.length&&e.every((s,a)=>s===o[a])||(e=[...o],t=n(...r)),t}}var wt;(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"})(wt||(wt={}));var _i=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}};_i.Code=wt;function Qr(n){return typeof n=="object"&&"code"in n&&typeof n.code=="number"}var Di=typeof window<"u"?window.indexedDB:void 0;function de(n){return n instanceof Error&&n.name==="AbortError"}function J(n){return new Promise((i,e)=>{n.onsuccess=()=>{i(n.result)},n.onerror=()=>{n.error&&de(n.error)?i(n.result):e(n.error)}})}function vt(n,i){return new Promise((e,t)=>{let r=n.transaction([i],"readonly"),s=r.objectStore(i).openCursor(),a=0,u=0;s.onsuccess=function(d){let m=s.result;m&&(a++,u=u+Er(m.value),m.continue())},s.onerror=function(d){s.error&&de(s.error)?e({count:a,size:u}):t(s.error)},r.oncomplete=function(d){e({count:a,size:u})},r.onabort=function(d){t(d)},r.onerror=function(d){t(d)}})}function en(n,i){let e=n.transaction(i,"readonly"),t=i.map(r=>{let o=e.objectStore(r);return J(o.getAll())});return Promise.all(t)}async function ge(n){n.close(),await new Promise((i,e)=>{i()})}async function tn(n,i=Di){let e=i.deleteDatabase([n,"meta"].join("_")),t=i.deleteDatabase([n,"collections"].join("_"));await Promise.all([new Promise((r,o)=>{e.onsuccess=r,e.onerror=o}),new Promise((r,o)=>{t.onsuccess=r,t.onerror=o})]),window.location.reload()}function Jr(n,i=window.indexedDB){return J(i.deleteDatabase(n))}async function Gr(n=window.indexedDB){return n.databases()}function nn(n,i,e,t,r){let o=n.transaction(i,e);if(t){let s=()=>{r?.("debug","aborting transaction");try{o.abort()}catch(a){r?.("debug","aborting transaction failed",a)}};t.addEventListener("abort",s),o.addEventListener("error",()=>{t.removeEventListener("abort",s)}),o.addEventListener("complete",()=>{t.removeEventListener("abort",s)})}return o}var _e=class{constructor(){this._disposes=[];this.disposed=!1;this.dispose=()=>{this.disposed=!0,this._disposes.forEach(i=>i()),this._disposes=[]};this.addDispose=i=>{this._disposes.push(i)}}};var se=class extends _e{constructor(e,{log:t}={}){super();this.db=e;this.globalAbortController=new AbortController;this.createTransaction=(e,t)=>{let r=nn(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 s=(r?.transaction||this.createTransaction([e],r)).objectStore(e),a=t(s);return J(a)};this.runAll=async(e,t,r)=>{if(this.disposed||r?.transaction?.error)return Promise.resolve([]);let s=(r?.transaction||this.createTransaction([e],r)).objectStore(e),a=t(s);return Promise.all(a.map(J))};this.iterate=async(e,t,r,o)=>{let a=(o?.transaction||this.createTransaction([e],o)).objectStore(e),u=t(a);return Array.isArray(u)?Promise.all(u.map(d=>new Promise((m,S)=>{d.onsuccess=()=>{let b=d.result;b?(r(b.value,a),b.continue()):m()},d.onerror=()=>{d.error&&de(d.error)?m():S(d.error)}}))).then(()=>{}):new Promise((d,m)=>{u.onsuccess=()=>{let S=u.result;S?(r(S.value,a),S.continue()):d()},u.onerror=()=>{u.error&&de(u.error)?d():m(u.error)}})};this.clear=e=>this.run(e,t=>t.clear(),{mode:"readwrite"});this.log=t,this.addDispose(()=>{this.globalAbortController.abort()})}};var rn=class extends se{constructor(){super(...arguments);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"})}}};var on=class extends se{constructor(e,t){super(e,t);this.getAllForDocument=async(e,{mode:t="readonly",transaction:r}={})=>{let o=[];return await this.iterateOverAllForDocument(e,s=>{o.push(s)},{mode:t,transaction:r}),o};this.iterateOverAllForDocument=async(e,t,{mode:r="readonly",transaction:o}={})=>this.iterate("baselines",s=>{let a=z(e),[u,d]=di(e),[m,S]=ui(e);return[s.openCursor(IDBKeyRange.only(a)),s.openCursor(IDBKeyRange.bound(u,d,!1,!1)),s.openCursor(IDBKeyRange.bound(m,S,!1,!1))]},t,{mode:r,transaction:o});this.iterateOverAllForCollection=async(e,t,{mode:r="readonly",transaction:o}={})=>this.iterate("baselines",s=>[s.openCursor(IDBKeyRange.bound(e,e+"\uFFFF",!1,!1))],t,{mode:r,transaction:o});this.getAllForMultipleDocuments=async(e,{mode:t="readonly"}={})=>(await this.runAll("baselines",o=>e.flatMap(s=>{let a=z(s),[u,d]=di(s),[m,S]=ui(s);return[o.get(a),o.getAll(IDBKeyRange.bound(u,d,!1,!1)),o.getAll(IDBKeyRange.bound(m,S,!1,!1))]}),{mode:t})).flat();this.getAllSince=async(e,{mode:t="readonly"}={})=>this.run("baselines",r=>{let o=e?IDBKeyRange.lowerBound(e,!0):void 0;return r.index("timestamp").getAll(o)},{mode:t});this.get=async(e,{transaction:t,mode:r="readonly"}={})=>this.run("baselines",o=>o.get(e),{mode:r,transaction:t});this.set=async(e,{transaction:t}={})=>{await this.run("baselines",r=>r.put(e),{mode:"readwrite",transaction:t})};this.setAll=async(e,{transaction:t}={})=>{await this.runAll("baselines",r=>e.map(o=>r.put(o)),{mode:"readwrite",transaction:t})};this.reset=()=>this.clear("baselines");this.delete=async(e,{transaction:t})=>{await this.run("baselines",r=>r.delete(e),{mode:"readwrite",transaction:t})}}};var Yr=Ue(Xe(),1);var sn=class extends se{constructor(){super(...arguments);this.get=async({transaction:e}={})=>{if(this.cached)return this.cached;let t=await this.run("info",r=>r.get("localReplicaInfo"),{transaction:e});return t?(this.cached=t,t):(this._creating||(this._creating=(async()=>{let o={type:"localReplicaInfo",id:(0,Yr.default)(),ackedLogicalTime:null,lastSyncedLogicalTime:null};await this.run("info",s=>s.put(o),{mode:"readwrite"}),this.cached=o})()),await this._creating,this.get({transaction:e}))};this.update=async(e,{transaction:t}={})=>{let r=await this.get({transaction:t});Object.assign(r,e),await this.run("info",o=>o.put(r),{mode:"readwrite"}),this.cached=r};this.reset=async()=>{let e=await this.get();e.ackedLogicalTime=null,e.lastSyncedLogicalTime=null,await this.run("info",t=>t.put(e),{mode:"readwrite"})}}};var an=class{constructor(i){this.meta=i;this.createOperation=async i=>{let e=await this.meta.localReplica.get();return{type:"op",timestamp:this.meta.now,replicaId:e.id,operations:i.operations.map(t=>({data:t.data,oid:t.oid,timestamp:t.timestamp}))}};this.createMigrationOperation=async({targetVersion:i,...e})=>{let t=await this.meta.localReplica.get();return{type:"op",operations:e.operations.map(r=>({...r,timestamp:this.meta.time.zero(i)})),timestamp:this.meta.time.zero(i),replicaId:t.id}};this.createSyncStep1=async i=>{let e=await this.meta.localReplica.get(),t=i===null?null:e.lastSyncedLogicalTime,r=[],o=new Set;t?await this.meta.operations.iterateOverAllLocalOperations(a=>{r.push({data:a.data,oid:a.oid,timestamp:a.timestamp}),o.add(z(a.oid))},{after:t,mode:"readwrite"}):await this.meta.operations.iterateOverAllOperations(a=>{r.push({data:a.data,oid:a.oid,timestamp:a.timestamp}),o.add(z(a.oid))},{mode:"readwrite"});let s=[];return t||(s=await this.meta.baselines.getAllSince("")),{type:"sync",schemaVersion:this.meta.schema.currentVersion,timestamp:this.meta.now,replicaId:e.id,resyncAll:!e.lastSyncedLogicalTime,operations:r,baselines:s,since:t}};this.createPresenceUpdate=async i=>{let e=await this.meta.localReplica.get();return{type:"presence-update",presence:i,replicaId:e.id}};this.createHeartbeat=async()=>{let i=await this.meta.localReplica.get();return{type:"heartbeat",timestamp:this.meta.now,replicaId:i.id}};this.createAck=async i=>{let e=await this.meta.localReplica.get();return{type:"ack",timestamp:this.meta.now,replicaId:e.id,nonce:i}}}};var cn=class extends se{constructor(e,t){super(e,t);this.iterateOverAllOperationsForDocument=async(e,t,{to:r,from:o,after:s,mode:a="readonly",transaction:u}={})=>{let m=(u||this.createTransaction(["operations"],{mode:a})).objectStore("operations"),S=m.index("d_t"),b=o||s,C=b?le(e,b):qe(e),w=r?le(e,r):Ke(e),v=IDBKeyRange.bound(C,w,!!s,!1),_=S.openCursor(v,"next");return new Promise((I,O)=>{let R;_.onsuccess=y=>{let D=_.result;if(D){let f=D.value;L(f.oid.startsWith(e)),L(R===void 0||R<=f.timestamp,`expected ${R} <= ${f.timestamp}`),t(f,m),R=f.timestamp,D.continue()}else I()},_.onerror=y=>{if(de(_.error)){I();return}else O(_.error)}})};this.iterateOverAllOperationsForEntity=async(e,t,{after:r,to:o,mode:s,transaction:a})=>{let d=(a||this.createTransaction(["operations"],{mode:s})).objectStore("operations"),m=r?le(e,r):qe(e),S=o?le(e,o):Ke(e),b=IDBKeyRange.bound(m,S,!!r,!1),C=d.openCursor(b,"next");return new Promise((w,v)=>{let _;C.onsuccess=I=>{let O=C.result;if(O){let R=O.value;L(R.oid.startsWith(e)),L(_===void 0||_<=R.timestamp,`expected ${_} <= ${R.timestamp}`),t(R,d),_=R.timestamp,O.continue()}else w()},C.onerror=I=>{de(C.error)?w():v(C.error)}})};this.iterateOverAllOperationsForCollection=async(e,t,{after:r,to:o,mode:s,transaction:a})=>{let u=a||this.createTransaction(["operations"],{mode:s});return this.iterate("operations",d=>d.openCursor(IDBKeyRange.bound(e,e+"\uFFFF",!1,!1),"next"),t,{mode:s,transaction:u})};this.iterateOverAllLocalOperations=async(e,{before:t,after:r,mode:o="readonly",transaction:s})=>{let u=(s||this.createTransaction(["operations"],{mode:o})).objectStore("operations"),d=u.index("l_t"),m=r?le(!0,r):qe(!0),S=t?le(!0,t):Ke(!0),b=IDBKeyRange.bound(m,S,!!r,!0),C=d.openCursor(b,"next");return new Promise((w,v)=>{let _;C.onsuccess=I=>{let O=C.result;if(O){let R=O.value;L(_===void 0||_<=R.timestamp,`expected ${_} <= ${R.timestamp}`),e(R,u),_=R.timestamp,O.continue()}else w()},C.onerror=I=>{de(C.error)?w():v(C.error)}})};this.iterateOverAllOperations=async(e,{before:t,transaction:r,mode:o,from:s})=>{await this.iterate("operations",a=>{let u=s?qe(s):void 0,d=t?Ke(t):void 0,m=u&&d?window.IDBKeyRange.bound(u,d,!1,!0):u?window.IDBKeyRange.lowerBound(u,!1):d?window.IDBKeyRange.upperBound(d,!0):void 0;return a.index("timestamp").openCursor(m,"next")},e,{mode:o,transaction:r})};this.addOperations=async(e,{transaction:t}={})=>this.insert(e.map(this.addCompoundIndexes),{transaction:t});this.addCompoundIndexes=e=>({...e,oid_timestamp:le(e.oid,e.timestamp),l_t:le(e.isLocal,e.timestamp),d_t:le(z(e.oid),e.timestamp)});this.insert=async(e,{transaction:t})=>{let r=new Set;return await this.runAll("operations",o=>e.map(s=>(r.add(z(s.oid)),o.put(s))),{mode:"readwrite",transaction:t}),Array.from(r)};this.reset=()=>this.clear("operations")}};var ln=class{constructor(i,e){this.db=i;this.currentVersion=e;this.cached=null;this.get=async()=>{if(this.cached)return this.cached;let r=this.db.transaction("info","readonly").objectStore("info").get("schema"),o=await J(r);return o?(this.cached=JSON.parse(o.schema),this.cached):null};this.set=async i=>{let o=this.db.transaction("info","readwrite").objectStore("info").put({type:"schema",schema:JSON.stringify(i)});this.cached=i,await J(o)}}};var xt=class extends V{constructor({disableRebasing:e,context:t,onOperation:r}){super();this.time=new kt;this.disableRebasing=!1;this._closing=!1;this.setContext=e=>{this.context=e};this.close=()=>{this._closing=!0};this.createTransaction=(e,t={})=>nn(this.db,e,t.write?"readwrite":"readonly",t.abort,this.context.log);this.getAllDocumentRelatedOids=async e=>{let t=new Set,r=z(e);L(r===e,"Must be root document OID"),t.add(r);let o=this.createTransaction(["baselines","operations"]);return await Promise.all([this.baselines.iterateOverAllForDocument(r,s=>{t.add(s.oid)},{transaction:o}),this.operations.iterateOverAllOperationsForDocument(r,s=>{t.add(s.oid)},{transaction:o})]),Array.from(t)};this.getAllCollectionRelatedOids=async e=>{let t=new Set,r=this.db.transaction(["baselines","operations"],"readwrite");return await Promise.all([this.baselines.iterateOverAllForCollection(e,o=>{t.add(o.oid)},{transaction:r}),this.operations.iterateOverAllOperationsForCollection(e,o=>{t.add(o.oid)},{transaction:r})]),Array.from(t)};this.getDocumentSnapshot=async(e,t={})=>{let r=z(e);L(r===e,"Must be root document OID");let o=this.db.transaction(["baselines","operations"],"readwrite"),s=await this.baselines.getAllForDocument(r,{transaction:o}),a=new Map;for(let d of s)d.snapshot&&$(d.snapshot,d.oid),a.set(d.oid,d.snapshot);await this.operations.iterateOverAllOperationsForDocument(r,d=>{let m=a.get(d.oid)||void 0,S=Ne(m,d.data);S&&$(S,d.oid),a.set(d.oid,S)},{transaction:o,to:t.to||this.now});let u=a.get(r);return u&&Wt(u,a),u};this.getDocumentData=async(e,t)=>{let r=this.createTransaction(["baselines","operations"],t),o=[],s={};return await Promise.all([this.baselines.iterateOverAllForDocument(e,a=>{o.push(a)},{transaction:r}),this.operations.iterateOverAllOperationsForDocument(e,a=>{s[a.oid]??=[],s[a.oid].push(a)},{transaction:r})]),{baselines:o,operations:s}};this.ack=async e=>{let t=await this.localReplica.get();e>this.now||(this.emit("message",{type:"ack",replicaId:t.id,timestamp:e}),!this._closing&&(!t.ackedLogicalTime||e>t.ackedLogicalTime)&&this.localReplica.update({ackedLogicalTime:e}))};this.insertLocalOperations=async(e,t)=>{if(e.length===0)return;this.log("debug",`Inserting ${e.length} local operations`,e);for(let o of e)o.isLocal=!0;await this.operations.addOperations(e,t);let r=await this.messageCreator.createOperation({operations:e});this.emit("message",r),this.tryAutonomousRebase(),this.onOperation&&e.forEach(o=>this.onOperation(o))};this.insertRemoteOperations=async(e,t)=>{if(e.length===0)return[];this.log("debug",`Inserting ${e.length} remote operations`,e);let r=await this.operations.addOperations(e.map(o=>({...o,isLocal:!1})),t);return this.ack(e[e.length-1].timestamp),this.onOperation&&e.forEach(o=>this.onOperation(o)),r};this.insertRemoteBaselines=async(e,t)=>{if(e.length===0)return[];this.log(`Inserting ${e.length} remote baselines`),await this.baselines.setAll(e,t);let r=new Set;return e.forEach(o=>{r.add(z(o.oid))}),Array.from(r)};this.insertData=async(e,t)=>{let r=this.createTransaction(["baselines","operations"],{...t,write:!0});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._closing)return this.localReplica.update({lastSyncedLogicalTime:e})};this.lastSyncedTimestamp=async()=>(await this.localReplica.get()).lastSyncedLogicalTime;this.tryAutonomousRebase=async()=>{this.disableRebasing||(await this.localReplica.get()).lastSyncedLogicalTime||await this.runRebase(this.now)};this.runRebase=async e=>{if(this._closing)return;let t,r=new Set,o=this.createTransaction(["baselines","operations"],{write:!0}),s=0;if(await this.operations.iterateOverAllOperations(u=>{r.add(u.oid),t=u.timestamp,s++},{before:e,transaction:o}),!r.size||this._closing)return;let a=[];for(let u of r)a.push(await this.rebase(u,t||e,o));this.emit("rebase",a)};this.rebase=async(e,t,r)=>{let o=(await this.localReplica.get()).id;this.log("[",o,"]","Rebasing",e,"up to",t);let s=r||this.createTransaction(["operations","baselines"],{write:!0}),a=await this.baselines.get(e,{transaction:s}),u=a?.snapshot||void 0,d=0,m=[];await this.operations.iterateOverAllOperationsForEntity(e,(b,C)=>{(!a||b.timestamp>a.timestamp)&&(u=Ne(u,b.data,m)),d++,C.delete(b.oid_timestamp)},{to:t,transaction:s}),u&&$(u,e);let S={oid:e,snapshot:u,timestamp:t};if(S.snapshot?await this.baselines.set(S,{transaction:s}):await this.baselines.delete(e,{transaction:s}),this.log("debug","successfully rebased",e,"up to",t,":",u,"and deleted",d,"operations"),m.length){let b=m.filter(we);b.length&&this.emit("filesDeleted",b)}return S};this.reset=async()=>{await this.operations.reset(),await this.baselines.reset(),await this.localReplica.reset()};this.updateSchema=async(e,t)=>{let r=await this.schema.get();if(r&&t===r.version&&r.version===e.version&&JSON.stringify(r)!==JSON.stringify(e))throw console.error(`Schema mismatch for version ${e.version}
|
|
7
7
|
${JSON.stringify(r)}
|
|
8
|
-
${JSON.stringify(e)}`),new Error("Schema has changed without a version change! Any changes to your schema must be accompanied by a change in schema version and a migration routine.");await this.schema.set(e)};this.setGlobalAck=async e=>{this._closing||(await this.ackInfo.setGlobalAck(e),this.disableRebasing||await this.runRebase(e))};this.export=async()=>{let e=this.db,[t,r]=await Yt(e,["baselines","operations"]),s=await this.localReplica.get(),o=await this.schema.get();if(!o)throw new Error("Cannot export Client data before initializing");return{operations:r,baselines:t,localReplica:s,schema:o}};this.resetFrom=async e=>{let r=this.db.transaction(["baselines","operations","info"],"readwrite");await J(r.objectStore("baselines").clear()),await J(r.objectStore("operations").clear()),await J(r.objectStore("info").clear()),await this.localReplica.update({ackedLogicalTime:e.localReplica.ackedLogicalTime,lastSyncedLogicalTime:e.localReplica.lastSyncedLogicalTime},{transaction:r})};this.stats=async()=>{let e=this.db,t=await vt(e,"operations"),r=await vt(e,"baselines");return{operationsSize:t,baselinesSize:r}};this.context=t,this.schema=new on(t.metaDb,t.schema.version),this.operations=new sn(this.db,{log:t.log}),this.baselines=new tn(this.db,{log:t.log}),this.localReplica=new nn(this.db),this.ackInfo=new en(this.db),this.messageCreator=new rn(this),this.patchCreator=new Gt(()=>this.now),this.onOperation=r,e&&(this.disableRebasing=e)}get db(){return this.context.metaDb}get log(){return this.context.log}get now(){return this.time.now(this.schema.currentVersion)}};var Lo=[Uo,Vo,No,$o,zo];function an({indexedDB:n=window.indexedDB,namespace:i,log:e,metadataVersion:t=5}){return new Promise((r,s)=>{let o=n.open(`${i}_meta`,t),a=!1;o.onupgradeneeded=async h=>{let d=o.result,m=o.transaction,v=Lo.slice(h.oldVersion);for(let b of v)await b(d,m);await new Promise((b,D)=>{m.addEventListener("complete",b),m.addEventListener("error",D)}),h.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 Gr({wipNamespace:n,namespace:i,indexedDB:e,log:t,metadataVersion:r}){let s=await an({namespace:n,indexedDB:e,log:t,metadataVersion:r});if(!s.wasInitialized)return s;t?.("debug","Beginning copy of production metadata database to WIP");let{db:o}=await an({namespace:i,indexedDB:e,log:t,metadataVersion:r}),a=o.transaction(["baselines","operations","info"],"readonly"),[h,d,m]=await Promise.all([J(a.objectStore("baselines").getAll()),J(a.objectStore("operations").getAll()),J(a.objectStore("info").getAll())]),v=s.db.transaction(["baselines","operations","info"],"readwrite"),b=v.objectStore("baselines"),D=v.objectStore("operations"),w=v.objectStore("info");for(let x of h)b.put(x);for(let x of d)D.put(x);for(let x of m)w.put(x);return await new Promise((x,_)=>{v.oncomplete=()=>{x()},v.onerror=O=>{_(O)},v.onabort=O=>{_(O)}}),await Ke(o),t?.("debug","Finished copy of production metadata database to WIP. Copied:",h.length,"baselines,",d.length,"operations"),s}async function Uo(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 Vo(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:h,...d}=o.value;o.update({...d,l_t:a,d_t:h}),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 No(n,i){i.objectStore("operations").createIndex("timestamp","timestamp")}async function $o(n,i){let e=n.createObjectStore("files",{keyPath:"id"});e.createIndex("remote","remote"),e.createIndex("deletedAt","deletedAt")}async function zo(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 h=di(a.value);h.oid_timestamp!==a.primaryKey?(a.delete(),e.put(h)):a.update(h),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 h=di(a.value);h.oid!==a.primaryKey?(a.delete(),t.put(h)):a.update(h),a.continue()}else r()},o.onerror=a=>{s(o.error)}})}var Ko=n=>IDBKeyRange.only(xe(n.equals)),qo=n=>{},Ho=n=>{let i=n.gte||n.gt,e=n.lte||n.lt;return i===e?IDBKeyRange.only(xe(i)):i?e?IDBKeyRange.bound(xe(i),xe(e),!!n.gt,!!n.lt):IDBKeyRange.lowerBound(xe(i),!!n.gt):IDBKeyRange.upperBound(xe(e),!!n.lt)},Wo=(n,i,e)=>{let t=n.collections[i].compounds[e.where];L(t,`Index ${e.where} does not exist on collection ${i}`);let r=Object.keys(e.match).sort((h,d)=>t.of.indexOf(h)-t.of.indexOf(d));for(let h of r)if(t.of.indexOf(h)!==r.indexOf(h))throw new Error(`Compound index ${e.where} does not have ${h} at the start of its order`);let s=r.map(h=>e.match[h]);if(r.length===t.of.length)return IDBKeyRange.only(le(...s));let o=ze(...s),a=$e(...s);return IDBKeyRange.bound(o,a)};function Qo(n){let i=n.startsWith,e=n.startsWith+"\uFFFF";return IDBKeyRange.bound(i,e)}function cn(n,i,e){if(e)return hi(e)?Ho(e):fi(e)?Ko(e):Vr(e)?qo(e):pi(e)?Qo(e):Wo(n,i,e)}function Ii(n,i,e){return n.transaction(i,e?"readwrite":"readonly").objectStore(i)}async function ln({collection:n,index:i,context:e}){let t=Ii(e.documentDb,n),r=i?.where?t.index(i.where):t,s=cn(e.schema,n,i),o=i?.order==="desc"?"prev":"next",a=r.openCursor(s,o);return await new Promise((d,m)=>{a.onsuccess=()=>{let v=a.result;d(v?Z(n,v.primaryKey.toString()):null)},a.onerror=()=>{a.error?.name==="InvalidStateError"?(e.log("error","findOne query failed with InvalidStateError",a.error),d(null)):de(a.error)?d(null):m(a.error)}})}async function dn({collection:n,index:i,context:e}){let t=Ii(e.documentDb,n),r=i?.where?t.index(i.where):t,s=cn(e.schema,n,i),o=i?.order==="desc"?"prev":"next",a=r.openCursor(s,o);return await new Promise((d,m)=>{let v=new Set;a.onsuccess=()=>{let b=a.result;b?(v.add(Z(n,b.primaryKey.toString())),b.continue()):d(Array.from(v))},a.onerror=()=>{a.error?.name==="InvalidStateError"?(e.log("error","findAll query failed with InvalidStateError",a.error),d([])):de(a.error)?d([]):m(a.error)}})}async function Ot({collection:n,index:i,context:e,limit:t,offset:r}){let s=Ii(e.documentDb,n),o=i?.where?s.index(i.where):s,a=cn(e.schema,n,i),h=i?.order==="desc"?"prev":"next",d=o.openCursor(a,h),m=!r,v=!1,b=0;return{result:await new Promise((w,x)=>{let _=new Set;d.onsuccess=()=>{b++;let O=d.result;O?r&&!m?(O.advance(r),m=!0):(t&&_.size<t&&_.add(Z(n,O.primaryKey.toString())),t&&b>t?(v=!0,w(Array.from(_))):O.continue()):w(Array.from(_))},d.onerror=()=>{d.error?.name==="InvalidStateError"?(e.log("error","find query failed with InvalidStateError",d.error),w([])):de(d.error)?w([]):x(d.error)}}),hasNextPage:v}}async function _i(n,i,e,t){function r(a,h){let d,m,v=n.open([i,"collections"].join("_"),e);v.onupgradeneeded=async b=>{d=b.oldVersion;let D=v.transaction;m=v.result,D.abort()},v.onsuccess=b=>{a([v.result.version,v.result])},v.onblocked=b=>{t?.("Database blocked, waiting...")},v.onerror=b=>{a([d,m])}}let[s,o]=await new Promise(r);return await un(o),s}async function un(n){n.close(),await new Promise(i=>i())}async function Yr(n,i,e,t,r){function s(o,a){let h=n.open([i,"collections"].join("_"),e),d=!1;h.onupgradeneeded=m=>{let v=h.transaction;t(v,h.result,m),d=!0},h.onsuccess=m=>{h.result.close(),d?o():a(new Error("Database was not upgraded when a version change was expected"))},h.onerror=m=>{a(h.error||new Error("Unknown error"))},h.onblocked=m=>{r?.("Database upgrade blocked, waiting...")}}return new Promise(s)}async function Xr(n,i){typeof navigator<"u"&&navigator.locks?await navigator.locks.request(`verdant_migration_${n}`,i):await i()}async function qe(n,i,e,t){t?.("debug","Opening database",i,"at version",e);let r=await new Promise((s,o)=>{let a=n.open([i,"collections"].join("_"),e);a.onupgradeneeded=async h=>{a.transaction.abort(),t?.("error","Database upgrade needed, but not expected","Expected",e,"Got",a.result.version),o(a.error||new Error(`Migration error: database version changed unexpectedly when reading current data. Expected ${e}, got ${a.result.version}`))},a.onsuccess=h=>{s(a.result)},a.onblocked=h=>{o(new Error("Migration error: database blocked"))},a.onerror=h=>{o(new Error("Migration error: database error"))}});return r.addEventListener("versionchange",s=>{r.close()}),r}var nt=class extends Error{constructor(e){super(e);this.message=e;this.name="MigrationPathError"}};function fn({currentVersion:n,targetVersion:i,migrations:e}){let t=Zr({currentVersion:n,targetVersion:i,migrations:e});if(!t)throw new nt(`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 Zr({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=Zr({currentVersion:r.newSchema.version,targetVersion:i,migrations:e});if(s)return[r,...s]}return null}var Ei=typeof window<"u"?window.indexedDB:void 0;async function St({version:n,indexedDB:i=Ei,migrations:e,meta:t,context:r}){if(r.schema.wip)throw new Error("Cannot open a production client with a WIP schema!");let s=await _i(i,r.namespace,n,r.log);r.log("debug","Current database version:",s,"target version:",n);let o=fn({currentVersion:s,targetVersion:n,migrations:e});return o.length>0&&(r.log("debug","Migrations to run:",o.map(a=>a.version)),await Di({context:r,toRun:o,meta:t,indexedDB:i})),qe(i,r.namespace,n,r.log)}async function es({version:n,indexedDB:i=Ei,migrations:e,meta:t,context:r,wipNamespace:s}){r.log("debug","Opening WIP database",s);let o=await _i(i,s,n,r.log);if(o===n)r.log("info","WIP schema is up-to-date; not refreshing database");else{r.log("info","WIP schema is out-of-date; refreshing database");let a=fn({currentVersion:o,targetVersion:n-1,migrations:e});if(a.length>0){await Di({context:r,toRun:a,meta:t,indexedDB:i,namespace:s});let d=await qe(i,r.namespace,n-1,r.log),m=await qe(i,s,n-1,r.log),v=new Array;for(let O=0;O<d.objectStoreNames.length;O++)v.push(d.objectStoreNames[O]);let b=d.transaction(v,"readonly"),D=v.map(O=>b.objectStore(O)),w=await Promise.all(D.map(O=>J(O.getAll()))),x=m.transaction(v,"readwrite"),_=v.map(O=>x.objectStore(O));for(let O=0;O<_.length;O++)await Promise.all(w[O].map(I=>J(_[O].put(I))))}let h=fn({currentVersion:n-1,targetVersion:n,migrations:e});h.length>0&&await Di({context:r,toRun:h,meta:t,indexedDB:i,namespace:s})}return qe(i,s,n,r.log)}async function Di({context:n,toRun:i,meta:e,indexedDB:t=Ei,namespace:r=n.namespace}){await Xr(r,async()=>{for(let s of i){let o;if(s.oldSchema.version===0)o=Yo({meta:e,migration:s,context:n}),await s.migrate(o);else{let d=await qe(t,r,s.oldSchema.version,n.log);o=Go({meta:e,migration:s,context:{...n,documentDb:d}});try{await s.migrate(o),await Promise.all(o.awaitables)}catch(m){throw n.log("critical",`Migration failed (${s.oldSchema.version} -> ${s.newSchema.version})`,m),m instanceof Error?m:new Error("Unknown error during migration")}await un(d)}n.log("debug","Upgrading database",r,"to version",s.newSchema.version),await Yr(t,r,s.newSchema.version,(d,m)=>{for(let v of s.addedCollections)m.createObjectStore(v,{keyPath:s.newSchema.collections[v].primaryKey,autoIncrement:!1});for(let v of s.allCollections){let b=d.objectStore(v);for(let D of s.addedIndexes[v]||[])b.createIndex(D.name,D.name,{multiEntry:D.multiEntry});for(let D of s.removedIndexes[v]||[])b.deleteIndex(D.name)}for(let v of s.removedCollections)d.objectStore(v).clear()},n.log);let a=await ta({meta:e,currentVersion:s.oldSchema.version,newVersion:s.newSchema.version}),h=await qe(t,r,s.newSchema.version,n.log);for(let d of s.allCollections){let v=h.transaction(d,"readwrite").objectStore(d),D=(await Xo(v)).map(I=>Z(d,`${I}`));D.push(...o.newOids.filter(I=>me(I).collection===d),...a.filter(I=>me(I).collection===d));let x=(await Promise.all(D.map(async I=>{try{let R=await e.getDocumentSnapshot(I);return[I,R]}catch(R){return n.log("error","Could not regenerate snapshot during migration for oid",I,"this document will not be preserved",R),null}}))).filter(I=>!!I).map(([I,R])=>{if(!R)return[I,void 0];let y=Wt(s.newSchema.collections[d],R);return[I,y]}),O=h.transaction(d,"readwrite").objectStore(d);await Promise.all(x.map(([I,R])=>{if(R)return ea(O,R);{let{id:y}=me(I);return Zo(O,y)}}))}await un(h),n.log("debug",`Migration of ${r} complete.`),n.log(`
|
|
9
|
-
\u2B06\uFE0F v${
|
|
10
|
-
- Added collections: ${
|
|
11
|
-
- Removed collections: ${
|
|
12
|
-
- Changed collections: ${
|
|
13
|
-
- New indexes: ${Object.keys(
|
|
14
|
-
- Removed indexes: ${Object.keys(
|
|
15
|
-
`)}})}function ts({migration:n,meta:i,getMigrationNow:e,newOids:t}){return n.allCollections.reduce((r,s)=>(r[s]={put:async o=>{Ae(n.newSchema.collections[s],o);let a=o[n.newSchema.collections[s].primaryKey],h=Z(s,a);return t.push(h),await i.insertLocalOperations(Ce(o,h,e)),o},delete:async o=>{let a=Z(s,o),h=await i.getAllDocumentRelatedOids(a);return i.insertLocalOperations(h.map(d=>({oid:d,timestamp:e(),data:{op:"delete"}})))}},r),{})}function Jo({migration:n,context:i,meta:e}){return n.oldCollections.reduce((t,r)=>(t[r]={get:async s=>{let o=Z(r,s);return await e.getDocumentSnapshot(o,{to:e.time.now(n.oldSchema.version)})},findOne:async s=>{let o=await ln({collection:r,index:s,context:i});return o?await e.getDocumentSnapshot(o,{to:e.time.now(n.oldSchema.version)}):null},findAll:async s=>{let o=await dn({collection:r,index:s,context:i});return await Promise.all(o.map(h=>e.getDocumentSnapshot(h,{to:e.time.now(n.oldSchema.version)})))}},t),{})}function Go({meta:n,migration:i,context:e}){function t(){return n.time.zero(i.version)}let r=new Array,s=Jo({migration:i,context:e,meta:n}),o=ts({migration:i,getMigrationNow:t,newOids:r,meta:n}),a=async m=>{let v=await n.getAllCollectionRelatedOids(m);return n.insertLocalOperations(v.map(b=>({oid:b,timestamp:t(),data:{op:"delete"}})))},h=new Array;return{log:e.log,newOids:r,deleteCollection:a,migrate:async(m,v)=>{let b=await s[m].findAll();await Promise.all(b.filter(Boolean).map(async D=>{let w=ne(D);L(!!w,`Document is missing an OID: ${JSON.stringify(D)}`);let x=ae(D),_=await v(D);if(_){pt(x),pt(_),et(_);let O=gt(x,_,t,void 0,[],{mergeUnknownObjects:!0});O.length>0&&await n.insertLocalOperations(O)}}))},queries:s,mutations:o,awaitables:h}}function Yo({meta:n,migration:i,context:e}){function t(){return n.time.zero(i.version)}let r=new Array,s=new Proxy({},{get(){throw new Error("Queries are not available in initial migrations; there is no database yet!")}}),o=ts({migration:i,getMigrationNow:t,newOids:r,meta:n});return{log:e.log,newOids:r,deleteCollection:()=>{throw new Error("Calling deleteCollection() in initial migrations is not supported! Use initial migrations to seed initial data using mutations.")},migrate:()=>{throw new Error("Calling migrate() in initial migrations is not supported! Use initial migrations to seed initial data using mutations.")},queries:s,mutations:o,awaitables:[]}}async function Xo(n){return new Promise((i,e)=>{let t=n.getAllKeys();t.onsuccess=r=>{i(t.result)},t.onerror=r=>{e(t.error)}})}async function Zo(n,i){let e=n.delete(i);return new Promise((t,r)=>{e.onsuccess=s=>{t()},e.onerror=s=>{r(e.error)}})}async function ea(n,i){let e=n.put(i);return new Promise((t,r)=>{e.onsuccess=s=>{t()},e.onerror=s=>{r(e.error)}})}async function ta({meta:n,currentVersion:i,newVersion:e}){let t=[];return await n.operations.iterateOverAllOperations(r=>t.push(r),{from:n.time.zero(i+1)}),Array.from(new Set(t.map(r=>z(r.oid))))}var He=class extends V{constructor(){super(...arguments);this._undoable=[];this._undone=[];this.undo=async()=>{let e=this._undoable.pop();if(e){let t=await e();return t&&this._undone.push(t),this.emit("change"),!0}return!1};this.redo=async()=>{let e=this._undone.pop();if(e){let t=await e();return t&&this._undoable.push(t),this.emit("change"),!0}return!1};this.addUndo=e=>{this._undoable.push(e),this._undone=[],this.emit("change")};this.addRedo=e=>{this._undone.push(e),this.emit("change")};this.clear=()=>{this._undoable=[],this._undone=[],this.emit("change")}}get canUndo(){return this._undoable.length>0}get canRedo(){return this._undone.length>0}};var hn=class{constructor(i,e,t){this.meta=i;this.schema=e;this.entities=t;this.getOid=(i,e)=>{let t=this.schema.collections[i].primaryKey,r=e[t];return L(r,`Document must have a primary key: ${t.toString()} (got: ${JSON.stringify(e)})`),Z(i,r)};this.addDefaults=(i,e)=>{let t=this.schema.collections[i];return Ae(t,e)};this.create=(i,e,t={})=>{let r=this.addDefaults(i,e),s=this.getOid(i,r);return this.entities.create(r,s,t)};this.delete=async(i,e,t={})=>{let r=Z(i,e);return this.entities.delete(r,t)};this.deleteAll=async(i,e={})=>this.entities.deleteAll(i.map(([t,r])=>Z(t,r)),e);this.deleteAllFromCollection=async(i,e,t={})=>this.entities.deleteAll(e.map(r=>Z(i,r)),t)}};var it=Symbol("entity-file-update"),It=Symbol("entity-file-mark-failed"),na,ia,ue=class extends V{constructor(e,{downloadRemote:t=!1}={}){super();this.id=e;this._objectUrl=null;this._fileData=null;this._loading=!0;this._failed=!1;this._downloadRemote=!1;this[na]=e=>{this._loading=!1,this._failed=!1,this._fileData=e,e.file&&(this._objectUrl&&URL.revokeObjectURL(this._objectUrl),this._objectUrl=URL.createObjectURL(e.file)),this.emit("change")};this[ia]=()=>{this._failed=!0,this._loading=!1,this.emit("change")};this.destroy=()=>{this._objectUrl&&URL.revokeObjectURL(this._objectUrl),this.dispose()};this._downloadRemote=t}static{na=it,ia=It}get downloadRemote(){return this._downloadRemote}get isFile(){return!0}get url(){return this.loading?null:this._objectUrl?this._objectUrl:this._fileData?.url??null}get name(){return this._fileData?.name??null}get type(){return this._fileData?.type??null}get loading(){return this._loading}get failed(){return this._failed}getSnapshot(){return{id:this.id,url:this.loading||this.failed?void 0:this.url}}};var ns=Me(Xe(),1);function ra(n){return{id:(0,ns.default)(),file:n,url:void 0,remote:!1,name:n.name,type:n.type}}function Ci(n){return n instanceof File||typeof Blob<"u"&&n instanceof Blob}function rt(n,i){if(typeof window<"u"&&Ci(n)){let e=ra(n);return i(e),Lt(e.id)}if(Array.isArray(n)){for(let e=0;e<n.length;e++)n[e]=rt(n[e],i);return n}if(typeof n=="object"){for(let e in n)n[e]=rt(n[e],i);return n}return n}function is(n){return new Promise((i,e)=>{let t=new FileReader;t.onload=()=>{i(t.result)},t.onerror=e,t.readAsArrayBuffer(n)})}var pn=class extends oe{constructor(){super(...arguments);this.addFile=async(e,{transaction:t,downloadRemote:r=!1}={})=>{let s=e.file?await is(e.file):void 0;if(!s&&r&&e.url)try{s=await fetch(e.url,{method:"GET",credentials:"include"}).then(o=>o.arrayBuffer())}catch(o){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.",o)}return this.run("files",o=>o.put({id:e.id,remote:e.remote?"true":"false",deletedAt:null,name:e.name,type:e.type,url:e.url,buffer:s}),{mode:"readwrite",transaction:t})};this.hydrateFileData=e=>{e.remote=e.remote==="true";let t=e.buffer;return delete e.buffer,e.file=t?sa(t,e.type):void 0,e};this.markUploaded=async(e,{transaction:t}={})=>{let r=await this.getFileRaw(e,{transaction:t});if(!r)throw new Error("File is not in local database");return this.run("files",s=>s.put({...r,remote:"true"}),{mode:"readwrite",transaction:t})};this.getFileRaw=async(e,{transaction:t}={})=>{let r=await this.run("files",s=>s.get(e),{mode:"readonly",transaction:t});if(r)return r};this.getFile=async(e,{transaction:t}={})=>{let r=await this.getFileRaw(e,{transaction:t});if(r)return this.hydrateFileData(r)};this.markPendingDelete=async(e,{transaction:t}={})=>{let r=await this.getFileRaw(e,{transaction:t});if(!r)throw new Error("File is not in local database");return this.run("files",s=>s.put({...r,deletedAt:Date.now()}),{mode:"readwrite",transaction:t})};this.listUnsynced=async()=>(await this.run("files",t=>t.index("remote").getAll("false"),{mode:"readonly"})).map(this.hydrateFileData);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});this.getAll=async()=>{let[e]=await Yt(this.db,["files"]);return e.map(this.hydrateFileData)}}deleteFile(e,{transaction:t}={}){return this.run("files",r=>r.delete(e),{mode:"readwrite",transaction:t})}};function sa(n,i){return new Blob([n],{type:i})}function oa(n){return n.deletedAt!==null&&n.deletedAt<Date.now()-1e3*60*24*3}var mn=class{constructor({db:i,sync:e,context:t,meta:r,config:s={}}){this.files=new Map;this.add=async i=>{let e=i;if(e.remote=!1,this.files.has(e.id))this.files.get(e.id)[it](e);else{let t=new ue(e.id);t[it](e),this.files.set(e.id,t)}await this.storage.addFile(e),e.file&&await this.uploadFile(e,1)};this.uploadFile=async(i,e=0)=>{let t=await this.sync.uploadFile(i);t.success?await this.storage.markUploaded(i.id):t.retry&&e<5?(this.context.log("error","Error uploading file, retrying..."),setTimeout(this.uploadFile,1e3,i,e+1)):this.context.log("error","Failed to upload file. Not retrying until next sync.")};this.get=(i,e)=>{if(this.files.has(i))return this.files.get(i);let t=new ue(i,e);return this.files.set(i,t),this.load(t),t};this.load=async(i,e=0)=>{if(e>5){this.context.log("error","Failed to load file after 5 retries"),i[It]();return}let t=await this.storage.getFile(i.id);if(t)i[it](t);else try{let r=await this.sync.getFile(i.id);r.success?(i[it](r.data),await this.storage.addFile(r.data,{downloadRemote:i.downloadRemote})):(this.context.log("error","Failed to load file",r),i[It](),r.retry&&setTimeout(this.load,1e3,i,e+1))}catch(r){this.context.log("error","Failed to load file",r),i[It](),setTimeout(this.load,1e3,i,e+1)}};this.listUnsynced=async()=>this.storage.listUnsynced();this.exportAll=async(i=!1)=>{let e=await this.storage.getAll();if(i){for(let t of e)if(!t.file&&t.url)try{let r=await fetch(t.url,{method:"GET",credentials:"include"}).then(s=>s.blob());t.file=r}catch(r){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.",r)}}return e};this.importAll=async i=>{await Promise.all(i.map(e=>this.add(e)))};this.onOnlineChange=async i=>{if(i){let e=await this.listUnsynced();await Promise.all(e.map(this.uploadFile))}};this.tryCleanupDeletedFiles=async()=>{let i=0,e=0;await this.storage.iterateOverPendingDelete((t,r)=>{this.config.canCleanupDeletedFile(t)?(i++,r.delete(t.id)):e++}),this.context.log("info",`Cleaned up ${i} files, skipped ${e} files`)};this.handleFileRefsDeleted=async i=>{let e=this.storage.createTransaction(["files"],{mode:"readwrite"});await Promise.all(i.map(async t=>{try{await this.storage.markPendingDelete(t.id,{transaction:e})}catch(r){this.context.log("error","Failed to mark file for deletion",r)}})),this.context.log("info",`Marked ${i.length} files as pending delete`)};this.close=()=>{this.storage.dispose()};this.storage=new pn(i),this.sync=e,this.context=t,this.meta=r,this.config={canCleanupDeletedFile:oa,...s},this.sync.subscribe("onlineChange",this.onOnlineChange),this.meta.subscribe("filesDeleted",this.handleFileRefsDeleted),this.tryCleanupDeletedFiles()}};var gn=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 fe(i);return this.cache.set(i.oid,e),e};this.has=i=>this.cache.has(i);this.getFile=(i,e)=>{if(this.cache.has(i))return this.cache.get(i);let t=new ue(i,e);return this.cache.set(i,t),t};this.getCached=i=>this.cache.get(i);if(i)for(let e of i)this.cache.set(e.oid,e)}};var fe=class n extends V{constructor({oid:e,schema:t,entityFamily:r,parent:s,ctx:o,metadataFamily:a,readonlyKeys:h,files:d,patchCreator:m,events:v,deleteSelf:b}){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.validate=qr(()=>(this.validationError=Be({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 ue?e(s):s);return $(r,this.oid),r}else{let r=Object.entries(t).reduce((s,[o,a])=>(a instanceof n||a instanceof ue?s[o]=e(a):s[o]=a,s),{});return $(r,this.oid),r}};this.getSnapshot=()=>this.viewWithMappedChildren(e=>e.getSnapshot());this.addPendingOperations=e=>{this.ctx.log("debug","Entity: adding pending operations",this.oid);let 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.ctx.log("Emitting change event",this.oid),this.emit("change",{isLocal:e.isLocal}))};this.changeNested=e=>{this.deepChange(this,e),this.ctx.log("Emitting change event",this.oid),this.emit("change",{isLocal:e.isLocal})};this.deepChange=(e,t)=>{this.cachedDeepUpdatedAt=null,this.cachedView=void 0,this.ctx.log("debug","Deep change detected at",this.oid,"reset cached view"),this.ctx.log("debug","Emitting deep change event",this.oid),this.emit("changeDeep",e,t),this.parent?.deepChange(e,t)};this.getChild=(e,t)=>{let r=Ne(this.schema,e);if(!r)throw new Error(`No schema for key ${String(e)} in ${JSON.stringify(this.schema)}`);return this.entityFamily.get({oid:t,schema:r,entityFamily:this.entityFamily,metadataFamily:this.metadataFamily,parent:this,ctx:this.ctx,files:this.files,fieldPath:[...this.fieldPath,e],patchCreator:this.patchCreator,events:this.events,deleteSelf:this.delete.bind(this,e)})};this.get=e=>{Pi(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=Ne(this.schema,e);if(!s)throw new Error(`No schema for key ${String(e)} in ${JSON.stringify(this.schema)}`);if(Q(r))if(be(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});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:Be({field:s,value:r,fieldPath:[...this.fieldPath,e],depth:1,requireDefaults:!0})?Pe(s)?gi(s):ve(s)?null:void 0:r};this.getOrSet=(e,t)=>{Pi(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()}`);Ci(e)||(e=ae(e,!1));let r=Ne(this.schema,t);if(r){Ve(e,r);let s=Be({field:r,value:e,fieldPath:[...this.fieldPath,t]});if(s)throw new Error(s.message)}return rt(e,this.files.add)};this.getDeleteMode=e=>{if(this.readonlyKeys.includes(e))return!1;if(this.schema.type==="any"||this.schema.type==="map")return"delete";if(this.schema.type==="object"){let t=this.schema.properties[e];if(!t||t.type==="any")return"delete";if(t.type==="map")return!1;if(t.nullable)return"null"}return!1};this.getItemRefValue=e=>{if(e instanceof n)return ce(e.oid);if(e instanceof ue)return Lt(e.id);if(typeof e=="object"){let t=pe(e);if(!t||!this.entityFamily.has(t))throw new Error(`Cannot move object ${JSON.stringify(e)} which does not exist in this list`);return ce(t)}else return e};this.set=(e,t,r)=>{Pi(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={};$(o,this.oid);for(let[a,h]of Object.entries(e)){if(this.readonlyKeys.includes(a))throw new Error(`Cannot set readonly key ${a.toString()}`);if(h===void 0&&!s)continue;let d=Ne(this.schema,a);d&&Ve(h,d),o[a]=this.processInputValue(h,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(Q(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 Q(t)?this.view.some(r=>{if(Q(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()};L(!!e,"oid is required"),this.oid=e,this.readonlyKeys=h||[],this.ctx=o,this.files=d,this.schema=t,this.entityFamily=r||new gn({initial:[this]}),this.patchCreator=m,this.metadataFamily=a,this.events=v,this.parent=s,this._deleteSelf=b,this.parent||(v.add.attach(this.onAdd),v.replace.attach(this.onReplace),v.resetAll.attach(this.onResetAll))}get metadata(){return this.metadataFamily.get(this.oid)}get viewData(){return this._viewData===void 0&&(this._viewData=this.metadata.computeView(),this.validate()),this._viewData}get rawView(){return this.viewData.view}get view(){if(this.cachedView!==void 0)return this.cachedView;if(this.viewData.deleted)return null;let e=this.rawView;if(!e&&!ve(this.schema)||this.schema.type==="array"&&!Array.isArray(e)||(this.schema.type==="object"||this.schema.type==="map")&&!N(e))return Pe(this.schema)?gi(this.schema):null;if(this.cachedView=this.isList?[]:{},$(this.cachedView,this.oid),Array.isArray(e)){let r=Ne(this.schema,0);if(!r)this.ctx.log("error","No child field schema for list entity.",this.oid);else for(let s=0;s<e.length;s++){let o=this.get(s);this.childIsNull(o)&&!ve(r)?this.ctx.log("error","Child missing in non-nullable field",this.oid,"index:",s):this.cachedView.push(o)}}else if(N(e)){let r=this.schema.type==="object"?Object.keys(this.schema.properties):Object.keys(e);for(let s of r){let o=Ne(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)&&!ve(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 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 Pi(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 Ai=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=ae(this.baseline?.snapshot??void 0),t=this.baseline?.timestamp??null,r=this.applyOperations(e,!e,this.confirmedOperations,t,t);r.futureSeen&&this.ctx.globalEvents.emit("futureSeen",r.futureSeen);let s=i?r:this.applyOperations(r.view,r.deleted,this.pendingOperations,r.latestTimestamp,null);s.view&&$(s.view,this.oid);let o=!!r.latestTimestamp&&ei(r.latestTimestamp,this.ctx.getNow())<0,a=!this.baseline&&!this.pendingOperations.length&&!this.confirmedOperations.length;a&&this.ctx.log("warn",`Tried to load Entity ${this.oid} with no data`);let h=s.latestTimestamp??r.latestTimestamp??t,d=h?ti(h):0;if(!s.view&&!s.deleted&&!a){this.ctx.log("warn",`Entity ${this.oid} has no view, no deleted flag, and not empty`);debugger}return{view:s.view??void 0,deleted:s.deleted,empty:a,fromOlderVersion:o,updatedAt:d}};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=this.ctx.getNow();for(let h of t)if(!(s&&h.timestamp<=s)){if(ei(h.timestamp,a)>0){o=h.timestamp;continue}h.data.op==="delete"?e=!0:(i=Ue(i,h.data),h.data.op==="initialize"&&(e=!1)),(!r||h.timestamp>r)&&(r=h.timestamp)}return{view:i,latestTimestamp:r??null,deleted:e,futureSeen:o}};L(i,"oid is required"),this.ctx=e,this.oid=i,t&&(this.confirmedOperations=t),r&&(this.pendingOperations=r),s&&(this.baseline=s)}},yn=class{constructor({ctx:i,onPendingOperations:e,rootOid:t}){this.entities=new Map;this.get=i=>(L(i,"oid is required"),this.entities.has(i)||this.entities.set(i,new Ai({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)}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 _t="@@default",bn=class{constructor({batchTimeout:i=200,meta:e,ctx:t,entities:r}){this.currentBatchKey=_t;this.flushOperations=async(i,e,t)=>{if(this.ctx.log("debug","Flushing",i.length,"operations from batch",e,"to storage / sync"),!i.length)return;let r=[],s={};for(let o=i.length-1;o>=0;o--){let a=i[o],h=s[a.oid];if(h&&Lr(a,h)){this.entities.discardPendingOperation(a);continue}let d=Mr(a);d!==!1&&(s[a.oid]||(s[a.oid]=new Set),s[a.oid].add(d)),r.unshift(a)}for(let o of r)o.timestamp=this.meta.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=Nt(),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=_t,o),commit:async()=>(await this.batcher.flush(_t),s.flush()),flush:()=>o.commit(),discard:()=>{this.batcher.discard(e)}};return o};this.flushAll=()=>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.meta.now;return await this.commitOperations(e,{undoable:!1}),t}:null};this.getInverseOperations=async({ops:i,source:e})=>{let t=yt(i),r=[],s=()=>this.meta.now;return await Promise.all(Object.entries(t).map(async([o,a])=>{let d=(e??await this.entities.hydrate(z(o)))?.__getViewData__(o,"confirmed");if(!d){this.ctx.log("warn","could not find entity",o,"for undo operation",i);return}let m=Kr(o,d.view,a,s);r.unshift(...m)})),r};this.meta=e,this.ctx=t,this.entities=r,this.defaultBatchTimeout=i,this.batcher=new tt(this.flushOperations),this.batcher.add({key:_t,items:[],max:100,timeout:i,userData:{undoable:!0}})}get isDefaultBatch(){return this.currentBatchKey===_t}};var wn=class extends oe{constructor({ctx:e}){super(e.documentDb,{log:e.log});this.reset=async()=>{let e=Object.keys(this.ctx.schema.collections),t=this.ctx.documentDb.transaction(e,"readwrite");await Promise.all(e.map(r=>{let s=t.objectStore(r);return J(s.clear())})),this.ctx.entityEvents.emit("collectionsChanged",e),this.ctx.log("info","\u{1F4A8} Reset queryable storage")};this.saveEntities=async(e,t)=>{if(e.length===0)return;let r=Array.from(new Set(e.map(a=>me(a.oid).collection))),s=r.filter(a=>!this.ctx.schema.collections[a]);if(s.length>0){this.ctx.log("warn",`Ignoring entities from collections that no longer exist: ${s.join(", ")}`);let a=new Set(r);s.forEach(h=>a.delete(h)),r=Array.from(a)}let o={transaction:this.createTransaction(r,{mode:"readwrite",abort:t?.abort})};await Promise.all(e.map(async a=>{let h=a.getSnapshot();try{await this.saveDocument(a.oid,h,o)}catch(d){throw this.ctx.log("error",`Error saving document ${a.oid} (${JSON.stringify(h)})`,d),d instanceof Error?d:new Error("Unknown error saving document")}})),o.transaction.commit(),this.ctx.entityEvents.emit("collectionsChanged",r);for(let a of e)this.ctx.entityEvents.emit("documentChanged",a.oid)};this.saveDocument=async(e,t,{transaction:r})=>{this.ctx.log("debug",`Saving document indexes for querying ${e}`,t);let{collection:s,id:o}=me(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],h=Wt(a,t);await this.run(s,d=>d.put(h),{mode:"readwrite",transaction:r}),this.ctx.log("debug",`Saved document indexes for querying ${e}`,t)}};this.ctx=e,this.addDispose(this.ctx.internalEvents.subscribe("documentDbChanged",t=>{this.db=t}))}};var Cn=Me(Ms(),1);var Pn=class extends Ie{constructor({ctx:e,meta:t,files:r}){super();this.events={add:new Cn.WeakEvent,replace:new Cn.WeakEvent,resetAll:new Cn.WeakEvent};this.cache=new Map;this.pendingEntityPromises=new Map;this.abortDataQueueController=new AbortController;this.ongoingResetPromise=null;this.entityFinalizationRegistry=new FinalizationRegistry(e=>{this.ctx.log("debug","Entity GC",e)});this.addData=async e=>{if(this.disposed){this.ctx.log("warn","EntityStore is disposed, not adding incoming data");return}e.reset&&(this.ctx.log("info","Resetting local store to replicate remote synced data - dropping any current transactions"),this.abortDataQueueController.abort(0),this.abortDataQueueController=new AbortController,this.ongoingResetPromise=this.resetData().finally(()=>{this.ongoingResetPromise=null})),this.ongoingResetPromise&&(this.ctx.log("debug","Waiting for ongoing reset to complete"),await this.ongoingResetPromise,this.ctx.log("debug","Ongoing reset complete")),await this.processData(e)};this.resetData=async()=>{if(this.disposed){this.ctx.log("warn","EntityStore is disposed, not resetting local data");return}await this.meta.reset(),await this.queryableStorage.reset(),this.events.resetAll.invoke(this)};this.processData=async e=>{if(this.disposed){this.ctx.log("warn","EntityStore is disposed, not processing incoming data");return}let t=e?.baselines??[],r=e?.operations??[];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=>z(m.oid)).concat(r.map(m=>z(m.oid))))),o=jr(t),a=Br(r);this.ctx.log("debug","Applying data to live entities");for(let m of s){let v=o[m],b=a[m]??[],D=yt(b),w=e.reset?this.events.replace:this.events.add,x=this.pendingEntityPromises.get(m);x?x.then(()=>{w.invoke(this,{oid:m,baselines:v,operations:D,isLocal:!1})}):w.invoke(this,{oid:m,baselines:v,operations:D,isLocal:!1})}let h={abort:this.abortDataQueueController.signal};await this.meta.insertData(e,h);let d=await Promise.all(s.map(async m=>await this.hydrate(m,h)??{oid:m,getSnapshot(){return null}}));try{await this.queryableStorage.saveEntities(d,h)}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(!Tr(e))throw new Error("Cannot hydrate non-root entity");if(this.cache.has(e)){this.ctx.log("debug","Hydrating entity from cache",e);let s=this.cache.get(e);if(s){let o=s.deref();if(o)return o.deleted?null: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 entity hydration",e),r;{this.ctx.log("debug","Hydrating entity from storage",e);let s=this.constructEntity(e);if(!s)return 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}={})=>{this.ctx.log("debug","Creating new entity",t);let{collection:s}=me(t);$t(e);let o=rt(e,this.files.add);$(o,t);let a=this.constructEntity(t);if(!a)throw new Error(`Could not put new document: no schema exists for collection ${s}`);let h=this.meta.patchCreator.createInitialize(o,t);await this.batcher.commitOperations(h,{undoable:!!r,source:a});let d=yt(h);return this.events.add.invoke(this,{operations:d,isLocal:!0,oid:t}),this.cache.set(t,this.ctx.weakRef(a)),a};this.deleteAll=async(e,t)=>{this.ctx.log("info","Deleting documents",e),L(e.every(o=>o===z(o)),"Only root documents may be deleted via client methods");let r=await Promise.all(e.flatMap(async o=>(await this.hydrate(o))?.__getFamilyOids__()??[]));e.forEach(o=>{this.cache.delete(o),this.ctx.log("debug","Deleted document from cache",o)});let s=this.meta.patchCreator.createDeleteAll(r.flat());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}=me(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 yn({ctx:this.ctx,onPendingOperations:this.onPendingOperations,rootOid:e});return new fe({ctx:this.ctx,oid:e,schema:r,readonlyKeys:s,files:this.files,metadataFamily:o,patchCreator:this.meta.patchCreator,events:this.events,deleteSelf:this.delete.bind(this,e)})};this.onPendingOperations=e=>{this.batcher.addOperations(e)};this.discardPendingOperation=e=>{let t=z(e.oid);this.cache.get(t)?.deref()?.__discardPendingOperation__(e)};this.loadEntity=async(e,t)=>{let{operations:r,baselines:s}=await this.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}),this.cache.set(e.oid,this.ctx.weakRef(e)),this.entityFinalizationRegistry.register(e,e.oid),e)};this.ctx=e,this.meta=t,this.files=r,this.queryableStorage=new wn({ctx:e}),this.batcher=new bn({ctx:e,meta:t,entities:this})}get batch(){return this.batcher.batch}get flushAllBatches(){return this.batcher.flushAll}};var qi=Symbol("handleMessage"),Sa,Et=class extends V{constructor({initialPresence:e,updateBatchTimeout:t=200,defaultProfile:r,replicaStore: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[Sa]=async(e,t)=>{let r=!1,s=new Set(this.peerIds);if(t.type==="presence-changed")this.isSelf(e,t.userInfo)?(this._self=t.userInfo,this._selfReplicaIds.add(t.userInfo.replicaId),this.emit("selfChanged",t.userInfo)):(s.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={},s.clear();for(let[o,a]of Object.entries(t.peerPresence))this.isSelf(e,a)?(this._self=a,this._selfReplicaIds.add(a.replicaId),this.emit("selfChanged",a)):(r=!0,s.add(o),this._peers[o]=a,this.emit("peerChanged",o,a))}else if(t.type==="presence-offline"){s.delete(t.userId),this._selfReplicaIds.delete(t.replicaId);let o=this._peers[t.userId];delete this._peers[t.userId],r=!0,this.emit("peerLeft",t.userId,o)}r&&(this._peerIds=Array.from(s),this.emit("peersChanged",this._peers))};this.update=async e=>{this._updateBatch.update({items:[e]}),this.self.presence={...this.self.presence,...e},this.emit("selfChanged",this.self)};this.flushPresenceUpdates=e=>{let t=e.reduce((r,s)=>({...r,...s}),this.self.presence);this.emit("update",t)};this.self.presence=e,this.self.profile=r,this.self.id="",this.self.replicaId="",s.get().then(o=>{this.self.replicaId=o.id}),this._updateBatcher=new tt(this.flushPresenceUpdates),this._updateBatch=this._updateBatcher.add({max:25,timeout:t,items:[],key:"default"})}static{Sa=qi}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 An=class{constructor({endpointProvider:i,log:e}){this.uploadFile=async i=>{let e=i.file;if(!e)throw new Error("Cannot upload a non-local file");let{files:t,token:r}=await this.endpointProvider.getEndpoints(),s=new window.FormData;s.append("file",e);try{let o=await fetch(t+`/${i.id}`,{method:"POST",body:s,credentials:"include",headers:{Authorization:`Bearer ${r}`}});return o.ok?(this.log("info","File upload successful"),{success:!0,retry:!1}):(this.log("error","File upload failed",o.status,await o.text()),{success:!1,retry:o.status>=500})}catch(o){return this.log("error","File upload failed",o),{success:!1,retry:!0}}};this.getFile=async i=>{let{files:e,token:t}=await this.endpointProvider.getEndpoints();try{let r=await fetch(e+`/${i}`,{method:"GET",credentials:"include",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`}});return r.ok?{success:!0,data:await r.json()}:(this.log("error","File information fetch failed",r.status,await r.text()),{success:!1,retry:r.status>=500||r.status===404})}catch(r){return this.log("error","File information fetch failed",r),{success:!1,error:r,retry:!0}}};this.endpointProvider=i,this.log=e}};var ot=class extends V{constructor({interval:e=15*1e3,deadlineLength:t=3*1e3,restartOnTabFocus:r=!0}={}){super();this.nextBeat=null;this.deadline=null;this.keepAlive=()=>{this.deadline&&(clearTimeout(this.deadline),this.deadline=null,this.start())};this.start=(e=!1)=>{this.stop(),e?this.beat():this.nextBeat=setTimeout(this.beat,this._interval)};this.stop=()=>{this.nextBeat&&clearTimeout(this.nextBeat),this.deadline&&clearTimeout(this.deadline)};this.beat=async()=>{this.emit("beat"),this.deadline=setTimeout(this.onDeadline,this.deadlineLength)};this.onDeadline=()=>{this.deadline=null,this.emit("missed")};this.setInterval=e=>{this._interval=e};this._interval=e,this.deadlineLength=t,typeof window<"u"&&r&&(window.addEventListener("pageshow",()=>this.start(!0)),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&this.start(!0)}))}get interval(){return this._interval}};var Rn=class extends V{constructor({endpointProvider:e,meta:t,presence:r,interval:s=15*1e3,log:o=()=>{},fetch:a=window.fetch.bind(window)}){super();this.mode="pull";this._isConnected=!1;this._status="paused";this._hasSynced=!1;this.setInterval=e=>{this.heartbeat.setInterval(e)};this.sendRequest=async e=>{this.log("Sending sync request",e);try{let{http: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.log("Sync request failed",s.status,await s.text()),this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1));let o=await s.json();Hr(o)&&o.code===wt.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.log(t),this.heartbeat.keepAlive()}};this.handleServerMessage=async e=>{e.type==="sync-resp"&&(this._hasSynced=!0,e.ackThisNonce&&(this.log("Sending sync ack",e.ackThisNonce),await this.sendRequest([await this.meta.messageCreator.createAck(e.ackThisNonce)]))),this.emit("message",e)};this.send=e=>{switch(e.type){case"presence-update":case"sync":case"heartbeat":return this.sendRequest([e]);case"op":if(this._hasSynced)return this.sendRequest([e]);break}};this.destroy=()=>{this.dispose(),this.stop()};this.onHeartbeat=async()=>{this.sendRequest([await this.meta.messageCreator.createPresenceUpdate(this.presence.self.presence),await this.meta.messageCreator.createSyncStep1()])};this.onHeartbeatMissed=async()=>{this.emit("onlineChange",!1),this.log("Missed heartbeat"),this._isConnected=!1};this.syncOnce=async()=>{await this.sendRequest([await this.meta.messageCreator.createSyncStep1()])};this.log=o,this.meta=t,this.presence=r,this.endpointProvider=e,this.fetch=a,this.heartbeat=new ot({interval:s}),this.heartbeat.subscribe("beat",this.onHeartbeat),this.heartbeat.subscribe("missed",this.onHeartbeatMissed)}get interval(){return this.heartbeat.interval}start(){this.status!=="active"&&(this.heartbeat.start(!0),this._status="active")}stop(){this.heartbeat.stop(),this._status="paused"}reconnect(){this.heartbeat.start(!0)}ignoreIncoming(){this.stop()}get isConnected(){return this._isConnected}get status(){return this._status}};function Hi(n){this.message=n}Hi.prototype=new Error,Hi.prototype.name="InvalidCharacterError";var Ls=typeof window<"u"&&window.atob&&window.atob.bind(window)||function(n){var i=String(n).replace(/=+$/,"");if(i.length%4==1)throw new Hi("'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 Ia(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(Ls(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 Ls(i)}}function Fn(n){this.message=n}function _a(n,i){if(typeof n!="string")throw new Fn("Invalid token specified");var e=(i=i||{}).header===!0?0:1;try{return JSON.parse(Ia(n.split(".")[e]))}catch(t){throw new Fn("Invalid token specified: "+t.message)}}Fn.prototype=new Error,Fn.prototype.name="InvalidTokenError";var Us=_a;var Tn=class{constructor(i){this.config=i;this.cached=null;this.type=ke.Realtime;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(h=>{if(h.ok)return h.json();throw new Error(`Auth endpoint returned non-200 response: ${h.status}`)}),L(i.accessToken,"No access token provided from auth endpoint");let e=Us(i.accessToken);L(e.url,"No sync endpoint provided from auth endpoint"),L(e.type!==void 0,"No replica type provided from auth endpoint"),this.type=parseInt(e.type+"");let 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")}};var kn=class extends V{constructor(e){super();this.timer=null;this.isScheduled=!1;this.next=()=>{this.isScheduled||(this.isScheduled=!0,this.timer=setTimeout(()=>{this.emit("trigger"),this.isScheduled=!1,this.backoff.next()},this.backoff.current))};this.reset=()=>{this.backoff.reset(),this.timer&&(clearTimeout(this.timer),this.timer=null)};this.backoff=e}},Bn=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 jn=class extends V{constructor({endpointProvider:e,meta:t,presence:r,log:s}){super();this.socket=null;this.connectQueue=[];this.syncQueue=[];this.incomingQueue=[];this._status="paused";this.synced=!1;this.hasStartedSync=!1;this._ignoreIncoming=!1;this.mode="realtime";this.log=(...e)=>{};this.heartbeat=new ot;this.reconnectScheduler=new kn(new Bn(60*1e3,1.5));this.onOpen=()=>{if(!this.socket)throw new Error("Invalid sync state: online but socket is null");if(this.synced=!1,this.connectQueue.length){for(let e of this.connectQueue)this.log("Sending queued message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e));this.connectQueue=[]}this.log("Sync connected"),this.onOnlineChange(!0),this.reconnectScheduler.reset()};this.onOnlineChange=async e=>{this.log("Socket online change",e),!this.disposed&&(e?(this.log("Starting sync"),this.hasStartedSync=!0,this.synced=!1,this.send(await this.meta.messageCreator.createPresenceUpdate(this.presence.self.presence)),this.send(await this.meta.messageCreator.createSyncStep1()),this.heartbeat.start()):(this.hasStartedSync=!1,this.synced=!1,this.heartbeat.stop()),this.emit("onlineChange",e))};this.onMessage=async e=>{if(this._ignoreIncoming){this.log("Ignoring incoming message (ignore incoming flag set)",e.data);return}let t=JSON.parse(e.data);switch(t.type){case"sync-resp":if(t.ackThisNonce&&this.send(await this.meta.messageCreator.createAck(t.ackThisNonce)),this.hasStartedSync=!0,this.synced=!0,this.syncQueue.length)if(t.overwriteLocalData)this.log("warn","Overwriting local data - dropping outgoing message queue"),this.syncQueue=[];else{for(let r of this.syncQueue)this.send(r);this.syncQueue=[]}if(this.emit("message",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.log("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.log(e),this.reconnectScheduler.next(),this.log("Attempting reconnect to websocket sync")};this.onClose=e=>{this.log("Sync disconnected"),this.onOnlineChange(!1),this.onError(e)};this.initializeSocket=async()=>{let e=await this.endpointProvider.getEndpoints();return this.socket=new WebSocket(e.websocket,["Bearer",e.token]),this.socket.addEventListener("message",this.onMessage),this.socket.addEventListener("open",this.onOpen),this.socket.addEventListener("error",this.onError),this.socket.addEventListener("close",this.onClose),this.socket};this.sendHeartbeat=async()=>{this.send(await this.meta.messageCreator.createHeartbeat())};this.reconnect=()=>{this.stop(),this.start()};this.canSkipSyncWait=e=>e.type==="sync"||e.type==="presence-update"||e.type==="sync-ack"||e.type==="heartbeat";this.send=e=>{this.status==="active"&&(!this.hasStartedSync&&!this.canSkipSyncWait(e)||(this.canSkipSyncWait(e)?this.socket?.readyState===WebSocket.OPEN?(this.log("Sending message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e))):(this.log("Enqueueing message until socket is open",JSON.stringify(e,null,2)),this.connectQueue.push(e)):this.synced?this.socket?.readyState===WebSocket.OPEN&&(this.log("Sending message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e))):this.hasStartedSync&&(this.log("Enqueueing message until synced",JSON.stringify(e,null,2)),this.syncQueue.push(e))))};this.destroy=()=>{this.dispose(),this.stop()};this.start=()=>{this.socket||(this.initializeSocket(),this._status="active")};this.stop=()=>{this.socket?.removeEventListener("message",this.onMessage),this.socket?.removeEventListener("close",this.onClose),this.socket?.close(),this.socket=null,this._status="paused"};this.log=s||this.log,this.endpointProvider=e,this.meta=t,this.presence=r,this.reconnectScheduler.subscribe("trigger",this.initializeSocket),this.heartbeat.subscribe("beat",this.sendHeartbeat)}ignoreIncoming(){this.incomingQueue=[],this._ignoreIncoming=!0}get isConnected(){return this.socket?.readyState===WebSocket.OPEN}get status(){return this._status}};var Mn=class extends V{constructor({meta:e}){super();this.mode="pull";this.destroy=()=>{};this.isConnected=!1;this.status="paused";this.pullInterval=0;this.uploadFile=async()=>({success:!1,retry:!1});this.getFile=async()=>({success:!1,retry:!1});this.syncOnce=async()=>{};this.presence=new Et({initialPresence:null,defaultProfile:null,replicaStore:e.localReplica})}send(){}start(){}stop(){}ignoreIncoming(){}reconnect(){}setMode(){}setPullInterval(){}},at=class extends V{constructor({authEndpoint:e,fetchAuth:t,fetch:r,initialPresence:s,automaticTransportSelection:o=!0,autoStart:a,initialTransport:h,pullInterval:d,presenceUpdateBatchTimeout:m,defaultProfile:v,useBroadcastChannel:b,onOutgoingMessage:D},{meta:w,ctx:x,onData:_}){super();this.broadcastChannel=null;this._activelySyncing=!1;this.handleBroadcastChannelMessage=e=>{e.data.type==="sync"&&this.handleMessage(e.data.message,{source:"broadcastChannel"})};this.onTokenExpired=()=>{this.endpointProvider.clearCache()};this.handleMessage=async(e,{source:t}={source:"network"})=>{if(e.type==="op-re"||e.type==="sync-resp")for(let r of e.operations)this.meta.time.update(r.timestamp);switch(this.log("sync message",JSON.stringify(e,null,2)),e.type){case"op-re":await this.onData({operations:e.operations,baselines:e.baselines}),e.globalAckTimestamp&&await this.meta.setGlobalAck(e.globalAckTimestamp);break;case"global-ack":await this.meta.setGlobalAck(e.timestamp);break;case"sync-resp":this._activelySyncing=!0,this.emit("syncingChange",!0),await this.onData({operations:e.operations,baselines:e.baselines,reset:e.overwriteLocalData}),e.globalAckTimestamp&&await this.meta.setGlobalAck(e.globalAckTimestamp),await this.meta.updateLastSynced(e.ackedTimestamp),this._activelySyncing=!1,this.emit("syncingChange",!1);break;case"need-since":this.activeSync.send(await this.meta.messageCreator.createSyncStep1(e.since));break;case"server-ack":await this.meta.updateLastSynced(e.timestamp)}t==="network"&&this.broadcastChannel?.postMessage({type:"sync",message:e}),this.presence[qi](await this.meta.localReplica.get(),e)};this.handleOnlineChange=e=>{this.emit("onlineChange",e)};this.handlePresenceUpdate=async e=>{this.send(await this.meta.messageCreator.createPresenceUpdate(e))};this.setMode=e=>{if(e==="realtime"&&!this.canDoRealtime)throw new Error("Cannot switch to realtime mode, because the current auth token does not allow it");let t;e==="realtime"?t=this.webSocketSync:t=this.pushPullSync,t!==this.activeSync&&(this.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=>{this.activeSync.status==="active"&&(await this.activeSync.send(e),this.onOutgoingMessage?.(e))};this.uploadFile=async e=>(this.log("info","Uploading file",{name:e.name,type:e.type,id:e.id}),this.activeSync.status==="active"?this.fileSync.uploadFile(e):{success:!1,retry:!1});this.getFile=async e=>{if(this.activeSync.status==="active")return this.fileSync.getFile(e);throw new Error("Offline, cannot retrieve remote file details")};this.start=()=>this.activeSync.start();this.stop=()=>this.activeSync.stop();this.destroy=()=>{this.dispose(),this.webSocketSync.destroy(),this.pushPullSync.destroy()};this.reconnect=()=>this.activeSync.reconnect();this.syncOnce=()=>this.pushPullSync.syncOnce();if(this.meta=w,this.onData=_,this.log=x.log,this.onOutgoingMessage=D,this.presence=new Et({initialPresence:s,defaultProfile:v,updateBatchTimeout:m,replicaStore:w.localReplica}),this.endpointProvider=new Tn({authEndpoint:e,fetchAuth:t,fetch:r}),this.webSocketSync=new jn({endpointProvider:this.endpointProvider,meta:w,presence:this.presence,log:this.log}),this.pushPullSync=new Rn({endpointProvider:this.endpointProvider,meta:w,presence:this.presence,log:this.log,interval:d,fetch:r}),this.fileSync=new An({endpointProvider:this.endpointProvider,log:this.log}),b&&"BroadcastChannel"in window&&(this.broadcastChannel=new BroadcastChannel(`verdant-${x.namespace}`),this.broadcastChannel.addEventListener("message",this.handleBroadcastChannelMessage)),h==="realtime"?this.activeSync=this.webSocketSync:this.activeSync=this.pushPullSync,this.presence.subscribe("update",this.handlePresenceUpdate),this.meta.subscribe("message",this.send),this.webSocketSync.subscribe("message",this.handleMessage),this.webSocketSync.subscribe("onlineChange",this.handleOnlineChange),this.pushPullSync.subscribe("message",this.handleMessage),this.pushPullSync.subscribe("onlineChange",this.handleOnlineChange),o&&this.canDoRealtime){let O=()=>{I&&clearTimeout(I);let y=Object.keys(this.presence.peers).length>0||o!=="peers-only"&&this.presence.selfReplicaIds.size>1;y&&this.mode==="pull"?this.setMode("realtime"):!y&&this.mode==="realtime"&&(I=setTimeout(()=>{Object.keys(this.presence.peers).length===0&&this.setMode("pull")},1e3))},I;this.presence.subscribe("peersChanged",O),o!=="peers-only"&&this.presence.subscribe("selfChanged",O)}a&&this.start()}get canDoRealtime(){return this.endpointProvider.type===ke.Realtime||this.endpointProvider.type===ke.PassiveRealtime||this.endpointProvider.type===ke.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 Da(n){return n!==null}function Wi(n){return Array.isArray(n)?n.map(Wi).filter(Da):n instanceof fe&&n.deleted?null:n}function je(n,i){return!n&&!i||n&&i&&Fe(n)===Fe(i)}var Qi=Symbol("ON_ALL_UNSUBSCRIBED"),he=Symbol("UPDATE"),Ea,ge=class extends Ie{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=Wi(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 fe&&(this._internalUnsubscribes.push(t.subscribe("delete",this.refreshValue)),this._internalUnsubscribes.push(t.subscribe("restore",this.refreshValue)))}):e instanceof fe&&(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[Ea]=e=>{this._allUnsubscribedHandler=e};this._rawValue=e,this._value=e,this.isListQuery=Array.isArray(e),this._events=new V(h=>{h==="change"&&this._allUnsubscribedHandler?.(this)}),this.context=t,this.key=s,this.collection=r;let a=o||(h=>h.includes(r));this.addDispose(this.context.entityEvents.subscribe("collectionsChanged",h=>{a(h)&&(this.context.log("info","Updating query",this.key),this.execute())}))}static{Ea=Qi}get current(){return this._value}get resolved(){return this.status==="ready"?Promise.resolve(this._value):this._executionPromise??this.execute()}get subscribed(){return this._events.totalSubscriberCount()>0}get status(){return this._status}set status(e){this._status!==e&&(this._status=e,this._events.emit("statusChange",this._status))}get hasDeleted(){return this.isListQuery?this._rawValue.length!==this._value.length:!!this._rawValue&&!this._value}subscribe(e,t){if(t===void 0&&typeof e=="function")return this.resolved,this._events.subscribe("change",e);if(e==="change"&&t!==void 0)return this.resolved,this._events.subscribe("change",t);if(e==="statusChange"&&typeof t=="function")return this._events.subscribe(e,t);throw new Error("Invalid invocation of Query.subscribe")}};var Ln=class extends ge{constructor({id:e,hydrate:t,...r}){super({initial:null,...r});this.run=async()=>{let e=await this.hydrate(this.oid);this.setValue(e)};this.oid=Z(r.collection,e),this.hydrate=t}};var Ca,Un=class extends ge{constructor({index:e,hydrate:t,...r}){super({initial:null,...r});this.run=async()=>{let e=await ln({collection:this.collection,index:this.index,context:this.context});this.setValue(e?await this.hydrate(e):null)};this[Ca]=e=>{je(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=t}static{Ca=he}};var Pa,Vn=class extends ge{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 Ot({collection:this.collection,index:this.index,context:this.context,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[Pa]=e=>{je(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=t,this._pageSize=r,this._page=s}static{Pa=he}get pageSize(){return this._pageSize}get page(){return this._page}get hasNextPage(){return this._hasNextPage}get hasPreviousPage(){return this._page>0}};var Aa,Nn=class extends ge{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 Ot({collection:this.collection,context:this.context,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 Ot({collection:this.collection,context:this.context,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=>{je(this.index,e)||(this.index=e,this.execute())};this.index=r,this.hydrate=e,this._pageSize=t}static{Aa=he}get pageSize(){return this._pageSize}get hasMore(){return this._hasNextPage}};var Ra,$n=class extends ge{constructor({index:e,hydrate:t,...r}){super({initial:[],...r});this.run=async()=>{let e=await dn({collection:this.collection,index:this.index,context:this.context});this.context.log("debug",`FindAllQuery: ${e.length} oids found: ${e}`),this.setValue(await Promise.all(e.map(this.hydrate)))};this[Ra]=e=>{je(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=t}static{Ra=he}};var zn=class{constructor({collection:i,cache:e,entities:t,context:r,documentManager:s}){this.serializeIndex=i=>i?Fe(i):"";this.get=i=>{let e=`get:${this.collection}:${i}`;return this.cache.getOrSet(e,()=>new Ln({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 Un({index:i,collection:this.collection,hydrate:this.hydrate,context:this.context,key:t}),r=>{r[he](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[he](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 Vn({index:i,collection:this.collection,hydrate:this.hydrate,context:this.context,key:s,pageSize:e,page:t}),o=>{o[he](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 Nn({index:i,collection:this.collection,hydrate:this.hydrate,context:this.context,key:r,pageSize:e}),s=>{s[he](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)}};var Kn=class extends Ie{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._cache.forEach(e=>e.dispose()),this._cache.clear()};this._evictionTime=e,this.context=t}get(e){return this._cache.get(e)||null}set(e){return this._cache.set(e.key,e),e[Qi](this.onQueryUnsubscribed),e}getOrSet(e,t,r){let s=this.get(e);return s?(r?.(s),s):this.set(t())}};var Je=class extends V{constructor(e,t,r){super();this.config=e;this.context=t;this._closed=!1;this.addData=e=>this._entities.addData(e);this.stats=async()=>{let e=Object.keys(this.schema.collections),t={};if(this.disposed)return{};for(let d of e)try{t[d]=await vt(this.documentDb,d)}catch(m){this.context.log?.("error",m)}if(this.disposed)return{collections:t};let r=await this.meta.stats(),s=typeof navigator<"u"&&typeof navigator.storage<"u"&&"estimate"in navigator.storage?await navigator.storage.estimate():void 0,o=Object.values(t).reduce((d,{size:m})=>d+m,0),a=r.baselinesSize.size+r.operationsSize.size,h=a/o;return{collections:t,meta:r,storage:s,totalMetaSize:a,totalCollectionsSize:o,metaToDataRatio:h,quotaUsage:s?.usage&&s?.quota?s.usage/s.quota:void 0}};this.close=async()=>{this._closed=!0,this.sync.ignoreIncoming(),await this._entities.flushAllBatches(),this._fileManager.close(),this.sync.stop(),this.sync.destroy(),await this._entities.destroy(),this.meta.close(),await new Promise(async e=>{await Ke(this.documentDb),await Ke(this.metaDb),e()}),this.context.log?.("Client closed")};this.__dangerous__resetLocal=async()=>{this.sync.stop(),await Xt(this.namespace,indexedDB)};this.export=async({downloadRemoteFiles:e}={downloadRemoteFiles:!0})=>{this.context.log("info","Exporting data...");let t=await this.meta.export(),r=await this._fileManager.exportAll(e),s=[],o=[];for(let a of r){let h=a.file;if(delete a.file,s.push(a),h){let d=new File([h],this.getFileExportName(a.name,a.id),{type:a.type});o.push(d)}else this.context.log("warn",`File ${a.id} was could not be loaded locally or from the server. It will be missing in the export.`)}return{data:t,fileData:s,files:o}};this.getFileExportName=(e,t)=>`${t}___${e}`;this.parseFileExportname=e=>{let[t,r]=e.split("___");return{id:t,originalFileName:r}};this.import=async({data:e,fileData:t,files:r})=>{this.context.log("info","Importing data..."),await Ke(this.context.documentDb),await this.meta.resetFrom(e);let s=new Map(r.map(m=>{let{id:v}=this.parseFileExportname(m.name);return[v,m]})),o=t.map(m=>{let v=s.get(m.id);return{...m,file:v}});await this._fileManager.importAll(o);let a=e.schema.version,h=indexedDB.deleteDatabase([this.namespace,"collections"].join("_"));await new Promise((m,v)=>{h.onsuccess=m,h.onerror=v});let d=this.context.schema;if(d.version!==a)throw new Error("Only exports from the current schema version can be imported");this.context.documentDb=await St({meta:this.meta,migrations:this.config.migrations,context:this.context,version:a}),this.context.internalEvents.emit("documentDbChanged",this.documentDb),this.context.log("Re-initializing data from imported data..."),await this._entities.addData({operations:e.operations,baselines:e.baselines,reset:!0}),await Ke(this.context.documentDb),this.context.log("Migrating up to latest schema..."),this.context.schema=d,this.context.documentDb=await St({meta:this.meta,migrations:this.config.migrations,context:this.context,version:d.version}),this.context.internalEvents.emit("documentDbChanged",this.documentDb)};this.__dangerous__hardReset=async()=>{let e=await this.export();await this.import(e)};this.meta=r.meta,this.collectionNames=Object.keys(t.schema.collections),this._sync=this.config.syncConfig&&!t.schema.wip?new at(this.config.syncConfig,{meta:this.meta,onData:this.addData,ctx:this.context}):new Mn({meta:this.meta}),t.schema.wip&&this.config.syncConfig&&t.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 mn({db:this.metaDb,sync:this.sync,context:this.context,config:this.config.files,meta:this.meta}),this._entities=new Pn({ctx:this.context,meta:this.meta,files:this._fileManager}),this._queryCache=new Kn({context:t}),this._documentManager=new hn(this.meta,this.schema,this._entities);let s=Pr(()=>{this.emit("futureSeen")},300);this.context.globalEvents.subscribe("futureSeen",s),this.documentDb.addEventListener("versionchange",()=>{this.context.log?.(`Another tab has requested a version change for ${this.namespace}`),this.documentDb.close(),typeof window<"u"&&window.location.reload()}),this.metaDb.addEventListener("versionchange",()=>{this.context.log?.(`Another tab has requested a version change for ${this.namespace}`),this.metaDb.close(),typeof window<"u"&&window.location.reload()});for(let[o,a]of Object.entries(t.schema.collections)){let h=o;this[h]=new zn({collection:h,cache:this._queryCache,context:this.context,entities:this.entities,documentManager:this.documentManager})}}get sync(){return this._sync}get entities(){return this._entities}get documentManager(){return this._documentManager}get documentDb(){return this.context.documentDb}get metaDb(){return this.context.metaDb}get schema(){return this.context.schema}get namespace(){return this.context.namespace}get undoHistory(){return this.context.undoHistory}get batch(){return this.entities.batch}};var Ct=class{constructor(i){this.value=i}deref(){return this.value}};var Vs=Symbol("metadataVersion");var qn=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;return i.schema.wip?e=await this.initializeWIPDatabases(i):(e=await this.initializeDatabases(i),this.cleanupWIPDatabases(i)),this.resolveReady(e),this._resolvedValue=e,e}catch(e){throw e instanceof Error?(this.rejectReady(e),e):new Error("Unknown error initializing storage")}finally{this._initializing=!1}};this.initializeDatabases=async i=>{let e=i[Vs],{db:t}=await an({indexedDB:i.indexedDb,log:i.log,namespace:i.namespace,metadataVersion:e}),r={namespace:this._namespace,metaDb:t,schema:i.schema,log:i.log||(()=>{}),undoHistory:i.undoHistory||new He,entityEvents:new V,globalEvents:new V,internalEvents:new V,weakRef:m=>i.EXPERIMENTAL_weakRefs?new WeakRef(m):new Ct(m),migrations:i.migrations},s=new xt({context:r,disableRebasing:i.disableRebasing,onOperation:i.onOperation});await s.updateSchema(i.schema,i.overrideSchemaConflict);let o=Object.assign(r,{getNow:()=>s.now}),a=await St({context:o,version:i.schema.version,meta:s,migrations:i.migrations,indexedDB:i.indexedDb}),h=Object.assign(o,{documentDb:a});return new Je({syncConfig:i.sync,migrations:i.migrations,files:i.files},h,{meta:s})};this.initializeWIPDatabases=async i=>{let e=Fe(i.schema);console.info(`WIP schema in use. Opening database with hash ${e}`);let t=`@@wip_${i.namespace}_${e}`,{db:r}=await Gr({indexedDB:i.indexedDb,log:i.log,namespace:i.namespace,wipNamespace:t}),s={namespace:this._namespace,metaDb:r,schema:i.schema,log:i.log||(()=>{}),undoHistory:i.undoHistory||new He,entityEvents:new V,globalEvents:new V,internalEvents:new V,weakRef:v=>i.EXPERIMENTAL_weakRefs?new WeakRef(v):new Ct(v),migrations:i.migrations},o=new xt({context:s,disableRebasing:i.disableRebasing}),a=Object.assign(s,{getNow:()=>o.now});await o.updateSchema(i.schema,i.overrideSchemaConflict);let h=await es({context:a,version:i.schema.version,meta:o,migrations:i.migrations,indexedDB:i.indexedDb,wipNamespace:t}),d=Object.assign(a,{documentDb:h});return new Je({syncConfig:i.sync,migrations:i.migrations,files:i.files},d,{meta:o})};this.cleanupWIPDatabases=async i=>{let r=(await Qr(i.indexedDb)).filter(s=>s.name?.startsWith("@@wip_")).map(s=>s.name).filter(s=>!s.startsWith(`@@wip_${i.namespace}_${Fe(i.schema)}`));for(let s of r)await Wr(s,i.indexedDb)};this.open=()=>this.initialize(this.init);this.close=async()=>{this._resolvedValue&&this._resolvedValue.close(),this._initializing&&(await this._readyPromise).close()};this.__dangerous__resetLocal=async()=>{await Xt(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 Ji=Me(Xe(),1);function Fa(n){return n?Ji.default.slug():(0,Ji.default)()}window.Verdant=Gi;
|
|
8
|
+
${JSON.stringify(e)}`),new Error("Schema has changed without a version change! Any changes to your schema must be accompanied by a change in schema version and a migration routine.");await this.schema.set(e)};this.setGlobalAck=async e=>{this._closing||(await this.ackInfo.setGlobalAck(e),this.disableRebasing||await this.runRebase(e))};this.export=async()=>{let e=this.db,[t,r]=await en(e,["baselines","operations"]),o=await this.localReplica.get(),s=await this.schema.get();if(!s)throw new Error("Cannot export Client data before initializing");return{operations:r,baselines:t,localReplica:o,schema:s}};this.resetFrom=async e=>{let r=this.db.transaction(["baselines","operations","info"],"readwrite");await J(r.objectStore("baselines").clear()),await J(r.objectStore("operations").clear()),await J(r.objectStore("info").clear()),await this.localReplica.update({ackedLogicalTime:e.localReplica.ackedLogicalTime,lastSyncedLogicalTime:e.localReplica.lastSyncedLogicalTime},{transaction:r})};this.stats=async()=>{let e=this.db,t=await vt(e,"operations"),r=await vt(e,"baselines");return{operationsSize:t,baselinesSize:r}};this.context=t,this.schema=new ln(t.metaDb,t.schema.version),this.operations=new cn(this.db,{log:t.log}),this.baselines=new on(this.db,{log:t.log}),this.localReplica=new sn(this.db),this.ackInfo=new rn(this.db),this.messageCreator=new an(this),this.patchCreator=new Zt(()=>this.now),this.onOperation=r,e&&(this.disableRebasing=e)}get db(){return this.context.metaDb}get log(){return this.context.log}get now(){return this.time.now(this.schema.currentVersion)}};var Ks=[qs,Hs,Ws,Qs,Js];function dn({indexedDB:n=window.indexedDB,namespace:i,log:e,metadataVersion:t=5}){return new Promise((r,o)=>{let s=n.open(`${i}_meta`,t),a=!1;s.onupgradeneeded=async u=>{let d=s.result,m=s.transaction,S=Ks.slice(u.oldVersion);for(let b of S)await b(d,m);await new Promise((b,C)=>{m.addEventListener("complete",b),m.addEventListener("error",C)}),u.oldVersion||(a=!0)},s.onerror=()=>{console.error("Error opening database",s.error),o(s.error)},s.onsuccess=()=>{r({db:s.result,wasInitialized:a})}})}async function Xr({wipNamespace:n,namespace:i,indexedDB:e,log:t,metadataVersion:r}){let o=await dn({namespace:n,indexedDB:e,log:t,metadataVersion:r});if(!o.wasInitialized)return o;t?.("debug","Beginning copy of production metadata database to WIP");let{db:s}=await dn({namespace:i,indexedDB:e,log:t,metadataVersion:r}),a=s.transaction(["baselines","operations","info"],"readonly"),[u,d,m]=await Promise.all([J(a.objectStore("baselines").getAll()),J(a.objectStore("operations").getAll()),J(a.objectStore("info").getAll())]),S=o.db.transaction(["baselines","operations","info"],"readwrite"),b=S.objectStore("baselines"),C=S.objectStore("operations"),w=S.objectStore("info");for(let v of u)b.put(v);for(let v of d)C.put(v);for(let v of m)w.put(v);return await new Promise((v,_)=>{S.oncomplete=()=>{v()},S.onerror=I=>{_(I)},S.onabort=I=>{_(I)}}),await ge(s),t?.("debug","Finished copy of production metadata database to WIP. Copied:",u.length,"baselines,",d.length,"operations"),o}async function qs(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 Hs(n,i){let e=i.objectStore("operations");await new Promise((t,r)=>{let o=e.openCursor();o.onsuccess=()=>{let s=o.result;if(s){let{isLocal_timestamp:a,documentOid_timestamp:u,...d}=s.value;s.update({...d,l_t:a,d_t:u}),s.continue()}else t()},o.onerror=s=>{r(o.error)}}),e.deleteIndex("isLocal_timestamp"),e.deleteIndex("documentOid_timestamp"),e.createIndex("l_t","l_t",{unique:!1}),e.createIndex("o_t","o_t",{unique:!1}),e.createIndex("d_t","d_t",{unique:!1})}async function Ws(n,i){i.objectStore("operations").createIndex("timestamp","timestamp")}async function Qs(n,i){let e=n.createObjectStore("files",{keyPath:"id"});e.createIndex("remote","remote"),e.createIndex("deletedAt","deletedAt")}async function Js(n,i){let e=i.objectStore("operations");await new Promise((r,o)=>{let s=e.openCursor();s.onsuccess=()=>{let a=s.result;if(a){let u=fi(a.value);u.oid_timestamp!==a.primaryKey?(a.delete(),e.put(u)):a.update(u),a.continue()}else r()},s.onerror=a=>{o(s.error)}});let t=i.objectStore("baselines");await new Promise((r,o)=>{let s=t.openCursor();s.onsuccess=()=>{let a=s.result;if(a){let u=fi(a.value);u.oid!==a.primaryKey?(a.delete(),t.put(u)):a.update(u),a.continue()}else r()},s.onerror=a=>{o(s.error)}})}async function un(n,i,e,t){function r(a,u){let d,m,S=n.open([i,"collections"].join("_"),e);S.onupgradeneeded=async b=>{d=b.oldVersion;let C=S.transaction;m=S.result,C.abort()},S.onsuccess=b=>{a([S.result.version,S.result])},S.onblocked=b=>{t?.("Database blocked, waiting...")},S.onerror=b=>{a([d,m])}}let[o,s]=await new Promise(r);return await ge(s),o}async function Zr(n,i,e,t,r){function o(s,a){let u=n.open([i,"collections"].join("_"),e),d=!1;u.onupgradeneeded=m=>{let S=u.transaction;t(S,u.result,m),d=!0},u.onsuccess=m=>{d?s(u.result):a(new Error("Database was not upgraded when a version change was expected"))},u.onerror=m=>{a(u.error||new Error("Unknown error"))},u.onblocked=m=>{r?.("Database upgrade blocked, waiting...")}}return new Promise(o)}async function eo(n,i){typeof navigator<"u"&&navigator.locks?await navigator.locks.request(`verdant_migration_${n}`,i):await i()}async function je({indexedDB:n=Di,namespace:i,version:e,context:t}){t.log("debug","Opening database",i,"at version",e);let r=await new Promise((o,s)=>{let a=n.open([i,"collections"].join("_"),e);a.onupgradeneeded=async u=>{a.transaction.abort(),t.log("error","Database upgrade needed, but not expected","Expected",e,"Got",a.result.version),s(a.error||new Error(`Migration error: database version changed unexpectedly when reading current data. Expected ${e}, got ${a.result.version}`))},a.onsuccess=u=>{o(a.result)},a.onblocked=u=>{s(new Error("Migration error: database blocked"))},a.onerror=u=>{s(new Error("Migration error: database error"))}});return r.addEventListener("versionchange",o=>{r.close()}),r}async function to(n,i){let e=new Array;for(let u=0;u<n.objectStoreNames.length;u++)e.push(n.objectStoreNames[u]);let t=n.transaction(e,"readonly"),r=e.map(u=>t.objectStore(u)),o=await Promise.all(r.map(u=>J(u.getAll()))),s=i.transaction(e,"readwrite"),a=e.map(u=>s.objectStore(u));for(let u=0;u<a.length;u++)await Promise.all(o[u].map(d=>J(a[u].put(d))))}var Gs=n=>IDBKeyRange.only(Oe(n.equals)),Ys=n=>{},Xs=n=>{let i=n.gte||n.gt,e=n.lte||n.lt;return i===e?IDBKeyRange.only(Oe(i)):i?e?IDBKeyRange.bound(Oe(i),Oe(e),!!n.gt,!!n.lt):IDBKeyRange.lowerBound(Oe(i),!!n.gt):IDBKeyRange.upperBound(Oe(e),!!n.lt)},Zs=(n,i,e)=>{let t=n.collections[i].compounds[e.where];L(t,`Index ${e.where} does not exist on collection ${i}`);let r=Object.keys(e.match).sort((u,d)=>t.of.indexOf(u)-t.of.indexOf(d));for(let u of r)if(t.of.indexOf(u)!==r.indexOf(u))throw new Error(`Compound index ${e.where} does not have ${u} at the start of its order`);let o=r.map(u=>e.match[u]);if(r.length===t.of.length)return IDBKeyRange.only(le(...o));let s=qe(...o),a=Ke(...o);return IDBKeyRange.bound(s,a)};function ea(n){let i=n.startsWith,e=n.startsWith+"\uFFFF";return IDBKeyRange.bound(i,e)}function fn(n,i,e){if(e)return mi(e)?Xs(e):pi(e)?Gs(e):Nr(e)?Ys(e):gi(e)?ea(e):Zs(n,i,e)}function Ei(n,i,e){return n.transaction(i,e?"readwrite":"readonly").objectStore(i)}async function hn({collection:n,index:i,context:e}){let t=Ei(e.documentDb,n),r=i?.where?t.index(i.where):t,o=fn(e.schema,n,i),s=i?.order==="desc"?"prev":"next",a=r.openCursor(o,s);return await new Promise((d,m)=>{a.onsuccess=()=>{let S=a.result;d(S?Y(n,S.primaryKey.toString()):null)},a.onerror=()=>{a.error?.name==="InvalidStateError"?(e.log("error","findOne query failed with InvalidStateError",a.error),d(null)):de(a.error)?d(null):m(a.error)}})}async function pn({collection:n,index:i,context:e}){let t=Ei(e.documentDb,n),r=i?.where?t.index(i.where):t,o=fn(e.schema,n,i),s=i?.order==="desc"?"prev":"next",a=r.openCursor(o,s);return await new Promise((d,m)=>{let S=new Set;a.onsuccess=()=>{let b=a.result;b?(S.add(Y(n,b.primaryKey.toString())),b.continue()):d(Array.from(S))},a.onerror=()=>{a.error?.name==="InvalidStateError"?(e.log("error","findAll query failed with InvalidStateError",a.error),d([])):de(a.error)?d([]):m(a.error)}})}async function Ot({collection:n,index:i,context:e,limit:t,offset:r}){let o=Ei(e.documentDb,n),s=i?.where?o.index(i.where):o,a=fn(e.schema,n,i),u=i?.order==="desc"?"prev":"next",d=s.openCursor(a,u),m=!r,S=!1,b=0;return{result:await new Promise((w,v)=>{let _=new Set;d.onsuccess=()=>{b++;let I=d.result;I?r&&!m?(I.advance(r),m=!0):(t&&_.size<t&&_.add(Y(n,I.primaryKey.toString())),t&&b>t?(S=!0,w(Array.from(_))):I.continue()):w(Array.from(_))},d.onerror=()=>{d.error?.name==="InvalidStateError"?(e.log("error","find query failed with InvalidStateError",d.error),w([])):de(d.error)?w([]):v(d.error)}}),hasNextPage:S}}function no({migration:n,meta:i,getMigrationNow:e,newOids:t}){return n.allCollections.reduce((r,o)=>(r[o]={put:async s=>{Re(n.newSchema.collections[o],s);let a=s[n.newSchema.collections[o].primaryKey],u=Y(o,a);return t.push(u),await i.insertLocalOperations(Pe(s,u,e)),s},delete:async s=>{let a=Y(o,s),u=await i.getAllDocumentRelatedOids(a);return i.insertLocalOperations(u.map(d=>({oid:d,timestamp:e(),data:{op:"delete"}})))}},r),{})}function ta({migration:n,context:i,meta:e}){return n.oldCollections.reduce((t,r)=>(t[r]={get:async o=>{let s=Y(r,o);return await e.getDocumentSnapshot(s,{to:e.time.now(n.oldSchema.version)})},findOne:async o=>{let s=await hn({collection:r,index:o,context:i});return s?await e.getDocumentSnapshot(s,{to:e.time.now(n.oldSchema.version)}):null},findAll:async o=>{let s=await pn({collection:r,index:o,context:i});return await Promise.all(s.map(u=>e.getDocumentSnapshot(u,{to:e.time.now(n.oldSchema.version)})))}},t),{})}function io({meta:n,migration:i,context:e}){function t(){return n.time.zero(i.version)}let r=new Array,o=ta({migration:i,context:e,meta:n}),s=no({migration:i,getMigrationNow:t,newOids:r,meta:n}),a=async m=>{let S=await n.getAllCollectionRelatedOids(m);return n.insertLocalOperations(S.map(b=>({oid:b,timestamp:t(),data:{op:"delete"}})))},u=new Array;return{log:e.log,newOids:r,deleteCollection:a,migrate:async(m,S)=>{let b=await o[m].findAll();await Promise.all(b.filter(Boolean).map(async C=>{let w=ne(C);L(!!w,`Document is missing an OID: ${JSON.stringify(C)}`);let v=ae(C),_=await S(C);if(_){pt(v),pt(_),et(_);let I=gt(v,_,t,void 0,[],{mergeUnknownObjects:!0});I.length>0&&await n.insertLocalOperations(I)}}))},queries:o,mutations:s,awaitables:u}}function ro({meta:n,migration:i,context:e}){function t(){return n.time.zero(i.version)}let r=new Array,o=new Proxy({},{get(){throw new Error("Queries are not available in initial migrations; there is no database yet!")}}),s=no({migration:i,getMigrationNow:t,newOids:r,meta:n});return{log:e.log,newOids:r,deleteCollection:()=>{throw new Error("Calling deleteCollection() in initial migrations is not supported! Use initial migrations to seed initial data using mutations.")},migrate:()=>{throw new Error("Calling migrate() in initial migrations is not supported! Use initial migrations to seed initial data using mutations.")},queries:o,mutations:s,awaitables:[]}}var oo=typeof window<"u"?window.indexedDB:void 0;async function St({context:n,toRun:i,meta:e,indexedDB:t=oo,namespace:r=n.namespace}){await eo(r,async()=>{for(let o of i){let s;if(o.oldSchema.version===0)s=ro({meta:e,migration:o,context:n}),await o.migrate(s);else{let d=await je({indexedDB:t,namespace:r,version:o.oldSchema.version,context:n});s=io({meta:e,migration:o,context:{...n,documentDb:d}});try{await o.migrate(s),await Promise.all(s.awaitables)}catch(m){throw n.log("critical",`Migration failed (${o.oldSchema.version} -> ${o.newSchema.version})`,m),m instanceof Error?m:new Error("Unknown error during migration")}await ge(d)}n.log("debug","Upgrading database",r,"to version",o.newSchema.version);let a=await sa({migration:o,indexedDB:t,namespace:r,context:n}),u=await oa({meta:e,currentVersion:o.oldSchema.version,newVersion:o.newSchema.version});for(let d of o.allCollections){let S=a.transaction(d,"readwrite").objectStore(d),C=(await na(S)).map(O=>Y(d,`${O}`));C.push(...s.newOids.filter(O=>me(O).collection===d),...u.filter(O=>me(O).collection===d));let v=(await Promise.all(C.map(async O=>{try{let R=await e.getDocumentSnapshot(O);return[O,R]}catch(R){return n.log("error","Could not regenerate snapshot during migration for oid",O,"this document will not be preserved",R),null}}))).filter(O=>!!O).map(([O,R])=>{if(!R)return[O,void 0];let y=Gt(o.newSchema.collections[d],R);return[O,y]}),I=a.transaction(d,"readwrite").objectStore(d);await Promise.all(v.map(([O,R])=>{if(R)return ra(I,R);{let{id:y}=me(O);return ia(I,y)}}))}await ge(a),n.log("debug",`Migration of ${r} complete.`),n.log(`
|
|
9
|
+
\u2B06\uFE0F v${o.newSchema.version} Migration complete. Here's the rundown:
|
|
10
|
+
- Added collections: ${o.addedCollections.join(", ")}
|
|
11
|
+
- Removed collections: ${o.removedCollections.join(", ")}
|
|
12
|
+
- Changed collections: ${o.changedCollections.join(", ")}
|
|
13
|
+
- New indexes: ${Object.keys(o.addedIndexes).map(d=>o.addedIndexes[d].map(m=>`${d}.${m.name}`)).flatMap(d=>d).join(", ")}
|
|
14
|
+
- Removed indexes: ${Object.keys(o.removedIndexes).map(d=>o.removedIndexes[d].map(m=>`${d}.${m.name}`)).flatMap(d=>d).join(", ")}
|
|
15
|
+
`)}})}async function na(n){return new Promise((i,e)=>{let t=n.getAllKeys();t.onsuccess=r=>{i(t.result)},t.onerror=r=>{e(t.error)}})}async function ia(n,i){let e=n.delete(i);return new Promise((t,r)=>{e.onsuccess=o=>{t()},e.onerror=o=>{r(e.error)}})}async function ra(n,i){let e=n.put(i);return new Promise((t,r)=>{e.onsuccess=o=>{t()},e.onerror=o=>{r(e.error)}})}async function oa({meta:n,currentVersion:i,newVersion:e}){let t=[];return await n.operations.iterateOverAllOperations(r=>t.push(r),{from:n.time.zero(i+1)}),Array.from(new Set(t.map(r=>z(r.oid))))}function sa({migration:n,indexedDB:i=oo,namespace:e,context:t}){return Zr(i,e,n.newSchema.version,(r,o)=>{for(let s of n.addedCollections)o.createObjectStore(s,{keyPath:n.newSchema.collections[s].primaryKey,autoIncrement:!1});for(let s of n.allCollections){let a=r.objectStore(s);for(let u of n.addedIndexes[s]||[])a.createIndex(u.name,u.name,{multiEntry:u.multiEntry});for(let u of n.removedIndexes[s]||[])a.deleteIndex(u.name)}for(let s of n.removedCollections)r.objectStore(s).clear()},t.log)}var nt=class extends Error{constructor(e){super(e);this.message=e;this.name="MigrationPathError"}};function It({currentVersion:n,targetVersion:i,migrations:e}){let t=so({currentVersion:n,targetVersion:i,migrations:e});if(!t)throw new nt(`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,o)=>o.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 o=so({currentVersion:r.newSchema.version,targetVersion:i,migrations:e});if(o)return[r,...o]}return null}var aa=typeof window<"u"?window.indexedDB:void 0;async function ao({version:n,indexedDB:i=aa,migrations:e,meta:t,context:r,wipNamespace:o}){r.log("debug","Opening WIP database",o);let s=await un(i,o,n,r.log);if(s===n)r.log("info","WIP schema is up-to-date; not refreshing database");else{r.log("info","WIP schema is out-of-date; refreshing database");let a=It({currentVersion:s,targetVersion:n-1,migrations:e});if(a.length>0){await St({context:r,toRun:a,meta:t,indexedDB:i,namespace:o});let d=await je({indexedDB:i,namespace:r.namespace,version:n-1,context:r}),m=await je({indexedDB:i,namespace:o,version:n-1,context:r});await to(d,m)}let u=It({currentVersion:n-1,targetVersion:n,migrations:e});u.length>0&&await St({context:r,toRun:u,meta:t,indexedDB:i,namespace:o})}return je({indexedDB:i,namespace:o,version:n,context:r})}var He=class extends V{constructor(){super(...arguments);this._undoable=[];this._undone=[];this.undo=async()=>{let e=this._undoable.pop();if(e){let t=await e();return t&&this._undone.push(t),this.emit("change"),!0}return!1};this.redo=async()=>{let e=this._undone.pop();if(e){let t=await e();return t&&this._undoable.push(t),this.emit("change"),!0}return!1};this.addUndo=e=>{this._undoable.push(e),this._undone=[],this.emit("change")};this.addRedo=e=>{this._undone.push(e),this.emit("change")};this.clear=()=>{this._undoable=[],this._undone=[],this.emit("change")}}get canUndo(){return this._undoable.length>0}get canRedo(){return this._undone.length>0}};var mn=class{constructor(i,e,t){this.meta=i;this.schema=e;this.entities=t;this.getOid=(i,e)=>{let t=this.schema.collections[i].primaryKey,r=e[t];return L(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 Re(t,e)};this.validate=(i,e)=>{let t=this.schema.collections[i];return zr(t.fields,e)};this.create=(i,e,t={})=>{let r=this.addDefaults(i,e),o=this.validate(i,r),s=this.getOid(i,o);return this.entities.create(o,s,t)};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)}};var co=Ue(Xe(),1);function ca(n){return{id:(0,co.default)(),file:n,url:void 0,remote:!1,name:n.name,type:n.type}}function Ci(n){return n instanceof File||typeof Blob<"u"&&n instanceof Blob}function it(n,i){if(typeof window<"u"&&Ci(n)){let e=ca(n);return i(e),Vt(e.id)}if(Array.isArray(n)){for(let e=0;e<n.length;e++)n[e]=it(n[e],i);return n}if(typeof n=="object"){for(let e in n)n[e]=it(n[e],i);return n}return n}function lo(n){return new Promise((i,e)=>{let t=new FileReader;t.onload=()=>{i(t.result)},t.onerror=e,t.readAsArrayBuffer(n)})}var rt=Symbol("entity-file-update"),_t=Symbol("entity-file-mark-failed"),la,da,ue=class extends V{constructor(e,{downloadRemote:t=!1}={}){super();this.id=e;this._objectUrl=null;this._fileData=null;this._loading=!0;this._failed=!1;this._downloadRemote=!1;this[la]=e=>{this._loading=!1,this._failed=!1,this._fileData=e,e.file&&(this._objectUrl&&URL.revokeObjectURL(this._objectUrl),this._objectUrl=URL.createObjectURL(e.file)),this.emit("change")};this[da]=()=>{this._failed=!0,this._loading=!1,this.emit("change")};this.destroy=()=>{this._objectUrl&&URL.revokeObjectURL(this._objectUrl),this.dispose()};this._downloadRemote=t}static{la=rt,da=_t}get downloadRemote(){return this._downloadRemote}get isFile(){return!0}get url(){return this.loading?null:this._objectUrl?this._objectUrl:this._fileData?.url??null}get name(){return this._fileData?.name??null}get type(){return this._fileData?.type??null}get loading(){return this._loading}get failed(){return this._failed}getSnapshot(){return{id:this.id,url:this.loading||this.failed?void 0:this.url}}};var gn=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 fe(i);return this.cache.set(i.oid,e),e};this.has=i=>this.cache.has(i);this.getFile=(i,e)=>{if(this.cache.has(i))return this.cache.get(i);let t=new ue(i,e);return this.cache.set(i,t),t};this.getCached=i=>this.cache.get(i);if(i)for(let e of i)this.cache.set(e.oid,e)}};var fe=class n extends V{constructor({oid:e,schema:t,entityFamily:r,parent:o,ctx:s,metadataFamily:a,readonlyKeys:u,files:d,patchCreator:m,events:S,deleteSelf:b}){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.validate=Wr(()=>(this.validationError=Te({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(o=>o instanceof n||o instanceof ue?e(o):o);return $(r,this.oid),r}else{let r=Object.entries(t).reduce((o,[s,a])=>(a instanceof n||a instanceof ue?o[s]=e(a):o[s]=a,o),{});return $(r,this.oid),r}};this.getSnapshot=()=>this.viewWithMappedChildren(e=>e.getSnapshot());this.addPendingOperations=e=>{this.ctx.log("debug","Entity: adding pending operations",this.oid);let 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.ctx.log("Emitting change event",this.oid),this.emit("change",{isLocal:e.isLocal}))};this.changeNested=e=>{this.deepChange(this,e),this.ctx.log("Emitting change event",this.oid),this.emit("change",{isLocal:e.isLocal})};this.deepChange=(e,t)=>{this.cachedDeepUpdatedAt=null,this.cachedView=void 0,this.ctx.log("debug","Deep change detected at",this.oid,"reset cached view"),this.ctx.log("debug","Emitting deep change event",this.oid),this.emit("changeDeep",e,t),this.parent?.deepChange(e,t)};this.getChild=(e,t)=>{let r=ze(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],patchCreator:this.patchCreator,events:this.events,deleteSelf:this.delete.bind(this,e)})};this.get=e=>{Pi(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],o=ze(this.schema,e);if(!o)throw new Error(`No schema for key ${String(e)} in ${JSON.stringify(this.schema)}`);if(Q(r))if(we(r)){if(o.type!=="file")throw new Error(`Expected file schema for key ${String(e)}, got ${o.type}`);let s=this.files.get(r.id,{downloadRemote:!!o.downloadRemote});return s.subscribe("change",()=>{this.deepChange(this,{isLocal:!1,oid:this.oid})}),s}else return this.getChild(e,r.id);else return this.schema.type==="map"&&r===void 0?void 0:Te({field:o,value:r,fieldPath:[...this.fieldPath,e],depth:1,requireDefaults:!0})?Ae(o)?bi(o):xe(o)?null:void 0:r};this.getOrSet=(e,t)=>{Pi(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()}`);Ci(e)||(e=ae(e,!1));let r=ze(this.schema,t);if(r){$e(e,r);let o=Te({field:r,value:e,fieldPath:[...this.fieldPath,t]});if(o)throw new Error(o.message)}return it(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 ce(e.oid);if(e instanceof ue)return Vt(e.id);if(typeof e=="object"){let t=pe(e);if(!t||!this.entityFamily.has(t))throw new Error(`Cannot move object ${JSON.stringify(e)} which does not exist in this list`);return ce(t)}else return e};this.set=(e,t,r)=>{Pi(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)ua(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:o=!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 s={};$(s,this.oid);for(let[a,u]of Object.entries(e)){if(this.readonlyKeys.includes(a))throw new Error(`Cannot set readonly key ${a.toString()}`);if(u===void 0&&!o)continue;let d=ze(this.schema,a);d&&$e(u,d),s[a]=this.processInputValue(u,a)}this.addPendingOperations(this.patchCreator.createDiff(this.getSnapshot(),s,{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(Q(r))this.addPendingOperations(this.patchCreator.createListMoveByRef(this.oid,r,t));else{let o=this.view.indexOf(e);if(o===-1)throw new Error(`Cannot move item ${JSON.stringify(e)} which does not exist in this list`);this.move(o,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 Q(t)?this.view.some(r=>{if(Q(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()};L(!!e,"oid is required"),this.oid=e,this.readonlyKeys=u||[],this.ctx=s,this.files=d,this.schema=t,this.entityFamily=r||new gn({initial:[this]}),this.patchCreator=m,this.metadataFamily=a,this.events=S,this.parent=o,this._deleteSelf=b,this.parent||(S.add.attach(this.onAdd),S.replace.attach(this.onReplace),S.resetAll.attach(this.onResetAll))}get metadata(){return this.metadataFamily.get(this.oid)}get viewData(){return this._viewData===void 0&&(this._viewData=this.metadata.computeView(),this.validate()),this._viewData}get rawView(){return this.viewData.view}get view(){if(this.cachedView!==void 0)return this.cachedView;if(this.viewData.deleted)return null;let e=this.rawView;if(!e&&!xe(this.schema)||this.schema.type==="array"&&!Array.isArray(e)||(this.schema.type==="object"||this.schema.type==="map")&&!N(e))return Ae(this.schema)?bi(this.schema):null;if(this.cachedView=this.isList?[]:{},$(this.cachedView,this.oid),Array.isArray(e)){let r=ze(this.schema,0);if(!r)this.ctx.log("error","No child field schema for list entity.",this.oid);else for(let o=0;o<e.length;o++){let s=this.get(o);this.childIsNull(s)&&!xe(r)?this.ctx.log("error","Child missing in non-nullable field",this.oid,"index:",o):this.cachedView.push(s)}}else if(N(e)){let r=this.schema.type==="object"?Object.keys(this.schema.properties):Object.keys(e);for(let o of r){let s=ze(this.schema,o);if(!s){this.ctx.log("error","No child field schema for object entity at key",o),this.schema.type==="map"?this.cachedView={}:this.cachedView=null;break}let a=this.get(o);if(this.childIsNull(a)&&!xe(s)){if(this.ctx.log("error","Child entity is missing for non-nullable field",this.oid,"key:",o),this.schema.type!=="map"){this.cachedView=null;break}}else this.cachedView[o]=a}}return this.cachedView}get uid(){return this.oid}get deleted(){return this.viewData.deleted||this.view===null}get invalid(){return!!this.validate()}get isList(){return this.schema.type==="array"||Array.isArray(this.viewData.view)}get updatedAt(){return this.viewData.updatedAt}get deepUpdatedAt(){if(this.cachedDeepUpdatedAt)return this.cachedDeepUpdatedAt;let e=this.updatedAt;return this.isList?this.forEach(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 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 Pi(n){if(typeof n=="symbol")throw new Error("Symbol keys aren't supported")}function ua(n){if(typeof n!="number")throw new Error("Only number keys are supported in list entities")}var Ai=class{constructor({oid:i,ctx:e,confirmedOperations:t,pendingOperations:r,baseline:o}){this.baseline=null;this.confirmedOperations=[];this.pendingOperations=[];this.computeView=(i=!1)=>{let e=ae(this.baseline?.snapshot??void 0),t=this.baseline?.timestamp??null,r=this.applyOperations(e,!e,this.confirmedOperations,t,t);r.futureSeen&&this.ctx.globalEvents.emit("futureSeen",r.futureSeen);let o=i?r:this.applyOperations(r.view,r.deleted,this.pendingOperations,r.latestTimestamp,null);o.view&&$(o.view,this.oid);let s=!!r.latestTimestamp&&ni(r.latestTimestamp,this.ctx.getNow())<0,a=!this.baseline&&!this.pendingOperations.length&&!this.confirmedOperations.length;a&&this.ctx.log("warn",`Tried to load Entity ${this.oid} with no data`);let u=o.latestTimestamp??r.latestTimestamp??t,d=u?ii(u):0;if(!o.view&&!o.deleted&&!a){this.ctx.log("warn",`Entity ${this.oid} has no view, no deleted flag, and not empty`);debugger}return{view:o.view??void 0,deleted:o.deleted,empty:a,fromOlderVersion:s,updatedAt:d}};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(s=>s.timestamp>=t.timestamp);r!==-1?this.confirmedOperations[r].timestamp!==t.timestamp&&(this.confirmedOperations.splice(r,0,t),e++):(this.confirmedOperations.push(t),e++);let o=this.pendingOperations.length;this.discardPendingOperation(t),e-=o-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,o)=>{let s,a=this.ctx.getNow();for(let u of t)if(!(o&&u.timestamp<=o)){if(ni(u.timestamp,a)>0){s=u.timestamp;continue}u.data.op==="delete"?e=!0:(i=Ne(i,u.data),u.data.op==="initialize"&&(e=!1)),(!r||u.timestamp>r)&&(r=u.timestamp)}return{view:i,latestTimestamp:r??null,deleted:e,futureSeen:s}};L(i,"oid is required"),this.ctx=e,this.oid=i,t&&(this.confirmedOperations=t),r&&(this.pendingOperations=r),o&&(this.baseline=o)}},yn=class{constructor({ctx:i,onPendingOperations:e,rootOid:t}){this.entities=new Map;this.get=i=>(L(i,"oid is required"),this.entities.has(i)||this.entities.set(i,new Ai({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 o of i){if(!Ce(this.rootOid,o.oid))throw new Error(`Invalid baseline for entity ${this.rootOid}: `+JSON.stringify(o));this.get(o.oid).addBaseline(o)}for(let[o,s]of Object.entries(e)){if(!Ce(this.rootOid,o))throw new Error(`Invalid operations for entity ${this.rootOid}: `+JSON.stringify(s));this.get(o).addConfirmedOperations(s)!==0&&(r[o]??={oid:o,isLocal: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 o of t)r[o]={oid:o,isLocal:!1};for(let o of e){if(!Ce(this.rootOid,o.oid))throw new Error(`Invalid baseline for entity ${this.rootOid}: `+JSON.stringify(o));this.get(o.oid).addBaseline(o),r[o.oid]??={oid:o.oid,isLocal:!1}}for(let[o,s]of Object.entries(i)){if(!Ce(this.rootOid,o))throw new Error(`Invalid operations for entity ${this.rootOid}: `+JSON.stringify(s));this.get(o).addConfirmedOperations(s),r[o]??={oid:o,isLocal:!1}}return Object.values(r)};this.discardPendingOperation=i=>{this.entities.get(i.oid)?.discardPendingOperation(i)};this.ctx=i,this.rootOid=t,this.onPendingOperations=e}};var Dt="@@default",bn=class{constructor({batchTimeout:i=200,meta:e,ctx:t,entities:r}){this.currentBatchKey=Dt;this.flushOperations=async(i,e,t)=>{if(this.ctx.log("debug","Flushing",i.length,"operations from batch",e,"to storage / sync"),!i.length)return;let r=[],o={};for(let s=i.length-1;s>=0;s--){let a=i[s],u=o[a.oid];if(u&&Ur(a,u)){this.entities.discardPendingOperation(a);continue}let d=Lr(a);d!==!1&&(o[a.oid]||(o[a.oid]=new Set),o[a.oid].add(d)),r.unshift(a)}for(let s of r)s.timestamp=this.meta.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=zt(),max:t=null,timeout:r=this.defaultBatchTimeout}={})=>{let o=this.batcher.add({key:e,max:t,timeout:r,items:[],userData:{undoable:i}}),s={run:a=>(this.currentBatchKey=e,a(),this.currentBatchKey=Dt,s),commit:async()=>(await this.batcher.flush(Dt),o.flush()),flush:()=>s.commit(),discard:()=>{this.batcher.discard(e)}};return s};this.flushAll=()=>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.meta.now;return await this.commitOperations(e,{undoable:!1}),t}:null};this.getInverseOperations=async({ops:i,source:e})=>{let t=yt(i),r=[],o=()=>this.meta.now;return await Promise.all(Object.entries(t).map(async([s,a])=>{let d=(e??await this.entities.hydrate(z(s)))?.__getViewData__(s,"confirmed");if(!d){this.ctx.log("warn","could not find entity",s,"for undo operation",i);return}let m=Hr(s,d.view,a,o);r.unshift(...m)})),r};this.meta=e,this.ctx=t,this.entities=r,this.defaultBatchTimeout=i,this.batcher=new tt(this.flushOperations),this.batcher.add({key:Dt,items:[],max:100,timeout:i,userData:{undoable:!0}})}get isDefaultBatch(){return this.currentBatchKey===Dt}};var wn=class extends se{constructor({ctx:e}){super(e.documentDb,{log:e.log});this.reset=async()=>{let e=Object.keys(this.ctx.schema.collections),t=this.createTransaction(e,{mode:"readwrite"});await Promise.all(e.map(r=>{let o=t.objectStore(r);return J(o.clear())})),this.ctx.entityEvents.emit("collectionsChanged",e),this.ctx.log("info","\u{1F4A8} Reset queryable storage")};this.saveEntities=async(e,t)=>{if(e.length===0)return;let r=Array.from(new Set(e.map(a=>me(a.oid).collection))),o=r.filter(a=>!this.ctx.schema.collections[a]);if(o.length>0){this.ctx.log("warn",`Ignoring entities from collections that no longer exist: ${o.join(", ")}`);let a=new Set(r);o.forEach(u=>a.delete(u)),r=Array.from(a)}let s={transaction:this.createTransaction(r,{mode:"readwrite",abort:t?.abort})};await Promise.all(e.map(async a=>{let u=a.getSnapshot();try{await this.saveDocument(a.oid,u,s)}catch(d){throw this.ctx.log("error",`Error saving document ${a.oid} (${JSON.stringify(u)})`,d),d instanceof Error?d:new Error("Unknown error saving document")}})),s.transaction.commit(),this.ctx.entityEvents.emit("collectionsChanged",r);for(let a of e)this.ctx.entityEvents.emit("documentChanged",a.oid)};this.saveDocument=async(e,t,{transaction:r})=>{this.ctx.log("debug",`Saving document indexes for querying ${e}`,t);let{collection:o,id:s}=me(e);if(!t)await this.run(o,a=>a.delete(s),{mode:"readwrite",transaction:r}),this.ctx.log("debug",`Deleted document indexes for querying ${e}`);else{let a=this.ctx.schema.collections[o],u=Gt(a,t);await this.run(o,d=>d.put(u),{mode:"readwrite",transaction:r}),this.ctx.log("debug",`Saved document indexes for querying ${e}`,t)}};this.ctx=e,this.addDispose(this.ctx.internalEvents.subscribe("documentDbChanged",t=>{this.db=t}))}};var Cn=Ue(Ko(),1);var Pn=class extends _e{constructor({ctx:e,meta:t,files:r}){super();this.events={add:new Cn.WeakEvent,replace:new Cn.WeakEvent,resetAll:new Cn.WeakEvent};this.cache=new Map;this.pendingEntityPromises=new Map;this.abortDataQueueController=new AbortController;this.ongoingResetPromise=null;this.entityFinalizationRegistry=new FinalizationRegistry(e=>{this.ctx.log("debug","Entity GC",e)});this.addData=async e=>{if(this.disposed){this.ctx.log("warn","EntityStore is disposed, not adding incoming data");return}e.reset&&(this.ctx.log("info","Resetting local store to replicate remote synced data - dropping any current transactions"),this.abortDataQueueController.abort(0),this.abortDataQueueController=new AbortController,this.ongoingResetPromise=this.resetData().finally(()=>{this.ongoingResetPromise=null})),this.ongoingResetPromise&&(this.ctx.log("debug","Waiting for ongoing reset to complete"),await this.ongoingResetPromise,this.ctx.log("debug","Ongoing reset complete")),await this.processData(e)};this.empty=async()=>{await this.queryableStorage.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.meta.reset(),await this.queryableStorage.reset(),this.events.resetAll.invoke(this)};this.processData=async e=>{if(this.disposed){this.ctx.log("warn","EntityStore is disposed, not processing incoming data");return}let t=e?.baselines??[],r=e?.operations??[];this.ctx.log("debug","Processing incoming data",{operations:r.length,baselines:t.length,reset:!!e.reset});let o=Array.from(new Set(t.map(m=>z(m.oid)).concat(r.map(m=>z(m.oid))))),s=jr(t),a=Mr(r);this.ctx.log("debug","Applying data to live entities");for(let m of o){let S=s[m],b=a[m]??[],C=yt(b),w=e.reset?this.events.replace:this.events.add,v=this.pendingEntityPromises.get(m);v?v.then(()=>{w.invoke(this,{oid:m,baselines:S,operations:C,isLocal:!1})}):w.invoke(this,{oid:m,baselines:S,operations:C,isLocal:!1})}let u={abort:this.abortDataQueueController.signal};await this.meta.insertData(e,u);let d=await Promise.all(o.map(async m=>await this.hydrate(m,u)??{oid:m,getSnapshot(){return null}}));try{await this.queryableStorage.saveEntities(d,u)}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(!Br(e))throw new Error("Cannot hydrate non-root entity");if(this.cache.has(e)){this.ctx.log("debug","Hydrating entity from cache",e);let o=this.cache.get(e);if(o){let s=o.deref();if(s)return s.deleted?null:s;this.ctx.log("debug","Removing GC'd entity from cache",e),this.cache.delete(e)}}let r=this.pendingEntityPromises.get(e);if(r)return this.ctx.log("debug","Waiting for entity hydration",e),r;{this.ctx.log("debug","Hydrating entity from storage",e);let o=this.constructEntity(e);if(!o)return null;let s=this.loadEntity(o,t);return s.finally(()=>{this.pendingEntityPromises.delete(e)}),this.pendingEntityPromises.set(e,s),s}};this.destroy=async()=>{this.dispose(),await this.batcher.flushAll()};this.create=async(e,t,{undoable:r=!0}={})=>{this.ctx.log("debug","Creating new entity",t);let{collection:o}=me(t);Kt(e);let s=it(e,this.files.add);$(s,t);let a=this.constructEntity(t);if(!a)throw new Error(`Could not put new document: no schema exists for collection ${o}`);let u=this.meta.patchCreator.createInitialize(s,t);await this.batcher.commitOperations(u,{undoable:!!r,source:a});let d=yt(u);return this.events.add.invoke(this,{operations:d,isLocal:!0,oid:t}),this.cache.set(t,this.ctx.weakRef(a)),a};this.deleteAll=async(e,t)=>{this.ctx.log("info","Deleting documents",e),L(e.every(s=>s===z(s)),"Only root documents may be deleted via client methods");let r=await Promise.all(e.flatMap(async s=>(await this.hydrate(s))?.__getFamilyOids__()??[]));e.forEach(s=>{this.cache.delete(s),this.ctx.log("debug","Deleted document from cache",s)});let o=this.meta.patchCreator.createDeleteAll(r.flat());await this.batcher.commitOperations(o,{undoable: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}=me(e),{schema:r,readonlyKeys:o}=this.getCollectionSchema(t);if(!r)return null;if(this.disposed)throw new Error("Cannot hydrate entity after store has been disposed");let s=new yn({ctx:this.ctx,onPendingOperations:this.onPendingOperations,rootOid:e});return new fe({ctx:this.ctx,oid:e,schema:r,readonlyKeys:o,files:this.files,metadataFamily:s,patchCreator:this.meta.patchCreator,events:this.events,deleteSelf:this.delete.bind(this,e)})};this.onPendingOperations=e=>{this.batcher.addOperations(e)};this.discardPendingOperation=e=>{let t=z(e.oid);this.cache.get(t)?.deref()?.__discardPendingOperation__(e)};this.loadEntity=async(e,t)=>{let{operations:r,baselines:o}=await this.meta.getDocumentData(e.oid,t);return!o.length&&!Object.keys(r).length?(this.ctx.log("debug","No data found for entity",e.oid),null):(this.ctx.log("debug","Loaded entity from storage",e.oid),this.events.replace.invoke(this,{oid:e.oid,baselines:o,operations:r,isLocal:!1}),this.cache.set(e.oid,this.ctx.weakRef(e)),this.entityFinalizationRegistry.register(e,e.oid),e)};this.ctx=e,this.meta=t,this.files=r,this.queryableStorage=new wn({ctx:e}),this.batcher=new bn({ctx:e,meta:t,entities:this})}get batch(){return this.batcher.batch}get flushAllBatches(){return this.batcher.flushAll}};var An=class extends se{constructor(){super(...arguments);this.addFile=async(e,{transaction:t,downloadRemote:r=!1}={})=>{let o=e.file?await lo(e.file):void 0;if(!o&&r&&e.url)try{o=await fetch(e.url,{method:"GET",credentials:"include"}).then(s=>s.arrayBuffer())}catch(s){console.error("Failed to download file to cache it locally. The file will still be available using its URL. Check the file server's CORS configuration.",s)}return this.run("files",s=>s.put({id:e.id,remote:e.remote?"true":"false",deletedAt:null,name:e.name,type:e.type,url:e.url,buffer:o}),{mode:"readwrite",transaction:t})};this.hydrateFileData=e=>{e.remote=e.remote==="true";let t=e.buffer;return delete e.buffer,e.file=t?Ea(t,e.type):void 0,e};this.markUploaded=async(e,{transaction:t}={})=>{let r=await this.getFileRaw(e,{transaction:t});if(!r)throw new Error("File is not in local database");return this.run("files",o=>o.put({...r,remote:"true"}),{mode:"readwrite",transaction:t})};this.getFileRaw=async(e,{transaction:t}={})=>{let r=await this.run("files",o=>o.get(e),{mode:"readonly",transaction:t});if(r)return r};this.getFile=async(e,{transaction:t}={})=>{let r=await this.getFileRaw(e,{transaction:t});if(r)return this.hydrateFileData(r)};this.markPendingDelete=async(e,{transaction:t}={})=>{let r=await this.getFileRaw(e,{transaction:t});if(!r)throw new Error("File is not in local database");return this.run("files",o=>o.put({...r,deletedAt:Date.now()}),{mode:"readwrite",transaction:t})};this.listUnsynced=async()=>(await this.run("files",t=>t.index("remote").getAll("false"),{mode:"readonly"})).map(this.hydrateFileData);this.iterateOverPendingDelete=(e,t)=>this.iterate("files",r=>r.index("deletedAt").openCursor(IDBKeyRange.lowerBound(0,!0)),(r,o)=>{e(this.hydrateFileData(r),o)},{mode:"readwrite",transaction:t});this.getAll=async()=>{let[e]=await en(this.db,["files"]);return e.map(this.hydrateFileData)}}deleteFile(e,{transaction:t}={}){return this.run("files",r=>r.delete(e),{mode:"readwrite",transaction:t})}};function Ea(n,i){return new Blob([n],{type:i})}function Ca(n){return n.deletedAt!==null&&n.deletedAt<Date.now()-1e3*60*24*3}var Rn=class{constructor({db:i,sync:e,context:t,meta:r,config:o={}}){this.files=new Map;this.add=async i=>{let e=i;if(e.remote=!1,this.files.has(e.id))this.files.get(e.id)[rt](e);else{let t=new ue(e.id);t[rt](e),this.files.set(e.id,t)}await this.storage.addFile(e),e.file&&await this.uploadFile(e,1)};this.uploadFile=async(i,e=0)=>{let t=await this.sync.uploadFile(i);t.success?await this.storage.markUploaded(i.id):t.retry&&e<5?(this.context.log("error","Error uploading file, retrying..."),setTimeout(this.uploadFile,1e3,i,e+1)):this.context.log("error","Failed to upload file. Not retrying until next sync.")};this.get=(i,e)=>{if(this.files.has(i))return this.files.get(i);let t=new ue(i,e);return this.files.set(i,t),this.load(t),t};this.load=async(i,e=0)=>{if(e>5){this.context.log("error","Failed to load file after 5 retries"),i[_t]();return}let t=await this.storage.getFile(i.id);if(t)i[rt](t);else try{let r=await this.sync.getFile(i.id);r.success?(i[rt](r.data),await this.storage.addFile(r.data,{downloadRemote:i.downloadRemote})):(this.context.log("error","Failed to load file",r),i[_t](),r.retry&&setTimeout(this.load,1e3,i,e+1))}catch(r){this.context.log("error","Failed to load file",r),i[_t](),setTimeout(this.load,1e3,i,e+1)}};this.listUnsynced=async()=>this.storage.listUnsynced();this.exportAll=async(i=!1)=>{let e=await this.storage.getAll();if(i){for(let t of e)if(!t.file&&t.url)try{let r=await fetch(t.url,{method:"GET",credentials:"include"}).then(o=>o.blob());t.file=r}catch(r){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.",r)}}return e};this.importAll=async i=>{await Promise.all(i.map(e=>this.add(e)))};this.onOnlineChange=async i=>{if(i){let e=await this.listUnsynced();await Promise.all(e.map(this.uploadFile))}};this.tryCleanupDeletedFiles=async()=>{let i=0,e=0;await this.storage.iterateOverPendingDelete((t,r)=>{this.config.canCleanupDeletedFile(t)?(i++,r.delete(t.id)):e++}),this.context.log("info",`Cleaned up ${i} files, skipped ${e} files`)};this.handleFileRefsDeleted=async i=>{let e=this.storage.createTransaction(["files"],{mode:"readwrite"});await Promise.all(i.map(async t=>{try{await this.storage.markPendingDelete(t.id,{transaction:e})}catch(r){this.context.log("error","Failed to mark file for deletion",r)}})),this.context.log("info",`Marked ${i.length} files as pending delete`)};this.close=()=>{this.storage.dispose()};this.storage=new An(i),this.sync=e,this.context=t,this.meta=r,this.config={canCleanupDeletedFile:Ca,...o},this.sync.subscribe("onlineChange",this.onOnlineChange),this.meta.subscribe("filesDeleted",this.handleFileRefsDeleted),this.tryCleanupDeletedFiles()}};var Pa=typeof window<"u"?window.indexedDB:void 0;async function Ct({version:n,indexedDB:i=Pa,migrations:e,meta:t,context:r}){if(r.schema.wip)throw new Error("Cannot open a production client with a WIP schema!");let o=await un(i,r.namespace,n,r.log);r.log("debug","Current database version:",o,"target version:",n);let s=It({currentVersion:o,targetVersion:n,migrations:e});return s.length>0&&(r.log("debug","Migrations to run:",s.map(a=>a.version)),await St({context:r,toRun:s,meta:t,indexedDB:i})),je({indexedDB:i,namespace:r.namespace,version:n,context:r})}function Aa(n){return n!==null}function qi(n){return Array.isArray(n)?n.map(qi).filter(Aa):n instanceof fe&&n.deleted?null:n}function Le(n,i){return!n&&!i||n&&i&&Be(n)===Be(i)}var Hi=Symbol("ON_ALL_UNSUBSCRIBED"),he=Symbol("UPDATE"),Ra,ye=class extends _e{constructor({initial:e,context:t,collection:r,key:o,shouldUpdate:s}){super();this._internalUnsubscribes=[];this._status="initial";this._executionPromise=null;this.setValue=e=>{this._rawValue=e,this.subscribeToDeleteAndRestore(this._rawValue);let t=qi(e),r=!0;this.status==="initializing"||this.status==="initial"?r=!0:this.isListQuery?this._value.length===t.length&&this._value.every((o,s)=>o===t[s])&&(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 fe&&(this._internalUnsubscribes.push(t.subscribe("delete",this.refreshValue)),this._internalUnsubscribes.push(t.subscribe("restore",this.refreshValue)))}):e instanceof fe&&(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[Ra]=e=>{this._allUnsubscribedHandler=e};this._rawValue=e,this._value=e,this.isListQuery=Array.isArray(e),this._events=new V(u=>{u==="change"&&this._allUnsubscribedHandler?.(this)}),this.context=t,this.key=o,this.collection=r;let a=s||(u=>u.includes(r));this.addDispose(this.context.entityEvents.subscribe("collectionsChanged",u=>{a(u)&&(this.context.log("info","Updating query",this.key),this.execute())}))}static{Ra=Hi}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")}};var Fn=class extends ye{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 Fa,Tn=class extends ye{constructor({index:e,hydrate:t,...r}){super({initial:null,...r});this.run=async()=>{let e=await hn({collection:this.collection,index:this.index,context:this.context});this.setValue(e?await this.hydrate(e):null)};this[Fa]=e=>{Le(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=t}static{Fa=he}};var Ta,Bn=class extends ye{constructor({index:e,hydrate:t,pageSize:r,page:o,...s}){super({initial:[],...s});this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:t}=await Ot({collection:this.collection,index:this.index,context:this.context,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[Ta]=e=>{Le(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=t,this._pageSize=r,this._page=o}static{Ta=he}get pageSize(){return this._pageSize}get page(){return this._page}get hasNextPage(){return this._hasNextPage}get hasPreviousPage(){return this._page>0}};var Ba,kn=class extends ye{constructor({hydrate:e,pageSize:t,index:r,...o}){super({initial:[],...o});this._upToPage=1;this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:t}=await Ot({collection:this.collection,context:this.context,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 Ot({collection:this.collection,context:this.context,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[Ba]=e=>{Le(this.index,e)||(this.index=e,this.execute())};this.index=r,this.hydrate=e,this._pageSize=t}static{Ba=he}get pageSize(){return this._pageSize}get hasMore(){return this._hasNextPage}};var ka,Mn=class extends ye{constructor({index:e,hydrate:t,...r}){super({initial:[],...r});this.run=async()=>{let e=await pn({collection:this.collection,index:this.index,context:this.context});this.context.log("debug",`FindAllQuery: ${e.length} oids found: ${e}`),this.setValue(await Promise.all(e.map(this.hydrate)))};this[ka]=e=>{Le(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=t}static{ka=he}};var jn=class{constructor({collection:i,cache:e,entities:t,context:r,documentManager:o}){this.serializeIndex=i=>i?Be(i):"";this.get=i=>{let e=`get:${this.collection}:${i}`;return this.cache.getOrSet(e,()=>new Fn({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 Tn({index:i,collection:this.collection,hydrate:this.hydrate,context:this.context,key:t}),r=>{r[he](i)})};this.findAll=({index:i,key:e}={})=>{let t=e||`findAll:${this.collection}:${this.serializeIndex(i)}`;return this.cache.getOrSet(t,()=>new Mn({index:i,collection:this.collection,hydrate:this.hydrate,context:this.context,key:t}),r=>{r[he](i)})};this.findPage=({index:i,pageSize:e,page:t,key:r})=>{let o=r||`findPage:${this.collection}:${this.serializeIndex(i)}:${e}`;return this.cache.getOrSet(o,()=>new Bn({index:i,collection:this.collection,hydrate:this.hydrate,context:this.context,key:o,pageSize:e,page:t}),s=>{s[he](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 kn({index:i,collection:this.collection,hydrate:this.hydrate,context:this.context,key:r,pageSize:e}),o=>{o[he](i)})};this.cache=e,this.collection=i,this.hydrate=t.hydrate,this.context=r,this.documentManager=o,this.put=this.documentManager.create.bind(this.documentManager,this.collection),this.delete=this.documentManager.delete.bind(this.documentManager,this.collection),this.deleteAll=this.documentManager.deleteAllFromCollection.bind(this.documentManager,this.collection)}};var Ln=class extends _e{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._cache.forEach(e=>e.dispose()),this._cache.clear()};this._evictionTime=e,this.context=t}get(e){return this._cache.get(e)||null}set(e){return this._cache.set(e.key,e),e[Hi](this.onQueryUnsubscribed),e}getOrSet(e,t,r){let o=this.get(e);return o?(r?.(o),o):this.set(t())}};var Wi=Symbol("handleMessage"),Ma,Pt=class extends V{constructor({initialPresence:e,updateBatchTimeout:t=200,defaultProfile:r,replicaStore:o}){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[Ma]=async(e,t)=>{let r=!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),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[s,a]of Object.entries(t.peerPresence))this.isSelf(e,a)?(this._self=a,this._selfReplicaIds.add(a.replicaId),this.emit("selfChanged",a)):(r=!0,o.add(s),this._peers[s]=a,this.emit("peerChanged",s,a))}else if(t.type==="presence-offline"){o.delete(t.userId),this._selfReplicaIds.delete(t.replicaId);let s=this._peers[t.userId];delete this._peers[t.userId],r=!0,this.emit("peerLeft",t.userId,s)}r&&(this._peerIds=Array.from(o),this.emit("peersChanged",this._peers))};this.update=async e=>{this._updateBatch.update({items:[e]}),this.self.presence={...this.self.presence,...e},this.emit("selfChanged",this.self)};this.flushPresenceUpdates=e=>{let t=e.reduce((r,o)=>({...r,...o}),this.self.presence);this.emit("update",t)};this.self.presence=e,this.self.profile=r,this.self.id="",this.self.replicaId="",o.get().then(s=>{this.self.replicaId=s.id}),this._updateBatcher=new tt(this.flushPresenceUpdates),this._updateBatch=this._updateBatcher.add({max:25,timeout:t,items:[],key:"default"})}static{Ma=Wi}get self(){return this._self}get peers(){return this._peers}get peerIds(){return this._peerIds}get everyone(){let e={...this._peers};return e[this.self.id]=this.self,e}get selfReplicaIds(){return this._selfReplicaIds}};var Un=class{constructor({endpointProvider:i,log:e}){this.uploadFile=async i=>{let e=i.file;if(!e)throw new Error("Cannot upload a non-local file");let{files:t,token:r}=await this.endpointProvider.getEndpoints(),o=new window.FormData;o.append("file",e);try{let s=await fetch(t+`/${i.id}`,{method:"POST",body:o,credentials:"include",headers:{Authorization:`Bearer ${r}`}});return s.ok?(this.log("info","File upload successful"),{success:!0,retry:!1}):(this.log("error","File upload failed",s.status,await s.text()),{success:!1,retry:s.status>=500})}catch(s){return this.log("error","File upload failed",s),{success:!1,retry:!0}}};this.getFile=async i=>{let{files:e,token:t}=await this.endpointProvider.getEndpoints();try{let r=await fetch(e+`/${i}`,{method:"GET",credentials:"include",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`}});return r.ok?{success:!0,data:await r.json()}:(this.log("error","File information fetch failed",r.status,await r.text()),{success:!1,retry:r.status>=500||r.status===404})}catch(r){return this.log("error","File information fetch failed",r),{success:!1,error:r,retry:!0}}};this.endpointProvider=i,this.log=e}};var st=class extends V{constructor({interval:e=15*1e3,deadlineLength:t=3*1e3,restartOnTabFocus:r=!0}={}){super();this.nextBeat=null;this.deadline=null;this.keepAlive=()=>{this.deadline&&(clearTimeout(this.deadline),this.deadline=null,this.start())};this.start=(e=!1)=>{this.stop(),e?this.beat():this.nextBeat=setTimeout(this.beat,this._interval)};this.stop=()=>{this.nextBeat&&clearTimeout(this.nextBeat),this.deadline&&clearTimeout(this.deadline)};this.beat=async()=>{this.emit("beat"),this.deadline=setTimeout(this.onDeadline,this.deadlineLength)};this.onDeadline=()=>{this.deadline=null,this.emit("missed")};this.setInterval=e=>{this._interval=e};this._interval=e,this.deadlineLength=t,typeof window<"u"&&r&&(window.addEventListener("pageshow",()=>this.start(!0)),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&this.start(!0)}))}get interval(){return this._interval}};var Vn=class extends V{constructor({endpointProvider:e,meta:t,presence:r,interval:o=15*1e3,log:s=()=>{},fetch:a=window.fetch.bind(window)}){super();this.mode="pull";this._isConnected=!1;this._status="paused";this._hasSynced=!1;this.setInterval=e=>{this.heartbeat.setInterval(e)};this.sendRequest=async e=>{this.log("Sending sync request",e);try{let{http:t,token:r}=await this.endpointProvider.getEndpoints(),o=await this.fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({messages:e}),credentials:"include"});if(o.ok){this.heartbeat.keepAlive();let s=await o.json(),a=Promise.all(s.messages.map(this.handleServerMessage));this._isConnected||(this._isConnected=!0,this.emit("onlineChange",!0)),await a}else{this.log("Sync request failed",o.status,await o.text()),this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1));let s=await o.json();Qr(s)&&s.code===wt.TokenExpired&&(this.endpointProvider.clearCache(),this.heartbeat.keepAlive()),o.status>=500&&this.heartbeat.keepAlive()}}catch(t){this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1)),this.log(t),this.heartbeat.keepAlive()}};this.handleServerMessage=async e=>{e.type==="sync-resp"&&(this._hasSynced=!0,e.ackThisNonce&&(this.log("Sending sync ack",e.ackThisNonce),await this.sendRequest([await this.meta.messageCreator.createAck(e.ackThisNonce)]))),this.emit("message",e)};this.throttledPresenceUpdate=Ar(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.destroy=()=>{this.dispose(),this.stop()};this.onHeartbeat=async()=>{this.sendRequest([await this.meta.messageCreator.createPresenceUpdate(this.presence.self.presence),await this.meta.messageCreator.createSyncStep1()])};this.onHeartbeatMissed=async()=>{this.emit("onlineChange",!1),this.log("Missed heartbeat"),this._isConnected=!1};this.syncOnce=async()=>{await this.sendRequest([await this.meta.messageCreator.createSyncStep1()])};this.log=s,this.meta=t,this.presence=r,this.endpointProvider=e,this.fetch=a,this.heartbeat=new st({interval:o}),this.heartbeat.subscribe("beat",this.onHeartbeat),this.heartbeat.subscribe("missed",this.onHeartbeatMissed)}get interval(){return this.heartbeat.interval}start(){this.status!=="active"&&(this.heartbeat.start(!0),this._status="active")}stop(){this.heartbeat.stop(),this._status="paused"}reconnect(){this.heartbeat.start(!0)}ignoreIncoming(){this.stop()}get isConnected(){return this._isConnected}get status(){return this._status}};function Qi(n){this.message=n}Qi.prototype=new Error,Qi.prototype.name="InvalidCharacterError";var qo=typeof window<"u"&&window.atob&&window.atob.bind(window)||function(n){var i=String(n).replace(/=+$/,"");if(i.length%4==1)throw new Qi("'atob' failed: The string to be decoded is not correctly encoded.");for(var e,t,r=0,o=0,s="";t=i.charAt(o++);~t&&(e=r%4?64*e+t:t,r++%4)?s+=String.fromCharCode(255&e>>(-2*r&6)):0)t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(t);return s};function ja(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(qo(e).replace(/(.)/g,function(t,r){var o=r.charCodeAt(0).toString(16).toUpperCase();return o.length<2&&(o="0"+o),"%"+o}))}(i)}catch{return qo(i)}}function Nn(n){this.message=n}function La(n,i){if(typeof n!="string")throw new Nn("Invalid token specified");var e=(i=i||{}).header===!0?0:1;try{return JSON.parse(ja(n.split(".")[e]))}catch(t){throw new Nn("Invalid token specified: "+t.message)}}Nn.prototype=new Error,Nn.prototype.name="InvalidTokenError";var Ho=La;var $n=class{constructor(i){this.config=i;this.cached=null;this.type=Me.Realtime;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(u=>{if(u.ok)return u.json();throw new Error(`Auth endpoint returned non-200 response: ${u.status}`)}),L(i.accessToken,"No access token provided from auth endpoint");let e=Ho(i.accessToken);L(e.url,"No sync endpoint provided from auth endpoint"),L(e.type!==void 0,"No replica type provided from auth endpoint"),this.type=parseInt(e.type+"");let t=new URL(e.url);t.protocol=t.protocol.replace("ws","http");let r=t.toString();t.protocol=t.protocol.replace("http","ws");let o=t.toString(),s=e.file;if(!s){let a=new URL(r);a.pathname=a.pathname+"/files",s=a.toString()}return this.cached={http:r,websocket:o,files:s,token: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")}};var zn=class extends V{constructor(e){super();this.timer=null;this.isScheduled=!1;this.next=()=>{this.isScheduled||(this.isScheduled=!0,this.timer=setTimeout(()=>{this.emit("trigger"),this.isScheduled=!1,this.backoff.next()},this.backoff.current))};this.reset=()=>{this.backoff.reset(),this.timer&&(clearTimeout(this.timer),this.timer=null)};this.backoff=e}},Kn=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 qn=class extends V{constructor({endpointProvider:e,meta:t,presence:r,log:o}){super();this.socket=null;this.connectQueue=[];this.syncQueue=[];this.incomingQueue=[];this._status="paused";this.synced=!1;this.hasStartedSync=!1;this._ignoreIncoming=!1;this.mode="realtime";this.log=(...e)=>{};this.heartbeat=new st;this.reconnectScheduler=new zn(new Kn(60*1e3,1.5));this.onOpen=()=>{if(!this.socket)throw new Error("Invalid sync state: online but socket is null");if(this.synced=!1,this.connectQueue.length){for(let e of this.connectQueue)this.log("Sending queued message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e));this.connectQueue=[]}this.log("Sync connected"),this.onOnlineChange(!0),this.reconnectScheduler.reset()};this.onOnlineChange=async e=>{this.log("Socket online change",e),!this.disposed&&(e?(this.log("Starting sync"),this.hasStartedSync=!0,this.synced=!1,this.send(await this.meta.messageCreator.createPresenceUpdate(this.presence.self.presence)),this.send(await this.meta.messageCreator.createSyncStep1()),this.heartbeat.start()):(this.hasStartedSync=!1,this.synced=!1,this.heartbeat.stop()),this.emit("onlineChange",e))};this.onMessage=async e=>{if(this._ignoreIncoming){this.log("Ignoring incoming message (ignore incoming flag set)",e.data);return}let t=JSON.parse(e.data);switch(t.type){case"sync-resp":if(t.ackThisNonce&&this.send(await this.meta.messageCreator.createAck(t.ackThisNonce)),this.hasStartedSync=!0,this.synced=!0,this.syncQueue.length)if(t.overwriteLocalData)this.log("warn","Overwriting local data - dropping outgoing message queue"),this.syncQueue=[];else{for(let r of this.syncQueue)this.send(r);this.syncQueue=[]}if(this.emit("message",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.log("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.log(e),this.reconnectScheduler.next(),this.log("Attempting reconnect to websocket sync")};this.onClose=e=>{this.log("Sync disconnected"),this.onOnlineChange(!1),this.onError(e)};this.initializeSocket=async()=>{let e=await this.endpointProvider.getEndpoints();return this.socket=new WebSocket(e.websocket,["Bearer",e.token]),this.socket.addEventListener("message",this.onMessage),this.socket.addEventListener("open",this.onOpen),this.socket.addEventListener("error",this.onError),this.socket.addEventListener("close",this.onClose),this.socket};this.sendHeartbeat=async()=>{this.send(await this.meta.messageCreator.createHeartbeat())};this.reconnect=()=>{this.stop(),this.start()};this.canSkipSyncWait=e=>e.type==="sync"||e.type==="presence-update"||e.type==="sync-ack"||e.type==="heartbeat";this.send=e=>{this.status==="active"&&(!this.hasStartedSync&&!this.canSkipSyncWait(e)||(this.canSkipSyncWait(e)?this.socket?.readyState===WebSocket.OPEN?(this.log("Sending message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e))):(this.log("Enqueueing message until socket is open",JSON.stringify(e,null,2)),this.connectQueue.push(e)):this.synced?this.socket?.readyState===WebSocket.OPEN&&(this.log("Sending message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e))):this.hasStartedSync&&(this.log("Enqueueing message until synced",JSON.stringify(e,null,2)),this.syncQueue.push(e))))};this.destroy=()=>{this.dispose(),this.stop()};this.start=()=>{this.socket||(this.initializeSocket(),this._status="active")};this.stop=()=>{this.socket?.removeEventListener("message",this.onMessage),this.socket?.removeEventListener("close",this.onClose),this.socket?.close(),this.socket=null,this._status="paused"};this.log=o||this.log,this.endpointProvider=e,this.meta=t,this.presence=r,this.reconnectScheduler.subscribe("trigger",this.initializeSocket),this.heartbeat.subscribe("beat",this.sendHeartbeat)}ignoreIncoming(){this.incomingQueue=[],this._ignoreIncoming=!0}get isConnected(){return this.socket?.readyState===WebSocket.OPEN}get status(){return this._status}};var Hn=class extends V{constructor({meta:e}){super();this.mode="pull";this.destroy=()=>{};this.isConnected=!1;this.status="paused";this.pullInterval=0;this.uploadFile=async()=>({success:!1,retry:!1});this.getFile=async()=>({success:!1,retry:!1});this.syncOnce=async()=>{};this.presence=new Pt({initialPresence:null,defaultProfile:null,replicaStore:e.localReplica})}send(){}start(){}stop(){}ignoreIncoming(){}reconnect(){}setMode(){}setPullInterval(){}},at=class extends V{constructor({authEndpoint:e,fetchAuth:t,fetch:r,initialPresence:o,automaticTransportSelection:s=!0,autoStart:a,initialTransport:u,pullInterval:d,presenceUpdateBatchTimeout:m,defaultProfile:S,useBroadcastChannel:b,onOutgoingMessage:C},{meta:w,ctx:v,onData:_}){super();this.broadcastChannel=null;this._activelySyncing=!1;this.handleBroadcastChannelMessage=e=>{e.data.type==="sync"&&this.handleMessage(e.data.message,{source:"broadcastChannel"})};this.onTokenExpired=()=>{this.endpointProvider.clearCache()};this.handleMessage=async(e,{source:t}={source:"network"})=>{if(e.type==="op-re"||e.type==="sync-resp")for(let r of e.operations)this.meta.time.update(r.timestamp);switch(this.log("sync message",JSON.stringify(e,null,2)),e.type){case"op-re":await this.onData({operations:e.operations,baselines:e.baselines}),e.globalAckTimestamp&&await this.meta.setGlobalAck(e.globalAckTimestamp);break;case"global-ack":await this.meta.setGlobalAck(e.timestamp);break;case"sync-resp":this._activelySyncing=!0,this.emit("syncingChange",!0),await this.onData({operations:e.operations,baselines:e.baselines,reset:e.overwriteLocalData}),e.globalAckTimestamp&&await this.meta.setGlobalAck(e.globalAckTimestamp),await this.meta.updateLastSynced(e.ackedTimestamp),this._activelySyncing=!1,this.emit("syncingChange",!1);break;case"need-since":this.activeSync.send(await this.meta.messageCreator.createSyncStep1(e.since));break;case"server-ack":await this.meta.updateLastSynced(e.timestamp)}t==="network"&&this.broadcastChannel?.postMessage({type:"sync",message:e}),this.presence[Wi](await this.meta.localReplica.get(),e)};this.handleOnlineChange=e=>{this.emit("onlineChange",e)};this.handlePresenceUpdate=async e=>{this.send(await this.meta.messageCreator.createPresenceUpdate(e))};this.setMode=e=>{if(e==="realtime"&&!this.canDoRealtime)throw new Error("Cannot switch to realtime mode, because the current auth token does not allow it");let t;e==="realtime"?t=this.webSocketSync:t=this.pushPullSync,t!==this.activeSync&&(this.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=>{this.activeSync.status==="active"&&(await this.activeSync.send(e),this.onOutgoingMessage?.(e))};this.uploadFile=async e=>(this.log("info","Uploading file",{name:e.name,type:e.type,id:e.id}),this.activeSync.status==="active"?this.fileSync.uploadFile(e):{success:!1,retry:!1});this.getFile=async e=>{if(this.activeSync.status==="active")return this.fileSync.getFile(e);throw new Error("Offline, cannot retrieve remote file details")};this.start=()=>this.activeSync.start();this.stop=()=>this.activeSync.stop();this.destroy=()=>{this.dispose(),this.webSocketSync.destroy(),this.pushPullSync.destroy()};this.reconnect=()=>this.activeSync.reconnect();this.syncOnce=()=>this.pushPullSync.syncOnce();if(this.meta=w,this.onData=_,this.log=v.log,this.onOutgoingMessage=C,this.presence=new Pt({initialPresence:o,defaultProfile:S,updateBatchTimeout:m,replicaStore:w.localReplica}),this.endpointProvider=new $n({authEndpoint:e,fetchAuth:t,fetch:r}),this.webSocketSync=new qn({endpointProvider:this.endpointProvider,meta:w,presence:this.presence,log:this.log}),this.pushPullSync=new Vn({endpointProvider:this.endpointProvider,meta:w,presence:this.presence,log:this.log,interval:d,fetch:r}),this.fileSync=new Un({endpointProvider:this.endpointProvider,log:this.log}),b&&"BroadcastChannel"in window&&(this.broadcastChannel=new BroadcastChannel(`verdant-${v.namespace}`),this.broadcastChannel.addEventListener("message",this.handleBroadcastChannelMessage)),u==="realtime"?this.activeSync=this.webSocketSync:this.activeSync=this.pushPullSync,this.presence.subscribe("update",this.handlePresenceUpdate),this.meta.subscribe("message",this.send),this.webSocketSync.subscribe("message",this.handleMessage),this.webSocketSync.subscribe("onlineChange",this.handleOnlineChange),this.pushPullSync.subscribe("message",this.handleMessage),this.pushPullSync.subscribe("onlineChange",this.handleOnlineChange),s&&this.canDoRealtime){let I=()=>{O&&clearTimeout(O);let y=Object.keys(this.presence.peers).length>0||s!=="peers-only"&&this.presence.selfReplicaIds.size>1;y&&this.mode==="pull"?this.setMode("realtime"):!y&&this.mode==="realtime"&&(O=setTimeout(()=>{Object.keys(this.presence.peers).length===0&&this.setMode("pull")},1e3))},O;this.presence.subscribe("peersChanged",I),s!=="peers-only"&&this.presence.subscribe("selfChanged",I)}a&&this.start()}get canDoRealtime(){return this.endpointProvider.type===Me.Realtime||this.endpointProvider.type===Me.PassiveRealtime||this.endpointProvider.type===Me.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}};var Je=class extends V{constructor(e,t,r){super();this.config=e;this.context=t;this._closed=!1;this.addData=e=>this._entities.addData(e);this.stats=async()=>{let e=Object.keys(this.schema.collections),t={};if(this.disposed)return{};for(let d of e)try{t[d]=await vt(this.documentDb,d)}catch(m){this.context.log?.("error",m)}if(this.disposed)return{collections:t};let r=await this.meta.stats(),o=typeof navigator<"u"&&typeof navigator.storage<"u"&&"estimate"in navigator.storage?await navigator.storage.estimate():void 0,s=Object.values(t).reduce((d,{size:m})=>d+m,0),a=r.baselinesSize.size+r.operationsSize.size,u=a/s;return{collections:t,meta:r,storage:o,totalMetaSize:a,totalCollectionsSize:s,metaToDataRatio:u,quotaUsage:o?.usage&&o?.quota?o.usage/o.quota:void 0}};this.close=async()=>{this._closed=!0,this.sync.ignoreIncoming(),await this._entities.flushAllBatches(),this._fileManager.close(),this.sync.stop(),this.sync.destroy(),await this._entities.destroy(),this.meta.close(),await new Promise(async e=>{await ge(this.documentDb),await ge(this.metaDb),e()}),this.context.log?.("Client closed")};this.__dangerous__resetLocal=async()=>{this.sync.stop(),await tn(this.namespace,indexedDB)};this.export=async({downloadRemoteFiles:e}={downloadRemoteFiles:!0})=>{this.context.log("info","Exporting data...");let t=await this.meta.export(),r=await this._fileManager.exportAll(e),o=[],s=[];for(let a of r){let u=a.file;if(delete a.file,o.push(a),u){let d=new File([u],this.getFileExportName(a.name,a.id),{type:a.type});s.push(d)}else this.context.log("warn",`File ${a.id} was could not be loaded locally or from the server. It will be missing in the export.`)}return{data:t,fileData:o,files:s}};this.getFileExportName=(e,t)=>`${t}___${e}`;this.parseFileExportname=e=>{let[t,r]=e.split("___");return{id:t,originalFileName:r}};this.import=async({data:e,fileData:t,files:r})=>{this.context.log("info","Importing data..."),await ge(this.context.documentDb),await this.meta.resetFrom(e);let o=new Map(r.map(m=>{let{id:S}=this.parseFileExportname(m.name);return[S,m]})),s=t.map(m=>{let S=o.get(m.id);return{...m,file:S}});await this._fileManager.importAll(s);let a=e.schema.version,u=indexedDB.deleteDatabase([this.namespace,"collections"].join("_"));await new Promise((m,S)=>{u.onsuccess=m,u.onerror=S});let d=this.context.schema;if(d.version!==a)throw new Error("Only exports from the current schema version can be imported");this.context.documentDb=await Ct({meta:this.meta,migrations:this.config.migrations,context:this.context,version:a}),this.context.internalEvents.emit("documentDbChanged",this.documentDb),this.context.log("Re-initializing data from imported data..."),await this._entities.addData({operations:e.operations,baselines:e.baselines,reset:!0}),await ge(this.context.documentDb),this.context.log("Migrating up to latest schema..."),this.context.schema=d,this.context.documentDb=await Ct({meta:this.meta,migrations:this.config.migrations,context:this.context,version:d.version}),this.context.internalEvents.emit("documentDbChanged",this.documentDb)};this.__dangerous__hardReset=async()=>{let e=await this.export();await this.import(e)};this.meta=r.meta,this.collectionNames=Object.keys(t.schema.collections),this._sync=this.config.syncConfig&&!t.schema.wip?new at(this.config.syncConfig,{meta:this.meta,onData:this.addData,ctx:this.context}):new Hn({meta:this.meta}),t.schema.wip&&this.config.syncConfig&&t.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 Rn({db:this.metaDb,sync:this.sync,context:this.context,config:this.config.files,meta:this.meta}),this._entities=new Pn({ctx:this.context,meta:this.meta,files:this._fileManager}),this._queryCache=new Ln({context:t}),this._documentManager=new mn(this.meta,this.schema,this._entities);let o=Pr(()=>{this.emit("futureSeen")},300);this.context.globalEvents.subscribe("futureSeen",o),this.documentDb.addEventListener("versionchange",()=>{this.context.log?.(`Another tab has requested a version change for ${this.namespace}`),this.documentDb.close(),typeof window<"u"&&window.location.reload()}),this.metaDb.addEventListener("versionchange",()=>{this.context.log?.(`Another tab has requested a version change for ${this.namespace}`),this.metaDb.close(),typeof window<"u"&&window.location.reload()});for(let[s,a]of Object.entries(t.schema.collections)){let u=s;this[u]=new jn({collection:u,cache:this._queryCache,context:this.context,entities:this.entities,documentManager:this.documentManager})}}get sync(){return this._sync}get entities(){return this._entities}get documentManager(){return this._documentManager}get documentDb(){return this.context.documentDb}get metaDb(){return this.context.metaDb}get schema(){return this.context.schema}get namespace(){return this.context.namespace}get undoHistory(){return this.context.undoHistory}get batch(){return this.entities.batch}};var At=class{constructor(i){this.value=i}deref(){return this.value}};var Wo=Symbol("metadataVersion");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;return i.schema.wip?e=await this.initializeWIPDatabases(i):(e=await this.initializeDatabases(i),this.cleanupWIPDatabases(i)),this.resolveReady(e),this._resolvedValue=e,e}catch(e){throw e instanceof Error?(this.rejectReady(e),e):new Error("Unknown error initializing storage")}finally{this._initializing=!1}};this.initializeDatabases=async i=>{let e=i[Wo],{db:t}=await dn({indexedDB:i.indexedDb,log:i.log,namespace:i.namespace,metadataVersion:e}),r={namespace:this._namespace,metaDb:t,schema:i.schema,log:i.log||(()=>{}),undoHistory:i.undoHistory||new He,entityEvents:new V,globalEvents:new V,internalEvents:new V,weakRef:m=>i.EXPERIMENTAL_weakRefs?new WeakRef(m):new At(m),migrations:i.migrations,oldSchemas:i.oldSchemas},o=new xt({context:r,disableRebasing:i.disableRebasing,onOperation:i.onOperation});await o.updateSchema(i.schema,i.overrideSchemaConflict);let s=Object.assign(r,{getNow:()=>o.now}),a=await Ct({context:s,version:i.schema.version,meta:o,migrations:i.migrations,indexedDB:i.indexedDb}),u=Object.assign(s,{documentDb:a});return new Je({syncConfig:i.sync,migrations:i.migrations,files:i.files},u,{meta:o})};this.initializeWIPDatabases=async i=>{let e=Be(i.schema);console.info(`WIP schema in use. Opening database with hash ${e}`);let t=`@@wip_${i.namespace}_${e}`,{db:r}=await Xr({indexedDB:i.indexedDb,log:i.log,namespace:i.namespace,wipNamespace:t}),o={namespace:this._namespace,metaDb:r,schema:i.schema,log:i.log||(()=>{}),undoHistory:i.undoHistory||new He,entityEvents:new V,globalEvents:new V,internalEvents:new V,weakRef:S=>i.EXPERIMENTAL_weakRefs?new WeakRef(S):new At(S),migrations:i.migrations,oldSchemas:i.oldSchemas},s=new xt({context:o,disableRebasing:i.disableRebasing}),a=Object.assign(o,{getNow:()=>s.now});await s.updateSchema(i.schema,i.overrideSchemaConflict);let u=await ao({context:a,version:i.schema.version,meta:s,migrations:i.migrations,indexedDB:i.indexedDb,wipNamespace:t}),d=Object.assign(a,{documentDb:u});return new Je({syncConfig:i.sync,migrations:i.migrations,files:i.files},d,{meta:s})};this.cleanupWIPDatabases=async i=>{let r=(await Gr(i.indexedDb)).filter(o=>o.name?.startsWith("@@wip_")).map(o=>o.name).filter(o=>!o.startsWith(`@@wip_${i.namespace}_${Be(i.schema)}`));for(let o of r)await Jr(o,i.indexedDb)};this.open=()=>this.initialize(this.init);this.close=async()=>{this._resolvedValue&&this._resolvedValue.close(),this._initializing&&(await this._readyPromise).close()};this.__dangerous__resetLocal=async()=>{await tn(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 Ji=Ue(Xe(),1);function Ua(n){return n?Ji.default.slug():(0,Ji.default)()}window.Verdant=Gi;
|
|
16
16
|
//# sourceMappingURL=index.js.map
|