@verdant-web/store 2.5.8 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/dist/bundle/index.js +15 -10
  2. package/dist/bundle/index.js.map +4 -4
  3. package/dist/cjs/__tests__/queries.test.js +2 -0
  4. package/dist/cjs/__tests__/queries.test.js.map +1 -1
  5. package/dist/cjs/client/Client.js +23 -11
  6. package/dist/cjs/client/Client.js.map +1 -1
  7. package/dist/cjs/client/ClientDescriptor.d.ts +3 -0
  8. package/dist/cjs/client/ClientDescriptor.js +100 -36
  9. package/dist/cjs/client/ClientDescriptor.js.map +1 -1
  10. package/dist/cjs/entities/DocumentFamiliyCache.d.ts +20 -1
  11. package/dist/cjs/entities/DocumentFamiliyCache.js +33 -18
  12. package/dist/cjs/entities/DocumentFamiliyCache.js.map +1 -1
  13. package/dist/cjs/entities/EntityStore.d.ts +2 -1
  14. package/dist/cjs/entities/EntityStore.js +36 -7
  15. package/dist/cjs/entities/EntityStore.js.map +1 -1
  16. package/dist/cjs/idb.d.ts +2 -0
  17. package/dist/cjs/idb.js +9 -1
  18. package/dist/cjs/idb.js.map +1 -1
  19. package/dist/cjs/metadata/openMetadataDatabase.d.ts +11 -2
  20. package/dist/cjs/metadata/openMetadataDatabase.js +56 -3
  21. package/dist/cjs/metadata/openMetadataDatabase.js.map +1 -1
  22. package/dist/cjs/migration/db.d.ts +1 -1
  23. package/dist/cjs/migration/db.js +5 -2
  24. package/dist/cjs/migration/db.js.map +1 -1
  25. package/dist/cjs/migration/openDatabase.d.ts +8 -0
  26. package/dist/cjs/migration/openDatabase.js +216 -153
  27. package/dist/cjs/migration/openDatabase.js.map +1 -1
  28. package/dist/cjs/queries/BaseQuery.js +12 -1
  29. package/dist/cjs/queries/BaseQuery.js.map +1 -1
  30. package/dist/cjs/sync/WebSocketSync.js +4 -3
  31. package/dist/cjs/sync/WebSocketSync.js.map +1 -1
  32. package/dist/esm/__tests__/queries.test.js +2 -0
  33. package/dist/esm/__tests__/queries.test.js.map +1 -1
  34. package/dist/esm/client/Client.js +23 -11
  35. package/dist/esm/client/Client.js.map +1 -1
  36. package/dist/esm/client/ClientDescriptor.d.ts +3 -0
  37. package/dist/esm/client/ClientDescriptor.js +104 -40
  38. package/dist/esm/client/ClientDescriptor.js.map +1 -1
  39. package/dist/esm/entities/DocumentFamiliyCache.d.ts +20 -1
  40. package/dist/esm/entities/DocumentFamiliyCache.js +33 -18
  41. package/dist/esm/entities/DocumentFamiliyCache.js.map +1 -1
  42. package/dist/esm/entities/EntityStore.d.ts +2 -1
  43. package/dist/esm/entities/EntityStore.js +36 -7
  44. package/dist/esm/entities/EntityStore.js.map +1 -1
  45. package/dist/esm/idb.d.ts +2 -0
  46. package/dist/esm/idb.js +6 -0
  47. package/dist/esm/idb.js.map +1 -1
  48. package/dist/esm/metadata/openMetadataDatabase.d.ts +11 -2
  49. package/dist/esm/metadata/openMetadataDatabase.js +54 -2
  50. package/dist/esm/metadata/openMetadataDatabase.js.map +1 -1
  51. package/dist/esm/migration/db.d.ts +1 -1
  52. package/dist/esm/migration/db.js +5 -2
  53. package/dist/esm/migration/db.js.map +1 -1
  54. package/dist/esm/migration/openDatabase.d.ts +8 -0
  55. package/dist/esm/migration/openDatabase.js +213 -151
  56. package/dist/esm/migration/openDatabase.js.map +1 -1
  57. package/dist/esm/queries/BaseQuery.js +12 -1
  58. package/dist/esm/queries/BaseQuery.js.map +1 -1
  59. package/dist/esm/sync/WebSocketSync.js +4 -3
  60. package/dist/esm/sync/WebSocketSync.js.map +1 -1
  61. package/dist/tsconfig-cjs.tsbuildinfo +1 -1
  62. package/dist/tsconfig.tsbuildinfo +1 -1
  63. package/package.json +2 -2
  64. package/src/__tests__/queries.test.ts +3 -0
  65. package/src/client/Client.ts +26 -12
  66. package/src/client/ClientDescriptor.ts +145 -49
  67. package/src/entities/DocumentFamiliyCache.ts +59 -19
  68. package/src/entities/EntityStore.ts +45 -6
  69. package/src/idb.ts +10 -0
  70. package/src/metadata/openMetadataDatabase.ts +96 -13
  71. package/src/migration/db.ts +14 -1
  72. package/src/migration/openDatabase.ts +344 -203
  73. package/src/queries/BaseQuery.ts +14 -1
  74. package/src/sync/WebSocketSync.ts +1 -0
