@verdant-web/store 2.5.4 → 2.5.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bundle/index.js +4 -4
- package/dist/bundle/index.js.map +4 -4
- package/dist/cjs/entities/Entity.d.ts +6 -0
- package/dist/cjs/entities/Entity.js +9 -0
- package/dist/cjs/entities/Entity.js.map +1 -1
- package/dist/cjs/index.d.ts +1 -0
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/queries/BaseQuery.d.ts +15 -1
- package/dist/cjs/queries/BaseQuery.js +25 -5
- package/dist/cjs/queries/BaseQuery.js.map +1 -1
- package/dist/esm/entities/Entity.d.ts +6 -0
- package/dist/esm/entities/Entity.js +9 -0
- package/dist/esm/entities/Entity.js.map +1 -1
- package/dist/esm/index.d.ts +1 -0
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/queries/BaseQuery.d.ts +15 -1
- package/dist/esm/queries/BaseQuery.js +25 -5
- package/dist/esm/queries/BaseQuery.js.map +1 -1
- package/dist/tsconfig-cjs.tsbuildinfo +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +2 -2
- package/src/entities/Entity.ts +17 -0
- package/src/index.ts +1 -0
- package/src/queries/BaseQuery.ts +43 -5
package/dist/bundle/index.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
"use strict";var di=Object.create;var Bt=Object.defineProperty;var ui=Object.getOwnPropertyDescriptor;var pi=Object.getOwnPropertyNames;var hi=Object.getPrototypeOf,mi=Object.prototype.hasOwnProperty;var ke=(i,t)=>()=>(t||i((t={exports:{}}).exports,t),t.exports),fi=(i,t)=>{for(var e in t)Bt(i,e,{get:t[e],enumerable:!0})},yi=(i,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of pi(t))!mi.call(i,r)&&r!==e&&Bt(i,r,{get:()=>t[r],enumerable:!(n=ui(t,r))||n.enumerable});return i};var jt=(i,t,e)=>(e=i!=null?di(hi(i)):{},yi(t||!i||!i.__esModule?Bt(e,"default",{value:i,enumerable:!0}):e,i));var Lt=ke((Fr,pn)=>{pn.exports=function(t,e){var n="000000000"+t;return n.substr(n.length-e)}});var mn=ke((Ar,hn)=>{var gi=Lt(),bi=typeof window=="object"?window:self,vi=Object.keys(bi).length,Si=navigator.mimeTypes?navigator.mimeTypes.length:0,xi=gi((Si+navigator.userAgent.length).toString(36)+vi.toString(36),4);hn.exports=function(){return xi}});var bn=ke((Mr,gn)=>{var Vt,fn=typeof window<"u"&&(window.crypto||window.msCrypto)||typeof self<"u"&&self.crypto;fn?(yn=Math.pow(2,32)-1,Vt=function(){return Math.abs(fn.getRandomValues(new Uint32Array(1))[0]/yn)}):Vt=Math.random;var yn;gn.exports=Vt});var Ae=ke((Br,On)=>{var _e=mn(),vn=Lt(),Oi=bn(),me=0,Ut=4,Fe=36,Sn=Math.pow(Fe,Ut);function Nt(){return vn((Oi()*Sn<<0).toString(Fe),Ut)}function xn(){return me=me<Sn?me:0,me++,me-1}function fe(){var i="c",t=new Date().getTime().toString(Fe),e=vn(xn().toString(Fe),Ut),n=_e(),r=Nt()+Nt();return i+t+e+n+r}fe.slug=function(){var t=new Date().getTime().toString(36),e=xn().toString(36).slice(-4),n=_e().slice(0,1)+_e().slice(-1),r=Nt().slice(-2);return t.slice(-2)+e+n+r};fe.isCuid=function(t){return typeof t!="string"?!1:!!t.startsWith("c")};fe.isSlug=function(t){if(typeof t!="string")return!1;var e=t.length;return e>=7&&e<=10};fe.fingerprint=_e;On.exports=fe});var un={};fi(un,{Client:()=>he,ClientDescriptor:()=>Mt,Entity:()=>U,EntityFile:()=>ne,MigrationPathError:()=>oe,ServerSync:()=>ue,Storage:()=>he,StorageDescriptor:()=>Mt,collection:()=>Hn,createDefaultMigration:()=>rn,migrate:()=>Ye,schema:()=>Qn});var Tn=jt(Ae(),1),Me=4,ge=36;function wn(i){return i.toString(ge).padStart(Me,"0")}function wi(i){return i.toString().padStart(6,"0")}var Be=class{constructor(){this.latest={time:Date.now(),counter:0,node:Ii()};this.zeroCounter=0;this.now=t=>(this.latest=Cn(this.latest),this.get(t,this.latest));this.OLD_now=t=>(this.latest=Cn(this.latest),wi(t)+Di(this.latest));this.timerState=()=>this.latest;this.update=t=>{let e=t.slice(Me);this.latest=Ci(this.latest,Dn(e))};this.get=(t,e)=>wn(t)+In(e);this.zero=t=>wn(t)+In({time:0,counter:this.zeroCounter++,node:this.latest.node});this.getWallClockTime=t=>Dn(t.slice(Me)).time}},je=class extends Error{constructor(...e){super();this.type="ClockDriftError",this.message=["maximum clock drift exceeded"].concat(e).join(" ")}},Le=class extends Error{constructor(){super();this.type="OverflowError",this.message="timestamp counter overflow"}},Kt=4,zt=7,Ve=60*1e3,ye=9;function Ii(){return Tn.default.slug().padStart(zt,"0").slice(0,zt)}function In(i){let t=new Date(i.time).getTime().toString(ge).padStart(ye,"0"),e=i.counter.toString(ge).padStart(Kt,"0"),n=i.node.padStart(zt,"0");return`${t}${e}${n}`}function Cn(i){let t=Date.now(),e=Math.max(i.time,t),n=i.time===e?i.counter+1:0;if(e-t>Ve)throw new je(e,t,Ve);if(n>65535)throw new Le;return{time:e,counter:n,node:i.node}}function Ci(i,t){let e=Date.now(),n=Math.max(e,Math.max(i.time,t.time)),r=Math.max(i.counter,t.counter),s;if(i.time===n&&t.time===n?s=r+1:i.time===n?s=i.counter+1:t.time===n?s=t.counter+1:s=0,n-e>Ve)throw new je(n,e,Ve);if(s>65535)throw new Le;return{time:n,counter:s,node:i.node}}function Dn(i){let t=i.slice(0,ye),e=i.slice(ye,ye+Kt),n=i.slice(ye+Kt),r=parseInt(t,ge),s=parseInt(e,ge);if(isNaN(r)||isNaN(s))throw new Error("invalid clock format");return{time:r,counter:s,node:n}}function Di(i){let t=new Date(i.time).toISOString(),e=i.counter.toString(16).toUpperCase().padStart(4,"0"),n=i.node.padStart(16,"0");return`${t}-${e}-${n}`}function Pn(i){return parseInt(i.slice(0,Me),36)}function En(i,t){return Pn(i)-Pn(t)}var Ne,Pi=new Uint8Array(16);function $t(){if(!Ne&&(Ne=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!Ne))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Ne(Pi)}var Rn=/^(?:[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 Ti(i){return typeof i=="string"&&Rn.test(i)}var kn=Ti;var P=[];for(Ue=0;Ue<256;++Ue)P.push((Ue+256).toString(16).substr(1));var Ue;function Ei(i){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=(P[i[t+0]]+P[i[t+1]]+P[i[t+2]]+P[i[t+3]]+"-"+P[i[t+4]]+P[i[t+5]]+"-"+P[i[t+6]]+P[i[t+7]]+"-"+P[i[t+8]]+P[i[t+9]]+"-"+P[i[t+10]]+P[i[t+11]]+P[i[t+12]]+P[i[t+13]]+P[i[t+14]]+P[i[t+15]]).toLowerCase();if(!kn(e))throw TypeError("Stringified UUID is invalid");return e}var _n=Ei;function Ri(i,t,e){i=i||{};var n=i.random||(i.rng||$t)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){e=e||0;for(var r=0;r<16;++r)t[e+r]=n[r];return t}return _n(n)}var be=Ri;function K(i){return i&&i["@@type"]==="file"}function Fn(i){return{"@@type":"file",id:i}}function R(i){return E(i)||K(i)}function An(i,t){return i===t?!0:!(!R(i)||!R(t)||i["@@type"]!==t["@@type"]||i.id!==t.id)}function ki(i,t){return typeof t!="object"||t===null||Array.isArray(t)?t:Object.fromEntries(Object.entries(t).sort(([e],[n])=>e<n?-1:e>n?1:0))}function Ke(i){return JSON.stringify(i,ki)}function k(i,t=!0){if(S(i)||Array.isArray(i)){let e=F(i),n;if(Array.isArray(i))n=i.map(r=>k(r,t));else{n={};for(let[r,s]of Object.entries(i))n[r]=k(s,t)}return t&&e&&x(n,e),n}return i}function ve(i){return Ke(i)}function S(i){return i&&typeof i=="object"}function Mn(i){for(var t=[],e=[i],n=0;e.length;){var r=e.pop();if(typeof r=="boolean")n+=4;else if(typeof r=="string")n+=r.length*2;else if(typeof r=="number")n+=8;else if(typeof r=="object"&&t.indexOf(r)===-1){t.push(r);for(var s in r)e.push(r[s])}}return n}function y(i,t="assertion failed"){if(!i)throw new Error(t)}function ze(i=16){return be().replace("-","").slice(0,i)}function Bn(i,t){for(let e=i.length-1;e>=0;e--)if(t(i[e]))return e;return-1}function jn(i,t){let e;return function(...n){let r=this;clearTimeout(e),e=setTimeout(()=>i.apply(r,n),t)}}var J="__@@oid_do_not_use",H="@@id",_i="/",He=":",Ht=new WeakMap;function L(i){let t=F(i);return y(!!t,`Object ${JSON.stringify(i)} does not have an OID assigned to it`),t}function F(i){if(S(i))return Ht.get(i)??i[H]??i[J]}function x(i,t){return y(S(i),`Only objects can be assigned OIDs, received ${JSON.stringify(i)}`),xe(i)&&Qe(i),Ht.set(i,t),i}function xe(i){return!!F(i)}function Qe(i){return Ht.delete(i),i}function Qt(i){return i===H||i===J}function Wt(i,t,e){if(xe(i))return L(i);{let n=z(t,e);return x(i,n),n}}function Ln(i,t,e){if(xe(i)){let n=L(i);if(We(n,t))return L(i);{let r=z(t,e);return x(i,r),r}}else{let n=z(t,e);return x(i,n),n}}var qt={".":"˙","/":"&slash;",":":":"};function Vn(i){return i.replace(/[/]/g,qt["/"]).replace(/[:]/g,qt[":"]).replace(/[.]/g,qt["."])}function Nn(i){return i.replace(/&slash;/g,"/").replace(/:/g,":").replace(/˙/g,".")}function T(i,t,e){let n=Vn(i)+_i+Vn(t);return e&&(n+=He+e),n}function z(i,t=Li){let{collection:e,id:n}=M(i);return T(e,n,t())}function M(i){let[t,e]=i.split(He),[n,r]=t.split("/"),s;return r.includes(".")?s=r.slice(0,r.indexOf(".")):s=r,{collection:Nn(n),id:Nn(s),subId:e}}function re(i,t){let e=L(i);if(Array.isArray(i)){let n;for(let r=0;r<i.length;r++)n=i[r],S(n)&&!R(n)&&(Ln(n,e,t),re(n,t))}else if(S(i)&&!R(i))for(let n of Object.keys(i))S(i[n])&&!R(i[n])&&(Ln(i[n],e,t),re(i[n],t))}function Fi(i,t){return y(S(i),`Only objects can be assigned OIDs, received ${JSON.stringify(i)}`),i[H]=t,i}function Ai(i){if(S(i))return i[H]||i[J]}function Mi(i){return S(i)&&(delete i[J],delete i[H]),i}function Bi(i){let t=F(i);t&&Fi(i,t)}function se(i){if(Bi(i),Array.isArray(i))for(let t=0;t<i.length;t++)se(i[t]);else if(S(i))for(let t of Object.keys(i))se(i[t])}function ji(i){let t=Ai(i);t&&x(i,t)}function Se(i){if(ji(i),Mi(i),Array.isArray(i))for(let t=0;t<i.length;t++)Se(i[t]);else if(S(i))for(let t of Object.keys(i))Se(i[t])}function $e(i){if(Qe(i),Array.isArray(i))for(let t=0;t<i.length;t++)$e(i[t]);else if(S(i))for(let t of Object.keys(i))$e(i[t])}function Li(){return be().slice(0,8)}function $(i){return{"@@type":"ref",id:i}}function qe(i,t=new Map){if(Array.isArray(i)){let e=L(i),n=x([],e);for(let r=0;r<i.length;r++){let s=i[r];if(S(s)){if(E(s))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(K(s)){n[r]=s;continue}else{let a=L(s);n[r]=$(a),qe(s,t)}}else n[r]=s}t.set(e,n)}else if(S(i)&&!R(i)){let e=L(i),n=x({},e);for(let r of Object.keys(i)){let s=i[r];if(S(s)){if(E(s))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(K(s))n[r]=s;else{let a=L(s);n[r]=$(a),qe(s,t)}}else n[r]=s}t.set(e,n)}else R(i);return t}function w(i){return i.split(".")[0].split(He)[0]}function Jt(i){let t=w(i);return[t,`${t}${He}\uFFFF`]}function We(i,t){return w(i)===w(t)}function E(i){return i&&typeof i=="object"&&i["@@type"]==="ref"}function Gt(i){return S(i)&&!R(i)}function Vi(i,t){return i===t?!0:R(i)&&R(t)?An(i,t):!1}function Oe(i,t,e,n,r=[],s={}){let a=L(i);function o(c,l,u){if(!Gt(l))Vi(l,u)||r.push({oid:a,timestamp:e(),data:{op:"set",name:c,value:l}});else{let d=F(u),p=F(l);p&&!We(a,p)?(l=k(l,!1),p=z(a,n),x(l,p)):s.mergeUnknownObjects?!p&&d?(x(l,d),p=d):p=Wt(l,a,n):p=Wt(l,a,n),y(!!p,"Error: no value OID was resolved during diff. This is a bug in Verdant."),y(We(a,p),`Error: value OID ${p} is not related to parent OID ${a}. This is a bug in Verdant.`),u===void 0||p!==d?(Q(l,p,e,n,r),r.push({oid:a,timestamp:e(),data:{op:"set",name:c,value:$(p)}}),d!==void 0&&r.push({oid:d,timestamp:e(),data:{op:"delete"}})):Oe(u,l,e,n,r,s)}}if(Array.isArray(i)&&Array.isArray(t)){for(let l=0;l<t.length;l++){let u=t[l],d=i[l];o(l,u,d)}let c=i.length-t.length;if(c>0){for(let l=t.length;l<i.length;l++){let u=i[l],d=F(u);d&&r.push({oid:d,timestamp:e(),data:{op:"delete"}})}r.push({oid:a,timestamp:e(),data:{op:"list-delete",index:t.length,count:c}})}}else{if(Array.isArray(i)||Array.isArray(t))throw new Error("Cannot diff an array with an object");if(Gt(i)&&Gt(t)){let c=new Set(Object.keys(i));for(let[l,u]of Object.entries(t)){if(u===void 0&&s.defaultUndefined||(c.delete(l),Qt(l)))continue;let d=i[l];o(l,u,d)}if(!s.defaultUndefined)for(let l of c)Qt(l)||r.push({oid:a,timestamp:e(),data:{op:"remove",name:l}})}}return r}function Q(i,t,e,n,r=[]){x(i,t),re(i,n);let s=qe(i);for(let a of s.keys()){let o=s.get(a);r.push({oid:a,timestamp:e(),data:{op:"initialize",value:Qe(o)}})}return r}function Kn(i){let t={};for(let e of i)e.oid in t?t[e.oid].push(e):t[e.oid]=[e];return t}function Xt(i){let t={};for(let e of i){let n=w(e.oid);n in t?t[n].push(e):t[n]=[e]}return t}function Yt(i){let t={};for(let e of i){let n=w(e.oid);n in t?t[n].push(e):t[n]=[e]}return t}function G(i){return Array.isArray(i)?!0:(console.error(`Cannot apply list patch; expected array, received ${JSON.stringify(i)}. This suggests your data is changing from a list to an object over time. (OID: ${F(i)})`),!1)}function X(i,t,e){if(i==null&&t.op!=="initialize")return i;let n=i,r,s;function a(o){e&&R(o)&&e.push(o)}switch(t.op){case"set":a(n[t.name]),n[t.name]=t.value;break;case"remove":a(n[t.name]),delete n[t.name];break;case"list-push":G(i)&&i.push(t.value);break;case"list-delete":G(i)&&(a(i[t.index]),i.splice(t.index,t.count));break;case"list-move-by-index":G(i)&&(s=i.splice(t.from,1),i.splice(t.to,0,s[0]));break;case"list-remove":if(G(i))do{let o=t.value;t.only==="last"?E(o)?r=Bn(i,c=>c.id===o.id):r=i.lastIndexOf(o):E(o)?r=i.findIndex(c=>c.id===o.id):r=i.indexOf(o),r!==-1&&(a(i[r]),i.splice(r,1))}while(!t.only&&r!==-1);break;case"list-add":G(i)&&(i.some(c=>E(c)&&E(t.value)?c.id===t.value.id:c===t.value)||i.push(t.value));break;case"list-move-by-ref":G(i)&&(r=i.indexOf(t.value),s=i.splice(r,1),i.splice(t.index,0,s[0]));break;case"list-insert":if(G(i)){if(!t.value&&!t.values)throw new Error(`Cannot apply list insert patch; expected value or values, received ${JSON.stringify(t)}`);t.value?i.splice(t.index,0,t.value):i.splice(t.index,0,...t.values)}break;case"delete":Array.isArray(i)?i.forEach(a):S(i)&&Object.values(i||{}).forEach(a);return;case"initialize":return k(t.value);default:throw new Error(`Unsupported patch operation: ${t.op}`)}return i}function Je(i,t,e=[]){if(Array.isArray(i))for(let n=0;n<i.length;n++){let r=i[n];i[n]=Un(r,t,e),S(i[n])&&Je(i[n],t,e)}else if(S(i)){y(F(i),`Object ${JSON.stringify(i)} must have an oid`);for(let n of Object.keys(i))i[n]=Un(i[n],t,e),S(i[n])&&Je(i[n],t,e)}return e}function Un(i,t,e){if(E(i)){e.push(i.id);let n=t.get(i.id);return y(!!n,`No value was found in object map for ${i.id}`),x(n,i.id)}else return i}function Zt(i){return i.equals!==void 0}function en(i){return i.gte!==void 0||i.lte!==void 0||i.gt!==void 0||i.lt!==void 0}function Ni(i){return!!i.match}function tn(i){return i.startsWith!==void 0}function zn(i){return!en(i)&&!Zt(i)&&!Ni(i)&&!tn(i)&&i.order}function Ui(i){return i.type==="any"?!0:i.type==="map"?!1:i.nullable}function Z(i,t){for(let[e,n]of Object.entries(i.fields)){let r=$n(n);(r!==void 0&&t[e]===void 0||!Ui(n)&&t[e]===null)&&(t[e]=r),t[e]&&Y(t[e],n)}return t}function Y(i,t){if(i==null)return i;if(t.type==="object")for(let[e,n]of Object.entries(t.properties)){if(i[e]===void 0){let r=$n(n);r!==void 0&&(i[e]=r)}Y(i[e],n)}else if(t.type==="array")for(let e of i)Y(e,t.items);else if(t.type==="map")for(let[e,n]of Object.entries(i))e===H||e===J||Y(n,t.values)}function $n(i){if(i.type==="string"||i.type==="number"||i.type==="boolean"||i.type==="any"){if(i.default&&typeof i.default=="function")return i.default();if(i.default!==void 0)return JSON.parse(JSON.stringify(i.default))}if(i.type==="array")return[];if(i.type==="map")return{};if(i.type!=="any"&&i.nullable)return null}function qn(i,t){for(let[e,n]of Object.entries(t))e===H||e===J||(i.fields[e]?nn(n,i.fields[e]):delete t[e]);return t}function nn(i,t){if(S(i)&&t.type==="object")for(let[e,n]of Object.entries(i))t.properties[e]?nn(n,t.properties[e]):delete i[e];else if(Array.isArray(i)&&t.type==="array")for(let e of i)nn(e,t.items)}function Hn(i){return i}function Qn(i){return i}var Ge="\uFFFFFE",Ki="\0",zi="\uFFFFFF";function B(...i){let t=$i(i);return t.length===1?t[0]:t}function ee(...i){return i.join(Ge)+`${zi}`}function te(...i){return i.join(Ge)+`${Ge}${Ki}`}function $i(i){let t=[[]];for(let e of i)if(Array.isArray(e)){let n=[];for(let r of t)for(let s of e)n.push(r.concat(s));t=n}else for(let n of t)n.push(`${e}`);return Array.from(new Set(t.map(e=>e.join(Ge))))}function qi(i,t){let e={};for(let[n,r]of Object.entries(i.synthetics||{}))e[n]=q(r.compute(t));return e}function Hi(i,t){return Object.entries(i.compounds||{}).reduce((e,[n,r])=>(e[n]=B(...r.of.map(s=>t[s])),e),{})}function Xe(i,t){return Object.assign(t,qi(i,t)),Object.assign(t,Hi(i,t)),t}var Qi="null";function q(i){if(i===null)return Qi;if(typeof i=="string"||typeof i=="number")return i;if(typeof i=="boolean"||i===null)return`${i}`;if(i===void 0)return"undefined";if(Array.isArray(i))return i.map(q);throw new Error(`Unsupported index value: ${i}`)}var Wi={version:0,collections:{}};function Ye(i,t,e){let n=typeof t=="function",r=n?Wi:i,s=n?i:t,a=n?t:e,o=Object.keys(s.collections).filter(h=>r.collections[h]&&Ke(r.collections[h])!==Ke(s.collections[h])),c=Object.keys(r.collections).filter(h=>!s.collections[h]),l=Object.keys(s.collections).filter(h=>!r.collections[h]),u=new Set;for(let h of o){let m=r.collections[h].fields,f=s.collections[h].fields;Object.keys(f).some(v=>!m[v]?.default&&f[v]?.default)&&u.add(h),Object.keys(m).some(v=>!f[v])&&u.add(h)}let d={},p={};for(let h of[...o,...l]){let m=Wn(r.collections[h]),f=Wn(s.collections[h]),v=f.filter(O=>!m.find(D=>D.name===O.name)),C=m.filter(O=>!f.find(D=>D.name===O.name));v.length>0&&(d[h]=v,o.includes(h)&&u.add(h)),C.length>0&&(p[h]=C,o.includes(h)&&u.add(h))}let g=(h,m)=>Z(s.collections[h],m),I=h=>m=>{let f=s.collections[h];return Z(f,qn(f,m))};return{version:s.version,migrate:async h=>{let m=[];if(await a({migrate:async(f,v)=>{let C=I(f),O=async D=>{let A=await v(D);return x(A,L(D)),C(A)};await h.migrate(f,O),m.push(f),u.delete(f)},identity:f=>f,withDefaults:g,info:{changedCollections:o,addedCollections:l,removedCollections:c},queries:h.queries,mutations:h.mutations}),s.version>1){h.log("debug","auto-migrating collections with new defaults",u);for(let v of u)await h.migrate(v,I(v)),m.push(v);let f=o.filter(v=>!m.includes(v));f.length>0&&console.error(`Unmigrated changed collections from version ${r.version} to version ${s.version}:`,f)}},removedCollections:c,addedIndexes:d,removedIndexes:p,allCollections:Object.keys(s.collections),changedCollections:o,addedCollections:l,oldCollections:Object.keys(r.collections),oldSchema:r,newSchema:s}}function Wn(i){return i?[...Object.keys(i.fields).filter(e=>i.fields[e].indexed).map(e=>({name:e,multiEntry:i.fields[e].type==="array",synthetic:!1,compound:!1})),...Object.keys(i.synthetics||{}).map(e=>({name:e,multiEntry:["array","string[]","number[]","boolean[]"].includes(i.synthetics[e].type),synthetic:!0,compound:!1})),...Object.keys(i.compounds||{}).map(e=>({name:e,multiEntry:i.compounds[e].of.some(n=>(i.fields[n]||i.synthetics[n]).type==="array"),synthetic:!1,compound:!0}))]:[]}function rn(i,t){return Ye(t?i:{version:0,collections:{}},t||i,async({migrate:n,info:r})=>{if((t||i).version!==1)for(let s of r.changedCollections)await n(s,a=>a)})}var Ze=class{constructor(t,e){this.getNow=t;this.createSubId=e;this.createDiff=(t,e,n={})=>Oe(t,e,this.getNow,this.createSubId,[],n);this.createInitialize=(t,e)=>Q(t,e,this.getNow,this.createSubId);this.createSet=(t,e,n)=>{if(!S(n)||R(n))return[{oid:t,timestamp:this.getNow(),data:{op:"set",name:e,value:n}}];{let r=z(t,this.createSubId);return[...Q(n,r,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"set",value:$(r),name:e}}]}};this.createRemove=(t,e)=>[{oid:t,timestamp:this.getNow(),data:{op:"remove",name:e}}];this.createListPush=(t,e)=>{if(S(e)){let n=z(t,this.createSubId);return[...Q(e,n,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:$(n)}}]}else return[{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:e}}]};this.createListAdd=(t,e)=>S(e)?[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:$(e)}}]:[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:e}}];this.createListInsert=(t,e,n)=>{if(S(n)){let r=z(t,this.createSubId);return[...Q(n,r,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:$(r),index:e}}]}else return[{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:n,index:e}}]};this.createListRemove=(t,e,n)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-remove",value:e,only:n}}];this.createListDelete=(t,e,n=1)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-delete",index:e,count:n}}];this.createListMoveByRef=(t,e,n)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-move-by-ref",value:e,index:n}}];this.createListMoveByIndex=(t,e,n)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-move-by-index",from:e,to:n}}];this.createDelete=t=>[{oid:t,timestamp:this.getNow(),data:{op:"delete"}}];this.createDeleteAll=t=>t.map(e=>({oid:e,timestamp:this.getNow(),data:{op:"delete"}}))}};var b=class{constructor(t){this._onAllUnsubscribed=t;this.subscribers={};this.counts={};this._disabled=!1;this.subscriberCount=t=>this.counts[t]??0;this.totalSubscriberCount=()=>Object.values(this.counts).reduce((t,e)=>t+e,0);this.subscribe=(t,e)=>{let n=ze(),r=this.subscribers[t];return r||(r=this.subscribers[t]={}),r[n]=e,this.counts[t]=(this.counts[t]||0)+1,()=>{this.subscribers[t]&&(delete this.subscribers[t][n],this.counts[t]--,this.counts[t]===0&&(delete this.subscribers[t],delete this.counts[t],this._onAllUnsubscribed&&this._onAllUnsubscribed(t)))}};this.emit=(t,...e)=>{this._disabled||this.subscribers[t]&&Object.values(this.subscribers[t]).forEach(n=>n(...e))};this.dispose=()=>{let t=Object.keys(this.subscribers);this.subscribers={},this.counts={},t.forEach(e=>{this._onAllUnsubscribed&&this._onAllUnsubscribed(e)})};this.disable=()=>{this._disabled=!0}}get disabled(){return this._disabled}};function Jn(i,t,e,n){if(t===void 0)return[{oid:i,timestamp:n(),data:{op:"delete"}}];let r=k(t),s=[];for(let a of e){let o=Ji(i,r,a,n);s.unshift(...o),X(r,a.data)}return s}function Ji(i,t,e,n){let r=e.data;switch(r.op){case"set":case"remove":return[{oid:i,timestamp:n(),data:{op:"set",name:r.name,value:t[r.name]}}];case"list-insert":return[{oid:i,timestamp:n(),data:{op:"list-delete",index:r.index,count:1}}];case"list-delete":return[{oid:i,timestamp:n(),data:{op:"list-insert",index:r.index,values:t.slice(r.index,r.count)}}];case"list-move-by-ref":return[{oid:i,timestamp:n(),data:{op:"list-move-by-ref",value:r.value,index:t.indexOf(r.value)}}];case"list-move-by-index":return[{oid:i,timestamp:n(),data:{op:"list-move-by-index",from:r.to,to:r.from}}];case"delete":return[{oid:i,timestamp:n(),data:{op:"initialize",value:t}}];case"list-push":return[{oid:i,timestamp:n(),data:{op:"list-remove",value:r.value,only:"last"}}];case"list-remove":if(r.only==="last"){let s=t.lastIndexOf(r.value);return[{oid:i,timestamp:n(),data:{op:"list-insert",index:s,values:[r.value]}}]}else if(r.only==="first"){let s=t.indexOf(r.value);return[{oid:i,timestamp:n(),data:{op:"list-insert",index:s,values:[r.value]}}]}else{let s=[],a=t.indexOf(r.value);for(;a!==-1;)s.push(a),a=t.indexOf(r.value,a+1);return s.map(o=>({oid:i,timestamp:n(),data:{op:"list-insert",index:o,value:r.value}}))}case"list-add":return[{oid:i,timestamp:n(),data:{op:"list-remove",value:r.value,only:"last"}}];case"initialize":return[{oid:i,timestamp:n(),data:{op:"delete"}}];default:throw new Error(`Cannot undo operation type: ${r.op}`)}}var ae=class{constructor(t){this.flusher=t;this.batches=new Map;this.flush=t=>{let e=this.batches.get(t);if(e)return e.flush()};this.discard=t=>{let e=this.batches.get(t);e&&(e.discard(),this.batches.delete(t))}}add({key:t,userData:e,items:n,max:r,timeout:s}){let a=this.batches.get(t);return a||(a=new sn({max:r||null,startedAt:Date.now(),userData:e,timeout:s||null,flusher:this.flusher,key:t}),this.batches.set(t,a)),a.update({items:n,max:r,timeout:s,userData:e}),a}},sn=class{constructor({max:t,startedAt:e,timeout:n,userData:r,flusher:s,key:a}){this.items=[];this.update=({items:t,max:e,timeout:n,userData:r})=>{this.items.push(...t),e!==void 0&&(this.max=e),n!==void 0&&(this.timeout=n),r&&(this.userData=r);let 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 t=this.items;return this.items=[],this.flusher(t,this.key,this.userData)};this.discard=()=>{this.flushTimeout&&clearTimeout(this.flushTimeout),this.flushTimeout=void 0,this.items=[]};this.max=t,this.startedAt=e,this.timeout=n,this.userData=r,this.flusher=s,this.key=a}};function _(i){return new Promise((t,e)=>{i.onsuccess=()=>{t(i.result)},i.onerror=()=>{e(i.error)}})}function we(i,t){return new Promise((e,n)=>{let r=i.transaction([t],"readonly"),a=r.objectStore(t).openCursor(),o=0,c=0;a.onsuccess=function(l){let u=a.result;u&&(o++,c=c+Mn(u.value),u.continue())},a.onerror=function(l){n(l)},r.oncomplete=function(l){e({count:o,size:c})},r.onabort=function(l){n(l)},r.onerror=function(l){n(l)}})}function Gn(i,t){let e=i.transaction(t,"readonly"),n=t.map(r=>{let s=e.objectStore(r);return _(s.getAll())});return Promise.all(n)}async function Ie(i){i.close(),await new Promise((t,e)=>{t()})}async function et(i,t=window.indexedDB){let e=t.deleteDatabase([i,"meta"].join("_")),n=t.deleteDatabase([i,"collections"].join("_"));await Promise.all([new Promise((r,s)=>{e.onsuccess=r,e.onerror=s}),new Promise((r,s)=>{n.onsuccess=r,n.onerror=s})]),window.location.reload()}var V=class{constructor(t){this.db=t;this.createTransaction=(t,e)=>this.db.transaction(t,e);this.run=async(t,e,n="readonly",r)=>{let a=(r||this.db.transaction(t,n)).objectStore(t),o=e(a);return _(o)};this.runAll=async(t,e,n="readonly",r)=>{let a=(r||this.db.transaction(t,n)).objectStore(t),o=e(a);return Promise.all(o.map(_))};this.iterate=async(t,e,n,r="readonly",s)=>{let o=(s||this.db.transaction(t,r)).objectStore(t),c=e(o);return new Promise((l,u)=>{c.onsuccess=d=>{let p=c.result;p?(n(p.value,o),p.continue()):l()},c.onerror=u})};this.clear=t=>this.run(t,e=>e.clear(),"readwrite")}};var tt=class extends V{constructor(){super(...arguments);this.getAckInfo=async()=>{let e=await this.run("info",n=>n.get("ack"));return e||{globalAckTimestamp:null,type:"ack"}};this.setGlobalAck=async e=>{await this.run("info",n=>n.put({type:"ack",globalAckTimestamp:e}),"readwrite")}}};var nt=class extends V{constructor(e){super(e);this.getAllForDocument=async(e,{mode:n="readonly",transaction:r}={})=>{let s=[];return await this.iterateOverAllForDocument(e,a=>{s.push(a)},{mode:n,transaction:r}),s};this.iterateOverAllForDocument=async(e,n,{mode:r="readonly",transaction:s}={})=>this.iterate("baselines",a=>{let[o,c]=Jt(e);return a.openCursor(IDBKeyRange.bound(o,c,!1,!1))},n,r,s);this.getAllForMultipleDocuments=async(e,{mode:n="readonly"}={})=>(await this.runAll("baselines",s=>e.map(a=>{let[o,c]=Jt(a);return s.getAll(IDBKeyRange.bound(o,c,!1,!1))}),n)).flat();this.getAllSince=async(e,{mode:n="readonly"}={})=>this.run("baselines",r=>{let s=e?IDBKeyRange.lowerBound(e,!0):void 0;return r.index("timestamp").getAll(s)},n);this.get=async(e,{transaction:n,mode:r="readonly"}={})=>this.run("baselines",s=>s.get(e),r,n);this.set=async(e,{transaction:n}={})=>{await this.run("baselines",r=>r.put(e),"readwrite",n)};this.setAll=async(e,{transaction:n}={})=>{await this.runAll("baselines",r=>e.map(s=>r.put(s)),"readwrite",n)};this.reset=()=>this.clear("baselines");this.delete=async(e,{transaction:n})=>{await this.run("baselines",r=>r.delete(e),"readwrite",n)}}};var Xn=jt(Ae(),1);var it=class extends V{constructor(){super(...arguments);this.get=async({transaction:e}={})=>{if(this.cached)return this.cached;let n=await this.run("info",r=>r.get("localReplicaInfo"),void 0,e);if(!n){let s={type:"localReplicaInfo",id:(0,Xn.default)(),ackedLogicalTime:null,lastSyncedLogicalTime:null};return await this.run("info",a=>a.put(s),"readwrite"),this.cached=s,s}return this.cached=n,n};this.update=async(e,{transaction:n}={})=>{let r=await this.get({transaction:n});Object.assign(r,e),await this.run("info",s=>s.put(r),"readwrite"),this.cached=r};this.reset=async()=>{let e=await this.get();e.ackedLogicalTime=null,e.lastSyncedLogicalTime=null,await this.run("info",n=>n.put(e),"readwrite")}}};var rt=class{constructor(t){this.meta=t;this.createOperation=async t=>{let e=await this.meta.localReplica.get();return{type:"op",timestamp:this.meta.now,replicaId:e.id,operations:t.operations.map(n=>({data:n.data,oid:n.oid,timestamp:n.timestamp}))}};this.createMigrationOperation=async({targetVersion:t,...e})=>{let n=await this.meta.localReplica.get();return{type:"op",operations:e.operations.map(r=>({...r,timestamp:this.meta.time.zero(t)})),timestamp:this.meta.time.zero(t),replicaId:n.id}};this.createSyncStep1=async t=>{let e=await this.meta.localReplica.get(),n=t===null?null:e.lastSyncedLogicalTime,r=[],s=new Set;n?await this.meta.operations.iterateOverAllLocalOperations(o=>{r.push({data:o.data,oid:o.oid,timestamp:o.timestamp}),s.add(w(o.oid))},{after:n,mode:"readwrite"}):await this.meta.operations.iterateOverAllOperations(o=>{r.push({data:o.data,oid:o.oid,timestamp:o.timestamp}),s.add(w(o.oid))},{mode:"readwrite"});let a=[];return n||(a=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:a,since:n}};this.createPresenceUpdate=async t=>{let e=await this.meta.localReplica.get();return{type:"presence-update",presence:t,replicaId:e.id}};this.createHeartbeat=async()=>{let t=await this.meta.localReplica.get();return{type:"heartbeat",timestamp:this.meta.now,replicaId:t.id}};this.createAck=async t=>{let e=await this.meta.localReplica.get();return{type:"ack",timestamp:this.meta.now,replicaId:e.id,nonce:t}}}};var st=class extends V{constructor(){super(...arguments);this.iterateOverAllOperationsForDocument=async(e,n,{to:r,from:s,after:a,mode:o="readonly",transaction:c}={})=>{let u=(c||this.db.transaction("operations",o)).objectStore("operations"),d=u.index("d_t"),p=s||a,g=p?B(e,p):te(e),I=r?B(e,r):ee(e),h=IDBKeyRange.bound(g,I,!!a,!1),m=d.openCursor(h,"next");return new Promise((f,v)=>{let C;m.onsuccess=O=>{let D=m.result;if(D){let A=D.value;y(A.oid.startsWith(e)),y(C===void 0||C<=A.timestamp,`expected ${C} <= ${A.timestamp}`),n(A,u),C=A.timestamp,D.continue()}else f()},m.onerror=O=>{v(O)}})};this.iterateOverAllOperationsForEntity=async(e,n,{after:r,to:s,mode:a,transaction:o})=>{let l=(o||this.db.transaction("operations",a)).objectStore("operations"),u=r?B(e,r):te(e),d=s?B(e,s):ee(e),p=IDBKeyRange.bound(u,d,!!r,!1),g=l.openCursor(p,"next");return new Promise((I,h)=>{let m;g.onsuccess=f=>{let v=g.result;if(v){let C=v.value;y(C.oid.startsWith(e)),y(m===void 0||m<=C.timestamp,`expected ${m} <= ${C.timestamp}`),n(C,l),m=C.timestamp,v.continue()}else I()},g.onerror=f=>{h(f)}})};this.iterateOverAllLocalOperations=async(e,{before:n,after:r,mode:s="readonly",transaction:a})=>{let c=(a||this.db.transaction("operations",s)).objectStore("operations"),l=c.index("l_t"),u=r?B(!0,r):te(!0),d=n?B(!0,n):ee(!0),p=IDBKeyRange.bound(u,d,!!r,!0),g=l.openCursor(p,"next");return new Promise((I,h)=>{let m;g.onsuccess=f=>{let v=g.result;if(v){let C=v.value;y(m===void 0||m<=C.timestamp,`expected ${m} <= ${C.timestamp}`),e(C,c),m=C.timestamp,v.continue()}else I()},g.onerror=f=>{h(f)}})};this.iterateOverAllOperations=async(e,{before:n,transaction:r,mode:s,from:a})=>{await this.iterate("operations",o=>{let c=a?te(a):void 0,l=n?ee(n):void 0,u=c&&l?IDBKeyRange.bound(c,l,!1,!0):c?IDBKeyRange.lowerBound(c,!1):l?IDBKeyRange.upperBound(l,!0):void 0;return o.index("timestamp").openCursor(u,"next")},e,s,r)};this.addOperations=async(e,{transaction:n}={})=>this.insert(e.map(this.addCompoundIndexes),{transaction:n});this.addCompoundIndexes=e=>({...e,oid_timestamp:B(e.oid,e.timestamp),l_t:B(e.isLocal,e.timestamp),d_t:B(w(e.oid),e.timestamp)});this.insert=async(e,{transaction:n})=>{let r=new Set;return await this.runAll("operations",s=>e.map(a=>(r.add(w(a.oid)),s.put(a))),"readwrite",n),Array.from(r)};this.reset=()=>this.clear("operations")}};var at=class{constructor(t,e){this.db=t;this.currentVersion=e;this.cached=null;this.get=async()=>{if(this.cached)return this.cached;let r=this.db.transaction("info","readonly").objectStore("info").get("schema"),s=await _(r);return s?(this.cached=JSON.parse(s.schema),this.cached):null};this.set=async t=>{let s=this.db.transaction("info","readwrite").objectStore("info").put({type:"schema",schema:JSON.stringify(t)});this.cached=t,await _(s)}}};var ot=class extends b{constructor({disableRebasing:e,context:n}){super();this.time=new Be;this.disableRebasing=!1;this._closing=!1;this.setContext=e=>{this.context=e};this.close=()=>{this._closing=!0};this.createTransaction=e=>this.db.transaction(e,"readwrite");this.getAllDocumentRelatedOids=async e=>{let n=new Set,r=w(e);y(r===e,"Must be root document OID"),n.add(r);let s=this.db.transaction(["baselines","operations"],"readwrite");return await Promise.all([this.baselines.iterateOverAllForDocument(r,a=>{n.add(a.oid)},{transaction:s}),this.operations.iterateOverAllOperationsForDocument(r,a=>{n.add(a.oid)},{transaction:s})]),Array.from(n)};this.getDocumentSnapshot=async e=>{let n=w(e);y(n===e,"Must be root document OID");let r=this.db.transaction(["baselines","operations"],"readwrite"),s=await this.baselines.getAllForDocument(n,{transaction:r}),a=new Map;for(let c of s)c.snapshot&&x(c.snapshot,c.oid),a.set(c.oid,c.snapshot);await this.operations.iterateOverAllOperationsForDocument(n,c=>{let l=a.get(c.oid)||void 0,u=X(l,c.data);u&&x(u,c.oid),a.set(c.oid,u)},{transaction:r});let o=a.get(n);return o&&Je(o,a),o};this.ack=async e=>{let n=await this.localReplica.get();e>this.now||(this.emit("message",{type:"ack",replicaId:n.id,timestamp:e}),!this._closing&&(!n.ackedLogicalTime||e>n.ackedLogicalTime)&&this.localReplica.update({ackedLogicalTime:e}))};this.insertLocalOperation=async e=>{if(e.length===0)return;this.log(`Inserting ${e.length} local operations`);for(let r of e)r.isLocal=!0;await this.operations.addOperations(e);let n=await this.messageCreator.createOperation({operations:e});this.emit("message",n),this.tryAutonomousRebase()};this.insertRemoteOperations=async e=>{if(e.length===0)return[];this.log(`Inserting ${e.length} remote operations`);let n=await this.operations.addOperations(e.map(r=>({...r,isLocal:!1})));return this.ack(e[e.length-1].timestamp),n};this.insertRemoteBaselines=async e=>{if(e.length===0)return[];this.log(`Inserting ${e.length} remote baselines`),await this.baselines.setAll(e);let n=new Set;return e.forEach(r=>{n.add(w(r.oid))}),Array.from(n)};this.updateLastSynced=async e=>{if(!this._closing)return this.localReplica.update({lastSyncedLogicalTime:e})};this.lastSyncedTimestamp=async()=>(await this.localReplica.get()).lastSyncedLogicalTime;this.tryAutonomousRebase=async()=>{this.disableRebasing||(await this.localReplica.get()).lastSyncedLogicalTime||await this.runRebase(this.now)};this.runRebase=async e=>{if(this._closing)return;let n,r=new Set,s=this.db.transaction(["baselines","operations"],"readwrite"),a=0;if(await this.operations.iterateOverAllOperations(c=>{r.add(c.oid),n=c.timestamp,a++},{before:e,transaction:s}),!r.size){this.log("Cannot rebase, no operations prior to",e);return}if(this._closing)return;let o=[];for(let c of r)o.push(await this.rebase(c,n||e,s));this.emit("rebase",o)};this.rebase=async(e,n,r)=>{let s=(await this.localReplica.get()).id;this.log("[",s,"]","Rebasing",e,"up to",n);let a=r||this.db.transaction(["operations","baselines"],"readwrite"),o=await this.baselines.get(e,{transaction:a}),c=o?.snapshot||void 0,l=0,u=[];await this.operations.iterateOverAllOperationsForEntity(e,(p,g)=>{(!o||p.timestamp>o.timestamp)&&(c=X(c,p.data,u)),l++,g.delete(p.oid_timestamp)},{to:n,transaction:a}),c&&x(c,e);let d={oid:e,snapshot:c,timestamp:n};if(d.snapshot?await this.baselines.set(d,{transaction:a}):await this.baselines.delete(e,{transaction:a}),this.log("successfully rebased",e,"up to",n,":",c,"and deleted",l,"operations"),u.length){let p=u.filter(K);p.length&&this.emit("filesDeleted",p)}return d};this.reset=async()=>{await this.operations.reset(),await this.baselines.reset(),await this.localReplica.reset()};this.updateSchema=async(e,n)=>{let r=await this.schema.get();if(r&&n===r.version&&r.version===e.version&&JSON.stringify(r)!==JSON.stringify(e))throw console.error(`Schema mismatch for version ${e.version}
|
|
1
|
+
"use strict";var di=Object.create;var Bt=Object.defineProperty;var ui=Object.getOwnPropertyDescriptor;var pi=Object.getOwnPropertyNames;var hi=Object.getPrototypeOf,mi=Object.prototype.hasOwnProperty;var _e=(i,t)=>()=>(t||i((t={exports:{}}).exports,t),t.exports),fi=(i,t)=>{for(var e in t)Bt(i,e,{get:t[e],enumerable:!0})},yi=(i,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of pi(t))!mi.call(i,r)&&r!==e&&Bt(i,r,{get:()=>t[r],enumerable:!(n=ui(t,r))||n.enumerable});return i};var jt=(i,t,e)=>(e=i!=null?di(hi(i)):{},yi(t||!i||!i.__esModule?Bt(e,"default",{value:i,enumerable:!0}):e,i));var Vt=_e((Fr,pn)=>{pn.exports=function(t,e){var n="000000000"+t;return n.substr(n.length-e)}});var mn=_e((Ar,hn)=>{var gi=Vt(),bi=typeof window=="object"?window:self,vi=Object.keys(bi).length,Si=navigator.mimeTypes?navigator.mimeTypes.length:0,xi=gi((Si+navigator.userAgent.length).toString(36)+vi.toString(36),4);hn.exports=function(){return xi}});var bn=_e((Mr,gn)=>{var Lt,fn=typeof window<"u"&&(window.crypto||window.msCrypto)||typeof self<"u"&&self.crypto;fn?(yn=Math.pow(2,32)-1,Lt=function(){return Math.abs(fn.getRandomValues(new Uint32Array(1))[0]/yn)}):Lt=Math.random;var yn;gn.exports=Lt});var Ae=_e((Br,On)=>{var ke=mn(),vn=Vt(),Oi=bn(),me=0,Ut=4,Fe=36,Sn=Math.pow(Fe,Ut);function Nt(){return vn((Oi()*Sn<<0).toString(Fe),Ut)}function xn(){return me=me<Sn?me:0,me++,me-1}function fe(){var i="c",t=new Date().getTime().toString(Fe),e=vn(xn().toString(Fe),Ut),n=ke(),r=Nt()+Nt();return i+t+e+n+r}fe.slug=function(){var t=new Date().getTime().toString(36),e=xn().toString(36).slice(-4),n=ke().slice(0,1)+ke().slice(-1),r=Nt().slice(-2);return t.slice(-2)+e+n+r};fe.isCuid=function(t){return typeof t!="string"?!1:!!t.startsWith("c")};fe.isSlug=function(t){if(typeof t!="string")return!1;var e=t.length;return e>=7&&e<=10};fe.fingerprint=ke;On.exports=fe});var un={};fi(un,{Client:()=>he,ClientDescriptor:()=>Mt,Entity:()=>K,EntityFile:()=>ne,MigrationPathError:()=>oe,ServerSync:()=>ue,Storage:()=>he,StorageDescriptor:()=>Mt,collection:()=>Qn,createDefaultMigration:()=>rn,migrate:()=>Ye,schema:()=>Hn});var Tn=jt(Ae(),1),Me=4,ge=36;function wn(i){return i.toString(ge).padStart(Me,"0")}function wi(i){return i.toString().padStart(6,"0")}var Be=class{constructor(){this.latest={time:Date.now(),counter:0,node:Ii()};this.zeroCounter=0;this.now=t=>(this.latest=Cn(this.latest),this.get(t,this.latest));this.OLD_now=t=>(this.latest=Cn(this.latest),wi(t)+Di(this.latest));this.timerState=()=>this.latest;this.update=t=>{let e=t.slice(Me);this.latest=Ci(this.latest,Dn(e))};this.get=(t,e)=>wn(t)+In(e);this.zero=t=>wn(t)+In({time:0,counter:this.zeroCounter++,node:this.latest.node});this.getWallClockTime=t=>Dn(t.slice(Me)).time}},je=class extends Error{constructor(...e){super();this.type="ClockDriftError",this.message=["maximum clock drift exceeded"].concat(e).join(" ")}},Ve=class extends Error{constructor(){super();this.type="OverflowError",this.message="timestamp counter overflow"}},Kt=4,zt=7,Le=60*1e3,ye=9;function Ii(){return Tn.default.slug().padStart(zt,"0").slice(0,zt)}function In(i){let t=new Date(i.time).getTime().toString(ge).padStart(ye,"0"),e=i.counter.toString(ge).padStart(Kt,"0"),n=i.node.padStart(zt,"0");return`${t}${e}${n}`}function Cn(i){let t=Date.now(),e=Math.max(i.time,t),n=i.time===e?i.counter+1:0;if(e-t>Le)throw new je(e,t,Le);if(n>65535)throw new Ve;return{time:e,counter:n,node:i.node}}function Ci(i,t){let e=Date.now(),n=Math.max(e,Math.max(i.time,t.time)),r=Math.max(i.counter,t.counter),s;if(i.time===n&&t.time===n?s=r+1:i.time===n?s=i.counter+1:t.time===n?s=t.counter+1:s=0,n-e>Le)throw new je(n,e,Le);if(s>65535)throw new Ve;return{time:n,counter:s,node:i.node}}function Dn(i){let t=i.slice(0,ye),e=i.slice(ye,ye+Kt),n=i.slice(ye+Kt),r=parseInt(t,ge),s=parseInt(e,ge);if(isNaN(r)||isNaN(s))throw new Error("invalid clock format");return{time:r,counter:s,node:n}}function Di(i){let t=new Date(i.time).toISOString(),e=i.counter.toString(16).toUpperCase().padStart(4,"0"),n=i.node.padStart(16,"0");return`${t}-${e}-${n}`}function Pn(i){return parseInt(i.slice(0,Me),36)}function En(i,t){return Pn(i)-Pn(t)}function V(i){return i&&i["@@type"]==="file"}function Rn(i){return{"@@type":"file",id:i}}var Ne,Pi=new Uint8Array(16);function $t(){if(!Ne&&(Ne=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!Ne))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Ne(Pi)}var _n=/^(?:[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 Ti(i){return typeof i=="string"&&_n.test(i)}var kn=Ti;var P=[];for(Ue=0;Ue<256;++Ue)P.push((Ue+256).toString(16).substr(1));var Ue;function Ei(i){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=(P[i[t+0]]+P[i[t+1]]+P[i[t+2]]+P[i[t+3]]+"-"+P[i[t+4]]+P[i[t+5]]+"-"+P[i[t+6]]+P[i[t+7]]+"-"+P[i[t+8]]+P[i[t+9]]+"-"+P[i[t+10]]+P[i[t+11]]+P[i[t+12]]+P[i[t+13]]+P[i[t+14]]+P[i[t+15]]).toLowerCase();if(!kn(e))throw TypeError("Stringified UUID is invalid");return e}var Fn=Ei;function Ri(i,t,e){i=i||{};var n=i.random||(i.rng||$t)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){e=e||0;for(var r=0;r<16;++r)t[e+r]=n[r];return t}return Fn(n)}var be=Ri;function R(i){return E(i)||V(i)}function An(i,t){return i===t?!0:!(!R(i)||!R(t)||i["@@type"]!==t["@@type"]||i.id!==t.id)}function _i(i,t){return typeof t!="object"||t===null||Array.isArray(t)?t:Object.fromEntries(Object.entries(t).sort(([e],[n])=>e<n?-1:e>n?1:0))}function Ke(i){return JSON.stringify(i,_i)}function _(i,t=!0){if(S(i)||Array.isArray(i)){let e=F(i),n;if(Array.isArray(i))n=i.map(r=>_(r,t));else{n={};for(let[r,s]of Object.entries(i))n[r]=_(s,t)}return t&&e&&x(n,e),n}return i}function ve(i){return Ke(i)}function S(i){return i&&typeof i=="object"}function Mn(i){for(var t=[],e=[i],n=0;e.length;){var r=e.pop();if(typeof r=="boolean")n+=4;else if(typeof r=="string")n+=r.length*2;else if(typeof r=="number")n+=8;else if(typeof r=="object"&&t.indexOf(r)===-1){t.push(r);for(var s in r)e.push(r[s])}}return n}function y(i,t="assertion failed"){if(!i)throw new Error(t)}function ze(i=16){return be().replace("-","").slice(0,i)}function Bn(i,t){for(let e=i.length-1;e>=0;e--)if(t(i[e]))return e;return-1}function jn(i,t){let e;return function(...n){let r=this;clearTimeout(e),e=setTimeout(()=>i.apply(r,n),t)}}var J="__@@oid_do_not_use",Q="@@id",ki="/",Qe=":",Qt=new WeakMap;function L(i){let t=F(i);return y(!!t,`Object ${JSON.stringify(i)} does not have an OID assigned to it`),t}function F(i){if(S(i))return Qt.get(i)??i[Q]??i[J]}function x(i,t){return y(S(i),`Only objects can be assigned OIDs, received ${JSON.stringify(i)}`),xe(i)&&He(i),Qt.set(i,t),i}function xe(i){return!!F(i)}function He(i){return Qt.delete(i),i}function Ht(i){return i===Q||i===J}function Wt(i,t,e){if(xe(i))return L(i);{let n=z(t,e);return x(i,n),n}}function Vn(i,t,e){if(xe(i)){let n=L(i);if(We(n,t))return L(i);{let r=z(t,e);return x(i,r),r}}else{let n=z(t,e);return x(i,n),n}}var qt={".":"˙","/":"&slash;",":":":"};function Ln(i){return i.replace(/[/]/g,qt["/"]).replace(/[:]/g,qt[":"]).replace(/[.]/g,qt["."])}function Nn(i){return i.replace(/&slash;/g,"/").replace(/:/g,":").replace(/˙/g,".")}function T(i,t,e){let n=Ln(i)+ki+Ln(t);return e&&(n+=Qe+e),n}function z(i,t=Vi){let{collection:e,id:n}=M(i);return T(e,n,t())}function M(i){let[t,e]=i.split(Qe),[n,r]=t.split("/"),s;return r.includes(".")?s=r.slice(0,r.indexOf(".")):s=r,{collection:Nn(n),id:Nn(s),subId:e}}function re(i,t){let e=L(i);if(Array.isArray(i)){let n;for(let r=0;r<i.length;r++)n=i[r],S(n)&&!R(n)&&(Vn(n,e,t),re(n,t))}else if(S(i)&&!R(i))for(let n of Object.keys(i))S(i[n])&&!R(i[n])&&(Vn(i[n],e,t),re(i[n],t))}function Fi(i,t){return y(S(i),`Only objects can be assigned OIDs, received ${JSON.stringify(i)}`),i[Q]=t,i}function Ai(i){if(S(i))return i[Q]||i[J]}function Mi(i){return S(i)&&(delete i[J],delete i[Q]),i}function Bi(i){let t=F(i);t&&Fi(i,t)}function se(i){if(Bi(i),Array.isArray(i))for(let t=0;t<i.length;t++)se(i[t]);else if(S(i))for(let t of Object.keys(i))se(i[t])}function ji(i){let t=Ai(i);t&&x(i,t)}function Se(i){if(ji(i),Mi(i),Array.isArray(i))for(let t=0;t<i.length;t++)Se(i[t]);else if(S(i))for(let t of Object.keys(i))Se(i[t])}function $e(i){if(He(i),Array.isArray(i))for(let t=0;t<i.length;t++)$e(i[t]);else if(S(i))for(let t of Object.keys(i))$e(i[t])}function Vi(){return be().slice(0,8)}function $(i){return{"@@type":"ref",id:i}}function qe(i,t=new Map){if(Array.isArray(i)){let e=L(i),n=x([],e);for(let r=0;r<i.length;r++){let s=i[r];if(S(s)){if(E(s))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(V(s)){n[r]=s;continue}else{let a=L(s);n[r]=$(a),qe(s,t)}}else n[r]=s}t.set(e,n)}else if(S(i)&&!R(i)){let e=L(i),n=x({},e);for(let r of Object.keys(i)){let s=i[r];if(S(s)){if(E(s))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(V(s))n[r]=s;else{let a=L(s);n[r]=$(a),qe(s,t)}}else n[r]=s}t.set(e,n)}else R(i);return t}function w(i){return i.split(".")[0].split(Qe)[0]}function Jt(i){let t=w(i);return[t,`${t}${Qe}\uFFFF`]}function We(i,t){return w(i)===w(t)}function E(i){return i&&typeof i=="object"&&i["@@type"]==="ref"}function Gt(i){return S(i)&&!R(i)}function Li(i,t){return i===t?!0:R(i)&&R(t)?An(i,t):!1}function Oe(i,t,e,n,r=[],s={}){let a=L(i);function o(c,l,u){if(!Gt(l))Li(l,u)||r.push({oid:a,timestamp:e(),data:{op:"set",name:c,value:l}});else{let d=F(u),p=F(l);p&&!We(a,p)?(l=_(l,!1),p=z(a,n),x(l,p)):s.mergeUnknownObjects?!p&&d?(x(l,d),p=d):p=Wt(l,a,n):p=Wt(l,a,n),y(!!p,"Error: no value OID was resolved during diff. This is a bug in Verdant."),y(We(a,p),`Error: value OID ${p} is not related to parent OID ${a}. This is a bug in Verdant.`),u===void 0||p!==d?(H(l,p,e,n,r),r.push({oid:a,timestamp:e(),data:{op:"set",name:c,value:$(p)}}),d!==void 0&&r.push({oid:d,timestamp:e(),data:{op:"delete"}})):Oe(u,l,e,n,r,s)}}if(Array.isArray(i)&&Array.isArray(t)){for(let l=0;l<t.length;l++){let u=t[l],d=i[l];o(l,u,d)}let c=i.length-t.length;if(c>0){for(let l=t.length;l<i.length;l++){let u=i[l],d=F(u);d&&r.push({oid:d,timestamp:e(),data:{op:"delete"}})}r.push({oid:a,timestamp:e(),data:{op:"list-delete",index:t.length,count:c}})}}else{if(Array.isArray(i)||Array.isArray(t))throw new Error("Cannot diff an array with an object");if(Gt(i)&&Gt(t)){let c=new Set(Object.keys(i));for(let[l,u]of Object.entries(t)){if(u===void 0&&s.defaultUndefined||(c.delete(l),Ht(l)))continue;let d=i[l];o(l,u,d)}if(!s.defaultUndefined)for(let l of c)Ht(l)||r.push({oid:a,timestamp:e(),data:{op:"remove",name:l}})}}return r}function H(i,t,e,n,r=[]){x(i,t),re(i,n);let s=qe(i);for(let a of s.keys()){let o=s.get(a);r.push({oid:a,timestamp:e(),data:{op:"initialize",value:He(o)}})}return r}function Kn(i){let t={};for(let e of i)e.oid in t?t[e.oid].push(e):t[e.oid]=[e];return t}function Xt(i){let t={};for(let e of i){let n=w(e.oid);n in t?t[n].push(e):t[n]=[e]}return t}function Yt(i){let t={};for(let e of i){let n=w(e.oid);n in t?t[n].push(e):t[n]=[e]}return t}function G(i){return Array.isArray(i)?!0:(console.error(`Cannot apply list patch; expected array, received ${JSON.stringify(i)}. This suggests your data is changing from a list to an object over time. (OID: ${F(i)})`),!1)}function X(i,t,e){if(i==null&&t.op!=="initialize")return i;let n=i,r,s;function a(o){e&&R(o)&&e.push(o)}switch(t.op){case"set":a(n[t.name]),n[t.name]=t.value;break;case"remove":a(n[t.name]),delete n[t.name];break;case"list-push":G(i)&&i.push(t.value);break;case"list-delete":G(i)&&(a(i[t.index]),i.splice(t.index,t.count));break;case"list-move-by-index":G(i)&&(s=i.splice(t.from,1),i.splice(t.to,0,s[0]));break;case"list-remove":if(G(i))do{let o=t.value;t.only==="last"?E(o)?r=Bn(i,c=>c.id===o.id):r=i.lastIndexOf(o):E(o)?r=i.findIndex(c=>c.id===o.id):r=i.indexOf(o),r!==-1&&(a(i[r]),i.splice(r,1))}while(!t.only&&r!==-1);break;case"list-add":G(i)&&(i.some(c=>E(c)&&E(t.value)?c.id===t.value.id:c===t.value)||i.push(t.value));break;case"list-move-by-ref":G(i)&&(r=i.indexOf(t.value),s=i.splice(r,1),i.splice(t.index,0,s[0]));break;case"list-insert":if(G(i)){if(!t.value&&!t.values)throw new Error(`Cannot apply list insert patch; expected value or values, received ${JSON.stringify(t)}`);t.value?i.splice(t.index,0,t.value):i.splice(t.index,0,...t.values)}break;case"delete":Array.isArray(i)?i.forEach(a):S(i)&&Object.values(i||{}).forEach(a);return;case"initialize":return _(t.value);default:throw new Error(`Unsupported patch operation: ${t.op}`)}return i}function Je(i,t,e=[]){if(Array.isArray(i))for(let n=0;n<i.length;n++){let r=i[n];i[n]=Un(r,t,e),S(i[n])&&Je(i[n],t,e)}else if(!V(i)){if(S(i)){y(F(i),`Object ${JSON.stringify(i)} must have an oid`);for(let n of Object.keys(i))i[n]=Un(i[n],t,e),S(i[n])&&Je(i[n],t,e)}}return e}function Un(i,t,e){if(E(i)){e.push(i.id);let n=t.get(i.id);return y(!!n,`No value was found in object map for ${i.id}`),x(n,i.id)}else return i}function Zt(i){return i.equals!==void 0}function en(i){return i.gte!==void 0||i.lte!==void 0||i.gt!==void 0||i.lt!==void 0}function Ni(i){return!!i.match}function tn(i){return i.startsWith!==void 0}function zn(i){return!en(i)&&!Zt(i)&&!Ni(i)&&!tn(i)&&i.order}function Ui(i){return i.type==="any"?!0:i.type==="map"?!1:i.nullable}function Z(i,t){for(let[e,n]of Object.entries(i.fields)){let r=$n(n);(r!==void 0&&t[e]===void 0||!Ui(n)&&t[e]===null)&&(t[e]=r),t[e]&&Y(t[e],n)}return t}function Y(i,t){if(i==null)return i;if(t.type==="object")for(let[e,n]of Object.entries(t.properties)){if(i[e]===void 0){let r=$n(n);r!==void 0&&(i[e]=r)}Y(i[e],n)}else if(t.type==="array")for(let e of i)Y(e,t.items);else if(t.type==="map")for(let[e,n]of Object.entries(i))e===Q||e===J||Y(n,t.values)}function $n(i){if(i.type==="string"||i.type==="number"||i.type==="boolean"||i.type==="any"){if(i.default&&typeof i.default=="function")return i.default();if(i.default!==void 0)return JSON.parse(JSON.stringify(i.default))}if(i.type==="array")return[];if(i.type==="map")return{};if(i.type!=="any"&&i.nullable)return null}function qn(i,t){for(let[e,n]of Object.entries(t))e===Q||e===J||(i.fields[e]?nn(n,i.fields[e]):delete t[e]);return t}function nn(i,t){if(S(i)&&t.type==="object")for(let[e,n]of Object.entries(i))t.properties[e]?nn(n,t.properties[e]):delete i[e];else if(Array.isArray(i)&&t.type==="array")for(let e of i)nn(e,t.items)}function Qn(i){return i}function Hn(i){return i}var Ge="\uFFFFFE",Ki="\0",zi="\uFFFFFF";function B(...i){let t=$i(i);return t.length===1?t[0]:t}function ee(...i){return i.join(Ge)+`${zi}`}function te(...i){return i.join(Ge)+`${Ge}${Ki}`}function $i(i){let t=[[]];for(let e of i)if(Array.isArray(e)){let n=[];for(let r of t)for(let s of e)n.push(r.concat(s));t=n}else for(let n of t)n.push(`${e}`);return Array.from(new Set(t.map(e=>e.join(Ge))))}function qi(i,t){let e={};for(let[n,r]of Object.entries(i.synthetics||{}))e[n]=q(r.compute(t));return e}function Qi(i,t){return Object.entries(i.compounds||{}).reduce((e,[n,r])=>(e[n]=B(...r.of.map(s=>t[s])),e),{})}function Xe(i,t){return Object.assign(t,qi(i,t)),Object.assign(t,Qi(i,t)),t}var Hi="null";function q(i){if(i===null)return Hi;if(typeof i=="string"||typeof i=="number")return i;if(typeof i=="boolean"||i===null)return`${i}`;if(i===void 0)return"undefined";if(Array.isArray(i))return i.map(q);throw new Error(`Unsupported index value: ${i}`)}var Wi={version:0,collections:{}};function Ye(i,t,e){let n=typeof t=="function",r=n?Wi:i,s=n?i:t,a=n?t:e,o=Object.keys(s.collections).filter(h=>r.collections[h]&&Ke(r.collections[h])!==Ke(s.collections[h])),c=Object.keys(r.collections).filter(h=>!s.collections[h]),l=Object.keys(s.collections).filter(h=>!r.collections[h]),u=new Set;for(let h of o){let m=r.collections[h].fields,f=s.collections[h].fields;Object.keys(f).some(v=>!m[v]?.default&&f[v]?.default)&&u.add(h),Object.keys(m).some(v=>!f[v])&&u.add(h)}let d={},p={};for(let h of[...o,...l]){let m=Wn(r.collections[h]),f=Wn(s.collections[h]),v=f.filter(O=>!m.find(D=>D.name===O.name)),C=m.filter(O=>!f.find(D=>D.name===O.name));v.length>0&&(d[h]=v,o.includes(h)&&u.add(h)),C.length>0&&(p[h]=C,o.includes(h)&&u.add(h))}let g=(h,m)=>Z(s.collections[h],m),I=h=>m=>{let f=s.collections[h];return Z(f,qn(f,m))};return{version:s.version,migrate:async h=>{let m=[];if(await a({migrate:async(f,v)=>{let C=I(f),O=async D=>{let A=await v(D);return x(A,L(D)),C(A)};await h.migrate(f,O),m.push(f),u.delete(f)},identity:f=>f,withDefaults:g,info:{changedCollections:o,addedCollections:l,removedCollections:c},queries:h.queries,mutations:h.mutations}),s.version>1){h.log("debug","auto-migrating collections with new defaults",u);for(let v of u)await h.migrate(v,I(v)),m.push(v);let f=o.filter(v=>!m.includes(v));f.length>0&&console.error(`Unmigrated changed collections from version ${r.version} to version ${s.version}:`,f)}},removedCollections:c,addedIndexes:d,removedIndexes:p,allCollections:Object.keys(s.collections),changedCollections:o,addedCollections:l,oldCollections:Object.keys(r.collections),oldSchema:r,newSchema:s}}function Wn(i){return i?[...Object.keys(i.fields).filter(e=>i.fields[e].indexed).map(e=>({name:e,multiEntry:i.fields[e].type==="array",synthetic:!1,compound:!1})),...Object.keys(i.synthetics||{}).map(e=>({name:e,multiEntry:["array","string[]","number[]","boolean[]"].includes(i.synthetics[e].type),synthetic:!0,compound:!1})),...Object.keys(i.compounds||{}).map(e=>({name:e,multiEntry:i.compounds[e].of.some(n=>(i.fields[n]||i.synthetics[n]).type==="array"),synthetic:!1,compound:!0}))]:[]}function rn(i,t){return Ye(t?i:{version:0,collections:{}},t||i,async({migrate:n,info:r})=>{if((t||i).version!==1)for(let s of r.changedCollections)await n(s,a=>a)})}var Ze=class{constructor(t,e){this.getNow=t;this.createSubId=e;this.createDiff=(t,e,n={})=>Oe(t,e,this.getNow,this.createSubId,[],n);this.createInitialize=(t,e)=>H(t,e,this.getNow,this.createSubId);this.createSet=(t,e,n)=>{if(!S(n)||R(n))return[{oid:t,timestamp:this.getNow(),data:{op:"set",name:e,value:n}}];{let r=z(t,this.createSubId);return[...H(n,r,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"set",value:$(r),name:e}}]}};this.createRemove=(t,e)=>[{oid:t,timestamp:this.getNow(),data:{op:"remove",name:e}}];this.createListPush=(t,e)=>{if(S(e)){let n=z(t,this.createSubId);return[...H(e,n,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:$(n)}}]}else return[{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:e}}]};this.createListAdd=(t,e)=>S(e)?[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:$(e)}}]:[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:e}}];this.createListInsert=(t,e,n)=>{if(S(n)){let r=z(t,this.createSubId);return[...H(n,r,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:$(r),index:e}}]}else return[{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:n,index:e}}]};this.createListRemove=(t,e,n)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-remove",value:e,only:n}}];this.createListDelete=(t,e,n=1)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-delete",index:e,count:n}}];this.createListMoveByRef=(t,e,n)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-move-by-ref",value:e,index:n}}];this.createListMoveByIndex=(t,e,n)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-move-by-index",from:e,to:n}}];this.createDelete=t=>[{oid:t,timestamp:this.getNow(),data:{op:"delete"}}];this.createDeleteAll=t=>t.map(e=>({oid:e,timestamp:this.getNow(),data:{op:"delete"}}))}};var b=class{constructor(t){this._onAllUnsubscribed=t;this.subscribers={};this.counts={};this._disabled=!1;this.subscriberCount=t=>this.counts[t]??0;this.totalSubscriberCount=()=>Object.values(this.counts).reduce((t,e)=>t+e,0);this.subscribe=(t,e)=>{let n=ze(),r=this.subscribers[t];return r||(r=this.subscribers[t]={}),r[n]=e,this.counts[t]=(this.counts[t]||0)+1,()=>{this.subscribers[t]&&(delete this.subscribers[t][n],this.counts[t]--,this.counts[t]===0&&(delete this.subscribers[t],delete this.counts[t],this._onAllUnsubscribed&&this._onAllUnsubscribed(t)))}};this.emit=(t,...e)=>{this._disabled||this.subscribers[t]&&Object.values(this.subscribers[t]).forEach(n=>n(...e))};this.dispose=()=>{let t=Object.keys(this.subscribers);this.subscribers={},this.counts={},t.forEach(e=>{this._onAllUnsubscribed&&this._onAllUnsubscribed(e)})};this.disable=()=>{this._disabled=!0}}get disabled(){return this._disabled}};function Jn(i,t,e,n){if(t===void 0)return[{oid:i,timestamp:n(),data:{op:"delete"}}];let r=_(t),s=[];for(let a of e){let o=Ji(i,r,a,n);s.unshift(...o),X(r,a.data)}return s}function Ji(i,t,e,n){let r=e.data;switch(r.op){case"set":case"remove":return[{oid:i,timestamp:n(),data:{op:"set",name:r.name,value:t[r.name]}}];case"list-insert":return[{oid:i,timestamp:n(),data:{op:"list-delete",index:r.index,count:1}}];case"list-delete":return[{oid:i,timestamp:n(),data:{op:"list-insert",index:r.index,values:t.slice(r.index,r.count)}}];case"list-move-by-ref":return[{oid:i,timestamp:n(),data:{op:"list-move-by-ref",value:r.value,index:t.indexOf(r.value)}}];case"list-move-by-index":return[{oid:i,timestamp:n(),data:{op:"list-move-by-index",from:r.to,to:r.from}}];case"delete":return[{oid:i,timestamp:n(),data:{op:"initialize",value:t}}];case"list-push":return[{oid:i,timestamp:n(),data:{op:"list-remove",value:r.value,only:"last"}}];case"list-remove":if(r.only==="last"){let s=t.lastIndexOf(r.value);return[{oid:i,timestamp:n(),data:{op:"list-insert",index:s,values:[r.value]}}]}else if(r.only==="first"){let s=t.indexOf(r.value);return[{oid:i,timestamp:n(),data:{op:"list-insert",index:s,values:[r.value]}}]}else{let s=[],a=t.indexOf(r.value);for(;a!==-1;)s.push(a),a=t.indexOf(r.value,a+1);return s.map(o=>({oid:i,timestamp:n(),data:{op:"list-insert",index:o,value:r.value}}))}case"list-add":return[{oid:i,timestamp:n(),data:{op:"list-remove",value:r.value,only:"last"}}];case"initialize":return[{oid:i,timestamp:n(),data:{op:"delete"}}];default:throw new Error(`Cannot undo operation type: ${r.op}`)}}var ae=class{constructor(t){this.flusher=t;this.batches=new Map;this.flush=t=>{let e=this.batches.get(t);if(e)return e.flush()};this.discard=t=>{let e=this.batches.get(t);e&&(e.discard(),this.batches.delete(t))}}add({key:t,userData:e,items:n,max:r,timeout:s}){let a=this.batches.get(t);return a||(a=new sn({max:r||null,startedAt:Date.now(),userData:e,timeout:s||null,flusher:this.flusher,key:t}),this.batches.set(t,a)),a.update({items:n,max:r,timeout:s,userData:e}),a}},sn=class{constructor({max:t,startedAt:e,timeout:n,userData:r,flusher:s,key:a}){this.items=[];this.update=({items:t,max:e,timeout:n,userData:r})=>{this.items.push(...t),e!==void 0&&(this.max=e),n!==void 0&&(this.timeout=n),r&&(this.userData=r);let 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 t=this.items;return this.items=[],this.flusher(t,this.key,this.userData)};this.discard=()=>{this.flushTimeout&&clearTimeout(this.flushTimeout),this.flushTimeout=void 0,this.items=[]};this.max=t,this.startedAt=e,this.timeout=n,this.userData=r,this.flusher=s,this.key=a}};function k(i){return new Promise((t,e)=>{i.onsuccess=()=>{t(i.result)},i.onerror=()=>{e(i.error)}})}function we(i,t){return new Promise((e,n)=>{let r=i.transaction([t],"readonly"),a=r.objectStore(t).openCursor(),o=0,c=0;a.onsuccess=function(l){let u=a.result;u&&(o++,c=c+Mn(u.value),u.continue())},a.onerror=function(l){n(l)},r.oncomplete=function(l){e({count:o,size:c})},r.onabort=function(l){n(l)},r.onerror=function(l){n(l)}})}function Gn(i,t){let e=i.transaction(t,"readonly"),n=t.map(r=>{let s=e.objectStore(r);return k(s.getAll())});return Promise.all(n)}async function Ie(i){i.close(),await new Promise((t,e)=>{t()})}async function et(i,t=window.indexedDB){let e=t.deleteDatabase([i,"meta"].join("_")),n=t.deleteDatabase([i,"collections"].join("_"));await Promise.all([new Promise((r,s)=>{e.onsuccess=r,e.onerror=s}),new Promise((r,s)=>{n.onsuccess=r,n.onerror=s})]),window.location.reload()}var N=class{constructor(t){this.db=t;this.createTransaction=(t,e)=>this.db.transaction(t,e);this.run=async(t,e,n="readonly",r)=>{let a=(r||this.db.transaction(t,n)).objectStore(t),o=e(a);return k(o)};this.runAll=async(t,e,n="readonly",r)=>{let a=(r||this.db.transaction(t,n)).objectStore(t),o=e(a);return Promise.all(o.map(k))};this.iterate=async(t,e,n,r="readonly",s)=>{let o=(s||this.db.transaction(t,r)).objectStore(t),c=e(o);return new Promise((l,u)=>{c.onsuccess=d=>{let p=c.result;p?(n(p.value,o),p.continue()):l()},c.onerror=u})};this.clear=t=>this.run(t,e=>e.clear(),"readwrite")}};var tt=class extends N{constructor(){super(...arguments);this.getAckInfo=async()=>{let e=await this.run("info",n=>n.get("ack"));return e||{globalAckTimestamp:null,type:"ack"}};this.setGlobalAck=async e=>{await this.run("info",n=>n.put({type:"ack",globalAckTimestamp:e}),"readwrite")}}};var nt=class extends N{constructor(e){super(e);this.getAllForDocument=async(e,{mode:n="readonly",transaction:r}={})=>{let s=[];return await this.iterateOverAllForDocument(e,a=>{s.push(a)},{mode:n,transaction:r}),s};this.iterateOverAllForDocument=async(e,n,{mode:r="readonly",transaction:s}={})=>this.iterate("baselines",a=>{let[o,c]=Jt(e);return a.openCursor(IDBKeyRange.bound(o,c,!1,!1))},n,r,s);this.getAllForMultipleDocuments=async(e,{mode:n="readonly"}={})=>(await this.runAll("baselines",s=>e.map(a=>{let[o,c]=Jt(a);return s.getAll(IDBKeyRange.bound(o,c,!1,!1))}),n)).flat();this.getAllSince=async(e,{mode:n="readonly"}={})=>this.run("baselines",r=>{let s=e?IDBKeyRange.lowerBound(e,!0):void 0;return r.index("timestamp").getAll(s)},n);this.get=async(e,{transaction:n,mode:r="readonly"}={})=>this.run("baselines",s=>s.get(e),r,n);this.set=async(e,{transaction:n}={})=>{await this.run("baselines",r=>r.put(e),"readwrite",n)};this.setAll=async(e,{transaction:n}={})=>{await this.runAll("baselines",r=>e.map(s=>r.put(s)),"readwrite",n)};this.reset=()=>this.clear("baselines");this.delete=async(e,{transaction:n})=>{await this.run("baselines",r=>r.delete(e),"readwrite",n)}}};var Xn=jt(Ae(),1);var it=class extends N{constructor(){super(...arguments);this.get=async({transaction:e}={})=>{if(this.cached)return this.cached;let n=await this.run("info",r=>r.get("localReplicaInfo"),void 0,e);if(!n){let s={type:"localReplicaInfo",id:(0,Xn.default)(),ackedLogicalTime:null,lastSyncedLogicalTime:null};return await this.run("info",a=>a.put(s),"readwrite"),this.cached=s,s}return this.cached=n,n};this.update=async(e,{transaction:n}={})=>{let r=await this.get({transaction:n});Object.assign(r,e),await this.run("info",s=>s.put(r),"readwrite"),this.cached=r};this.reset=async()=>{let e=await this.get();e.ackedLogicalTime=null,e.lastSyncedLogicalTime=null,await this.run("info",n=>n.put(e),"readwrite")}}};var rt=class{constructor(t){this.meta=t;this.createOperation=async t=>{let e=await this.meta.localReplica.get();return{type:"op",timestamp:this.meta.now,replicaId:e.id,operations:t.operations.map(n=>({data:n.data,oid:n.oid,timestamp:n.timestamp}))}};this.createMigrationOperation=async({targetVersion:t,...e})=>{let n=await this.meta.localReplica.get();return{type:"op",operations:e.operations.map(r=>({...r,timestamp:this.meta.time.zero(t)})),timestamp:this.meta.time.zero(t),replicaId:n.id}};this.createSyncStep1=async t=>{let e=await this.meta.localReplica.get(),n=t===null?null:e.lastSyncedLogicalTime,r=[],s=new Set;n?await this.meta.operations.iterateOverAllLocalOperations(o=>{r.push({data:o.data,oid:o.oid,timestamp:o.timestamp}),s.add(w(o.oid))},{after:n,mode:"readwrite"}):await this.meta.operations.iterateOverAllOperations(o=>{r.push({data:o.data,oid:o.oid,timestamp:o.timestamp}),s.add(w(o.oid))},{mode:"readwrite"});let a=[];return n||(a=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:a,since:n}};this.createPresenceUpdate=async t=>{let e=await this.meta.localReplica.get();return{type:"presence-update",presence:t,replicaId:e.id}};this.createHeartbeat=async()=>{let t=await this.meta.localReplica.get();return{type:"heartbeat",timestamp:this.meta.now,replicaId:t.id}};this.createAck=async t=>{let e=await this.meta.localReplica.get();return{type:"ack",timestamp:this.meta.now,replicaId:e.id,nonce:t}}}};var st=class extends N{constructor(){super(...arguments);this.iterateOverAllOperationsForDocument=async(e,n,{to:r,from:s,after:a,mode:o="readonly",transaction:c}={})=>{let u=(c||this.db.transaction("operations",o)).objectStore("operations"),d=u.index("d_t"),p=s||a,g=p?B(e,p):te(e),I=r?B(e,r):ee(e),h=IDBKeyRange.bound(g,I,!!a,!1),m=d.openCursor(h,"next");return new Promise((f,v)=>{let C;m.onsuccess=O=>{let D=m.result;if(D){let A=D.value;y(A.oid.startsWith(e)),y(C===void 0||C<=A.timestamp,`expected ${C} <= ${A.timestamp}`),n(A,u),C=A.timestamp,D.continue()}else f()},m.onerror=O=>{v(O)}})};this.iterateOverAllOperationsForEntity=async(e,n,{after:r,to:s,mode:a,transaction:o})=>{let l=(o||this.db.transaction("operations",a)).objectStore("operations"),u=r?B(e,r):te(e),d=s?B(e,s):ee(e),p=IDBKeyRange.bound(u,d,!!r,!1),g=l.openCursor(p,"next");return new Promise((I,h)=>{let m;g.onsuccess=f=>{let v=g.result;if(v){let C=v.value;y(C.oid.startsWith(e)),y(m===void 0||m<=C.timestamp,`expected ${m} <= ${C.timestamp}`),n(C,l),m=C.timestamp,v.continue()}else I()},g.onerror=f=>{h(f)}})};this.iterateOverAllLocalOperations=async(e,{before:n,after:r,mode:s="readonly",transaction:a})=>{let c=(a||this.db.transaction("operations",s)).objectStore("operations"),l=c.index("l_t"),u=r?B(!0,r):te(!0),d=n?B(!0,n):ee(!0),p=IDBKeyRange.bound(u,d,!!r,!0),g=l.openCursor(p,"next");return new Promise((I,h)=>{let m;g.onsuccess=f=>{let v=g.result;if(v){let C=v.value;y(m===void 0||m<=C.timestamp,`expected ${m} <= ${C.timestamp}`),e(C,c),m=C.timestamp,v.continue()}else I()},g.onerror=f=>{h(f)}})};this.iterateOverAllOperations=async(e,{before:n,transaction:r,mode:s,from:a})=>{await this.iterate("operations",o=>{let c=a?te(a):void 0,l=n?ee(n):void 0,u=c&&l?IDBKeyRange.bound(c,l,!1,!0):c?IDBKeyRange.lowerBound(c,!1):l?IDBKeyRange.upperBound(l,!0):void 0;return o.index("timestamp").openCursor(u,"next")},e,s,r)};this.addOperations=async(e,{transaction:n}={})=>this.insert(e.map(this.addCompoundIndexes),{transaction:n});this.addCompoundIndexes=e=>({...e,oid_timestamp:B(e.oid,e.timestamp),l_t:B(e.isLocal,e.timestamp),d_t:B(w(e.oid),e.timestamp)});this.insert=async(e,{transaction:n})=>{let r=new Set;return await this.runAll("operations",s=>e.map(a=>(r.add(w(a.oid)),s.put(a))),"readwrite",n),Array.from(r)};this.reset=()=>this.clear("operations")}};var at=class{constructor(t,e){this.db=t;this.currentVersion=e;this.cached=null;this.get=async()=>{if(this.cached)return this.cached;let r=this.db.transaction("info","readonly").objectStore("info").get("schema"),s=await k(r);return s?(this.cached=JSON.parse(s.schema),this.cached):null};this.set=async t=>{let s=this.db.transaction("info","readwrite").objectStore("info").put({type:"schema",schema:JSON.stringify(t)});this.cached=t,await k(s)}}};var ot=class extends b{constructor({disableRebasing:e,context:n}){super();this.time=new Be;this.disableRebasing=!1;this._closing=!1;this.setContext=e=>{this.context=e};this.close=()=>{this._closing=!0};this.createTransaction=e=>this.db.transaction(e,"readwrite");this.getAllDocumentRelatedOids=async e=>{let n=new Set,r=w(e);y(r===e,"Must be root document OID"),n.add(r);let s=this.db.transaction(["baselines","operations"],"readwrite");return await Promise.all([this.baselines.iterateOverAllForDocument(r,a=>{n.add(a.oid)},{transaction:s}),this.operations.iterateOverAllOperationsForDocument(r,a=>{n.add(a.oid)},{transaction:s})]),Array.from(n)};this.getDocumentSnapshot=async e=>{let n=w(e);y(n===e,"Must be root document OID");let r=this.db.transaction(["baselines","operations"],"readwrite"),s=await this.baselines.getAllForDocument(n,{transaction:r}),a=new Map;for(let c of s)c.snapshot&&x(c.snapshot,c.oid),a.set(c.oid,c.snapshot);await this.operations.iterateOverAllOperationsForDocument(n,c=>{let l=a.get(c.oid)||void 0,u=X(l,c.data);u&&x(u,c.oid),a.set(c.oid,u)},{transaction:r});let o=a.get(n);return o&&Je(o,a),o};this.ack=async e=>{let n=await this.localReplica.get();e>this.now||(this.emit("message",{type:"ack",replicaId:n.id,timestamp:e}),!this._closing&&(!n.ackedLogicalTime||e>n.ackedLogicalTime)&&this.localReplica.update({ackedLogicalTime:e}))};this.insertLocalOperation=async e=>{if(e.length===0)return;this.log(`Inserting ${e.length} local operations`);for(let r of e)r.isLocal=!0;await this.operations.addOperations(e);let n=await this.messageCreator.createOperation({operations:e});this.emit("message",n),this.tryAutonomousRebase()};this.insertRemoteOperations=async e=>{if(e.length===0)return[];this.log(`Inserting ${e.length} remote operations`);let n=await this.operations.addOperations(e.map(r=>({...r,isLocal:!1})));return this.ack(e[e.length-1].timestamp),n};this.insertRemoteBaselines=async e=>{if(e.length===0)return[];this.log(`Inserting ${e.length} remote baselines`),await this.baselines.setAll(e);let n=new Set;return e.forEach(r=>{n.add(w(r.oid))}),Array.from(n)};this.updateLastSynced=async e=>{if(!this._closing)return this.localReplica.update({lastSyncedLogicalTime:e})};this.lastSyncedTimestamp=async()=>(await this.localReplica.get()).lastSyncedLogicalTime;this.tryAutonomousRebase=async()=>{this.disableRebasing||(await this.localReplica.get()).lastSyncedLogicalTime||await this.runRebase(this.now)};this.runRebase=async e=>{if(this._closing)return;let n,r=new Set,s=this.db.transaction(["baselines","operations"],"readwrite"),a=0;if(await this.operations.iterateOverAllOperations(c=>{r.add(c.oid),n=c.timestamp,a++},{before:e,transaction:s}),!r.size){this.log("Cannot rebase, no operations prior to",e);return}if(this._closing)return;let o=[];for(let c of r)o.push(await this.rebase(c,n||e,s));this.emit("rebase",o)};this.rebase=async(e,n,r)=>{let s=(await this.localReplica.get()).id;this.log("[",s,"]","Rebasing",e,"up to",n);let a=r||this.db.transaction(["operations","baselines"],"readwrite"),o=await this.baselines.get(e,{transaction:a}),c=o?.snapshot||void 0,l=0,u=[];await this.operations.iterateOverAllOperationsForEntity(e,(p,g)=>{(!o||p.timestamp>o.timestamp)&&(c=X(c,p.data,u)),l++,g.delete(p.oid_timestamp)},{to:n,transaction:a}),c&&x(c,e);let d={oid:e,snapshot:c,timestamp:n};if(d.snapshot?await this.baselines.set(d,{transaction:a}):await this.baselines.delete(e,{transaction:a}),this.log("successfully rebased",e,"up to",n,":",c,"and deleted",l,"operations"),u.length){let p=u.filter(V);p.length&&this.emit("filesDeleted",p)}return d};this.reset=async()=>{await this.operations.reset(),await this.baselines.reset(),await this.localReplica.reset()};this.updateSchema=async(e,n)=>{let r=await this.schema.get();if(r&&n===r.version&&r.version===e.version&&JSON.stringify(r)!==JSON.stringify(e))throw console.error(`Schema mismatch for version ${e.version}
|
|
2
2
|
${JSON.stringify(r)}
|
|
3
|
-
${JSON.stringify(e)}`),new Error("Schema has changed without a version change! Any changes to your schema must be accompanied by a change in schema version and a migration routine.");await this.schema.set(e)};this.setGlobalAck=async e=>{this._closing||(await this.ackInfo.setGlobalAck(e),this.disableRebasing||await this.runRebase(e))};this.export=async()=>{let e=this.db,[n,r]=await Gn(e,["baselines","operations"]),s=await this.localReplica.get(),a=await this.schema.get();if(!a)throw new Error("Cannot export Client data before initializing");return{operations:r,baselines:n,localReplica:s,schema:a}};this.resetFrom=async e=>{let r=this.db.transaction(["baselines","operations","info"],"readwrite");await
|
|
3
|
+
${JSON.stringify(e)}`),new Error("Schema has changed without a version change! Any changes to your schema must be accompanied by a change in schema version and a migration routine.");await this.schema.set(e)};this.setGlobalAck=async e=>{this._closing||(await this.ackInfo.setGlobalAck(e),this.disableRebasing||await this.runRebase(e))};this.export=async()=>{let e=this.db,[n,r]=await Gn(e,["baselines","operations"]),s=await this.localReplica.get(),a=await this.schema.get();if(!a)throw new Error("Cannot export Client data before initializing");return{operations:r,baselines:n,localReplica:s,schema:a}};this.resetFrom=async e=>{let r=this.db.transaction(["baselines","operations","info"],"readwrite");await k(r.objectStore("baselines").clear()),await k(r.objectStore("operations").clear()),await k(r.objectStore("info").clear()),await this.localReplica.update({ackedLogicalTime:e.localReplica.ackedLogicalTime,lastSyncedLogicalTime:e.localReplica.lastSyncedLogicalTime},{transaction:r})};this.stats=async()=>{let e=this.db,n=await we(e,"operations"),r=await we(e,"baselines");return{operationsSize:n,baselinesSize:r}};this.context=n,this.schema=new at(n.metaDb,n.schema.version),this.operations=new st(this.db),this.baselines=new nt(this.db),this.localReplica=new it(this.db),this.ackInfo=new tt(this.db),this.messageCreator=new rt(this),this.patchCreator=new Ze(()=>this.now),e&&(this.disableRebasing=e)}get db(){return this.context.metaDb}get log(){return this.context.log}get now(){return this.time.now(this.schema.currentVersion)}};var Gi=[Xi,Yi,Zi,er];function Yn(i,{indexedDB:t=window.indexedDB,databaseName:e,log:n}){return new Promise((r,s)=>{let a=t.open(e,4),o=!1;a.onupgradeneeded=async c=>{let l=a.result,u=a.transaction,d=Gi.slice(c.oldVersion);for(let p of d)await p(l,u);c.oldVersion||(o=!0)},a.onerror=()=>{console.error("Error opening database",a.error),s(a.error)},a.onsuccess=()=>{r({db:a.result,wasInitialized:o})}})}async function Xi(i,t){let e=i.createObjectStore("baselines",{keyPath:"oid"}),n=i.createObjectStore("operations",{keyPath:"oid_timestamp"}),r=i.createObjectStore("info",{keyPath:"type"});e.createIndex("timestamp","timestamp"),n.createIndex("isLocal_timestamp","isLocal_timestamp"),n.createIndex("documentOid_timestamp","documentOid_timestamp")}async function Yi(i,t){let e=t.objectStore("operations");await new Promise((n,r)=>{let s=e.openCursor();s.onsuccess=()=>{let a=s.result;if(a){let{isLocal_timestamp:o,documentOid_timestamp:c,...l}=a.value;a.update({...l,l_t:o,d_t:c}),a.continue()}else n()},s.onerror=a=>{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 Zi(i,t){t.objectStore("operations").createIndex("timestamp","timestamp")}async function er(i,t){let e=i.createObjectStore("files",{keyPath:"id"});e.createIndex("remote","remote"),e.createIndex("deletedAt","deletedAt")}var tr=i=>IDBKeyRange.only(q(i.equals)),nr=i=>{},ir=i=>{let t=i.gte||i.gt,e=i.lte||i.lt;return t===e?IDBKeyRange.only(q(t)):t?e?IDBKeyRange.bound(q(t),q(e),!!i.gt,!!i.lt):IDBKeyRange.lowerBound(q(t),!!i.gt):IDBKeyRange.upperBound(q(e),!!i.lt)},rr=(i,t,e)=>{let n=i.collections[t].compounds[e.where];y(n,`Index ${e.where} does not exist on collection ${t}`);let r=Object.keys(e.match).sort((c,l)=>n.of.indexOf(c)-n.of.indexOf(l));for(let c of r)if(n.of.indexOf(c)!==r.indexOf(c))throw new Error(`Compound index ${e.where} does not have ${c} at the start of its order`);let s=r.map(c=>e.match[c]);if(r.length===n.of.length)return IDBKeyRange.only(B(...s));let a=te(...s),o=ee(...s);return IDBKeyRange.bound(a,o)};function sr(i){let t=i.startsWith,e=i.startsWith+"\uFFFF";return IDBKeyRange.bound(t,e)}function ct(i,t,e){if(e)return en(e)?ir(e):Zt(e)?tr(e):zn(e)?nr(e):tn(e)?sr(e):rr(i,t,e)}function an(i,t,e){return i.transaction(t,e?"readwrite":"readonly").objectStore(t)}async function lt({collection:i,index:t,context:e}){let n=an(e.documentDb,i),r=t?n.index(t.where):n,s=ct(e.schema,i,t),a=t?.order==="desc"?"prev":"next",o=r.openCursor(s,a);return await new Promise((l,u)=>{o.onsuccess=()=>{let d=o.result;l(d?T(i,d.primaryKey.toString()):null)},o.onerror=()=>{o.error?.name==="InvalidStateError"?(e.log("error","findOne query failed with InvalidStateError",o.error),l(null)):u(o.error)}})}async function dt({collection:i,index:t,context:e}){let n=an(e.documentDb,i),r=t?n.index(t.where):n,s=ct(e.schema,i,t),a=t?.order==="desc"?"prev":"next",o=r.openCursor(s,a);return await new Promise((l,u)=>{let d=new Set;o.onsuccess=()=>{let p=o.result;p?(d.add(T(i,p.primaryKey.toString())),p.continue()):l(Array.from(d))},o.onerror=()=>{o.error?.name==="InvalidStateError"?(e.log("error","findAll query failed with InvalidStateError",o.error),l([])):u(o.error)}})}async function Ce({collection:i,index:t,context:e,limit:n,offset:r}){let s=an(e.documentDb,i),a=t?s.index(t.where):s,o=ct(e.schema,i,t),c=t?.order==="desc"?"prev":"next",l=a.openCursor(o,c),u=!r,d=!1,p=0;return{result:await new Promise((I,h)=>{let m=new Set;l.onsuccess=()=>{p++;let f=l.result;f?r&&!u?(f.advance(r),u=!0):(n&&m.size<n&&m.add(T(i,f.primaryKey.toString())),n&&p>n?(d=!0,I(Array.from(m))):f.continue()):I(Array.from(m))},l.onerror=()=>{l.error?.name==="InvalidStateError"?(e.log("error","find query failed with InvalidStateError",l.error),I([])):h(l.error)}}),hasNextPage:d}}async function Zn(i,t,e,n){function r(o,c){let l,u,d=i.open([t,"collections"].join("_"),e);d.onupgradeneeded=async p=>{l=p.oldVersion;let g=d.transaction;u=d.result,g.abort()},d.onsuccess=p=>{o([d.result.version,d.result])},d.onblocked=p=>{n?.("Database blocked, waiting...")},d.onerror=p=>{o([l,u])}}let[s,a]=await new Promise(r);return await ut(a),s}async function ut(i){i.close(),await new Promise(t=>t())}async function ei(i,t,e,n,r){function s(a,o){let c=i.open([t,"collections"].join("_"),e),l=!1;c.onupgradeneeded=u=>{let d=c.transaction;n(d,c.result,u),l=!0},c.onsuccess=u=>{c.result.close(),l?a():o(new Error("Database was not upgraded when a version change was expected"))},c.onerror=u=>{o(c.error||new Error("Unknown error"))},c.onblocked=u=>{r?.("Database upgrade blocked, waiting...")}}return new Promise(s)}async function ti(i,t){typeof navigator<"u"&&navigator.locks?await navigator.locks.request(`verdant_migration_${i}`,t):await t()}async function De(i,t,e){let n=await new Promise((r,s)=>{let a=i.open([t,"collections"].join("_"),e);a.onupgradeneeded=async o=>{a.transaction.abort(),s(new Error("Migration error: database version changed while migrating"))},a.onsuccess=o=>{r(a.result)},a.onblocked=o=>{s(new Error("Migration error: database blocked"))},a.onerror=o=>{s(new Error("Migration error: database error"))}});return n.addEventListener("versionchange",r=>{n.close()}),n}var oe=class extends Error{constructor(e){super(e);this.message=e;this.name="MigrationPathError"}};function ni({currentVersion:i,targetVersion:t,migrations:e}){let n=ii({currentVersion:i,targetVersion:t,migrations:e});if(!n)throw new oe(`No migration path found from ${i} to ${t}! This is a bug. If you're seeing this, contact the developer and provide them with the full contents of this message.`);return n}function ii({currentVersion:i,targetVersion:t,migrations:e}){if(i===t)return[];let n=e.filter(r=>r.oldSchema.version===i).sort((r,s)=>s.newSchema.version-r.newSchema.version);for(;n.length>0;){let r=n.shift();if(r.newSchema.version>t)return null;if(r.newSchema.version===t)return[r];let s=ii({currentVersion:r.newSchema.version,targetVersion:t,migrations:e});if(s)return[r,...s]}return null}var ar=typeof window<"u"?window.indexedDB:void 0;async function Pe({version:i,indexedDB:t=ar,migrations:e,meta:n,context:r}){let s=await Zn(t,r.namespace,i,r.log);r.log("Current database version:",s,"target version:",i);let a=ni({currentVersion:s,targetVersion:i,migrations:e});return a.length>0?(await ti(r.namespace,async()=>{for(let o of a){let c;if(o.oldSchema.version===0)c=lr({meta:n,migration:o,context:r}),await o.migrate(c);else{let d=await De(t,r.namespace,o.oldSchema.version);c=cr({meta:n,migration:o,context:{...r,documentDb:d}}),await o.migrate(c),await Promise.all(c.awaitables),await ut(d)}await ei(t,r.namespace,o.newSchema.version,(d,p)=>{for(let g of o.addedCollections)p.createObjectStore(g,{keyPath:o.newSchema.collections[g].primaryKey,autoIncrement:!1});for(let g of o.allCollections){let I=d.objectStore(g);for(let h of o.addedIndexes[g]||[])I.createIndex(h.name,h.name,{multiEntry:h.multiEntry});for(let h of o.removedIndexes[g]||[])I.deleteIndex(h.name)}for(let g of o.removedCollections)d.objectStore(g).clear()},r.log);let l=await hr({meta:n,currentVersion:o.oldSchema.version,newVersion:o.newSchema.version}),u=await De(t,r.namespace,o.newSchema.version);for(let d of o.allCollections){let g=u.transaction(d,"readwrite").objectStore(d),h=(await dr(g)).map(O=>T(d,`${O}`));h.push(...c.newOids.filter(O=>M(O).collection===d),...l.filter(O=>M(O).collection===d));let f=(await Promise.all(h.map(async O=>{try{let D=await n.getDocumentSnapshot(O);return[O,D]}catch(D){return r.log("error","Could not regenerate snapshot during migration for oid",O,"this document will not be preserved",D),null}}))).filter(O=>!!O).map(([O,D])=>{if(!D)return[O,void 0];let A=Xe(o.newSchema.collections[d],D);return se(A),[O,A]}),C=u.transaction(d,"readwrite").objectStore(d);await Promise.all(f.map(([O,D])=>{if(D)return pr(C,D);{let{id:A}=M(O);return ur(C,A)}}))}await ut(u),r.log(`
|
|
4
4
|
\u2B06\uFE0F v${o.newSchema.version} Migration complete. Here's the rundown:
|
|
5
5
|
- Added collections: ${o.addedCollections.join(", ")}
|
|
6
6
|
- Removed collections: ${o.removedCollections.join(", ")}
|
|
7
7
|
- Changed collections: ${o.changedCollections.join(", ")}
|
|
8
8
|
- New indexes: ${Object.keys(o.addedIndexes).map(d=>o.addedIndexes[d].map(p=>`${d}.${p.name}`)).flatMap(d=>d).join(", ")}
|
|
9
9
|
- Removed indexes: ${Object.keys(o.removedIndexes).map(d=>o.removedIndexes[d].map(p=>`${d}.${p.name}`)).flatMap(d=>d).join(", ")}
|
|
10
|
-
`)}}),De(t,r.namespace,i)):De(t,r.namespace,i)}function ri({migration:i,meta:t,getMigrationNow:e,newOids:n}){return i.allCollections.reduce((r,s)=>(r[s]={put:async a=>{Z(i.newSchema.collections[s],a);let o=a[i.newSchema.collections[s].primaryKey],c=T(s,o);return n.push(c),await t.insertLocalOperation(Q(a,c,e)),a},delete:a=>{let o=T(s,a);return t.insertLocalOperation([{oid:o,timestamp:e(),data:{op:"delete"}}])}},r),{})}function or({migration:i,context:t,meta:e}){return i.oldCollections.reduce((n,r)=>(n[r]={get:async s=>{let a=T(r,s);return await e.getDocumentSnapshot(a)},findOne:async s=>{let a=await lt({collection:r,index:s,context:t});return a?await e.getDocumentSnapshot(a):null},findAll:async s=>{let a=await dt({collection:r,index:s,context:t});return await Promise.all(a.map(c=>e.getDocumentSnapshot(c)))}},n),{})}function cr({meta:i,migration:t,context:e}){function n(){return i.time.zero(t.version)}let r=new Array,s=or({migration:t,context:e,meta:i}),a=ri({migration:t,getMigrationNow:n,newOids:r,meta:i}),o=new Array;return{log:e.log,newOids:r,migrate:async(l,u)=>{let d=await s[l].findAll();await Promise.all(d.map(async p=>{y(xe(p),`Document is missing an OID: ${JSON.stringify(p)}`);let g=k(p),I=await u(p);if(I){Se(g),Se(I),re(I);let h=Oe(g,I,n,void 0,[],{mergeUnknownObjects:!0});h.length>0&&await i.insertLocalOperation(h)}}))},queries:s,mutations:a,awaitables:o}}function lr({meta:i,migration:t,context:e}){function n(){return i.time.zero(t.version)}let r=new Array,s=new Proxy({},{get(){throw new Error("Queries are not available in initial migrations; there is no database yet!")}}),a=ri({migration:t,getMigrationNow:n,newOids:r,meta:i});return{log:e.log,newOids:r,migrate:()=>{throw new Error("Calling migrate() in initial migrations is not supported! Use initial migrations to seed initial data using mutations.")},queries:s,mutations:a,awaitables:[]}}async function dr(i){return new Promise((t,e)=>{let n=i.getAllKeys();n.onsuccess=r=>{t(n.result)},n.onerror=r=>{e(n.error)}})}async function ur(i,t){let e=i.delete(t);return new Promise((n,r)=>{e.onsuccess=s=>{n()},e.onerror=s=>{r(e.error)}})}async function pr(i,t){let e=i.put(t);return new Promise((n,r)=>{e.onsuccess=s=>{n()},e.onerror=s=>{r(e.error)}})}async function hr({meta:i,currentVersion:t,newVersion:e}){let n=[];return await i.operations.iterateOverAllOperations(r=>n.push(r),{from:i.time.zero(t+1)}),Array.from(new Set(n.map(r=>w(r.oid))))}var pt=class extends b{constructor(){super(...arguments);this._undoable=[];this._undone=[];this.undo=async()=>{let e=this._undoable.pop();return e?(this._undone.push(await e()),this.emit("change"),!0):!1};this.redo=async()=>{let e=this._undone.pop();return e?(this._undoable.push(await e()),this.emit("change"),!0):!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 ht=class{constructor(t,e,n){this.meta=t;this.schema=e;this.entities=n;this.getOid=(t,e)=>{let n=this.schema.collections[t].primaryKey,r=e[n];return y(r,`Document must have a primary key: ${n.toString()} (got: ${JSON.stringify(e)})`),T(t,r)};this.addDefaults=(t,e)=>{let n=this.schema.collections[t];return Z(n,e)};this.create=async(t,e,n={})=>{let r=this.addDefaults(t,e),s=this.getOid(t,r);return this.entities.create(r,s,n)};this.delete=async(t,e,n={})=>{let r=T(t,e);return this.entities.delete(r,n)};this.deleteAll=async(t,e={})=>this.entities.deleteAll(t.map(([n,r])=>T(n,r)),e);this.deleteAllFromCollection=async(t,e,n={})=>this.entities.deleteAll(e.map(r=>T(t,r)),n)}};var ce=Symbol("entity-file-update"),Te=Symbol("entity-file-mark-failed"),mr,fr,ne=class extends b{constructor(e,{downloadRemote:n=!1}={}){super();this.id=e;this._objectUrl=null;this._fileData=null;this._loading=!0;this._failed=!1;this._disposed=!1;this._downloadRemote=!1;this[mr]=e=>{this._loading=!1,this._failed=!1,this._disposed=!1,this._fileData=e,e.file&&(this._objectUrl&&URL.revokeObjectURL(this._objectUrl),this._objectUrl=URL.createObjectURL(e.file)),this.emit("change")};this[fr]=()=>{this._failed=!0,this._loading=!1,this.emit("change")};this.dispose=()=>{this._objectUrl&&URL.revokeObjectURL(this._objectUrl),this._disposed=!0};this._downloadRemote=n}static{mr=ce,fr=Te}get downloadRemote(){return this._downloadRemote}get url(){return this.loading?null:this._objectUrl?this._objectUrl:this._fileData?.url??null}get name(){return this._fileData?.name??null}get type(){return this._fileData?.type??null}get loading(){return this._loading}get failed(){return this._failed}};var si=jt(Ae(),1);function yr(i){return{id:(0,si.default)(),file:i,url:void 0,remote:!1,name:i.name,type:i.type}}function ie(i,t){if(typeof window<"u"&&i instanceof File){let e=yr(i);return t(e),Fn(e.id)}if(Array.isArray(i)){for(let e=0;e<i.length;e++)i[e]=ie(i[e],t);return i}if(typeof i=="object"){for(let e in i)i[e]=ie(i[e],t);return i}return i}function ai(i){return new Promise((t,e)=>{let n=new FileReader;n.onload=()=>{t(n.result)},n.onerror=e,n.readAsArrayBuffer(i)})}var mt=class extends V{constructor(){super(...arguments);this.addFile=async(e,{transaction:n,downloadRemote:r=!1}={})=>{let s=e.file?await ai(e.file):void 0;if(!s&&r&&e.url)try{s=await fetch(e.url,{method:"GET",credentials:"include"}).then(a=>a.arrayBuffer())}catch(a){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.",a)}return this.run("files",a=>a.put({id:e.id,remote:e.remote?"true":"false",deletedAt:null,name:e.name,type:e.type,url:e.url,buffer:s}),"readwrite",n)};this.hydrateFileData=e=>{e.remote=e.remote==="true";let n=e.buffer;return delete e.buffer,e.file=n?gr(n,e.type):void 0,e};this.markUploaded=async(e,{transaction:n}={})=>{let r=await this.getFileRaw(e,{transaction:n});if(!r)throw new Error("File is not in local database");return this.run("files",s=>s.put({...r,remote:"true"}),"readwrite",n)};this.getFileRaw=async(e,{transaction:n}={})=>{let r=await this.run("files",s=>s.get(e),"readonly",n);if(r)return r};this.getFile=async(e,{transaction:n}={})=>{let r=await this.getFileRaw(e,{transaction:n});if(r)return this.hydrateFileData(r)};this.markPendingDelete=async(e,{transaction:n}={})=>{let r=await this.getFileRaw(e,{transaction:n});if(!r)throw new Error("File is not in local database");return this.run("files",s=>s.put({...r,deletedAt:Date.now()}),"readwrite",n)};this.listUnsynced=async()=>(await this.run("files",n=>n.index("remote").getAll("false"),"readonly")).map(this.hydrateFileData);this.iterateOverPendingDelete=(e,n)=>this.iterate("files",r=>r.index("deletedAt").openCursor(IDBKeyRange.lowerBound(0,!0)),(r,s)=>{e(this.hydrateFileData(r),s)},"readwrite",n)}deleteFile(e,{transaction:n}={}){return this.run("files",r=>r.delete(e),"readwrite",n)}};function gr(i,t){return new Blob([i],{type:t})}function br(i){return i.deletedAt!==null&&i.deletedAt<Date.now()-1e3*60*24*3}var ft=class{constructor({db:t,sync:e,context:n,meta:r,config:s={}}){this.files=new Map;this.add=async t=>{let e=t;if(e.remote=!1,this.files.has(e.id))this.files.get(e.id)[ce](e);else{let n=new ne(e.id);n[ce](e),this.files.set(e.id,n)}await this.storage.addFile(e),e.file&&((await this.sync.uploadFile(e)).success?await this.storage.markUploaded(e.id):this.context.log("error","Failed to upload file"))};this.uploadFile=async(t,e=0)=>{let n=await this.sync.uploadFile(t);n.success?await this.storage.markUploaded(t.id):n.retry&&e<5?(this.context.log("error","Error uploading file, retrying..."),setTimeout(this.uploadFile,1e3,t,e+1)):this.context.log("error","Failed to upload file. Not retrying until next sync.")};this.get=t=>{if(this.files.has(t))return this.files.get(t);let e=new ne(t);return this.files.set(t,e),this.load(e),e};this.load=async(t,e=0)=>{if(e>5){t[Te]();return}let n=await this.storage.getFile(t.id);if(n)t[ce](n);else try{let r=await this.sync.getFile(t.id);r.success?(t[ce](r.data),await this.storage.addFile(r.data,{downloadRemote:t.downloadRemote})):(t[Te](),r.retry&&setTimeout(this.load,1e3,t,e+1))}catch(r){this.context.log("error","Failed to load file",r),t[Te](),setTimeout(this.load,1e3,t,e+1)}};this.listUnsynced=async()=>this.storage.listUnsynced();this.onOnlineChange=async t=>{if(t){let e=await this.listUnsynced();await Promise.all(e.map(this.uploadFile))}};this.tryCleanupDeletedFiles=async()=>{let t=0,e=0;await this.storage.iterateOverPendingDelete((n,r)=>{this.config.canCleanupDeletedFile(n)?(t++,r.delete(n.id)):e++}),this.context.log("info",`Cleaned up ${t} files, skipped ${e} files`)};this.handleFileRefsDeleted=async t=>{let e=this.storage.createTransaction(["files"],"readwrite");await Promise.all(t.map(async n=>{try{await this.storage.markPendingDelete(n.id,{transaction:e})}catch(r){this.context.log("error","Failed to mark file for deletion",r)}})),this.context.log("info",`Marked ${t.length} files as pending delete`)};this.storage=new mt(t),this.sync=e,this.context=n,this.meta=r,this.config={canCleanupDeletedFile:br,...s},this.sync.subscribe("onlineChange",this.onOnlineChange),this.meta.subscribe("filesDeleted",this.handleFileRefsDeleted),this.tryCleanupDeletedFiles()}};var le=class{constructor(t){this.value=t}deref(){return this.value}};var oi="@@refresh",yt="@@deepChange";function Ee(i,t){return i[oi](t)}var vr,Sr,U=class i{constructor({oid:t,store:e,fieldSchema:n,cache:r,parent:s,onAllUnsubscribed:a}){this._current=null;this._deleted=!1;this.cachedSnapshot=null;this.cachedDestructure=null;this.cachedDeepUpdatedAt=null;this._updatedAt=null;this[vr]=t=>{let{view:e,deleted:n,lastTimestamp:r}=this.cache.computeView(this.oid);this._current=e;let s=this._deleted&&!n;this._deleted=n,this.cachedDestructure=null,this._updatedAt=r||null,this.cachedDeepUpdatedAt=null,this._deleted?this.events.emit("delete",t):(this.events.emit("change",t),this[yt](this,t)),s&&(this.cachedSnapshot=null,this.events.emit("restore",t))};this[Sr]=(t,e)=>{this.cachedSnapshot=null,this.cachedDeepUpdatedAt=null,this.events.emit("changeDeep",t,e);let n=this.parent?.deref();n&&n[yt](t,e)};this.getChildFieldSchema=t=>{if(this.fieldSchema.type==="object")return this.fieldSchema.properties[t];if(this.fieldSchema.type==="array")return this.fieldSchema.items;if(this.fieldSchema.type==="map")return this.fieldSchema.values;if(this.fieldSchema.type==="any")return this.fieldSchema;throw new Error("Invalid field schema")};this.dispose=()=>{this.events.dispose()};this.subscribe=(t,e)=>this.events.subscribe(t,e);this.addPatches=t=>{this.store.addLocalOperations(t)};this.cloneCurrent=()=>{if(this._current!==void 0)return k(this._current)};this.getSubObject=(t,e)=>{let n=this.getChildFieldSchema(e);return this.cache.getEntity(t,n,this)};this.wrapValue=(t,e)=>{if(E(t)){let n=t.id,r=this.getSubObject(n,e);if(r)return r;throw new Error(`CACHE MISS: Subobject ${n} does not exist on ${this.oid}`)}else if(K(t)){let n=this.store.getFile(t.id);if(n)return n.subscribe("change",()=>{this[yt](this,{isLocal:!1})}),n}return t};this.processInputValue=(t,e)=>{let n=this.getChildFieldSchema(e);return n&&Y(t,n),ie(t,this.store.addFile)};this.get=t=>{if(this.value===void 0||this.value===null)throw new Error("Cannot access deleted entity");let e=this.value[t];return this.wrapValue(e,t)};this.getAll=()=>{if(this.value===void 0||this.value===null)throw new Error("Cannot access deleted entity");if(this.cachedDestructure)return this.cachedDestructure;let t;if(Array.isArray(this.value))t=this.value.map((e,n)=>this.wrapValue(e,n));else{t={};for(let e in this.value)t[e]=this.get(e)}return this.cachedDestructure=t,t};this.getSnapshot=()=>{if(!this.value||this.deleted)return null;if(this.cachedSnapshot)return this.cachedSnapshot;let t;if(Array.isArray(this.value))t=this.value.map((e,n)=>E(e)?this.getSubObject(e.id,n)?.getSnapshot():e);else{t={...this.value};for(let[e,n]of Object.entries(t))E(n)&&(t[e]=this.getSubObject(n.id,e)?.getSnapshot())}return x(t,this.oid),this.cachedSnapshot=t,t};this.keys=()=>Object.keys(this.value||{});this.entries=()=>Object.entries(this.getAll());this.values=()=>Object.values(this.getAll());this.set=(t,e)=>{this.addPatches(this.store.patchCreator.createSet(this.oid,t,this.processInputValue(e,t)))};this.delete=t=>{if(Array.isArray(this.value))this.addPatches(this.store.patchCreator.createListDelete(this.oid,t,1));else{let e=this.getDeleteMode(t);if(!e)throw new Error(`Cannot delete key ${t} - the property is not marked as optional in the schema`);e==="delete"?this.addPatches(this.store.patchCreator.createRemove(this.oid,t)):this.addPatches(this.store.patchCreator.createSet(this.oid,t,null))}};this.getDeleteMode=t=>{if(this.fieldSchema.type==="any"||this.fieldSchema.type==="map")return"delete";if(this.fieldSchema.type==="object"){let e=this.fieldSchema.properties[t];if(!e||e.type==="any")return"delete";if(e.type==="map")return!1;if(e.nullable)return"null"}return!1};this.remove=this.delete.bind(this);this.update=(t,{replaceSubObjects:e=!1,merge:n=!0}={replaceSubObjects:!1,merge:!0})=>{if(!n&&this.fieldSchema.type!=="any"&&this.fieldSchema.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.');for(let[s,a]of Object.entries(t)){let o=this.getChildFieldSchema(s);o&&Y(a,o)}let r=ie(t,this.store.addFile);this.addPatches(this.store.patchCreator.createDiff(this.getSnapshot(),x(r,this.oid),{mergeUnknownObjects:!e,defaultUndefined:n}))};this.getItemRefValue=t=>{if(typeof t=="object"){let e=F(t);if(!e||!this.cache.hasOid(e))throw new Error(`Cannot move object ${JSON.stringify(t)} which does not exist in this list`);return e}else return t};this.push=t=>{this.addPatches(this.store.patchCreator.createListPush(this.oid,this.processInputValue(t,this.value.length)))};this.insert=(t,e)=>{this.addPatches(this.store.patchCreator.createListInsert(this.oid,t,this.processInputValue(e,t)))};this.move=(t,e)=>{this.addPatches(this.store.patchCreator.createListMoveByIndex(this.oid,t,e))};this.moveItem=(t,e)=>{let n=this.getItemRefValue(t);if(E(n))this.addPatches(this.store.patchCreator.createListMoveByRef(this.oid,n,e));else{let r=this.value.indexOf(n);this.addPatches(this.store.patchCreator.createListMoveByIndex(this.oid,r,e))}};this.removeAll=t=>{this.addPatches(this.store.patchCreator.createListRemove(this.oid,this.getItemRefValue(t)))};this.removeFirst=t=>{this.addPatches(this.store.patchCreator.createListRemove(this.oid,this.getItemRefValue(t),"first"))};this.removeLast=t=>{this.addPatches(this.store.patchCreator.createListRemove(this.oid,this.getItemRefValue(t),"last"))};this.add=t=>{this.addPatches(this.store.patchCreator.createListAdd(this.oid,this.processInputValue(t,this.value.length)))};this.has=t=>typeof t=="object"?this.value.some(e=>E(e)?e.id===F(t):(K(e),!1)):this.value.includes(t);this.getAsWrapped=()=>{if(!this.isList)throw new Error("Cannot map items of a non-list");return this.value.map(this.wrapValue)};this.map=t=>this.getAsWrapped().map(t);this.filter=t=>this.getAsWrapped().filter((e,n)=>t(e,n));this.forEach=t=>{this.getAsWrapped().forEach(t)};this.oid=t;let{collection:o}=M(t);this.collection=o,this.parent=s&&new le(s),this.store=e,this.fieldSchema=n,this.cache=r;let{view:c,deleted:l,lastTimestamp:u}=this.cache.computeView(t);if(this._current=c,this._deleted=l,this._updatedAt=u||null,this.cachedDeepUpdatedAt=null,this.events=new b(()=>{this.hasSubscribers||a?.()}),this.oid.includes(".")&&!this.parent)throw new Error("Parent must be provided for sub entities");y(!!n,"Field schema must be provided")}hasSubscribersToDeepChanges(){return this.events.subscriberCount("changeDeep")>0}get hasSubscribers(){if(this.events.totalSubscriberCount()>0)return!0;let t=this.parent?.deref();for(;t;){if(t.hasSubscribersToDeepChanges())return!0;t=t.parent?.deref()}return!1}get deleted(){return this._deleted}get value(){return this._current}get isList(){return Array.isArray(this._current)}get updatedAt(){return this._updatedAt}get deepUpdatedAt(){if(this.cachedDeepUpdatedAt)return this.cachedDeepUpdatedAt;let t=this._updatedAt;return this.isList?this.forEach(e=>{if(e instanceof i){let n=e.deepUpdatedAt;n&&(!t||n>t)&&(t=n)}}):this.values().forEach(e=>{if(e instanceof i){let n=e.deepUpdatedAt;n&&(!t||n>t)&&(t=n)}}),this.cachedDeepUpdatedAt=t,t}get uid(){return this.oid}get length(){return this.value.length}[(vr=oi,Sr=yt,Symbol.iterator)](){let t=0;return{next:()=>t<this.value.length?{value:this.get(t++),done:!1}:{value:void 0,done:!0}}}};var gt=class extends b{constructor({oid:e,store:n,context:r}){super();this.entities=new Map;this.insertLocalOperations=e=>{let n=new Set;for(let r of e){let{oid:s}=r;n.add(s);let a=this.localOperationsMap.get(s)||[];a.push(r),this.localOperationsMap.set(s,a)}for(let r of n){let a=this.entities.get(r)?.deref();a&&(Ee(a,{isLocal:!0}),this.emit(`change:${r}`),this.emit("change:*",r))}};this.insertOperations=(e,n)=>{for(let r of e){let{oid:s}=r;n.affectedOids?.add(s);let a=this.operationsMap.get(s)||[],o=a.findIndex(l=>l.timestamp>=r.timestamp);if(o!==-1){if(a[o].timestamp===r.timestamp)continue;a.splice(o,0,r)}else a.push(r);this.operationsMap.set(s,a);let c=this.localOperationsMap.get(s);c&&this.localOperationsMap.set(s,c.filter(l=>l.timestamp!==r.timestamp))}};this.insertBaselines=(e,{affectedOids:n})=>{for(let r of e){let{oid:s}=r,a=this.baselinesMap.get(s);if(a?.timestamp&&a.timestamp>=r.timestamp)continue;n?.add(s),this.baselinesMap.set(s,r);let o=this.operationsMap.get(s)||[];for(;o[0]?.timestamp<r.timestamp;)o.shift()}};this.addData=({operations:e,baselines:n,reset:r,isLocal:s})=>{r&&(this.operationsMap.clear(),this.baselinesMap.clear());let a={isLocal:s||!1,affectedOids:new Set};if(this.insertBaselines(n,a),this.insertOperations(e,a),r)for(let o of this.entities.values()){let c=o.deref();c&&Ee(c,a)}else for(let o of a.affectedOids){let l=this.entities.get(o)?.deref();l&&(Ee(l,a),this.emit(`change:${o}`),this.emit("change:*",o))}};this.applyOperations=(e,n,r,s)=>{let a,o=this.storeTools.now;for(let c of r)if(!(s&&c.timestamp<=s)){if(En(c.timestamp,o)>0){a=c.timestamp;continue}c.data.op==="delete"?n=!0:(e=X(e,c.data),c.data.op==="initialize"&&(n=!1))}return a&&this.context.globalEvents.emit("futureSeen",a),{view:e,deleted:n,empty:!e&&!r.length}};this.computeView=e=>{let n=this.computeConfirmedView(e),r=this.localOperationsMap.get(e)||[];if(n.empty&&!r.length)return this.context.log("debug",`Entity ${e} accessed with no local data at all`),{view:null,deleted:!0,lastTimestamp:null};let{view:s,deleted:a}=this.applyOperations(n.view,n.deleted,r);return s&&x(s,e),{view:s,deleted:a,lastTimestamp:this.getLastTimestamp(e)}};this.computeConfirmedView=e=>{let n=this.baselinesMap.get(e),r=this.operationsMap.get(e)||[],s=k(n?.snapshot||void 0),a=this.applyOperations(s,!s,r,n?.timestamp);return a.view&&x(a.view,e),a.empty&&this.context.log("debug",`Entity ${e} accessed with no confirmed data`),a};this.getLastTimestamp=e=>{let n=this.localOperationsMap.get(e);n?.length||(n=this.operationsMap.get(e)||[]);let r=null;return n.length?r=n[n.length-1]?.timestamp:r=this.baselinesMap.get(e)?.timestamp??null,r?this.storeTools.time.getWallClockTime(r):null};this.getEntity=(e,n,r)=>{let a=this.entities.get(e)?.deref();return a||(a=new U({oid:e,cache:this,fieldSchema:n,store:this.storeTools,parent:r}),this.entities.set(e,new le(a))),a};this.hasOid=e=>this.operationsMap.has(e)||this.baselinesMap.has(e);this.dispose=()=>{this.entities.forEach(e=>e.deref()?.dispose()),this.entities.clear()};this.reset=(e,n,r=!1)=>{let s={isLocal:!1,affectedOids:new Set};if(this.baselinesMap=new Map(n.map(a=>[a.oid,a])),r)this.operationsMap=new Map;else for(let a of this.operationsMap.keys())this.operationsMap.set(a,this.operationsMap.get(a)?.filter(o=>!o.confirmed)??[]);this.insertOperations(e,s);for(let a of this.entities.keys()){let c=this.entities.get(a)?.deref();c&&(Ee(c,s),this.emit(`change:${a}`),this.emit("change:*",a))}};this.oid=e,this.operationsMap=new Map,this.localOperationsMap=new Map,this.baselinesMap=new Map,this.storeTools={addLocalOperations:n.addLocalOperations,patchCreator:n.meta.patchCreator,addFile:n.files.add,getFile:n.files.get,time:n.meta.time,now:n.meta.now},this.context=r}};var bt="@@default",vt=class{constructor({context:t,meta:e,batchTimeout:n=200,files:r}){this.documentFamilyCaches=new Map;this.unsubscribes=[];this._disposed=!1;this.currentBatchKey=bt;this.setContext=t=>{this.context=t};this.getDocumentSchema=t=>{let{collection:e}=M(t);return this.schema.collections[e]?{type:"object",properties:this.schema.collections[e].fields}:(this.log("warn",`Missing schema for collection: ${e}`),null)};this.refreshFamilyCache=async(t,e=!1)=>{if(this._disposed)return;let n=this.meta.createTransaction(["baselines","operations"]),r=[],s=[];await Promise.all([this.meta.baselines.iterateOverAllForDocument(t.oid,a=>{r.push(a)},{transaction:n,mode:"readwrite"}),this.meta.operations.iterateOverAllOperationsForDocument(t.oid,a=>{a.confirmed=!0,s.push(a)},{transaction:n,mode:"readwrite"})]),t.reset(s,r,e)};this.openFamilyCache=async t=>{let e=w(t),n=this.documentFamilyCaches.get(e);return n||(n=new gt({oid:e,store:this,context:this.context}),this.documentFamilyCaches.set(e,n),await this.refreshFamilyCache(n)),n};this.onEntityChange=async t=>{};this.writeDocumentToStorage=async t=>{if(this._disposed){this.log("warn","EntityStore is disposed, not writing to storage");return}let e=w(t),{id:n,collection:r}=M(e),s=await this.get(e);if(this._disposed){this.log("warn","EntityStore is disposed, not writing to storage");return}let a=s?.getSnapshot();if(a){let o=k(a);Xe(this.schema.collections[r],o),se(o);try{let l=this.db.transaction(r,"readwrite").objectStore(r);await _(l.put(o)),this.log("info","\u{1F4DD}","wrote",r,n,"to storage",o)}catch{this.log("\u26A0\uFE0F CRITICAL: possibly corrupt data couldn't be written to queryable storage. This is probably a bug in verdant! Please report at https://github.com/a-type/verdant/issues",`
|
|
11
|
-
`,"Invalid data:",JSON.stringify(o))}}else{let c=this.db.transaction(r,"readwrite").objectStore(r);await _(c.delete(n)),this.log("info","\u274C","deleted",r,n,"from storage")}};this.get=async t=>{let e=await this.openFamilyCache(t),n=this.getDocumentSchema(t);return n?e.getEntity(t,n):null};this.getCached=t=>{let e=this.documentFamilyCaches.get(t);if(e){let n=this.getDocumentSchema(t);return n?e.getEntity(t,n):null}return null};this.create=async(t,e,n)=>{$e(t);let r=ie(t,this.files.add);x(r,e);let s=this.meta.patchCreator.createInitialize(r,e),a=await this.openFamilyCache(e);a.insertLocalOperations(s),await this.submitOperations(s,n);let o=this.getDocumentSchema(e);if(!o)throw new Error(`Cannot create a document in the ${M(e).collection} collection; it is not defined in the current schema version.`);return a.getEntity(e,o)};this.addOperationsToOpenCaches=async(t,e)=>{let n=Xt(t);Object.keys(n).forEach(s=>{let a=this.documentFamilyCaches.get(s);a&&(this.log("adding",e.confirmed?"confirmed":"unconfirmed","operations to cache",s,n[s].length),e.isLocal?a.insertLocalOperations(n[s]):a.insertOperations(n[s],e))})};this.addBaselinesToOpenCaches=async(t,e)=>{let n=Yt(t);Object.keys(n).forEach(s=>{let a=this.documentFamilyCaches.get(s);a&&(this.log("adding","baselines to cache",s,n[s].length),a.insertBaselines(n[s],e))})};this.addDataToOpenCaches=({baselines:t,operations:e,reset:n,isLocal:r})=>{let s=Yt(t),a=Xt(e),o=Array.from(new Set(Object.keys(s).concat(Object.keys(a))));for(let c of o){let l=this.documentFamilyCaches.get(c);l?(l.addData({operations:a[c]||[],baselines:s[c]||[],reset:n,isLocal:r}),this.log("debug","Added data to cache for",c,a[c]?.length??0,"operations",s[c]?.length??0,"baselines")):this.log("debug","Could not add data to cache for",c,"because it is not open")}return o};this.addData=async({operations:t,baselines:e,reset:n})=>{let r=t;for(let o of r)o.confirmed=!1;let s=[];n?(this.log("Resetting local store to replicate remote synced data",e.length,"baselines, and",t.length,"operations"),await this.meta.reset(),await this.resetStoredDocuments(),s=Array.from(new Set(e.map(o=>w(o.oid)).concat(t.map(o=>w(o.oid)))))):s=this.addDataToOpenCaches({operations:r,baselines:e,reset:n}),await this.meta.insertRemoteBaselines(e),await this.meta.insertRemoteOperations(t),n&&await this.refreshAllCaches(!0);for(let o of s)await this.writeDocumentToStorage(o);let a=Array.from(new Set(s.map(o=>M(o).collection)));this.context.log("changes to collections",a),this.context.entityEvents.emit("collectionsChanged",a)};this.addLocalOperations=async t=>{this.log("Adding local operations",t.length),this.addOperationsToOpenCaches(t,{isLocal:!0,confirmed:!1}),this.operationBatcher.add({key:this.currentBatchKey,items:t})};this.batch=({undoable:t=!0,batchName:e=ze(),max:n=null,timeout:r=this.defaultBatchTimeout}={})=>{let s=this.operationBatcher.add({key:e,max:n,timeout:r,items:[],userData:{undoable:t}}),a={run:o=>(this.currentBatchKey=e,o(),this.currentBatchKey=bt,a),flush:async()=>(await this.operationBatcher.flush(bt),s.flush()),discard:()=>{this.operationBatcher.discard(e)}};return a};this.flushPatches=async()=>{await this.operationBatcher.flush(this.currentBatchKey)};this.flushOperations=async(t,e,n)=>{if(t.length){this.log("Flushing operations",t.length,"to storage / sync");for(let r of t)r.timestamp=this.meta.now;await this.submitOperations(t,n)}};this.submitOperations=async(t,{undoable:e=!0}={})=>{e&&this.undoHistory.addUndo(await this.createUndo(t)),await this.meta.insertLocalOperation(t),this.addDataToOpenCaches({operations:t,baselines:[]});let n=Array.from(new Set(t.map(s=>w(s.oid))));for(let s of n)await this.writeDocumentToStorage(s);let r=new Set(t.map(({oid:s})=>M(s).collection));this.context.log("changes to collections",r),this.context.entityEvents.emit("collectionsChanged",Array.from(r))};this.getInverseOperations=async t=>{let e=Kn(t),n=[],r=()=>this.meta.now;for(let[s,a]of Object.entries(e)){let o=await this.openFamilyCache(s),{view:c,deleted:l}=o.computeConfirmedView(s),u=Jn(s,c,a,r);n.unshift(...u)}return n};this.createUndo=async t=>{let e=await this.getInverseOperations(t);return async()=>{let n=await this.createUndo(e);return await this.submitOperations(e.map(r=>(r.timestamp=this.meta.now,r)),{undoable:!1}),n}};this.delete=async(t,e)=>{y(t===w(t),"Only root documents may be deleted via client methods");let n=await this.meta.getAllDocumentRelatedOids(t),r=this.meta.patchCreator.createDeleteAll(n);await this.submitOperations(r,e)};this.deleteAll=async(t,e)=>{let n=await Promise.all(t.map(s=>this.meta.getAllDocumentRelatedOids(s))),r=this.meta.patchCreator.createDeleteAll(n.flat());await this.submitOperations(r,e)};this.reset=async()=>{this.context.log("warn","Resetting local database"),await this.resetStoredDocuments(),await this.refreshAllCaches(!0)};this.destroy=()=>{this._disposed=!0;for(let t of this.unsubscribes)t();for(let t of this.documentFamilyCaches.values())t.dispose();this.documentFamilyCaches.clear()};this.handleRebase=t=>{this.log("debug","Reacting to rebases",t.length),this.addBaselinesToOpenCaches(t,{isLocal:!0})};this.resetStoredDocuments=async()=>{let t=this.db.transaction(Object.keys(this.schema.collections),"readwrite");for(let e of Object.keys(this.schema.collections)){let n=t.objectStore(e);await _(n.clear())}};this.refreshAllCaches=async(t=!1)=>{for(let[e,n]of this.documentFamilyCaches)await this.refreshFamilyCache(n,t)};this.context=t,this.defaultBatchTimeout=n,this.meta=e,this.files=r,this.operationBatcher=new ae(this.flushOperations),this.operationBatcher.add({key:bt,items:[],max:100,timeout:n,userData:{undoable:!0}}),this.unsubscribes.push(this.meta.subscribe("rebase",this.handleRebase))}get log(){return this.context.log}get db(){return this.context.documentDb}get undoHistory(){return this.context.undoHistory}get schema(){return this.context.schema}};var on=Symbol("handleMessage"),xr,Re=class extends b{constructor({initialPresence:e,updateBatchTimeout:n=200,defaultProfile:r}){super();this._peers={};this._self={profile:{}};this._selfReplicaIds=new Set;this._peerIds=new Array;this.isSelf=(e,n)=>e.id===n.replicaId||this._selfReplicaIds.has(n.replicaId)||this._self.id===n.id;this[xr]=async(e,n)=>{let r=!1,s=new Set(this.peerIds);if(n.type==="presence-changed")this.isSelf(e,n.userInfo)?(this._self=n.userInfo,this._selfReplicaIds.add(n.userInfo.replicaId),this.emit("selfChanged",n.userInfo)):(s.add(n.userInfo.id),this._peers[n.userInfo.id]=n.userInfo,r=!0,this.emit("peerChanged",n.userInfo.id,n.userInfo));else if(n.type==="sync-resp"){this._peers={},s.clear();for(let[a,o]of Object.entries(n.peerPresence))this.isSelf(e,o)?(this._self=o,this._selfReplicaIds.add(o.replicaId),this.emit("selfChanged",o)):(r=!0,s.add(a),this._peers[a]=o,this.emit("peerChanged",a,o))}else if(n.type==="presence-offline"){s.delete(n.userId),this._selfReplicaIds.delete(n.replicaId);let a=this._peers[n.userId];delete this._peers[n.userId],r=!0,this.emit("peerLeft",n.userId,a)}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 n=e.reduce((r,s)=>({...r,...s}),this.self.presence);this.emit("update",n)};this.self.presence=e,this.self.profile=r,this._updateBatcher=new ae(this.flushPresenceUpdates),this._updateBatch=this._updateBatcher.add({max:25,timeout:n,items:[],key:"default"})}static{xr=on}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 St=class{constructor({endpointProvider:t,log:e}){this.uploadFile=async t=>{let e=t.file;if(!e)throw new Error("Cannot upload a non-local file");let{files:n,token:r}=await this.endpointProvider.getEndpoints(),s=new window.FormData;s.append("file",e);try{let a=await fetch(n+`/${t.id}`,{method:"POST",body:s,credentials:"include",headers:{Authorization:`Bearer ${r}`}});return a.ok?{success:!0,retry:!1}:(this.log("error","File upload failed",a.status,await a.text()),{success:!1,retry:a.status>=500})}catch(a){return this.log("error","File upload failed",a),{success:!1,retry:!0}}};this.getFile=async t=>{let{files:e,token:n}=await this.endpointProvider.getEndpoints();try{let r=await fetch(e+`/${t}`,{method:"GET",credentials:"include",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`}});return r.ok?{success:!0,data:await r.json()}:(this.log("error","File information fetch failed",r.status,await r.text()),{success:!1,retry:r.status>=500||r.status===404})}catch(r){return this.log("error","File information fetch failed",r),{success:!1,retry:!0}}};this.endpointProvider=t,this.log=e}};var de=class extends b{constructor({interval:e=15*1e3,deadlineLength:n=3*1e3,restartOnTabFocus:r=!0}={}){super();this.nextBeat=null;this.deadline=null;this.keepAlive=()=>{this.deadline&&(clearTimeout(this.deadline),this.deadline=null,this.start())};this.start=(e=!1)=>{this.stop(),e?this.beat():this.nextBeat=setTimeout(this.beat,this._interval)};this.stop=()=>{this.nextBeat&&clearTimeout(this.nextBeat),this.deadline&&clearTimeout(this.deadline)};this.beat=async()=>{this.emit("beat"),this.deadline=setTimeout(this.onDeadline,this.deadlineLength)};this.onDeadline=()=>{this.deadline=null,this.emit("missed")};this.setInterval=e=>{this._interval=e};this._interval=e,this.deadlineLength=n,typeof window<"u"&&r&&window.addEventListener("pageshow",()=>this.start(!0))}get interval(){return this._interval}};var xt=class extends b{constructor({endpointProvider:e,meta:n,presence:r,interval:s=15*1e3,log:a=()=>{}}){super();this.mode="pull";this._isConnected=!1;this._status="paused";this._hasSynced=!1;this.setInterval=e=>{this.heartbeat.setInterval(e)};this.sendRequest=async e=>{this.log("Sending sync request",e);try{let{http:n,token:r}=await this.endpointProvider.getEndpoints(),s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({messages:e}),credentials:"include"});if(s.ok){this.heartbeat.keepAlive();let a=await s.json();for(let o of a.messages)this.handleServerMessage(o);this._isConnected||(this._isConnected=!0,this.emit("onlineChange",!0))}else this.log("Sync request failed",s.status,await s.text()),this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1)),s.status>=500&&this.heartbeat.keepAlive()}catch(n){this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1)),this.log(n),this.heartbeat.keepAlive()}};this.handleServerMessage=async e=>{e.type==="sync-resp"&&(e.ackThisNonce&&(this.log("Sending sync ack",e.ackThisNonce),this.sendRequest([await this.meta.messageCreator.createAck(e.ackThisNonce)])),this._hasSynced=!0),this.emit("message",e)};this.send=e=>{switch(e.type){case"presence-update":case"sync":case"heartbeat":return this.sendRequest([e]);case"op":if(this._hasSynced)return this.sendRequest([e]);break}};this.dispose=()=>{};this.onHeartbeat=async()=>{this.sendRequest([await this.meta.messageCreator.createPresenceUpdate(this.presence.self.presence),await this.meta.messageCreator.createSyncStep1()])};this.onHeartbeatMissed=async()=>{this.emit("onlineChange",!1),this.log("Missed heartbeat"),this._isConnected=!1};this.log=a,this.meta=n,this.presence=r,this.endpointProvider=e,this.heartbeat=new de({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)}get isConnected(){return this._isConnected}get status(){return this._status}};function cn(i){this.message=i}cn.prototype=new Error,cn.prototype.name="InvalidCharacterError";var ci=typeof window<"u"&&window.atob&&window.atob.bind(window)||function(i){var t=String(i).replace(/=+$/,"");if(t.length%4==1)throw new cn("'atob' failed: The string to be decoded is not correctly encoded.");for(var e,n,r=0,s=0,a="";n=t.charAt(s++);~n&&(e=r%4?64*e+n:n,r++%4)?a+=String.fromCharCode(255&e>>(-2*r&6)):0)n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(n);return a};function Or(i){var t=i.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(ci(e).replace(/(.)/g,function(n,r){var s=r.charCodeAt(0).toString(16).toUpperCase();return s.length<2&&(s="0"+s),"%"+s}))}(t)}catch{return ci(t)}}function Ot(i){this.message=i}function wr(i,t){if(typeof i!="string")throw new Ot("Invalid token specified");var e=(t=t||{}).header===!0?0:1;try{return JSON.parse(Or(i.split(".")[e]))}catch(n){throw new Ot("Invalid token specified: "+n.message)}}Ot.prototype=new Error,Ot.prototype.name="InvalidTokenError";var li=wr;var wt=class{constructor(t){this.config=t;this.cached=null;this.type=0;this.getEndpoints=async()=>{if(this.cached)return this.cached;let t;this.config.fetchAuth?t=await this.config.fetchAuth():t=await fetch(this.config.authEndpoint,{credentials:"include"}).then(o=>{if(o.ok)return o.json();throw new Error(`Auth endpoint returned non-200 response: ${o.status}`)}),y(t.accessToken,"No access token provided from auth endpoint");let e=li(t.accessToken);y(e.url,"No sync endpoint provided from auth endpoint"),y(e.type!==void 0,"No replica type provided from auth endpoint"),this.type=parseInt(e.type+"");let n=new URL(e.url);n.protocol=n.protocol.replace("ws","http");let r=n.toString();n.protocol=n.protocol.replace("http","ws");let s=n.toString(),a=e.file;if(!a){let o=new URL(r);o.pathname=o.pathname+"/files",a=o.toString()}return this.cached={http:r,websocket:s,files:a,token:t.accessToken},this.cached};if(!t.authEndpoint&&!t.fetchAuth)throw new Error("Either authEndpoint or fetchAuth must be provided to ServerSyncEndpointProvider")}};var It=class extends b{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}},Ct=class{constructor(t,e){this.current=0;this.next=()=>{this.current=Math.min(this.max,this.current*this.factor)};this.reset=()=>{this.current=0};this.max=t,this.factor=e}};var Dt=class extends b{constructor({endpointProvider:e,meta:n,presence:r,log:s}){super();this.socket=null;this.connectQueue=[];this.syncQueue=[];this._status="paused";this.synced=!1;this.hasStartedSync=!1;this.mode="realtime";this.log=(...e)=>{};this.heartbeat=new de;this.reconnectScheduler=new It(new Ct(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),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=>{let n=JSON.parse(e.data);switch(n.type){case"sync-resp":if(n.ackThisNonce&&this.send(await this.meta.messageCreator.createAck(n.ackThisNonce)),this.hasStartedSync=!0,this.synced=!0,this.syncQueue.length){for(let r of this.syncQueue)this.send(r);this.syncQueue=[]}case"need-since":case"presence-changed":case"presence-offline":this.emit("message",n);break;case"op-re":if(!this.hasStartedSync){this.log("Skipping op-re message because sync hasn't started yet",n);break}this.emit("message",n);break;case"heartbeat-response":this.heartbeat.keepAlive(),this.emit("message",n);break;default:this.synced&&this.emit("message",n);break}};this.onError=e=>{this.log(e),this.reconnectScheduler.next(),this.log("Attempting reconnect to websocket sync")};this.onClose=e=>{this.log("Sync disconnected"),this.onOnlineChange(!1),this.onError(e)};this.initializeSocket=async()=>{let e=await this.endpointProvider.getEndpoints();return this.socket=new WebSocket(e.websocket,["Bearer",e.token]),this.socket.addEventListener("message",this.onMessage),this.socket.addEventListener("open",this.onOpen),this.socket.addEventListener("error",this.onError),this.socket.addEventListener("close",this.onClose),this.socket};this.sendHeartbeat=async()=>{this.send(await this.meta.messageCreator.createHeartbeat())};this.reconnect=()=>{this.stop(),this.start()};this.canSkipSyncWait=e=>e.type==="sync"||e.type==="presence-update"||e.type==="sync-ack"||e.type==="heartbeat";this.send=e=>{this.status==="active"&&(!this.hasStartedSync&&!this.canSkipSyncWait(e)||(this.canSkipSyncWait(e)?this.socket?.readyState===WebSocket.OPEN?(this.log("Sending message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e))):(this.log("Enqueueing message until socket is open",JSON.stringify(e,null,2)),this.connectQueue.push(e)):this.synced?this.socket?.readyState===WebSocket.OPEN&&(this.log("Sending message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e))):this.hasStartedSync&&(this.log("Enqueueing message until synced",JSON.stringify(e,null,2)),this.syncQueue.push(e))))};this.dispose=()=>{this.socket?.removeEventListener("close",this.onClose),this.socket?.close()};this.start=()=>{this.socket||(this.initializeSocket(),this._status="active")};this.stop=()=>{this.dispose(),this.socket=null,this._status="paused"};this.log=s||this.log,this.endpointProvider=e,this.meta=n,this.presence=r,this.reconnectScheduler.subscribe("trigger",this.initializeSocket),this.heartbeat.subscribe("beat",this.sendHeartbeat)}get isConnected(){return this.socket?.readyState===WebSocket.OPEN}get status(){return this._status}};var Pt=class extends b{constructor(){super(...arguments);this.mode="pull";this.dispose=()=>{};this.isConnected=!1;this.status="paused";this.pullInterval=0;this.presence=new Re({initialPresence:{},defaultProfile:{}});this.uploadFile=async()=>({success:!1,retry:!1});this.getFile=async()=>({success:!1,retry:!1})}send(){}start(){}stop(){}reconnect(){}setMode(){}setPullInterval(){}},ue=class extends b{constructor({authEndpoint:e,fetchAuth:n,initialPresence:r,automaticTransportSelection:s=!0,autoStart:a,initialTransport:o,pullInterval:c,presenceUpdateBatchTimeout:l,defaultProfile:u,useBroadcastChannel:d},{meta:p,log:g,onData:I}){super();this.broadcastChannel=null;this._activelySyncing=!1;this.handleBroadcastChannelMessage=e=>{e.data.type==="sync"&&this.handleMessage(e.data.message)};this.handleMessage=async e=>{if(e.type==="op-re"||e.type==="sync-resp")for(let n of e.operations)this.meta.time.update(n.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)}this.broadcastChannel?.postMessage({type:"sync",message:e}),this.presence[on](await this.meta.localReplica.get(),e)};this.handleOnlineChange=e=>{this.emit("onlineChange",e)};this.handlePresenceUpdate=async e=>{this.send(await this.meta.messageCreator.createPresenceUpdate(e))};this.setMode=e=>{if(e==="realtime"&&!this.canDoRealtime)throw new Error("Cannot switch to realtime mode, because the current auth token does not allow it");let n;e==="realtime"?n=this.webSocketSync:n=this.pushPullSync,n!==this.activeSync&&(this.log("switching to",e,"mode"),this.activeSync.status==="active"&&n.start(),this.activeSync.stop(),this.activeSync=n)};this.setPullInterval=e=>{this.pushPullSync.setInterval(e)};this.send=e=>{if(this.activeSync.status==="active")return this.activeSync.send(e)};this.uploadFile=async e=>this.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.dispose=()=>{this.webSocketSync.dispose(),this.pushPullSync.dispose()};this.reconnect=()=>this.activeSync.reconnect();if(this.meta=p,this.onData=I,this.log=g||(()=>{}),this.presence=new Re({initialPresence:r,defaultProfile:u,updateBatchTimeout:l}),this.endpointProvider=new wt({authEndpoint:e,fetchAuth:n}),this.webSocketSync=new Dt({endpointProvider:this.endpointProvider,meta:p,presence:this.presence,log:this.log}),this.pushPullSync=new xt({endpointProvider:this.endpointProvider,meta:p,presence:this.presence,log:this.log,interval:c}),this.fileSync=new St({endpointProvider:this.endpointProvider,log:this.log}),d&&"BroadcastChannel"in window&&(this.broadcastChannel=new BroadcastChannel("verdant"),this.broadcastChannel.addEventListener("message",this.handleBroadcastChannelMessage)),o==="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 h=()=>{m&&clearTimeout(m);let v=Object.keys(this.presence.peers).length>0||s!=="peers-only"&&this.presence.selfReplicaIds.size>1;v&&this.mode==="pull"?this.setMode("realtime"):!v&&this.mode==="realtime"&&(m=setTimeout(()=>{Object.keys(this.presence.peers).length===0&&this.setMode("pull")},1e3))},m;this.presence.subscribe("peersChanged",h),s!=="peers-only"&&this.presence.subscribe("selfChanged",h)}a&&this.start()}get canDoRealtime(){return this.endpointProvider.type===0||this.endpointProvider.type===2||this.endpointProvider.type===5}get syncing(){return this._activelySyncing}get pullInterval(){return this.pushPullSync.interval}get isConnected(){return this.activeSync.isConnected}get status(){return this.activeSync.status}get mode(){return this.activeSync.mode}};var pe=class{constructor(){this._disposes=[];this.disposed=!1;this.dispose=()=>{this.disposed=!0,this._disposes.forEach(t=>t()),this._disposes=[]};this.addDispose=t=>{this._disposes.push(t)}}};function Cr(i){return i!==null}function ln(i){return Array.isArray(i)?i.map(ln).filter(Cr):i instanceof U&&i.deleted?null:i}function W(i,t){return!i&&!t||i&&t&&ve(i)===ve(t)}var dn=Symbol("ON_ALL_UNSUBSCRIBED"),j=Symbol("UPDATE"),Dr,N=class extends pe{constructor({initial:e,context:n,collection:r,key:s,shouldUpdate:a}){super();this._internalUnsubscribes=[];this._status="initial";this._executionPromise=null;this.subscribe=e=>(this.resolved,this._events.subscribe("change",e));this.setValue=e=>{this._rawValue=e,this.subscribeToDeleteAndRestore(this._rawValue),this._value=ln(e),this._status="ready",this._events.emit("change",this._value)};this.refreshValue=()=>{this.setValue(this._rawValue)};this.subscribeToDeleteAndRestore=e=>{for(;this._internalUnsubscribes.length;)this._internalUnsubscribes.pop()?.();Array.isArray(e)?e.forEach(n=>{n instanceof U&&(this._internalUnsubscribes.push(n.subscribe("delete",this.refreshValue)),this._internalUnsubscribes.push(n.subscribe("restore",this.refreshValue)))}):e instanceof U&&(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),this._executionPromise);this[Dr]=e=>{this._allUnsubscribedHandler=e};this._rawValue=e,this._value=e,this._events=new b(c=>{c==="change"&&this._allUnsubscribedHandler?.(this)}),this.context=n,this.key=s,this.collection=r;let o=a||(c=>c.includes(r));this.addDispose(this.context.entityEvents.subscribe("collectionsChanged",c=>{o(c)&&(this.context.log("info","Updating query",this.key),this.execute())}))}static{Dr=dn}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}};var Tt=class extends N{constructor({id:e,hydrate:n,...r}){super({initial:null,...r});this.run=async()=>{let e=await this.hydrate(this.oid);this.setValue(e)};this.oid=T(r.collection,e),this.hydrate=n}};var Pr,Et=class extends N{constructor({index:e,hydrate:n,...r}){super({initial:null,...r});this.run=async()=>{let e=await lt({collection:this.collection,index:this.index,context:this.context});this.setValue(e?await this.hydrate(e):null)};this[Pr]=e=>{W(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n}static{Pr=j}};var Tr,Rt=class extends N{constructor({index:e,hydrate:n,pageSize:r,page:s,...a}){super({initial:[],...a});this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:n}=await Ce({collection:this.collection,index:this.index,context:this.context,limit:this._pageSize,offset:this._page*this._pageSize});this._hasNextPage=n,this.setValue(await Promise.all(e.map(this.hydrate)))};this.nextPage=async()=>{this.hasNextPage&&(this._page++,await this.run())};this.previousPage=async()=>{this._page!==0&&(this._page--,await this.run())};this.setPage=async e=>{this._page=e,await this.run()};this[Tr]=e=>{W(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n,this._pageSize=r,this._page=s}static{Tr=j}get pageSize(){return this._pageSize}get page(){return this._page}get hasNextPage(){return this._hasNextPage}get hasPreviousPage(){return this._page>0}};var Er,kt=class extends N{constructor({hydrate:e,pageSize:n,index:r,...s}){super({initial:[],...s});this._upToPage=1;this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:n}=await Ce({collection:this.collection,context:this.context,limit:this._pageSize*this._upToPage,offset:0,index:this.index});this._hasNextPage=n,this.setValue(await Promise.all(e.map(this.hydrate)))};this.loadMore=async()=>{let{result:e,hasNextPage:n}=await Ce({collection:this.collection,context:this.context,limit:this._pageSize,offset:this._pageSize*this._upToPage,index:this.index});this._hasNextPage=n,this._upToPage++,this.setValue([...this.current,...await Promise.all(e.map(this.hydrate))])};this[Er]=e=>{W(this.index,e)||(this.index=e,this.execute())};this.index=r,this.hydrate=e,this._pageSize=n}static{Er=j}get pageSize(){return this._pageSize}get hasMore(){return this._hasNextPage}};var Rr,_t=class extends N{constructor({index:e,hydrate:n,...r}){super({initial:[],...r});this.run=async()=>{let e=await dt({collection:this.collection,index:this.index,context:this.context});this.setValue(await Promise.all(e.map(this.hydrate)))};this[Rr]=e=>{W(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n}static{Rr=j}};var Ft=class{constructor({collection:t,cache:e,entities:n,context:r,documentManager:s}){this.serializeIndex=t=>t?ve(t):"";this.get=t=>{let e=`get:${this.collection}:${t}`;return this.cache.getOrSet(e,()=>new Tt({id:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:e}))};this.findOne=({index:t,key:e}={})=>{let n=e||`findOne:${this.collection}:${this.serializeIndex(t)}`;return this.cache.getOrSet(n,()=>new Et({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:n}),r=>{r[j](t)})};this.findAll=({index:t,key:e}={})=>{let n=e||`findAll:${this.collection}:${this.serializeIndex(t)}`;return this.cache.getOrSet(n,()=>new _t({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:n}),r=>{r[j](t)})};this.findPage=({index:t,pageSize:e,page:n,key:r})=>{let s=r||`findPage:${this.collection}:${this.serializeIndex(t)}:${e}`;return this.cache.getOrSet(s,()=>new Rt({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:s,pageSize:e,page:n}),a=>{a[j](t)})};this.findAllInfinite=({index:t,pageSize:e,key:n})=>{let r=n||`findAllInfinite:${this.collection}:${this.serializeIndex(t)}:${e}`;return this.cache.getOrSet(r,()=>new kt({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:r,pageSize:e}),s=>{s[j](t)})};this.cache=e,this.collection=t,this.hydrate=n.get,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 At=class extends pe{constructor({evictionTime:e=5*1e3,context:n}){super();this._cache=new Map;this.onQueryUnsubscribed=e=>{setTimeout(()=>{e.subscribed||this._cache.get(e.key)===e&&this._cache.delete(e.key)},this._evictionTime)};this._evictionTime=e,this.context=n}get(e){return this._cache.get(e)||null}set(e){return this._cache.set(e.key,e),e[dn](this.onQueryUnsubscribed),e}getOrSet(e,n,r){let s=this.get(e);return s?(r?.(s),s):this.set(n())}};var he=class extends b{constructor(e,n,r){super();this.config=e;this.context=n;this.addData=e=>this._entities.addData(e);this.stats=async()=>{let e=Object.keys(this.schema.collections),n={};for(let l of e)n[l]=await we(this.documentDb,l);let r=await this.meta.stats(),s=typeof navigator<"u"&&typeof navigator.storage<"u"&&"estimate"in navigator.storage?await navigator.storage.estimate():void 0,a=Object.values(n).reduce((l,{size:u})=>l+u,0),o=r.baselinesSize.size+r.operationsSize.size,c=o/a;return{collections:n,meta:r,storage:s,totalMetaSize:o,totalCollectionsSize:a,metaToDataRatio:c,quotaUsage:s?.usage&&s?.quota?s.usage/s.quota:void 0}};this.close=async()=>{await this.entities.flushPatches(),this.sync.stop(),this.sync.dispose(),this.meta.close(),this._entities.destroy(),await Ie(this.documentDb),await Ie(this.metaDb),this.context.log?.("Client closed")};this.__dangerous__resetLocal=async()=>{this.sync.stop(),await et(this.namespace,indexedDB)};this.export=async()=>{let e=await this.meta.export();return Buffer.from(JSON.stringify(e))};this.import=async e=>{this.context.log("Importing data..."),await Ie(this.context.documentDb);let n=JSON.parse(e.toString());await this.meta.resetFrom(n);let r=n.schema.version,s=indexedDB.deleteDatabase([this.namespace,"collections"].join("_"));await new Promise((o,c)=>{s.onsuccess=o,s.onerror=c});let a=this.context.schema;this.context.schema=n.schema,this.context.documentDb=await Pe({meta:this.meta,migrations:this.config.migrations,context:this.context,version:r}),this.context.log("Re-initializing data from imported data..."),await this._entities.addData({operations:n.operations,baselines:n.baselines,reset:!0}),await Ie(this.context.documentDb),this.context.log("Migrating up to latest schema..."),this.context.schema=a,this.context.documentDb=await Pe({meta:this.meta,migrations:this.config.migrations,context:this.context,version:a.version})};this.meta=r.meta,this.collectionNames=Object.keys(n.schema.collections),this._sync=this.config.syncConfig?new ue(this.config.syncConfig,{meta:this.meta,onData:this.addData,log:this.context.log}):new Pt,this._fileManager=new ft({db:this.metaDb,sync:this.sync,context:this.context,config:this.config.files,meta:this.meta}),this._entities=new vt({context:this.context,meta:this.meta,files:this._fileManager}),this._queryCache=new At({context:n}),this._documentManager=new ht(this.meta,this.schema,this._entities);let s=jn(()=>{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[a,o]of Object.entries(n.schema.collections)){let c=o,l=c.pluralName??c.name+"s";y(l===a,`The key of the collection in the schema must be the plural of the name (expected: "${l}")`),this[l]=new Ft({collection:l,cache:this._queryCache,context:this.context,entities:this.entities,documentManager:this.documentManager})}}get sync(){return this._sync}get entities(){return this._entities}get documentManager(){return this._documentManager}get documentDb(){return this.context.documentDb}get metaDb(){return this.context.metaDb}get schema(){return this.context.schema}get namespace(){return this.context.namespace}get undoHistory(){return this.context.undoHistory}get presence(){return this.sync.presence}get batch(){return this.entities.batch}};var Mt=class{constructor(t){this.init=t;this._initializing=!1;this.initialize=async t=>{if(typeof window>"u"&&!t.indexedDb)throw new Error("A verdant client was initialized in an environment without IndexedDB. If you are using verdant in a server-rendered framework, you must enforce that all clients are initialized on the client-side, or you must provide some mock interface of IDBFactory to the ClientDescriptor options.");if(this._initializing||this._resolvedValue)return this._readyPromise;this._initializing=!0;try{let e=[t.namespace,"meta"].join("_"),{db:n}=await Yn(this._namespace,{indexedDB:t.indexedDb,log:t.log,databaseName:e}),r={namespace:this._namespace,metaDb:n,schema:t.schema,log:t.log||(()=>{}),undoHistory:t.undoHistory||new pt,entityEvents:new b,globalEvents:new b},s=new ot({context:r,disableRebasing:t.disableRebasing});await s.updateSchema(t.schema,t.overrideSchemaConflict);let a=await Pe({context:r,version:t.schema.version,meta:s,migrations:t.migrations,indexedDB:t.indexedDb}),o=Object.assign(r,{documentDb:a}),c=new he({syncConfig:t.sync,migrations:t.migrations,files:t.files},o,{meta:s});return this.resolveReady(c),this._resolvedValue=c,c}catch(e){throw this.rejectReady(e),e}finally{this._initializing=!1}};this.open=()=>this.initialize(this.init);this.close=async()=>{this._resolvedValue&&this._resolvedValue.close(),this._initializing&&(await this._readyPromise).close()};this.__dangerous__resetLocal=async()=>{await et(this.namespace)};this._readyPromise=new Promise((e,n)=>{this.resolveReady=e,this.rejectReady=n}),this._namespace=t.namespace}get namespace(){return this._namespace}get current(){return this._resolvedValue}get readyPromise(){return this._readyPromise}get schema(){return this.init.schema}};window.Verdant=un;
|
|
10
|
+
`)}}),De(t,r.namespace,i)):De(t,r.namespace,i)}function ri({migration:i,meta:t,getMigrationNow:e,newOids:n}){return i.allCollections.reduce((r,s)=>(r[s]={put:async a=>{Z(i.newSchema.collections[s],a);let o=a[i.newSchema.collections[s].primaryKey],c=T(s,o);return n.push(c),await t.insertLocalOperation(H(a,c,e)),a},delete:a=>{let o=T(s,a);return t.insertLocalOperation([{oid:o,timestamp:e(),data:{op:"delete"}}])}},r),{})}function or({migration:i,context:t,meta:e}){return i.oldCollections.reduce((n,r)=>(n[r]={get:async s=>{let a=T(r,s);return await e.getDocumentSnapshot(a)},findOne:async s=>{let a=await lt({collection:r,index:s,context:t});return a?await e.getDocumentSnapshot(a):null},findAll:async s=>{let a=await dt({collection:r,index:s,context:t});return await Promise.all(a.map(c=>e.getDocumentSnapshot(c)))}},n),{})}function cr({meta:i,migration:t,context:e}){function n(){return i.time.zero(t.version)}let r=new Array,s=or({migration:t,context:e,meta:i}),a=ri({migration:t,getMigrationNow:n,newOids:r,meta:i}),o=new Array;return{log:e.log,newOids:r,migrate:async(l,u)=>{let d=await s[l].findAll();await Promise.all(d.map(async p=>{y(xe(p),`Document is missing an OID: ${JSON.stringify(p)}`);let g=_(p),I=await u(p);if(I){Se(g),Se(I),re(I);let h=Oe(g,I,n,void 0,[],{mergeUnknownObjects:!0});h.length>0&&await i.insertLocalOperation(h)}}))},queries:s,mutations:a,awaitables:o}}function lr({meta:i,migration:t,context:e}){function n(){return i.time.zero(t.version)}let r=new Array,s=new Proxy({},{get(){throw new Error("Queries are not available in initial migrations; there is no database yet!")}}),a=ri({migration:t,getMigrationNow:n,newOids:r,meta:i});return{log:e.log,newOids:r,migrate:()=>{throw new Error("Calling migrate() in initial migrations is not supported! Use initial migrations to seed initial data using mutations.")},queries:s,mutations:a,awaitables:[]}}async function dr(i){return new Promise((t,e)=>{let n=i.getAllKeys();n.onsuccess=r=>{t(n.result)},n.onerror=r=>{e(n.error)}})}async function ur(i,t){let e=i.delete(t);return new Promise((n,r)=>{e.onsuccess=s=>{n()},e.onerror=s=>{r(e.error)}})}async function pr(i,t){let e=i.put(t);return new Promise((n,r)=>{e.onsuccess=s=>{n()},e.onerror=s=>{r(e.error)}})}async function hr({meta:i,currentVersion:t,newVersion:e}){let n=[];return await i.operations.iterateOverAllOperations(r=>n.push(r),{from:i.time.zero(t+1)}),Array.from(new Set(n.map(r=>w(r.oid))))}var pt=class extends b{constructor(){super(...arguments);this._undoable=[];this._undone=[];this.undo=async()=>{let e=this._undoable.pop();return e?(this._undone.push(await e()),this.emit("change"),!0):!1};this.redo=async()=>{let e=this._undone.pop();return e?(this._undoable.push(await e()),this.emit("change"),!0):!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 ht=class{constructor(t,e,n){this.meta=t;this.schema=e;this.entities=n;this.getOid=(t,e)=>{let n=this.schema.collections[t].primaryKey,r=e[n];return y(r,`Document must have a primary key: ${n.toString()} (got: ${JSON.stringify(e)})`),T(t,r)};this.addDefaults=(t,e)=>{let n=this.schema.collections[t];return Z(n,e)};this.create=async(t,e,n={})=>{let r=this.addDefaults(t,e),s=this.getOid(t,r);return this.entities.create(r,s,n)};this.delete=async(t,e,n={})=>{let r=T(t,e);return this.entities.delete(r,n)};this.deleteAll=async(t,e={})=>this.entities.deleteAll(t.map(([n,r])=>T(n,r)),e);this.deleteAllFromCollection=async(t,e,n={})=>this.entities.deleteAll(e.map(r=>T(t,r)),n)}};var ce=Symbol("entity-file-update"),Te=Symbol("entity-file-mark-failed"),mr,fr,ne=class extends b{constructor(e,{downloadRemote:n=!1}={}){super();this.id=e;this._objectUrl=null;this._fileData=null;this._loading=!0;this._failed=!1;this._disposed=!1;this._downloadRemote=!1;this[mr]=e=>{this._loading=!1,this._failed=!1,this._disposed=!1,this._fileData=e,e.file&&(this._objectUrl&&URL.revokeObjectURL(this._objectUrl),this._objectUrl=URL.createObjectURL(e.file)),this.emit("change")};this[fr]=()=>{this._failed=!0,this._loading=!1,this.emit("change")};this.dispose=()=>{this._objectUrl&&URL.revokeObjectURL(this._objectUrl),this._disposed=!0};this._downloadRemote=n}static{mr=ce,fr=Te}get downloadRemote(){return this._downloadRemote}get url(){return this.loading?null:this._objectUrl?this._objectUrl:this._fileData?.url??null}get name(){return this._fileData?.name??null}get type(){return this._fileData?.type??null}get loading(){return this._loading}get failed(){return this._failed}};var si=jt(Ae(),1);function yr(i){return{id:(0,si.default)(),file:i,url:void 0,remote:!1,name:i.name,type:i.type}}function ie(i,t){if(typeof window<"u"&&i instanceof File){let e=yr(i);return t(e),Rn(e.id)}if(Array.isArray(i)){for(let e=0;e<i.length;e++)i[e]=ie(i[e],t);return i}if(typeof i=="object"){for(let e in i)i[e]=ie(i[e],t);return i}return i}function ai(i){return new Promise((t,e)=>{let n=new FileReader;n.onload=()=>{t(n.result)},n.onerror=e,n.readAsArrayBuffer(i)})}var mt=class extends N{constructor(){super(...arguments);this.addFile=async(e,{transaction:n,downloadRemote:r=!1}={})=>{let s=e.file?await ai(e.file):void 0;if(!s&&r&&e.url)try{s=await fetch(e.url,{method:"GET",credentials:"include"}).then(a=>a.arrayBuffer())}catch(a){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.",a)}return this.run("files",a=>a.put({id:e.id,remote:e.remote?"true":"false",deletedAt:null,name:e.name,type:e.type,url:e.url,buffer:s}),"readwrite",n)};this.hydrateFileData=e=>{e.remote=e.remote==="true";let n=e.buffer;return delete e.buffer,e.file=n?gr(n,e.type):void 0,e};this.markUploaded=async(e,{transaction:n}={})=>{let r=await this.getFileRaw(e,{transaction:n});if(!r)throw new Error("File is not in local database");return this.run("files",s=>s.put({...r,remote:"true"}),"readwrite",n)};this.getFileRaw=async(e,{transaction:n}={})=>{let r=await this.run("files",s=>s.get(e),"readonly",n);if(r)return r};this.getFile=async(e,{transaction:n}={})=>{let r=await this.getFileRaw(e,{transaction:n});if(r)return this.hydrateFileData(r)};this.markPendingDelete=async(e,{transaction:n}={})=>{let r=await this.getFileRaw(e,{transaction:n});if(!r)throw new Error("File is not in local database");return this.run("files",s=>s.put({...r,deletedAt:Date.now()}),"readwrite",n)};this.listUnsynced=async()=>(await this.run("files",n=>n.index("remote").getAll("false"),"readonly")).map(this.hydrateFileData);this.iterateOverPendingDelete=(e,n)=>this.iterate("files",r=>r.index("deletedAt").openCursor(IDBKeyRange.lowerBound(0,!0)),(r,s)=>{e(this.hydrateFileData(r),s)},"readwrite",n)}deleteFile(e,{transaction:n}={}){return this.run("files",r=>r.delete(e),"readwrite",n)}};function gr(i,t){return new Blob([i],{type:t})}function br(i){return i.deletedAt!==null&&i.deletedAt<Date.now()-1e3*60*24*3}var ft=class{constructor({db:t,sync:e,context:n,meta:r,config:s={}}){this.files=new Map;this.add=async t=>{let e=t;if(e.remote=!1,this.files.has(e.id))this.files.get(e.id)[ce](e);else{let n=new ne(e.id);n[ce](e),this.files.set(e.id,n)}await this.storage.addFile(e),e.file&&((await this.sync.uploadFile(e)).success?await this.storage.markUploaded(e.id):this.context.log("error","Failed to upload file"))};this.uploadFile=async(t,e=0)=>{let n=await this.sync.uploadFile(t);n.success?await this.storage.markUploaded(t.id):n.retry&&e<5?(this.context.log("error","Error uploading file, retrying..."),setTimeout(this.uploadFile,1e3,t,e+1)):this.context.log("error","Failed to upload file. Not retrying until next sync.")};this.get=t=>{if(this.files.has(t))return this.files.get(t);let e=new ne(t);return this.files.set(t,e),this.load(e),e};this.load=async(t,e=0)=>{if(e>5){t[Te]();return}let n=await this.storage.getFile(t.id);if(n)t[ce](n);else try{let r=await this.sync.getFile(t.id);r.success?(t[ce](r.data),await this.storage.addFile(r.data,{downloadRemote:t.downloadRemote})):(t[Te](),r.retry&&setTimeout(this.load,1e3,t,e+1))}catch(r){this.context.log("error","Failed to load file",r),t[Te](),setTimeout(this.load,1e3,t,e+1)}};this.listUnsynced=async()=>this.storage.listUnsynced();this.onOnlineChange=async t=>{if(t){let e=await this.listUnsynced();await Promise.all(e.map(this.uploadFile))}};this.tryCleanupDeletedFiles=async()=>{let t=0,e=0;await this.storage.iterateOverPendingDelete((n,r)=>{this.config.canCleanupDeletedFile(n)?(t++,r.delete(n.id)):e++}),this.context.log("info",`Cleaned up ${t} files, skipped ${e} files`)};this.handleFileRefsDeleted=async t=>{let e=this.storage.createTransaction(["files"],"readwrite");await Promise.all(t.map(async n=>{try{await this.storage.markPendingDelete(n.id,{transaction:e})}catch(r){this.context.log("error","Failed to mark file for deletion",r)}})),this.context.log("info",`Marked ${t.length} files as pending delete`)};this.storage=new mt(t),this.sync=e,this.context=n,this.meta=r,this.config={canCleanupDeletedFile:br,...s},this.sync.subscribe("onlineChange",this.onOnlineChange),this.meta.subscribe("filesDeleted",this.handleFileRefsDeleted),this.tryCleanupDeletedFiles()}};var le=class{constructor(t){this.value=t}deref(){return this.value}};var oi="@@refresh",yt="@@deepChange";function Ee(i,t){return i[oi](t)}var vr,Sr,K=class i{constructor({oid:t,store:e,fieldSchema:n,cache:r,parent:s,onAllUnsubscribed:a}){this._current=null;this._deleted=!1;this.cachedSnapshot=null;this.cachedDestructure=null;this.cachedDeepUpdatedAt=null;this._updatedAt=null;this[vr]=t=>{let{view:e,deleted:n,lastTimestamp:r}=this.cache.computeView(this.oid);this._current=e;let s=this._deleted&&!n;this._deleted=n,this.cachedDestructure=null,this._updatedAt=r||null,this.cachedDeepUpdatedAt=null,this._deleted?this.events.emit("delete",t):(this.events.emit("change",t),this[yt](this,t)),s&&(this.cachedSnapshot=null,this.events.emit("restore",t))};this[Sr]=(t,e)=>{this.cachedSnapshot=null,this.cachedDeepUpdatedAt=null,this.events.emit("changeDeep",t,e);let n=this.parent?.deref();n&&n[yt](t,e)};this.getChildFieldSchema=t=>{if(this.fieldSchema.type==="object")return this.fieldSchema.properties[t];if(this.fieldSchema.type==="array")return this.fieldSchema.items;if(this.fieldSchema.type==="map")return this.fieldSchema.values;if(this.fieldSchema.type==="any")return this.fieldSchema;throw new Error("Invalid field schema")};this.dispose=()=>{this.events.dispose()};this.subscribe=(t,e)=>this.events.subscribe(t,e);this.addPatches=t=>{this.store.addLocalOperations(t)};this.cloneCurrent=()=>{if(this._current!==void 0)return _(this._current)};this.getSubObject=(t,e)=>{let n=this.getChildFieldSchema(e);return this.cache.getEntity(t,n,this)};this.wrapValue=(t,e)=>{if(E(t)){let n=t.id,r=this.getSubObject(n,e);if(r)return r;throw new Error(`CACHE MISS: Subobject ${n} does not exist on ${this.oid}`)}else if(V(t)){let n=this.store.getFile(t.id);if(n)return n.subscribe("change",()=>{this[yt](this,{isLocal:!1})}),n}return t};this.processInputValue=(t,e)=>{let n=this.getChildFieldSchema(e);return n&&Y(t,n),ie(t,this.store.addFile)};this.get=t=>{if(this.value===void 0||this.value===null)throw new Error("Cannot access deleted entity");let e=this.value[t];return this.wrapValue(e,t)};this.getAll=()=>{if(this.value===void 0||this.value===null)throw new Error("Cannot access deleted entity");if(this.cachedDestructure)return this.cachedDestructure;let t;if(Array.isArray(this.value))t=this.value.map((e,n)=>this.wrapValue(e,n));else{t={};for(let e in this.value)t[e]=this.get(e)}return this.cachedDestructure=t,t};this.getSnapshot=()=>{if(!this.value||this.deleted)return null;if(this.cachedSnapshot)return this.cachedSnapshot;let t;if(Array.isArray(this.value))t=this.value.map((e,n)=>E(e)?this.getSubObject(e.id,n)?.getSnapshot():e);else{t={...this.value};for(let[e,n]of Object.entries(t))E(n)&&(t[e]=this.getSubObject(n.id,e)?.getSnapshot())}return x(t,this.oid),this.cachedSnapshot=t,t};this.keys=()=>Object.keys(this.value||{});this.entries=()=>Object.entries(this.getAll());this.values=()=>Object.values(this.getAll());this.set=(t,e)=>{this.addPatches(this.store.patchCreator.createSet(this.oid,t,this.processInputValue(e,t)))};this.delete=t=>{if(Array.isArray(this.value))this.addPatches(this.store.patchCreator.createListDelete(this.oid,t,1));else{let e=this.getDeleteMode(t);if(!e)throw new Error(`Cannot delete key ${t} - the property is not marked as optional in the schema`);e==="delete"?this.addPatches(this.store.patchCreator.createRemove(this.oid,t)):this.addPatches(this.store.patchCreator.createSet(this.oid,t,null))}};this.getDeleteMode=t=>{if(this.fieldSchema.type==="any"||this.fieldSchema.type==="map")return"delete";if(this.fieldSchema.type==="object"){let e=this.fieldSchema.properties[t];if(!e||e.type==="any")return"delete";if(e.type==="map")return!1;if(e.nullable)return"null"}return!1};this.remove=this.delete.bind(this);this.update=(t,{replaceSubObjects:e=!1,merge:n=!0}={replaceSubObjects:!1,merge:!0})=>{if(!n&&this.fieldSchema.type!=="any"&&this.fieldSchema.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.');for(let[s,a]of Object.entries(t)){let o=this.getChildFieldSchema(s);o&&Y(a,o)}let r=ie(t,this.store.addFile);this.addPatches(this.store.patchCreator.createDiff(this.getSnapshot(),x(r,this.oid),{mergeUnknownObjects:!e,defaultUndefined:n}))};this.getItemRefValue=t=>{if(typeof t=="object"){let e=F(t);if(!e||!this.cache.hasOid(e))throw new Error(`Cannot move object ${JSON.stringify(t)} which does not exist in this list`);return e}else return t};this.push=t=>{this.addPatches(this.store.patchCreator.createListPush(this.oid,this.processInputValue(t,this.value.length)))};this.insert=(t,e)=>{this.addPatches(this.store.patchCreator.createListInsert(this.oid,t,this.processInputValue(e,t)))};this.move=(t,e)=>{this.addPatches(this.store.patchCreator.createListMoveByIndex(this.oid,t,e))};this.moveItem=(t,e)=>{let n=this.getItemRefValue(t);if(E(n))this.addPatches(this.store.patchCreator.createListMoveByRef(this.oid,n,e));else{let r=this.value.indexOf(n);this.addPatches(this.store.patchCreator.createListMoveByIndex(this.oid,r,e))}};this.removeAll=t=>{this.addPatches(this.store.patchCreator.createListRemove(this.oid,this.getItemRefValue(t)))};this.removeFirst=t=>{this.addPatches(this.store.patchCreator.createListRemove(this.oid,this.getItemRefValue(t),"first"))};this.removeLast=t=>{this.addPatches(this.store.patchCreator.createListRemove(this.oid,this.getItemRefValue(t),"last"))};this.add=t=>{this.addPatches(this.store.patchCreator.createListAdd(this.oid,this.processInputValue(t,this.value.length)))};this.has=t=>typeof t=="object"?this.value.some(e=>E(e)?e.id===F(t):(V(e),!1)):this.value.includes(t);this.getAsWrapped=()=>{if(!this.isList)throw new Error("Cannot map items of a non-list");return this.value.map(this.wrapValue)};this.map=t=>this.getAsWrapped().map(t);this.filter=t=>this.getAsWrapped().filter((e,n)=>t(e,n));this.forEach=t=>{this.getAsWrapped().forEach(t)};this.some=t=>this.getAsWrapped().some(t);this.every=t=>this.getAsWrapped().every(t);this.find=t=>this.getAsWrapped().find(t);this.oid=t;let{collection:o}=M(t);this.collection=o,this.parent=s&&new le(s),this.store=e,this.fieldSchema=n,this.cache=r;let{view:c,deleted:l,lastTimestamp:u}=this.cache.computeView(t);if(this._current=c,this._deleted=l,this._updatedAt=u||null,this.cachedDeepUpdatedAt=null,this.events=new b(()=>{this.hasSubscribers||a?.()}),this.oid.includes(".")&&!this.parent)throw new Error("Parent must be provided for sub entities");y(!!n,"Field schema must be provided")}hasSubscribersToDeepChanges(){return this.events.subscriberCount("changeDeep")>0}get hasSubscribers(){if(this.events.totalSubscriberCount()>0)return!0;let t=this.parent?.deref();for(;t;){if(t.hasSubscribersToDeepChanges())return!0;t=t.parent?.deref()}return!1}get deleted(){return this._deleted}get value(){return this._current}get isList(){return Array.isArray(this._current)}get updatedAt(){return this._updatedAt}get deepUpdatedAt(){if(this.cachedDeepUpdatedAt)return this.cachedDeepUpdatedAt;let t=this._updatedAt;return this.isList?this.forEach(e=>{if(e instanceof i){let n=e.deepUpdatedAt;n&&(!t||n>t)&&(t=n)}}):this.values().forEach(e=>{if(e instanceof i){let n=e.deepUpdatedAt;n&&(!t||n>t)&&(t=n)}}),this.cachedDeepUpdatedAt=t,t}get uid(){return this.oid}get length(){return this.value.length}[(vr=oi,Sr=yt,Symbol.iterator)](){let t=0;return{next:()=>t<this.value.length?{value:this.get(t++),done:!1}:{value:void 0,done:!0}}}};var gt=class extends b{constructor({oid:e,store:n,context:r}){super();this.entities=new Map;this.insertLocalOperations=e=>{let n=new Set;for(let r of e){let{oid:s}=r;n.add(s);let a=this.localOperationsMap.get(s)||[];a.push(r),this.localOperationsMap.set(s,a)}for(let r of n){let a=this.entities.get(r)?.deref();a&&(Ee(a,{isLocal:!0}),this.emit(`change:${r}`),this.emit("change:*",r))}};this.insertOperations=(e,n)=>{for(let r of e){let{oid:s}=r;n.affectedOids?.add(s);let a=this.operationsMap.get(s)||[],o=a.findIndex(l=>l.timestamp>=r.timestamp);if(o!==-1){if(a[o].timestamp===r.timestamp)continue;a.splice(o,0,r)}else a.push(r);this.operationsMap.set(s,a);let c=this.localOperationsMap.get(s);c&&this.localOperationsMap.set(s,c.filter(l=>l.timestamp!==r.timestamp))}};this.insertBaselines=(e,{affectedOids:n})=>{for(let r of e){let{oid:s}=r,a=this.baselinesMap.get(s);if(a?.timestamp&&a.timestamp>=r.timestamp)continue;n?.add(s),this.baselinesMap.set(s,r);let o=this.operationsMap.get(s)||[];for(;o[0]?.timestamp<r.timestamp;)o.shift()}};this.addData=({operations:e,baselines:n,reset:r,isLocal:s})=>{r&&(this.operationsMap.clear(),this.baselinesMap.clear());let a={isLocal:s||!1,affectedOids:new Set};if(this.insertBaselines(n,a),this.insertOperations(e,a),r)for(let o of this.entities.values()){let c=o.deref();c&&Ee(c,a)}else for(let o of a.affectedOids){let l=this.entities.get(o)?.deref();l&&(Ee(l,a),this.emit(`change:${o}`),this.emit("change:*",o))}};this.applyOperations=(e,n,r,s)=>{let a,o=this.storeTools.now;for(let c of r)if(!(s&&c.timestamp<=s)){if(En(c.timestamp,o)>0){a=c.timestamp;continue}c.data.op==="delete"?n=!0:(e=X(e,c.data),c.data.op==="initialize"&&(n=!1))}return a&&this.context.globalEvents.emit("futureSeen",a),{view:e,deleted:n,empty:!e&&!r.length}};this.computeView=e=>{let n=this.computeConfirmedView(e),r=this.localOperationsMap.get(e)||[];if(n.empty&&!r.length)return this.context.log("debug",`Entity ${e} accessed with no local data at all`),{view:null,deleted:!0,lastTimestamp:null};let{view:s,deleted:a}=this.applyOperations(n.view,n.deleted,r);return s&&x(s,e),{view:s,deleted:a,lastTimestamp:this.getLastTimestamp(e)}};this.computeConfirmedView=e=>{let n=this.baselinesMap.get(e),r=this.operationsMap.get(e)||[],s=_(n?.snapshot||void 0),a=this.applyOperations(s,!s,r,n?.timestamp);return a.view&&x(a.view,e),a.empty&&this.context.log("debug",`Entity ${e} accessed with no confirmed data`),a};this.getLastTimestamp=e=>{let n=this.localOperationsMap.get(e);n?.length||(n=this.operationsMap.get(e)||[]);let r=null;return n.length?r=n[n.length-1]?.timestamp:r=this.baselinesMap.get(e)?.timestamp??null,r?this.storeTools.time.getWallClockTime(r):null};this.getEntity=(e,n,r)=>{let a=this.entities.get(e)?.deref();return a||(a=new K({oid:e,cache:this,fieldSchema:n,store:this.storeTools,parent:r}),this.entities.set(e,new le(a))),a};this.hasOid=e=>this.operationsMap.has(e)||this.baselinesMap.has(e);this.dispose=()=>{this.entities.forEach(e=>e.deref()?.dispose()),this.entities.clear()};this.reset=(e,n,r=!1)=>{let s={isLocal:!1,affectedOids:new Set};if(this.baselinesMap=new Map(n.map(a=>[a.oid,a])),r)this.operationsMap=new Map;else for(let a of this.operationsMap.keys())this.operationsMap.set(a,this.operationsMap.get(a)?.filter(o=>!o.confirmed)??[]);this.insertOperations(e,s);for(let a of this.entities.keys()){let c=this.entities.get(a)?.deref();c&&(Ee(c,s),this.emit(`change:${a}`),this.emit("change:*",a))}};this.oid=e,this.operationsMap=new Map,this.localOperationsMap=new Map,this.baselinesMap=new Map,this.storeTools={addLocalOperations:n.addLocalOperations,patchCreator:n.meta.patchCreator,addFile:n.files.add,getFile:n.files.get,time:n.meta.time,now:n.meta.now},this.context=r}};var bt="@@default",vt=class{constructor({context:t,meta:e,batchTimeout:n=200,files:r}){this.documentFamilyCaches=new Map;this.unsubscribes=[];this._disposed=!1;this.currentBatchKey=bt;this.setContext=t=>{this.context=t};this.getDocumentSchema=t=>{let{collection:e}=M(t);return this.schema.collections[e]?{type:"object",properties:this.schema.collections[e].fields}:(this.log("warn",`Missing schema for collection: ${e}`),null)};this.refreshFamilyCache=async(t,e=!1)=>{if(this._disposed)return;let n=this.meta.createTransaction(["baselines","operations"]),r=[],s=[];await Promise.all([this.meta.baselines.iterateOverAllForDocument(t.oid,a=>{r.push(a)},{transaction:n,mode:"readwrite"}),this.meta.operations.iterateOverAllOperationsForDocument(t.oid,a=>{a.confirmed=!0,s.push(a)},{transaction:n,mode:"readwrite"})]),t.reset(s,r,e)};this.openFamilyCache=async t=>{let e=w(t),n=this.documentFamilyCaches.get(e);return n||(n=new gt({oid:e,store:this,context:this.context}),this.documentFamilyCaches.set(e,n),await this.refreshFamilyCache(n)),n};this.onEntityChange=async t=>{};this.writeDocumentToStorage=async t=>{if(this._disposed){this.log("warn","EntityStore is disposed, not writing to storage");return}let e=w(t),{id:n,collection:r}=M(e),s=await this.get(e);if(this._disposed){this.log("warn","EntityStore is disposed, not writing to storage");return}let a=s?.getSnapshot();if(a){let o=_(a);Xe(this.schema.collections[r],o),se(o);try{let l=this.db.transaction(r,"readwrite").objectStore(r);await k(l.put(o)),this.log("info","\u{1F4DD}","wrote",r,n,"to storage",o)}catch{this.log("\u26A0\uFE0F CRITICAL: possibly corrupt data couldn't be written to queryable storage. This is probably a bug in verdant! Please report at https://github.com/a-type/verdant/issues",`
|
|
11
|
+
`,"Invalid data:",JSON.stringify(o))}}else{let c=this.db.transaction(r,"readwrite").objectStore(r);await k(c.delete(n)),this.log("info","\u274C","deleted",r,n,"from storage")}};this.get=async t=>{let e=await this.openFamilyCache(t),n=this.getDocumentSchema(t);return n?e.getEntity(t,n):null};this.getCached=t=>{let e=this.documentFamilyCaches.get(t);if(e){let n=this.getDocumentSchema(t);return n?e.getEntity(t,n):null}return null};this.create=async(t,e,n)=>{$e(t);let r=ie(t,this.files.add);x(r,e);let s=this.meta.patchCreator.createInitialize(r,e),a=await this.openFamilyCache(e);a.insertLocalOperations(s),await this.submitOperations(s,n);let o=this.getDocumentSchema(e);if(!o)throw new Error(`Cannot create a document in the ${M(e).collection} collection; it is not defined in the current schema version.`);return a.getEntity(e,o)};this.addOperationsToOpenCaches=async(t,e)=>{let n=Xt(t);Object.keys(n).forEach(s=>{let a=this.documentFamilyCaches.get(s);a&&(this.log("adding",e.confirmed?"confirmed":"unconfirmed","operations to cache",s,n[s].length),e.isLocal?a.insertLocalOperations(n[s]):a.insertOperations(n[s],e))})};this.addBaselinesToOpenCaches=async(t,e)=>{let n=Yt(t);Object.keys(n).forEach(s=>{let a=this.documentFamilyCaches.get(s);a&&(this.log("adding","baselines to cache",s,n[s].length),a.insertBaselines(n[s],e))})};this.addDataToOpenCaches=({baselines:t,operations:e,reset:n,isLocal:r})=>{let s=Yt(t),a=Xt(e),o=Array.from(new Set(Object.keys(s).concat(Object.keys(a))));for(let c of o){let l=this.documentFamilyCaches.get(c);l?(l.addData({operations:a[c]||[],baselines:s[c]||[],reset:n,isLocal:r}),this.log("debug","Added data to cache for",c,a[c]?.length??0,"operations",s[c]?.length??0,"baselines")):this.log("debug","Could not add data to cache for",c,"because it is not open")}return o};this.addData=async({operations:t,baselines:e,reset:n})=>{let r=t;for(let o of r)o.confirmed=!1;let s=[];n?(this.log("Resetting local store to replicate remote synced data",e.length,"baselines, and",t.length,"operations"),await this.meta.reset(),await this.resetStoredDocuments(),s=Array.from(new Set(e.map(o=>w(o.oid)).concat(t.map(o=>w(o.oid)))))):s=this.addDataToOpenCaches({operations:r,baselines:e,reset:n}),await this.meta.insertRemoteBaselines(e),await this.meta.insertRemoteOperations(t),n&&await this.refreshAllCaches(!0);for(let o of s)await this.writeDocumentToStorage(o);let a=Array.from(new Set(s.map(o=>M(o).collection)));this.context.log("changes to collections",a),this.context.entityEvents.emit("collectionsChanged",a)};this.addLocalOperations=async t=>{this.log("Adding local operations",t.length),this.addOperationsToOpenCaches(t,{isLocal:!0,confirmed:!1}),this.operationBatcher.add({key:this.currentBatchKey,items:t})};this.batch=({undoable:t=!0,batchName:e=ze(),max:n=null,timeout:r=this.defaultBatchTimeout}={})=>{let s=this.operationBatcher.add({key:e,max:n,timeout:r,items:[],userData:{undoable:t}}),a={run:o=>(this.currentBatchKey=e,o(),this.currentBatchKey=bt,a),flush:async()=>(await this.operationBatcher.flush(bt),s.flush()),discard:()=>{this.operationBatcher.discard(e)}};return a};this.flushPatches=async()=>{await this.operationBatcher.flush(this.currentBatchKey)};this.flushOperations=async(t,e,n)=>{if(t.length){this.log("Flushing operations",t.length,"to storage / sync");for(let r of t)r.timestamp=this.meta.now;await this.submitOperations(t,n)}};this.submitOperations=async(t,{undoable:e=!0}={})=>{e&&this.undoHistory.addUndo(await this.createUndo(t)),await this.meta.insertLocalOperation(t),this.addDataToOpenCaches({operations:t,baselines:[]});let n=Array.from(new Set(t.map(s=>w(s.oid))));for(let s of n)await this.writeDocumentToStorage(s);let r=new Set(t.map(({oid:s})=>M(s).collection));this.context.log("changes to collections",r),this.context.entityEvents.emit("collectionsChanged",Array.from(r))};this.getInverseOperations=async t=>{let e=Kn(t),n=[],r=()=>this.meta.now;for(let[s,a]of Object.entries(e)){let o=await this.openFamilyCache(s),{view:c,deleted:l}=o.computeConfirmedView(s),u=Jn(s,c,a,r);n.unshift(...u)}return n};this.createUndo=async t=>{let e=await this.getInverseOperations(t);return async()=>{let n=await this.createUndo(e);return await this.submitOperations(e.map(r=>(r.timestamp=this.meta.now,r)),{undoable:!1}),n}};this.delete=async(t,e)=>{y(t===w(t),"Only root documents may be deleted via client methods");let n=await this.meta.getAllDocumentRelatedOids(t),r=this.meta.patchCreator.createDeleteAll(n);await this.submitOperations(r,e)};this.deleteAll=async(t,e)=>{let n=await Promise.all(t.map(s=>this.meta.getAllDocumentRelatedOids(s))),r=this.meta.patchCreator.createDeleteAll(n.flat());await this.submitOperations(r,e)};this.reset=async()=>{this.context.log("warn","Resetting local database"),await this.resetStoredDocuments(),await this.refreshAllCaches(!0)};this.destroy=()=>{this._disposed=!0;for(let t of this.unsubscribes)t();for(let t of this.documentFamilyCaches.values())t.dispose();this.documentFamilyCaches.clear()};this.handleRebase=t=>{this.log("debug","Reacting to rebases",t.length),this.addBaselinesToOpenCaches(t,{isLocal:!0})};this.resetStoredDocuments=async()=>{let t=this.db.transaction(Object.keys(this.schema.collections),"readwrite");for(let e of Object.keys(this.schema.collections)){let n=t.objectStore(e);await k(n.clear())}};this.refreshAllCaches=async(t=!1)=>{for(let[e,n]of this.documentFamilyCaches)await this.refreshFamilyCache(n,t)};this.context=t,this.defaultBatchTimeout=n,this.meta=e,this.files=r,this.operationBatcher=new ae(this.flushOperations),this.operationBatcher.add({key:bt,items:[],max:100,timeout:n,userData:{undoable:!0}}),this.unsubscribes.push(this.meta.subscribe("rebase",this.handleRebase))}get log(){return this.context.log}get db(){return this.context.documentDb}get undoHistory(){return this.context.undoHistory}get schema(){return this.context.schema}};var on=Symbol("handleMessage"),xr,Re=class extends b{constructor({initialPresence:e,updateBatchTimeout:n=200,defaultProfile:r}){super();this._peers={};this._self={profile:{}};this._selfReplicaIds=new Set;this._peerIds=new Array;this.isSelf=(e,n)=>e.id===n.replicaId||this._selfReplicaIds.has(n.replicaId)||this._self.id===n.id;this[xr]=async(e,n)=>{let r=!1,s=new Set(this.peerIds);if(n.type==="presence-changed")this.isSelf(e,n.userInfo)?(this._self=n.userInfo,this._selfReplicaIds.add(n.userInfo.replicaId),this.emit("selfChanged",n.userInfo)):(s.add(n.userInfo.id),this._peers[n.userInfo.id]=n.userInfo,r=!0,this.emit("peerChanged",n.userInfo.id,n.userInfo));else if(n.type==="sync-resp"){this._peers={},s.clear();for(let[a,o]of Object.entries(n.peerPresence))this.isSelf(e,o)?(this._self=o,this._selfReplicaIds.add(o.replicaId),this.emit("selfChanged",o)):(r=!0,s.add(a),this._peers[a]=o,this.emit("peerChanged",a,o))}else if(n.type==="presence-offline"){s.delete(n.userId),this._selfReplicaIds.delete(n.replicaId);let a=this._peers[n.userId];delete this._peers[n.userId],r=!0,this.emit("peerLeft",n.userId,a)}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 n=e.reduce((r,s)=>({...r,...s}),this.self.presence);this.emit("update",n)};this.self.presence=e,this.self.profile=r,this._updateBatcher=new ae(this.flushPresenceUpdates),this._updateBatch=this._updateBatcher.add({max:25,timeout:n,items:[],key:"default"})}static{xr=on}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 St=class{constructor({endpointProvider:t,log:e}){this.uploadFile=async t=>{let e=t.file;if(!e)throw new Error("Cannot upload a non-local file");let{files:n,token:r}=await this.endpointProvider.getEndpoints(),s=new window.FormData;s.append("file",e);try{let a=await fetch(n+`/${t.id}`,{method:"POST",body:s,credentials:"include",headers:{Authorization:`Bearer ${r}`}});return a.ok?{success:!0,retry:!1}:(this.log("error","File upload failed",a.status,await a.text()),{success:!1,retry:a.status>=500})}catch(a){return this.log("error","File upload failed",a),{success:!1,retry:!0}}};this.getFile=async t=>{let{files:e,token:n}=await this.endpointProvider.getEndpoints();try{let r=await fetch(e+`/${t}`,{method:"GET",credentials:"include",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`}});return r.ok?{success:!0,data:await r.json()}:(this.log("error","File information fetch failed",r.status,await r.text()),{success:!1,retry:r.status>=500||r.status===404})}catch(r){return this.log("error","File information fetch failed",r),{success:!1,retry:!0}}};this.endpointProvider=t,this.log=e}};var de=class extends b{constructor({interval:e=15*1e3,deadlineLength:n=3*1e3,restartOnTabFocus:r=!0}={}){super();this.nextBeat=null;this.deadline=null;this.keepAlive=()=>{this.deadline&&(clearTimeout(this.deadline),this.deadline=null,this.start())};this.start=(e=!1)=>{this.stop(),e?this.beat():this.nextBeat=setTimeout(this.beat,this._interval)};this.stop=()=>{this.nextBeat&&clearTimeout(this.nextBeat),this.deadline&&clearTimeout(this.deadline)};this.beat=async()=>{this.emit("beat"),this.deadline=setTimeout(this.onDeadline,this.deadlineLength)};this.onDeadline=()=>{this.deadline=null,this.emit("missed")};this.setInterval=e=>{this._interval=e};this._interval=e,this.deadlineLength=n,typeof window<"u"&&r&&window.addEventListener("pageshow",()=>this.start(!0))}get interval(){return this._interval}};var xt=class extends b{constructor({endpointProvider:e,meta:n,presence:r,interval:s=15*1e3,log:a=()=>{}}){super();this.mode="pull";this._isConnected=!1;this._status="paused";this._hasSynced=!1;this.setInterval=e=>{this.heartbeat.setInterval(e)};this.sendRequest=async e=>{this.log("Sending sync request",e);try{let{http:n,token:r}=await this.endpointProvider.getEndpoints(),s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({messages:e}),credentials:"include"});if(s.ok){this.heartbeat.keepAlive();let a=await s.json();for(let o of a.messages)this.handleServerMessage(o);this._isConnected||(this._isConnected=!0,this.emit("onlineChange",!0))}else this.log("Sync request failed",s.status,await s.text()),this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1)),s.status>=500&&this.heartbeat.keepAlive()}catch(n){this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1)),this.log(n),this.heartbeat.keepAlive()}};this.handleServerMessage=async e=>{e.type==="sync-resp"&&(e.ackThisNonce&&(this.log("Sending sync ack",e.ackThisNonce),this.sendRequest([await this.meta.messageCreator.createAck(e.ackThisNonce)])),this._hasSynced=!0),this.emit("message",e)};this.send=e=>{switch(e.type){case"presence-update":case"sync":case"heartbeat":return this.sendRequest([e]);case"op":if(this._hasSynced)return this.sendRequest([e]);break}};this.dispose=()=>{};this.onHeartbeat=async()=>{this.sendRequest([await this.meta.messageCreator.createPresenceUpdate(this.presence.self.presence),await this.meta.messageCreator.createSyncStep1()])};this.onHeartbeatMissed=async()=>{this.emit("onlineChange",!1),this.log("Missed heartbeat"),this._isConnected=!1};this.log=a,this.meta=n,this.presence=r,this.endpointProvider=e,this.heartbeat=new de({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)}get isConnected(){return this._isConnected}get status(){return this._status}};function cn(i){this.message=i}cn.prototype=new Error,cn.prototype.name="InvalidCharacterError";var ci=typeof window<"u"&&window.atob&&window.atob.bind(window)||function(i){var t=String(i).replace(/=+$/,"");if(t.length%4==1)throw new cn("'atob' failed: The string to be decoded is not correctly encoded.");for(var e,n,r=0,s=0,a="";n=t.charAt(s++);~n&&(e=r%4?64*e+n:n,r++%4)?a+=String.fromCharCode(255&e>>(-2*r&6)):0)n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(n);return a};function Or(i){var t=i.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(ci(e).replace(/(.)/g,function(n,r){var s=r.charCodeAt(0).toString(16).toUpperCase();return s.length<2&&(s="0"+s),"%"+s}))}(t)}catch{return ci(t)}}function Ot(i){this.message=i}function wr(i,t){if(typeof i!="string")throw new Ot("Invalid token specified");var e=(t=t||{}).header===!0?0:1;try{return JSON.parse(Or(i.split(".")[e]))}catch(n){throw new Ot("Invalid token specified: "+n.message)}}Ot.prototype=new Error,Ot.prototype.name="InvalidTokenError";var li=wr;var wt=class{constructor(t){this.config=t;this.cached=null;this.type=0;this.getEndpoints=async()=>{if(this.cached)return this.cached;let t;this.config.fetchAuth?t=await this.config.fetchAuth():t=await fetch(this.config.authEndpoint,{credentials:"include"}).then(o=>{if(o.ok)return o.json();throw new Error(`Auth endpoint returned non-200 response: ${o.status}`)}),y(t.accessToken,"No access token provided from auth endpoint");let e=li(t.accessToken);y(e.url,"No sync endpoint provided from auth endpoint"),y(e.type!==void 0,"No replica type provided from auth endpoint"),this.type=parseInt(e.type+"");let n=new URL(e.url);n.protocol=n.protocol.replace("ws","http");let r=n.toString();n.protocol=n.protocol.replace("http","ws");let s=n.toString(),a=e.file;if(!a){let o=new URL(r);o.pathname=o.pathname+"/files",a=o.toString()}return this.cached={http:r,websocket:s,files:a,token:t.accessToken},this.cached};if(!t.authEndpoint&&!t.fetchAuth)throw new Error("Either authEndpoint or fetchAuth must be provided to ServerSyncEndpointProvider")}};var It=class extends b{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}},Ct=class{constructor(t,e){this.current=0;this.next=()=>{this.current=Math.min(this.max,this.current*this.factor)};this.reset=()=>{this.current=0};this.max=t,this.factor=e}};var Dt=class extends b{constructor({endpointProvider:e,meta:n,presence:r,log:s}){super();this.socket=null;this.connectQueue=[];this.syncQueue=[];this._status="paused";this.synced=!1;this.hasStartedSync=!1;this.mode="realtime";this.log=(...e)=>{};this.heartbeat=new de;this.reconnectScheduler=new It(new Ct(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),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=>{let n=JSON.parse(e.data);switch(n.type){case"sync-resp":if(n.ackThisNonce&&this.send(await this.meta.messageCreator.createAck(n.ackThisNonce)),this.hasStartedSync=!0,this.synced=!0,this.syncQueue.length){for(let r of this.syncQueue)this.send(r);this.syncQueue=[]}case"need-since":case"presence-changed":case"presence-offline":this.emit("message",n);break;case"op-re":if(!this.hasStartedSync){this.log("Skipping op-re message because sync hasn't started yet",n);break}this.emit("message",n);break;case"heartbeat-response":this.heartbeat.keepAlive(),this.emit("message",n);break;default:this.synced&&this.emit("message",n);break}};this.onError=e=>{this.log(e),this.reconnectScheduler.next(),this.log("Attempting reconnect to websocket sync")};this.onClose=e=>{this.log("Sync disconnected"),this.onOnlineChange(!1),this.onError(e)};this.initializeSocket=async()=>{let e=await this.endpointProvider.getEndpoints();return this.socket=new WebSocket(e.websocket,["Bearer",e.token]),this.socket.addEventListener("message",this.onMessage),this.socket.addEventListener("open",this.onOpen),this.socket.addEventListener("error",this.onError),this.socket.addEventListener("close",this.onClose),this.socket};this.sendHeartbeat=async()=>{this.send(await this.meta.messageCreator.createHeartbeat())};this.reconnect=()=>{this.stop(),this.start()};this.canSkipSyncWait=e=>e.type==="sync"||e.type==="presence-update"||e.type==="sync-ack"||e.type==="heartbeat";this.send=e=>{this.status==="active"&&(!this.hasStartedSync&&!this.canSkipSyncWait(e)||(this.canSkipSyncWait(e)?this.socket?.readyState===WebSocket.OPEN?(this.log("Sending message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e))):(this.log("Enqueueing message until socket is open",JSON.stringify(e,null,2)),this.connectQueue.push(e)):this.synced?this.socket?.readyState===WebSocket.OPEN&&(this.log("Sending message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e))):this.hasStartedSync&&(this.log("Enqueueing message until synced",JSON.stringify(e,null,2)),this.syncQueue.push(e))))};this.dispose=()=>{this.socket?.removeEventListener("close",this.onClose),this.socket?.close()};this.start=()=>{this.socket||(this.initializeSocket(),this._status="active")};this.stop=()=>{this.dispose(),this.socket=null,this._status="paused"};this.log=s||this.log,this.endpointProvider=e,this.meta=n,this.presence=r,this.reconnectScheduler.subscribe("trigger",this.initializeSocket),this.heartbeat.subscribe("beat",this.sendHeartbeat)}get isConnected(){return this.socket?.readyState===WebSocket.OPEN}get status(){return this._status}};var Pt=class extends b{constructor(){super(...arguments);this.mode="pull";this.dispose=()=>{};this.isConnected=!1;this.status="paused";this.pullInterval=0;this.presence=new Re({initialPresence:{},defaultProfile:{}});this.uploadFile=async()=>({success:!1,retry:!1});this.getFile=async()=>({success:!1,retry:!1})}send(){}start(){}stop(){}reconnect(){}setMode(){}setPullInterval(){}},ue=class extends b{constructor({authEndpoint:e,fetchAuth:n,initialPresence:r,automaticTransportSelection:s=!0,autoStart:a,initialTransport:o,pullInterval:c,presenceUpdateBatchTimeout:l,defaultProfile:u,useBroadcastChannel:d},{meta:p,log:g,onData:I}){super();this.broadcastChannel=null;this._activelySyncing=!1;this.handleBroadcastChannelMessage=e=>{e.data.type==="sync"&&this.handleMessage(e.data.message)};this.handleMessage=async e=>{if(e.type==="op-re"||e.type==="sync-resp")for(let n of e.operations)this.meta.time.update(n.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)}this.broadcastChannel?.postMessage({type:"sync",message:e}),this.presence[on](await this.meta.localReplica.get(),e)};this.handleOnlineChange=e=>{this.emit("onlineChange",e)};this.handlePresenceUpdate=async e=>{this.send(await this.meta.messageCreator.createPresenceUpdate(e))};this.setMode=e=>{if(e==="realtime"&&!this.canDoRealtime)throw new Error("Cannot switch to realtime mode, because the current auth token does not allow it");let n;e==="realtime"?n=this.webSocketSync:n=this.pushPullSync,n!==this.activeSync&&(this.log("switching to",e,"mode"),this.activeSync.status==="active"&&n.start(),this.activeSync.stop(),this.activeSync=n)};this.setPullInterval=e=>{this.pushPullSync.setInterval(e)};this.send=e=>{if(this.activeSync.status==="active")return this.activeSync.send(e)};this.uploadFile=async e=>this.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.dispose=()=>{this.webSocketSync.dispose(),this.pushPullSync.dispose()};this.reconnect=()=>this.activeSync.reconnect();if(this.meta=p,this.onData=I,this.log=g||(()=>{}),this.presence=new Re({initialPresence:r,defaultProfile:u,updateBatchTimeout:l}),this.endpointProvider=new wt({authEndpoint:e,fetchAuth:n}),this.webSocketSync=new Dt({endpointProvider:this.endpointProvider,meta:p,presence:this.presence,log:this.log}),this.pushPullSync=new xt({endpointProvider:this.endpointProvider,meta:p,presence:this.presence,log:this.log,interval:c}),this.fileSync=new St({endpointProvider:this.endpointProvider,log:this.log}),d&&"BroadcastChannel"in window&&(this.broadcastChannel=new BroadcastChannel("verdant"),this.broadcastChannel.addEventListener("message",this.handleBroadcastChannelMessage)),o==="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 h=()=>{m&&clearTimeout(m);let v=Object.keys(this.presence.peers).length>0||s!=="peers-only"&&this.presence.selfReplicaIds.size>1;v&&this.mode==="pull"?this.setMode("realtime"):!v&&this.mode==="realtime"&&(m=setTimeout(()=>{Object.keys(this.presence.peers).length===0&&this.setMode("pull")},1e3))},m;this.presence.subscribe("peersChanged",h),s!=="peers-only"&&this.presence.subscribe("selfChanged",h)}a&&this.start()}get canDoRealtime(){return this.endpointProvider.type===0||this.endpointProvider.type===2||this.endpointProvider.type===5}get syncing(){return this._activelySyncing}get pullInterval(){return this.pushPullSync.interval}get isConnected(){return this.activeSync.isConnected}get status(){return this.activeSync.status}get mode(){return this.activeSync.mode}};var pe=class{constructor(){this._disposes=[];this.disposed=!1;this.dispose=()=>{this.disposed=!0,this._disposes.forEach(t=>t()),this._disposes=[]};this.addDispose=t=>{this._disposes.push(t)}}};function Cr(i){return i!==null}function ln(i){return Array.isArray(i)?i.map(ln).filter(Cr):i instanceof K&&i.deleted?null:i}function W(i,t){return!i&&!t||i&&t&&ve(i)===ve(t)}var dn=Symbol("ON_ALL_UNSUBSCRIBED"),j=Symbol("UPDATE"),Dr,U=class extends pe{constructor({initial:e,context:n,collection:r,key:s,shouldUpdate:a}){super();this._internalUnsubscribes=[];this._status="initial";this._executionPromise=null;this.setValue=e=>{this._rawValue=e,this.subscribeToDeleteAndRestore(this._rawValue),this._value=ln(e),this._status="ready",this._events.emit("change",this._value)};this.refreshValue=()=>{this.setValue(this._rawValue)};this.subscribeToDeleteAndRestore=e=>{for(;this._internalUnsubscribes.length;)this._internalUnsubscribes.pop()?.();Array.isArray(e)?e.forEach(n=>{n instanceof K&&(this._internalUnsubscribes.push(n.subscribe("delete",this.refreshValue)),this._internalUnsubscribes.push(n.subscribe("restore",this.refreshValue)))}):e instanceof K&&(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),this._executionPromise);this[Dr]=e=>{this._allUnsubscribedHandler=e};this._rawValue=e,this._value=e,this._events=new b(c=>{c==="change"&&this._allUnsubscribedHandler?.(this)}),this.context=n,this.key=s,this.collection=r;let o=a||(c=>c.includes(r));this.addDispose(this.context.entityEvents.subscribe("collectionsChanged",c=>{o(c)&&(this.context.log("info","Updating query",this.key),this.execute())}))}static{Dr=dn}get current(){return this._value}get resolved(){return this.status==="ready"?Promise.resolve(this._value):this._executionPromise??this.execute()}get subscribed(){return this._events.totalSubscriberCount()>0}get status(){return this._status}subscribe(e,n){if(n===void 0&&typeof e=="function")return this.resolved,this._events.subscribe("change",e);if(e==="change"&&n!==void 0)return this.resolved,this._events.subscribe("change",n);if(e==="statusChange"&&typeof n=="function")return this._events.subscribe(e,n);throw new Error("Invalid invocation of Query.subscribe")}};var Tt=class extends U{constructor({id:e,hydrate:n,...r}){super({initial:null,...r});this.run=async()=>{let e=await this.hydrate(this.oid);this.setValue(e)};this.oid=T(r.collection,e),this.hydrate=n}};var Pr,Et=class extends U{constructor({index:e,hydrate:n,...r}){super({initial:null,...r});this.run=async()=>{let e=await lt({collection:this.collection,index:this.index,context:this.context});this.setValue(e?await this.hydrate(e):null)};this[Pr]=e=>{W(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n}static{Pr=j}};var Tr,Rt=class extends U{constructor({index:e,hydrate:n,pageSize:r,page:s,...a}){super({initial:[],...a});this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:n}=await Ce({collection:this.collection,index:this.index,context:this.context,limit:this._pageSize,offset:this._page*this._pageSize});this._hasNextPage=n,this.setValue(await Promise.all(e.map(this.hydrate)))};this.nextPage=async()=>{this.hasNextPage&&(this._page++,await this.run())};this.previousPage=async()=>{this._page!==0&&(this._page--,await this.run())};this.setPage=async e=>{this._page=e,await this.run()};this[Tr]=e=>{W(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n,this._pageSize=r,this._page=s}static{Tr=j}get pageSize(){return this._pageSize}get page(){return this._page}get hasNextPage(){return this._hasNextPage}get hasPreviousPage(){return this._page>0}};var Er,_t=class extends U{constructor({hydrate:e,pageSize:n,index:r,...s}){super({initial:[],...s});this._upToPage=1;this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:n}=await Ce({collection:this.collection,context:this.context,limit:this._pageSize*this._upToPage,offset:0,index:this.index});this._hasNextPage=n,this.setValue(await Promise.all(e.map(this.hydrate)))};this.loadMore=async()=>{let{result:e,hasNextPage:n}=await Ce({collection:this.collection,context:this.context,limit:this._pageSize,offset:this._pageSize*this._upToPage,index:this.index});this._hasNextPage=n,this._upToPage++,this.setValue([...this.current,...await Promise.all(e.map(this.hydrate))])};this[Er]=e=>{W(this.index,e)||(this.index=e,this.execute())};this.index=r,this.hydrate=e,this._pageSize=n}static{Er=j}get pageSize(){return this._pageSize}get hasMore(){return this._hasNextPage}};var Rr,kt=class extends U{constructor({index:e,hydrate:n,...r}){super({initial:[],...r});this.run=async()=>{let e=await dt({collection:this.collection,index:this.index,context:this.context});this.setValue(await Promise.all(e.map(this.hydrate)))};this[Rr]=e=>{W(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n}static{Rr=j}};var Ft=class{constructor({collection:t,cache:e,entities:n,context:r,documentManager:s}){this.serializeIndex=t=>t?ve(t):"";this.get=t=>{let e=`get:${this.collection}:${t}`;return this.cache.getOrSet(e,()=>new Tt({id:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:e}))};this.findOne=({index:t,key:e}={})=>{let n=e||`findOne:${this.collection}:${this.serializeIndex(t)}`;return this.cache.getOrSet(n,()=>new Et({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:n}),r=>{r[j](t)})};this.findAll=({index:t,key:e}={})=>{let n=e||`findAll:${this.collection}:${this.serializeIndex(t)}`;return this.cache.getOrSet(n,()=>new kt({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:n}),r=>{r[j](t)})};this.findPage=({index:t,pageSize:e,page:n,key:r})=>{let s=r||`findPage:${this.collection}:${this.serializeIndex(t)}:${e}`;return this.cache.getOrSet(s,()=>new Rt({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:s,pageSize:e,page:n}),a=>{a[j](t)})};this.findAllInfinite=({index:t,pageSize:e,key:n})=>{let r=n||`findAllInfinite:${this.collection}:${this.serializeIndex(t)}:${e}`;return this.cache.getOrSet(r,()=>new _t({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:r,pageSize:e}),s=>{s[j](t)})};this.cache=e,this.collection=t,this.hydrate=n.get,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 At=class extends pe{constructor({evictionTime:e=5*1e3,context:n}){super();this._cache=new Map;this.onQueryUnsubscribed=e=>{setTimeout(()=>{e.subscribed||this._cache.get(e.key)===e&&this._cache.delete(e.key)},this._evictionTime)};this._evictionTime=e,this.context=n}get(e){return this._cache.get(e)||null}set(e){return this._cache.set(e.key,e),e[dn](this.onQueryUnsubscribed),e}getOrSet(e,n,r){let s=this.get(e);return s?(r?.(s),s):this.set(n())}};var he=class extends b{constructor(e,n,r){super();this.config=e;this.context=n;this.addData=e=>this._entities.addData(e);this.stats=async()=>{let e=Object.keys(this.schema.collections),n={};for(let l of e)n[l]=await we(this.documentDb,l);let r=await this.meta.stats(),s=typeof navigator<"u"&&typeof navigator.storage<"u"&&"estimate"in navigator.storage?await navigator.storage.estimate():void 0,a=Object.values(n).reduce((l,{size:u})=>l+u,0),o=r.baselinesSize.size+r.operationsSize.size,c=o/a;return{collections:n,meta:r,storage:s,totalMetaSize:o,totalCollectionsSize:a,metaToDataRatio:c,quotaUsage:s?.usage&&s?.quota?s.usage/s.quota:void 0}};this.close=async()=>{await this.entities.flushPatches(),this.sync.stop(),this.sync.dispose(),this.meta.close(),this._entities.destroy(),await Ie(this.documentDb),await Ie(this.metaDb),this.context.log?.("Client closed")};this.__dangerous__resetLocal=async()=>{this.sync.stop(),await et(this.namespace,indexedDB)};this.export=async()=>{let e=await this.meta.export();return Buffer.from(JSON.stringify(e))};this.import=async e=>{this.context.log("Importing data..."),await Ie(this.context.documentDb);let n=JSON.parse(e.toString());await this.meta.resetFrom(n);let r=n.schema.version,s=indexedDB.deleteDatabase([this.namespace,"collections"].join("_"));await new Promise((o,c)=>{s.onsuccess=o,s.onerror=c});let a=this.context.schema;this.context.schema=n.schema,this.context.documentDb=await Pe({meta:this.meta,migrations:this.config.migrations,context:this.context,version:r}),this.context.log("Re-initializing data from imported data..."),await this._entities.addData({operations:n.operations,baselines:n.baselines,reset:!0}),await Ie(this.context.documentDb),this.context.log("Migrating up to latest schema..."),this.context.schema=a,this.context.documentDb=await Pe({meta:this.meta,migrations:this.config.migrations,context:this.context,version:a.version})};this.meta=r.meta,this.collectionNames=Object.keys(n.schema.collections),this._sync=this.config.syncConfig?new ue(this.config.syncConfig,{meta:this.meta,onData:this.addData,log:this.context.log}):new Pt,this._fileManager=new ft({db:this.metaDb,sync:this.sync,context:this.context,config:this.config.files,meta:this.meta}),this._entities=new vt({context:this.context,meta:this.meta,files:this._fileManager}),this._queryCache=new At({context:n}),this._documentManager=new ht(this.meta,this.schema,this._entities);let s=jn(()=>{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[a,o]of Object.entries(n.schema.collections)){let c=o,l=c.pluralName??c.name+"s";y(l===a,`The key of the collection in the schema must be the plural of the name (expected: "${l}")`),this[l]=new Ft({collection:l,cache:this._queryCache,context:this.context,entities:this.entities,documentManager:this.documentManager})}}get sync(){return this._sync}get entities(){return this._entities}get documentManager(){return this._documentManager}get documentDb(){return this.context.documentDb}get metaDb(){return this.context.metaDb}get schema(){return this.context.schema}get namespace(){return this.context.namespace}get undoHistory(){return this.context.undoHistory}get presence(){return this.sync.presence}get batch(){return this.entities.batch}};var Mt=class{constructor(t){this.init=t;this._initializing=!1;this.initialize=async t=>{if(typeof window>"u"&&!t.indexedDb)throw new Error("A verdant client was initialized in an environment without IndexedDB. If you are using verdant in a server-rendered framework, you must enforce that all clients are initialized on the client-side, or you must provide some mock interface of IDBFactory to the ClientDescriptor options.");if(this._initializing||this._resolvedValue)return this._readyPromise;this._initializing=!0;try{let e=[t.namespace,"meta"].join("_"),{db:n}=await Yn(this._namespace,{indexedDB:t.indexedDb,log:t.log,databaseName:e}),r={namespace:this._namespace,metaDb:n,schema:t.schema,log:t.log||(()=>{}),undoHistory:t.undoHistory||new pt,entityEvents:new b,globalEvents:new b},s=new ot({context:r,disableRebasing:t.disableRebasing});await s.updateSchema(t.schema,t.overrideSchemaConflict);let a=await Pe({context:r,version:t.schema.version,meta:s,migrations:t.migrations,indexedDB:t.indexedDb}),o=Object.assign(r,{documentDb:a}),c=new he({syncConfig:t.sync,migrations:t.migrations,files:t.files},o,{meta:s});return this.resolveReady(c),this._resolvedValue=c,c}catch(e){throw this.rejectReady(e),e}finally{this._initializing=!1}};this.open=()=>this.initialize(this.init);this.close=async()=>{this._resolvedValue&&this._resolvedValue.close(),this._initializing&&(await this._readyPromise).close()};this.__dangerous__resetLocal=async()=>{await et(this.namespace)};this._readyPromise=new Promise((e,n)=>{this.resolveReady=e,this.rejectReady=n}),this._namespace=t.namespace}get namespace(){return this._namespace}get current(){return this._resolvedValue}get readyPromise(){return this._readyPromise}get schema(){return this.init.schema}};window.Verdant=un;
|
|
12
12
|
//# sourceMappingURL=index.js.map
|