@@ -1,12 +1,17 @@
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 _(i){return E(i)||V(i)}function An(i,t){return i===t?!0:!(!_(i)||!_(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 R(i,t=!0){if(S(i)||Array.isArray(i)){let e=F(i),n;if(Array.isArray(i))n=i.map(r=>R(r,t));else{n={};for(let[r,s]of Object.entries(i))n[r]=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={".":"&dot;","/":"&slash;",":":"&colon;"};function Ln(i){return i.replace(/[/]/g,qt["/"]).replace(/[:]/g,qt[":"]).replace(/[.]/g,qt["."])}function Nn(i){return i.replace(/&slash;/g,"/").replace(/&colon;/g,":").replace(/&dot;/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)&&!_(n)&&(Vn(n,e,t),re(n,t))}else if(S(i)&&!_(i))for(let n of Object.keys(i))S(i[n])&&!_(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)&&!_(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 _(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)&&!_(i)}function Li(i,t){return i===t?!0:_(i)&&_(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=R(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&&_(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 R(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)||_(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=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,n={})=>{let r=w(e);y(r===e,"Must be root document OID");let s=this.db.transaction(["baselines","operations"],"readwrite"),a=await this.baselines.getAllForDocument(r,{transaction:s}),o=new Map;for(let l of a)l.snapshot&&x(l.snapshot,l.oid),o.set(l.oid,l.snapshot);await this.operations.iterateOverAllOperationsForDocument(r,l=>{let u=o.get(l.oid)||void 0,d=X(u,l.data);d&&x(d,l.oid),o.set(l.oid,d)},{transaction:s,to:n.to||this.now});let c=o.get(r);return c&&Je(c,o),c};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}
1
+ "use strict";var ir=Object.create;var bn=Object.defineProperty;var rr=Object.getOwnPropertyDescriptor;var sr=Object.getOwnPropertyNames;var or=Object.getPrototypeOf,ar=Object.prototype.hasOwnProperty;var We=(i,t)=>()=>(t||i((t={exports:{}}).exports,t),t.exports),cr=(i,t)=>{for(var e in t)bn(i,e,{get:t[e],enumerable:!0})},lr=(i,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of sr(t))!ar.call(i,r)&&r!==e&&bn(i,r,{get:()=>t[r],enumerable:!(n=rr(t,r))||n.enumerable});return i};var dt=(i,t,e)=>(e=i!=null?ir(or(i)):{},lr(t||!i||!i.__esModule?bn(e,"default",{value:i,enumerable:!0}):e,i));var vn=We((Is,ei)=>{ei.exports=function(t,e){var n="000000000"+t;return n.substr(n.length-e)}});var ni=We((Ds,ti)=>{var dr=vn(),ur=typeof window=="object"?window:self,pr=Object.keys(ur).length,fr=navigator.mimeTypes?navigator.mimeTypes.length:0,hr=dr((fr+navigator.userAgent.length).toString(36)+pr.toString(36),4);ti.exports=function(){return hr}});var oi=We((Cs,si)=>{var wn,ii=typeof window<"u"&&(window.crypto||window.msCrypto)||typeof self<"u"&&self.crypto;ii?(ri=Math.pow(2,32)-1,wn=function(){return Math.abs(ii.getRandomValues(new Uint32Array(1))[0]/ri)}):wn=Math.random;var ri;si.exports=wn});var ft=We((Es,di)=>{var ut=ni(),ai=vn(),mr=oi(),He=0,xn=4,pt=36,ci=Math.pow(pt,xn);function Sn(){return ai((mr()*ci<<0).toString(pt),xn)}function li(){return He=He<ci?He:0,He++,He-1}function Qe(){var i="c",t=new Date().getTime().toString(pt),e=ai(li().toString(pt),xn),n=ut(),r=Sn()+Sn();return i+t+e+n+r}Qe.slug=function(){var t=new Date().getTime().toString(36),e=li().toString(36).slice(-4),n=ut().slice(0,1)+ut().slice(-1),r=Sn().slice(-2);return t.slice(-2)+e+n+r};Qe.isCuid=function(t){return typeof t!="string"?!1:!!t.startsWith("c")};Qe.isSlug=function(t){if(typeof t!="string")return!1;var e=t.length;return e>=7&&e<=10};Qe.fingerprint=ut;di.exports=Qe});var Di=We((Oi,Ii)=>{(function(i){var t;typeof Oi=="object"?Ii.exports=i():typeof define=="function"&&define.amd?define(i):(typeof window<"u"?t=window:typeof global<"u"?t=global:typeof self<"u"&&(t=self),t.objectHash=i())})(function(){return function i(t,e,n){function r(d,h){if(!e[d]){if(!t[d]){var m=typeof require=="function"&&require;if(!h&&m)return m(d,!0);if(s)return s(d,!0);throw new Error("Cannot find module '"+d+"'")}h=e[d]={exports:{}},t[d][0].call(h.exports,function(C){var P=t[d][1][C];return r(P||C)},h,h.exports,i,t,e,n)}return e[d].exports}for(var s=typeof require=="function"&&require,a=0;a<n.length;a++)r(n[a]);return r}({1:[function(i,t,e){(function(n,r,s,a,d,h,m,C,P){"use strict";var v=i("crypto");function T(y,w){w=D(y,w);var l;return(l=w.algorithm!=="passthrough"?v.createHash(w.algorithm):new A).write===void 0&&(l.write=l.update,l.end=l.update),x(w,l).dispatch(y),l.update||l.end(""),l.digest?l.digest(w.encoding==="buffer"?void 0:w.encoding):(y=l.read(),w.encoding!=="buffer"?y.toString(w.encoding):y)}(e=t.exports=T).sha1=function(y){return T(y)},e.keys=function(y){return T(y,{excludeValues:!0,algorithm:"sha1",encoding:"hex"})},e.MD5=function(y){return T(y,{algorithm:"md5",encoding:"hex"})},e.keysMD5=function(y){return T(y,{algorithm:"md5",encoding:"hex",excludeValues:!0})};var b=v.getHashes?v.getHashes().slice():["sha1","md5"],I=(b.push("passthrough"),["buffer","hex","binary","base64"]);function D(y,w){var l={};if(l.algorithm=(w=w||{}).algorithm||"sha1",l.encoding=w.encoding||"hex",l.excludeValues=!!w.excludeValues,l.algorithm=l.algorithm.toLowerCase(),l.encoding=l.encoding.toLowerCase(),l.ignoreUnknown=w.ignoreUnknown===!0,l.respectType=w.respectType!==!1,l.respectFunctionNames=w.respectFunctionNames!==!1,l.respectFunctionProperties=w.respectFunctionProperties!==!1,l.unorderedArrays=w.unorderedArrays===!0,l.unorderedSets=w.unorderedSets!==!1,l.unorderedObjects=w.unorderedObjects!==!1,l.replacer=w.replacer||void 0,l.excludeKeys=w.excludeKeys||void 0,y===void 0)throw new Error("Object argument required.");for(var p=0;p<b.length;++p)b[p].toLowerCase()===l.algorithm.toLowerCase()&&(l.algorithm=b[p]);if(b.indexOf(l.algorithm)===-1)throw new Error('Algorithm "'+l.algorithm+'" not supported. supported values: '+b.join(", "));if(I.indexOf(l.encoding)===-1&&l.algorithm!=="passthrough")throw new Error('Encoding "'+l.encoding+'" not supported. supported values: '+I.join(", "));return l}function O(y){if(typeof y=="function")return/^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i.exec(Function.prototype.toString.call(y))!=null}function x(y,w,l){l=l||[];function p(c){return w.update?w.update(c,"utf8"):w.write(c,"utf8")}return{dispatch:function(c){return this["_"+((c=y.replacer?y.replacer(c):c)===null?"null":typeof c)](c)},_object:function(c){var g,S=Object.prototype.toString.call(c),M=/\[object (.*)\]/i.exec(S);if(M=(M=M?M[1]:"unknown:["+S+"]").toLowerCase(),0<=(S=l.indexOf(c)))return this.dispatch("[CIRCULAR:"+S+"]");if(l.push(c),s!==void 0&&s.isBuffer&&s.isBuffer(c))return p("buffer:"),p(c);if(M==="object"||M==="function"||M==="asyncfunction")return S=Object.keys(c),y.unorderedObjects&&(S=S.sort()),y.respectType===!1||O(c)||S.splice(0,0,"prototype","__proto__","constructor"),y.excludeKeys&&(S=S.filter(function(R){return!y.excludeKeys(R)})),p("object:"+S.length+":"),g=this,S.forEach(function(R){g.dispatch(R),p(":"),y.excludeValues||g.dispatch(c[R]),p(",")});if(!this["_"+M]){if(y.ignoreUnknown)return p("["+M+"]");throw new Error('Unknown object type "'+M+'"')}this["_"+M](c)},_array:function(c,R){R=R!==void 0?R:y.unorderedArrays!==!1;var S=this;if(p("array:"+c.length+":"),!R||c.length<=1)return c.forEach(function(j){return S.dispatch(j)});var M=[],R=c.map(function(j){var F=new A,q=l.slice();return x(y,F,q).dispatch(j),M=M.concat(q.slice(l.length)),F.read().toString()});return l=l.concat(M),R.sort(),this._array(R,!1)},_date:function(c){return p("date:"+c.toJSON())},_symbol:function(c){return p("symbol:"+c.toString())},_error:function(c){return p("error:"+c.toString())},_boolean:function(c){return p("bool:"+c.toString())},_string:function(c){p("string:"+c.length+":"),p(c.toString())},_function:function(c){p("fn:"),O(c)?this.dispatch("[native]"):this.dispatch(c.toString()),y.respectFunctionNames!==!1&&this.dispatch("function-name:"+String(c.name)),y.respectFunctionProperties&&this._object(c)},_number:function(c){return p("number:"+c.toString())},_xml:function(c){return p("xml:"+c.toString())},_null:function(){return p("Null")},_undefined:function(){return p("Undefined")},_regexp:function(c){return p("regex:"+c.toString())},_uint8array:function(c){return p("uint8array:"),this.dispatch(Array.prototype.slice.call(c))},_uint8clampedarray:function(c){return p("uint8clampedarray:"),this.dispatch(Array.prototype.slice.call(c))},_int8array:function(c){return p("int8array:"),this.dispatch(Array.prototype.slice.call(c))},_uint16array:function(c){return p("uint16array:"),this.dispatch(Array.prototype.slice.call(c))},_int16array:function(c){return p("int16array:"),this.dispatch(Array.prototype.slice.call(c))},_uint32array:function(c){return p("uint32array:"),this.dispatch(Array.prototype.slice.call(c))},_int32array:function(c){return p("int32array:"),this.dispatch(Array.prototype.slice.call(c))},_float32array:function(c){return p("float32array:"),this.dispatch(Array.prototype.slice.call(c))},_float64array:function(c){return p("float64array:"),this.dispatch(Array.prototype.slice.call(c))},_arraybuffer:function(c){return p("arraybuffer:"),this.dispatch(new Uint8Array(c))},_url:function(c){return p("url:"+c.toString())},_map:function(c){return p("map:"),c=Array.from(c),this._array(c,y.unorderedSets!==!1)},_set:function(c){return p("set:"),c=Array.from(c),this._array(c,y.unorderedSets!==!1)},_file:function(c){return p("file:"),this.dispatch([c.name,c.size,c.type,c.lastModfied])},_blob:function(){if(y.ignoreUnknown)return p("[blob]");throw Error(`Hashing Blob objects is currently not supported
2
+ (see https://github.com/puleos/object-hash/issues/26)
3
+ Use "options.replacer" or "options.ignoreUnknown"
4
+ `)},_domwindow:function(){return p("domwindow")},_bigint:function(c){return p("bigint:"+c.toString())},_process:function(){return p("process")},_timer:function(){return p("timer")},_pipe:function(){return p("pipe")},_tcp:function(){return p("tcp")},_udp:function(){return p("udp")},_tty:function(){return p("tty")},_statwatcher:function(){return p("statwatcher")},_securecontext:function(){return p("securecontext")},_connection:function(){return p("connection")},_zlib:function(){return p("zlib")},_context:function(){return p("context")},_nodescript:function(){return p("nodescript")},_httpparser:function(){return p("httpparser")},_dataview:function(){return p("dataview")},_signal:function(){return p("signal")},_fsevent:function(){return p("fsevent")},_tlswrap:function(){return p("tlswrap")}}}function A(){return{buf:"",write:function(y){this.buf+=y},end:function(y){this.buf+=y},read:function(){return this.buf}}}e.writeToStream=function(y,w,l){return l===void 0&&(l=w,w={}),x(w=D(y,w),l).dispatch(y)}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/fake_9a5aa49d.js","/")},{buffer:3,crypto:5,lYpoI2:11}],2:[function(i,t,e){(function(n,r,s,a,d,h,m,C,P){(function(v){"use strict";var T=typeof Uint8Array<"u"?Uint8Array:Array,b="+".charCodeAt(0),I="/".charCodeAt(0),D="0".charCodeAt(0),O="a".charCodeAt(0),x="A".charCodeAt(0),A="-".charCodeAt(0),y="_".charCodeAt(0);function w(l){return l=l.charCodeAt(0),l===b||l===A?62:l===I||l===y?63:l<D?-1:l<D+10?l-D+26+26:l<x+26?l-x:l<O+26?l-O+26:void 0}v.toByteArray=function(l){var p,c;if(0<l.length%4)throw new Error("Invalid string. Length must be a multiple of 4");var g=l.length,g=l.charAt(g-2)==="="?2:l.charAt(g-1)==="="?1:0,S=new T(3*l.length/4-g),M=0<g?l.length-4:l.length,R=0;function j(F){S[R++]=F}for(p=0;p<M;p+=4,0)j((16711680&(c=w(l.charAt(p))<<18|w(l.charAt(p+1))<<12|w(l.charAt(p+2))<<6|w(l.charAt(p+3))))>>16),j((65280&c)>>8),j(255&c);return g==2?j(255&(c=w(l.charAt(p))<<2|w(l.charAt(p+1))>>4)):g==1&&(j((c=w(l.charAt(p))<<10|w(l.charAt(p+1))<<4|w(l.charAt(p+2))>>2)>>8&255),j(255&c)),S},v.fromByteArray=function(l){var p,c,g,S,M=l.length%3,R="";function j(F){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(F)}for(p=0,g=l.length-M;p<g;p+=3)c=(l[p]<<16)+(l[p+1]<<8)+l[p+2],R+=j((S=c)>>18&63)+j(S>>12&63)+j(S>>6&63)+j(63&S);switch(M){case 1:R=(R+=j((c=l[l.length-1])>>2))+j(c<<4&63)+"==";break;case 2:R=(R=(R+=j((c=(l[l.length-2]<<8)+l[l.length-1])>>10))+j(c>>4&63))+j(c<<2&63)+"="}return R}})(e===void 0?this.base64js={}:e)}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/base64-js/lib/b64.js","/node_modules/gulp-browserify/node_modules/base64-js/lib")},{buffer:3,lYpoI2:11}],3:[function(i,t,e){(function(n,r,b,a,d,h,m,C,P){var v=i("base64-js"),T=i("ieee754");function b(o,u,f){if(!(this instanceof b))return new b(o,u,f);var _,E,k,L,Q=typeof o;if(u==="base64"&&Q=="string")for(o=(L=o).trim?L.trim():L.replace(/^\s+|\s+$/g,"");o.length%4!=0;)o+="=";if(Q=="number")_=ee(o);else if(Q=="string")_=b.byteLength(o,u);else{if(Q!="object")throw new Error("First argument needs to be a number, array or string.");_=ee(o.length)}if(b._useTypedArrays?E=b._augment(new Uint8Array(_)):((E=this).length=_,E._isBuffer=!0),b._useTypedArrays&&typeof o.byteLength=="number")E._set(o);else if(H(L=o)||b.isBuffer(L)||L&&typeof L=="object"&&typeof L.length=="number")for(k=0;k<_;k++)b.isBuffer(o)?E[k]=o.readUInt8(k):E[k]=o[k];else if(Q=="string")E.write(o,0,u);else if(Q=="number"&&!b._useTypedArrays&&!f)for(k=0;k<_;k++)E[k]=0;return E}function I(o,u,f,_){return b._charsWritten=lt(function(E){for(var k=[],L=0;L<E.length;L++)k.push(255&E.charCodeAt(L));return k}(u),o,f,_)}function D(o,u,f,_){return b._charsWritten=lt(function(E){for(var k,L,Q=[],Y=0;Y<E.length;Y++)L=E.charCodeAt(Y),k=L>>8,L=L%256,Q.push(L),Q.push(k);return Q}(u),o,f,_)}function O(o,u,f){var _="";f=Math.min(o.length,f);for(var E=u;E<f;E++)_+=String.fromCharCode(o[E]);return _}function x(o,u,f,k){k||(B(typeof f=="boolean","missing or invalid endian"),B(u!=null,"missing offset"),B(u+1<o.length,"Trying to read beyond buffer length"));var E,k=o.length;if(!(k<=u))return f?(E=o[u],u+1<k&&(E|=o[u+1]<<8)):(E=o[u]<<8,u+1<k&&(E|=o[u+1])),E}function A(o,u,f,k){k||(B(typeof f=="boolean","missing or invalid endian"),B(u!=null,"missing offset"),B(u+3<o.length,"Trying to read beyond buffer length"));var E,k=o.length;if(!(k<=u))return f?(u+2<k&&(E=o[u+2]<<16),u+1<k&&(E|=o[u+1]<<8),E|=o[u],u+3<k&&(E+=o[u+3]<<24>>>0)):(u+1<k&&(E=o[u+1]<<16),u+2<k&&(E|=o[u+2]<<8),u+3<k&&(E|=o[u+3]),E+=o[u]<<24>>>0),E}function y(o,u,f,_){if(_||(B(typeof f=="boolean","missing or invalid endian"),B(u!=null,"missing offset"),B(u+1<o.length,"Trying to read beyond buffer length")),!(o.length<=u))return _=x(o,u,f,!0),32768&_?-1*(65535-_+1):_}function w(o,u,f,_){if(_||(B(typeof f=="boolean","missing or invalid endian"),B(u!=null,"missing offset"),B(u+3<o.length,"Trying to read beyond buffer length")),!(o.length<=u))return _=A(o,u,f,!0),2147483648&_?-1*(4294967295-_+1):_}function l(o,u,f,_){return _||(B(typeof f=="boolean","missing or invalid endian"),B(u+3<o.length,"Trying to read beyond buffer length")),T.read(o,u,f,23,4)}function p(o,u,f,_){return _||(B(typeof f=="boolean","missing or invalid endian"),B(u+7<o.length,"Trying to read beyond buffer length")),T.read(o,u,f,52,8)}function c(o,u,f,_,E){if(E||(B(u!=null,"missing value"),B(typeof _=="boolean","missing or invalid endian"),B(f!=null,"missing offset"),B(f+1<o.length,"trying to write beyond buffer length"),yn(u,65535)),E=o.length,!(E<=f))for(var k=0,L=Math.min(E-f,2);k<L;k++)o[f+k]=(u&255<<8*(_?k:1-k))>>>8*(_?k:1-k)}function g(o,u,f,_,E){if(E||(B(u!=null,"missing value"),B(typeof _=="boolean","missing or invalid endian"),B(f!=null,"missing offset"),B(f+3<o.length,"trying to write beyond buffer length"),yn(u,4294967295)),E=o.length,!(E<=f))for(var k=0,L=Math.min(E-f,4);k<L;k++)o[f+k]=u>>>8*(_?k:3-k)&255}function S(o,u,f,_,E){E||(B(u!=null,"missing value"),B(typeof _=="boolean","missing or invalid endian"),B(f!=null,"missing offset"),B(f+1<o.length,"Trying to write beyond buffer length"),gn(u,32767,-32768)),o.length<=f||c(o,0<=u?u:65535+u+1,f,_,E)}function M(o,u,f,_,E){E||(B(u!=null,"missing value"),B(typeof _=="boolean","missing or invalid endian"),B(f!=null,"missing offset"),B(f+3<o.length,"Trying to write beyond buffer length"),gn(u,2147483647,-2147483648)),o.length<=f||g(o,0<=u?u:4294967295+u+1,f,_,E)}function R(o,u,f,_,E){E||(B(u!=null,"missing value"),B(typeof _=="boolean","missing or invalid endian"),B(f!=null,"missing offset"),B(f+3<o.length,"Trying to write beyond buffer length"),Xn(u,34028234663852886e22,-34028234663852886e22)),o.length<=f||T.write(o,u,f,_,23,4)}function j(o,u,f,_,E){E||(B(u!=null,"missing value"),B(typeof _=="boolean","missing or invalid endian"),B(f!=null,"missing offset"),B(f+7<o.length,"Trying to write beyond buffer length"),Xn(u,17976931348623157e292,-17976931348623157e292)),o.length<=f||T.write(o,u,f,_,52,8)}e.Buffer=b,e.SlowBuffer=b,e.INSPECT_MAX_BYTES=50,b.poolSize=8192,b._useTypedArrays=function(){try{var o=new ArrayBuffer(0),u=new Uint8Array(o);return u.foo=function(){return 42},u.foo()===42&&typeof u.subarray=="function"}catch{return!1}}(),b.isEncoding=function(o){switch(String(o).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},b.isBuffer=function(o){return!(o==null||!o._isBuffer)},b.byteLength=function(o,u){var f;switch(o+="",u||"utf8"){case"hex":f=o.length/2;break;case"utf8":case"utf-8":f=ye(o).length;break;case"ascii":case"binary":case"raw":f=o.length;break;case"base64":f=Yn(o).length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":f=2*o.length;break;default:throw new Error("Unknown encoding")}return f},b.concat=function(o,u){if(B(H(o),`Usage: Buffer.concat(list, [totalLength])
5
+ list should be an Array.`),o.length===0)return new b(0);if(o.length===1)return o[0];if(typeof u!="number")for(E=u=0;E<o.length;E++)u+=o[E].length;for(var f=new b(u),_=0,E=0;E<o.length;E++){var k=o[E];k.copy(f,_),_+=k.length}return f},b.prototype.write=function(o,u,f,_){isFinite(u)?isFinite(f)||(_=f,f=void 0):(Y=_,_=u,u=f,f=Y),u=Number(u)||0;var E,k,L,Q,Y=this.length-u;switch((!f||Y<(f=Number(f)))&&(f=Y),_=String(_||"utf8").toLowerCase()){case"hex":E=function(he,re,se,G){se=Number(se)||0;var J=he.length-se;(!G||J<(G=Number(G)))&&(G=J),B((J=re.length)%2==0,"Invalid hex string"),J/2<G&&(G=J/2);for(var Me=0;Me<G;Me++){var Zn=parseInt(re.substr(2*Me,2),16);B(!isNaN(Zn),"Invalid hex string"),he[se+Me]=Zn}return b._charsWritten=2*Me,Me}(this,o,u,f);break;case"utf8":case"utf-8":k=this,L=u,Q=f,E=b._charsWritten=lt(ye(o),k,L,Q);break;case"ascii":case"binary":E=I(this,o,u,f);break;case"base64":k=this,L=u,Q=f,E=b._charsWritten=lt(Yn(o),k,L,Q);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":E=D(this,o,u,f);break;default:throw new Error("Unknown encoding")}return E},b.prototype.toString=function(o,u,f){var _,E,k,L,Q=this;if(o=String(o||"utf8").toLowerCase(),u=Number(u)||0,(f=f!==void 0?Number(f):Q.length)===u)return"";switch(o){case"hex":_=function(Y,he,re){var se=Y.length;(!he||he<0)&&(he=0),(!re||re<0||se<re)&&(re=se);for(var G="",J=he;J<re;J++)G+=z(Y[J]);return G}(Q,u,f);break;case"utf8":case"utf-8":_=function(Y,he,re){var se="",G="";re=Math.min(Y.length,re);for(var J=he;J<re;J++)Y[J]<=127?(se+=Gn(G)+String.fromCharCode(Y[J]),G=""):G+="%"+Y[J].toString(16);return se+Gn(G)}(Q,u,f);break;case"ascii":case"binary":_=O(Q,u,f);break;case"base64":E=Q,L=f,_=(k=u)===0&&L===E.length?v.fromByteArray(E):v.fromByteArray(E.slice(k,L));break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":_=function(Y,he,re){for(var se=Y.slice(he,re),G="",J=0;J<se.length;J+=2)G+=String.fromCharCode(se[J]+256*se[J+1]);return G}(Q,u,f);break;default:throw new Error("Unknown encoding")}return _},b.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},b.prototype.copy=function(o,u,f,_){if(u=u||0,(_=_||_===0?_:this.length)!==(f=f||0)&&o.length!==0&&this.length!==0){B(f<=_,"sourceEnd < sourceStart"),B(0<=u&&u<o.length,"targetStart out of bounds"),B(0<=f&&f<this.length,"sourceStart out of bounds"),B(0<=_&&_<=this.length,"sourceEnd out of bounds"),_>this.length&&(_=this.length);var E=(_=o.length-u<_-f?o.length-u+f:_)-f;if(E<100||!b._useTypedArrays)for(var k=0;k<E;k++)o[k+u]=this[k+f];else o._set(this.subarray(f,f+E),u)}},b.prototype.slice=function(o,u){var f=this.length;if(o=q(o,f,0),u=q(u,f,f),b._useTypedArrays)return b._augment(this.subarray(o,u));for(var _=u-o,E=new b(_,void 0,!0),k=0;k<_;k++)E[k]=this[k+o];return E},b.prototype.get=function(o){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(o)},b.prototype.set=function(o,u){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(o,u)},b.prototype.readUInt8=function(o,u){if(u||(B(o!=null,"missing offset"),B(o<this.length,"Trying to read beyond buffer length")),!(o>=this.length))return this[o]},b.prototype.readUInt16LE=function(o,u){return x(this,o,!0,u)},b.prototype.readUInt16BE=function(o,u){return x(this,o,!1,u)},b.prototype.readUInt32LE=function(o,u){return A(this,o,!0,u)},b.prototype.readUInt32BE=function(o,u){return A(this,o,!1,u)},b.prototype.readInt8=function(o,u){if(u||(B(o!=null,"missing offset"),B(o<this.length,"Trying to read beyond buffer length")),!(o>=this.length))return 128&this[o]?-1*(255-this[o]+1):this[o]},b.prototype.readInt16LE=function(o,u){return y(this,o,!0,u)},b.prototype.readInt16BE=function(o,u){return y(this,o,!1,u)},b.prototype.readInt32LE=function(o,u){return w(this,o,!0,u)},b.prototype.readInt32BE=function(o,u){return w(this,o,!1,u)},b.prototype.readFloatLE=function(o,u){return l(this,o,!0,u)},b.prototype.readFloatBE=function(o,u){return l(this,o,!1,u)},b.prototype.readDoubleLE=function(o,u){return p(this,o,!0,u)},b.prototype.readDoubleBE=function(o,u){return p(this,o,!1,u)},b.prototype.writeUInt8=function(o,u,f){f||(B(o!=null,"missing value"),B(u!=null,"missing offset"),B(u<this.length,"trying to write beyond buffer length"),yn(o,255)),u>=this.length||(this[u]=o)},b.prototype.writeUInt16LE=function(o,u,f){c(this,o,u,!0,f)},b.prototype.writeUInt16BE=function(o,u,f){c(this,o,u,!1,f)},b.prototype.writeUInt32LE=function(o,u,f){g(this,o,u,!0,f)},b.prototype.writeUInt32BE=function(o,u,f){g(this,o,u,!1,f)},b.prototype.writeInt8=function(o,u,f){f||(B(o!=null,"missing value"),B(u!=null,"missing offset"),B(u<this.length,"Trying to write beyond buffer length"),gn(o,127,-128)),u>=this.length||(0<=o?this.writeUInt8(o,u,f):this.writeUInt8(255+o+1,u,f))},b.prototype.writeInt16LE=function(o,u,f){S(this,o,u,!0,f)},b.prototype.writeInt16BE=function(o,u,f){S(this,o,u,!1,f)},b.prototype.writeInt32LE=function(o,u,f){M(this,o,u,!0,f)},b.prototype.writeInt32BE=function(o,u,f){M(this,o,u,!1,f)},b.prototype.writeFloatLE=function(o,u,f){R(this,o,u,!0,f)},b.prototype.writeFloatBE=function(o,u,f){R(this,o,u,!1,f)},b.prototype.writeDoubleLE=function(o,u,f){j(this,o,u,!0,f)},b.prototype.writeDoubleBE=function(o,u,f){j(this,o,u,!1,f)},b.prototype.fill=function(o,u,f){if(u=u||0,f=f||this.length,B(typeof(o=typeof(o=o||0)=="string"?o.charCodeAt(0):o)=="number"&&!isNaN(o),"value is not a number"),B(u<=f,"end < start"),f!==u&&this.length!==0){B(0<=u&&u<this.length,"start out of bounds"),B(0<=f&&f<=this.length,"end out of bounds");for(var _=u;_<f;_++)this[_]=o}},b.prototype.inspect=function(){for(var o=[],u=this.length,f=0;f<u;f++)if(o[f]=z(this[f]),f===e.INSPECT_MAX_BYTES){o[f+1]="...";break}return"<Buffer "+o.join(" ")+">"},b.prototype.toArrayBuffer=function(){if(typeof Uint8Array>"u")throw new Error("Buffer.toArrayBuffer not supported in this browser");if(b._useTypedArrays)return new b(this).buffer;for(var o=new Uint8Array(this.length),u=0,f=o.length;u<f;u+=1)o[u]=this[u];return o.buffer};var F=b.prototype;function q(o,u,f){return typeof o!="number"?f:u<=(o=~~o)?u:0<=o||0<=(o+=u)?o:0}function ee(o){return(o=~~Math.ceil(+o))<0?0:o}function H(o){return(Array.isArray||function(u){return Object.prototype.toString.call(u)==="[object Array]"})(o)}function z(o){return o<16?"0"+o.toString(16):o.toString(16)}function ye(o){for(var u=[],f=0;f<o.length;f++){var _=o.charCodeAt(f);if(_<=127)u.push(o.charCodeAt(f));else for(var E=f,k=(55296<=_&&_<=57343&&f++,encodeURIComponent(o.slice(E,f+1)).substr(1).split("%")),L=0;L<k.length;L++)u.push(parseInt(k[L],16))}return u}function Yn(o){return v.toByteArray(o)}function lt(o,u,f,_){for(var E=0;E<_&&!(E+f>=u.length||E>=o.length);E++)u[E+f]=o[E];return E}function Gn(o){try{return decodeURIComponent(o)}catch{return String.fromCharCode(65533)}}function yn(o,u){B(typeof o=="number","cannot write a non-number as a number"),B(0<=o,"specified a negative value for writing an unsigned value"),B(o<=u,"value is larger than maximum value for type"),B(Math.floor(o)===o,"value has a fractional component")}function gn(o,u,f){B(typeof o=="number","cannot write a non-number as a number"),B(o<=u,"value larger than maximum allowed value"),B(f<=o,"value smaller than minimum allowed value"),B(Math.floor(o)===o,"value has a fractional component")}function Xn(o,u,f){B(typeof o=="number","cannot write a non-number as a number"),B(o<=u,"value larger than maximum allowed value"),B(f<=o,"value smaller than minimum allowed value")}function B(o,u){if(!o)throw new Error(u||"Failed assertion")}b._augment=function(o){return o._isBuffer=!0,o._get=o.get,o._set=o.set,o.get=F.get,o.set=F.set,o.write=F.write,o.toString=F.toString,o.toLocaleString=F.toString,o.toJSON=F.toJSON,o.copy=F.copy,o.slice=F.slice,o.readUInt8=F.readUInt8,o.readUInt16LE=F.readUInt16LE,o.readUInt16BE=F.readUInt16BE,o.readUInt32LE=F.readUInt32LE,o.readUInt32BE=F.readUInt32BE,o.readInt8=F.readInt8,o.readInt16LE=F.readInt16LE,o.readInt16BE=F.readInt16BE,o.readInt32LE=F.readInt32LE,o.readInt32BE=F.readInt32BE,o.readFloatLE=F.readFloatLE,o.readFloatBE=F.readFloatBE,o.readDoubleLE=F.readDoubleLE,o.readDoubleBE=F.readDoubleBE,o.writeUInt8=F.writeUInt8,o.writeUInt16LE=F.writeUInt16LE,o.writeUInt16BE=F.writeUInt16BE,o.writeUInt32LE=F.writeUInt32LE,o.writeUInt32BE=F.writeUInt32BE,o.writeInt8=F.writeInt8,o.writeInt16LE=F.writeInt16LE,o.writeInt16BE=F.writeInt16BE,o.writeInt32LE=F.writeInt32LE,o.writeInt32BE=F.writeInt32BE,o.writeFloatLE=F.writeFloatLE,o.writeFloatBE=F.writeFloatBE,o.writeDoubleLE=F.writeDoubleLE,o.writeDoubleBE=F.writeDoubleBE,o.fill=F.fill,o.inspect=F.inspect,o.toArrayBuffer=F.toArrayBuffer,o}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/buffer/index.js","/node_modules/gulp-browserify/node_modules/buffer")},{"base64-js":2,buffer:3,ieee754:10,lYpoI2:11}],4:[function(i,t,e){(function(n,r,v,a,d,h,m,C,P){var v=i("buffer").Buffer,T=4,b=new v(T);b.fill(0),t.exports={hash:function(I,D,O,x){for(var A=D(function(c,g){c.length%T!=0&&(S=c.length+(T-c.length%T),c=v.concat([c,b],S));for(var S,M=[],R=g?c.readInt32BE:c.readInt32LE,j=0;j<c.length;j+=T)M.push(R.call(c,j));return M}(I=v.isBuffer(I)?I:new v(I),x),8*I.length),D=x,y=new v(O),w=D?y.writeInt32BE:y.writeInt32LE,l=0;l<A.length;l++)w.call(y,A[l],4*l,!0);return y}}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/helpers.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{buffer:3,lYpoI2:11}],5:[function(i,t,e){(function(n,r,v,a,d,h,m,C,P){var v=i("buffer").Buffer,T=i("./sha"),b=i("./sha256"),I=i("./rng"),D={sha1:T,sha256:b,md5:i("./md5")},O=64,x=new v(O);function A(c,g){var S=D[c=c||"sha1"],M=[];return S||y("algorithm:",c,"is not yet supported"),{update:function(R){return v.isBuffer(R)||(R=new v(R)),M.push(R),R.length,this},digest:function(R){var j=v.concat(M),j=g?function(F,q,ee){v.isBuffer(q)||(q=new v(q)),v.isBuffer(ee)||(ee=new v(ee)),q.length>O?q=F(q):q.length<O&&(q=v.concat([q,x],O));for(var H=new v(O),z=new v(O),ye=0;ye<O;ye++)H[ye]=54^q[ye],z[ye]=92^q[ye];return ee=F(v.concat([H,ee])),F(v.concat([z,ee]))}(S,g,j):S(j);return M=null,R?j.toString(R):j}}}function y(){var c=[].slice.call(arguments).join(" ");throw new Error([c,"we accept pull requests","http://github.com/dominictarr/crypto-browserify"].join(`
6
+ `))}x.fill(0),e.createHash=function(c){return A(c)},e.createHmac=A,e.randomBytes=function(c,g){if(!g||!g.call)return new v(I(c));try{g.call(this,void 0,new v(I(c)))}catch(S){g(S)}};var w,l=["createCredentials","createCipher","createCipheriv","createDecipher","createDecipheriv","createSign","createVerify","createDiffieHellman","pbkdf2"],p=function(c){e[c]=function(){y("sorry,",c,"is not implemented yet")}};for(w in l)p(l[w],w)}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/index.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./md5":6,"./rng":7,"./sha":8,"./sha256":9,buffer:3,lYpoI2:11}],6:[function(i,t,e){(function(n,r,s,a,d,h,m,C,P){var v=i("./helpers");function T(y,w){y[w>>5]|=128<<w%32,y[14+(w+64>>>9<<4)]=w;for(var l=1732584193,p=-271733879,c=-1732584194,g=271733878,S=0;S<y.length;S+=16){var M=l,R=p,j=c,F=g,l=I(l,p,c,g,y[S+0],7,-680876936),g=I(g,l,p,c,y[S+1],12,-389564586),c=I(c,g,l,p,y[S+2],17,606105819),p=I(p,c,g,l,y[S+3],22,-1044525330);l=I(l,p,c,g,y[S+4],7,-176418897),g=I(g,l,p,c,y[S+5],12,1200080426),c=I(c,g,l,p,y[S+6],17,-1473231341),p=I(p,c,g,l,y[S+7],22,-45705983),l=I(l,p,c,g,y[S+8],7,1770035416),g=I(g,l,p,c,y[S+9],12,-1958414417),c=I(c,g,l,p,y[S+10],17,-42063),p=I(p,c,g,l,y[S+11],22,-1990404162),l=I(l,p,c,g,y[S+12],7,1804603682),g=I(g,l,p,c,y[S+13],12,-40341101),c=I(c,g,l,p,y[S+14],17,-1502002290),l=D(l,p=I(p,c,g,l,y[S+15],22,1236535329),c,g,y[S+1],5,-165796510),g=D(g,l,p,c,y[S+6],9,-1069501632),c=D(c,g,l,p,y[S+11],14,643717713),p=D(p,c,g,l,y[S+0],20,-373897302),l=D(l,p,c,g,y[S+5],5,-701558691),g=D(g,l,p,c,y[S+10],9,38016083),c=D(c,g,l,p,y[S+15],14,-660478335),p=D(p,c,g,l,y[S+4],20,-405537848),l=D(l,p,c,g,y[S+9],5,568446438),g=D(g,l,p,c,y[S+14],9,-1019803690),c=D(c,g,l,p,y[S+3],14,-187363961),p=D(p,c,g,l,y[S+8],20,1163531501),l=D(l,p,c,g,y[S+13],5,-1444681467),g=D(g,l,p,c,y[S+2],9,-51403784),c=D(c,g,l,p,y[S+7],14,1735328473),l=O(l,p=D(p,c,g,l,y[S+12],20,-1926607734),c,g,y[S+5],4,-378558),g=O(g,l,p,c,y[S+8],11,-2022574463),c=O(c,g,l,p,y[S+11],16,1839030562),p=O(p,c,g,l,y[S+14],23,-35309556),l=O(l,p,c,g,y[S+1],4,-1530992060),g=O(g,l,p,c,y[S+4],11,1272893353),c=O(c,g,l,p,y[S+7],16,-155497632),p=O(p,c,g,l,y[S+10],23,-1094730640),l=O(l,p,c,g,y[S+13],4,681279174),g=O(g,l,p,c,y[S+0],11,-358537222),c=O(c,g,l,p,y[S+3],16,-722521979),p=O(p,c,g,l,y[S+6],23,76029189),l=O(l,p,c,g,y[S+9],4,-640364487),g=O(g,l,p,c,y[S+12],11,-421815835),c=O(c,g,l,p,y[S+15],16,530742520),l=x(l,p=O(p,c,g,l,y[S+2],23,-995338651),c,g,y[S+0],6,-198630844),g=x(g,l,p,c,y[S+7],10,1126891415),c=x(c,g,l,p,y[S+14],15,-1416354905),p=x(p,c,g,l,y[S+5],21,-57434055),l=x(l,p,c,g,y[S+12],6,1700485571),g=x(g,l,p,c,y[S+3],10,-1894986606),c=x(c,g,l,p,y[S+10],15,-1051523),p=x(p,c,g,l,y[S+1],21,-2054922799),l=x(l,p,c,g,y[S+8],6,1873313359),g=x(g,l,p,c,y[S+15],10,-30611744),c=x(c,g,l,p,y[S+6],15,-1560198380),p=x(p,c,g,l,y[S+13],21,1309151649),l=x(l,p,c,g,y[S+4],6,-145523070),g=x(g,l,p,c,y[S+11],10,-1120210379),c=x(c,g,l,p,y[S+2],15,718787259),p=x(p,c,g,l,y[S+9],21,-343485551),l=A(l,M),p=A(p,R),c=A(c,j),g=A(g,F)}return Array(l,p,c,g)}function b(y,w,l,p,c,g){return A((w=A(A(w,y),A(p,g)))<<c|w>>>32-c,l)}function I(y,w,l,p,c,g,S){return b(w&l|~w&p,y,w,c,g,S)}function D(y,w,l,p,c,g,S){return b(w&p|l&~p,y,w,c,g,S)}function O(y,w,l,p,c,g,S){return b(w^l^p,y,w,c,g,S)}function x(y,w,l,p,c,g,S){return b(l^(w|~p),y,w,c,g,S)}function A(y,w){var l=(65535&y)+(65535&w);return(y>>16)+(w>>16)+(l>>16)<<16|65535&l}t.exports=function(y){return v.hash(y,T,16)}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/md5.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],7:[function(i,t,e){(function(n,r,s,a,d,h,m,C,P){var v;t.exports=v||function(T){for(var b,I=new Array(T),D=0;D<T;D++)!(3&D)&&(b=4294967296*Math.random()),I[D]=b>>>((3&D)<<3)&255;return I}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/rng.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{buffer:3,lYpoI2:11}],8:[function(i,t,e){(function(n,r,s,a,d,h,m,C,P){var v=i("./helpers");function T(D,O){D[O>>5]|=128<<24-O%32,D[15+(O+64>>9<<4)]=O;for(var x,A,y,w=Array(80),l=1732584193,p=-271733879,c=-1732584194,g=271733878,S=-1009589776,M=0;M<D.length;M+=16){for(var R=l,j=p,F=c,q=g,ee=S,H=0;H<80;H++){w[H]=H<16?D[M+H]:I(w[H-3]^w[H-8]^w[H-14]^w[H-16],1);var z=b(b(I(l,5),(z=p,A=c,y=g,(x=H)<20?z&A|~z&y:!(x<40)&&x<60?z&A|z&y|A&y:z^A^y)),b(b(S,w[H]),(x=H)<20?1518500249:x<40?1859775393:x<60?-1894007588:-899497514)),S=g,g=c,c=I(p,30),p=l,l=z}l=b(l,R),p=b(p,j),c=b(c,F),g=b(g,q),S=b(S,ee)}return Array(l,p,c,g,S)}function b(D,O){var x=(65535&D)+(65535&O);return(D>>16)+(O>>16)+(x>>16)<<16|65535&x}function I(D,O){return D<<O|D>>>32-O}t.exports=function(D){return v.hash(D,T,20,!0)}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],9:[function(i,t,e){(function(n,r,s,a,d,h,m,C,P){function v(O,x){var A=(65535&O)+(65535&x);return(O>>16)+(x>>16)+(A>>16)<<16|65535&A}function T(O,x){var A,y=new Array(1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298),w=new Array(1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225),l=new Array(64);O[x>>5]|=128<<24-x%32,O[15+(x+64>>9<<4)]=x;for(var p,c,g=0;g<O.length;g+=16){for(var S=w[0],M=w[1],R=w[2],j=w[3],F=w[4],q=w[5],ee=w[6],H=w[7],z=0;z<64;z++)l[z]=z<16?O[z+g]:v(v(v((c=l[z-2],I(c,17)^I(c,19)^D(c,10)),l[z-7]),(c=l[z-15],I(c,7)^I(c,18)^D(c,3))),l[z-16]),A=v(v(v(v(H,I(c=F,6)^I(c,11)^I(c,25)),F&q^~F&ee),y[z]),l[z]),p=v(I(p=S,2)^I(p,13)^I(p,22),S&M^S&R^M&R),H=ee,ee=q,q=F,F=v(j,A),j=R,R=M,M=S,S=v(A,p);w[0]=v(S,w[0]),w[1]=v(M,w[1]),w[2]=v(R,w[2]),w[3]=v(j,w[3]),w[4]=v(F,w[4]),w[5]=v(q,w[5]),w[6]=v(ee,w[6]),w[7]=v(H,w[7])}return w}var b=i("./helpers"),I=function(O,x){return O>>>x|O<<32-x},D=function(O,x){return O>>>x};t.exports=function(O){return b.hash(O,T,32,!0)}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha256.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],10:[function(i,t,e){(function(n,r,s,a,d,h,m,C,P){e.read=function(v,T,b,I,g){var O,x,A=8*g-I-1,y=(1<<A)-1,w=y>>1,l=-7,p=b?g-1:0,c=b?-1:1,g=v[T+p];for(p+=c,O=g&(1<<-l)-1,g>>=-l,l+=A;0<l;O=256*O+v[T+p],p+=c,l-=8);for(x=O&(1<<-l)-1,O>>=-l,l+=I;0<l;x=256*x+v[T+p],p+=c,l-=8);if(O===0)O=1-w;else{if(O===y)return x?NaN:1/0*(g?-1:1);x+=Math.pow(2,I),O-=w}return(g?-1:1)*x*Math.pow(2,O-I)},e.write=function(v,T,b,I,D,S){var x,A,y=8*S-D-1,w=(1<<y)-1,l=w>>1,p=D===23?Math.pow(2,-24)-Math.pow(2,-77):0,c=I?0:S-1,g=I?1:-1,S=T<0||T===0&&1/T<0?1:0;for(T=Math.abs(T),isNaN(T)||T===1/0?(A=isNaN(T)?1:0,x=w):(x=Math.floor(Math.log(T)/Math.LN2),T*(I=Math.pow(2,-x))<1&&(x--,I*=2),2<=(T+=1<=x+l?p/I:p*Math.pow(2,1-l))*I&&(x++,I/=2),w<=x+l?(A=0,x=w):1<=x+l?(A=(T*I-1)*Math.pow(2,D),x+=l):(A=T*Math.pow(2,l-1)*Math.pow(2,D),x=0));8<=D;v[b+c]=255&A,c+=g,A/=256,D-=8);for(x=x<<D|A,y+=D;0<y;v[b+c]=255&x,c+=g,x/=256,y-=8);v[b+c-g]|=128*S}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/ieee754/index.js","/node_modules/gulp-browserify/node_modules/ieee754")},{buffer:3,lYpoI2:11}],11:[function(i,t,e){(function(n,r,s,a,d,h,m,C,P){var v,T,b;function I(){}(n=t.exports={}).nextTick=(T=typeof window<"u"&&window.setImmediate,b=typeof window<"u"&&window.postMessage&&window.addEventListener,T?function(D){return window.setImmediate(D)}:b?(v=[],window.addEventListener("message",function(D){var O=D.source;O!==window&&O!==null||D.data!=="process-tick"||(D.stopPropagation(),0<v.length&&v.shift()())},!0),function(D){v.push(D),window.postMessage("process-tick","*")}):function(D){setTimeout(D,0)}),n.title="browser",n.browser=!0,n.env={},n.argv=[],n.on=I,n.addListener=I,n.once=I,n.off=I,n.removeListener=I,n.removeAllListeners=I,n.emit=I,n.binding=function(D){throw new Error("process.binding is not supported")},n.cwd=function(){return"/"},n.chdir=function(D){throw new Error("process.chdir is not supported")}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/process/browser.js","/node_modules/gulp-browserify/node_modules/process")},{buffer:3,lYpoI2:11}]},{},[1])(1)})});var Jn={};cr(Jn,{Client:()=>Re,ClientDescriptor:()=>mn,Entity:()=>me,EntityFile:()=>ke,MigrationPathError:()=>Ue,ServerSync:()=>$e,Storage:()=>Re,StorageDescriptor:()=>mn,collection:()=>Li,createDefaultMigration:()=>Vn,migrate:()=>Tt,schema:()=>Vi});var yi=dt(ft(),1),ht=4,Ye=36;function ui(i){return i.toString(Ye).padStart(ht,"0")}function yr(i){return i.toString().padStart(6,"0")}var mt=class{constructor(){this.latest={time:Date.now(),counter:0,node:gr()};this.zeroCounter=0;this.now=t=>(this.latest=fi(this.latest),this.get(t,this.latest));this.OLD_now=t=>(this.latest=fi(this.latest),yr(t)+vr(this.latest));this.timerState=()=>this.latest;this.update=t=>{let e=t.slice(ht);this.latest=br(this.latest,hi(e))};this.get=(t,e)=>ui(t)+pi(e);this.zero=t=>ui(t)+pi({time:0,counter:this.zeroCounter++,node:this.latest.node});this.getWallClockTime=t=>hi(t.slice(ht)).time}},yt=class extends Error{constructor(...e){super();this.type="ClockDriftError",this.message=["maximum clock drift exceeded"].concat(e).join(" ")}},gt=class extends Error{constructor(){super();this.type="OverflowError",this.message="timestamp counter overflow"}},On=4,In=7,bt=60*1e3,Je=9;function gr(){return yi.default.slug().padStart(In,"0").slice(0,In)}function pi(i){let t=new Date(i.time).getTime().toString(Ye).padStart(Je,"0"),e=i.counter.toString(Ye).padStart(On,"0"),n=i.node.padStart(In,"0");return`${t}${e}${n}`}function fi(i){let t=Date.now(),e=Math.max(i.time,t),n=i.time===e?i.counter+1:0;if(e-t>bt)throw new yt(e,t,bt);if(n>65535)throw new gt;return{time:e,counter:n,node:i.node}}function br(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>bt)throw new yt(n,e,bt);if(s>65535)throw new gt;return{time:n,counter:s,node:i.node}}function hi(i){let t=i.slice(0,Je),e=i.slice(Je,Je+On),n=i.slice(Je+On),r=parseInt(t,Ye),s=parseInt(e,Ye);if(isNaN(r)||isNaN(s))throw new Error("invalid clock format");return{time:r,counter:s,node:n}}function vr(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 mi(i){return parseInt(i.slice(0,ht),36)}function gi(i,t){return mi(i)-mi(t)}function de(i){return i&&i["@@type"]==="file"}function bi(i){return{"@@type":"file",id:i}}var vt,wr=new Uint8Array(16);function Dn(){if(!vt&&(vt=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!vt))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return vt(wr)}var vi=/^(?:[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 Sr(i){return typeof i=="string"&&vi.test(i)}var wi=Sr;var X=[];for(wt=0;wt<256;++wt)X.push((wt+256).toString(16).substr(1));var wt;function xr(i){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=(X[i[t+0]]+X[i[t+1]]+X[i[t+2]]+X[i[t+3]]+"-"+X[i[t+4]]+X[i[t+5]]+"-"+X[i[t+6]]+X[i[t+7]]+"-"+X[i[t+8]]+X[i[t+9]]+"-"+X[i[t+10]]+X[i[t+11]]+X[i[t+12]]+X[i[t+13]]+X[i[t+14]]+X[i[t+15]]).toLowerCase();if(!wi(e))throw TypeError("Stringified UUID is invalid");return e}var Si=xr;function Or(i,t,e){i=i||{};var n=i.random||(i.rng||Dn)();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 Si(n)}var Ge=Or;function ie(i){return te(i)||de(i)}function xi(i,t){return i===t?!0:!(!ie(i)||!ie(t)||i["@@type"]!==t["@@type"]||i.id!==t.id)}var Ci=dt(Di(),1);function Ir(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 Cn(i){return JSON.stringify(i,Ir)}function ne(i,t=!0){if(N(i)||Array.isArray(i)){let e=oe(i),n;if(Array.isArray(i))n=i.map(r=>ne(r,t));else{n={};for(let[r,s]of Object.entries(i))n[r]=ne(s,t)}return t&&e&&K(n,e),n}return i}function we(i){return(0,Ci.default)(i)}function N(i){return i&&typeof i=="object"}function Ei(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 V(i,t="assertion failed"){if(!i)throw new Error(t)}function St(i=16){return Ge().replace("-","").slice(0,i)}function _i(i,t){for(let e=i.length-1;e>=0;e--)if(t(i[e]))return e;return-1}function Pi(i,t){let e;return function(...n){let r=this;clearTimeout(e),e=setTimeout(()=>i.apply(r,n),t)}}var Ie="__@@oid_do_not_use",Se="@@id",Dr="/",It=":",_n=new WeakMap;function ue(i){let t=oe(i);return V(!!t,`Object ${JSON.stringify(i)} does not have an OID assigned to it`),t}function oe(i){if(N(i))return _n.get(i)??i[Se]??i[Ie]}function K(i,t){return V(N(i),`Only objects can be assigned OIDs, received ${JSON.stringify(i)}`),Ze(i)&&Dt(i),_n.set(i,t),i}function Ze(i){return!!oe(i)}function Dt(i){return _n.delete(i),i}function Pn(i){return i===Se||i===Ie}function Tn(i,t,e){if(Ze(i))return ue(i);{let n=ge(t,e);return K(i,n),n}}function Ti(i,t,e){if(Ze(i)){let n=ue(i);if(Ct(n,t))return ue(i);{let r=ge(t,e);return K(i,r),r}}else{let n=ge(t,e);return K(i,n),n}}var En={".":"&dot;","/":"&slash;",":":"&colon;"};function Ai(i){return i.replace(/[/]/g,En["/"]).replace(/[:]/g,En[":"]).replace(/[.]/g,En["."])}function Bi(i){return i.replace(/&slash;/g,"/").replace(/&colon;/g,":").replace(/&dot;/g,".")}function Z(i,t,e){let n=Ai(i)+Dr+Ai(t);return e&&(n+=It+e),n}function ge(i,t=Ar){let{collection:e,id:n}=ae(i);return Z(e,n,t())}function ae(i){let[t,e]=i.split(It),[n,r]=t.split("/"),s;return r.includes(".")?s=r.slice(0,r.indexOf(".")):s=r,{collection:Bi(n),id:Bi(s),subId:e}}function je(i,t){let e=ue(i);if(Array.isArray(i)){let n;for(let r=0;r<i.length;r++)n=i[r],N(n)&&!ie(n)&&(Ti(n,e,t),je(n,t))}else if(N(i)&&!ie(i))for(let n of Object.keys(i))N(i[n])&&!ie(i[n])&&(Ti(i[n],e,t),je(i[n],t))}function Cr(i,t){return V(N(i),`Only objects can be assigned OIDs, received ${JSON.stringify(i)}`),i[Se]=t,i}function Er(i){if(N(i))return i[Se]||i[Ie]}function _r(i){return N(i)&&(delete i[Ie],delete i[Se]),i}function Pr(i){let t=oe(i);t&&Cr(i,t)}function Le(i){if(Pr(i),Array.isArray(i))for(let t=0;t<i.length;t++)Le(i[t]);else if(N(i))for(let t of Object.keys(i))Le(i[t])}function Tr(i){let t=Er(i);t&&K(i,t)}function Xe(i){if(Tr(i),_r(i),Array.isArray(i))for(let t=0;t<i.length;t++)Xe(i[t]);else if(N(i))for(let t of Object.keys(i))Xe(i[t])}function xt(i){if(Dt(i),Array.isArray(i))for(let t=0;t<i.length;t++)xt(i[t]);else if(N(i))for(let t of Object.keys(i))xt(i[t])}function Ar(){return Ge().slice(0,8)}function be(i){return{"@@type":"ref",id:i}}function Ot(i,t=new Map){if(Array.isArray(i)){let e=ue(i),n=K([],e);for(let r=0;r<i.length;r++){let s=i[r];if(N(s)){if(te(s))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(de(s)){n[r]=s;continue}else{let a=ue(s);n[r]=be(a),Ot(s,t)}}else n[r]=s}t.set(e,n)}else if(N(i)&&!ie(i)){let e=ue(i),n=K({},e);for(let r of Object.keys(i)){let s=i[r];if(N(s)){if(te(s))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(de(s))n[r]=s;else{let a=ue(s);n[r]=be(a),Ot(s,t)}}else n[r]=s}t.set(e,n)}else ie(i);return t}function $(i){return i.split(".")[0].split(It)[0]}function An(i){let t=$(i);return[t,`${t}${It}\uFFFF`]}function Ct(i,t){return $(i)===$(t)}function te(i){return i&&typeof i=="object"&&i["@@type"]==="ref"}function Bn(i){return N(i)&&!ie(i)}function Br(i,t){return i===t?!0:ie(i)&&ie(t)?xi(i,t):!1}function et(i,t,e,n,r=[],s={}){let a=ue(i);function d(h,m,C){if(!Bn(m))Br(m,C)||r.push({oid:a,timestamp:e(),data:{op:"set",name:h,value:m}});else{let P=oe(C),v=oe(m);v&&!Ct(a,v)?(m=ne(m,!1),v=ge(a,n),K(m,v)):s.mergeUnknownObjects?!v&&P?(K(m,P),v=P):v=Tn(m,a,n):v=Tn(m,a,n),V(!!v,"Error: no value OID was resolved during diff. This is a bug in Verdant."),V(Ct(a,v),`Error: value OID ${v} is not related to parent OID ${a}. This is a bug in Verdant.`),C===void 0||v!==P?(xe(m,v,e,n,r),r.push({oid:a,timestamp:e(),data:{op:"set",name:h,value:be(v)}}),P!==void 0&&r.push({oid:P,timestamp:e(),data:{op:"delete"}})):et(C,m,e,n,r,s)}}if(Array.isArray(i)&&Array.isArray(t)){for(let m=0;m<t.length;m++){let C=t[m],P=i[m];d(m,C,P)}let h=i.length-t.length;if(h>0){for(let m=t.length;m<i.length;m++){let C=i[m],P=oe(C);P&&r.push({oid:P,timestamp:e(),data:{op:"delete"}})}r.push({oid:a,timestamp:e(),data:{op:"list-delete",index:t.length,count:h}})}}else{if(Array.isArray(i)||Array.isArray(t))throw new Error("Cannot diff an array with an object");if(Bn(i)&&Bn(t)){let h=new Set(Object.keys(i));for(let[m,C]of Object.entries(t)){if(C===void 0&&s.defaultUndefined||(h.delete(m),Pn(m)))continue;let P=i[m];d(m,C,P)}if(!s.defaultUndefined)for(let m of h)Pn(m)||r.push({oid:a,timestamp:e(),data:{op:"remove",name:m}})}}return r}function xe(i,t,e,n,r=[]){K(i,t),je(i,n);let s=Ot(i);for(let a of s.keys()){let d=s.get(a);r.push({oid:a,timestamp:e(),data:{op:"initialize",value:Dt(d)}})}return r}function Fi(i){let t={};for(let e of i)e.oid in t?t[e.oid].push(e):t[e.oid]=[e];return t}function kn(i){let t={};for(let e of i){let n=$(e.oid);n in t?t[n].push(e):t[n]=[e]}return t}function Fn(i){let t={};for(let e of i){let n=$(e.oid);n in t?t[n].push(e):t[n]=[e]}return t}function De(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: ${oe(i)})`),!1)}function Ce(i,t,e){if(i==null&&t.op!=="initialize")return i;let n=i,r,s;function a(d){e&&ie(d)&&e.push(d)}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":De(i)&&i.push(t.value);break;case"list-delete":De(i)&&(a(i[t.index]),i.splice(t.index,t.count));break;case"list-move-by-index":De(i)&&(s=i.splice(t.from,1),i.splice(t.to,0,s[0]));break;case"list-remove":if(De(i))do{let d=t.value;t.only==="last"?te(d)?r=_i(i,h=>h.id===d.id):r=i.lastIndexOf(d):te(d)?r=i.findIndex(h=>h.id===d.id):r=i.indexOf(d),r!==-1&&(a(i[r]),i.splice(r,1))}while(!t.only&&r!==-1);break;case"list-add":De(i)&&(i.some(h=>te(h)&&te(t.value)?h.id===t.value.id:h===t.value)||i.push(t.value));break;case"list-move-by-ref":De(i)&&(r=i.indexOf(t.value),s=i.splice(r,1),i.splice(t.index,0,s[0]));break;case"list-insert":if(De(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):N(i)&&Object.values(i||{}).forEach(a);return;case"initialize":return ne(t.value);default:throw new Error(`Unsupported patch operation: ${t.op}`)}return i}function Et(i,t,e=[]){if(Array.isArray(i))for(let n=0;n<i.length;n++){let r=i[n];i[n]=ki(r,t,e),N(i[n])&&Et(i[n],t,e)}else if(!de(i)){if(N(i)){V(oe(i),`Object ${JSON.stringify(i)} must have an oid`);for(let n of Object.keys(i))i[n]=ki(i[n],t,e),N(i[n])&&Et(i[n],t,e)}}return e}function ki(i,t,e){if(te(i)){e.push(i.id);let n=t.get(i.id);return V(!!n,`No value was found in object map for ${i.id}`),K(n,i.id)}else return i}function Rn(i){return i.equals!==void 0}function Mn(i){return i.gte!==void 0||i.lte!==void 0||i.gt!==void 0||i.lt!==void 0}function kr(i){return!!i.match}function jn(i){return i.startsWith!==void 0}function Ri(i){return!Mn(i)&&!Rn(i)&&!kr(i)&&!jn(i)&&i.order}function Fr(i){return i.type==="any"?!0:i.type==="map"?!1:i.nullable}function _e(i,t){for(let[e,n]of Object.entries(i.fields)){let r=Mi(n);(r!==void 0&&t[e]===void 0||!Fr(n)&&t[e]===null)&&(t[e]=r),t[e]&&Ee(t[e],n)}return t}function Ee(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=Mi(n);r!==void 0&&(i[e]=r)}Ee(i[e],n)}else if(t.type==="array")for(let e of i)Ee(e,t.items);else if(t.type==="map")for(let[e,n]of Object.entries(i))e===Se||e===Ie||Ee(n,t.values)}function Mi(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 ji(i,t){for(let[e,n]of Object.entries(t))e===Se||e===Ie||(i.fields[e]?Ln(n,i.fields[e]):delete t[e]);return t}function Ln(i,t){if(N(i)&&t.type==="object")for(let[e,n]of Object.entries(i))t.properties[e]?Ln(n,t.properties[e]):delete i[e];else if(Array.isArray(i)&&t.type==="array")for(let e of i)Ln(e,t.items)}function Li(i){return i}function Vi(i){return i}var _t="\uFFFFFE",Rr="\0",Mr="\uFFFFFF";function ce(...i){let t=jr(i);return t.length===1?t[0]:t}function Pe(...i){return i.join(_t)+`${Mr}`}function Te(...i){return i.join(_t)+`${_t}${Rr}`}function jr(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(_t))))}function Lr(i,t){let e={};for(let[n,r]of Object.entries(i.synthetics||{}))e[n]=ve(r.compute(t));return e}function Vr(i,t){return Object.entries(i.compounds||{}).reduce((e,[n,r])=>(e[n]=ce(...r.of.map(s=>t[s])),e),{})}function Pt(i,t){return Object.assign(t,Lr(i,t)),Object.assign(t,Vr(i,t)),t}var Ur="null";function ve(i){if(i===null)return Ur;if(typeof i=="string"||typeof i=="number")return i;if(typeof i=="boolean"||i===null)return`${i}`;if(i===void 0)return"undefined";if(Array.isArray(i))return i.map(ve);throw new Error(`Unsupported index value: ${i}`)}var Nr={version:0,collections:{}};function Tt(i,t,e){let n=typeof t=="function",r=n?Nr:i,s=n?i:t,a=n?t:e,d=Object.keys(s.collections).filter(I=>r.collections[I]&&Cn(r.collections[I])!==Cn(s.collections[I])),h=Object.keys(r.collections).filter(I=>!s.collections[I]),m=Object.keys(s.collections).filter(I=>!r.collections[I]),C=new Set;for(let I of d){let D=r.collections[I].fields,O=s.collections[I].fields;Object.keys(O).some(x=>!D[x]?.default&&O[x]?.default)&&C.add(I),Object.keys(D).some(x=>!O[x])&&C.add(I)}let P={},v={};for(let I of[...d,...m]){let D=Ui(r.collections[I]),O=Ui(s.collections[I]),x=O.filter(y=>!D.find(w=>w.name===y.name)),A=D.filter(y=>!O.find(w=>w.name===y.name));x.length>0&&(P[I]=x,d.includes(I)&&C.add(I)),A.length>0&&(v[I]=A,d.includes(I)&&C.add(I))}let T=(I,D)=>_e(s.collections[I],D),b=I=>D=>{let O=s.collections[I];return _e(O,ji(O,D))};return{version:s.version,migrate:async I=>{let D=[];if(await a({migrate:async(O,x)=>{let A=b(O),y=async w=>{let l=await x(w);return K(l,ue(w)),A(l)};await I.migrate(O,y),D.push(O),C.delete(O)},identity:O=>O,withDefaults:T,info:{changedCollections:d,addedCollections:m,removedCollections:h},queries:I.queries,mutations:I.mutations}),s.version>1){I.log("debug","auto-migrating collections with new defaults",C);for(let x of C)await I.migrate(x,b(x)),D.push(x);let O=d.filter(x=>!D.includes(x));O.length>0&&console.error(`Unmigrated changed collections from version ${r.version} to version ${s.version}:`,O)}},removedCollections:h,addedIndexes:P,removedIndexes:v,allCollections:Object.keys(s.collections),changedCollections:d,addedCollections:m,oldCollections:Object.keys(r.collections),oldSchema:r,newSchema:s}}function Ui(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 Vn(i,t){return Tt(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 At=class{constructor(t,e){this.getNow=t;this.createSubId=e;this.createDiff=(t,e,n={})=>et(t,e,this.getNow,this.createSubId,[],n);this.createInitialize=(t,e)=>xe(t,e,this.getNow,this.createSubId);this.createSet=(t,e,n)=>{if(!N(n)||ie(n))return[{oid:t,timestamp:this.getNow(),data:{op:"set",name:e,value:n}}];{let r=ge(t,this.createSubId);return[...xe(n,r,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"set",value:be(r),name:e}}]}};this.createRemove=(t,e)=>[{oid:t,timestamp:this.getNow(),data:{op:"remove",name:e}}];this.createListPush=(t,e)=>{if(N(e)){let n=ge(t,this.createSubId);return[...xe(e,n,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:be(n)}}]}else return[{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:e}}]};this.createListAdd=(t,e)=>N(e)?[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:be(e)}}]:[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:e}}];this.createListInsert=(t,e,n)=>{if(N(n)){let r=ge(t,this.createSubId);return[...xe(n,r,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:be(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 U=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=St(),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 Ni(i,t,e,n){if(t===void 0)return[{oid:i,timestamp:n(),data:{op:"delete"}}];let r=ne(t),s=[];for(let a of e){let d=Kr(i,r,a,n);s.unshift(...d),Ce(r,a.data)}return s}function Kr(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(d=>({oid:i,timestamp:n(),data:{op:"list-insert",index:d,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 Ve=class{constructor(t){this.flusher=t;this.batches=new Map;this.flush=t=>{let e=this.batches.get(t);if(e)return e.flush()};this.discard=t=>{let e=this.batches.get(t);e&&(e.discard(),this.batches.delete(t))};this.flushAll=()=>[...this.batches.values()].map(t=>t.flush())}add({key:t,userData:e,items:n,max:r,timeout:s}){let a=this.batches.get(t);return a||(a=new Un({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}},Un=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 W(i){return new Promise((t,e)=>{i.onsuccess=()=>{t(i.result)},i.onerror=()=>{e(i.error)}})}function tt(i,t){return new Promise((e,n)=>{let r=i.transaction([t],"readonly"),a=r.objectStore(t).openCursor(),d=0,h=0;a.onsuccess=function(m){let C=a.result;C&&(d++,h=h+Ei(C.value),C.continue())},a.onerror=function(m){n(m)},r.oncomplete=function(m){e({count:d,size:h})},r.onabort=function(m){n(m)},r.onerror=function(m){n(m)}})}function Ki(i,t){let e=i.transaction(t,"readonly"),n=t.map(r=>{let s=e.objectStore(r);return W(s.getAll())});return Promise.all(n)}async function Ae(i){i.close(),await new Promise((t,e)=>{t()})}async function Bt(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()}function zi(i,t=window.indexedDB){return W(t.deleteDatabase(i))}async function $i(i=window.indexedDB){return i.databases()}var pe=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),d=e(a);return W(d)};this.runAll=async(t,e,n="readonly",r)=>{let a=(r||this.db.transaction(t,n)).objectStore(t),d=e(a);return Promise.all(d.map(W))};this.iterate=async(t,e,n,r="readonly",s)=>{let d=(s||this.db.transaction(t,r)).objectStore(t),h=e(d);return new Promise((m,C)=>{h.onsuccess=P=>{let v=h.result;v?(n(v.value,d),v.continue()):m()},h.onerror=C})};this.clear=t=>this.run(t,e=>e.clear(),"readwrite")}};var kt=class extends pe{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 Ft=class extends pe{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[d,h]=An(e);return a.openCursor(IDBKeyRange.bound(d,h,!1,!1))},n,r,s);this.getAllForMultipleDocuments=async(e,{mode:n="readonly"}={})=>(await this.runAll("baselines",s=>e.map(a=>{let[d,h]=An(a);return s.getAll(IDBKeyRange.bound(d,h,!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 qi=dt(ft(),1);var Rt=class extends pe{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,qi.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 Mt=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(d=>{r.push({data:d.data,oid:d.oid,timestamp:d.timestamp}),s.add($(d.oid))},{after:n,mode:"readwrite"}):await this.meta.operations.iterateOverAllOperations(d=>{r.push({data:d.data,oid:d.oid,timestamp:d.timestamp}),s.add($(d.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 jt=class extends pe{constructor(){super(...arguments);this.iterateOverAllOperationsForDocument=async(e,n,{to:r,from:s,after:a,mode:d="readonly",transaction:h}={})=>{let C=(h||this.db.transaction("operations",d)).objectStore("operations"),P=C.index("d_t"),v=s||a,T=v?ce(e,v):Te(e),b=r?ce(e,r):Pe(e),I=IDBKeyRange.bound(T,b,!!a,!1),D=P.openCursor(I,"next");return new Promise((O,x)=>{let A;D.onsuccess=y=>{let w=D.result;if(w){let l=w.value;V(l.oid.startsWith(e)),V(A===void 0||A<=l.timestamp,`expected ${A} <= ${l.timestamp}`),n(l,C),A=l.timestamp,w.continue()}else O()},D.onerror=y=>{x(y)}})};this.iterateOverAllOperationsForEntity=async(e,n,{after:r,to:s,mode:a,transaction:d})=>{let m=(d||this.db.transaction("operations",a)).objectStore("operations"),C=r?ce(e,r):Te(e),P=s?ce(e,s):Pe(e),v=IDBKeyRange.bound(C,P,!!r,!1),T=m.openCursor(v,"next");return new Promise((b,I)=>{let D;T.onsuccess=O=>{let x=T.result;if(x){let A=x.value;V(A.oid.startsWith(e)),V(D===void 0||D<=A.timestamp,`expected ${D} <= ${A.timestamp}`),n(A,m),D=A.timestamp,x.continue()}else b()},T.onerror=O=>{I(O)}})};this.iterateOverAllLocalOperations=async(e,{before:n,after:r,mode:s="readonly",transaction:a})=>{let h=(a||this.db.transaction("operations",s)).objectStore("operations"),m=h.index("l_t"),C=r?ce(!0,r):Te(!0),P=n?ce(!0,n):Pe(!0),v=IDBKeyRange.bound(C,P,!!r,!0),T=m.openCursor(v,"next");return new Promise((b,I)=>{let D;T.onsuccess=O=>{let x=T.result;if(x){let A=x.value;V(D===void 0||D<=A.timestamp,`expected ${D} <= ${A.timestamp}`),e(A,h),D=A.timestamp,x.continue()}else b()},T.onerror=O=>{I(O)}})};this.iterateOverAllOperations=async(e,{before:n,transaction:r,mode:s,from:a})=>{await this.iterate("operations",d=>{let h=a?Te(a):void 0,m=n?Pe(n):void 0,C=h&&m?IDBKeyRange.bound(h,m,!1,!0):h?IDBKeyRange.lowerBound(h,!1):m?IDBKeyRange.upperBound(m,!0):void 0;return d.index("timestamp").openCursor(C,"next")},e,s,r)};this.addOperations=async(e,{transaction:n}={})=>this.insert(e.map(this.addCompoundIndexes),{transaction:n});this.addCompoundIndexes=e=>({...e,oid_timestamp:ce(e.oid,e.timestamp),l_t:ce(e.isLocal,e.timestamp),d_t:ce($(e.oid),e.timestamp)});this.insert=async(e,{transaction:n})=>{let r=new Set;return await this.runAll("operations",s=>e.map(a=>(r.add($(a.oid)),s.put(a))),"readwrite",n),Array.from(r)};this.reset=()=>this.clear("operations")}};var Lt=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 W(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 W(s)}}};var nt=class extends U{constructor({disableRebasing:e,context:n}){super();this.time=new mt;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=$(e);V(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,n={})=>{let r=$(e);V(r===e,"Must be root document OID");let s=this.db.transaction(["baselines","operations"],"readwrite"),a=await this.baselines.getAllForDocument(r,{transaction:s}),d=new Map;for(let m of a)m.snapshot&&K(m.snapshot,m.oid),d.set(m.oid,m.snapshot);await this.operations.iterateOverAllOperationsForDocument(r,m=>{let C=d.get(m.oid)||void 0,P=Ce(C,m.data);P&&K(P,m.oid),d.set(m.oid,P)},{transaction:s,to:n.to||this.now});let h=d.get(r);return h&&Et(h,d),h};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($(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(h=>{r.add(h.oid),n=h.timestamp,a++},{before:e,transaction:s}),!r.size){this.log("Cannot rebase, no operations prior to",e);return}if(this._closing)return;let d=[];for(let h of r)d.push(await this.rebase(h,n||e,s));this.emit("rebase",d)};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"),d=await this.baselines.get(e,{transaction:a}),h=d?.snapshot||void 0,m=0,C=[];await this.operations.iterateOverAllOperationsForEntity(e,(v,T)=>{(!d||v.timestamp>d.timestamp)&&(h=Ce(h,v.data,C)),m++,T.delete(v.oid_timestamp)},{to:n,transaction:a}),h&&K(h,e);let P={oid:e,snapshot:h,timestamp:n};if(P.snapshot?await this.baselines.set(P,{transaction:a}):await this.baselines.delete(e,{transaction:a}),this.log("successfully rebased",e,"up to",n,":",h,"and deleted",m,"operations"),C.length){let v=C.filter(de);v.length&&this.emit("filesDeleted",v)}return P};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
7
  ${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 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}});try{await o.migrate(c),await Promise.all(c.awaitables)}catch(p){throw r.log("critical",`Migration failed (${o.oldSchema.version} -> ${o.newSchema.version})`,p),p}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,{to:n.time.now(o.newSchema.version)});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
- \u2B06\uFE0F v${o.newSchema.version} Migration complete. Here's the rundown:
5
- - Added collections: ${o.addedCollections.join(", ")}
6
- - Removed collections: ${o.removedCollections.join(", ")}
7
- - Changed collections: ${o.changedCollections.join(", ")}
8
- - New indexes: ${Object.keys(o.addedIndexes).map(d=>o.addedIndexes[d].map(p=>`${d}.${p.name}`)).flatMap(d=>d).join(", ")}
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(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,{to:e.time.now(i.oldSchema.version)})},findOne:async s=>{let a=await lt({collection:r,index:s,context:t});return a?await e.getDocumentSnapshot(a,{to:e.time.now(i.oldSchema.version)}):null},findAll:async s=>{let a=await dt({collection:r,index:s,context:t});return await Promise.all(a.map(c=>e.getDocumentSnapshot(c,{to:e.time.now(i.oldSchema.version)})))}},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.filter(Boolean).map(async p=>{y(xe(p),`Document is missing an OID: ${JSON.stringify(p)}`);let g=R(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 R(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)=>{t instanceof File||(t=R(t,!1));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=R(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=R(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;
8
+ ${JSON.stringify(e)}`),new Error("Schema has changed without a version change! Any changes to your schema must be accompanied by a change in schema version and a migration routine.");await this.schema.set(e)};this.setGlobalAck=async e=>{this._closing||(await this.ackInfo.setGlobalAck(e),this.disableRebasing||await this.runRebase(e))};this.export=async()=>{let e=this.db,[n,r]=await Ki(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 W(r.objectStore("baselines").clear()),await W(r.objectStore("operations").clear()),await W(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 tt(e,"operations"),r=await tt(e,"baselines");return{operationsSize:n,baselinesSize:r}};this.context=n,this.schema=new Lt(n.metaDb,n.schema.version),this.operations=new jt(this.db),this.baselines=new Ft(this.db),this.localReplica=new Rt(this.db),this.ackInfo=new kt(this.db),this.messageCreator=new Mt(this),this.patchCreator=new At(()=>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 zr=[$r,qr,Wr,Hr];function Vt({indexedDB:i=window.indexedDB,namespace:t,log:e}){return new Promise((n,r)=>{let s=i.open(`${t}_meta`,4),a=!1;s.onupgradeneeded=async d=>{let h=s.result,m=s.transaction,C=zr.slice(d.oldVersion);for(let P of C)await P(h,m);d.oldVersion||(a=!0)},s.onerror=()=>{console.error("Error opening database",s.error),r(s.error)},s.onsuccess=()=>{n({db:s.result,wasInitialized:a})}})}async function Wi({wipNamespace:i,namespace:t,indexedDB:e,log:n}){let r=await Vt({namespace:i,indexedDB:e,log:n});if(!r.wasInitialized)return r;n?.("debug","Beginning copy of production metadata database to WIP");let{db:s}=await Vt({namespace:t,indexedDB:e,log:n}),a=s.transaction(["baselines","operations","info"],"readonly"),[d,h,m]=await Promise.all([W(a.objectStore("baselines").getAll()),W(a.objectStore("operations").getAll()),W(a.objectStore("info").getAll())]),C=r.db.transaction(["baselines","operations","info"],"readwrite"),P=C.objectStore("baselines"),v=C.objectStore("operations"),T=C.objectStore("info");for(let b of d)P.put(b);for(let b of h)v.put(b);for(let b of m)T.put(b);return await new Promise((b,I)=>{C.oncomplete=()=>{b()},C.onerror=D=>{I(D)},C.onabort=D=>{I(D)}}),await Ae(s),n?.("debug","Finished copy of production metadata database to WIP. Copied:",d.length,"baselines,",h.length,"operations"),r}async function $r(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 qr(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:d,documentOid_timestamp:h,...m}=a.value;a.update({...m,l_t:d,d_t:h}),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 Wr(i,t){t.objectStore("operations").createIndex("timestamp","timestamp")}async function Hr(i,t){let e=i.createObjectStore("files",{keyPath:"id"});e.createIndex("remote","remote"),e.createIndex("deletedAt","deletedAt")}var Qr=i=>IDBKeyRange.only(ve(i.equals)),Jr=i=>{},Yr=i=>{let t=i.gte||i.gt,e=i.lte||i.lt;return t===e?IDBKeyRange.only(ve(t)):t?e?IDBKeyRange.bound(ve(t),ve(e),!!i.gt,!!i.lt):IDBKeyRange.lowerBound(ve(t),!!i.gt):IDBKeyRange.upperBound(ve(e),!!i.lt)},Gr=(i,t,e)=>{let n=i.collections[t].compounds[e.where];V(n,`Index ${e.where} does not exist on collection ${t}`);let r=Object.keys(e.match).sort((h,m)=>n.of.indexOf(h)-n.of.indexOf(m));for(let h of r)if(n.of.indexOf(h)!==r.indexOf(h))throw new Error(`Compound index ${e.where} does not have ${h} at the start of its order`);let s=r.map(h=>e.match[h]);if(r.length===n.of.length)return IDBKeyRange.only(ce(...s));let a=Te(...s),d=Pe(...s);return IDBKeyRange.bound(a,d)};function Xr(i){let t=i.startsWith,e=i.startsWith+"\uFFFF";return IDBKeyRange.bound(t,e)}function Ut(i,t,e){if(e)return Mn(e)?Yr(e):Rn(e)?Qr(e):Ri(e)?Jr(e):jn(e)?Xr(e):Gr(i,t,e)}function Nn(i,t,e){return i.transaction(t,e?"readwrite":"readonly").objectStore(t)}async function Nt({collection:i,index:t,context:e}){let n=Nn(e.documentDb,i),r=t?n.index(t.where):n,s=Ut(e.schema,i,t),a=t?.order==="desc"?"prev":"next",d=r.openCursor(s,a);return await new Promise((m,C)=>{d.onsuccess=()=>{let P=d.result;m(P?Z(i,P.primaryKey.toString()):null)},d.onerror=()=>{d.error?.name==="InvalidStateError"?(e.log("error","findOne query failed with InvalidStateError",d.error),m(null)):C(d.error)}})}async function Kt({collection:i,index:t,context:e}){let n=Nn(e.documentDb,i),r=t?n.index(t.where):n,s=Ut(e.schema,i,t),a=t?.order==="desc"?"prev":"next",d=r.openCursor(s,a);return await new Promise((m,C)=>{let P=new Set;d.onsuccess=()=>{let v=d.result;v?(P.add(Z(i,v.primaryKey.toString())),v.continue()):m(Array.from(P))},d.onerror=()=>{d.error?.name==="InvalidStateError"?(e.log("error","findAll query failed with InvalidStateError",d.error),m([])):C(d.error)}})}async function it({collection:i,index:t,context:e,limit:n,offset:r}){let s=Nn(e.documentDb,i),a=t?s.index(t.where):s,d=Ut(e.schema,i,t),h=t?.order==="desc"?"prev":"next",m=a.openCursor(d,h),C=!r,P=!1,v=0;return{result:await new Promise((b,I)=>{let D=new Set;m.onsuccess=()=>{v++;let O=m.result;O?r&&!C?(O.advance(r),C=!0):(n&&D.size<n&&D.add(Z(i,O.primaryKey.toString())),n&&v>n?(P=!0,b(Array.from(D))):O.continue()):b(Array.from(D))},m.onerror=()=>{m.error?.name==="InvalidStateError"?(e.log("error","find query failed with InvalidStateError",m.error),b([])):I(m.error)}}),hasNextPage:P}}async function Kn(i,t,e,n){function r(d,h){let m,C,P=i.open([t,"collections"].join("_"),e);P.onupgradeneeded=async v=>{m=v.oldVersion;let T=P.transaction;C=P.result,T.abort()},P.onsuccess=v=>{d([P.result.version,P.result])},P.onblocked=v=>{n?.("Database blocked, waiting...")},P.onerror=v=>{d([m,C])}}let[s,a]=await new Promise(r);return await zt(a),s}async function zt(i){i.close(),await new Promise(t=>t())}async function Hi(i,t,e,n,r){function s(a,d){let h=i.open([t,"collections"].join("_"),e),m=!1;h.onupgradeneeded=C=>{let P=h.transaction;n(P,h.result,C),m=!0},h.onsuccess=C=>{h.result.close(),m?a():d(new Error("Database was not upgraded when a version change was expected"))},h.onerror=C=>{d(h.error||new Error("Unknown error"))},h.onblocked=C=>{r?.("Database upgrade blocked, waiting...")}}return new Promise(s)}async function Qi(i,t){typeof navigator<"u"&&navigator.locks?await navigator.locks.request(`verdant_migration_${i}`,t):await t()}async function Be(i,t,e,n){n?.("debug","Opening database",t,"at version",e);let r=await new Promise((s,a)=>{let d=i.open([t,"collections"].join("_"),e);d.onupgradeneeded=async h=>{d.transaction.abort(),n?.("error","Database upgrade needed, but not expected","Expected",e,"Got",d.result.version),a(d.error||new Error(`Migration error: database version changed unexpectedly when reading current data. Expected ${e}, got ${d.result.version}`))},d.onsuccess=h=>{s(d.result)},d.onblocked=h=>{a(new Error("Migration error: database blocked"))},d.onerror=h=>{a(new Error("Migration error: database error"))}});return r.addEventListener("versionchange",s=>{r.close()}),r}var Ue=class extends Error{constructor(e){super(e);this.message=e;this.name="MigrationPathError"}};function $t({currentVersion:i,targetVersion:t,migrations:e}){let n=Ji({currentVersion:i,targetVersion:t,migrations:e});if(!n)throw new Ue(`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 Ji({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=Ji({currentVersion:r.newSchema.version,targetVersion:t,migrations:e});if(s)return[r,...s]}return null}var $n=typeof window<"u"?window.indexedDB:void 0;async function rt({version:i,indexedDB:t=$n,migrations:e,meta:n,context:r}){if(r.schema.wip)throw new Error("Cannot open a production client with a WIP schema!");let s=await Kn(t,r.namespace,i,r.log);r.log("debug","Current database version:",s,"target version:",i);let a=$t({currentVersion:s,targetVersion:i,migrations:e});return a.length>0&&(r.log("debug","Migrations to run:",a.map(d=>d.version)),await zn({context:r,toRun:a,meta:n,indexedDB:t})),Be(t,r.namespace,i,r.log)}async function Yi({version:i,indexedDB:t=$n,migrations:e,meta:n,context:r,wipNamespace:s}){r.log("debug","Opening WIP database",s);let a=await Kn(t,s,i,r.log);if(a===i)r.log("info","WIP schema is up-to-date; not refreshing database");else{r.log("info","WIP schema is out-of-date; refreshing database");let d=$t({currentVersion:a,targetVersion:i-1,migrations:e});if(d.length>0){await zn({context:r,toRun:d,meta:n,indexedDB:t,namespace:s});let m=await Be(t,r.namespace,i-1,r.log),C=await Be(t,s,i-1,r.log),P=new Array;for(let O=0;O<m.objectStoreNames.length;O++)P.push(m.objectStoreNames[O]);let v=m.transaction(P,"readonly"),T=P.map(O=>v.objectStore(O)),b=await Promise.all(T.map(O=>W(O.getAll()))),I=C.transaction(P,"readwrite"),D=P.map(O=>I.objectStore(O));for(let O=0;O<D.length;O++)await Promise.all(b[O].map(x=>W(D[O].put(x))))}let h=$t({currentVersion:i-1,targetVersion:i,migrations:e});h.length>0&&await zn({context:r,toRun:h,meta:n,indexedDB:t,namespace:s})}return Be(t,s,i,r.log)}async function zn({context:i,toRun:t,meta:e,indexedDB:n=$n,namespace:r=i.namespace}){await Qi(r,async()=>{for(let s of t){let a;if(s.oldSchema.version===0)a=ts({meta:e,migration:s,context:i}),await s.migrate(a);else{let m=await Be(n,r,s.oldSchema.version,i.log);a=es({meta:e,migration:s,context:{...i,documentDb:m}});try{await s.migrate(a),await Promise.all(a.awaitables)}catch(C){throw i.log("critical",`Migration failed (${s.oldSchema.version} -> ${s.newSchema.version})`,C),C}await zt(m)}i.log("debug","Upgrading database",r,"to version",s.newSchema.version),await Hi(n,r,s.newSchema.version,(m,C)=>{for(let P of s.addedCollections)C.createObjectStore(P,{keyPath:s.newSchema.collections[P].primaryKey,autoIncrement:!1});for(let P of s.allCollections){let v=m.objectStore(P);for(let T of s.addedIndexes[P]||[])v.createIndex(T.name,T.name,{multiEntry:T.multiEntry});for(let T of s.removedIndexes[P]||[])v.deleteIndex(T.name)}for(let P of s.removedCollections)m.objectStore(P).clear()},i.log);let d=await ss({meta:e,currentVersion:s.oldSchema.version,newVersion:s.newSchema.version}),h=await Be(n,r,s.newSchema.version,i.log);for(let m of s.allCollections){let P=h.transaction(m,"readwrite").objectStore(m),T=(await ns(P)).map(x=>Z(m,`${x}`));T.push(...a.newOids.filter(x=>ae(x).collection===m),...d.filter(x=>ae(x).collection===m));let I=(await Promise.all(T.map(async x=>{try{let A=await e.getDocumentSnapshot(x);return[x,A]}catch(A){return i.log("error","Could not regenerate snapshot during migration for oid",x,"this document will not be preserved",A),null}}))).filter(x=>!!x).map(([x,A])=>{if(!A)return[x,void 0];let y=Pt(s.newSchema.collections[m],A);return Le(y),[x,y]}),O=h.transaction(m,"readwrite").objectStore(m);await Promise.all(I.map(([x,A])=>{if(A)return rs(O,A);{let{id:y}=ae(x);return is(O,y)}}))}await zt(h),i.log("debug",`Migration of ${r} complete.`),i.log(`
9
+ \u2B06\uFE0F v${s.newSchema.version} Migration complete. Here's the rundown:
10
+ - Added collections: ${s.addedCollections.join(", ")}
11
+ - Removed collections: ${s.removedCollections.join(", ")}
12
+ - Changed collections: ${s.changedCollections.join(", ")}
13
+ - New indexes: ${Object.keys(s.addedIndexes).map(m=>s.addedIndexes[m].map(C=>`${m}.${C.name}`)).flatMap(m=>m).join(", ")}
14
+ - Removed indexes: ${Object.keys(s.removedIndexes).map(m=>s.removedIndexes[m].map(C=>`${m}.${C.name}`)).flatMap(m=>m).join(", ")}
15
+ `)}})}function Gi({migration:i,meta:t,getMigrationNow:e,newOids:n}){return i.allCollections.reduce((r,s)=>(r[s]={put:async a=>{_e(i.newSchema.collections[s],a);let d=a[i.newSchema.collections[s].primaryKey],h=Z(s,d);return n.push(h),await t.insertLocalOperation(xe(a,h,e)),a},delete:a=>{let d=Z(s,a);return t.insertLocalOperation([{oid:d,timestamp:e(),data:{op:"delete"}}])}},r),{})}function Zr({migration:i,context:t,meta:e}){return i.oldCollections.reduce((n,r)=>(n[r]={get:async s=>{let a=Z(r,s);return await e.getDocumentSnapshot(a,{to:e.time.now(i.oldSchema.version)})},findOne:async s=>{let a=await Nt({collection:r,index:s,context:t});return a?await e.getDocumentSnapshot(a,{to:e.time.now(i.oldSchema.version)}):null},findAll:async s=>{let a=await Kt({collection:r,index:s,context:t});return await Promise.all(a.map(h=>e.getDocumentSnapshot(h,{to:e.time.now(i.oldSchema.version)})))}},n),{})}function es({meta:i,migration:t,context:e}){function n(){return i.time.zero(t.version)}let r=new Array,s=Zr({migration:t,context:e,meta:i}),a=Gi({migration:t,getMigrationNow:n,newOids:r,meta:i}),d=new Array;return{log:e.log,newOids:r,migrate:async(m,C)=>{let P=await s[m].findAll();await Promise.all(P.filter(Boolean).map(async v=>{V(Ze(v),`Document is missing an OID: ${JSON.stringify(v)}`);let T=ne(v),b=await C(v);if(b){Xe(T),Xe(b),je(b);let I=et(T,b,n,void 0,[],{mergeUnknownObjects:!0});I.length>0&&await i.insertLocalOperation(I)}}))},queries:s,mutations:a,awaitables:d}}function ts({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=Gi({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 ns(i){return new Promise((t,e)=>{let n=i.getAllKeys();n.onsuccess=r=>{t(n.result)},n.onerror=r=>{e(n.error)}})}async function is(i,t){let e=i.delete(t);return new Promise((n,r)=>{e.onsuccess=s=>{n()},e.onerror=s=>{r(e.error)}})}async function rs(i,t){let e=i.put(t);return new Promise((n,r)=>{e.onsuccess=s=>{n()},e.onerror=s=>{r(e.error)}})}async function ss({meta:i,currentVersion:t,newVersion:e}){let n=[];return await i.operations.iterateOverAllOperations(r=>n.push(r),{from:i.time.zero(t+1)}),Array.from(new Set(n.map(r=>$(r.oid))))}var st=class extends U{constructor(){super(...arguments);this._undoable=[];this._undone=[];this.undo=async()=>{let e=this._undoable.pop();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 qt=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 V(r,`Document must have a primary key: ${n.toString()} (got: ${JSON.stringify(e)})`),Z(t,r)};this.addDefaults=(t,e)=>{let n=this.schema.collections[t];return _e(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=Z(t,e);return this.entities.delete(r,n)};this.deleteAll=async(t,e={})=>this.entities.deleteAll(t.map(([n,r])=>Z(n,r)),e);this.deleteAllFromCollection=async(t,e,n={})=>this.entities.deleteAll(e.map(r=>Z(t,r)),n)}};var Ne=Symbol("entity-file-update"),ot=Symbol("entity-file-mark-failed"),os,as,ke=class extends U{constructor(e,{downloadRemote:n=!1}={}){super();this.id=e;this._objectUrl=null;this._fileData=null;this._loading=!0;this._failed=!1;this._disposed=!1;this._downloadRemote=!1;this[os]=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[as]=()=>{this._failed=!0,this._loading=!1,this.emit("change")};this.dispose=()=>{this._objectUrl&&URL.revokeObjectURL(this._objectUrl),this._disposed=!0};this._downloadRemote=n}static{os=Ne,as=ot}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 Xi=dt(ft(),1);function cs(i){return{id:(0,Xi.default)(),file:i,url:void 0,remote:!1,name:i.name,type:i.type}}function Fe(i,t){if(typeof window<"u"&&i instanceof File){let e=cs(i);return t(e),bi(e.id)}if(Array.isArray(i)){for(let e=0;e<i.length;e++)i[e]=Fe(i[e],t);return i}if(typeof i=="object"){for(let e in i)i[e]=Fe(i[e],t);return i}return i}function Zi(i){return new Promise((t,e)=>{let n=new FileReader;n.onload=()=>{t(n.result)},n.onerror=e,n.readAsArrayBuffer(i)})}var Wt=class extends pe{constructor(){super(...arguments);this.addFile=async(e,{transaction:n,downloadRemote:r=!1}={})=>{let s=e.file?await Zi(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?ls(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 ls(i,t){return new Blob([i],{type:t})}function ds(i){return i.deletedAt!==null&&i.deletedAt<Date.now()-1e3*60*24*3}var Ht=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)[Ne](e);else{let n=new ke(e.id);n[Ne](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 ke(t);return this.files.set(t,e),this.load(e),e};this.load=async(t,e=0)=>{if(e>5){t[ot]();return}let n=await this.storage.getFile(t.id);if(n)t[Ne](n);else try{let r=await this.sync.getFile(t.id);r.success?(t[Ne](r.data),await this.storage.addFile(r.data,{downloadRemote:t.downloadRemote})):(t[ot](),r.retry&&setTimeout(this.load,1e3,t,e+1))}catch(r){this.context.log("error","Failed to load file",r),t[ot](),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 Wt(t),this.sync=e,this.context=n,this.meta=r,this.config={canCleanupDeletedFile:ds,...s},this.sync.subscribe("onlineChange",this.onOnlineChange),this.meta.subscribe("filesDeleted",this.handleFileRefsDeleted),this.tryCleanupDeletedFiles()}};var Ke=class{constructor(t){this.value=t}deref(){return this.value}};var er="@@refresh",Qt="@@deepChange";function at(i,t){return i[er](t)}var us,ps,me=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[us]=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[Qt](this,t)),s&&(this.cachedSnapshot=null,this.events.emit("restore",t))};this[ps]=(t,e)=>{this.cachedSnapshot=null,this.cachedDeepUpdatedAt=null,this.events.emit("changeDeep",t,e);let n=this.parent?.deref();n&&n[Qt](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 ne(this._current)};this.getSubObject=(t,e)=>{let n=this.getChildFieldSchema(e);return this.cache.getEntity(t,n,this)};this.wrapValue=(t,e)=>{if(te(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(de(t)){let n=this.store.getFile(t.id);if(n)return n.subscribe("change",()=>{this[Qt](this,{isLocal:!1})}),n}return t};this.processInputValue=(t,e)=>{t instanceof File||(t=ne(t,!1));let n=this.getChildFieldSchema(e);return n&&Ee(t,n),Fe(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)=>te(e)?this.getSubObject(e.id,n)?.getSnapshot():e);else{t={...this.value};for(let[e,n]of Object.entries(t))te(n)&&(t[e]=this.getSubObject(n.id,e)?.getSnapshot())}return K(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 d=this.getChildFieldSchema(s);d&&Ee(a,d)}let r=Fe(t,this.store.addFile);this.addPatches(this.store.patchCreator.createDiff(this.getSnapshot(),K(r,this.oid),{mergeUnknownObjects:!e,defaultUndefined:n}))};this.getItemRefValue=t=>{if(typeof t=="object"){let e=oe(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(te(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=>te(e)?e.id===oe(t):(de(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:d}=ae(t);this.collection=d,this.parent=s&&new Ke(s),this.store=e,this.fieldSchema=n,this.cache=r;let{view:h,deleted:m,lastTimestamp:C}=this.cache.computeView(t);if(this._current=h,this._deleted=m,this._updatedAt=C||null,this.cachedDeepUpdatedAt=null,this.events=new U(()=>{this.hasSubscribers||a?.()}),this.oid.includes(".")&&!this.parent)throw new Error("Parent must be provided for sub entities");V(!!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}[(us=er,ps=Qt,Symbol.iterator)](){let t=0;return{next:()=>t<this.value.length?{value:this.get(t++),done:!1}:{value:void 0,done:!0}}}};var Jt=class{constructor(){let t,e;this.promise=new Promise((n,r)=>{t=n,e=r}),this._resolve=t,this._reject=e}resolve(t){this._resolve(t)}reject(t){this._reject(t)}};var Yt=class extends U{constructor({oid:e,store:n,context:r}){super();this.entities=new Map;this._initialized=new Jt;this.setInitialized=()=>{this._initialized.resolve(!0)};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&&(at(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)||[],d=a.findIndex(m=>m.timestamp>=r.timestamp);if(d!==-1){if(a[d].timestamp===r.timestamp)continue;a.splice(d,0,r)}else a.push(r);this.operationsMap.set(s,a);let h=this.localOperationsMap.get(s);h&&this.localOperationsMap.set(s,h.filter(m=>m.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 d=this.operationsMap.get(s)||[];for(;d[0]?.timestamp<r.timestamp;)d.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 d of this.entities.values()){let h=d.deref();h&&at(h,a)}else for(let d of a.affectedOids){let m=this.entities.get(d)?.deref();m&&(at(m,a),this.emit(`change:${d}`),this.emit("change:*",d))}};this.applyOperations=(e,n,r,s)=>{let a,d=this.storeTools.now;for(let h of r)if(!(s&&h.timestamp<=s)){if(gi(h.timestamp,d)>0){a=h.timestamp;continue}h.data.op==="delete"?n=!0:(e=Ce(e,h.data),h.data.op==="initialize"&&(n=!1))}return a&&this.context.globalEvents.emit("futureSeen",a),{view:e,deleted:n,empty:!e&&!r.length}};this.computeView=e=>{if(this.baselinesMap.size===0&&this.operationsMap.size===0&&this.localOperationsMap.size===0)return this.context.log("debug",`Entity ${e} accessed with no data at all`),{view:null,deleted:!0,lastTimestamp:null};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&&K(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=ne(n?.snapshot||void 0),a=this.applyOperations(s,!s,r,n?.timestamp);return a.view&&K(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 me({oid:e,cache:this,fieldSchema:n,store:this.storeTools,parent:r}),this.entities.set(e,new Ke(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=({operations:e,baselines:n,dropExistingUnconfirmed:r=!1,unconfirmedOperations:s,dropAll:a})=>{this.context.log("debug",`Resetting cache for ${this.oid} with ${e.length} ops and ${n.length} baselines, dropUnconfirmed=${r}`);let d={isLocal:!1,affectedOids:new Set};a&&this.baselinesMap.clear(),this.insertBaselines(n,d),a&&this.operationsMap.clear(),this.insertOperations(e,d),(s||r)&&(this.localOperationsMap.clear(),s&&this.insertLocalOperations(s));for(let h of this.entities.keys()){let C=this.entities.get(h)?.deref();C&&(at(C,d),this.emit(`change:${h}`),this.emit("change:*",h))}};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}get initializedPromise(){return this._initialized.promise}};var Gt="@@default",Xt=class{constructor({context:t,meta:e,batchTimeout:n=200,files:r}){this.documentFamilyCaches=new Map;this.unsubscribes=[];this._disposed=!1;this.currentBatchKey=Gt;this.setContext=t=>{this.context=t};this.getDocumentSchema=t=>{let{collection:e}=ae(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,n=!1)=>{if(this._disposed){this.context.log("debug",`EntityStore is disposed, not refreshing ${t.oid} cache`);return}let r=this.meta.createTransaction(["baselines","operations"]),s=[],a=[];await Promise.all([this.meta.baselines.iterateOverAllForDocument(t.oid,d=>{s.push(d)},{transaction:r,mode:"readwrite"}),this.meta.operations.iterateOverAllOperationsForDocument(t.oid,d=>{d.confirmed=!0,a.push(d)},{transaction:r,mode:"readwrite"})]),t.reset({operations:a,baselines:s,dropExistingUnconfirmed:e,dropAll:n})};this.openFamilyCache=async t=>{let e=$(t),n=this.documentFamilyCaches.get(e);return n||(this.context.log("debug","opening family cache for",e),n=new Yt({oid:e,store:this,context:this.context}),this.documentFamilyCaches.set(e,n),await this.refreshFamilyCache(n),n.setInitialized()),await n.initializedPromise,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=$(t),{id:n,collection:r}=ae(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 d=ne(a);Pt(this.schema.collections[r],d),Le(d);try{let m=this.db.transaction(r,"readwrite").objectStore(r);await W(m.put(d)),this.log("info","\u{1F4DD}","wrote",r,n,"to storage",d)}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",`
16
+ `,"Invalid data:",JSON.stringify(d))}}else{let h=this.db.transaction(r,"readwrite").objectStore(r);await W(h.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)=>{xt(t);let r=Fe(t,this.files.add);K(r,e);let s=this.meta.patchCreator.createInitialize(r,e),a=await this.openFamilyCache(e);a.insertLocalOperations(s),await this.submitOperations(s,n);let d=this.getDocumentSchema(e);if(!d)throw new Error(`Cannot create a document in the ${ae(e).collection} collection; it is not defined in the current schema version.`);return a.getEntity(e,d)};this.addOperationsToOpenCaches=async(t,e)=>{let n=kn(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=Fn(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=Fn(t),a=kn(e),d=Array.from(new Set(Object.keys(s).concat(Object.keys(a))));for(let h of d){let m=this.documentFamilyCaches.get(h);m?(m.addData({operations:a[h]||[],baselines:s[h]||[],reset:n,isLocal:r}),this.log("debug","Added data to cache for",h,a[h]?.length??0,"operations",s[h]?.length??0,"baselines")):this.log("debug","Could not add data to cache for",h,"because it is not open")}return d};this.addData=async({operations:t,baselines:e,reset:n})=>{if(this._disposed){this.log("warn","EntityStore is disposed, not adding data");return}let r=t;for(let d of r)d.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(d=>$(d.oid)).concat(t.map(d=>$(d.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,!0);for(let d of s)await this.writeDocumentToStorage(d);let a=Array.from(new Set(s.map(d=>ae(d).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=St(),max:n=null,timeout:r=this.defaultBatchTimeout}={})=>{let s=this.operationBatcher.add({key:e,max:n,timeout:r,items:[],userData:{undoable:t}}),a={run:d=>(this.currentBatchKey=e,d(),this.currentBatchKey=Gt,a),flush:async()=>(await this.operationBatcher.flush(Gt),s.flush()),discard:()=>{this.operationBatcher.discard(e)}};return a};this.flushPatches=async()=>{await this.operationBatcher.flush(this.currentBatchKey)};this.flushAllBatches=async()=>{await Promise.all(this.operationBatcher.flushAll())};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=>$(s.oid))));for(let s of n)await this.writeDocumentToStorage(s);let r=new Set(t.map(({oid:s})=>ae(s).collection));this.context.log("changes to collections",r),this.context.entityEvents.emit("collectionsChanged",Array.from(r))};this.getInverseOperations=async t=>{let e=Fi(t),n=[],r=()=>this.meta.now;for(let[s,a]of Object.entries(e)){let d=await this.openFamilyCache(s),{view:h,deleted:m}=d.computeConfirmedView(s),C=Ni(s,h,a,r);n.unshift(...C)}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)=>{V(t===$(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=async()=>{this._disposed=!0;for(let t of this.unsubscribes)t();for(let t of this.documentFamilyCaches.values())t.dispose();this.documentFamilyCaches.clear(),await this.flushAllBatches()};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 W(n.clear())}};this.refreshAllCaches=async(t=!1,e=!1)=>{for(let[n,r]of this.documentFamilyCaches)await this.refreshFamilyCache(r,t,e)};this.context=t,this.defaultBatchTimeout=n,this.meta=e,this.files=r,this.operationBatcher=new Ve(this.flushOperations),this.operationBatcher.add({key:Gt,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 qn=Symbol("handleMessage"),fs,ct=class extends U{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[fs]=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,d]of Object.entries(n.peerPresence))this.isSelf(e,d)?(this._self=d,this._selfReplicaIds.add(d.replicaId),this.emit("selfChanged",d)):(r=!0,s.add(a),this._peers[a]=d,this.emit("peerChanged",a,d))}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 Ve(this.flushPresenceUpdates),this._updateBatch=this._updateBatcher.add({max:25,timeout:n,items:[],key:"default"})}static{fs=qn}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 Zt=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 ze=class extends U{constructor({interval:e=15*1e3,deadlineLength:n=3*1e3,restartOnTabFocus:r=!0}={}){super();this.nextBeat=null;this.deadline=null;this.keepAlive=()=>{this.deadline&&(clearTimeout(this.deadline),this.deadline=null,this.start())};this.start=(e=!1)=>{this.stop(),e?this.beat():this.nextBeat=setTimeout(this.beat,this._interval)};this.stop=()=>{this.nextBeat&&clearTimeout(this.nextBeat),this.deadline&&clearTimeout(this.deadline)};this.beat=async()=>{this.emit("beat"),this.deadline=setTimeout(this.onDeadline,this.deadlineLength)};this.onDeadline=()=>{this.deadline=null,this.emit("missed")};this.setInterval=e=>{this._interval=e};this._interval=e,this.deadlineLength=n,typeof window<"u"&&r&&window.addEventListener("pageshow",()=>this.start(!0))}get interval(){return this._interval}};var en=class extends U{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 d of a.messages)this.handleServerMessage(d);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 ze({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 Wn(i){this.message=i}Wn.prototype=new Error,Wn.prototype.name="InvalidCharacterError";var tr=typeof window<"u"&&window.atob&&window.atob.bind(window)||function(i){var t=String(i).replace(/=+$/,"");if(t.length%4==1)throw new Wn("'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 hs(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(tr(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 tr(t)}}function tn(i){this.message=i}function ms(i,t){if(typeof i!="string")throw new tn("Invalid token specified");var e=(t=t||{}).header===!0?0:1;try{return JSON.parse(hs(i.split(".")[e]))}catch(n){throw new tn("Invalid token specified: "+n.message)}}tn.prototype=new Error,tn.prototype.name="InvalidTokenError";var nr=ms;var nn=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(d=>{if(d.ok)return d.json();throw new Error(`Auth endpoint returned non-200 response: ${d.status}`)}),V(t.accessToken,"No access token provided from auth endpoint");let e=nr(t.accessToken);V(e.url,"No sync endpoint provided from auth endpoint"),V(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 d=new URL(r);d.pathname=d.pathname+"/files",a=d.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 rn=class extends U{constructor(e){super();this.timer=null;this.isScheduled=!1;this.next=()=>{this.isScheduled||(this.isScheduled=!0,this.timer=setTimeout(()=>{this.emit("trigger"),this.isScheduled=!1,this.backoff.next()},this.backoff.current))};this.reset=()=>{this.backoff.reset(),this.timer&&(clearTimeout(this.timer),this.timer=null)};this.backoff=e}},sn=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 on=class extends U{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 ze;this.reconnectScheduler=new rn(new sn(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("message",this.onMessage),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 an=class extends U{constructor(){super(...arguments);this.mode="pull";this.dispose=()=>{};this.isConnected=!1;this.status="paused";this.pullInterval=0;this.presence=new ct({initialPresence:{},defaultProfile:{}});this.uploadFile=async()=>({success:!1,retry:!1});this.getFile=async()=>({success:!1,retry:!1})}send(){}start(){}stop(){}reconnect(){}setMode(){}setPullInterval(){}},$e=class extends U{constructor({authEndpoint:e,fetchAuth:n,initialPresence:r,automaticTransportSelection:s=!0,autoStart:a,initialTransport:d,pullInterval:h,presenceUpdateBatchTimeout:m,defaultProfile:C,useBroadcastChannel:P},{meta:v,log:T,onData:b}){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[qn](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=v,this.onData=b,this.log=T||(()=>{}),this.presence=new ct({initialPresence:r,defaultProfile:C,updateBatchTimeout:m}),this.endpointProvider=new nn({authEndpoint:e,fetchAuth:n}),this.webSocketSync=new on({endpointProvider:this.endpointProvider,meta:v,presence:this.presence,log:this.log}),this.pushPullSync=new en({endpointProvider:this.endpointProvider,meta:v,presence:this.presence,log:this.log,interval:h}),this.fileSync=new Zt({endpointProvider:this.endpointProvider,log:this.log}),P&&"BroadcastChannel"in window&&(this.broadcastChannel=new BroadcastChannel("verdant"),this.broadcastChannel.addEventListener("message",this.handleBroadcastChannelMessage)),d==="realtime"?this.activeSync=this.webSocketSync:this.activeSync=this.pushPullSync,this.presence.subscribe("update",this.handlePresenceUpdate),this.meta.subscribe("message",this.send),this.webSocketSync.subscribe("message",this.handleMessage),this.webSocketSync.subscribe("onlineChange",this.handleOnlineChange),this.pushPullSync.subscribe("message",this.handleMessage),this.pushPullSync.subscribe("onlineChange",this.handleOnlineChange),s&&this.canDoRealtime){let I=()=>{D&&clearTimeout(D);let x=Object.keys(this.presence.peers).length>0||s!=="peers-only"&&this.presence.selfReplicaIds.size>1;x&&this.mode==="pull"?this.setMode("realtime"):!x&&this.mode==="realtime"&&(D=setTimeout(()=>{Object.keys(this.presence.peers).length===0&&this.setMode("pull")},1e3))},D;this.presence.subscribe("peersChanged",I),s!=="peers-only"&&this.presence.subscribe("selfChanged",I)}a&&this.start()}get canDoRealtime(){return this.endpointProvider.type===0||this.endpointProvider.type===2||this.endpointProvider.type===5}get syncing(){return this._activelySyncing}get pullInterval(){return this.pushPullSync.interval}get isConnected(){return this.activeSync.isConnected}get status(){return this.activeSync.status}get mode(){return this.activeSync.mode}};var qe=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 gs(i){return i!==null}function Hn(i){return Array.isArray(i)?i.map(Hn).filter(gs):i instanceof me&&i.deleted?null:i}function Oe(i,t){return!i&&!t||i&&t&&we(i)===we(t)}var Qn=Symbol("ON_ALL_UNSUBSCRIBED"),le=Symbol("UPDATE"),bs,fe=class extends qe{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=Hn(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 me&&(this._internalUnsubscribes.push(n.subscribe("delete",this.refreshValue)),this._internalUnsubscribes.push(n.subscribe("restore",this.refreshValue)))}):e instanceof me&&(this._internalUnsubscribes.push(e.subscribe("delete",this.refreshValue)),this._internalUnsubscribes.push(e.subscribe("restore",()=>{this.refreshValue()})))};this.execute=()=>(this.context.log("debug","Executing query",this.key),this._status==="initial"?this._status="initializing":this._status==="ready"&&(this._status="revalidating"),this._executionPromise=this.run().then(()=>this._value).catch(e=>{if(e instanceof Error&&(e.name==="InvalidStateError"||e.name==="InvalidAccessError"))return this._value;throw e}),this._executionPromise);this[bs]=e=>{this._allUnsubscribedHandler=e};this._rawValue=e,this._value=e,this._events=new U(h=>{h==="change"&&this._allUnsubscribedHandler?.(this)}),this.context=n,this.key=s,this.collection=r;let d=a||(h=>h.includes(r));this.addDispose(this.context.entityEvents.subscribe("collectionsChanged",h=>{d(h)&&(this.context.log("info","Updating query",this.key),this.execute())}))}static{bs=Qn}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 cn=class extends fe{constructor({id:e,hydrate:n,...r}){super({initial:null,...r});this.run=async()=>{let e=await this.hydrate(this.oid);this.setValue(e)};this.oid=Z(r.collection,e),this.hydrate=n}};var vs,ln=class extends fe{constructor({index:e,hydrate:n,...r}){super({initial:null,...r});this.run=async()=>{let e=await Nt({collection:this.collection,index:this.index,context:this.context});this.setValue(e?await this.hydrate(e):null)};this[vs]=e=>{Oe(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n}static{vs=le}};var ws,dn=class extends fe{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 it({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[ws]=e=>{Oe(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n,this._pageSize=r,this._page=s}static{ws=le}get pageSize(){return this._pageSize}get page(){return this._page}get hasNextPage(){return this._hasNextPage}get hasPreviousPage(){return this._page>0}};var Ss,un=class extends fe{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 it({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 it({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[Ss]=e=>{Oe(this.index,e)||(this.index=e,this.execute())};this.index=r,this.hydrate=e,this._pageSize=n}static{Ss=le}get pageSize(){return this._pageSize}get hasMore(){return this._hasNextPage}};var xs,pn=class extends fe{constructor({index:e,hydrate:n,...r}){super({initial:[],...r});this.run=async()=>{let e=await Kt({collection:this.collection,index:this.index,context:this.context});this.setValue(await Promise.all(e.map(this.hydrate)))};this[xs]=e=>{Oe(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n}static{xs=le}};var fn=class{constructor({collection:t,cache:e,entities:n,context:r,documentManager:s}){this.serializeIndex=t=>t?we(t):"";this.get=t=>{let e=`get:${this.collection}:${t}`;return this.cache.getOrSet(e,()=>new cn({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 ln({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:n}),r=>{r[le](t)})};this.findAll=({index:t,key:e}={})=>{let n=e||`findAll:${this.collection}:${this.serializeIndex(t)}`;return this.cache.getOrSet(n,()=>new pn({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:n}),r=>{r[le](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 dn({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:s,pageSize:e,page:n}),a=>{a[le](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 un({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:r,pageSize:e}),s=>{s[le](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 hn=class extends qe{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[Qn](this.onQueryUnsubscribed),e}getOrSet(e,n,r){let s=this.get(e);return s?(r?.(s),s):this.set(n())}};var Re=class extends U{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 m of e)n[m]=await tt(this.documentDb,m);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((m,{size:C})=>m+C,0),d=r.baselinesSize.size+r.operationsSize.size,h=d/a;return{collections:n,meta:r,storage:s,totalMetaSize:d,totalCollectionsSize:a,metaToDataRatio:h,quotaUsage:s?.usage&&s?.quota?s.usage/s.quota:void 0}};this.close=async()=>{this.sync.stop(),this.sync.dispose(),await this._entities.destroy(),this.meta.close(),await new Promise(async e=>{await Ae(this.documentDb),await Ae(this.metaDb),e()}),this.context.log?.("Client closed")};this.__dangerous__resetLocal=async()=>{this.sync.stop(),await Bt(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 Ae(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((d,h)=>{s.onsuccess=d,s.onerror=h});let a=this.context.schema;this.context.schema=n.schema,this.context.documentDb=await rt({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 Ae(this.context.documentDb),this.context.log("Migrating up to latest schema..."),this.context.schema=a,this.context.documentDb=await rt({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&&!n.schema.wip?new $e(this.config.syncConfig,{meta:this.meta,onData:this.addData,log:this.context.log}):new an,n.schema.wip&&this.config.syncConfig&&n.log("warn","\u26A0\uFE0F\u26A0\uFE0F Sync is disabled for WIP schemas. Commit your schema changes to start syncing again. \u26A0\uFE0F\u26A0\uFE0F"),this._fileManager=new Ht({db:this.metaDb,sync:this.sync,context:this.context,config:this.config.files,meta:this.meta}),this._entities=new Xt({context:this.context,meta:this.meta,files:this._fileManager}),this._queryCache=new hn({context:n}),this._documentManager=new qt(this.meta,this.schema,this._entities);let s=Pi(()=>{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,d]of Object.entries(n.schema.collections)){let h=d,m=h.pluralName??h.name+"s";V(m===a,`The key of the collection in the schema must be the plural of the name (expected: "${m}")`),this[m]=new fn({collection:m,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 mn=class{constructor(t){this.init=t;this._initializing=!1;this.initialize=async t=>{if(typeof window>"u"&&!t.indexedDb)throw new Error("A verdant client was initialized in an environment without IndexedDB. If you are using verdant in a server-rendered framework, you must enforce that all clients are initialized on the client-side, or you must provide some mock interface of IDBFactory to the ClientDescriptor options.");if(this._initializing||this._resolvedValue)return this._readyPromise;this._initializing=!0;try{let e;return t.schema.wip?e=await this.initializeWIPDatabases(t):(e=await this.initializeDatabases(t),this.cleanupWIPDatabases(t)),this.resolveReady(e),this._resolvedValue=e,e}catch(e){throw this.rejectReady(e),e}finally{this._initializing=!1}};this.initializeDatabases=async t=>{let{db:e}=await Vt({indexedDB:t.indexedDb,log:t.log,namespace:t.namespace}),n={namespace:this._namespace,metaDb:e,schema:t.schema,log:t.log||(()=>{}),undoHistory:t.undoHistory||new st,entityEvents:new U,globalEvents:new U},r=new nt({context:n,disableRebasing:t.disableRebasing});await r.updateSchema(t.schema,t.overrideSchemaConflict);let s=await rt({context:n,version:t.schema.version,meta:r,migrations:t.migrations,indexedDB:t.indexedDb}),a=Object.assign(n,{documentDb:s});return new Re({syncConfig:t.sync,migrations:t.migrations,files:t.files},a,{meta:r})};this.initializeWIPDatabases=async t=>{let e=we(t.schema);console.info(`WIP schema in use. Opening database with hash ${e}`);let n=`@@wip_${t.namespace}_${e}`,{db:r}=await Wi({indexedDB:t.indexedDb,log:t.log,namespace:t.namespace,wipNamespace:n}),s={namespace:this._namespace,metaDb:r,schema:t.schema,log:t.log||(()=>{}),undoHistory:t.undoHistory||new st,entityEvents:new U,globalEvents:new U},a=new nt({context:s,disableRebasing:t.disableRebasing});await a.updateSchema(t.schema,t.overrideSchemaConflict);let d=await Yi({context:s,version:t.schema.version,meta:a,migrations:t.migrations,indexedDB:t.indexedDb,wipNamespace:n}),h=Object.assign(s,{documentDb:d});return new Re({syncConfig:t.sync,migrations:t.migrations,files:t.files},h,{meta:a})};this.cleanupWIPDatabases=async t=>{let r=(await $i(t.indexedDb)).filter(s=>s.name?.startsWith("@@wip_")).map(s=>s.name).filter(s=>!s.startsWith(`@@wip_${t.namespace}_${we(t.schema)}`));for(let s of r)await zi(s,t.indexedDb)};this.open=()=>this.initialize(this.init);this.close=async()=>{this._resolvedValue&&this._resolvedValue.close(),this._initializing&&(await this._readyPromise).close()};this.__dangerous__resetLocal=async()=>{await Bt(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=Jn;
12
17
  //# sourceMappingURL=index.js.map